@reddb-io/red-skills 3.3.9 → 3.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,72 +1,81 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var bd=Object.defineProperty;var _d=(e,n)=>()=>(e&&(n=e(e=0)),n);var wd=(e,n)=>{for(var t in n)bd(e,t,{get:n[t],enumerable:!0})};var Zs={};wd(Zs,{REDSKILLED_BIN_ENV:()=>pr,REDSKILLED_BUNDLE_ASSET:()=>Q,REDSKILLED_ENTRY_UNRESOLVED:()=>ln,RedskilledDaemonEntryError:()=>an,isRedskilledEntryPath:()=>fr,isResolvedRedskilledEntry:()=>Y,redskilledBundleCacheRoot:()=>Vn,redskilledServeArgv:()=>_e,requireRedskilledEntry:()=>Bn,resolveRedskilledEntry:()=>ue});import{existsSync as Gu,readdirSync as zu}from"node:fs";import{homedir as Qu}from"node:os";import{basename as ur,dirname as cr,join as M,resolve as Un}from"node:path";function Y(e){return"command"in e}function _e(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 Vn(e=process.env){return Ys(e)}function ue(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??Gu,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[pr];if(a)return{command:a,args:[],source:"env-redskilled-bin",entry:a};if(i&&fr(i))return l(Un(i),"caller-entry");let d=[];for(let[u,p]of ep(i,n.rootDir,t,n.listDir??rp))if(d.push(u),r(u))return l(u,p);return{diagnostic:ln,searched:d,...i?{callerEntry:Un(i)}:{}}}function Bn(e={},n={}){let t=ue(e,n);if(Y(t))return t;throw new an(t)}function fr(e){let n=ur(e);return n===Q||mr.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:Xu(Un(e))}function Xu(e){let n=cr(e);for(let t=0;t<4;t++){if(ur(n)==="redskilled")return!0;let r=cr(n);if(r===n)return!1;n=r}return!1}function*ep(e,n,t,r){if(e){let s=cr(Un(e));yield[M(s,Q),"caller-sibling-bundle"];let i=Yu.exec(ur(e));i&&(yield[M(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[M(s,"..","dist",Q),"caller-sibling-bundle"]}for(let s of Zu){let i=t[s];i&&(yield[M(i,"dist",Q),"plugin-root-bundle"],yield[M(i,"..","..","dist",Q),"plugin-root-bundle"])}n&&(yield[M(n,"dist",Q),"repo-bundle"],yield[M(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[M(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=Ys(t);yield[M(o,Q),"bundle-cache"];for(let s of np(o,r))yield[M(o,s),"bundle-cache"]}function Ys(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||M(e.HOME||Qu(),".cache");return M(n,"red-skills","bundles")}function np(e,n){return n(e).filter(t=>mr.test(t)).sort((t,r)=>tp(Qs(r),Qs(t)))}function Qs(e){return mr.exec(e)?.[1]??""}function tp(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 rp(e){try{return zu(e)}catch{return[]}}var Q,ln,pr,an,Yu,mr,Zu,re=_d(()=>{"use strict";Q="redskilled.bundle.min.mjs",ln="redskilled-daemon-entry-unresolved",pr="REDSKILLED_BIN";an=class extends Error{code=ln;searched;callerEntry;constructor(n){super(`${ln}: no published ${Q} found to spawn the redskilled daemon from${n.callerEntry?` (caller entry: ${n.callerEntry}, which is NOT used as a fallback)`:""}
3
+ var Bc=Object.defineProperty;var Kc=(e,n)=>()=>(e&&(n=e(e=0)),n);var Vc=(e,n)=>{for(var t in n)Bc(e,t,{get:n[t],enumerable:!0})};var ol={};Vc(ol,{REDSKILLED_BIN_ENV:()=>Gr,REDSKILLED_BUNDLE_ASSET:()=>le,REDSKILLED_ENTRY_UNRESOLVED:()=>xn,RedskilledDaemonEntryError:()=>Sn,isRedskilledEntryPath:()=>Qr,isResolvedRedskilledEntry:()=>ae,redskilledBundleCacheRoot:()=>mt,redskilledServeArgv:()=>Ae,requireRedskilledEntry:()=>ht,resolveRedskilledEntry:()=>Re});import{existsSync as Bf,readdirSync as Kf}from"node:fs";import{homedir as Vf}from"node:os";import{basename as qr,dirname as Vr,join as V,resolve as ft}from"node:path";function ae(e){return"command"in e}function Ae(e,n={}){let t=["serve","--socket",e.socketPath,"--lease",e.leasePath,"--events",e.eventLanePath,"--session-key-hash",e.sessionKeyHash,"--machine-id-hash",e.machineIdHash,"--machine-claim",e.machineClaimPath];return n.idleMs!=null&&t.push("--idle-ms",String(n.idleMs)),n.daemonVersion!=null&&t.push("--daemon-version",n.daemonVersion),t}function mt(e=process.env){return rl(e)}function Re(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??Bf,o=n.execPath??process.execPath,i=n.execArgv??[],s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,a=(p,u)=>({command:o,args:[...i,p],source:u,entry:p}),l=t[Gr];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(s&&Qr(s))return a(ft(s),"caller-entry");let d=[];for(let[p,u]of Qf(s,n.rootDir,t,n.listDir??Xf))if(d.push(p),r(p))return a(p,u);return{diagnostic:xn,searched:d,...s?{callerEntry:ft(s)}:{}}}function ht(e={},n={}){let t=Re(e,n);if(ae(t))return t;throw new Sn(t)}function Qr(e){let n=qr(e);return n===le||Jr.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:Jf(ft(e))}function Jf(e){let n=Vr(e);for(let t=0;t<4;t++){if(qr(n)==="redskilled")return!0;let r=Vr(n);if(r===n)return!1;n=r}return!1}function*Qf(e,n,t,r){if(e){let i=Vr(ft(e));yield[V(i,le),"caller-sibling-bundle"];let s=qf.exec(qr(e));s&&(yield[V(i,`redskilled-${s[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[V(i,"..","dist",le),"caller-sibling-bundle"]}for(let i of Gf){let s=t[i];s&&(yield[V(s,"dist",le),"plugin-root-bundle"],yield[V(s,"..","..","dist",le),"plugin-root-bundle"])}n&&(yield[V(n,"dist",le),"repo-bundle"],yield[V(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[V(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=rl(t);yield[V(o,le),"bundle-cache"];for(let i of zf(o,r))yield[V(o,i),"bundle-cache"]}function rl(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||V(e.HOME||Vf(),".cache");return V(n,"red-skills","bundles")}function zf(e,n){return n(e).filter(t=>Jr.test(t)).sort((t,r)=>Yf(tl(r),tl(t)))}function tl(e){return Jr.exec(e)?.[1]??""}function Yf(e,n){let t=i=>i.split(".").map(s=>Number.parseInt(s,10)),[r,o]=[t(e),t(n)];for(let i=0;i<Math.max(r.length,o.length);i++){let[s,a]=[r[i],o[i]];if(Number.isNaN(s)||s===void 0)return Number.isNaN(a)||a===void 0?e.localeCompare(n):-1;if(Number.isNaN(a)||a===void 0)return 1;if(s!==a)return s-a}return 0}function Xf(e){try{return Kf(e)}catch{return[]}}var le,xn,Gr,Sn,qf,Jr,Gf,fe=Kc(()=>{"use strict";le="redskilled.bundle.min.mjs",xn="redskilled-daemon-entry-unresolved",Gr="REDSKILLED_BIN";Sn=class extends Error{code=xn;searched;callerEntry;constructor(n){super(`${xn}: no published ${le} found to spawn the redskilled daemon from${n.callerEntry?` (caller entry: ${n.callerEntry}, which is NOT used as a fallback)`:""}
4
4
  searched:
5
5
  ${n.searched.map(t=>` ${t}`).join(`
6
- `)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};Yu=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,mr=/^redskilled-(.+)\.bundle\.min\.mjs$/,Zu=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as iy}from"node:child_process";import{homedir as lo}from"node:os";import{join as qa}from"node:path";var Ye=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},ge=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 Ye(e,n)}function S(e,n){return new ge(e,n)}function Pe(e){return e instanceof ge?e:e instanceof Ye?new ge(e.line,e.reason):new ge(0,String(e&&e.message?e.message:e))}var j=",";function An(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 K(e){return R(e,"invalid quoted string")}function J(e,n){if(e==="")return"";if(e.startsWith('"'))return Co(e,n);if(e.includes('"'))throw K(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:vd(e)?Number(e):e}function ne(e,n){let t=e.trim();if(t.startsWith('"'))return[Co(t,n),!0];if(t.includes('"')||/\s/.test(t))throw R(n,"expected non-empty field name");return[t,!1]}function Co(e,n){if(e[0]!=='"')throw K(n);let t="",r=1;for(;r<e.length;){let o=e[r];if(r+=1,o==='"'){if(e.slice(r).trim()==="")return t;throw K(n)}if(o==="\\"){let s=e[r];switch(r+=1,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 K(n);let l=Number.parseInt(i,16);if(l>=55296&&l<=57343)throw K(n);t+=String.fromCharCode(l),r+=4;break}default:throw K(n)}continue}if(o<" "&&o!==" ")throw K(n);t+=o}throw K(n)}function he(e,n,t){if(e==="")return[];let r=[],o=0,s=!1,i=!1;for(let l=0;l<e.length;l+=1){let a=e[l];if(i){i=!1;continue}a==="\\"&&s?i=!0:a==='"'?s=!s:a===n&&!s&&(r.push(e.slice(o,l).trim()),o=l+1)}if(s||i)throw K(t);return r.push(e.slice(o).trim()),r}function T(e,n,t){let r=!1,o=!1;for(let s=0;s<e.length;s+=1){let i=e[s];if(o){o=!1;continue}if(i==="\\"&&r)o=!0;else if(i==='"')r=!r;else if(i===n&&!r)return s}if(r||o)throw K(t);return-1}function vd(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Sd(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function xd(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 Ze(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function q(e,n){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return xd(e);if(typeof e=="string")return Pd(e,n);throw R(0,"not a primitive")}function Ed(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function F(e){return Ed(e)?e:Fo(e)}function Pd(e,n){return jd(e,n)?Fo(e):e}function jd(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Sd(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}function Fo(e){let n='"';for(let t of e)switch(t){case'"':n+='\\"';break;case"\\":n+="\\\\";break;case`
9
- `:n+="\\n";break;case"\r":n+="\\r";break;case" ":n+="\\t";break;default:t<" "?n+=`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`:n+=t}return`${n}"`}function je(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}var Lt=2;function Dd(e={}){return{indent:Math.max(1,e.indent??Lt),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function Od(e,n){let t=[],r=!1;return An(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");t.push({number:i,depth:Math.floor(l/n.indent),content:o.slice(l),blankBefore:r}),r=!1}),t}function G(e,n){let t=Dd(n),r=Od(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("[")){let d;try{d=Tt(o.content,T(o.content,":",o.number))}catch(u){if(t.strict)throw Ot(u,o.number);d=void 0}if(d!==void 0)return Ad(d,r,t)}if(s&&T(o.content,":",o.number)===-1)return J(o.content.trim(),o.number);let i={index:0},l=At(r,i,0,t),a=r[i.index];if(a!==void 0)throw R(a.number,"expected end of document");return l}function At(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}=$d(e,n,t,r);Vo(o,i,l,a,r,s.number)}return o}function $d(e,n,t,r){let o=e[n.index],s=o.content,i=T(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=T(l,"[",o.number),u=T(l,"{",o.number);if(u!==-1&&(d===-1||u<d)){let y;try{y=Wd(l)}catch(k){if(r.strict)throw Ot(k,o.number);n.index+=1;let b=Et(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:b}}if(a.trim()!=="")throw R(o.number,"expected keyed map rows");let _=Ld(y,e,n,t+1,r);return{key:y.key,quoted:y.keyQuoted,value:_}}if(d!==-1){let y;try{y=Tt(l,i)}catch(k){if(r.strict)throw Ot(k,o.number);n.index+=1;let b=Et(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:b}}if(y.key===""&&!y.keyQuoted)throw R(o.number,"expected non-empty field name");let _=It(y,a,e,n,t,r);return{key:y.key,quoted:y.keyQuoted,value:_}}let[p,m]=ne(l,o.number);if(p===""&&!m)throw R(o.number,"expected non-empty field name");n.index+=1;let g=Et(e,n,t,a,o.number,r);return{key:p,quoted:m,value:g}}function Et(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?At(e,n,t+1,s):{}}function Ld(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=T(i.content,":",i.number);if(l===-1)throw R(i.number,"expected `key: value`");let[a,d]=ne(i.content.slice(0,l),i.number);if(a===""&&!d)throw R(i.number,"expected non-empty field name");let u=he(i.content.slice(l+1).trim(),e.delimiter,i.number);if(u.length!==e.fields.length)throw R(i.number,"keyed map row length mismatch");let p={};e.fields.forEach((m,g)=>{Xe(p,m,J(u[g],i.number),o,i.number)}),Vo(s,a,d,p,o,i.number),t.index+=1}return s}function Ad(e,n,t){let r=n[0],o=T(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=It(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 It(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 Id(e,e.fields,t,r,o+1,s)}if(l!==""){let a=he(l,e.delimiter,i).map(d=>J(d,i));if(a.length!==e.len)throw R(i,"array length mismatch");return a}return Td(e,t,r,o+1,s)}function Id(e,n,t,r,o,s){let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0)throw jt(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(!Ho(a.content,e.delimiter,a.number))break;let d=he(a.content,e.delimiter,a.number);if(d.length!==n.length)throw R(a.number,"array row length mismatch");let u={};n.forEach((p,m)=>{Xe(u,p,J(d[m],a.number),s,a.number)}),i.push(u),r.index+=1}if(i.length!==e.len)throw jt(t,r.index);let l=t[r.index];if(l!==void 0&&l.depth>=o&&Ho(l.content,e.delimiter,l.number))throw R(l.number,"array length mismatch");return i}function Ho(e,n,t){let r=T(e,":",t);if(r===-1)return!0;let o=T(e,n,t);return o===-1?!1:o<r}function Td(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 jt(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(Nd(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 Nd(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=T(s,":",o.number),l;try{l=Tt(s,i)}catch{l=void 0}if(l!==void 0){let a=s.slice(i+1);return It(l,a,e,n,t,r)}}if(T(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 At(i,{index:0},t+1,r)}return n.index+=1,J(s,o.number)}function jt(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function Tt(e,n){if(n===-1)throw R(0,"array header missing colon");let t=e.slice(0,n),r=T(t,"[",0);if(r===-1)throw R(0,"invalid array header");let o,s;try{[o,s]=ne(t.slice(0,r),0)}catch{throw R(0,"invalid array header")}let i=t.slice(r+1),l=i.indexOf("]");if(l===-1)throw R(0,"invalid array header");let a=i.slice(0,l),d=/^[0-9]*/.exec(a)[0];if(d===""||d.length>1&&d.startsWith("0"))throw R(0,"invalid array header");let u=Number.parseInt(d,10),p;switch(a.slice(d.length)){case"":p=",";break;case" ":p=" ";break;case"|":p="|";break;default:throw R(0,"invalid array header")}let m=i.slice(l+1),g;if(m==="")g=void 0;else if(m.startsWith("{")&&m.endsWith("}")&&m.length>=2)try{g=Uo(m.slice(1,-1),p)}catch(y){throw R(0,y.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw R(0,"invalid array header");return{key:o,keyQuoted:s,len:u,delimiter:p,fields:g}}function Wd(e){let n=T(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=ne(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;try{o=Uo(e.slice(n+1,-1),j)}catch(s){throw R(0,s.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:j,fields:o}}function Uo(e,n){let t=[],r=0;function o(l,a){let d=0;for(;r<e.length&&!(a&&e[r]==="}");){if(e[r]===n||e[r]==="}")throw R(0,"invalid array header");let u=r;for(;r<e.length;){let m=e[r];if(m==='"'){s();continue}if(m===n||m==="{"||m==="}")break;r+=1}let[p]=ne(e.slice(u,r),0);if(p==="")throw R(0,"invalid array header");if(d+=1,e[r]==="{"){r+=1;let m=t.length;if(o([...l,p],!0),e[r]!=="}"||t.length===m)throw R(0,"invalid array header");r+=1}else t.push([...l,p]);if(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===0)throw R(0,"invalid array header")}function s(){for(r+=1;r<e.length;){let l=e[r];if(r+=1,l==="\\")r+=1;else if(l==='"')return}}if(o([],!1),r!==e.length)throw R(0,"invalid array header");let i=new Set;for(let l=0;l<t.length;l+=1)for(let a=l+1;a<t.length;a+=1)if(Md(t[l],t[a])||Dt(t[l],t[a])||Dt(t[a],t[l]))throw R(0,"duplicate key");for(let l of t){let a=l.join("\0");if(i.has(a))throw R(0,"duplicate key");i.add(a)}return t}function Md(e,n){return e.length===n.length&&Dt(e,n)}function Dt(e,n){return n.every((t,r)=>e[r]===t)}function Ot(e,n){return R(n,e.reason??String(e.message))}function Vo(e,n,t,r,o,s){if(o.expandPaths&&!t&&n.includes(".")){let i=n.split(".");if(i.every(Cd)){Xe(e,i,r,o,s);return}}Xe(e,[n],r,o,s)}function Xe(e,n,t,r,o){let s=n[0],i=Object.prototype.hasOwnProperty.call(e,s);if(n.length===1){if(i&&r.strict)throw R(o,"duplicate key");je(e,s,t);return}if(i&&!De(e[s])){if(r.strict)throw R(o,"path expansion conflict");je(e,s,{})}else i||je(e,s,{});Xe(e[s],n.slice(1),t,r,o)}function Cd(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function De(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function I(e,n={}){let t={nestedTabularHeaders:n.nestedTabularHeaders===!0,keyedMapCollapse:n.keyedMapCollapse===!0},r=[];return Array.isArray(e)?Nt(r,void 0,e,0,!1,t):De(e)?Bo(r,e,0,t):r.push(q(e,j)),r.join("")}function en(e,n){e.push(" ".repeat(n*Lt))}function Bo(e,n,t,r){for(let[o,s]of Object.entries(n))en(e,t),$t(e,o,s,t,r)}function $t(e,n,t,r,o){if(Array.isArray(t)){Nt(e,n,t,r,!1,o);return}if(De(t)){let s=o.keyedMapCollapse?Hd(t,o):void 0;if(s!==void 0){e.push(F(n),"{",s.fields.map(Wt).join(j),`}:
10
- `);for(let[i,l]of Object.entries(t))en(e,r+1),e.push(F(i),": ",s.paths.map(a=>q(Go(l,a),j)).join(j),`
11
- `);return}e.push(F(n),`:
12
- `),Bo(e,t,r+1,o);return}e.push(F(n),": ",q(t,j),`
13
- `)}function Nt(e,n,t,r,o,s){if(t.length===0){n!==void 0?e.push(F(n),`: []
6
+ `)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};qf=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Jr=/^redskilled-(.+)\.bundle\.min\.mjs$/,Gf=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as xR}from"node:child_process";import{homedir as zo}from"node:os";import{join as pc}from"node:path";var Fe=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},ve=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonlError",this.line=n,this.reason=t}};function R(e,n){return new Fe(e,n)}function S(e,n){return new ve(e,n)}function Ue(e){return e instanceof ve?e:e instanceof Fe?new ve(e.line,e.reason):new ve(0,String(e&&e.message?e.message:e))}var Di=["type","kind","event"],Ee="|",Oi=new Set(["order","discriminator","rows","common"]);var D=",";function Xn(e){let n=e.split(`
7
+ `);return n.length>0&&n[n.length-1]===""&&n.pop(),n.map(t=>t.endsWith("\r")?t.slice(0,-1):t)}function re(e){return R(e,"invalid quoted string")}function B(e,n){if(e==="")return"";if(e.startsWith('"'))return $i(e,n);if(e.includes('"'))throw re(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:qc(e)?Number(e):e}function J(e,n){let t=e.trim();if(t.startsWith('"'))return[$i(t,n),!0];if(t.includes('"')||/\s/.test(t))throw R(n,"expected non-empty field name");return[t,!1]}var Ai=/["\\\u0000-\u0008\u000a-\u001f]/g;function $i(e,n){if(e.charCodeAt(0)!==34)throw re(n);let t="",r=1;for(;r<e.length;){Ai.lastIndex=r;let o=Ai.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(r,o.index);throw re(n)}if(o[0]!=="\\")throw re(n);t+=e.slice(r,o.index);let i=e[o.index+1];switch(r=o.index+2,i){case'"':t+='"';break;case"\\":t+="\\";break;case"n":t+=`
8
+ `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let s=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw re(n);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw re(n);t+=String.fromCharCode(a),r+=4;break}default:throw re(n)}}throw re(n)}function Ii(e,n,t){for(;;){let r=e.indexOf('"',n),o=e.indexOf("\\",n);if(o!==-1&&(r===-1||o<r)){if(o===e.length-1)throw re(t);n=o+2;continue}if(r===-1)throw re(t);return r+1}}function Q(e,n,t){if(e==="")return[];let r=[],o=0,i=0;for(;i<e.length;){let s=e.indexOf('"',i),a=e.indexOf(n,i);if(a!==-1&&(s===-1||a<s))r.push(e.slice(o,a).trim()),o=a+1,i=a+1;else if(s!==-1)i=Ii(e,s+1,t);else break}return r.push(e.slice(o).trim()),r}function W(e,n,t){let r=0;for(;r<e.length;){let o=e.indexOf('"',r),i=e.indexOf(n,r);if(i!==-1&&(o===-1||i<o))return i;if(o===-1)return-1;r=Ii(e,o+1,t)}return-1}function qc(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Gc(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Jc(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw R(0,"number is not representable in TOON");return String(e)}function oe(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function H(e,n){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Jc(e);if(typeof e=="string")return zc(e,n);throw R(0,"not a primitive")}function Qc(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function N(e){return Qc(e)?e:Zn(e)}function zc(e,n){return nr(e,n)?Zn(e):e}function nr(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Gc(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}var Li=/["\\\u0000-\u001f]/g;function Zn(e){let n='"',t=0;Li.lastIndex=0;let r;for(;(r=Li.exec(e))!==null;){let o=e.charCodeAt(r.index),i;o===34?i='\\"':o===92?i="\\\\":o===10?i="\\n":o===13?i="\\r":o===9?i="\\t":i=`\\u${o.toString(16).padStart(4,"0")}`,n+=e.slice(t,r.index)+i,t=r.index+1}return`${n}${e.slice(t)}"`}function z(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function A(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ti(e={}){let n=e.maxDepth??1e3,t=n===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(n));return{indent:Math.max(1,e.indent??2),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0,cyclicDiscriminatedArrays:e.cyclicDiscriminatedArrays!==!1,maxDepth:t}}function Ni(e,n){let t=[],r=!1;return Xn(e).forEach((o,i)=>{let s=i+1;if(o.trim()===""){r=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw R(s,"invalid indentation");if(n.strict&&a%n.indent!==0)throw R(s,"invalid indentation");let l=Math.floor(a/n.indent);ie(l,s,n),t.push({number:s,depth:l,content:o.slice(a),blankBefore:r}),r=!1}),t}function ie(e,n,t){if(t.maxDepth!==0&&e>t.maxDepth)throw R(n,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function gn(e,n,t){if(t.maxDepth===0)return;let r=0,o=!1,i=!1;for(let s of e){if(i){i=!1;continue}if(o&&s==="\\"){i=!0;continue}if(s==='"'){o=!o;continue}o||(s==="{"?(r+=1,ie(r,n,t)):s==="}"&&(r=Math.max(0,r-1)))}}function Wi(e){if(!A(e)||Object.keys(e).length===0)return e;let n={};for(let[t,r]of Object.entries(e)){let o=Yc(r,1);if(o===void 0)return e;z(n,t,o)}return n}function Yc(e,n){if(!A(e)||!Xc(e))return;let{order:t,discriminator:r,rows:o}=e;if(typeof t!="string"||typeof r!="string"||!Number.isSafeInteger(o)||o<0)throw C(n);let i=Zc(t,o,n),s=e.common,a=s===void 0?Array.from({length:o},()=>({})):s;if(!Array.isArray(a)||a.length!==o||!a.every(A))throw Hi(n);let l=new Map;for(let[u,f]of Object.entries(e))if(!Oi.has(u)){if(!Array.isArray(f)||!f.every(A))throw C(n);l.set(u,f)}if(l.size===0)throw C(n);let d=new Map,p=i.map((u,f)=>{let m=l.get(u);if(m===void 0)throw tr(n);let h=d.get(u)??0,b=m[h];if(b===void 0)throw tr(n);return d.set(u,h+1),eu(r,u,a[f],b,n)});for(let[u,f]of l)if((d.get(u)??0)!==f.length)throw tr(n);return p}function Xc(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function Zc(e,n,t){if(!e.startsWith("cycle("))throw C(t);let r=e.slice(6),o=r.indexOf(")*");if(o===-1)throw C(t);let i=r.slice(0,o),s=r.slice(o+2);if(i===""||s.includes("+tail("))throw C(t);let a=i.split(",").map(p=>ou(p,t));if(a.some(p=>p===""))throw C(t);let l=ru(s,t),d=a.length*l;if(!Number.isSafeInteger(d))throw C(t);if(d!==n)throw Hi(t);return Array.from({length:d},(p,u)=>a[u%a.length])}function eu(e,n,t,r,o){let i={};z(i,e,n);for(let[s,a]of Object.entries(t??{})){if(s===e||Object.prototype.hasOwnProperty.call(i,s))throw C(o);z(i,s,a)}for(let[s,a]of Object.entries(nu(r,o))){if(s===e||Object.prototype.hasOwnProperty.call(i,s))throw C(o);z(i,s,a)}return i}function nu(e,n){let t={};for(let[r,o]of Object.entries(e))tu(t,r.split("."),o,n);return et(t,n)}function tu(e,n,t,r){if(n.some(i=>i===""))throw C(r);let o=e;for(let i=0;i<n.length;i+=1){let s=n[i];if(i===n.length-1){o[s]=t;return}if(o[s]??={},o=o[s],!A(o))throw C(r)}}function et(e,n){return Array.isArray(e)?e.map(t=>et(t,n)):A(e)?Number.isSafeInteger(e.length)&&e.length>=0?Array.from({length:e.length},(t,r)=>{if(!Object.prototype.hasOwnProperty.call(e,String(r)))throw C(n);return et(e[String(r)],n)}):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,et(r,n)])):e}function ru(e,n){if(e===""||e.length>1&&e.startsWith("0")||!/^[0-9]+$/.test(e))throw C(n);let t=Number(e);if(!Number.isSafeInteger(t))throw C(n);return t}function ou(e,n){try{return decodeURIComponent(e)}catch{throw C(n)}}function Ci(e){return encodeURIComponent(e)}function C(e){return R(e,"invalid cyclic array wire")}function Hi(e){return R(e,"cyclic array length mismatch")}function tr(e){return R(e,"cyclic array group length mismatch")}function Fi(e){if(!A(e))return;let n=Object.entries(e);if(n.length===0)return;let t=[];for(let[o,i]of n){let s=iu(i);if(s===void 0)return;t.push([o,s])}let r=[];for(let[o,i]of t)du(r,o,i);return r.join("")}function iu(e){if(!Array.isArray(e)||e.length===0||!e.every(A))return;let n=su(e);if(n===void 0)return;let t=e.map(a=>a[n]),r=lu(t);if(r===void 0)return;let o=au(e,n),i=new Map;for(let a of e){let l=a[n];i.has(l)||i.set(l,[]);let d={};for(let[p,u]of Object.entries(a))if(p!==n&&!o.includes(p)&&!rr(u,p,d))return;i.get(l).push(d)}let s=[];for(let a of r.cycle){let l=i.get(a),d=uu(l);if(d===void 0||d.length===0)return;s.push({fields:d,label:a,rows:l})}return{common:o,commonRows:e.map(a=>Object.fromEntries(o.map(l=>[l,a[l]]))),discriminator:n,groups:s,order:r,rows:e}}function su(e){return Di.find(n=>e.every(t=>typeof t[n]=="string"))}function lu(e){if(!(e.length<12))for(let n=2;n<=Math.min(8,Math.floor(e.length/3));n+=1){if(e.length%n!==0)continue;let t=e.slice(0,n);if(new Set(t).size<2||!e.every((s,a)=>s===t[a%n]))continue;let r=e.length/n;if(r<3)continue;let o=e.map(Ci).join(","),i=`cycle(${t.map(Ci).join(",")})*${r}`;if(i.length<=o.length*.4)return{cycle:t,encoded:i,repeats:r}}}function au(e,n){let t=[],r=Object.keys(e[0]),o=r.indexOf(n)+1;for(let i of r.slice(o).filter(s=>s!==n)){if(!cu(i)||!e.every(s=>Object.prototype.hasOwnProperty.call(s,i))||!e.every(s=>oe(s[i])))break;t.push(i)}return t}function du(e,n,t){e.push(N(n),`:
9
+ `),e.push(" order: ",H(t.order.encoded,Ee),`
10
+ `),e.push(" discriminator: ",H(t.discriminator,Ee),`
11
+ `),e.push(" rows: ",String(t.rows.length),`
12
+ `),t.common.length>0&&Mi(e,"common",t.common,t.commonRows);for(let r of t.groups)Mi(e,r.label,r.fields,r.rows)}function Mi(e,n,t,r){e.push(" ",N(n),"[",String(r.length),Ee,"]{",t.map(N).join(Ee),`}:
13
+ `);for(let o of r)e.push(" ",t.map(i=>H(o[i],Ee)).join(Ee),`
14
+ `)}function cu(e){return e!==""&&or(e)}function rr(e,n,t,r=new Set){if(!or(n))return!1;if(oe(e))return t[n]=e,!0;if(Array.isArray(e)){if(r.has(e))return!1;r.add(e),t[`${n}.length`]=e.length;let o=e.every((i,s)=>rr(i,`${n}.${s}`,t,r));return r.delete(e),o}if(A(e)){if(r.has(e))return!1;r.add(e);let o=Object.entries(e).every(([i,s])=>!i.includes(".")&&rr(s,`${n}.${i}`,t,r));return r.delete(e),o}return!1}function uu(e){let n=Object.keys(e[0]??{});if(e.every(t=>pu(Object.keys(t),n)))return n.every(or)?n:void 0}function pu(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function or(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function Be(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function nt(e,n){if(n===-1)throw R(0,"array header missing colon");let t=e.slice(0,n),r=W(t,"[",0);if(r===-1)throw R(0,"invalid array header");let o,i;try{[o,i]=J(t.slice(0,r),0)}catch{throw R(0,"invalid array header")}let s=t.slice(r+1),a=s.indexOf("]");if(a===-1)throw R(0,"invalid array header");let l=s.slice(0,a),d=/^[0-9]*/.exec(l)[0];if(d===""||d.length>1&&d.startsWith("0"))throw R(0,"invalid array header");let p=Number.parseInt(d,10),u;switch(l.slice(d.length)){case"":u=",";break;case" ":u=" ";break;case"|":u="|";break;default:throw R(0,"invalid array header")}let f=s.slice(a+1),m,h;if(f==="")m=void 0,h=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{h=mu(f.slice(1,-1),u),m=sr(h)}catch(b){throw R(0,b.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw R(0,"invalid array header");return{key:o,keyQuoted:i,len:p,delimiter:u,fields:m,fieldTree:h}}function Ui(e){let n=W(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=J(e.slice(0,n),0)}catch{throw R(0,"invalid keyed map header")}if(t===""&&!r)throw R(0,"expected non-empty field name");let o=e.slice(n+1,-1),i=D;(o.startsWith("|")||o.startsWith(" "))&&(i=o[0],o=o.slice(1));let s;try{s=fu(o,i,i)}catch(a){throw R(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:i,fields:s}}function fu(e,n,t){let r=[],o=0;function i(l,d){let p=0;for(;o<e.length&&!(d&&e[o]==="}");){if(e[o]===n||e[o]==="}")throw R(0,"invalid array header");let u=o;for(;o<e.length;){let h=e[o];if(h==='"'){s();continue}if(h===n||h==="{"||h==="}"||h==="[")break;o+=1}let[f,m]=J(e.slice(u,o),0);if(f===""&&!m)throw R(0,"invalid array header");if(p+=1,e[o]==="["){o+=1;let h=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw R(0,"invalid array header");let b=e.slice(h,o);if(!Bi(b,t))throw R(0,"invalid array header");o+=1,r.push({path:[...l,f],listDelimiter:b})}else if(e[o]==="{"){o+=1;let h=r.length;if(i([...l,f],!0),e[o]!=="}"||r.length===h)throw R(0,"invalid array header");o+=1}else r.push({path:[...l,f],listDelimiter:void 0});if(e[o]===n){if(o+=1,o>=e.length||e[o]==="}")throw R(0,"invalid array header");continue}if(d?e[o]==="}":o===e.length)break;throw R(0,"invalid array header")}if(p===0)throw R(0,"invalid array header")}function s(){for(o+=1;o<e.length;){let l=e[o];if(o+=1,l==="\\")o+=1;else if(l==='"')return}}if(i([],!1),o!==e.length)throw R(0,"invalid array header");let a=new Set;for(let l=0;l<r.length;l+=1)for(let d=l+1;d<r.length;d+=1)if(Ki(r[l].path,r[d].path)||yn(r[l].path,r[d].path)||yn(r[d].path,r[l].path))throw R(0,"duplicate key");for(let l of r){let p=l.path.join("\0");if(a.has(p))throw R(0,"duplicate key");a.add(p)}return r}function mu(e,n){if(n!==D&&e.includes(D)&&(e.includes("[")||e.includes("{")))return ir(e,D,n);try{return ir(e,n,n)}catch(t){if(n!==D&&t.reason!=="duplicate key")return ir(e,D,n);throw t}}function ir(e,n,t){let r=0;function o(l){let d=[];for(;r<e.length&&!(l&&e[r]==="}");){if(e[r]===n||e[r]==="}")throw R(0,"invalid array header");let p=r;for(;r<e.length;){let h=e[r];if(h==='"'){i();continue}if(h===n||h==="{"||h==="}"||h==="[")break;r+=1}let[u,f]=J(e.slice(p,r),0);if(u===""&&!f)throw R(0,"invalid array header");let m={key:u};if(e[r]==="["){r+=1;let h=r;for(;r<e.length&&e[r]!=="]";)r+=1;if(r>=e.length)throw R(0,"invalid array header");let b=e.slice(h,r);r+=1;let k=hu(b);if(k!==void 0){if(k.delimiter!==t)throw R(0,"invalid array header");m.fixedLength=k.len,m.fixedDelimiter=k.delimiter}else if(Bi(b,t))m.listDelimiter=b;else throw R(0,"invalid array header")}else if(e[r]==="{"){if(r+=1,m.children=o(!0),e[r]!=="}"||m.children.length===0)throw R(0,"invalid array header");r+=1}if(d.push(m),e[r]===n){if(r+=1,r>=e.length||e[r]==="}")throw R(0,"invalid array header");continue}if(l?e[r]==="}":r===e.length)break;throw R(0,"invalid array header")}if(d.length===0)throw R(0,"invalid array header");return d}function i(){for(r+=1;r<e.length;){let l=e[r];if(r+=1,l==="\\")r+=1;else if(l==='"')return}}let s=o(!1);if(r!==e.length)throw R(0,"invalid array header");let a=sr(s);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(Ki(a[l].path,a[d].path)||yn(a[l].path,a[d].path)||yn(a[d].path,a[l].path))throw R(0,"duplicate key");return s}function hu(e){let n=/^[0-9]+/.exec(e)?.[0];if(n===void 0||n.length>1&&n.startsWith("0"))return;let t=e.slice(n.length),r;switch(t){case"":r=D;break;case" ":r=" ";break;case"|":r="|";break;default:return}return{len:Number.parseInt(n,10),delimiter:r}}function sr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?sr(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function tt(e,n,t){return e.listDelimiter===void 0?B(n,t):Q(n,e.listDelimiter,t).map(r=>B(r,t))}function Bi(e,n){return e.length===1&&e!==n&&!/[ \t\r\n"[\]{}:]/.test(e)}function Ki(e,n){return e.length===n.length&&yn(e,n)}function yn(e,n){return n.every((t,r)=>e[r]===t)}function rt(e,n){return R(n,e.reason??String(e.message))}function Y(e,n){let t=Ti(n),r=Ni(e,t),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw R(o.number,"invalid indentation");let i=r.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){gn(o.content,o.number,t);let d;try{d=nt(o.content,W(o.content,":",o.number))}catch(p){if(t.strict)throw rt(p,o.number);d=void 0}if(d!==void 0)return ku(d,r,t)}if(i&&W(o.content,":",o.number)===-1)return B(o.content.trim(),o.number);let s={index:0},a=ar(r,s,0,t),l=r[s.index];if(l!==void 0)throw R(l.number,"expected end of document");return t.cyclicDiscriminatedArrays?Wi(a):a}function ar(e,n,t,r){let o={};for(;n.index<e.length;){let i=e[n.index];if(i.depth<t)break;if(i.depth>t)throw R(i.number,"invalid indentation");let{key:s,quoted:a,value:l}=gu(e,n,t,r);Yi(o,s,a,l,r,i.number)}return o}function gu(e,n,t,r){let o=e[n.index],i=o.content,s=W(i,":",o.number);if(s===-1)throw R(o.number,"expected `key: value`");let a=i.slice(0,s),l=i.slice(s+1),d=W(a,"[",o.number),p=W(a,"{",o.number);if(p!==-1&&(d===-1||p<d)){gn(a,o.number,r);let h;try{h=Ui(a)}catch(k){if(r.strict)throw rt(k,o.number);n.index+=1;let w=lr(e,n,t,l,o.number,r);return{key:a.trim(),quoted:!1,value:w}}if(l.trim()!=="")throw R(o.number,"expected keyed map rows");let b=yu(h,e,n,t+1,r);return{key:h.key,quoted:h.keyQuoted,value:b}}if(d!==-1){gn(a,o.number,r);let h;try{h=nt(a,s)}catch(k){if(r.strict)throw rt(k,o.number);n.index+=1;let w=lr(e,n,t,l,o.number,r);return{key:a.trim(),quoted:!1,value:w}}if(h.key===""&&!h.keyQuoted)throw R(o.number,"expected non-empty field name");let b=dr(h,l,e,n,t,r);return{key:h.key,quoted:h.keyQuoted,value:b}}let[u,f]=J(a,o.number);if(u===""&&!f)throw R(o.number,"expected non-empty field name");n.index+=1;let m=lr(e,n,t,l,o.number,r);return{key:u,quoted:f,value:m}}function lr(e,n,t,r,o,i){let s=r.trim();if(s==="[]")return[];if(s!=="")return B(s,o);let a=e[n.index];return a!==void 0&&a.depth>t?ar(e,n,t+1,i):{}}function yu(e,n,t,r,o){let i={};for(t.index+=1;t.index<n.length;){let s=n[t.index];if(s.depth<r)break;if(s.depth>r)throw R(s.number,"invalid indentation");if(s.blankBefore&&o.strict)throw R(s.number,"blank line inside keyed map");let a=W(s.content,":",s.number);if(a===-1)throw R(s.number,"expected `key: value`");let[l,d]=J(s.content.slice(0,a),s.number);if(l===""&&!d)throw R(s.number,"expected non-empty field name");let p=Q(s.content.slice(a+1).trim(),e.delimiter,s.number);if(p.length!==e.fields.length)throw R(s.number,"keyed map row length mismatch");let u={};e.fields.forEach((f,m)=>{Ve(u,f.path,tt(f,p[m],s.number),o,s.number)}),Yi(i,l,d,u,o,s.number),t.index+=1}return i}function ku(e,n,t){let r=n[0],o=W(r.content,":",r.number);if(o===-1)throw R(r.number,"expected `key: value`");let i=r.content.slice(o+1),s={index:0},a=dr(e,i,n,s,0,t),l=n[s.index];if(l!==void 0)throw R(l.number,"expected end of document");return a}function dr(e,n,t,r,o,i){let s=t[r.index].number,a=n.trim();if(r.index+=1,e.fields!==void 0){if(a!=="")throw R(s,"expected tabular rows");return Ru(e,e.fields,t,r,o+1,i)}if(a!==""){let l=Q(a,e.delimiter,s).map(d=>B(d,s));if(l.length!==e.len)throw R(s,"array length mismatch");return l}return Eu(e,t,r,o+1,i)}function Ru(e,n,t,r,o,i){if(e.fieldTree!==void 0&&Su(e.fieldTree))return bu(e,t,r,o,i);let s=[];for(;s.length<e.len;){let l=t[r.index];if(l===void 0)throw Be(t,r.index);if(l.depth<o)break;if(l.depth>o)throw R(l.number,"invalid indentation");if(l.blankBefore&&i.strict)throw R(l.number,"blank line inside array");if(!Ke(l.content,e.delimiter,l.number))break;let d=Q(l.content,e.delimiter,l.number);if(d.length!==n.length)throw R(l.number,"array row length mismatch");let p={};n.forEach((u,f)=>{Ve(p,u.path,tt(u,d[f],l.number),i,l.number)}),s.push(p),r.index+=1}if(s.length!==e.len)throw Be(t,r.index);let a=t[r.index];if(a!==void 0&&a.depth>=o&&Ke(a.content,e.delimiter,a.number))throw R(a.number,"array length mismatch");return s}function bu(e,n,t,r,o){return Vi(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function Vi(e,n,t,r,o,i,s,a){let l=[],d=Gi(e,n,t,r,o.index,i,s);for(;l.length<e;){let u=r[o.index];if(u===void 0)throw Be(r,o.index);if(u.depth<i)break;if(u.depth>i)throw R(u.number,"invalid indentation");if(u.blankBefore&&s.strict)throw R(u.number,"blank line inside array");if(!Ke(u.content,t,u.number))break;let f=Q(u.content,t,u.number),m={cellIndex:0,nextIndex:o.index+1,flatWidth:ot(n),childTableFields:d},h=qi(n,f,u.number,r,m,i+1,t,s);if(m.cellIndex!==f.length)throw R(u.number,"array row length mismatch");l.push(xu(n,h,a)),o.index=m.nextIndex}if(l.length!==e)throw Be(r,o.index);let p=r[o.index];if(p!==void 0&&p.depth>=i&&Ke(p.content,t,p.number))throw R(p.number,"array length mismatch");return l}function qi(e,n,t,r,o,i,s,a){let l={};return e.forEach((d,p)=>{let u=e.slice(p+1),f=_u(d,u,n,t,r,o,i,s,a);Ve(l,[d.key],f,a,t)}),l}function _u(e,n,t,r,o,i,s,a,l){if(e.fixedLength!==void 0){if(i.cellIndex+e.fixedLength>t.length)throw R(r,"array row length mismatch");let p=t.slice(i.cellIndex,i.cellIndex+e.fixedLength).map(u=>B(u,r));return i.cellIndex+=e.fixedLength,p}if(e.children!==void 0){let p=ot(e.children),u=t[i.cellIndex],f=Qi(u),m=t.length-i.cellIndex-1,h=o[i.nextIndex],b=h!==void 0&&h.depth===s,k=i.childTableFields===void 0?void 0:i.childTableFields.has(e);if(k===void 0?f!==void 0&&(b||t.length!==i.flatWidth&&m<p+vu(n)):k){if(f===void 0)throw R(r,"array row length mismatch");return i.cellIndex+=1,Vi(f,e.children,a,o,{get index(){return i.nextIndex},set index(j){i.nextIndex=j}},s,l,!1)}return qi(e.children,t,r,o,i,s,a,l)}let d=t[i.cellIndex];if(d===void 0)throw R(r,"array row length mismatch");return i.cellIndex+=1,tt(e,d,r)}function Gi(e,n,t,r,o,i,s){let a=n.filter(p=>p.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let l,d=1<<a.length;for(let p=0;p<d;p+=1){let u=new Set;a.forEach((m,h)=>{p&1<<h&&u.add(m)});let f=Ji(e,n,u,t,r,o,i,s);f!==void 0&&(l===void 0||f.consumedChildRows>l.consumedChildRows||f.consumedChildRows===l.consumedChildRows&&u.size<l.childTableFields.size)&&(l={childTableFields:u,consumedChildRows:f.consumedChildRows})}return l?.childTableFields}function Ji(e,n,t,r,o,i,s,a){let l=i,d=0;try{for(let u=0;u<e;u+=1){let f=o[l];if(f===void 0||f.depth!==s||f.blankBefore&&a.strict||!Ke(f.content,r,f.number))return;let m=Q(f.content,r,f.number),h=wu(n,t,m,r,o,l+1,s+1,a);if(h===void 0||o[h.nextIndex]?.depth>s)return;d+=h.consumedChildRows,l=h.nextIndex}let p=o[l];if(p!==void 0&&p.depth>=s&&Ke(p.content,r,p.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function wu(e,n,t,r,o,i,s,a){let l=0,d=i,p=0;for(let u of e){if(u.fixedLength!==void 0)l+=u.fixedLength;else if(u.children!==void 0)if(n.has(u)){let f=Qi(t[l]);if(f===void 0)return;l+=1;let m=Gi(f,u.children,r,o,d,s,a);if(m===void 0)return;let h=Ji(f,u.children,m,r,o,d,s,a);if(h===void 0)return;d=h.nextIndex,p+=f+h.consumedChildRows}else l+=ot(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:p}}function xu(e,n,t){return t&&e.length===1&&e[0].fixedLength!==void 0?n[e[0].key]:n}function Qi(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function Su(e){return e.some(n=>n.fixedLength!==void 0||n.children!==void 0)}function ot(e){return e.reduce((n,t)=>n+zi(t),0)}function zi(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?ot(e.children):1}function vu(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+zi(t),0)}function Ke(e,n,t){let r=W(e,":",t);if(r===-1)return!0;let o=W(e,n,t);return o===-1?!1:o<r}function Eu(e,n,t,r,o){let i=[];for(;i.length<e.len;){let a=n[t.index];if(a===void 0||a.depth<r)throw Be(n,t.index);if(a.depth>r)throw R(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw R(a.number,"blank line inside array");i.push(Pu(n,t,r,o))}let s=n[t.index];if(s!==void 0&&s.depth>=r)throw R(s.number,"array length mismatch");return i}function Pu(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw R(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return n.index+=1,{};if(i.startsWith("[")){let s=W(i,":",o.number);gn(i,o.number,r);let a;try{a=nt(i,s)}catch{a=void 0}if(a!==void 0){let l=i.slice(s+1);return dr(a,l,e,n,t,r)}}if(W(i,":",o.number)!==-1){let s=[{number:o.number,depth:t+1,content:i,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let a=e[n.index];if(a.depth<=t)break;s.push(a),n.index+=1}return ar(s,{index:0},t+1,r)}return n.index+=1,B(i,o.number)}function Yi(e,n,t,r,o,i){if(o.expandPaths&&!t&&n.includes(".")){let s=n.split(".");if(s.every(ju)){Ve(e,s,r,o,i);return}}Ve(e,[n],r,o,i)}function Ve(e,n,t,r,o){ie(n.length-1,o,r);let i=n[0],s=Object.prototype.hasOwnProperty.call(e,i);if(n.length===1){if(s&&r.strict)throw R(o,"duplicate key");z(e,i,t);return}if(s&&!A(e[i])){if(r.strict)throw R(o,"path expansion conflict");z(e,i,{})}else s||z(e,i,{});Ve(e[i],n.slice(1),t,r,o)}function ju(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function M(e,n={}){let t=n.maxDepth??1e3,r=n.delimiter??D;if(![D,"|"," "].includes(r))throw R(0,"invalid array header");let o={nestedTabularHeaders:n.nestedTabularHeaders===!0,keyedMapCollapse:n.keyedMapCollapse===!0,primitiveArrayColumns:n.primitiveArrayColumns===!0,objectArrayColumns:n.objectArrayColumns===!0,cyclicDiscriminatedArrays:n.cyclicDiscriminatedArrays===!0,delimiter:r,maxDepth:t===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(t))};if(o.cyclicDiscriminatedArrays){let s=Fi(e);if(s!==void 0)return s}let i=[];return Array.isArray(e)?fr(i,void 0,e,0,!1,o):A(e)?Xi(i,e,0,o):i.push(H(e,r)),i.join("")}function qe(e,n){e.push(" ".repeat(n*2))}function Xi(e,n,t,r){ie(t,0,r);for(let[o,i]of Object.entries(n))qe(e,t),ur(e,o,i,t,r)}function ur(e,n,t,r,o){if(ie(r,0,o),Array.isArray(t)){fr(e,n,t,r,!1,o);return}if(A(t)){let i=o.keyedMapCollapse?Ou(t,o,r+1):void 0;if(i!==void 0){e.push(N(n),"{",mr(o.delimiter),i.fields.map(s=>yr(s,o.delimiter)).join(o.delimiter),`}:
15
+ `);for(let[s,a]of Object.entries(t)){qe(e,r+1);let l=[];e.push(N(s),": ",i.paths.map(d=>kr(gr(a,d.path),d,o.delimiter,o,l,r+2)).join(o.delimiter),`
16
+ `),e.push(...l)}return}e.push(N(n),`:
17
+ `),Xi(e,t,r+1,o);return}e.push(N(n),": ",H(t,o.delimiter),`
18
+ `)}function fr(e,n,t,r,o,i){if(ie(r,0,i),t.length===0){n!==void 0?e.push(N(n),`: []
14
19
  `):o?e.push(`[0]:
15
20
  `):e.push(`[]
16
- `);return}if(t.every(Ze)){Pt(e,n,t.length,void 0),e.push(" "),e.push(t.map(l=>q(l,j)).join(j)),e.push(`
17
- `);return}let i=o?void 0:Ko(t,s);if(i!==void 0){Pt(e,n,t.length,i.fields),e.push(`
18
- `);for(let l of t)en(e,r+1),e.push(i.paths.map(a=>q(Go(l,a),j)).join(j)),e.push(`
19
- `);return}Pt(e,n,t.length,void 0),e.push(`
20
- `);for(let l of t)en(e,r+1),Fd(e,l,r+1,s)}function Fd(e,n,t,r){if(Array.isArray(n)){e.push("- "),Nt(e,void 0,n,t,!0,r);return}if(De(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
21
- `);return}e.push("- "),$t(e,o[0][0],o[0][1],t+1,r);for(let[s,i]of o.slice(1))en(e,t+1),$t(e,s,i,t+1,r);return}e.push("- ",q(n,j),`
22
- `)}function Pt(e,n,t,r){n!==void 0&&e.push(F(n)),e.push("[",String(t),"]"),r!==void 0&&e.push("{",r.map(Wt).join(j),"}"),e.push(":")}function Ko(e,n){let t=Jo(e.map(r=>({value:r})),n);return t===void 0?void 0:{fields:t,paths:qo(t)}}function Hd(e,n){let t=Object.values(e);if(!(t.length<2))return Ko(t,n)}function Jo(e,n){let t=e[0]?.value;if(!De(t))return;let r=Object.keys(t).map(o=>({key:o}));if(r.length!==0){for(let{value:o}of e)if(!De(o)||Object.keys(o).length!==r.length||r.some(i=>!Object.prototype.hasOwnProperty.call(o,i.key)))return;for(let o of r){let s=e.map(({value:l})=>({value:l[o.key]}));if(s.every(({value:l})=>Ze(l)))continue;if(!n.nestedTabularHeaders)return;let i=Jo(s,n);if(i===void 0)return;o.children=i}return r}}function qo(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children===void 0?[r]:qo(t.children,r)})}function Go(e,n){let t=e;for(let r of n)t=t[r];return t}function Wt(e){return e.children===void 0?F(e.key):`${F(e.key)}{${e.children.map(Wt).join(j)}}`}var ts=[j,"|"," "];var rs=8,os=/^[A-Za-z0-9_-]+$/,My=new TextEncoder,Cy=new TextDecoder;function Vd(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 ss(e,n){if(!os.test(e))throw S(n,"invalid tag")}function Bd(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!os.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw S(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function Kd(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(!ts.includes(i)&&i!=="")throw S(n,"invalid header delimiter");let l=i===""?j:i,a=t.slice(r+1),d=null;if(!s&&a.startsWith("<")){let m=a.indexOf(">");if(m===-1)throw S(n,"invalid tag");if(d=a.slice(1,m),ss(d,n),i!=="")throw S(n,"invalid header delimiter");a=a.slice(m+1)}if(!a.startsWith("{")||!a.endsWith("}:"))throw S(n,"invalid header");let u=a.slice(1,-2),p;try{p=he(u,l,n).map(m=>ne(m,n)[0])}catch(m){throw Pe(m)}if(p.length===0||p.some(m=>m===""))throw S(n,"invalid header fields");return{delimiter:l,fields:p,fieldText:u,continuation:s,tag:d}}function Jd(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 zo(e,n,t,r){let o;try{o=he(e,n,r)}catch(s){throw Pe(s)}if(o.length!==t)throw S(r,"row arity mismatch");for(let s of o)try{J(s,r)}catch(i){throw Pe(i)}return o}function qd(e,n,t){let r={};return e.forEach((o,s)=>{try{je(r,o,J(n[s],t))}catch(i){throw Pe(i)}}),r}function Gd(e,n,t){if(e.startsWith("- "))throw S(n,"reserved line prefix");let r=Vd(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=Kd(e,n);if(o!==null)return o.continuation?(Jd(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=Bd(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:zo(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:zo(e,t.delimiter,t.fields.length,n)}}function zd(e,n={}){let t=[],r=new Map,o=[],s=[],i=null,l=!1,a=!1;function d(g,y){let _=s.at(-1);if(_!==void 0&&_.lane===g.lane&&_.delimiter===g.delimiter&&_.fieldText===g.fieldText){_.rows.push(y);return}s.push({lane:g.lane,delimiter:g.delimiter,fields:g.fields,fieldText:g.fieldText,rows:[y]})}function u(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function p(g,y,_){let k=r.get(g);if(k===void 0){if(r.size>=rs)throw S(_,"too many tagged lanes");k={segments:[],current:null},r.set(g,k),t.push(g)}else k.current!==null&&k.segments.push(k.current);k.current={lane:g,delimiter:y.delimiter,fields:y.fields,fieldText:y.fieldText,rows:[]},k.delimiter=y.delimiter,k.fields=y.fields,k.fieldText=y.fieldText}if(An(e).forEach((g,y)=>{let _=y+1;if(g==="")return;let k=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},b=Gd(g,_,k);if(b.kind==="trailer"){u(),i=null;return}if(b.kind!=="continuation"){if(b.kind==="tag-header"){a=!0,p(b.header.tag,b.header,_);return}if(b.kind==="header"){u(),l||(t.push(null),l=!0),i={lane:null,delimiter:b.header.delimiter,fields:b.header.fields,fieldText:b.header.fieldText,rows:[]};return}if(b.kind==="tagged-row"){a=!0;let D=r.get(b.tag).current;D.rows.push(b.cells),d(D,b.cells);return}if(i===null)throw S(_,"row before header");i.rows.push(b.cells),d(i,b.cells)}}),!a)return u(),n.preserveInterleaving===!0,o;let m=[];u();for(let g of t){if(g===null){m.push(...o);continue}let y=r.get(g);m.push(...y.segments),y.current!==null&&m.push(y.current)}return n.preserveInterleaving===!0?s:m}function de(e){return zd(e).flatMap(n=>n.rows.map(t=>qd(n.fields,t,0)))}function Qd(e){if(!ts.includes(e))throw S(0,"invalid header delimiter")}function Qo(e,n,t=!1){return`[${`${t?"~":""}${e===j?"":e}`}]{${n}}:
23
- `}function Yo(e,n){return`[]<${e}>{${n}}:
24
- `}function Mt(e,n){return n.map(F).join(e)}function Yd(e){if(!Array.isArray(e)||e.length===0)throw S(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=ne(String(n),0)}catch(r){throw Pe(r)}if(t==="")throw S(0,"TOONL header requires fields");return t})}function Zo(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function Xo(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw S(0,"TOONL continuation cadence must be positive")}function Zd(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function es(e){if(e===null||typeof e!="object"||Array.isArray(e))throw S(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw S(0,"TOONL output requires object rows");if(n.some(t=>!Ze(e[t])))throw S(0,"TOONL rows must be flat objects");return n}function Xd(e){return JSON.stringify([...e].sort())}function ns(e,n){let t=Xd(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function te({delimiter:e=j,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){Qd(e),Xo(t),Xo(r);let o=null,s="",i=new Map,l=0,a=0,d=0,u=new Map,p=!1,m={continuationEveryRows:t,continuationEveryBytes:r},g=()=>o===null||!n?"":`[=${l}]
25
- `,y=()=>Zd(m,a,d)?(a=0,d=0,Qo(e,s,!0)):"",_=k=>{ss(k,0);let b=u.get(k);if(b===void 0){if(u.size>=rs)throw S(0,"too many tagged lanes");b={fields:null,fieldsByShape:new Map},u.set(k,b)}return b};return{push(k){if(p)throw S(0,"TOONL encoder is closed");let b=ns(es(k),i),D="";(o===null||o.length!==b.length||o.some((me,ve)=>me!==b[ve]))&&(D+=g(),o=b,s=Mt(e,o),l=0,a=0,d=0,D+=Qo(e,s));let V=o.map(me=>q(k[me],e));D+=y();let C=`${V.join(e)}
26
- `;return D+=C,l+=1,a+=1,d+=C.length,D},declareLane(k,b){if(p)throw S(0,"TOONL encoder is closed");let D=Yd(b),V=Mt(j,D),C=_(k);return Zo(C.fields,D)?"":(C.fields=D,Yo(k,V))},pushTagged(k,b){if(p)throw S(0,"TOONL encoder is closed");let D=_(k),V=ns(es(b),D.fieldsByShape),C=Mt(j,V),me=V.map(Rn=>q(b[Rn],j)),ve="";return Zo(D.fields,V)||(D.fields=V,ve+=Yo(k,C)),`${ve}${k}:${me.join(j)}
27
- `},end(){return p?"":(p=!0,g())}}}function Ct(e){let n={app:e,version:ec(Oe("__RED_BUILD_VERSION__",()=>"3.3.9")??"0.0.0-dev"),gitSha:Oe("__RED_BUILD_GIT_SHA__",()=>"b4523c083964ce5343de9ec567223db0b5a461e4")??"unknown",buildTime:Oe("__RED_BUILD_TIME__",()=>"2026-08-02T13:24:49Z")??"unknown",bundleAsset:Oe("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=Oe("__REDDB_SDK_VERSION__",()=>""),r=Oe("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function ec(e){return e.startsWith("v")?e.slice(1):e}function is(e){return`${e.app} ${e.version} ${e.gitSha}`}function Oe(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var ls={"=":"data",":=":{to:"data",typed:!0},":":"meta"},nc=/^[a-z][a-z0-9+.-]*:\/\//i;function tc(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 rc(e=ls){return Object.entries(e).map(([n,t])=>tc(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function oc(e){return/^-\d+(\.\d+)?$/.test(e)}function nn(e){return!(!e||e.startsWith("-")&&!oc(e))}function In(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 as(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=>as(t.trim())):e}function ye(e,n){switch(n){case"boolean":return sc(e);case"number":return ic(e);case"array":return e.split(",").map(t=>In(t.trim()));case"string":default:return e}}function sc(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function ic(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 ce(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function lc(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 ac(e){let n=[],t=cc(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
21
+ `);return}if(t.every(oe)){cr(e,n,t.length,void 0,i.delimiter),e.push(" "),e.push(t.map(a=>H(a,i.delimiter)).join(i.delimiter)),e.push(`
22
+ `);return}let s=o?void 0:Zi(t,i,r+1);if(s!==void 0){cr(e,n,t.length,s.fields,i.delimiter),e.push(`
23
+ `);for(let a of t){qe(e,r+1);let l=[];e.push(s.paths.map(d=>kr(gr(a,d.path),d,i.delimiter,i,l,r+2)).join(i.delimiter)),e.push(`
24
+ `),e.push(...l)}return}cr(e,n,t.length,void 0,i.delimiter),e.push(`
25
+ `);for(let a of t)qe(e,r+1),Du(e,a,r+1,i)}function Du(e,n,t,r){if(ie(t,0,r),Array.isArray(n)){e.push("- "),fr(e,void 0,n,t,!0,r);return}if(A(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
26
+ `);return}e.push("- "),ur(e,o[0][0],o[0][1],t+1,r);for(let[i,s]of o.slice(1))qe(e,t+1),ur(e,i,s,t+1,r);return}e.push("- ",H(n,r.delimiter),`
27
+ `)}function cr(e,n,t,r,o){n!==void 0&&e.push(N(n)),e.push("[",String(t),mr(o),"]"),r!==void 0&&e.push("{",r.map(i=>yr(i,o)).join(o),"}"),e.push(":")}function mr(e){return e===D?"":e}function Zi(e,n,t){let r=Au(e,n);if(r!==void 0)return r;let o=pr(e.map(i=>({value:i})),n,t);return o===void 0?void 0:{fields:o,paths:hr(o)}}function Ou(e,n,t){let r=Object.values(e);if(!(r.length<2))return Zi(r,n,t)}function pr(e,n,t){ie(t,0,n);let r=e[0]?.value;if(!A(r))return;let o=Object.keys(r).map(i=>({key:i}));if(o.length!==0){for(let{value:i}of e)if(!A(i)||Object.keys(i).length!==o.length||o.some(a=>!Object.prototype.hasOwnProperty.call(i,a.key)))return;for(let i of o){let s=e.map(({value:l})=>({value:l[i.key]}));if(s.every(({value:l})=>oe(l)))continue;if(n.primitiveArrayColumns&&s.every(({value:l})=>Array.isArray(l)&&l.every(oe))){i.listDelimiter=";";continue}if(n.objectArrayColumns&&s.every(({value:l})=>Array.isArray(l))){let l=es(s.map(({value:p})=>p));if(l!==void 0){i.fixedLength=l.fixedLength,i.fixedDelimiter=n.delimiter;continue}let d=pr(s.flatMap(({value:p})=>p.map(u=>({value:u}))),n,t+1);if(d!==void 0){i.children=d,i.childTable=!0;continue}}if(!n.nestedTabularHeaders)return;let a=pr(s,n,t+1);if(a===void 0)return;i.children=a}return o}}function Au(e,n){if(!n.objectArrayColumns)return;let t=es(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:n.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function es(e){let n=e[0]?.length;if(!(!Number.isInteger(n)||n===0)&&e.every(t=>Array.isArray(t)&&t.length===n&&t.every(oe)))return{fixedLength:n}}function hr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.childTable===!0?[{path:r,childFields:t.children}]:t.fixedLength!==void 0?[{path:r,fixedLength:t.fixedLength}]:t.children===void 0?[{path:r,listDelimiter:t.listDelimiter}]:hr(t.children,r)})}function gr(e,n){let t=e;for(let r of n)t=t[r];return t}function yr(e,n){return e.listDelimiter!==void 0?`${N(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${N(e.key)}[${e.fixedLength}${mr(n)}]`:e.children===void 0?N(e.key):`${N(e.key)}{${e.children.map(t=>yr(t,n)).join(n)}}`}function kr(e,n,t,r,o,i){return n.childFields!==void 0?(Lu(o,e,n.childFields,r,i),String(e.length)):n.fixedLength!==void 0?e.map(s=>H(s,t)).join(t):n.listDelimiter===void 0?H(e,t):e.map(s=>$u(s,t,n.listDelimiter)).join(n.listDelimiter)}function Lu(e,n,t,r,o){for(let i of n){qe(e,o);let s=[];e.push(hr(t).map(a=>kr(gr(i,a.path),a,r.delimiter,r,s,o+1)).join(r.delimiter)),e.push(`
28
+ `),e.push(...s)}}function $u(e,n,t){return typeof e!="string"?H(e,n):nr(e,n)||e.includes(t)?Zn(e):e}var as=[D,"|"," "];var ds=8,cs=/^[A-Za-z0-9_-]+$/,Hb=new TextEncoder,Fb=new TextDecoder;function Cu(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw S(n,"invalid trailer count");return Number.parseInt(t,10)}function us(e,n){if(!cs.test(e))throw S(n,"invalid tag")}function Mu(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!cs.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw S(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function Wu(e,n){if(!e.startsWith("["))return null;let t=e.slice(1),r=t.indexOf("]");if(r===-1)throw S(n,"invalid header");let o=t.slice(0,r),i=o.startsWith("~"),s=i?o.slice(1):o;if(!i&&s.startsWith("="))return null;if(!as.includes(s)&&s!=="")throw S(n,"invalid header delimiter");let a=s===""?D:s,l=t.slice(r+1),d=null;if(!i&&l.startsWith("<")){let f=l.indexOf(">");if(f===-1)throw S(n,"invalid tag");if(d=l.slice(1,f),us(d,n),s!=="")throw S(n,"invalid header delimiter");l=l.slice(f+1)}if(!l.startsWith("{")||!l.endsWith("}:"))throw S(n,"invalid header");let p=l.slice(1,-2),u;try{u=Q(p,a,n).map(f=>J(f,n)[0])}catch(f){throw Ue(f)}if(u.length===0||u.some(f=>f===""))throw S(n,"invalid header fields");return{delimiter:a,fields:u,fieldText:p,continuation:i,tag:d}}function Hu(e,n,t){if(e===null||e.delimiter===void 0)throw S(t,"continuation header before header");if(e.delimiter!==n.delimiter||e.fieldText!==n.fieldText)throw S(t,"continuation header mismatch")}function ns(e,n,t,r){let o;try{o=Q(e,n,r)}catch(i){throw Ue(i)}if(o.length!==t)throw S(r,"row arity mismatch");for(let i of o)try{B(i,r)}catch(s){throw Ue(s)}return o}function Fu(e,n,t){let r={};return e.forEach((o,i)=>{try{z(r,o,B(n[i],t))}catch(s){throw Ue(s)}}),r}function Uu(e,n,t){if(e.startsWith("- "))throw S(n,"reserved line prefix");let r=Cu(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw S(n,"trailer without header");if(t.rowCount!==r)throw S(n,"trailer count mismatch");return{kind:"trailer"}}let o=Wu(e,n);if(o!==null)return o.continuation?(Hu(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let i=Mu(e,n);if(i!==null){let s=t?.taggedLanes?.get(i.tag);if(s===void 0)throw S(n,"unknown tag");return{kind:"tagged-row",tag:i.tag,cells:ns(i.cellsText,s.delimiter,s.fields.length,n)}}if(t===null||t.delimiter===void 0)throw S(n,"row before header");return{kind:"row",cells:ns(e,t.delimiter,t.fields.length,n)}}function Bu(e,n={}){let t=[],r=new Map,o=[],i=[],s=null,a=!1,l=!1;function d(m,h){let b=i.at(-1);if(b!==void 0&&b.lane===m.lane&&b.delimiter===m.delimiter&&b.fieldText===m.fieldText){b.rows.push(h);return}i.push({lane:m.lane,delimiter:m.delimiter,fields:m.fields,fieldText:m.fieldText,rows:[h]})}function p(){s!==null&&o.push({delimiter:s.delimiter,fields:s.fields,fieldText:s.fieldText,lane:s.lane,rows:s.rows})}function u(m,h,b){let k=r.get(m);if(k===void 0){if(r.size>=ds)throw S(b,"too many tagged lanes");k={segments:[],current:null},r.set(m,k),t.push(m)}else k.current!==null&&k.segments.push(k.current);k.current={lane:m,delimiter:h.delimiter,fields:h.fields,fieldText:h.fieldText,rows:[]},k.delimiter=h.delimiter,k.fields=h.fields,k.fieldText=h.fieldText}if(Xn(e).forEach((m,h)=>{let b=h+1;if(m==="")return;let k=s===null?{taggedLanes:r}:{delimiter:s.delimiter,fields:s.fields,fieldText:s.fieldText,rowCount:s.rows.length,taggedLanes:r},w=Uu(m,b,k);if(w.kind==="trailer"){p(),s=null;return}if(w.kind!=="continuation"){if(w.kind==="tag-header"){l=!0,u(w.header.tag,w.header,b);return}if(w.kind==="header"){p(),a||(t.push(null),a=!0),s={lane:null,delimiter:w.header.delimiter,fields:w.header.fields,fieldText:w.header.fieldText,rows:[]};return}if(w.kind==="tagged-row"){l=!0;let j=r.get(w.tag).current;j.rows.push(w.cells),d(j,w.cells);return}if(s===null)throw S(b,"row before header");s.rows.push(w.cells),d(s,w.cells)}}),!l)return p(),n.preserveInterleaving===!0,o;let f=[];p();for(let m of t){if(m===null){f.push(...o);continue}let h=r.get(m);f.push(...h.segments),h.current!==null&&f.push(h.current)}return n.preserveInterleaving===!0?i:f}function ye(e){return Bu(e).flatMap(n=>n.rows.map(t=>Fu(n.fields,t,0)))}function Ku(e){if(!as.includes(e))throw S(0,"invalid header delimiter")}function ts(e,n,t=!1){return`[${`${t?"~":""}${e===D?"":e}`}]{${n}}:
29
+ `}function rs(e,n){return`[]<${e}>{${n}}:
30
+ `}function Rr(e,n){return n.map(N).join(e)}function Vu(e){if(!Array.isArray(e)||e.length===0)throw S(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=J(String(n),0)}catch(r){throw Ue(r)}if(t==="")throw S(0,"TOONL header requires fields");return t})}function os(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function is(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw S(0,"TOONL continuation cadence must be positive")}function qu(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function ss(e){if(e===null||typeof e!="object"||Array.isArray(e))throw S(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw S(0,"TOONL output requires object rows");if(n.some(t=>!oe(e[t])))throw S(0,"TOONL rows must be flat objects");return n}function Gu(e){return JSON.stringify([...e].sort())}function ls(e,n){let t=Gu(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function pe({delimiter:e=D,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){Ku(e),is(t),is(r);let o=null,i="",s=new Map,a=0,l=0,d=0,p=new Map,u=!1,f={continuationEveryRows:t,continuationEveryBytes:r},m=()=>o===null||!n?"":`[=${a}]
31
+ `,h=()=>qu(f,l,d)?(l=0,d=0,ts(e,i,!0)):"",b=k=>{us(k,0);let w=p.get(k);if(w===void 0){if(p.size>=ds)throw S(0,"too many tagged lanes");w={fields:null,fieldsByShape:new Map},p.set(k,w)}return w};return{push(k){if(u)throw S(0,"TOONL encoder is closed");let w=ls(ss(k),s),j="";(o===null||o.length!==w.length||o.some((we,Ne)=>we!==w[Ne]))&&(j+=m(),o=w,i=Rr(e,o),a=0,l=0,d=0,j+=ts(e,i));let ne=o.map(we=>H(k[we],e));j+=h();let q=`${ne.join(e)}
32
+ `;return j+=q,a+=1,l+=1,d+=q.length,j},declareLane(k,w){if(u)throw S(0,"TOONL encoder is closed");let j=Vu(w),ne=Rr(D,j),q=b(k);return os(q.fields,j)?"":(q.fields=j,rs(k,ne))},pushTagged(k,w){if(u)throw S(0,"TOONL encoder is closed");let j=b(k),ne=ls(ss(w),j.fieldsByShape),q=Rr(D,ne),we=ne.map(Cn=>H(w[Cn],D)),Ne="";return os(j.fields,ne)||(j.fields=ne,Ne+=rs(k,q)),`${Ne}${k}:${we.join(D)}
33
+ `},end(){return u?"":(u=!0,m())}}}function br(e){let n={app:e,version:Ju(Ge("__RED_BUILD_VERSION__",()=>"3.3.11")??"0.0.0-dev"),gitSha:Ge("__RED_BUILD_GIT_SHA__",()=>"0ac7e9947aa678cf8956b86c0428874cb3a09c31")??"unknown",buildTime:Ge("__RED_BUILD_TIME__",()=>"2026-08-02T23:50:43-03:00")??"unknown",bundleAsset:Ge("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=Ge("__REDDB_SDK_VERSION__",()=>""),r=Ge("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function Ju(e){return e.startsWith("v")?e.slice(1):e}function ps(e){return`${e.app} ${e.version} ${e.gitSha}`}function Ge(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var fs={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Qu=/^[a-z][a-z0-9+.-]*:\/\//i;function zu(e,n){return typeof n=="string"?{separator:e,to:n,typed:!1,prefix:!1}:{separator:e,to:n.to,typed:n.typed??!1,prefix:n.prefix??!1}}function Yu(e=fs){return Object.entries(e).map(([n,t])=>zu(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function Xu(e){return/^-\d+(\.\d+)?$/.test(e)}function kn(e){return!(!e||e.startsWith("-")&&!Xu(e))}function it(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e}function ms(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e.includes(",")?e.split(",").map(t=>ms(t.trim())):e}function Pe(e,n){switch(n){case"boolean":return Zu(e);case"number":return ep(e);case"array":return e.split(",").map(t=>it(t.trim()));case"string":default:return e}}function Zu(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function ep(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let n=Number(e);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${e}" to number`);return n}function ke(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function np(e,n={}){return e.map(t=>{let r=n[t.type];return r?r(t.value):t.value}).join("")}function E(e,n){return{type:e,value:n}}function tp(e){let n=[],t=op(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
28
34
  `),E("newline",`
29
35
  `)),e.positional&&e.positional.length>0){n.push(E("section-header","Arguments:"),E("newline",`
30
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",`
31
37
  `),E("indent"," "),E("option-description",r.description),E("newline",`
32
38
  `))}n.push(E("newline",`
33
39
  `))}if(e.options&&Object.keys(e.options).length>0){n.push(E("section-header","Options:"),E("newline",`
34
- `));let r=uc(e.options);n.push(...r)}return n}function dc(e,n){let t=ac(e);return lc(t,n)}function cc(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 uc(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=[],m=_=>{p.includes(_)||p.push(_)};u.short&&m(`-${u.short}`),m(`--${d}`);for(let _ of u.aliases??[])_.length===1?m(`-${_}`):m(`--${_}`);let g=p.join(", "),y=u.type&&u.type!=="boolean"?`<${u.type}>`:void 0;r.push({flags:g,type:y,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(E("indent"," ")),t.push(E(o,d.flags)),d.type&&(t.push(E("text"," ")),t.push(E(s,d.type))),t.push(E("text",p)),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",`
35
- `))}return t}function ds(e){let n=kc(e.options??{},e.autoShort??!1),t=rc(e.separators??ls);return{schema:e,parse(r){return pc(r,e,n,t)},help(){return dc(e,e.formatter)}}}function pc(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 m=l[i];if(m.variadic){let g=[];for(;a<e.length;){let y=e[a];g.push(m.type?ye(y,m.type):y),a++}o.positional[m.name]=g,i++}else{let g=m.type?ye(u,m.type):u;o.positional[m.name]=g,i++,a++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(u)),a++;continue}if(u.startsWith("--")){a=hc(u,a,e,o,t,n);continue}if(u.startsWith("-")&&u.length>1&&!vc(u)){a=yc(u,a,e,o,t,n);continue}let p=mc(u,r);if(p){let{key:m,value:g,config:y}=p,_=o,k=_[y.to]??(_[y.to]={});k[m]=y.typed?as(g):ce(g),a++;continue}if(i<l.length){let m=l[i];if(m.variadic){let y=[];for(;a<e.length&&!e[a].startsWith("-");){let _=e[a];y.push(m.type?ye(_,m.type):_),a++}o.positional[m.name]=y,i++;continue}let g=m.type?ye(u,m.type):u;o.positional[m.name]=g,i++}else n.allowUnknown!==!1?o.rest.push(u):o.errors.push(`Unexpected positional argument: ${u}`);a++}return bc(o,n,t),_c(o,n,l),wc(o,n,t),o}function mc(e,n){if(nc.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(fc(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(gc(o,s,t))return{key:o,value:s,config:t}}}return null}function fc(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function gc(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 hc(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 Tn(d,u,n+1,r,o,s)}let l=o.get(i);if(l){if(l.type!=="boolean"){let a=t[n+1];return nn(a)?Tn(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 yc(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=Ft(a,o);return u?Tn(u.name,d,n+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=In(ce(d))),n+1)}if(i.length===1){let l=Ft(i,o);if(l){if(l.type!=="boolean"){let a=t[n+1];return nn(a)?Tn(l.name,a,n+2,r,o,s):(r.errors.push(`Option -${i} requires a value`),n+1)}return r.options[l.name]=!0,n+1}if(s.strict)r.errors.push(`Unknown option: -${i}`);else if(s.allowUnknown!==!1){let a=t[n+1];if(nn(a))return r.options[i]=In(ce(a)),n+2;r.options[i]=!0}return n+1}for(let l of i){let a=Ft(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 Tn(e,n,t,r,o,s){let i=o.get(e);if(i){if(i.choices){let a=i.type?ye(ce(n),i.type):ce(n);if(!i.choices.includes(a))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${i.choices.join(", ")}`),t}let l=i.type?ye(ce(n),i.type):ce(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]=In(ce(n)));return t}function kc(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=Rc(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 Rc(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 Ft(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function bc(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?ye(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 _c(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 wc(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 vc(e){return/^-\d+(\.\d+)?$/.test(e)}var Ht=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 Sc(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 xc(e,n){let t=new Map;for(let[o,s]of Object.entries(n))if(!(s.kind!=="value"||s.type!=="array")){t.set(o,o);for(let i of s.aliases??[])t.set(i,o)}let r=new Map;for(let o=0;o<e.length;o+=1){let s=e[o];if(s==="--")break;let i=s.match(/^--([^=]+)(?:=(.*))?$/)??s.match(/^-([^=])(?:=(.*))?$/);if(i===null)continue;let l=t.get(i[1]);if(l===void 0)continue;let a=i[2];if(a===void 0&&nn(e[o+1])&&(a=e[o+1],o+=1),a===void 0)continue;let d=r.get(l)??[];d.push(a),r.set(l,d)}return r}function ke(e,n,t={}){let o=ds({options:Sc(n),separators:{},allowUnknown:!0}).parse([...e]),s={},i=xc(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 Ht(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 Ut=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 cs(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 Ut(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as Nc,mkdirSync as Wc,readFileSync as bs,statSync as Mc}from"node:fs";import{dirname as ws,join as Cc}from"node:path";var us="RED_WORKER_SCOPE",ps="RED_WORKER_MEMORY_CEILING",ms="RED_WORKER_SCOPE_DEGRADATION",Bt={scope:null,memory_ceiling:null,scope_degradation:null};function Kt(e){return{scope:Vt(e[us]),memory_ceiling:Vt(e[ps]),scope_degradation:Vt(e[ms])}}function tn(e){let n={};return e.scope!=null&&e.scope!==""&&(n[us]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[ps]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[ms]=e.scope_degradation),n}function Vt(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as jc,readdirSync as Dc,readFileSync as ys,rmSync as Oc,writeFileSync as $c}from"node:fs";import{basename as Lc,join as $e}from"node:path";import{isAbsolute as yk,join as Nn,resolve as kk}from"node:path";function Ec(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var fs="deaths",gs="deaths.toonl";function Wn(e){return Nn(Ec(e),fs)}function rn(e){return Nn(Wn(e),gs)}var on="live",hs="attributions.toonl";function Mn(e){return Nn(Wn(e),on)}function Jt(e){return Nn(Wn(e),hs)}var Gt=$e("sys","kernel","random","boot_id"),ks=1;function zt(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:ks,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:Rs($e(t,Gt)),cgroup:Ac(t,r),last_phase:e.last_phase}}function Rs(e){try{let n=ys(e,"utf8").trim();return n===""?null:n}catch{return null}}function Ac(e,n){let t=Rs($e(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
36
- `),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 Qt(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function Yt(e,n){let t=$e(e,Qt(n));try{return jc(e,{recursive:!0,mode:448}),$c(t,te({trailer:!1}).push(Tc(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function Re(e,n){try{Oc($e(e,Qt(n)),{force:!0})}catch{}}function Zt(e,n){let t;try{t=Dc(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=$e(e,o);try{let l=de(ys(s,"utf8"))[0];if(l===void 0)throw new Error("anchor holds no record");r.push(Ic(l))}catch(i){n?.(Lc(s),i instanceof Error?i.message:String(i))}}return r}function Ic(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:qt(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:qt(e.pid),ppid:qt(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 qt(e){return typeof e=="number"?e:Number(e)}function Tc(e){return{...e}}var Fc=1,Hc=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Uc(e){return typeof e=="string"&&Hc.has(e)}var Vc="startup";function Bc(e,n){return{...e.scope??Bt,version:Fc,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 Kc(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 er={mkdir(e){Wc(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=Mc(e).size}catch{return!0}if(n===0)return!0;try{return bs(e,"utf8").endsWith(`
37
- `)}catch{return!0}},append(e,n){Nc(e,n,{encoding:"utf8",mode:384})},read(e){return bs(e,"utf8")}};function Jc(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function qc(e,n,t=er){let r=te({trailer:!1}).push(Jc(n));return t.mkdir(ws(e)),t.endsClean(e)||t.append(e,`
38
- `),t.append(e,r),n}function vs(e){let n=e.endsWith(`
40
+ `));let r=ip(e.options);n.push(...r)}return n}function rp(e,n){let t=tp(e);return np(t,n)}function op(e){let n=["[options]"];if(e.positional)for(let t of e.positional)t.variadic?n.push(t.required?`<${t.name}...>`:`[${t.name}...]`):n.push(t.required?`<${t.name}>`:`[${t.name}]`);return n.join(" ")}function ip(e,n=!1){let t=[],r=[],o=n?"global-option-flag":"option-flag",i=n?"global-option-type":"option-type",s=n?"global-option-default":"option-default",a=n?"global-option-description":"option-description";for(let[d,p]of Object.entries(e)){if(p.hidden)continue;let u=[],f=b=>{u.includes(b)||u.push(b)};p.short&&f(`-${p.short}`),f(`--${d}`);for(let b of p.aliases??[])b.length===1?f(`-${b}`):f(`--${b}`);let m=u.join(", "),h=p.type&&p.type!=="boolean"?`<${p.type}>`:void 0;r.push({flags:m,type:h,desc:p.description??"",default:p.default!==void 0?String(p.default):void 0})}let l=Math.max(...r.map(d=>d.flags.length+(d.type?d.type.length+1:0)),20);for(let d of r){let p=d.flags.length+(d.type?d.type.length+1:0),u=" ".repeat(l-p+2);t.push(E("indent"," ")),t.push(E(o,d.flags)),d.type&&(t.push(E("text"," ")),t.push(E(i,d.type))),t.push(E("text",u)),t.push(E(a,d.desc)),d.default!==void 0&&(t.push(E("text"," ")),t.push(E(s,`(default: ${d.default})`))),t.push(E("newline",`
41
+ `))}return t}function hs(e){let n=pp(e.options??{},e.autoShort??!1),t=Yu(e.separators??fs);return{schema:e,parse(r){return sp(r,e,n,t)},help(){return rp(e,e.formatter)}}}function sp(e,n,t,r){let o={positional:{},options:{},errors:[],rest:[]},i=new Set(r.map(p=>p.to));for(let p of i)o[p]={};let s=0,a=n.positional??[],l=0,d=!1;for(;l<e.length;){let p=e[l];if(n.stopEarly&&s>0){o.rest=e.slice(l);break}if(p==="--"&&!d){d=!0,l++;continue}if(d){if(s<a.length){let f=a[s];if(f.variadic){let m=[];for(;l<e.length;){let h=e[l];m.push(f.type?Pe(h,f.type):h),l++}o.positional[f.name]=m,s++}else{let m=f.type?Pe(p,f.type):p;o.positional[f.name]=m,s++,l++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(p)),l++;continue}if(p.startsWith("--")){l=cp(p,l,e,o,t,n);continue}if(p.startsWith("-")&&p.length>1&&!yp(p)){l=up(p,l,e,o,t,n);continue}let u=lp(p,r);if(u){let{key:f,value:m,config:h}=u,b=o,k=b[h.to]??(b[h.to]={});k[f]=h.typed?ms(m):ke(m),l++;continue}if(s<a.length){let f=a[s];if(f.variadic){let h=[];for(;l<e.length&&!e[l].startsWith("-");){let b=e[l];h.push(f.type?Pe(b,f.type):b),l++}o.positional[f.name]=h,s++;continue}let m=f.type?Pe(p,f.type):p;o.positional[f.name]=m,s++}else n.allowUnknown!==!1?o.rest.push(p):o.errors.push(`Unexpected positional argument: ${p}`);l++}return mp(o,n,t),hp(o,n,a),gp(o,n,t),o}function lp(e,n){if(Qu.test(e))return null;for(let t of n){if(t.prefix&&e.startsWith(t.separator)){let o=e.slice(t.separator.length),i=o.indexOf(":");if(i>0){let s=o.slice(0,i),a=o.slice(i+1);if(ap(s))return{key:s,value:a,config:t}}continue}let r=e.indexOf(t.separator);if(r>0){let o=e.slice(0,r),i=e.slice(r+t.separator.length);if(dp(o,i,t))return{key:o,value:i,config:t}}}return null}function ap(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function dp(e,n,t){return e?t.separator===":"?e.includes("/")||e.includes(".")||/^\d+$/.test(n)?!1:/^[A-Z][a-zA-Z0-9-]*$/.test(e):!((t.separator==="="||t.separator===":=")&&e.includes("/")):!1}function cp(e,n,t,r,o,i){let s=e.slice(2);if(s.startsWith("no-")){let l=s.slice(3),d=o.get(l);if(d?.negatable!==!1&&d?.type==="boolean")return r.options[d.name]=!1,n+1}if(s.includes("=")){let l=s.indexOf("="),d=s.slice(0,l),p=s.slice(l+1);return st(d,p,n+1,r,o,i)}let a=o.get(s);if(a){if(a.type!=="boolean"){let l=t[n+1];return kn(l)?st(a.name,l,n+2,r,o,i):(r.errors.push(`Option --${s} requires a value`),n+1)}return r.options[a.name]=!0,n+1}return i.strict?r.errors.push(`Unknown option: --${s}`):i.allowUnknown!==!1&&(r.options[s]=!0),n+1}function up(e,n,t,r,o,i){let s=e.slice(1);if(s.includes("=")){let a=s.indexOf("="),l=s.slice(0,a),d=s.slice(a+1),p=_r(l,o);return p?st(p.name,d,n+1,r,o,i):(i.strict?r.errors.push(`Unknown option: -${l}`):i.allowUnknown!==!1&&(r.options[l]=it(ke(d))),n+1)}if(s.length===1){let a=_r(s,o);if(a){if(a.type!=="boolean"){let l=t[n+1];return kn(l)?st(a.name,l,n+2,r,o,i):(r.errors.push(`Option -${s} requires a value`),n+1)}return r.options[a.name]=!0,n+1}if(i.strict)r.errors.push(`Unknown option: -${s}`);else if(i.allowUnknown!==!1){let l=t[n+1];if(kn(l))return r.options[s]=it(ke(l)),n+2;r.options[s]=!0}return n+1}for(let a of s){let l=_r(a,o);l?l.type==="boolean"?r.options[l.name]=!0:r.errors.push(`Option -${a} requires a value`):i.strict?r.errors.push(`Unknown option: -${a}`):i.allowUnknown!==!1&&(r.options[a]=!0)}return n+1}function st(e,n,t,r,o,i){let s=o.get(e);if(s){if(s.choices){let l=s.type?Pe(ke(n),s.type):ke(n);if(!s.choices.includes(l))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${s.choices.join(", ")}`),t}let a=s.type?Pe(ke(n),s.type):ke(n);if(s.type==="array"){let l=r.options[e];Array.isArray(l)?l.push(...a):r.options[e]=a}else r.options[e]=a}else i.strict?r.errors.push(`Unknown option: --${e}`):i.allowUnknown!==!1&&(r.options[e]=it(ke(n)));return t}function pp(e,n=!1){let t=new Map,r=Object.entries(e).sort(([i],[s])=>i.localeCompare(s)),o=new Set;for(let[,i]of r)i.short&&o.add(i.short);for(let[i,s]of r){let a=s.short??"";n&&!a&&(a=fp(i,o),a&&o.add(a));let l={name:i,short:a,aliases:s.aliases??[],type:s.type??"string",description:s.description??"",required:s.required??!1,hidden:s.hidden??!1,negatable:s.negatable??!0,default:s.default,choices:s.choices,env:s.env,validate:s.validate};t.set(i,l);for(let d of l.aliases)t.set(d,l)}return t}function fp(e,n){for(let t of e){if(!/[a-zA-Z]/.test(t))continue;let r=t.toLowerCase();if(!n.has(r))return r;let o=t.toUpperCase();if(!n.has(o))return o}return""}function _r(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function mp(e,n,t){for(let r of t.values())if(e.options[r.name]===void 0)if(r.env&&process.env[r.env]!==void 0){let o=process.env[r.env];e.options[r.name]=r.type?Pe(o,r.type):o}else r.default!==void 0&&(e.options[r.name]=r.default);for(let r of n.positional??[])e.positional[r.name]===void 0&&r.default!==void 0&&(e.positional[r.name]=r.default)}function hp(e,n,t){if(n.options)for(let[r,o]of Object.entries(n.options))o.required&&e.options[r]===void 0&&e.errors.push(`Missing required option: --${r}`);for(let r of t)r.required&&e.positional[r.name]===void 0&&e.errors.push(`Missing required argument: <${r.name}>`)}function gp(e,n,t){for(let r of t.values()){let o=e.options[r.name];if(r.validate&&o!==void 0){let i=r.validate(o);i!==!0&&e.errors.push(i)}}for(let r of n.positional??[]){let o=e.positional[r.name];if(r.validate&&o!==void 0){let i=r.validate(o);i!==!0&&e.errors.push(i)}}}function yp(e){return/^-\d+(\.\d+)?$/.test(e)}var wr=class extends Error{flag;known;constructor(n,t){super(`unknown flag '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownFlagError",this.flag=n,this.known=t}};function kp(e){let n={};for(let[t,r]of Object.entries(e))n[t]={type:r.kind==="boolean"?"boolean":"string",...t.length===1?{short:t}:{},...r.aliases===void 0?{}:{aliases:r.aliases}};return n}function Rp(e,n){let t=new Map;for(let[o,i]of Object.entries(n))if(!(i.kind!=="value"||i.type!=="array")){t.set(o,o);for(let s of i.aliases??[])t.set(s,o)}let r=new Map;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="--")break;let s=i.match(/^--([^=]+)(?:=(.*))?$/)??i.match(/^-([^=])(?:=(.*))?$/);if(s===null)continue;let a=t.get(s[1]);if(a===void 0)continue;let l=s[2];if(l===void 0&&kn(e[o+1])&&(l=e[o+1],o+=1),l===void 0)continue;let d=r.get(a)??[];d.push(l),r.set(a,d)}return r}function je(e,n,t={}){let o=hs({options:kp(n),separators:{},allowUnknown:!0}).parse([...e]),i={},s=Rp(e,n),a=o.errors.find(l=>/^Option --?\S+ requires a value$/.test(l));if(a!==void 0)throw new Error(a.replace(/^Option /,""));if(o.errors.length>0)throw new Error(o.errors[0]);if(t.unknownFlags==="error"){let l=new Set(Object.keys(n));for(let d of Object.keys(o.options))if(!l.has(d))throw new wr(d.length===1?`-${d}`:`--${d}`,Object.keys(n).map(p=>p.length===1?`-${p}`:`--${p}`))}for(let[l,d]of Object.entries(n)){let p=o.options[l];p!==void 0&&(d.kind==="boolean"?i[l]=p:d.type==="array"?i[l]=(s.get(l)??[]).map(u=>d.coerce(u)):i[l]=d.coerce(String(p)))}return{values:i,positionals:o.rest}}var xr=class extends Error{token;known;constructor(n,t){super(`unknown command '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownCommandError",this.token=n,this.known=t}};function gs(e,n){let[t,...r]=e;if(t!==void 0){for(let[i,s]of Object.entries(n.commands))if(t===i||(s.aliases??[]).includes(t))return{command:i,args:r};if(n.errorOnUnknownCommand&&!t.startsWith("-"))throw new xr(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as Op,mkdirSync as Ap,readFileSync as Es,statSync as Lp}from"node:fs";import{dirname as js,join as $p}from"node:path";var ys="RED_WORKER_SCOPE",ks="RED_WORKER_MEMORY_CEILING",Rs="RED_WORKER_SCOPE_DEGRADATION",vr={scope:null,memory_ceiling:null,scope_degradation:null};function Er(e){return{scope:Sr(e[ys]),memory_ceiling:Sr(e[ks]),scope_degradation:Sr(e[Rs])}}function Rn(e){let n={};return e.scope!=null&&e.scope!==""&&(n[ys]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[ks]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[Rs]=e.scope_degradation),n}function Sr(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as wp,readdirSync as xp,readFileSync as xs,rmSync as Sp,writeFileSync as vp}from"node:fs";import{basename as Ep,join as Je}from"node:path";import{isAbsolute as b_,join as lt,resolve as __}from"node:path";function bp(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var bs="deaths",_s="deaths.toonl";function at(e){return lt(bp(e),bs)}function bn(e){return lt(at(e),_s)}var _n="live",ws="attributions.toonl";function dt(e){return lt(at(e),_n)}function Pr(e){return lt(at(e),ws)}var Dr=Je("sys","kernel","random","boot_id"),Ss=1;function Or(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:Ss,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:vs(Je(t,Dr)),cgroup:Pp(t,r),last_phase:e.last_phase}}function vs(e){try{let n=xs(e,"utf8").trim();return n===""?null:n}catch{return null}}function Pp(e,n){let t=vs(Je(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
42
+ `),o=r.find(s=>s.startsWith("0::"));if(o)return o.slice(3)||null;let i=r[0]?.split(":").slice(2).join(":");return i===void 0||i===""?null:i}function Ar(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function Lr(e,n){let t=Je(e,Ar(n));try{return wp(e,{recursive:!0,mode:448}),vp(t,pe({trailer:!1}).push(Dp(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function De(e,n){try{Sp(Je(e,Ar(n)),{force:!0})}catch{}}function $r(e,n){let t;try{t=xp(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let i=Je(e,o);try{let a=ye(xs(i,"utf8"))[0];if(a===void 0)throw new Error("anchor holds no record");r.push(jp(a))}catch(s){n?.(Ep(i),s instanceof Error?s.message:String(s))}}return r}function jp(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:jr(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:jr(e.pid),ppid:jr(e.ppid),boot_id:e.boot_id==null?null:String(e.boot_id),cgroup:e.cgroup==null?null:String(e.cgroup),last_phase:String(e.last_phase)}}function jr(e){return typeof e=="number"?e:Number(e)}function Dp(e){return{...e}}var Ip=1,Tp=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Np(e){return typeof e=="string"&&Tp.has(e)}var Cp="startup";function Mp(e,n){return{...e.scope??vr,version:Ip,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,exit_path:e.exit_path,signal:e.signal??null,exit_code:e.exit_code??null,last_phase:e.last_phase,detail:e.detail??null,...n}}function Wp(e){let n=e.resourceUsage();return{uptime_s:Math.round(e.uptime()),rss_kb:Math.round(e.memoryUsage().rss/1024),max_rss_kb:n.maxRSS,user_cpu_us:n.userCPUTime,system_cpu_us:n.systemCPUTime,minor_page_faults:n.minorPageFault,major_page_faults:n.majorPageFault,voluntary_ctx_switches:n.voluntaryContextSwitches,involuntary_ctx_switches:n.involuntaryContextSwitches}}var Tr={mkdir(e){Ap(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=Lp(e).size}catch{return!0}if(n===0)return!0;try{return Es(e,"utf8").endsWith(`
43
+ `)}catch{return!0}},append(e,n){Op(e,n,{encoding:"utf8",mode:384})},read(e){return Es(e,"utf8")}};function Hp(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function Fp(e,n,t=Tr){let r=pe({trailer:!1}).push(Hp(n));return t.mkdir(js(e)),t.endsClean(e)||t.append(e,`
44
+ `),t.append(e,r),n}function Ds(e){let n=e.endsWith(`
39
45
  `)?e:e.slice(0,e.lastIndexOf(`
40
- `)+1);return n===""?[]:de(n).map(Gc)}function Gc(e){let n=e.exit_path;if(!Uc(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:N(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:N(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:N(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:N(e.uptime_s),rss_kb:N(e.rss_kb),max_rss_kb:N(e.max_rss_kb),user_cpu_us:N(e.user_cpu_us),system_cpu_us:N(e.system_cpu_us),minor_page_faults:N(e.minor_page_faults),major_page_faults:N(e.major_page_faults),voluntary_ctx_switches:N(e.voluntary_ctx_switches),involuntary_ctx_switches:N(e.involuntary_ctx_switches)}}function N(e){return typeof e=="number"?e:Number(e)}function Ss(e,n=er){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return vs(t)}var zc=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],Xt=null;function xs(e){let n=e.host??process,t=e.io??er,r=e.clock??(()=>new Date().toISOString()),o=n.pid,s=e.scope??Kt(process.env),i=e.phase??Vc,l=null,a=e.presenceDir===void 0?Cc(ws(e.lanePath),on):e.presenceDir,d=null,u=()=>{a!==null&&(d=zt({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),Yt(a,d))},p=k=>{if(!l){try{l=qc(e.lanePath,Bc({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...k},Kc(n)),t)}catch{}a!==null&&d!==null&&Re(a,d)}},m={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:_s(k)})},unhandledRejection(k){p({exit_path:"unhandled-rejection",detail:_s(k)})}},y=[...(e.signals??zc).map(k=>{let b=()=>{if(m.signal(k),!(n.listenerCount?.(k)!==1||!n.kill)){n.off(k,b);try{n.kill(o,k)}catch{}}};return[k,b]}),["uncaughtException",(...k)=>m.uncaughtException(k[0])],["unhandledRejection",(...k)=>m.unhandledRejection(k[0])],["exit",(...k)=>m.exit(typeof k[0]=="number"?k[0]:null)]];for(let[k,b]of y)n.on(k,b);let _={lanePath:e.lanePath,phase(k){i=k,l||u()},currentPhase:()=>i,written:()=>l,uninstall(){for(let[k,b]of y)n.off(k,b);a!==null&&d!==null&&Re(a,d),Xt===_&&(Xt=null)},handlers:m};return e.setActive!==!1&&(Xt=_),u(),_}function _s(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Qc,readdirSync as Yc,readFileSync as Cn,statSync as Zc,writeFileSync as Xc}from"node:fs";import{join as Ds}from"node:path";var eu=1,nu=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],tu=512*1024;function ru(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??nu,r=[],o=Ds(n,Gt),s=null;try{let a=Cn(o,"utf8").trim();s=a===""?null:a,r.push({source:o,result:s?"read":"empty",detail:s})}catch(a){r.push({source:o,result:nr(a),detail:null})}let i=new Set;try{for(let a of Yc(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:nr(a),detail:null})}let l=[];for(let a of t)try{let u=ou(a,e.tailBytes??tu).split(`
41
- `).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:nr(d),detail:null})}return{boot_id:s,live_pids:i,journal:l,probes:r}}function nr(e){return e.code==="ENOENT"?"absent":"unreadable"}function ou(e,n){let t=Zc(e).size,r=Cn(e,"utf8");return t<=n?r:r.slice(r.length-n)}var su=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,iu=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,lu=/Killed (\/\S*) due to memory pressure/,au=/\bopid=(\d+)\b/,Es=/\bsig=(\d+)\b/,du=/\buid=(\d+)\b/,cu=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,uu={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function pu(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,m,g,y)=>({version:eu,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:p,confidence:m,signal:g,host_boot_changed:o,evidence:y,checked:s}),l=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],a=n.journal.find(p=>Ps(p,e.pid,su)||Ps(p,e.pid,iu));if(a!==void 0)return i("oomd",o?"medium":"high","SIGKILL",[a,...l]);if(e.cgroup!==null)for(let p of n.journal){let m=lu.exec(p)?.[1];if(m!==void 0){if(m===e.cgroup)return i("oomd",o?"medium":"high","SIGKILL",[p,...l]);if(e.cgroup.startsWith(`${m}/`))return i("oomd","medium","SIGKILL",[p,`the killed scope ${m} is an ancestor of this process's ${e.cgroup}`,...l])}}let d=n.journal.find(p=>Number(au.exec(p)?.[1])===e.pid&&Es.test(p));if(d!==void 0){let p=Number(Es.exec(d)?.[1]),m=du.exec(d)?.[1];return i("user-signal",o?"medium":"high",uu[p]??null,[d,...m===void 0?[]:[`sent by uid ${m}`],...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(m=>cu.test(m));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 Ps(e,n,t){return Number(t.exec(e)?.[1])===n}var mu=" | ";function js(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(mu)}function fu(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:js(e.evidence),checked:js(e.checked)}}function gu(e){let n=te({trailer:!1});return e.map(t=>n.push(fu(t))).join("")}function Os(e){let n=Mn(e.stateRoot),t=Jt(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??ru({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=Zt(n,p=>s.push(p)),l=Ss(rn(e.stateRoot)),a=[],d=[],u=[];for(let p of i){if(o.live_pids.has(p.pid)){d.push(p);continue}if(l.find(g=>g.pid===p.pid&&g.id===p.id)!==void 0){u.push(p),Re(n,p);continue}a.push(pu(p,o,l,r())),Re(n,p)}return a.length>0&&hu(t,a),{attributions:a,alive:d,self_recorded:u,skipped:s,laneText:()=>{try{return Cn(t,"utf8")}catch{return""}}}}function $s(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 hu(e,n){try{Qc(Ds(e,".."),{recursive:!0,mode:448});let t=yu(e),r=t===""||t.endsWith(`
46
+ `)+1);return n===""?[]:ye(n).map(Up)}function Up(e){let n=e.exit_path;if(!Np(n))throw new Error(`death record has unknown exit_path ${JSON.stringify(n)}`);let t=e.kind;if(t!=="launcher"&&t!=="worker"&&t!=="daemon")throw new Error(`death record has unknown kind ${JSON.stringify(t)}`);return{version:K(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:K(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:K(e.exit_code),last_phase:String(e.last_phase),detail:e.detail==null?null:String(e.detail),scope:e.scope==null?null:String(e.scope),memory_ceiling:e.memory_ceiling==null?null:String(e.memory_ceiling),scope_degradation:e.scope_degradation==null?null:String(e.scope_degradation),uptime_s:K(e.uptime_s),rss_kb:K(e.rss_kb),max_rss_kb:K(e.max_rss_kb),user_cpu_us:K(e.user_cpu_us),system_cpu_us:K(e.system_cpu_us),minor_page_faults:K(e.minor_page_faults),major_page_faults:K(e.major_page_faults),voluntary_ctx_switches:K(e.voluntary_ctx_switches),involuntary_ctx_switches:K(e.involuntary_ctx_switches)}}function K(e){return typeof e=="number"?e:Number(e)}function Os(e,n=Tr){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return Ds(t)}var Bp=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],Ir=null;function As(e){let n=e.host??process,t=e.io??Tr,r=e.clock??(()=>new Date().toISOString()),o=n.pid,i=e.scope??Er(process.env),s=e.phase??Cp,a=null,l=e.presenceDir===void 0?$p(js(e.lanePath),_n):e.presenceDir,d=null,p=()=>{l!==null&&(d=Or({kind:e.kind,id:e.id,last_phase:s,pid:o},{procRoot:e.procRoot}),Lr(l,d))},u=k=>{if(!a){try{a=Fp(e.lanePath,Mp({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:s,scope:i,...k},Wp(n)),t)}catch{}l!==null&&d!==null&&De(l,d)}},f={signal(k){u({exit_path:"signal",signal:k})},exit(k){u({exit_path:"exit",exit_code:k})},uncaughtException(k){u({exit_path:"uncaught-exception",detail:Ps(k)})},unhandledRejection(k){u({exit_path:"unhandled-rejection",detail:Ps(k)})}},h=[...(e.signals??Bp).map(k=>{let w=()=>{if(f.signal(k),!(n.listenerCount?.(k)!==1||!n.kill)){n.off(k,w);try{n.kill(o,k)}catch{}}};return[k,w]}),["uncaughtException",(...k)=>f.uncaughtException(k[0])],["unhandledRejection",(...k)=>f.unhandledRejection(k[0])],["exit",(...k)=>f.exit(typeof k[0]=="number"?k[0]:null)]];for(let[k,w]of h)n.on(k,w);let b={lanePath:e.lanePath,phase(k){s=k,a||p()},currentPhase:()=>s,written:()=>a,uninstall(){for(let[k,w]of h)n.off(k,w);l!==null&&d!==null&&De(l,d),Ir===b&&(Ir=null)},handlers:f};return e.setActive!==!1&&(Ir=b),p(),b}function Ps(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Kp,readdirSync as Vp,readFileSync as ct,statSync as qp,writeFileSync as Gp}from"node:fs";import{join as Ts}from"node:path";var Jp=1,Qp=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],zp=512*1024;function Yp(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??Qp,r=[],o=Ts(n,Dr),i=null;try{let l=ct(o,"utf8").trim();i=l===""?null:l,r.push({source:o,result:i?"read":"empty",detail:i})}catch(l){r.push({source:o,result:Nr(l),detail:null})}let s=new Set;try{for(let l of Vp(n))/^\d+$/.test(l)&&s.add(Number(l));r.push({source:n,result:"read",detail:`${s.size} live pids`})}catch(l){r.push({source:n,result:Nr(l),detail:null})}let a=[];for(let l of t)try{let p=Xp(l,e.tailBytes??zp).split(`
47
+ `).filter(u=>u.trim()!=="");a.push(...p),r.push({source:l,result:p.length===0?"empty":"read",detail:`${p.length} lines`})}catch(d){r.push({source:l,result:Nr(d),detail:null})}return{boot_id:i,live_pids:s,journal:a,probes:r}}function Nr(e){return e.code==="ENOENT"?"absent":"unreadable"}function Xp(e,n){let t=qp(e).size,r=ct(e,"utf8");return t<=n?r:r.slice(r.length-n)}var Zp=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,ef=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,nf=/Killed (\/\S*) due to memory pressure/,tf=/\bopid=(\d+)\b/,Ls=/\bsig=(\d+)\b/,rf=/\buid=(\d+)\b/,of=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,sf={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function lf(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,i=[...n.probes.map(u=>`${u.source}: ${u.result}${u.detail?` (${u.detail})`:""}`),`boot id: anchored under ${e.boot_id??"unknown"}, host now ${n.boot_id??"unknown"} (${o?"changed":"same"})`,`parent account: ppid ${e.ppid}`,`cgroup: ${e.cgroup??"unknown"}`],s=(u,f,m,h)=>({version:Jp,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:u,confidence:f,signal:m,host_boot_changed:o,evidence:h,checked:i}),a=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],l=n.journal.find(u=>$s(u,e.pid,Zp)||$s(u,e.pid,ef));if(l!==void 0)return s("oomd",o?"medium":"high","SIGKILL",[l,...a]);if(e.cgroup!==null)for(let u of n.journal){let f=nf.exec(u)?.[1];if(f!==void 0){if(f===e.cgroup)return s("oomd",o?"medium":"high","SIGKILL",[u,...a]);if(e.cgroup.startsWith(`${f}/`))return s("oomd","medium","SIGKILL",[u,`the killed scope ${f} is an ancestor of this process's ${e.cgroup}`,...a])}}let d=n.journal.find(u=>Number(tf.exec(u)?.[1])===e.pid&&Ls.test(u));if(d!==void 0){let u=Number(Ls.exec(d)?.[1]),f=rf.exec(d)?.[1];return s("user-signal",o?"medium":"high",sf[u]??null,[d,...f===void 0?[]:[`sent by uid ${f}`],...a])}let p=t.find(u=>u.pid===e.ppid);if(p!==void 0&&!n.live_pids.has(e.ppid))return s("parent-death","medium",null,[`parent pid ${e.ppid} (${p.kind} ${p.id}) recorded its own death at ${p.ts} via ${p.exit_path}${p.signal?` ${p.signal}`:""}`]);if(o){let u=n.journal.find(f=>of.test(f));return u!==void 0?s("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,u]):s("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,"no shutdown record on any journal read: the host stopped without announcing it (a freeze or a power loss, not an orderly teardown)"])}return s("unknown","none",null,[])}function $s(e,n,t){return Number(t.exec(e)?.[1])===n}var af=" | ";function Is(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(af)}function df(e){return{version:e.version,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.last_seen,last_phase:e.last_phase,sender_class:e.sender_class,confidence:e.confidence,signal:e.signal,host_boot_changed:e.host_boot_changed,evidence:Is(e.evidence),checked:Is(e.checked)}}function cf(e){let n=pe({trailer:!1});return e.map(t=>n.push(df(t))).join("")}function Ns(e){let n=dt(e.stateRoot),t=Pr(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??Yp({procRoot:e.procRoot,journalPaths:e.journalPaths}),i=[],s=$r(n,u=>i.push(u)),a=Os(bn(e.stateRoot)),l=[],d=[],p=[];for(let u of s){if(o.live_pids.has(u.pid)){d.push(u);continue}if(a.find(m=>m.pid===u.pid&&m.id===u.id)!==void 0){p.push(u),De(n,u);continue}l.push(lf(u,o,a,r())),De(n,u)}return l.length>0&&uf(t,l),{attributions:l,alive:d,self_recorded:p,skipped:i,laneText:()=>{try{return ct(t,"utf8")}catch{return""}}}}function Cs(e){let n=e.skipped.length===0?"":` | unreadable anchors=${e.skipped.join(",")}`;if(e.attributions.length===0)return`death reaper: no un-recorded deaths (live=${e.alive.length} self-recorded=${e.self_recorded.length})${n}`;let t=e.attributions.map(r=>` | ${r.kind} ${r.id} pid=${r.pid} ${r.sender_class}/${r.confidence} phase=${r.last_phase}`+(r.evidence[0]?` evidence="${r.evidence[0]}"`:"")).join("");return`death reaper: attributed ${e.attributions.length}${t}${n}`}function uf(e,n){try{Kp(Ts(e,".."),{recursive:!0,mode:448});let t=pf(e),r=t===""||t.endsWith(`
42
48
  `)?"":`
43
- `;Xc(e,`${t}${r}${gu(n)}`,{encoding:"utf8",mode:384})}catch{}}function yu(e){try{return Cn(e,"utf8")}catch{return""}}import{join as ku}from"node:path";var Ru=[".red","redskilled"],z=448;function be(e){return ku(e,...Ru)}import{execFileSync as Au}from"node:child_process";import{readFileSync as Iu}from"node:fs";import{dirname as Ms,join as Tu}from"node:path";import{existsSync as bu,readFileSync as zk}from"node:fs";import{dirname as _u,join as wu}from"node:path";function Ls(e,n){let t=e;for(let r=0;r<16;r++){let o=wu(t,n);if(bu(o))return o;let s=_u(t);if(s===t)break;t=s}return null}function vu(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function Le(e,n){let t=[];for(let r of e.split(`
44
- `)){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 vu(d)}}import{createHash as Su}from"node:crypto";var xu="project.name";function Is(e){let n=Le(e,xu)?.trim();return n===void 0||n===""?void 0:n}var Eu=8,Ts="project";function Ns(e){let n=$u(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:Pu(e.remoteUrl)??{name:ju(e.checkoutPath,n),source:"basename"},o=Ou(n??tr(e.checkoutPath));return{name:r.name,slug:`${Du(r.name)}-${o}`,hash:o,source:r.source}}function Ws(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 Pu(e){let n=Ws(e);return n===void 0?void 0:{name:n,source:"remote"}}function ju(e,n){let t=n===void 0?"":As(Lu(n));if(t!=="")return t;let r=As(tr(e));return r===""?Ts:r}function Du(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?Ts:t}function Ou(e){return Su("sha256").update(e).digest("hex").slice(0,Eu)}function $u(e){let n=tr(e??"");return n===""?void 0:n}function tr(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function As(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function Lu(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var Nu=2e3;function Cs(e){return Wu(e).name}function Wu(e){let n=or(e),t=rr(e,["rev-parse","--absolute-git-dir"])??rr(e,["rev-parse","--git-common-dir"]),r=rr(e,["remote","get-url","origin"]);return Ns({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function or(e){let n=Ls(e,Tu(".red","config.yaml"));if(n==null)return{};let t;try{t=Iu(n,"utf8")}catch{return{}}let r=Is(t),o=Ms(Ms(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function rr(e,n){try{let t=Au("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Nu}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as ka}from"node:crypto";import{spawn as hh}from"node:child_process";import{mkdir as yh,rm as kh}from"node:fs/promises";import{dirname as Rh}from"node:path";import{createHash as Fu}from"node:crypto";import{constants as dr}from"node:fs";import{mkdir as Hu,open as Uu}from"node:fs/promises";import{createConnection as Vu}from"node:net";import{tmpdir as Bu}from"node:os";import{dirname as Ku,join as sn}from"node:path";var Mu="toon";function Us(e){return e.trimStart().startsWith("{")?"json":"toon"}function ir(e){let n=0;for(;e[n]===`
45
- `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=Us(t);if(r==="json"){let s=t.indexOf(`
46
- `);return s<0?null:{frame:t.slice(0,s),dialect:r,rest:t.slice(s+1)}}let o=t.indexOf(`
49
+ `;Gp(e,`${t}${r}${cf(n)}`,{encoding:"utf8",mode:384})}catch{}}function pf(e){try{return ct(e,"utf8")}catch{return""}}import{join as ff}from"node:path";var mf=[".red","redskilled"],se=448;function Oe(e){return ff(e,...mf)}import{execFileSync as jf}from"node:child_process";import{readFileSync as Df}from"node:fs";import{dirname as Ks,join as Of}from"node:path";import{existsSync as hf,readFileSync as X_}from"node:fs";import{dirname as gf,join as yf}from"node:path";function Ms(e,n){let t=e;for(let r=0;r<16;r++){let o=yf(t,n);if(hf(o))return o;let i=gf(t);if(i===t)break;t=i}return null}function kf(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function Qe(e,n){let t=[];for(let r of e.split(`
50
+ `)){let o=r.replace(/\r$/,""),i=o.trim();if(!i||i.startsWith("#"))continue;let s=o.indexOf(":");if(s<0)continue;let a=o.length-o.trimStart().length,l=o.slice(0,s).trim();if(!l)continue;let d=o.slice(s+1).trim();for(;t.length&&t[t.length-1].indent>=a;)t.pop();if(t.push({indent:a,key:l}),d&&t.map(u=>u.key).join(".")===n)return kf(d)}}import{createHash as Rf}from"node:crypto";var bf="project.name";function Hs(e){let n=Qe(e,bf)?.trim();return n===void 0||n===""?void 0:n}var _f=8,Fs="project";function Us(e){let n=Ef(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:wf(e.remoteUrl)??{name:xf(e.checkoutPath,n),source:"basename"},o=vf(n??Cr(e.checkoutPath));return{name:r.name,slug:`${Sf(r.name)}-${o}`,hash:o,source:r.source}}function Bs(e){let n=(e??"").trim();if(n==="")return;let t=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),r=/^[^/]*?:(?!\d)(.+)$/.exec(t),i=(r?r[1]:t.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(s=>s.trim()).filter(s=>s!=="");if(i.length!==0)return i.slice(-2).join("/")}function wf(e){let n=Bs(e);return n===void 0?void 0:{name:n,source:"remote"}}function xf(e,n){let t=n===void 0?"":Ws(Pf(n));if(t!=="")return t;let r=Ws(Cr(e));return r===""?Fs:r}function Sf(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?Fs:t}function vf(e){return Rf("sha256").update(e).digest("hex").slice(0,_f)}function Ef(e){let n=Cr(e??"");return n===""?void 0:n}function Cr(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function Ws(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function Pf(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var Af=2e3;function Vs(e){return Lf(e).name}function Lf(e){let n=Wr(e),t=Mr(e,["rev-parse","--absolute-git-dir"])??Mr(e,["rev-parse","--git-common-dir"]),r=Mr(e,["remote","get-url","origin"]);return Us({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function Wr(e){let n=Ms(e,Of(".red","config.yaml"));if(n==null)return{};let t;try{t=Df(n,"utf8")}catch{return{}}let r=Hs(t),o=Ks(Ks(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function Mr(e,n){try{let t=jf("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Af}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as Nd}from"node:crypto";import{spawn as $k}from"node:child_process";import{mkdir as Ik,rm as Tk}from"node:fs/promises";import{dirname as Nk}from"node:path";import{createHash as Tf}from"node:crypto";import{constants as Kr}from"node:fs";import{mkdir as Nf,open as Cf}from"node:fs/promises";import{createConnection as Mf}from"node:net";import{tmpdir as Wf}from"node:os";import{dirname as Hf,join as wn}from"node:path";var $f="toon";function Js(e){return e.trimStart().startsWith("{")?"json":"toon"}function Fr(e){let n=0;for(;e[n]===`
51
+ `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=Js(t);if(r==="json"){let i=t.indexOf(`
52
+ `);return i<0?null:{frame:t.slice(0,i),dialect:r,rest:t.slice(i+1)}}let o=t.indexOf(`
47
53
 
48
- `);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function lr(e){let n=Us(e)==="json"?sr:Fs,t=n===sr?Fs:sr;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function sr(e){return JSON.parse(e)}function Fs(e){return G(e)}function ar(e,n){if(n==="toon"){let t=Cu(e);if(t!==null)return t.endsWith(`
54
+ `);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function Ur(e){let n=Js(e)==="json"?Hr:qs,t=n===Hr?qs:Hr;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function Hr(e){return JSON.parse(e)}function qs(e){return Y(e)}function Br(e,n){if(n==="toon"){let t=If(e);if(t!==null)return t.endsWith(`
49
55
  `)?`${t}
50
56
  `:`${t}
51
57
 
52
58
  `}return`${JSON.stringify(e)}
53
- `}function Cu(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=I(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function Vs(e,n){return!Hs(e)||!Hs(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function Hs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Bs=new Set;function Ks(e){return Bs.has(e)?"json":Mu}function Js(e){Bs.add(e)}var Ju=108;async function Fn(e,n,t="resident server"){let r=e.wire,o=r??Ks(e.socketPath),s=await qs(e,n,t,o);return r||o==="json"||!Vs(n,s)?s:(Js(e.socketPath),await qs(e,n,t,"json"))}async function qs(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=Vu(e.socketPath),a=!1,d="",u=setTimeout(()=>{p(()=>i(new Error(`${t} timed out`))),l.destroy()},o);function p(m){a||(a=!0,clearTimeout(u),m())}l.on("connect",()=>{l.write(ar(n,r))}),l.on("data",m=>{d+=m.toString("utf8");let g=ir(d);g&&(d=g.rest,p(()=>{try{s(lr(g.frame))}catch(y){i(y)}}),l.end())}),l.on("error",m=>p(()=>i(m))),l.on("close",()=>{a||p(()=>i(new Error(`${t} closed without response`)))})})}function Gs(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=ir(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(ar(l,s.dialect))}catch{}};(async()=>{let l;try{l=lr(s.frame),await n(l,i)}catch(a){t(a,l,i)}finally{e.end()}})()})}async function zs(e){await Hu(Ku(e),{recursive:!0,mode:448});try{return await Uu(e,dr.O_CREAT|dr.O_EXCL|dr.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}function W(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var qu="/tmp";function Hn(e){let n=e.env??process.env,t=Fu("sha256").update(e.key).digest("hex").slice(0,20),r=a=>sn(a,e.socketFileName).length<Ju,o=n.XDG_RUNTIME_DIR;if(o){let a=sn(o,"red-skills",t);if(r(a))return a}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=sn(`red-skills-${s}`,t),l=sn(Bu(),i);return r(l)||process.platform==="win32"?l:sn(qu,i)}re();import{homedir as hp}from"node:os";import{join as yr}from"node:path";import{spawnSync as yp}from"node:child_process";import{createHash as kp}from"node:crypto";import{existsSync as Rp}from"node:fs";import{mkdir as ti,readFile as bp,writeFile as _p}from"node:fs/promises";import{dirname as wp}from"node:path";var dn="@reddb-io/red-skills",op="https://registry.npmjs.org",sp="canary",Ae=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function ip(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function Kn(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return Jn(r,ip(n,t,o))}function lp(e){return e==="dev"?["rsp"]:[]}function ap(e){return`${e}.bundle.min.mjs`}function dp(e){return Jn("dist",ap(e))}function cp(e,n="stable"){return`${dn}@${n==="canary"?sp:e}`}function up(e=dn){return`${op}/${e.replace("/","%2F")}`}async function hr(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=Kn({plugin:t,version:r,cacheDir:o,channel:s}),l=lp(t),a=l.map(m=>Kn({plugin:m,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await pp(e,a))return i;let d=cp(r,s),u=Jn(o,`.staging-${t}-${s==="canary"?"canary":r}`),p;try{p=await e.materialize(d,u)}catch(m){throw ni(m,d)}for(let m of[t,...l]){let g=dp(m),y=Jn(p,g);if(!await e.exists(y))throw new Ae("bundle-missing",`npm package ${d} has no ${g}`);let _=m===t?i:Kn({plugin:m,version:r,cacheDir:o,channel:s});await e.writeFile(_,await e.readFile(y))}return i}async function pp(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function Xs(e,n,t=dn){let r;try{r=await e.fetchText(up(t))}catch(s){throw ni(s,t)}let o=mp(r);return{sameMajor:fp(o,n),newest:gp(o)}}function mp(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 fp(e,n){let t=gr(n);if(t===null)return null;let r=null;for(let o of e)gr(o)===t&&(r===null||ei(o,r)>0)&&(r=o);return r}function gp(e){let n=null;for(let t of e){let r=String(t).trim();gr(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||ei(r,n)>0)&&(n=r)}return n}function gr(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function ei(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 ni(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Ae("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Ae("package-missing",`npm could not resolve ${n}: ${t}`,e):new Ae("network",`failed to resolve ${n}: ${t}`,e)}function Jn(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}re();var vp={async materialize(e,n){await ti(n,{recursive:!0});let t=yp("npm",["install",e,"--prefix",n,"--no-save","--no-audit","--no-fund","--ignore-scripts","--loglevel=error"],{stdio:["ignore","ignore","pipe"],encoding:"utf8"});if(t.error)throw t.error;if(t.status!==0)throw new Error(`npm install ${e} -> ${t.status}: ${(t.stderr||"").trim()}`);return yr(n,"node_modules",...dn.split("/"))},async readFile(e){return new Uint8Array(await bp(e))},async writeFile(e,n){await ti(wp(e),{recursive:!0}),await _p(e,n)},async exists(e){return Rp(e)},sha256(e){return kp("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()}},Sp="redskilled";function xp(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||yr(e.HOME||hp(),".cache");return yr(n,"red-skills","bundles")}async function Ep(e={},n={},t={}){let r=ue(e,n);if(Y(r))return r;let o=t.env??n.env??process.env;try{await hr(t.bundleIO??vp,{plugin:Sp,version:t.version??"",cacheDir:xp(o)})}catch{return r}return ue(e,n)}async function ri(e={},n={},t={}){let r=await Ep(e,n,t);if(Y(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(re(),Zs));throw new o(r)}import{randomUUID as lt}from"node:crypto";import{mkdir as lh,rm as ga}from"node:fs/promises";import{createServer as ah}from"node:net";import{dirname as dh}from"node:path";import{totalmem as Pp}from"node:os";function oi(e){let n=0,t=0,r=0,o=[],s=[];for(let i of e){let l=i.budget??{},a=!1;for(let[d,u]of[[l.memory_high,p=>n+=p],[l.memory_max,p=>t+=p]]){if(d==null)continue;let p=Ie(d);p==null?a=!0:u(p)}l.cpu_weight!=null&&(r+=l.cpu_weight),a&&o.push(i.worker_id),i.isolated||s.push(i.worker_id)}return{version:1,worker_count:e.length,memory_high_bytes:n,memory_max_bytes:t,cpu_weight_total:r,unaccounted_workers:o.sort(),unisolated_workers:s.sort()}}function Ie(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 si(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 jp="REDSKILLED_MEMORY_CEILING",Dp="REDSKILLED_WORKER_CEILING",Op=.7;function ii(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return Ie(n)}function qn(e){let n=0,t=[];for(let r of e){let o=ii(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 li(e){let{ceiling:n}=e,t=qn(e.workers),r=ii(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 ai(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=qn(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'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 di(e=process.env,n=Pp()){let t=(e[jp]??"").trim(),r=(e[Dp]??"").trim(),o=Lp(r);if(t!==""){let s=$p(t,n);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(n*Op),worker_count:o,source:r!==""?"declared":"host-fraction"}}function $p(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)):Ie(e)??void 0}function Lp(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 Ap,mkdir as Ip,open as Tp,readFile as Np,stat as Wp,truncate as ci}from"node:fs/promises";import{dirname as Mp}from"node:path";var ui="redskilled.events.toonl";function Cp(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 Fp="daemon:";function Hp(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${Fp}${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 pi(e){let n=te({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await Ip(Mp(e),{recursive:!0,mode:448}),await Up(e),await Ap(e,n.push(Jp(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(Cp(o)),recordDaemonStop:o=>r(Hp(o)),read:()=>Vp(e),flush:async()=>{await t}}}async function Up(e){let n;try{n=(await Wp(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await Tp(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 ci(e,s-i+a+1);return}}await ci(e,0)}finally{await r.close()}}async function Vp(e){let n;try{n=await Np(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return Bp(n)}function Bp(e){let n=e.split(`
54
- `);return n.pop(),n.length===0?[]:de(`${n.join(`
59
+ `}function If(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=M(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function Qs(e,n){return!Gs(e)||!Gs(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function Gs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zs=new Set;function Ys(e){return zs.has(e)?"json":$f}function Xs(e){zs.add(e)}var Ff=108;async function ut(e,n,t="resident server"){let r=e.wire,o=r??Ys(e.socketPath),i=await Zs(e,n,t,o);return r||o==="json"||!Qs(n,i)?i:(Xs(e.socketPath),await Zs(e,n,t,"json"))}async function Zs(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((i,s)=>{let a=Mf(e.socketPath),l=!1,d="",p=setTimeout(()=>{u(()=>s(new Error(`${t} timed out`))),a.destroy()},o);function u(f){l||(l=!0,clearTimeout(p),f())}a.on("connect",()=>{a.write(Br(n,r))}),a.on("data",f=>{d+=f.toString("utf8");let m=Fr(d);m&&(d=m.rest,u(()=>{try{i(Ur(m.frame))}catch(h){s(h)}}),a.end())}),a.on("error",f=>u(()=>s(f))),a.on("close",()=>{l||u(()=>s(new Error(`${t} closed without response`)))})})}function el(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let i=Fr(r);if(!i)return;r=i.rest,e.pause();let s=a=>{if(!(e.destroyed||!e.writable))try{e.write(Br(a,i.dialect))}catch{}};(async()=>{let a;try{a=Ur(i.frame),await n(a,s)}catch(l){t(l,a,s)}finally{e.end()}})()})}async function nl(e){await Nf(Hf(e),{recursive:!0,mode:448});try{return await Cf(e,Kr.O_CREAT|Kr.O_EXCL|Kr.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}function U(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var Uf="/tmp";function pt(e){let n=e.env??process.env,t=Tf("sha256").update(e.key).digest("hex").slice(0,20),r=l=>wn(l,e.socketFileName).length<Ff,o=n.XDG_RUNTIME_DIR;if(o){let l=wn(o,"red-skills",t);if(r(l))return l}let i=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),s=wn(`red-skills-${i}`,t),a=wn(Wf(),s);return r(a)||process.platform==="win32"?a:wn(Uf,s)}fe();import{homedir as um}from"node:os";import{join as Xr}from"node:path";import{spawnSync as pm}from"node:child_process";import{createHash as fm}from"node:crypto";import{existsSync as mm}from"node:fs";import{mkdir as al,readFile as hm,writeFile as gm}from"node:fs/promises";import{dirname as ym}from"node:path";var Le="@reddb-io/red-skills",Zf="https://registry.npmjs.org",em="canary",ze=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function nm(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function gt(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return yt(r,nm(n,t,o))}function tm(e){return e==="dev"?["rsp","redskilled"]:[]}function rm(e){return`${e}.bundle.min.mjs`}function om(e){return yt("dist",rm(e))}function im(e,n="stable"){return`${Le}@${n==="canary"?em:e}`}function sm(e=Le){return`${Zf}/${e.replace("/","%2F")}`}async function Yr(e,n){let{plugin:t,version:r,cacheDir:o,channel:i="stable"}=n,s=gt({plugin:t,version:r,cacheDir:o,channel:i}),a=tm(t),l=a.map(f=>gt({plugin:f,version:r,cacheDir:o,channel:i}));if(i!=="canary"&&await e.exists(s)&&await lm(e,l))return s;let d=im(r,i),p=yt(o,`.staging-${t}-${i==="canary"?"canary":r}`),u;try{u=await e.materialize(d,p)}catch(f){throw ll(f,d)}for(let f of[t,...a]){let m=om(f),h=yt(u,m);if(!await e.exists(h))throw new ze("bundle-missing",`npm package ${d} has no ${m}`);let b=f===t?s:gt({plugin:f,version:r,cacheDir:o,channel:i});await e.writeFile(b,await e.readFile(h))}return s}async function lm(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function il(e,n,t=Le){let r;try{r=await e.fetchText(sm(t))}catch(i){throw ll(i,t)}let o=am(r);return{sameMajor:dm(o,n),newest:cm(o)}}function am(e){let n;try{n=JSON.parse(e)}catch{return[]}if(typeof n!="object"||n===null)return[];let t=n.versions;return typeof t!="object"||t===null?[]:Object.keys(t)}function dm(e,n){let t=zr(n);if(t===null)return null;let r=null;for(let o of e)zr(o)===t&&(r===null||sl(o,r)>0)&&(r=o);return r}function cm(e){let n=null;for(let t of e){let r=String(t).trim();zr(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||sl(r,n)>0)&&(n=r)}return n}function zr(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function sl(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n.trim());return!t||!r?0:Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function ll(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new ze("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new ze("package-missing",`npm could not resolve ${n}: ${t}`,e):new ze("network",`failed to resolve ${n}: ${t}`,e)}function yt(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}fe();var km={async materialize(e,n){await al(n,{recursive:!0});let t=pm("npm",["install",e,"--prefix",n,"--no-save","--no-audit","--no-fund","--ignore-scripts","--loglevel=error"],{stdio:["ignore","ignore","pipe"],encoding:"utf8"});if(t.error)throw t.error;if(t.status!==0)throw new Error(`npm install ${e} -> ${t.status}: ${(t.stderr||"").trim()}`);return Xr(n,"node_modules",...Le.split("/"))},async readFile(e){return new Uint8Array(await hm(e))},async writeFile(e,n){await al(ym(e),{recursive:!0}),await gm(e,n)},async exists(e){return mm(e)},sha256(e){return fm("sha256").update(e).digest("hex")},async fetchText(e){let n=await fetch(e,{redirect:"follow"});if(!n.ok)throw new Error(`GET ${e} -> ${n.status}`);return await n.text()}},Rm="redskilled";function bm(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Xr(e.HOME||um(),".cache");return Xr(n,"red-skills","bundles")}async function _m(e={},n={},t={}){let r=Re(e,n);if(ae(r))return r;let o=t.env??n.env??process.env;try{await Yr(t.bundleIO??km,{plugin:Rm,version:t.version??"",cacheDir:bm(o)})}catch{return r}return Re(e,n)}async function dl(e={},n={},t={}){let r=await _m(e,n,t);if(ae(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(fe(),ol));throw new o(r)}import{randomUUID as Tn}from"node:crypto";import{mkdir as _k,rm as Ld}from"node:fs/promises";import{createServer as wk}from"node:net";import{dirname as xk}from"node:path";import{totalmem as xm}from"node:os";function vn(e){if(e.applied_budget!=null)return e.applied_budget;let n=e.budget??{};return n.memory_max==null&&n.memory_high==null&&e.memory_ceiling!=null?{...n,memory_max:e.memory_ceiling}:n}function cl(e,n={}){let t=0,r=0,o=0,i=[],s=[];for(let d of e){let p=vn(d),u=!1;for(let[f,m]of[[p.memory_high,h=>t+=h],[p.memory_max,h=>r+=h]]){if(f==null)continue;let h=Ye(f);h==null?u=!0:m(h)}p.cpu_weight!=null&&(o+=p.cpu_weight),u&&i.push(d.worker_id),d.isolated||s.push(d.worker_id)}let a=n.hostCeilingBytes??null,l=a==null?0:Math.max(0,r-a);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:r,cpu_weight_total:o,unaccounted_workers:i.sort(),unisolated_workers:s.sort(),memory_ceiling_bytes:a,over_committed_bytes:l,over_commitment_reason:l===0?null:wm(e.length,r,a,l)}}function wm(e,n,t,r){return`this host's ${e} Worker(s) carry ${n} bytes of applied MemoryMax against a host ceiling of ${t} bytes \u2014 ${r} bytes over. A per-Worker MemoryMax is a wall rather than a reservation, so the host stays safe only while the Workers do not all peak together; the ceiling is not enforced host-wide.`}function Ye(e){let n=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!n)return null;let t={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[n[2].toLowerCase()];return Math.round(Number(n[1])*t)}function ul(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&Number.isInteger(n.worker_count)&&typeof n.memory_high_bytes=="number"&&typeof n.memory_max_bytes=="number"&&typeof n.cpu_weight_total=="number"&&Array.isArray(n.unaccounted_workers)&&Array.isArray(n.unisolated_workers)}var Sm="REDSKILLED_MEMORY_CEILING",pl="REDSKILLED_WORKER_CEILING",vm=.7;function fl(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return Ye(n)}function kt(e){let n=0,t=[];for(let r of e){let o=fl(r.budget);o===null?t.push(r.worker_id):o!==void 0&&(n+=o)}return{worker_count:e.length,memory_bytes:n,unaccounted_workers:t.sort()}}function ml(e){let{ceiling:n}=e,t=kt(e.workers),r=fl(e.budget),o=r===void 0?null:r,i=t.memory_bytes+(r??0),s=t.worker_count+1,a=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",l=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,d=(p,u)=>({version:1,admitted:!1,verdict:p,reason:u,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:s,projected_memory_bytes:i});return n.worker_count!=null&&s>n.worker_count?d("refused-over-worker-ceiling",`redskilled refused this Worker${a}: it would be Worker ${s} past a host ceiling of ${n.worker_count} Worker(s), and ${l}`):n.memory_bytes!=null&&r===null?d("refused-unaccountable-budget",`redskilled refused this Worker${a}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${n.memory_bytes} bytes, and ${l}`):n.memory_bytes!=null&&i>n.memory_bytes?d("refused-over-memory-ceiling",`redskilled refused this Worker${a}: it would take the host to ${i} bytes of declared Worker memory, past the host ceiling of ${n.memory_bytes} bytes, and ${l}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${a}: ${i} bytes of declared Worker memory against a host ceiling of ${n.memory_bytes??"unbounded"} bytes, and ${l}`,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:s,projected_memory_bytes:i}}function hl(e){let n=e.budget?.memory_max??e.budget?.memory_high;if(n!=null)return{memory_max:n,reason:`the client declared this Worker's memory ceiling (${n}), so the host derived none`};if(e.ceiling.memory_bytes==null)return{memory_max:null,reason:"this host admits Workers against no memory ceiling, so there is no accounting to derive a per-Worker ceiling from; the daemon's RSS sampling floor is the only remaining ceiling"};let t=kt(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,i=o==null?r:Math.floor(e.ceiling.memory_bytes/o),s=Math.min(r,i);if(s<=0)return{memory_max:null,reason:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes is already fully committed to ${t.worker_count} Worker(s), so no positive per-Worker ceiling can be derived; the daemon's RSS sampling floor is the only remaining ceiling`};let a=o==null?`the headroom under this host's memory ceiling of ${e.ceiling.memory_bytes} bytes; this host declares no Worker slot count (${pl} is unset), so this ceiling is a per-Worker wall and not memory the host sets aside \u2014 N Workers may carry N such walls, and the host ceiling is not enforced host-wide. Declare a slot count to make it divide into shares that sum to it`:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes shared across its ${o} Worker slot(s)`;return{memory_max:String(s),reason:`derived from ${a} (ceiling source: ${e.ceiling.source})`}}function gl(e=process.env,n=xm()){let t=(e[Sm]??"").trim(),r=(e[pl]??"").trim(),o=Pm(r);if(t!==""){let i=Em(t,n);if(i!==void 0)return{memory_bytes:i,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(n*vm),worker_count:o,source:r!==""?"declared":"host-fraction"}}function Em(e,n){let t=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(t))return null;let r=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return r?Math.floor(n*(Number(r[1])/100)):Ye(e)??void 0}function Pm(e){if(e===""||["infinity","none","off","unbounded"].includes(e.toLowerCase()))return null;let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:null}import{appendFile as jm,mkdir as Dm,open as Om,readFile as Am,stat as Lm,truncate as yl}from"node:fs/promises";import{dirname as $m}from"node:path";var kl="redskilled.events.toonl";function Im(e){let n=e.worker.budget??{};return{version:1,ts:e.ts,event:e.event,worker_id:e.worker.worker_id,project_label:e.worker.project_label,pid:e.worker.pid,workspace_path:e.worker.workspace_path,log_path:e.worker.log_path??null,isolated:e.worker.isolated,unit:e.worker.unit??null,memory_high:n.memory_high??null,memory_max:n.memory_max??null,cpu_weight:n.cpu_weight??null,detail:e.detail??null,exit_code:e.exitCode??null,signal:e.signal??null,reason:e.reason??null}}var Tm="daemon:";function Nm(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${Tm}${e.pid}`,project_label:"",pid:e.pid,workspace_path:e.socketPath,log_path:null,isolated:!1,unit:null,memory_high:null,memory_max:null,cpu_weight:null,detail:e.detail,exit_code:null,signal:e.signal??null,reason:e.reason}}function Rl(e){let n=pe({trailer:!1}),t=Promise.resolve();async function r(o){let i=t.then(async()=>{await Dm($m(e),{recursive:!0,mode:448}),await Cm(e),await jm(e,n.push(Fm(o)),{encoding:"utf8",mode:384})});return t=i.catch(()=>{}),await i,o}return{path:e,record:o=>r(Im(o)),recordDaemonStop:o=>r(Nm(o)),read:()=>Mm(e),flush:async()=>{await t}}}async function Cm(e){let n;try{n=(await Lm(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await Om(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let i=n;i>0;i-=t){let s=Math.min(t,i),a=Buffer.alloc(s);await r.read(a,0,s,i-s);let l=a.lastIndexOf(10);if(l>=0){await yl(e,i-s+l+1);return}}await yl(e,0)}finally{await r.close()}}async function Mm(e){let n;try{n=await Am(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return Wm(n)}function Wm(e){let n=e.split(`
60
+ `);return n.pop(),n.length===0?[]:ye(`${n.join(`
55
61
  `)}
56
- `).filter(qp).map(Gp)}function mi(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,Kp(t)):n.delete(t.worker_id));return[...n.values()]}function Kp(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 Jp(e){return{...e}}function qp(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 Gp(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:oe(e.project_label)??"",pid:Number(e.pid??0),workspace_path:oe(e.workspace_path)??"",log_path:oe(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:oe(e.unit),memory_high:oe(e.memory_high),memory_max:oe(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:oe(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:oe(e.signal),reason:oe(e.reason)}}function oe(e){return e==null||e===""?null:String(e)}function fi(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}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 p=Math.max(0,Math.min(Math.max(0,i.target),d)-l);if(p===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:p,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 ${p} more`});for(let m=0;m<p;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 gi(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function yi(e){let n=e.workers.map(zp),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:Yp({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function ki(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 zp(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 Qp(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 Yp(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Qp(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${hi(e.held,"Worker")} across ${hi(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 hi(e,n){return`${e} ${n}${e===1?"":"s"}`}function kr(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 Zp,mkdir as Xp,readFile as em,rm as nm,writeFile as tm}from"node:fs/promises";import{dirname as Ri,join as vi}from"node:path";import{tmpdir as bi}from"node:os";var rm="redskilled.machine.claim.toon",om="REDSKILLED_MACHINE_DIR",sm=8,pe=class extends Error{constructor(t,r,o){super(lm(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},_i;function Si(){return _i??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},_i}function im(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[om]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||bi():bi();return vi(o,`redskilled-${e.machineIdHash}`)}function Gn(e){return vi(im(e),rm)}function zn(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??W;async function s(){let a;try{a=await em(e,"utf8")}catch(u){if(u.code==="ENOENT"||Rr(u))return;throw u}let d=dm(a);return cm(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 nm(e,{force:!0}),!0}catch(a){if(Rr(a))return!1;throw a}}return{claimPath:e,read:s,async claim(a){await Xp(Ri(e),{recursive:!0,mode:1023})!=null&&await Zp(Ri(e),1023).catch(()=>{});let u=!1;for(let p=0;p<sm;p+=1){let m=i(a,r());try{return await tm(e,am(m),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:u,claim:m}}catch(y){if(y.code!=="EEXIST"){if(Rr(y))return{claimed:!1,reason:"stale-claim-not-reapable"};throw y}}let g=await s();if(!g){if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable"};u=!0;continue}if(wi(g,a,n.socketPath))return{claimed:!0,reaped:u,claim:g};if(await o(g.pid))return{claimed:!1,reason:"held",claim:g};if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable",claim:g};u=!0}return{claimed:!1,reason:"contended"}},async release(a){let d=await s();return!d||!wi(d,a,n.socketPath)?!1:await l()}}}function xi(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 Ei(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 lm(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 Rr(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function wi(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function am(e){return`${I(e,{keyedMapCollapse:!0})}
57
- `}function dm(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return G(n)}catch{return null}}}function cm(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}function br(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 _r(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 um=3e5,pm=.5,vr=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 Pi(e,n){if(n.held!=null)throw new vr(n.held);let t=wr(e.project_label,"a project label"),r=wr(e.selector,"a selector"),o=br(e.argv,t),s=_r(e.env,t),i=wr(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.target)}`);let l=e.renew_within_ms??um;if(!Number.isFinite(l)||l<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let a=Date.parse(n.now);if(!Number.isFinite(a))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:i,env:s,target:e.target,registered_at:new Date(a).toISOString(),renew_within_ms:l,renew_by:new Date(a+l).toISOString(),renewed_at:new Date(a).toISOString(),renewals:0,launch_revision:0}}var Qn=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 ji(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:br(n.launch.argv,e.project_label),env:_r(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1};return{...e,...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1}}function Di(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 mm(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function Oi(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*pm;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 $i(e,n){let t=[],r=[];for(let o of e)(mm(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function Sr(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||fm(n.env))&&(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 fm(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function wr(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var gm={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 Li(e){return`worker-${e}`}function Ai(e){let n=gm[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 Mi(e){return{generated_at:e.now,hour:Ii("hour",36e5,e),day:Ii("day",864e5,e)}}function Yn(e,n,t){let r=cn(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(l=>{let a=cn(n(l));return a==null?!1:r==null||r-a<=o});return i.length<=s?i:i.slice(i.length-s)}function Ii(e,n,t){let r=cn(t.now),o=r==null?null:r-n,s=e==="hour"?"1h":"24h",i=t.observations.map(p=>({observation:p,at:cn(p.observed_at)})).filter(p=>p.at!=null&&Wi(p.at,o,r)).sort((p,m)=>p.at-m.at),l=t.outcomes.map(p=>cn(p.ts)).filter(p=>p!=null&&Wi(p,o,r)),a=Ti(i,p=>p.tokens,"tokens",s),d=Ti(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:hm(l.length,n,s),runner_share:Ni("runner",i,p=>p.runner,s),model_share:Ni("model",i,p=>p.model,s),unavailable:u}}function Ti(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 m=1;m<d.length;m++){let g=d[m-1],y=d[m];g==null||y==null||(i+=Math.max(0,y.count-g.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 hm(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 Ni(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 Wi(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function cn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}import{execFileSync as ym}from"node:child_process";import{readFileSync as km,readdirSync as Rm}from"node:fs";import{join as bm}from"node:path";function un(e){let n=e.budget??{},t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high],["MemoryMax",e.memory_ceiling]];for(let[r,o]of t){if(o==null)continue;let s=Ie(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function Ci(e){let n=[],t=[];for(let r of e.workers){let o=un(r);if(o==null){t.push({worker_id:r.worker_id,reason:(r.budget?.memory_max??r.budget?.memory_high??r.memory_ceiling)==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}s<=o.bytes||n.push(_m(r,o,s))}return{terminations:n,unenforceable:t}}function _m(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 wm=4096;function Fi(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{}};if(e.length===0)return r;let o=vm(t,n);if(o.size===0)return r;let s=new Map;for(let a of o.values()){let d=s.get(a.ppid);d?d.push(a.pid):s.set(a.ppid,[a.pid])}let i={},l={};for(let a of e){if(!o.has(a.pid))continue;let d=0,u=0,p=[a.pid],m=new Set;for(;p.length>0;){let g=p.pop();if(m.has(g))continue;m.add(g);let y=o.get(g);if(y){d+=y.rssBytes,u+=y.cpuSeconds;for(let _ of s.get(g)??[])p.push(_)}}i[a.worker_id]=d,l[a.worker_id]=u}return{rss:i,cpu_seconds:l}}function vm(e,n){return n.procRoot!=null||e==="linux"?Dm(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?Pm(Sm(n.psTable)):new Map}function Sm(e){try{return(e??xm)()}catch{return""}}function xm(){return ym("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Em=1024;function Pm(e){let n=new Map;for(let t of e.split(`
58
- `)){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=jm(r[3]);l!=null&&n.set(o,{pid:o,ppid:s,rssBytes:i*Em,cpuSeconds:l})}return n}function jm(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 Dm(e){let n=new Map,t;try{t=Rm(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=km(bm(e,r,"stat"),"utf8")}catch{continue}let s=$m(o);s&&n.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*wm,cpuSeconds:s.cpuTicks/Om})}return n}var Om=100;function $m(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 xr=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 Pr(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new xr(t.project_label,t.token_ref,n)}function Lm(e,n={now:new Date(0).toISOString()}){Tm(e);let t=n.closedWindowMs??6048e5,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 { remaining resetAt }",...s.flatMap(({alias:a,search_alias:d,project:u})=>{let p=JSON.stringify(u.owner),m=JSON.stringify(u.name),g=JSON.stringify(`repo:${u.owner}/${u.name} is:closed closed:>=${o}`);return[` ${a}: repository(owner: ${p}, name: ${m}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${d}: search(query: ${g}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
59
- `),aliases:s,closed_since:o}}function Am(e,n,t){let r=Te(n),o=Te(r.data),s=Array.isArray(r.errors)?r.errors.map(Te):[],i=Nm(o.rateLimit,s),l=e.aliases.map(({alias:a,search_alias:d,project:u})=>{let p=u.owner+"/"+u.name,m=o[a],g=s.find(y=>Hi(y.path,a)||Hi(y.path,d));if(qi(m)){let y=Ui(m.open_pull_requests),_=Ui(m.open_issues),k=Wm(o[d]);if(y!=null&&_!=null&&k!=null)return{project_label:u.project_label,repository:p,outcome:"counted",counts:{open_pull_requests:y,open_issues:_,recently_closed:k},detail:`counted ${p} for project ${JSON.stringify(u.project_label)}`}}return i.exhausted||Ji(g)?{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: ${Er(g?.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 Im(e){return{version:1,fetched_at:e,request_count:0,project_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}async function Vi(e){if(e.projects.length===0)return Im(e.now);Pr(e.projects,e.hostTokenRef);let n=Lm(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return Am(n,t,{fetchedAt:e.now})}catch(t){let r=t instanceof Error?t.message:String(t),o=/rate limit|secondary rate|429/i.test(r);return{version:1,fetched_at:e.now,request_count:1,project_count:e.projects.length,rate_limit:{remaining:null,reset_at:null,exhausted:o},projects:e.projects.map(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 Bi(e){let n=e.stalenessMs??12e4,t=e.activity;if(t==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:n,stale:!1,request_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[],reason:"the daemon polls no repository, so there are no counts to age"};let r=Date.parse(e.now),o=Date.parse(t.fetched_at),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 Ki(e){let n=e.endpoint??"https://api.github.com/graphql",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 Tm(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>100)throw new Error("redskilled activity fetch spans at most 100 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 Nm(e,n){let t=Te(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(Ji);return{remaining:r,reset_at:o,exhausted:s||r===0}}function Ji(e){if(e==null)return!1;let n=Er(e.type),t=Er(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function Hi(e,n){return Array.isArray(e)&&e.includes(n)}function Ui(e){let n=Te(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function Wm(e){let n=Te(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Te(e){return qi(e)?e:{}}function qi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Er(e){return typeof e=="string"?e:""}var Mm=3e4,Cm=4;function Gi(e){let n=e.stalenessMs??Mm,t=pn(e.now),r=e.sampledAt==null?null:pn(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(m=>Um(m,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[m.worker_id],display:e.displays?.[m.worker_id],state:i.has(m.worker_id)?"reattached":"running"})),a=l.filter(m=>m.vitals.rss_bytes==null).map(m=>m.worker_id).sort(),d=l.length-a.length,u=l.reduce((m,g)=>m+(g.vitals.rss_bytes??0),0),p=qn(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:Jm({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:Km(l),known_projects:Bm(e.hostState),registered_projects:(e.hostState.registrations??[]).map(m=>m.project_label).sort((m,g)=>m.localeCompare(g)),workers:l,repository_activity:Bi({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:Fm(e.deaths,e.recentDeathLimit??Cm)},engine:Hm(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function Fm(e,n){let t=[...e].sort((o,s)=>(pn(s.ts)??0)-(pn(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 Hm(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 Um(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=un(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=pn(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},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:Vm(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function Vm(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 Bm(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 Km(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 Jm(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 pn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}var O={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function zi(e,n=O){let t=Xm(e,n),r=Ym(e,n),o=Zm(e,n),s=ef(e,n,r,t),i=zm(n,r,o),l={detail:"host",line:s};for(let p of i){let m=uf(s,Qm(p,n,r,o),n.separator);if(l={detail:p,line:m},pf(m)<=n.maxWidth)break}let a=$r(l.line,n.maxWidth),d=n.verbose&&l.detail==="workers"?lf(r,n):[],u=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!==u||a!==l.line,stale:e.staleness.stale,generated_at:e.generated_at}}function Qi(e){let n=e.options??O,t=$r(Gm,n.maxWidth);return{version:1,line:t,lines:[t],verbose:n.verbose,mode:n.mode,project:n.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}var qm="!unregistered",Dr="\u21E1",Zn="\u2020",Gm="redskilled unreachable \u2014 Worker state unknown";function zm(e,n,t){let r=[];return n.length>0&&n.length<=e.maxWorkers&&r.push("workers"),e.mode==="global"&&t.length>0&&t.length<=e.maxProjects&&r.push("projects"),r.push("host"),r}function Qm(e,n,t,r){return e==="workers"?t.map(o=>sf(o,n)):e==="projects"?r.map(cf):[]}function Ym(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Zm(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function Xm(e,n){return Or(e,n.project)}function Or(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 ef(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(jr(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(jr(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(jr(e,n)),o.push(qm)):o.push(rf(n.project,r)),o.push(nf(e));let s=tf(e);return s!=null&&o.push(s),e.staleness.stale&&o.push(of(e)),o.join(" ")}function nf(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${Dr}`}function tf(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Zn}${n.count} ${n.latest.sender_class}`}function rf(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 jr(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?`${H(t)}/${H(r)}`:H(t)}function of(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function sf(e,n){let t=Yi(e,n),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?H(r):`${H(r)}/${H(e.budget.bytes)}`;return`${t} ${o}`}function lf(e,n){let t=[];for(let r of e){let o=df(r.log.last_line);o!=null&&t.push($r(` ${af} ${Yi(r,n)}: ${o}`,n.maxWidth))}return t}var af="\u21B3";function df(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}function Yi(e,n){return n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function cf(e){return`${e.project_label} ${e.worker_count}w ${H(e.observed_rss_bytes)}`}function uf(e,n,t){return[e,...n].join(t)}function pf(e){return[...e].length}function $r(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}function H(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}var Lr={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},mf=["runner","model","effort","origin","issue","phase","step","heartbeat"],ff=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function Zi(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...Lr};for(let r of mf){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of ff){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}var Xn=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],Ne={mode:"local",project:null,maxWidth:200,maxRows:16};var gf=" ",Xi="\u2588",hf="\u25B6",yf="\u2717",kf="\u2591";function el(e,n=Ne){let t=Or(e,n.project),r=Rf(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(p=>bf(p,n)),i=Df(s),l=o.map((p,m)=>({worker_id:p.worker_id,project_label:p.project_label,mine:n.project!=null&&p.project_label===n.project,cells:s[m],line:mn(Of(s[m],i),n.maxWidth)})),a=wf(e,n,r,t),d=r.length-o.length,u=[a.line,...l.map(p=>p.line)];return d>0&&u.push(mn(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),u.push(...Sf(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Xn,header:a,rows:l,lines:u,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Rf(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function bf(e,n){let t=e.display??Lr,r=[t.runner,t.model,t.effort].filter(o=>!!o).join(" ");return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:r===""?"":`run=${r}`,org:t.origin==null?"":`org=${t.origin}`,iss:t.issue==null?"":`iss=${t.issue}`,bar:_f(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:jf(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:Pf(t.added,t.removed),tks:t.tokens==null?"":`tks=${nl(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function _f(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 Xi.repeat(Math.floor(n));let o=e.failed?yf:hf;return`${Xi.repeat(r)}${o}${kf.repeat(Math.floor(n)-r-1)}`}function wf(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(b=>b.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=Ef(t),a=o?.repository??n.project,d=e.engine??null,u=d?.running_version??e.daemon.daemon_version,p=e.deaths??null,m=e.metrics??null,g=[`\xBB ${a??"host"} v${u}${d!=null&&d.current===!1?Dr:""}`];r==="unregistered"&&g.push("!unregistered"),r==="name-only"&&g.push("!lapsed"),l!=null&&g.push(l),g.push(`wrk=${t.length}/${e.host.worker_count}`),g.push(i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`),g.push(xf(i)),s.open_pull_requests!=null&&g.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&g.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&g.push(`iss=${s.open_issues}`),s.stale&&g.push("!counts stale");let y=m==null?null:vf(m.hour);if(y!=null&&g.push(y),p!=null&&p.count>0&&p.latest!=null&&g.push(`${Zn}${p.count} ${p.latest.sender_class}`),e.staleness.stale){let b=e.staleness.age_ms;g.push(b==null?"!unmeasured":`!stale ${Math.round(b/1e3)}s`)}let _=g.join(" \xB7 "),k=y!=null&&Ir(_)>n.maxWidth?g.filter(b=>b!==y).join(" \xB7 "):_;return{repo:a,project:n.project,project_match:r,version:u,engine:d,deaths:p,metrics:m,model:l,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:mn(k,n.maxWidth)}}function vf(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${Ar(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${Ar(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${Ar(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 Sf(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(s=>mn(`${Zn} ${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(mn(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function xf(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${H(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${H(e.memory_used_bytes)}/${H(e.memory_ceiling_bytes)}${n}`}function Ef(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 Pf(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 nl(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 Ar(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return nl(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 jf(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 Df(e){let n=Object.fromEntries(Xn.map(t=>[t,0]));for(let t of e)for(let r of Xn)n[r]=Math.max(n[r],Ir(t[r]));return n}function Of(e,n){return Xn.filter(r=>n[r]>0).map(r=>$f(e[r],n[r])).join(gf).replace(/\s+$/,"")}function $f(e,n){return e+" ".repeat(Math.max(0,n-Ir(e)))}function Ir(e){return[...e].length}function mn(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}var et=1;async function fn(e,n){return await Fn(e,n,"redskilled daemon")}function tl(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.line=="string"&&Array.isArray(n.lines)&&n.lines.every(t=>typeof t=="string")&&typeof n.verbose=="boolean"&&(n.mode==="local"||n.mode==="global")&&(n.project===null||typeof n.project=="string")&&typeof n.detail=="string"&&(n.project_match===void 0||typeof n.project_match=="string")&&typeof n.degraded=="boolean"&&typeof n.stale=="boolean"&&typeof n.generated_at=="string"}function rl(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:et,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:If(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:oi(n),upgrade:Tf(e)}}function If(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:Oi(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 Tf(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 ol(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)&&si(n.budget_accounting)&&(n.scope===void 0||Ei(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(Sr))&&(n.upgrade===void 0||Nf(n.upgrade))}function Nf(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||Wf(n.major_hold))}function Wf(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 rt}from"node:child_process";import{existsSync as Cr}from"node:fs";import{delimiter as Jf,join as fl}from"node:path";import{join as sl}from"node:path";import{existsSync as Mf}from"node:fs";import{createRequire as Cf}from"node:module";var il="redskilled-job-object.node",we=100;function We(e){return{available:!1,reason:e}}function Ff(e,n,t){return[sl(t,"prebuilds",`${e}-${n}`,il),sl(t,"native","build","Release",il)]}function ll(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return We(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??Uf(),o=e.exists??Mf,s=Ff(n,t,r),i=s.find(d=>o(d));if(i==null)return We(`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??Cf(import.meta.url),a;try{a=l(i)}catch(d){return We(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return Hf(a)?{available:!0,binding:a}:We(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function Hf(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Uf(){return new URL("..",import.meta.url).pathname}function al(e){let n=e??{},t=[],r=Vf(n);r==null&&(n.memory_max??n.memory_high)!=null&&t.push("the declared memory budget could not be reduced to bytes, so the job carries no memory ceiling");let o;return n.cpu_weight!=null&&(n.cpu_weight<we?o=Math.max(1,Math.min(100,Math.round(n.cpu_weight))):t.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${we}, and Windows CPU rate control is an absolute cap rather than a share, so no rate limit is set`)),{...r!=null?{memory_limit_bytes:r.bytes,memory_budget_name:r.name,memory_budget_declared:r.declared}:{},...o!=null?{cpu_rate_percent:o}:{},kill_on_close:!0,...t.length>0?{note:t.join("; ")}:{}}}function Vf(e){return un({budget:e})}var nt=5,dl=19;function Tr(e){return{available:!1,reason:e}}var Bf="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 ul(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=nt;else if(t.cpu_weight<we){let l=Math.round(dl*(we-t.cpu_weight)/we);o=Math.min(dl,Math.max(nt,l))}else o=nt,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${we}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${nt}`);let s=cl(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=cl(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:Bf,...r.length>0?{note:r.join("; ")}:{}}}function pl(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 ${Kf(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
60
- `),e.command,...e.args]}function ml(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 Nr(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 cl(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function Kf(e){return`'${e.replace(/'/g,"'\\''")}'`}var gl="REDSKILLED_PLACEMENT",tt="red-worker",Wr="/bin/sh";function hl(e=process.env,n=process.platform){let t=Tr(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:ll({platform:n}),posix:t};let r=We(`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:qf(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Cr(fl(o,"systemd","private"));return{platform:n,systemdRun:bl("systemd-run",e),userSession:s,jobObjects:r,posix:t}}function qf(e){return Cr(Wr)?{available:!0,shell:Wr,nice:bl("nice",e)}:Tr(`no POSIX shell was found at ${Wr}, so there is nothing to apply rlimits or priority in`)}function yl(e=process.env){let n=(e[gl]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Gf(e,n,t=tt){return kl(e,n,t).replace(/\.service$/,"")}function kl(e,n,t=tt){return`${Mr(t,"red-worker",24)}-${Mr(e,"project",32)}-${Mr(n,"worker",32)}.service`}function Rl(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,...r!=null?{memoryCeiling:r}:{},environment:tn({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 ${gl}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return Qf(e,n,t,r,o,i);if(e.probes.platform==="darwin")return zf(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=kl(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=tn({scope:l,memory_ceiling:r,scope_degradation:null});for(let[p,m]of Object.entries({...e.env??{},...d}))a.push(`--setenv=${p}=${m}`);let u=Nr(e.budget);return{isolated:!0,backend:"transient-unit",unit:l,command:e.probes.systemdRun,args:[...a,"--",e.command,...n],...r!=null?{memoryCeiling:r}:{},environment:d,...u!=null?{budgetWarning:u}:{}}}function zf(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=ul(t,{canRenice:s.nice!=null}),l=t.memory_high!=null||t.memory_max!=null,a=ml(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:pl({limits:i,nice:s.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:i,warning:a,...r!=null?{memoryCeiling:r}:{},environment:tn({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 Qf(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=al(t),a=Gf(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},...r!=null?{memoryCeiling:r}:{},environment:tn({scope:a,memory_ceiling:r,scope_degradation:null}),...Yf(o&&l.note!=null?`${l.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,Nr(e.budget))}}function Yf(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function bl(e,n){for(let t of(n.PATH??"").split(Jf)){if(!t)continue;let r=fl(t,e);if(Cr(r))return r}return null}function Mr(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function Fr(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}}function _l(e){return e.unit!=null&&e.unit!==""?Zf(e.unit):W(e.pid)}function Zf(e){let n=rt("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var Xf="REDSKILLED_UNIT_DISCOVERY",wl="(unowned)";function vl(e){let n=rt("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 eg(e=process.env){let n=(e[Xf]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Sl(e,n,t=process.env){return eg(t)&&e===n}function xl(e=tt){let n=rt("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(`
61
- `).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function El(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:wl,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 Pl(e){return e.project_label.trim()!==""?e:{...e,project_label:wl,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 jl(e){if(e.unit!=null&&e.unit!==""){let n=rt("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 ng(e,n=50){if(Ll(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 tg(e,n={}){let t=n.batchSize??50;if(Ll(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(`
62
- `),aliases:r}}function rg(e,n){let t=gn(n),r=gn(t.data),o=Array.isArray(t.errors)?t.errors.map(gn):[],s=sg(r.rateLimit,o);return{projects:e.aliases.map(({alias:l,project:a})=>{let d=lg(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=>ig(p.path,l));return s.exhausted||Al(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: ${Hr(u?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function og(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 Ol(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 $l(e){if(e.projects.length===0)return og(e.now);let n=e.batchSize??50,t=ng(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=tg(s,{batchSize:n});try{let l=await e.transport(i.query),a=rg(i,l);r.push(...a.projects),o=Dl(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=Dl(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 Ll(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 Dl(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 sg(e,n){let t=gn(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(Al)||r===0}}function Al(e){return e==null?!1:Hr(e.type)==="RATE_LIMITED"||/rate limit/i.test(Hr(e.message))}function ig(e,n){return Array.isArray(e)&&e.includes(n)}function lg(e){let n=gn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function gn(e){return ag(e)?e:{}}function ag(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hr(e){return typeof e=="string"?e:""}import{randomUUID as Nl}from"node:crypto";import{spawn as pg}from"node:child_process";import{closeSync as mg,mkdirSync as fg,openSync as gg}from"node:fs";import{dirname as hg}from"node:path";import{delimiter as Il,dirname as dg}from"node:path";function cg(e,n=Il){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function ug(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=dg(n);return t===""||t==="."?null:t}function Tl(e,n=process.execPath,t=Il){let r=cg(e,t),o=ug(n);return o==null?r.join(t):[o,...r.filter(s=>s!==o)].join(t)}var hn=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},ot=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function yg(e){if(e==null||e.trim()==="")return null;try{return fg(hg(e),{recursive:!0}),gg(e,"a")}catch{return null}}function kg(e){try{mg(e)}catch{}}function Rg(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 hn(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new hn("redskilled worker spec args must be an array")}function bg(e){if(e==null)throw new ot("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new ot(e.reason,e)}function Ml(e){let{spec:n,admission:t}=e;bg(t),Rg(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(n.worker_id??e.workerId??Nl()).trim()||Nl(),i=e.probes??hl(r),l=e.openLog===!1?null:yg(n.log_path),a={...n.env??{},PATH:Tl(n.env?.PATH??r.PATH,e.execPath??process.execPath)},d=Rl({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??yl(r),probes:i,pipeOutput:l!==null}),p=(e.spawnFn??pg)(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&&kg(l),p.pid==null)throw p.once("error",()=>{}),new hn(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${s}`);let m=d.job!=null?_g(d,i,p.pid):null;p.once("error",()=>{}),p.once("exit",(k,b)=>{try{m?.job?.close()}catch{}e.onExit?.(s,k,b)}),p.unref();let g=d.job!=null?m?.job!=null:d.isolated,y=[d.warning,m?.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:g,...d.unit!=null?{unit:d.unit}:{},...n.budget!=null?{budget:n.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:y},admission:t,warnings:y,plan:d,child:p,...m?.job!=null?{job:m.job}:{}}}function _g(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: ${Wl(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)}: ${Wl(i)}. ${o}`}}return{job:s}}function Wl(e){return e instanceof Error?e.message:String(e)}import{open as wg,stat as vg}from"node:fs/promises";var Sg=16*1024;async function Cl(e,n=Sg){let t;try{t=(await vg(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let s=await wg(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 xg(o)}function xg(e){let n=e.split(`
63
- `);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 Cg}from"node:child_process";import{existsSync as Fg,readdirSync as Hg}from"node:fs";import{dirname as Ug,join as Kl,resolve as Vg}from"node:path";function U(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 Ur(e,n){let t=U(e),r=U(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var u_=4*60*60*1e3;re();re();import{spawnSync as Eg}from"node:child_process";import{mkdir as Pg,rm as jg,writeFile as Dg}from"node:fs/promises";import{existsSync as Og}from"node:fs";import{homedir as $g}from"node:os";import{dirname as Lg,join as Vr}from"node:path";var Me="redskilled.service",Br="REDSKILLED_SUPERVISED",Ag="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function Ig(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||Vr(e.HOME?.trim()||$g(),".config");return Vr(n,"systemd","user")}function Kr(e=process.env){return Vr(Ig(e),Me)}function Fl(e,n={}){let t=n.env??process.env,r=Bn(n.override??{},n.entryLookup??{}),o=[...r.args,..._e(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:Me,unitPath:Kr(t),command:r.command,args:o,text:Tg(r.command,o,e)}}function Tg(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${Ag}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(Ng).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Br}=1"`,`Environment="REDSKILLED_SESSION=${Hl(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
64
- `)}function Ng(e){return/[\s"'\\$%]/.test(e)?`"${Hl(e)}"`:e}function Hl(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function Ul(e,n={}){let t=n.writeFile??Wg,r=n.run??Jr,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(st("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(st("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function Vl(e={}){let n=e.removeFile??Mg,t=e.run??Jr,r=Kr(e.env??process.env),o=[st("disable",t,["systemctl","--user","disable","--now",Me])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(st("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function Bl(e={}){let n=e.exists??Og,t=e.run??Jr,r=Kr(e.env??process.env),o=n(r);return{unitName:Me,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",Me]).status===0,active:o&&t(["systemctl","--user","is-active",Me]).status===0,floor:"auto-spawn"}}function st(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 Wg(e,n){await Pg(Lg(e),{recursive:!0}),await Dg(e,n,{encoding:"utf8",mode:420})}async function Mg(e){await jg(e,{force:!0})}function Jr(e){let n=Eg(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 Jl=75,Gl=9e5,ql="redskilled-replacement-entry-unresolved",Bg="REDSKILLED_NO_REGISTRY_PROBE",zl="REDSKILLED_BORN_BY_REPLACEMENT";function Ql(e=process.env){return e[zl]==="1"}function Yl(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function Zl(e){let n=e.running.trim();if(yn(n))return null;let t=e.newest?.trim()??"",r=U(t),o=U(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:Kg(r.major,e.supervised)}}function Kg(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: redskilled unit install && systemctl --user restart redskilled.service`:`${t}stop this daemon \u2014 the next client start resolves the newly installed bundle`}function Xl(e){let n=e.running.trim();if(yn(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||U(t)===null?{act:"hold",reason:"published-unknown"}:Ur(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function yn(e){let n=e.trim();return U(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function ea(e=process.env){return e[Br]==="1"}var qr=class extends Error{code=ql;searched;constructor(n,t){super(`${ql}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
62
+ `).filter(Um).map(Bm)}function bl(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,Hm(t)):n.delete(t.worker_id));return[...n.values()]}function Hm(e){let n={...e.memory_high!=null?{memory_high:e.memory_high}:{},...e.memory_max!=null?{memory_max:e.memory_max}:{},...e.cpu_weight!=null?{cpu_weight:e.cpu_weight}:{}};return{worker_id:e.worker_id,project_label:e.project_label,pid:e.pid,started_at:e.ts,workspace_path:e.workspace_path,...e.log_path!=null?{log_path:e.log_path}:{},isolated:e.isolated,...e.unit!=null?{unit:e.unit}:{},...Object.keys(n).length>0?{budget:n}:{},warnings:[]}}function Fm(e){return{...e}}function Um(e){return e.version===1&&typeof e.ts=="string"&&typeof e.worker_id=="string"&&(e.event==="worker-birth"||e.event==="worker-death"||e.event==="worker-budget-kill"||e.event==="daemon-stop")}function Bm(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:me(e.project_label)??"",pid:Number(e.pid??0),workspace_path:me(e.workspace_path)??"",log_path:me(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:me(e.unit),memory_high:me(e.memory_high),memory_max:me(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:me(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:me(e.signal),reason:me(e.reason)}}function me(e){return e==null||e===""?null:String(e)}function _l(e){let n=[...e.projects].sort((s,a)=>s.project_label.localeCompare(a.project_label)),t=e.backoffUntilMs??null,r=t!=null&&e.nowMs<t,o=[],i=[];for(let s of n){let a=Math.max(0,e.live[s.project_label]??0),l=Object.prototype.hasOwnProperty.call(e.queue,s.project_label),d=l?e.queue[s.project_label]??null:null,p={project_label:s.project_label,queue_depth:d,target:s.target,live:a};if(r){o.push({...p,outcome:"backing-off",wanted:0,detail:`the host refused a Worker, so no project is asked for one again before ${new Date(t).toISOString()}`});continue}let u=e.birthHaltUntilMs?.[s.project_label];if(u!=null&&e.nowMs<u){o.push({...p,outcome:"birth-halted",wanted:0,detail:`project ${JSON.stringify(s.project_label)} lost 3 Workers in a row inside 60000ms of birth, so it is not asked for another before ${new Date(u).toISOString()} \u2014 a Worker that cannot survive boot will not survive the next one either, and every birth spends host quota shared with every project`});continue}if(d==null){o.push({...p,outcome:"queue-unknown",wanted:0,detail:l?`the last poll produced no depth for project ${JSON.stringify(s.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(s.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...p,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(s.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,s.target),d)-a);if(f===0){o.push({...p,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(s.project_label)} holds ${a} Worker(s) against a target of ${s.target} and a queue of ${d}, so it asks for none`});continue}o.push({...p,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(s.project_label)} holds ${a} Worker(s) against a target of ${s.target} and a queue of ${d}, so it asks for ${f} more`});for(let m=0;m<f;m+=1)(i[m]??(i[m]=[])).push({project_label:s.project_label,index:a+m,argv:s.argv,workspace_path:s.workspace_path})}return{intents:o,births:i.flat()}}function wl(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}var Rt={shortLifeStreak:0,haltUntilMs:null};function xl(e,n,t){if(n>=6e4)return Rt;let r=e.shortLifeStreak+1;return r<3?{shortLifeStreak:r,haltUntilMs:null}:{shortLifeStreak:r,haltUntilMs:t+6e5}}function Sl(e,n){let t={};for(let[r,o]of Object.entries(e))o.haltUntilMs!=null&&n<o.haltUntilMs&&(t[r]=o.haltUntilMs);return t}function El(e){let n=e.workers.map(Km),t=[...new Set([...n.map(o=>o.project_label),...e.projects??[]])].filter(o=>o!=="").sort(),r=n.filter(o=>o.survives).map(o=>o.worker_id);return{version:1,running:!0,stopped:!0,reason:e.reason,socket_path:e.socketPath,daemon_version:e.daemonVersion,pid:e.pid,holding:{workers:n,projects:t},surviving:r,detail:qm({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function Pl(e){return{version:1,running:!1,stopped:!1,reason:"not-running",socket_path:e,daemon_version:null,pid:null,holding:{workers:[],projects:[]},surviving:[],detail:`no redskilled daemon is answering on ${JSON.stringify(e)}, so there was nothing to stop`}}function Km(e){return{worker_id:e.worker_id,project_label:e.project_label,pid:e.pid,unit:e.unit??null,isolated:e.isolated,survives:!0}}function Vm(e){return e==="requested"?"an operator asked for it":e==="signal"?"the daemon was signalled":e==="idle"?"the daemon was idle and held nothing":e==="replaced"?"a newer published bundle is taking the session over":"no daemon was running"}function qm(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Vm(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${vl(e.held,"Worker")} across ${vl(e.projects,"project")}, and ${e.surviving} of them survive it \u2014 a Worker is an init-system unit, so this is a restart and not an evacuation`}function vl(e,n){return`${e} ${n}${e===1?"":"s"}`}function Zr(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.holding;return n.version===1&&typeof n.running=="boolean"&&typeof n.stopped=="boolean"&&typeof n.reason=="string"&&typeof n.socket_path=="string"&&typeof n.detail=="string"&&(n.daemon_version===null||typeof n.daemon_version=="string")&&(n.pid===null||typeof n.pid=="number")&&t!=null&&Array.isArray(t.workers)&&Array.isArray(t.projects)&&Array.isArray(n.surviving)}import{chmod as Gm,mkdir as Jm,readFile as Qm,rm as zm,writeFile as Ym}from"node:fs/promises";import{dirname as jl,join as Ll}from"node:path";import{tmpdir as Dl}from"node:os";var Xm="redskilled.machine.claim.toon",Zm="REDSKILLED_MACHINE_DIR",eh=8,be=class extends Error{constructor(t,r,o){super(th(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},Ol;function $l(){return Ol??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},Ol}function nh(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[Zm]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||Dl():Dl();return Ll(o,`redskilled-${e.machineIdHash}`)}function bt(e){return Ll(nh(e),Xm)}function _t(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??U;async function i(){let l;try{l=await Qm(e,"utf8")}catch(p){if(p.code==="ENOENT"||eo(p))return;throw p}let d=oh(l);return ih(d)?d:void 0}function s(l,d){return{version:1,scope:"machine",pid:l.pid,start_time:l.startTime,uid:l.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}async function a(){try{return await zm(e,{force:!0}),!0}catch(l){if(eo(l))return!1;throw l}}return{claimPath:e,read:i,async claim(l){await Jm(jl(e),{recursive:!0,mode:1023})!=null&&await Gm(jl(e),1023).catch(()=>{});let p=!1;for(let u=0;u<eh;u+=1){let f=s(l,r());try{return await Ym(e,rh(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:p,claim:f}}catch(h){if(h.code!=="EEXIST"){if(eo(h))return{claimed:!1,reason:"stale-claim-not-reapable"};throw h}}let m=await i();if(!m){if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable"};p=!0;continue}if(Al(m,l,n.socketPath))return{claimed:!0,reaped:p,claim:m};if(await o(m.pid))return{claimed:!1,reason:"held",claim:m};if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable",claim:m};p=!0}return{claimed:!1,reason:"contended"}},async release(l){let d=await i();return!d||!Al(d,l,n.socketPath)?!1:await a()}}}function Il(e,n,t){return{kind:"machine",claim_path:e,owner_uid:t.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath}}function Tl(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.kind==="machine"&&typeof n.claim_path=="string"&&typeof n.owner_uid=="number"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&typeof n.socket_path=="string"}function th(e,n,t){let r=t==null?"":` \u2014 held by pid ${t.pid} (uid ${t.uid}) on socket ${JSON.stringify(t.socket_path)}`;return n==="held"?`this machine already has a redskilled daemon${r}; a second one would void the host budget, so none was started. Reach that daemon, or stop it before starting another.`:n==="stale-claim-not-reapable"?`the redskilled machine claim ${JSON.stringify(e)} is stale and cannot be removed by this user${r}; remove it as its owner, then start again. No second daemon was started.`:`the redskilled machine claim ${JSON.stringify(e)} changed hands repeatedly; no daemon was started.`}function eo(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function Al(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function rh(e){return`${M(e,{keyedMapCollapse:!0})}
63
+ `}function oh(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Y(n)}catch{return null}}}function ih(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||n.scope!=="machine"||!Number.isInteger(n.pid)||n.pid<=0||!Number.isInteger(n.uid))return!1;for(let t of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var sh=["worker_id","slot","workspace_path","log_path"],no=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${sh.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},lh=/\{\{([a-z_]+)\}\}/g;function ah(e,n){let t=(s,a)=>s.replace(lh,(l,d)=>{switch(d){case"worker_id":return n.worker_id;case"slot":return String(n.slot);case"workspace_path":return n.workspace_path;case"log_path":return n.log_path??"";default:throw new no(d,a)}}),r=e.argv.map((s,a)=>t(s,`argv word ${a}`)),o={};for(let[s,a]of Object.entries(e.env??{}))o[s]=t(a,`env entry ${JSON.stringify(s)}`);let i=e.log_path==null?void 0:t(e.log_path,"the log path");return{argv:r,env:o,...i==null||i===""?{}:{log_path:i}}}function Nl(e,n,t){let r=ah(e,n),o=r.log_path??n.log_path,[i,...s]=r.argv;if(i===void 0||i==="")throw new Error(`redskilled cannot start a Worker for project ${JSON.stringify(t.project_label)}: its launch expanded to an argv with no command`);return{worker_id:n.worker_id,project_label:t.project_label,workspace_path:n.workspace_path,...o==null||o===""?{}:{log_path:o},command:i,args:s,env:r.env}}function to(e,n){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(n)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((t,r)=>{if(typeof t!="string"||t==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${r} of project ${JSON.stringify(n)} is not`);return t})}function ro(e,n){if(e!=null){if(typeof e!="string"||e.trim()==="")throw new Error(`redskilled needs a declared log path to be a non-empty string to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}: a project that declares an empty path states a Worker whose output no surface can ever show, which reads as a Worker with nothing to say`);return e}}function oo(e,n){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error(`redskilled needs a launch env to be a map of strings to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}`);let t={};for(let[r,o]of Object.entries(e)){if(r==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(n)} to be named`);if(typeof o!="string")throw new Error(`redskilled needs every launch env value to be a string, and ${JSON.stringify(r)} of project ${JSON.stringify(n)} is ${JSON.stringify(o)}`);t[r]=o}return t}var dh=3e5,ch=.5,so=class extends Error{constructor(t){super(`redskilled already holds a registration for project ${JSON.stringify(t.project_label)}, registered at ${t.registered_at} for a target of ${t.target} and standing until ${t.renew_by}: a project contributes one registration, so a second one is refused rather than silently replacing the first`);this.held=t;this.name="RedskilledProjectRegisteredError"}};function Cl(e,n){if(n.held!=null)throw new so(n.held);let t=io(e.project_label,"a project label"),r=io(e.selector,"a selector"),o=to(e.argv,t),i=oo(e.env,t),s=ro(e.log_path,t),a=io(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.target)}`);let l=e.renew_within_ms??dh;if(!Number.isFinite(l)||l<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let d=Date.parse(n.now);if(!Number.isFinite(d))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(n.now)}`);return{version:1,project_label:t,selector:r,argv:o,workspace_path:a,env:i,...s==null?{}:{log_path:s},target:e.target,registered_at:new Date(d).toISOString(),renew_within_ms:l,renew_by:new Date(d+l).toISOString(),renewed_at:new Date(d).toISOString(),renewals:0,launch_revision:0}}var wt=class extends Error{constructor(t){super(`redskilled holds no registration for project ${JSON.stringify(t)} to renew: it lapsed or was never held, and a renewal never mints a record \u2014 register again, stating the selector, the argv and the target`);this.projectLabel=t;this.name="RedskilledProjectUnregisteredError"}};function Ml(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(n.now)}`);let r=n.renew_within_ms??e.renew_within_ms;if(!Number.isFinite(r)||r<=0)throw new Error(`redskilled needs a positive renewal window to renew project ${JSON.stringify(e.project_label)}, not ${JSON.stringify(n.renew_within_ms)}`);let o=n.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:to(n.launch.argv,e.project_label),env:oo(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},i=n.launch==null?e.log_path:ro(n.launch.log_path,e.project_label),{log_path:s,...a}=e;return{...a,...i==null?{}:{log_path:i},...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1}}function Wl(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(n.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,n.liveWorkers??0),i=n.queue,s=i!=null&&i.outcome==="counted"?i.depth:null,a=s!=null&&s>0?"open-work":o>0?"live-worker":null;if(a==null){let l=s===0?"drained":"uncounted";return{registration:e,verdict:l,detail:l==="drained"?`project ${r} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${r}, and an uncounted queue never sustains a registration \u2014 it stands on its own deadline of ${e.renew_by}`}}return{registration:{...e,renew_by:new Date(t+e.renew_within_ms).toISOString(),sustained_at:new Date(t).toISOString(),sustains:(e.sustains??0)+1,sustained_by:a},verdict:a,detail:a==="open-work"?`project ${r} has ${s} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function uh(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function Hl(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=i=>Number.isFinite(i)&&n-i<=e.renew_within_ms*ch;if(r(t))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return r(o)?"self-renewing":"running-on"}function Fl(e,n){let t=[],r=[];for(let o of e)(uh(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function lo(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.project_label=="string"&&typeof n.selector=="string"&&Array.isArray(n.argv)&&n.argv.every(t=>typeof t=="string")&&typeof n.workspace_path=="string"&&Number.isInteger(n.target)&&typeof n.registered_at=="string"&&typeof n.renew_within_ms=="number"&&typeof n.renew_by=="string"&&(n.renewed_at===void 0||typeof n.renewed_at=="string")&&(n.renewals===void 0||Number.isInteger(n.renewals))&&(n.env===void 0||ph(n.env))&&(n.log_path===void 0||typeof n.log_path=="string")&&(n.launch_revision===void 0||Number.isInteger(n.launch_revision))&&(n.sustained_at===void 0||typeof n.sustained_at=="string")&&(n.sustains===void 0||Number.isInteger(n.sustains))&&(n.sustained_by===void 0||n.sustained_by==="open-work"||n.sustained_by==="live-worker")}function ph(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function io(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var fh={ping:"host-read","host-state":"host-read","statusline-payload":"host-read",shutdown:"daemon-life","worker-start":"project-write","worker-stop":"project-write","worker-recycle":"project-write","worker-steer":"project-write","worker-heartbeat":"project-write","project-register":"project-write","project-renew":"project-write","project-deregister":"project-write"};function Ul(e){return`worker-${e}`}function Bl(e){let n=fh[e.op]??"project-write",t=e.sessionProject??null,r=e.targetProject??null,o={version:1,op:e.op,reach:n,session_project:t,target_project:r};return n==="host-read"?{...o,permitted:!0,verdict:"permitted-host-read",reason:`redskilled permitted ${e.op}: a session reads the whole host, whichever project it was started in`}:n==="daemon-life"?{...o,permitted:!0,verdict:"permitted-daemon-life",reason:`redskilled permitted ${e.op}: it acts on the daemon's own process, not on any project's Workers`}:t==null||t===""?{...o,permitted:!0,verdict:"permitted-unattributed",reason:`redskilled permitted ${e.op}: the session named no project of its own, so there is nothing to refuse it against`}:r!=null&&r===t?{...o,permitted:!0,verdict:"permitted-own-project",reason:`redskilled permitted ${e.op}: the target belongs to project ${JSON.stringify(t)}, which is this session's own`}:{...o,permitted:!1,verdict:"refused-cross-project",reason:`redskilled refused ${e.op} from a session in project ${JSON.stringify(t)}: ${r==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(r)}`}. A session reads the whole host and writes only its own project.`}}function Jl(e){return{generated_at:e.now,hour:Kl("hour",36e5,e),day:Kl("day",864e5,e)}}function xt(e,n,t){let r=En(t.now),o=t.retentionMs??864e5,i=t.limit??8192,s=e.filter(a=>{let l=En(n(a));return l==null?!1:r==null||r-l<=o});return s.length<=i?s:s.slice(s.length-i)}function Kl(e,n,t){let r=En(t.now),o=r==null?null:r-n,i=e==="hour"?"1h":"24h",s=t.observations.map(u=>({observation:u,at:En(u.observed_at)})).filter(u=>u.at!=null&&Gl(u.at,o,r)).sort((u,f)=>u.at-f.at),a=t.outcomes.map(u=>En(u.ts)).filter(u=>u!=null&&Gl(u,o,r)),l=Vl(s,u=>u.tokens,"tokens",i),d=Vl(s,u=>u.tools,"tools",i),p=[];return s.length===0?p.push("worker-vitals"):(l.samples===0&&p.push("worker-vitals.tokens"),d.samples===0&&p.push("worker-vitals.tools")),a.length===0&&p.push("worker-outcomes"),{window:e,window_ms:n,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:l,tools_per_min:d,issues_per_hour:mh(a.length,n,i),runner_share:ql("runner",s,u=>u.runner,i),model_share:ql("model",s,u=>u.model,i),unavailable:p}}function Vl(e,n,t,r){let o=new Map,i=0;for(let d of e){let p=n(d.observation);if(p==null||!Number.isFinite(p))continue;i+=1;let u=o.get(d.observation.worker_id)??[];u.push({at:d.at,count:p}),o.set(d.observation.worker_id,u)}if(i===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${r}`,samples:0};let s=0,a=null,l=null;for(let d of o.values()){if(d.length<2)continue;for(let f=1;f<d.length;f++){let m=d[f-1],h=d[f];m==null||h==null||(s+=Math.max(0,h.count-m.count))}let p=d[0],u=d[d.length-1];p!=null&&(a=a==null?p.at:Math.min(a,p.at)),u!=null&&(l=l==null?u.at:Math.max(l,u.at))}return a==null||l==null||l<=a?{value:null,absent_reason:`the last ${r} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:i}:{value:s/((l-a)/6e4),absent_reason:null,samples:i}}function mh(e,n,t){return e===0?{value:null,absent_reason:`no Worker outcome was recorded in the last ${t}`,samples:0}:{value:e/(n/36e5),absent_reason:null,samples:e}}function ql(e,n,t,r){let o=new Map;for(let d of n){let p=t(d.observation);p!=null?o.set(d.observation.worker_id,p):o.has(d.observation.worker_id)||o.set(d.observation.worker_id,null)}let i=new Map,s=0,a=0;for(let d of o.values()){if(d==null){a+=1;continue}s+=1,i.set(d,(i.get(d)??0)+1)}let l=[...i.entries()].map(([d,p])=>({key:d,worker_count:p,share:p/s})).sort((d,p)=>p.worker_count-d.worker_count||d.key.localeCompare(p.key));return{dimension:e,attributed_workers:s,unattributed_workers:a,shares:l,absent_reason:l.length>0?null:o.size===0?`no Worker was observed in the last ${r}`:`no Worker published a ${e} in the last ${r}`}}function Gl(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function En(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}import{execFileSync as hh}from"node:child_process";import{existsSync as gh,readFileSync as St,readdirSync as yh}from"node:fs";import{dirname as kh,join as $e}from"node:path";function Pn(e){let n=vn(e),t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let i=Ye(o);return i==null?null:{name:r,declared:o,bytes:i}}return null}function Ql(e){let n=[],t=[];for(let r of e.workers){let o=Pn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(vn(r).memory_max??vn(r).memory_high)==null?"this Worker declared no memory budget and the host derived no ceiling for it, so the sampler has none to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let i=e.rss[r.worker_id];if(typeof i!="number"||!Number.isFinite(i)){t.push({worker_id:r.worker_id,reason:"the host produced no RSS reading for this Worker on this tick, and an unmeasured Worker is never killed on suspicion"});continue}if(!(i<=o.bytes)){if(e.sources?.[r.worker_id]==="cgroup"&&o.name==="MemoryMax"){t.push({worker_id:r.worker_id,reason:`this Worker's ${o.name} of ${o.declared} is held by the kernel on its own cgroup, and the reading is memory.current \u2014 which counts reclaimable page cache the kernel drops before it kills anything, so the daemon does not duplicate an enforcement that can tell cache from anonymous memory`});continue}n.push(Rh(r,o,i))}}return{terminations:n,unenforceable:t}}function Rh(e,n,t){let r=`Worker ${JSON.stringify(e.worker_id)} of project ${JSON.stringify(e.project_label)}`;return{version:1,worker_id:e.worker_id,project_label:e.project_label,outcome:"terminated-over-memory-budget",classification:"budget-exceeded",stall:!1,budget_name:n.name,budget_declared:n.declared,budget_bytes:n.bytes,observed_rss_bytes:t,workspace_path:e.workspace_path,reason:`redskilled terminated ${r}: its tree RSS of ${t} bytes exceeded its ${n.name} budget of ${n.declared} (${n.bytes} bytes). This is a budget termination, not a stall, and the work in ${JSON.stringify(e.workspace_path)} is handed forward.`}}var bh=4096;function zl(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return r;let o={},i={},s={},a=wh(e,t,n);for(let[u,f]of a){let m=vh(f);m!=null&&(o[u]=m.memoryBytes,m.cpuSeconds!=null&&(i[u]=m.cpuSeconds),s[u]="cgroup")}let l=e.filter(u=>s[u.worker_id]==null);if(l.length===0)return{rss:o,cpu_seconds:i,sources:s};let d=jh(t,n);if(d.size===0)return{rss:o,cpu_seconds:i,sources:s};let p=new Map;for(let u of d.values()){let f=p.get(u.ppid);f?f.push(u.pid):p.set(u.ppid,[u.pid])}for(let u of l){if(!d.has(u.pid))continue;let f=0,m=0,h=[u.pid],b=new Set;for(;h.length>0;){let k=h.pop();if(b.has(k))continue;b.add(k);let w=d.get(k);if(w){f+=w.rssBytes,m+=w.cpuSeconds;for(let j of p.get(k)??[])h.push(j)}}o[u.worker_id]=f,i[u.worker_id]=m,s[u.worker_id]="process-tree"}return{rss:o,cpu_seconds:i,sources:s}}var _h="/sys/fs/cgroup";function wh(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let i=t.cgroupRoot??_h,s=e.filter(l=>l.unit!=null&&l.unit!=="");if(s.length===0)return r;let a=xh(i,t);for(let l of s)for(let d of a){let p=$e(d,l.unit);if(gh($e(p,"memory.current"))){r.set(l.worker_id,p);break}}return r}function xh(e,n){let t=n.selfCgroupPath??Sh(),r=[],o=a=>{r.includes(a)||r.push(a)},i=t;for(;i!=null&&i!==""&&i!=="/"&&i!==".";){o($e(e,i));let a=kh(i);if(a===i)break;i=a}o(e);let s=n.uid??process.getuid?.();return s!=null&&o($e(e,"user.slice",`user-${s}.slice`,`user@${s}.service`,"app.slice")),r}function Sh(){try{for(let e of St("/proc/self/cgroup","utf8").split(`
64
+ `))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function vh(e){let n;try{n=St($e(e,"memory.current"),"utf8")}catch{return null}let t=Number(n.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:Eh(e)}}function Eh(e){let n;try{n=St($e(e,"cpu.stat"),"utf8")}catch{return null}return Ph(n)}function Ph(e){for(let n of e.split(`
65
+ `)){let[t,r]=n.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(r);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function jh(e,n){return n.procRoot!=null||e==="linux"?Ih(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?Lh(Dh(n.psTable)):new Map}function Dh(e){try{return(e??Oh)()}catch{return""}}function Oh(){return hh("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Ah=1024;function Lh(e){let n=new Map;for(let t of e.split(`
66
+ `)){let r=t.trim().split(/\s+/);if(r.length!==4)continue;let[o,i,s]=r.slice(0,3).map(Number);if(![o,i,s].every(l=>l!=null&&Number.isSafeInteger(l)&&l>=0))continue;let a=$h(r[3]);a!=null&&n.set(o,{pid:o,ppid:i,rssBytes:s*Ah,cpuSeconds:a})}return n}function $h(e){let n=e.indexOf("-"),t=n<0?0:Number(e.slice(0,n));if(!Number.isFinite(t)||t<0)return null;let r=e.slice(n+1).split(":"),o=t*86400,i=1;for(let s=r.length-1;s>=0;s--){let a=Number(r[s]);if(!Number.isFinite(a)||a<0||r[s]==="")return null;o+=a*i,i*=60}return o}function Ih(e){let n=new Map,t;try{t=yh(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=St($e(e,r,"stat"),"utf8")}catch{continue}let i=Nh(o);i&&n.set(i.pid,{pid:i.pid,ppid:i.ppid,rssBytes:i.rssPages*bh,cpuSeconds:i.cpuTicks/Th})}return n}var Th=100;function Nh(e){let n=e.lastIndexOf(")");if(n<0)return null;let t=Number(e.slice(0,e.indexOf(" "))),r=e.slice(n+1).trim().split(/\s+/),o=Number(r[1]),i=Number(r[11]),s=Number(r[12]),a=Number(r[21]);return!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||!Number.isFinite(a)||!Number.isFinite(i)||!Number.isFinite(s)?null:{pid:t,ppid:o,rssPages:Math.max(0,a),cpuTicks:Math.max(0,i)+Math.max(0,s)}}function Yl(e){return e==="single-object"?"rest":"graphql"}function L(e,n,t,r,o){return{key:e,kind:"read",cardinality:n,surface:o??Yl(n),budget:t,...o?{only:o}:{},why:r}}function F(e,n,t,r){return{key:e,kind:"write",cardinality:"single-object",surface:n,budget:t,why:r}}var Xl=[L("issue view","single-object","rest","one issue by number; REST answers it in one request against the idle pool"),L("pr view","single-object","rest","one pull request by number, polled per Worker per iteration"),L("repo view","single-object","rest","one repository's own metadata"),L("run view","single-object","rest","one Actions run; the Actions API has no GraphQL surface either way"),L("release view","single-object","rest","one release by tag"),L("pr diff","single-object","rest","one pull request's diff, served by a REST media type"),L("issue list","multi-node","graphql","a connection of issues; one GraphQL query beats N REST pages"),L("pr list","multi-node","graphql","a connection of pull requests; one GraphQL query beats N REST pages"),L("pr checks","multi-node","graphql","every check context on one commit, which is a connection, not an object"),L("release list","multi-node","rest","Releases have no GraphQL connection gh reads; REST pages them","rest"),L("run list","multi-node","rest","the Actions API has no GraphQL surface, so a listing draws the request pool","rest"),L("label list","multi-node","graphql","a connection of labels inside one repository"),L("issue list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),L("pr list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),L("search issues","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),L("search prs","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),L("search repos","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),L("api graphql","multi-node","graphql","the caller wrote the query; `gh api graphql` is GraphQL by construction"),L("api rest","single-object","rest","any `gh api <path>` that is not `graphql` is a REST request"),F("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),F("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),F("issue close","graphql","graphql","gh closes with the closeIssue mutation"),F("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),F("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),F("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),F("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),F("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),F("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),F("pr close","graphql","graphql","gh closes with a GraphQL mutation"),F("pr edit","graphql","graphql","gh edits with GraphQL mutations"),F("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),F("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),F("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],Ch=new Map(Xl.map(e=>[e.key,e]));function Zl(e){let n=[],t=0;for(;t<e.length&&e[t].startsWith("-");)t+=e[t]==="-R"||e[t]==="--repo"?2:1;for(;t<e.length&&!e[t].startsWith("-")&&n.length<2;)n.push(e[t]),t+=1;return n}function ao(e){let n=Zl(e);if(n.length===0)return"";if(n[0]==="api")return n[1]==="graphql"?"api graphql":"api rest";let t=n.length===1?n[0]:`${n[0]} ${n[1]}`;return n[1]==="list"&&e.includes("--search")?`${t} (search)`:t}var vt=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(n){let t=ao(n);super(`unclassified GitHub operation ${JSON.stringify(t||"(empty argv)")}: add an entry to GITHUB_OPERATIONS in packages/github/surface.ts stating its cardinality. Defaulting to GraphQL is what sent every single-object poll to the node-point pool (ADR 0132 decision 4).`),this.operation=t,this.args=[...n]}};function ea(e){return Ch.get(ao(e))??null}function na(e){let n=ea(e);if(!n)throw new vt(e);return n}function co(e){return na(e).surface}var Mh=["api","graphql"],Wh=co(Mh);function Hh(e,n="https://api.github.com"){return e==="graphql"?`${n}/graphql`:n}var ta=100,fo=6e4,Fh=2*fo,Uh=7*24*60*60*1e3,uo=class extends Error{constructor(t,r,o){super(`redskilled polls every repository with one host token ${JSON.stringify(o)}, and project ${JSON.stringify(t)} declares its own credential ${JSON.stringify(r)}: a project needing its own credential invalidates the host-scoped poller (ADR 0130 Amendment 1) rather than bending it, so the poller returns to the projects instead of reaching this repository under the wrong identity`);this.projectLabel=t;this.tokenRef=r;this.hostTokenRef=o;this.name="RedskilledSplitCredentialError"}};function mo(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new uo(t.project_label,t.token_ref,n)}function Bh(e,n={now:new Date(0).toISOString()}){qh(e);let t=n.closedWindowMs??Uh,r=Date.parse(n.now);if(!Number.isFinite(r))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(n.now)}`);let o=new Date(r-Math.max(0,t)).toISOString(),i=e.map((l,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:l}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { remaining resetAt }",...i.flatMap(({alias:l,search_alias:d,project:p})=>{let u=JSON.stringify(p.owner),f=JSON.stringify(p.name),m=JSON.stringify(`repo:${p.owner}/${p.name} is:closed closed:>=${o}`);return[` ${l}: repository(owner: ${u}, name: ${f}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${d}: search(query: ${m}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
67
+ `),aliases:i,closed_since:o}}function Kh(e,n,t){let r=Xe(n),o=Xe(r.data),i=Array.isArray(r.errors)?r.errors.map(Xe):[],s=Gh(o.rateLimit,i),a=e.aliases.map(({alias:l,search_alias:d,project:p})=>{let u=p.owner+"/"+p.name,f=o[l],m=i.find(h=>ra(h.path,l)||ra(h.path,d));if(da(f)){let h=oa(f.open_pull_requests),b=oa(f.open_issues),k=Jh(o[d]);if(h!=null&&b!=null&&k!=null)return{project_label:p.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:h,open_issues:b,recently_closed:k},detail:`counted ${u} for project ${JSON.stringify(p.project_label)}`}}return s.exhausted||aa(m)?{project_label:p.project_label,repository:u,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${u} answered, so this project has no counts rather than zero counts${s.reset_at==null?"":`; the quota resets at ${s.reset_at}`}`}:{project_label:p.project_label,repository:u,outcome:"unreachable",counts:null,detail:`${u} is not reachable with the host token: ${po(m?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:a.length,rate_limit:s,projects:a}}function Vh(e){return{version:1,fetched_at:e,request_count:0,project_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}async function ia(e){if(e.projects.length===0)return Vh(e.now);mo(e.projects,e.hostTokenRef);let n=Bh(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return Kh(n,t,{fetchedAt:e.now})}catch(t){let r=t instanceof Error?t.message:String(t),o=/rate limit|secondary rate|429/i.test(r);return{version:1,fetched_at:e.now,request_count:1,project_count:e.projects.length,rate_limit:{remaining:null,reset_at:null,exhausted:o},projects:e.projects.map(i=>({project_label:i.project_label,repository:`${i.owner}/${i.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${i.owner}/${i.name} answered: ${r}`}))}}}function sa(e){let n=e.stalenessMs??Fh,t=e.activity;if(t==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:n,stale:!1,request_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[],reason:"the daemon polls no repository, so there are no counts to age"};let r=Date.parse(e.now),o=Date.parse(t.fetched_at),i=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,s=i==null||i>n;return{version:1,fetched_at:t.fetched_at,age_ms:i,threshold_ms:n,stale:t.projects.length>0&&s,request_count:t.request_count,rate_limit:t.rate_limit,projects:t.projects.map(a=>({...a,fetched_at:t.fetched_at,age_ms:i,stale:s})),reason:t.projects.length===0?"the daemon polls no repository, so there are no counts to age":i==null?"these counts carry no readable instant, so they cannot be presented as current":s?`these counts are ${i}ms old, past the ${n}ms window`:`fetched ${i}ms ago, within the ${n}ms window`}}function la(e){let n=e.endpoint??Hh(Wh),t=e.fetchImpl??fetch;return async r=>{let o=await t(n,{method:"POST",headers:{authorization:`bearer ${e.token}`,"content-type":"application/json",accept:"application/vnd.github+json"},body:JSON.stringify({query:r})});if(!o.ok){let i=o.headers.get("x-ratelimit-remaining"),s=o.status===429||i==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(s?": the host token's rate limit is spent":""))}return await o.json()}}function qh(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>ta)throw new Error(`redskilled activity fetch spans at most ${ta} repositories in one query`);let n=new Set;for(let t of e){if(t.project_label===""||t.owner===""||t.name==="")throw new Error("redskilled activity fetch needs a project label and an owner/name for every registered project");if(n.has(t.project_label))throw new Error(`redskilled holds one repository per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function Gh(e,n){let t=Xe(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,i=n.some(aa);return{remaining:r,reset_at:o,exhausted:i||r===0}}function aa(e){if(e==null)return!1;let n=po(e.type),t=po(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function ra(e,n){return Array.isArray(e)&&e.includes(n)}function oa(e){let n=Xe(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function Jh(e){let n=Xe(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Xe(e){return da(e)?e:{}}function da(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function po(e){return typeof e=="string"?e:""}var Qh=3e4,zh=4;function ca(e){let n=e.stalenessMs??Qh,t=jn(e.now),r=e.sampledAt==null?null:jn(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),i=o!=null&&o<=n,s=new Set(e.reattachedWorkerIds??[]),a=e.hostState.workers.map(f=>Zh(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:i,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:s.has(f.worker_id)?"reattached":"running"})),l=a.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=a.length-l.length,p=a.reduce((f,m)=>f+(m.vitals.rss_bytes??0),0),u=kt(e.hostState.workers);return{version:1,generated_at:e.now,daemon:{pid:e.hostState.pid,daemon_version:e.hostState.daemon_version,protocol_version:e.hostState.protocol_version,started_at:e.hostState.started_at,machine_id_hash:e.hostState.machine_id_hash,session_key_hash:e.hostState.session_key_hash},staleness:rg({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:a.length,measuredCount:d,unmeasured:l}),host:{worker_count:a.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:u,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:p,measured_worker_count:d,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:u.memory_bytes/e.ceiling.memory_bytes},projects:tg(a),known_projects:ng(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,m)=>f.localeCompare(m)),workers:a,repository_activity:sa({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:Yh(e.deaths,e.recentDeathLimit??zh)},engine:Xh(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function Yh(e,n){let t=[...e].sort((o,i)=>(jn(i.ts)??0)-(jn(o.ts)??0)),r=t.slice(0,Math.max(0,Math.floor(n))).map(o=>({kind:o.kind,id:o.id,pid:o.pid,ts:o.ts,last_seen:o.last_seen,last_phase:o.last_phase,sender_class:o.sender_class,confidence:o.confidence,signal:o.signal,evidence:o.evidence[0]??null}));return{count:t.length,recent:r,latest:r[0]??null,reaped_at:r[0]?.ts??null}}function Xh(e){let n=e.upgrade,t=n?.running_version??e.daemon_version,r=n?.published_version??null,o=n?.newest_published_version??null,i=(n?.newer_published??0)>0,s=(n?.major_held??0)>0;return{running_version:t,published_version:r,newer_published:i,major_held:s,current:r==null&&o==null?null:!i&&!s}}function Zh(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=Pn(e),i=e.budget?.memory_max??e.budget?.memory_high??null,s=jn(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms:n.nowMs==null||s==null?null:Math.max(0,n.nowMs-s),state:n.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:r,sampled_at:r==null?null:n.sampledAt,age_ms:r==null?null:n.ageMs,fresh:r!=null&&n.sampleFresh,rss_source:r==null?null:e.rss_source??null},budget:{name:o?.name??null,declared:o?.declared??i,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:eg(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function eg(e){let n={last_line:null,published_at:null,source:null};return e==null||e.line.trim()===""?n:{last_line:e.line,published_at:e.published_at,source:e.source}}function ng(e){let n=new Set;for(let t of e.registrations??[])n.add(t.project_label);for(let t of e.projects)n.add(t.project_label);return[...n].sort((t,r)=>t.localeCompare(r))}function tg(e){let n=new Map;for(let t of e){let r=n.get(t.project_label)??{workers:0,declared:0,observed:0,measured:0};r.workers+=1,r.declared+=t.budget.bytes??0,r.observed+=t.vitals.rss_bytes??0,r.measured+=t.vitals.rss_bytes==null?0:1,n.set(t.project_label,r)}return[...n.entries()].map(([t,r])=>({project_label:t,worker_count:r.workers,declared_memory_bytes:r.declared,observed_rss_bytes:r.observed,measured_worker_count:r.measured})).sort((t,r)=>t.project_label.localeCompare(r.project_label))}function rg(e){let n={sampled_at:e.sampledAt,age_ms:e.ageMs,threshold_ms:e.threshold,measured_worker_count:e.measuredCount,unmeasured_workers:e.unmeasured};return e.workerCount===0?{...n,stale:!1,reason:"the host holds no Workers, so there is nothing to measure and nothing to age"}:e.sampledAt==null||e.ageMs==null?{...n,stale:!0,reason:`this answer is stale: the daemon has taken no measurement of its ${e.workerCount} live Worker(s) yet`}:e.ageMs>e.threshold?{...n,stale:!0,reason:`this answer is stale: its measurement is ${e.ageMs}ms old, past the ${e.threshold}ms staleness window`}:{...n,stale:!1,reason:`measured ${e.ageMs}ms ago, within the ${e.threshold}ms staleness window`}}function jn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}var $={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function ua(e,n=$){let t=cg(e,n),r=ag(e,n),o=dg(e,n),i=ug(e,n,r,t),s=sg(n,r,o),a={detail:"host",line:i};for(let u of s){let f=_g(i,lg(u,n,r,o),n.separator);if(a={detail:u,line:f},wg(f)<=n.maxWidth)break}let l=ko(a.line,n.maxWidth),d=n.verbose&&a.detail==="workers"?yg(r,n):[],p=r.length>0?"workers":"host";return{version:1,line:l,lines:[l,...d],verbose:n.verbose,mode:n.mode,project:n.project,project_match:t,detail:a.detail,degraded:a.detail!==p||l!==a.line,stale:e.staleness.stale,generated_at:e.generated_at}}function pa(e){let n=e.options??$,t=ko(ig,n.maxWidth);return{version:1,line:t,lines:[t],verbose:n.verbose,mode:n.mode,project:n.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}var og="!unregistered",go="\u21E1",Et="\u2020",ig="redskilled unreachable \u2014 Worker state unknown";function sg(e,n,t){let r=[];return n.length>0&&n.length<=e.maxWorkers&&r.push("workers"),e.mode==="global"&&t.length>0&&t.length<=e.maxProjects&&r.push("projects"),r.push("host"),r}function lg(e,n,t,r){return e==="workers"?t.map(o=>gg(o,n)):e==="projects"?r.map(bg):[]}function ag(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function dg(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function cg(e,n){return yo(e,n.project)}function yo(e,n){return n==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(n)?e.registered_projects==null||e.registered_projects.includes(n)?"matched":"name-only":"unregistered"}function ug(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(ho(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(ho(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(ho(e,n)),o.push(og)):o.push(mg(n.project,r)),o.push(pg(e));let i=fg(e);return i!=null&&o.push(i),e.staleness.stale&&o.push(hg(e)),o.join(" ")}function pg(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${go}`}function fg(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Et}${n.count} ${n.latest.sender_class}`}function mg(e,n){return n==="unregistered"?`project unknown \u2014 ${e} is not registered on this host`:"project unknown \u2014 this directory resolved to no project"}function ho(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,i)=>o+i.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${X(t)}/${X(r)}`:X(t)}function hg(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function gg(e,n){let t=fa(e,n),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?X(r):`${X(r)}/${X(e.budget.bytes)}`;return`${t} ${o}`}function yg(e,n){let t=[];for(let r of e){let o=Rg(r.log.last_line);o!=null&&t.push(ko(` ${kg} ${fa(r,n)}: ${o}`,n.maxWidth))}return t}var kg="\u21B3";function Rg(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}function fa(e,n){return n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function bg(e){return`${e.project_label} ${e.worker_count}w ${X(e.observed_rss_bytes)}`}function _g(e,n,t){return[e,...n].join(t)}function wg(e){return[...e].length}function ko(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}function X(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}var Ro={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},xg=["runner","model","effort","origin","issue","phase","step","heartbeat"],Sg=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function ma(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...Ro};for(let r of xg){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of Sg){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}var Pt=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],Ze={mode:"local",project:null,maxWidth:200,maxRows:16};var vg=" ",ha="\u2588",Eg="\u25B6",Pg="\u2717",jg="\u2591";function ga(e,n=Ze){let t=yo(e,n.project),r=Dg(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),i=o.map(u=>Og(u,n)),s=Wg(i),a=o.map((u,f)=>({worker_id:u.worker_id,project_label:u.project_label,mine:n.project!=null&&u.project_label===n.project,cells:i[f],line:Dn(Hg(i[f],s),n.maxWidth)})),l=Lg(e,n,r,t),d=r.length-o.length,p=[l.line,...a.map(u=>u.line)];return d>0&&p.push(Dn(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),p.push(...Ig(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Pt,header:l,rows:a,lines:p,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Dg(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Og(e,n){let t=e.display??Ro,r=[t.runner,t.model,t.effort].filter(o=>!!o).join(" ");return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:r===""?"":`run=${r}`,org:t.origin==null?"":`org=${t.origin}`,iss:t.issue==null?"":`iss=${t.issue}`,bar:Ag(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:Mg(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:Cg(t.added,t.removed),tks:t.tokens==null?"":`tks=${ya(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function Ag(e){let n=e.phase_total,t=e.phase_index;if(n==null||n<=0||t==null||t<0)return"";let r=Math.min(Math.floor(t),Math.floor(n));if(r>=n)return ha.repeat(Math.floor(n));let o=e.failed?Pg:Eg;return`${ha.repeat(r)}${o}${jg.repeat(Math.floor(n)-r-1)}`}function Lg(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(w=>w.project_label===n.project),i={open_pull_requests:o?.counts?.open_pull_requests??null,recently_closed:o?.counts?.recently_closed??null,open_issues:o?.counts?.open_issues??null,stale:o?.stale===!0},s={memory_used_fraction:e.host.ceiling_used_fraction,memory_used_bytes:e.host.consumption.memory_bytes,memory_ceiling_bytes:e.host.ceiling.memory_bytes,worker_count:e.host.worker_count,worker_ceiling:e.host.ceiling.worker_count},a=Ng(t),l=o?.repository??n.project,d=e.engine??null,p=d?.running_version??e.daemon.daemon_version,u=e.deaths??null,f=e.metrics??null,m=[`\xBB ${l??"host"} v${p}${d!=null&&d.current===!1?go:""}`];r==="unregistered"&&m.push("!unregistered"),r==="name-only"&&m.push("!lapsed"),a!=null&&m.push(a),m.push(`wrk=${t.length}/${e.host.worker_count}`),m.push(s.worker_ceiling==null?"slots=\u221E":`slots=${s.worker_count}/${s.worker_ceiling}`),m.push(Tg(s)),i.open_pull_requests!=null&&m.push(`prs=${i.open_pull_requests}`),i.recently_closed!=null&&m.push(`cpr=${i.recently_closed}`),i.open_issues!=null&&m.push(`iss=${i.open_issues}`),i.stale&&m.push("!counts stale");let h=f==null?null:$g(f.hour);if(h!=null&&m.push(h),u!=null&&u.count>0&&u.latest!=null&&m.push(`${Et}${u.count} ${u.latest.sender_class}`),e.staleness.stale){let w=e.staleness.age_ms;m.push(w==null?"!unmeasured":`!stale ${Math.round(w/1e3)}s`)}let b=m.join(" \xB7 "),k=h!=null&&_o(b)>n.maxWidth?m.filter(w=>w!==h).join(" \xB7 "):b;return{repo:l,project:n.project,project_match:r,version:p,engine:d,deaths:u,metrics:f,model:a,windows:s,counts:i,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:Dn(k,n.maxWidth)}}function $g(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${bo(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${bo(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${bo(e.issues_per_hour.value)}`);let t=e.runner_share.shares[0];return t!=null&&n.push(`${t.key}=${Math.round(t.share*100)}%`),n.length===0?null:n.join(" ")}function Ig(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(i=>Dn(`${Et} ${i.kind} ${i.id} pid=${i.pid} ${i.sender_class}/${i.confidence} phase=${i.last_phase}`+(i.signal==null?"":` signal=${i.signal}`)+(i.evidence==null?"":` \u2014 ${i.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(Dn(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function Tg(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${X(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${X(e.memory_used_bytes)}/${X(e.memory_ceiling_bytes)}${n}`}function Ng(e){for(let n of e){let t=n.display;if(t==null)continue;let r=[t.runner,t.model,t.effort].filter(o=>!!o);if(r.length>0)return r.join("\xB7")}return null}function Cg(e,n){if(e==null&&n==null)return"";let t=[];return e!=null&&e>0&&t.push(`+${e}`),n!=null&&n>0&&t.push(`-${n}`),`loc=${t.length>0?t.join(" "):"0"}`}function ya(e){if(!Number.isFinite(e)||e<=0)return"0";let n=(t,r)=>{let o=(Math.round(t*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${r}`};return e>=1e9?n(e/1e9,"B"):e>=1e6?n(e/1e6,"M"):e>=1e3?n(e/1e3,"k"):String(Math.round(e))}function bo(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return ya(e);if(e<=0)return"0";let n=(Math.round(e*10)/10).toFixed(1);return n.endsWith(".0")?n.slice(0,-2):n}function Mg(e){if(e==null||!Number.isFinite(e)||e<0)return"\u2014";let n=Math.floor(e/1e3);if(n<60)return`${n}s`;let t=Math.floor(n/60);if(t<60)return`${t}m${n%60}s`;let r=Math.floor(t/60);return r<24?`${r}h${t%60}m`:`${Math.floor(r/24)}d${r%24}h`}function Wg(e){let n=Object.fromEntries(Pt.map(t=>[t,0]));for(let t of e)for(let r of Pt)n[r]=Math.max(n[r],_o(t[r]));return n}function Hg(e,n){return Pt.filter(r=>n[r]>0).map(r=>Fg(e[r],n[r])).join(vg).replace(/\s+$/,"")}function Fg(e,n){return e+" ".repeat(Math.max(0,n-_o(e)))}function _o(e){return[...e].length}function Dn(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}var jt=1;async function On(e,n){return await ut(e,n,"redskilled daemon")}function ka(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.line=="string"&&Array.isArray(n.lines)&&n.lines.every(t=>typeof t=="string")&&typeof n.verbose=="boolean"&&(n.mode==="local"||n.mode==="global")&&(n.project===null||typeof n.project=="string")&&typeof n.detail=="string"&&(n.project_match===void 0||typeof n.project_match=="string")&&typeof n.degraded=="boolean"&&typeof n.stale=="boolean"&&typeof n.generated_at=="string"}function Ra(e){let n=[...e.workers??[]],t=new Map;for(let r of n)t.set(r.project_label,(t.get(r.project_label)??0)+1);return{version:1,protocol_version:jt,daemon_version:e.daemonVersion,machine_id_hash:e.machineIdHash,session_key_hash:e.sessionKeyHash,pid:e.pid,started_at:e.startedAt,...e.scope==null?{}:{scope:e.scope},workers:n,projects:[...t.entries()].map(([r,o])=>({project_label:r,worker_count:o})).sort((r,o)=>r.project_label.localeCompare(o.project_label)),registrations:Kg(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:cl(n,{hostCeilingBytes:e.hostCeilingBytes??null}),upgrade:Vg(e)}}function Kg(e){let n=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(n),r=e.queue??null,o=new Map(r==null?[]:r.projects.map(i=>[i.project_label,i]));return[...e.registrations??[]].map(i=>{let s=o.get(i.project_label);return{...i,...t?{renewal:Hl(i,n)}:{},...r==null||s==null?{}:{last_poll:{at:r.fetched_at,outcome:s.outcome,depth:s.depth,request_count:r.request_count,detail:s.detail}}}}).sort((i,s)=>i.project_label.localeCompare(s.project_label))}function Vg(e){let n=e.daemonVersion,t=e.published?.version??null,r=e.published?.majorHold??null;return{running_version:n,published_version:t,published_unknown:+(t===null),newer_published:+(e.published?.newer===!0),replacement:e.published?.replacement??"none",checked_at:e.published?.checkedAt??null,checks:e.published?.checks??0,hold_reason:e.published?.holdReason??null,newest_published_version:e.published?.newest??null,major_held:+(r!==null),major_hold:r}}function ba(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.protocol_version=="number"&&typeof n.daemon_version=="string"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&Number.isInteger(n.pid)&&typeof n.started_at=="string"&&Array.isArray(n.workers)&&Array.isArray(n.projects)&&ul(n.budget_accounting)&&(n.scope===void 0||Tl(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(lo))&&(n.upgrade===void 0||qg(n.upgrade))}function qg(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")&&typeof n.published_unknown=="number"&&typeof n.newer_published=="number"&&(n.replacement==="none"||n.replacement==="pending"||n.replacement==="in-progress")&&(n.checked_at===null||typeof n.checked_at=="string")&&(n.newest_published_version===void 0||n.newest_published_version===null||typeof n.newest_published_version=="string")&&(n.major_held===void 0||typeof n.major_held=="number")&&(n.checks===void 0||typeof n.checks=="number")&&(n.hold_reason===void 0||n.hold_reason===null||typeof n.hold_reason=="string")&&(n.major_hold===void 0||n.major_hold===null||Gg(n.major_hold))}function Gg(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.version=="string"&&Number.isInteger(n.running_major)&&Number.isInteger(n.held_major)&&typeof n.reason=="string"&&typeof n.action=="string"&&n.action.trim()!==""}import{spawnSync as At}from"node:child_process";import{existsSync as Eo}from"node:fs";import{delimiter as ty,join as Oa}from"node:path";import{join as _a}from"node:path";import{existsSync as Jg}from"node:fs";import{createRequire as Qg}from"node:module";var wa="redskilled-job-object.node",Ie=100;function en(e){return{available:!1,reason:e}}function zg(e,n,t){return[_a(t,"prebuilds",`${e}-${n}`,wa),_a(t,"native","build","Release",wa)]}function xa(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return en(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??Xg(),o=e.exists??Jg,i=zg(n,t,r),s=i.find(d=>o(d));if(s==null)return en(`no Job Object addon was found for ${n}-${t} (looked in ${i.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let a=e.requireFn??Qg(import.meta.url),l;try{l=a(s)}catch(d){return en(`the Job Object addon at ${s} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return Yg(l)?{available:!0,binding:l}:en(`the Job Object addon at ${s} does not export createJobObject, so it cannot be the native reach`)}function Yg(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Xg(){return new URL("..",import.meta.url).pathname}function Sa(e){let n=e??{},t=[],r=Zg(n);r==null&&(n.memory_max??n.memory_high)!=null&&t.push("the declared memory budget could not be reduced to bytes, so the job carries no memory ceiling");let o;return n.cpu_weight!=null&&(n.cpu_weight<Ie?o=Math.max(1,Math.min(100,Math.round(n.cpu_weight))):t.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${Ie}, and Windows CPU rate control is an absolute cap rather than a share, so no rate limit is set`)),{...r!=null?{memory_limit_bytes:r.bytes,memory_budget_name:r.name,memory_budget_declared:r.declared}:{},...o!=null?{cpu_rate_percent:o}:{},kill_on_close:!0,...t.length>0?{note:t.join("; ")}:{}}}function Zg(e){return Pn({budget:e})}var Dt=5,va=19;function wo(e){return{available:!1,reason:e}}var ey="an address-space rlimit is not a resident-memory ceiling: a runtime that reserves address space it never faults in would die under a limit it never used, so no memory rlimit is set and the daemon's RSS sampling floor is the ceiling that actually holds";function Pa(e,n){let t=e??{},r=[],o;if(!n.canRenice)r.push("nice is not on this host, so no priority control was applied and the Worker competes with interactive work");else if(t.cpu_weight==null)o=Dt;else if(t.cpu_weight<Ie){let a=Math.round(va*(Ie-t.cpu_weight)/Ie);o=Math.min(va,Math.max(Dt,a))}else o=Dt,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${Ie}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Dt}`);let i=Ea(t.max_processes);i==null&&t.max_processes!=null&&r.push(`max_processes=${t.max_processes} is not a positive whole number, so no ulimit -u is set`);let s=Ea(t.cpu_seconds);return s==null&&t.cpu_seconds!=null&&r.push(`cpu_seconds=${t.cpu_seconds} is not a positive whole number, so no ulimit -t is set`),{...o!=null?{nice:o}:{},...i!=null?{max_processes:i}:{},...s!=null?{cpu_seconds:s}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:ey,...r.length>0?{note:r.join("; ")}:{}}}function ja(e){let{limits:n}=e,t=[];return n.max_processes!=null&&t.push(`ulimit -u ${n.max_processes}`),n.cpu_seconds!=null&&t.push(`ulimit -t ${n.cpu_seconds}`),t.push(n.nice!=null&&e.nice!=null?`exec ${ny(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
68
+ `),e.command,...e.args]}function Da(e){let n=[];return e.nice!=null?n.push(`the Worker runs at nice ${e.nice} so it yields to interactive work`):n.push("no priority control was applied"),e.max_processes!=null&&n.push(`its processes are capped at ${e.max_processes}`),e.cpu_seconds!=null&&n.push(`its CPU time is capped at ${e.cpu_seconds} seconds`),`macOS placement applied POSIX limits: ${n.join(", ")}. macOS has no resource-group equivalent, so the Worker is charged to the daemon's own resource group, and ${e.memory_ceiling_reason}`+(e.note!=null?` (${e.note})`:"")}function xo(e){let n=e??{},t=[n.max_processes!=null?"max_processes":null,n.cpu_seconds!=null?"cpu_seconds":null].filter(r=>r!=null);return t.length===0?null:`${t.join(" and ")} ${t.length===1?"is a POSIX rlimit":"are POSIX rlimits"} honoured only by the macOS placement backend, so this placement carries no equivalent`}function Ea(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function ny(e){return`'${e.replace(/'/g,"'\\''")}'`}var Aa="REDSKILLED_PLACEMENT",Ot="red-worker",So="/bin/sh";function La(e=process.env,n=process.platform){let t=wo(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:xa({platform:n}),posix:t};let r=en(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);if(n==="darwin")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:ry(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),i=o!==""&&Eo(Oa(o,"systemd","private"));return{platform:n,systemdRun:Na("systemd-run",e),userSession:i,jobObjects:r,posix:t}}function ry(e){return Eo(So)?{available:!0,shell:So,nice:Na("nice",e)}:wo(`no POSIX shell was found at ${So}, so there is nothing to apply rlimits or priority in`)}function $a(e=process.env){let n=(e[Aa]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function oy(e,n,t=Ot){return Ia(e,n,t).replace(/\.service$/,"")}function Ia(e,n,t=Ot){return`${vo(t,"red-worker",24)}-${vo(e,"project",32)}-${vo(n,"worker",32)}.service`}function Ta(e){let n=[...e.args??[]],t={...e.budget??{},...e.budget?.memory_max==null&&e.memoryCeiling?.memory_max!=null?{memory_max:e.memoryCeiling.memory_max}:{}},r=t.memory_max??t.memory_high??null,o=t.memory_high!=null||t.memory_max!=null||t.cpu_weight!=null,i=e.target??{isolation:"transient-unit"},s=u=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:u,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Rn({scope:null,memory_ceiling:r,scope_degradation:u}),...o?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(i.isolation==="inherit")return s("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return s(`worker isolation disabled by ${Aa}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return sy(e,n,t,r,o,s);if(e.probes.platform==="darwin")return iy(e,n,t,r,s);if(e.probes.platform!=="linux")return s(`transient-unit placement is the Linux backend (platform=${e.probes.platform}): the Worker is charged to the daemon's own resource group`);if(!e.probes.systemdRun)return s("transient-unit placement unavailable: systemd-run is not on PATH; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");if(!e.probes.userSession)return s("transient-unit placement unavailable: no systemd --user session; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");let a=Ia(e.projectLabel,e.workerId,i.unit_prefix),l=["--user","--collect","--quiet","--wait",`--unit=${a}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&l.push("--pipe"),t.memory_high!=null&&l.push(`--property=MemoryHigh=${t.memory_high}`),t.memory_max!=null&&l.push(`--property=MemoryMax=${t.memory_max}`),t.cpu_weight!=null&&l.push(`--property=CPUWeight=${t.cpu_weight}`);let d=Rn({scope:a,memory_ceiling:r,scope_degradation:null});for(let[u,f]of Object.entries({...e.env??{},...d}))l.push(`--setenv=${u}=${f}`);let p=xo(e.budget);return{isolated:!0,backend:"transient-unit",unit:a,command:e.probes.systemdRun,args:[...l,"--",e.command,...n],budget:t,...r!=null?{memoryCeiling:r}:{},environment:d,...p!=null?{budgetWarning:p}:{}}}function iy(e,n,t,r,o){let i=e.probes.posix;if(!i.available)return o(`POSIX limit placement unavailable: ${i.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let s=Pa(t,{canRenice:i.nice!=null}),a=t.memory_high!=null||t.memory_max!=null,l=Da(s);return{isolated:!1,backend:"posix-limits",command:i.shell,args:ja({limits:s,nice:i.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:s,warning:l,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Rn({scope:null,memory_ceiling:r,scope_degradation:l}),...a?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+s.memory_ceiling_reason}:{}}}function sy(e,n,t,r,o,i){let s=e.probes.jobObjects;if(!s.available)return i(`Job Object placement unavailable: ${s.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let a=Sa(t),l=oy(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...n],cwd:e.workspacePath,job:{name:l,limits:a},budget:t,...r!=null?{memoryCeiling:r}:{},environment:Rn({scope:l,memory_ceiling:r,scope_degradation:null}),...ly(o&&a.note!=null?`${a.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,xo(e.budget))}}function ly(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function Na(e,n){for(let t of(n.PATH??"").split(ty)){if(!t)continue;let r=Oa(t,e);if(Eo(r))return r}return null}function vo(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function Po(e,n){let t=[],r=[];for(let o of e){let i=!1;try{i=await n(o)===!0}catch{i=!1}(i?t:r).push(o)}return{alive:t,dead:r}}function Ca(e){return e.unit!=null&&e.unit!==""?ay(e.unit):U(e.pid)}function ay(e){let n=At("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var dy="REDSKILLED_UNIT_DISCOVERY",Ma="(unowned)";function Wa(e){let n=At("systemctl",["--user","show","--property=MainPID","--value",e],{encoding:"utf8"});if(n.error!=null||n.status!==0)return null;let t=Number.parseInt((n.stdout??"").trim(),10);return Number.isInteger(t)&&t>0?t:null}function cy(e=process.env){let n=(e[dy]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Ha(e,n,t=process.env){return cy(t)&&e===n}function Fa(e=Ot){let n=At("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return n.error!=null||n.status!==0?[]:(n.stdout??"").split(`
69
+ `).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function Ua(e){let n=new Set(e.held.map(o=>o.unit).filter(o=>o!=null&&o!=="")),t=new Set,r=[];for(let o of e.units)o===""||n.has(o)||t.has(o)||(t.add(o),r.push({worker_id:o.replace(/\.service$/,""),project_label:Ma,pid:e.mainPid?.(o)??0,started_at:e.now,workspace_path:"",isolated:!0,unit:o,warnings:[`adopted from active unit ${JSON.stringify(o)}, which has no birth on this host's event lane: its project, its Worker id and its budget belonged to a daemon that is gone, so they are reported as unknown rather than guessed \u2014 it is counted against the host budget from here on instead of running outside it`]}));return r}function Ba(e){return e.project_label.trim()!==""?e:{...e,project_label:Ma,warnings:[...e.warnings,"adopted at start with no owning project on the event lane: the daemon that birthed it recorded no project label, so it is held and counted under a stated placeholder rather than dropped"]}}function Ka(e){if(e.unit!=null&&e.unit!==""){let n=At("systemctl",["--user","stop",e.unit],{stdio:"ignore"});return n.error==null&&n.status===0}try{return process.kill(e.pid,"SIGTERM"),!0}catch{return!1}}function uy(e,n=50){if(Ja(e),!Number.isInteger(n)||n<=0)throw new Error(`redskilled queue discovery needs a whole, positive batch size, not ${JSON.stringify(n)}`);let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}function py(e,n={}){let t=n.batchSize??50;if(Ja(e),e.length>t)throw new Error(`redskilled queue discovery spans at most ${t} selectors in one query, and this batch holds ${e.length}: split it with planQueueDiscoveryBatches rather than dropping the remainder`);let r=e.map((s,a)=>({alias:`q${a}`,project:s}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...r.map(({alias:s,project:a})=>` ${s}: search(query: ${JSON.stringify(a.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
70
+ `),aliases:r}}function fy(e,n){let t=An(n),r=An(t.data),o=Array.isArray(t.errors)?t.errors.map(An):[],i=hy(r.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=yy(r[a]);if(d!=null)return{project_label:l.project_label,outcome:"counted",depth:d,detail:`project ${JSON.stringify(l.project_label)} has ${d} item(s) matching its selector`};let p=o.find(u=>gy(u.path,a));return i.exhausted||Qa(p)?{project_label:l.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(l.project_label)} answered, so this queue has no depth rather than a depth of zero`+(i.reset_at==null?"":`; the quota resets at ${i.reset_at}`)}:{project_label:l.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(l.project_label)} could not be counted with the host token: ${jo(p?.message)||"the query returned no count for this selector"}`}}),rate_limit:i}}function my(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function qa(e,n,t){return{version:1,fetched_at:n,request_count:0,project_count:e.length,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:e.map(r=>({project_label:r.project_label,outcome:"unconfigured",depth:null,detail:`project ${JSON.stringify(r.project_label)} was not counted because this host polls no tracker: ${t}`}))}}async function Ga(e){if(e.projects.length===0)return my(e.now);let n=e.batchSize??50,t=uy(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let i of t){let s=py(i,{batchSize:n});try{let a=await e.transport(s.query),l=fy(s,a);r.push(...l.projects),o=Va(o,l.rate_limit)}catch(a){let l=a instanceof Error?a.message:String(a),d=/rate limit|secondary rate|429/i.test(l);o=Va(o,{remaining:null,reset_at:null,exhausted:d});for(let p of i)r.push({project_label:p.project_label,outcome:d?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(p.project_label)} answered: ${l}`})}}return{version:1,fetched_at:e.now,request_count:t.length,project_count:r.length,batch_size:n,rate_limit:o,projects:r}}function Ja(e){if(e.length===0)throw new Error("redskilled queue discovery needs at least one registered project");let n=new Set;for(let t of e){if(typeof t.project_label!="string"||t.project_label==="")throw new Error("redskilled queue discovery needs a project label for every registered project");if(typeof t.selector!="string"||t.selector==="")throw new Error(`redskilled queue discovery needs a selector for project ${JSON.stringify(t.project_label)}: a project that names no work has no queue to discover`);if(n.has(t.project_label))throw new Error(`redskilled holds one selector per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function Va(e,n){return{remaining:n.remaining==null?e.remaining:e.remaining==null?n.remaining:Math.min(e.remaining,n.remaining),reset_at:n.reset_at??e.reset_at,exhausted:e.exhausted||n.exhausted}}function hy(e,n){let t=An(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null;return{remaining:r,reset_at:o,exhausted:n.some(Qa)||r===0}}function Qa(e){return e==null?!1:jo(e.type)==="RATE_LIMITED"||/rate limit/i.test(jo(e.message))}function gy(e,n){return Array.isArray(e)&&e.includes(n)}function yy(e){let n=An(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function An(e){return ky(e)?e:{}}function ky(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jo(e){return typeof e=="string"?e:""}function za(e,n,t){let r=e?.rate_limit;if(r==null)return n;if(r.exhausted){let i=r.reset_at==null?Number.NaN:Date.parse(r.reset_at),s=Number.isFinite(i)?i-t+1e3:n*4;return Math.min(Ry,Math.max(n,s))}let o=r.remaining;return o==null?n:o<=by?Math.max(n,3e4):o<=_y?Math.max(n,2e4):n}var Ry=3e5,by=250,_y=1e3;import{randomUUID as Za}from"node:crypto";import{spawn as vy}from"node:child_process";import{closeSync as Ey,mkdirSync as Py,openSync as jy}from"node:fs";import{dirname as Dy}from"node:path";import{delimiter as Ya,dirname as wy}from"node:path";function xy(e,n=Ya){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function Sy(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=wy(n);return t===""||t==="."?null:t}function Xa(e,n=process.execPath,t=Ya){let r=xy(e,t),o=Sy(n);return o==null?r.join(t):[o,...r.filter(i=>i!==o)].join(t)}var Ln=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},Lt=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function Oy(e){if(e==null||e.trim()==="")return null;try{return Py(Dy(e),{recursive:!0}),jy(e,"a")}catch{return null}}function Ay(e){try{Ey(e)}catch{}}function Ly(e){let n=[["project_label",e.project_label],["workspace_path",e.workspace_path],["command",e.command]];for(let[t,r]of n)if(typeof r!="string"||r.trim()==="")throw new Ln(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new Ln("redskilled worker spec args must be an array")}function $y(e){if(e==null)throw new Lt("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new Lt(e.reason,e)}function nd(e){let{spec:n,admission:t}=e;$y(t),Ly(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),i=(n.worker_id??e.workerId??Za()).trim()||Za(),s=e.probes??La(r),a=e.openLog===!1?null:Oy(n.log_path),l={...n.env??{},PATH:Xa(n.env?.PATH??r.PATH,e.execPath??process.execPath)},d=Ta({workerId:i,projectLabel:n.project_label,workspacePath:n.workspace_path,command:n.command,args:n.args,budget:n.budget,...e.memoryCeiling!=null?{memoryCeiling:e.memoryCeiling}:{},target:n.placement,env:l,enabled:e.enabled??$a(r),probes:s,pipeOutput:a!==null}),u=(e.spawnFn??vy)(d.command,d.args,{...d.cwd!=null?{cwd:d.cwd}:{},detached:!0,stdio:a===null?"ignore":["ignore",a,a],env:d.backend==="transient-unit"?{...r}:{...r,...l,...d.environment}});if(a!==null&&Ay(a),u.pid==null)throw u.once("error",()=>{}),new Ln(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${i}`);let f=d.job!=null?Iy(d,s,u.pid):null;u.once("error",()=>{}),u.once("exit",(k,w)=>{try{f?.job?.close()}catch{}e.onExit?.(i,k,w)}),u.unref();let m=d.job!=null?f?.job!=null:d.isolated,h=[d.warning,f?.warning,d.budgetWarning].filter(k=>k!=null);return{worker:{worker_id:i,project_label:n.project_label,pid:u.pid,started_at:o(),workspace_path:n.workspace_path,...n.log_path!=null?{log_path:n.log_path}:{},isolated:m,...d.unit!=null?{unit:d.unit}:{},...n.budget!=null?{budget:n.budget}:{},...Object.keys(d.budget).length>0?{applied_budget:d.budget}:{},...d.memoryCeiling!=null?{memory_ceiling:d.memoryCeiling,memory_ceiling_reason:e.memoryCeiling?.reason??"this Worker's ceiling is the budget its client declared"}:{},warnings:h},admission:t,warnings:h,plan:d,child:u,...f?.job!=null?{job:f.job}:{}}}function Iy(e,n,t){let r=e.job;if(r==null)return{};let o="the Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling";if(!n.jobObjects.available)return{warning:`Job Object placement unavailable: ${n.jobObjects.reason}. ${o}`};let i;try{i=n.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(s){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${ed(s)}. ${o}`}}try{i.assign(t)}catch(s){try{i.close()}catch{}return{warning:`Worker pid ${t} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${ed(s)}. ${o}`}}return{job:i}}function ed(e){return e instanceof Error?e.message:String(e)}import{open as Ty,stat as Ny}from"node:fs/promises";var Cy=16*1024;async function td(e,n=Cy){let t;try{t=(await Ny(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let i=await Ty(e,"r");try{let s=Buffer.alloc(r);await i.read(s,0,r,t-r),o=s.toString("utf8")}finally{await i.close()}}catch{return null}return My(o)}function My(e){let n=e.split(`
71
+ `);for(let t=n.length-1;t>=0;t-=1){let r=n[t].replace(/\r$/,"");if(r.trim()!=="")return r}return null}import{spawn as Zy}from"node:child_process";import{existsSync as ek,readdirSync as nk}from"node:fs";import{dirname as tk,join as ad,resolve as rk}from"node:path";var Wy="<version>";function _e(e,n=[],t){let r=t&&t.trim().length>0?t.trim():Wy;return[`npx -y -p ${Le}@${r}`,e,...n].join(" ")}function Z(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?{major:Number(n[1]),minor:Number(n[2]),patch:Number(n[3])}:null}function Do(e,n){let t=Z(e),r=Z(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var QS=4*60*60*1e3;fe();fe();import{spawnSync as Hy}from"node:child_process";import{mkdir as Fy,rm as Uy,writeFile as By}from"node:fs/promises";import{existsSync as Ky}from"node:fs";import{homedir as Vy}from"node:os";import{dirname as qy,join as Oo}from"node:path";var nn="redskilled.service",Ao="REDSKILLED_SUPERVISED",Gy="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function Jy(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||Oo(e.HOME?.trim()||Vy(),".config");return Oo(n,"systemd","user")}function Lo(e=process.env){return Oo(Jy(e),nn)}function rd(e,n={}){let t=n.env??process.env,r=ht(n.override??{},n.entryLookup??{}),o=[...r.args,...Ae(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:nn,unitPath:Lo(t),command:r.command,args:o,text:Qy(r.command,o,e)}}function Qy(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${Gy}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(zy).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Ao}=1"`,`Environment="REDSKILLED_SESSION=${od(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
72
+ `)}function zy(e){return/[\s"'\\$%]/.test(e)?`"${od(e)}"`:e}function od(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function id(e,n={}){let t=n.writeFile??Yy,r=n.run??$o,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push($t("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push($t("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(i=>i.ok),steps:o}}async function sd(e={}){let n=e.removeFile??Xy,t=e.run??$o,r=Lo(e.env??process.env),o=[$t("disable",t,["systemctl","--user","disable","--now",nn])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push($t("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function ld(e={}){let n=e.exists??Ky,t=e.run??$o,r=Lo(e.env??process.env),o=n(r);return{unitName:nn,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",nn]).status===0,active:o&&t(["systemctl","--user","is-active",nn]).status===0,floor:"auto-spawn"}}function $t(e,n,t){let r=n(t),o=(r.stderr??r.stdout??"").trim();return{step:e,argv:t,ok:r.status===0,...o?{detail:o}:{}}}async function Yy(e,n){await Fy(qy(e),{recursive:!0}),await By(e,n,{encoding:"utf8",mode:420})}async function Xy(e){await Uy(e,{force:!0})}function $o(e){let n=Hy(e[0],[...e.slice(1)],{encoding:"utf8"});return n.error!=null?{status:null,stderr:n.error.message}:{status:n.status,stdout:n.stdout??"",stderr:n.stderr??""}}var dd=75,ud=9e5,cd="redskilled-replacement-entry-unresolved",ok="REDSKILLED_NO_REGISTRY_PROBE",pd="REDSKILLED_BORN_BY_REPLACEMENT";function fd(e=process.env){return e[pd]==="1"}function md(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function hd(e){let n=e.running.trim();if($n(n))return null;let t=e.newest?.trim()??"",r=Z(t),o=Z(n);return r===null||o===null||r.major<=o.major?null:{version:t,running_major:o.major,held_major:r.major,reason:`redskilled ${t} is published and this daemon runs ${n}; a major version is deliberately never adopted by the background check, because a breaking change must not arrive on a machine that is holding Workers`,action:ik(r.major,e.supervised)}}function ik(e,n){let t=`install the ${e}.x bundle (update this machine's plugin pin), then `;return n?`${t}re-point the unit and restart it: ${_e("red-skills-redskilled",["unit","install"])} && systemctl --user restart redskilled.service`:`${t}stop this daemon \u2014 the next client start resolves the newly installed bundle`}function gd(e){let n=e.running.trim();if($n(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||Z(t)===null?{act:"hold",reason:"published-unknown"}:Do(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function $n(e){let n=e.trim();return Z(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function yd(e=process.env){return e[Ao]==="1"}var Io=class extends Error{code=cd;searched;constructor(n,t){super(`${cd}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
65
73
  searched:
66
74
  ${t.map(r=>` ${r}`).join(`
67
- `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function Jg(e,n={}){let t=n.env??process.env,r=n.exists??Fg,o=n.execPath??process.execPath,s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,l=[],a=[[Kl(Vn(t),i),"bundle-cache"]];s&&a.push([Kl(Ug(Vg(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 qr(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 na(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>Jg(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function ta(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??Gg)(Jl),{...e,exitCode:Jl};let o=[...e.entry.args,..._e(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??qg(r.env))(e.entry,o),e}function qg(e){return(n,t)=>{let r=Cg(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[zl]:"1"}});r.on("error",()=>{}),r.unref()}}function Gg(e){process.exitCode=e,process.exit(e)}async function ra(e,n=process.env,t=zg){let r=sa(n),o=ia(e,n);if(n[Bg]==="1")return{version:o,newest:r};let s=U(e)===null?"0.0.0":e;try{let i=await Xs({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function oa(e,n=process.env,t){let r=t??Gr;return{version:ia(e,n,r),newest:sa(n,r)}}function sa(e=process.env,n=Gr){return aa(la(e,n))}function ia(e,n=process.env,t=Gr){let r=U(e.trim())?.major;return r===void 0?null:aa(la(n,t).filter(o=>U(o)?.major===r))}function la(e,n){let t=[];for(let r of n(Vn(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||U(o)===null||t.push(o)}return t}function aa(e){let n=null;for(let t of e)(n===null||Ur(t,n)>0)&&(n=t);return n}function Gr(e){try{return Hg(e)}catch{return[]}}async function zg(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 Qg,readFile as Yg,rename as Zg,rm as zr,writeFile as da}from"node:fs/promises";import{randomUUID as Xg}from"node:crypto";import{dirname as eh}from"node:path";var it=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function Yr(e){let n;try{n=await Yg(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=nh(n);return th(t)?t:void 0}var ca;function pa(){return ca??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},ca}function ma(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??W;async function s(){return await Yr(e)}async function i(a){let d=`${e}.${a.pid}.${Xg()}.tmp`;await da(d,ua(a),{encoding:"utf8",mode:384}),await Zg(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 Qg(eh(e),{recursive:!0,mode:448});let d=!1;for(;;){let u=r(),p=l(a,u);try{return await da(e,ua(p),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:p}}catch(g){if(g.code!=="EEXIST")throw g}let m=await s();if(!m){await zr(e,{force:!0}),d=!0;continue}if(Qr(m,a))return{acquired:!0,reaped:d,lease:m};if(await o(m.pid))return{acquired:!1,lease:m};await zr(e,{force:!0}),d=!0}},async renew(a){let d=await s();if(!d||!Qr(d,a))throw new it(e);let u={...d,renewed_at:r()};return await i(u),u},async release(a){let d=await s();if(!d)return!1;if(!Qr(d,a))throw new it(e);return await zr(e,{force:!0}),!0}}}function Qr(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function ua(e){return`${I(e,{keyedMapCollapse:!0})}
68
- `}function nh(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return G(n)}catch{return null}}}function th(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 Zr=3e5,ch=1e4,uh=6e4,ph=15e3,fa=16,Ce=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},mh="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function ha(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??Zr,o=e.clock??(()=>new Date().toISOString()),s=e.launch??Ml,i=e.ceiling??di();e.repositoryActivity!=null&&Pr(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??pa(),a=e.leaseStore??ma(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??Si(),u={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},p=e.machineClaimStore??zn(n.machineClaimPath,u,{clock:o});await lh(dh(n.socketPath),{recursive:!0,mode:448});let m=await p.claim(d);if(!m.claimed)throw m.claim?.socket_path===n.socketPath?new Ce(n.socketPath):new pe(p.claimPath,m.reason,m.claim);let g=await a.acquire(l);if(!g.acquired)throw await p.release(d).catch(()=>{}),new Ce(n.socketPath,g.lease);let y;try{y=await fh(n.socketPath)}catch(c){throw await a.release(l).catch(()=>{}),await p.release(d).catch(()=>{}),c}let _=o(),k=e.eventLane??pi(n.eventLanePath),b=e.liveness??_l,D=e.stopWorker??jl,V=e.unitInventory??(()=>Sl(n.machineClaimPath,Gn({machineIdHash:n.machineIdHash}))?xl():[]),C=e.unitMainPid??vl,me=e.treeSampler??Fi,ve=e.readLogTail??Cl,Rn=e.sampleMs??ph,co=e.publishedVersion??(c=>ra(c)),uo=e.replaceCheckMs??Gl,po=e.publishedProbeTimeoutMs??ch,za=e.localPublishedEvidence??(c=>oa(c,e.replacementIO?.env??process.env)),Qa=e.bornByReplacement??Ql(),mo=e.replaceBootCheckMs??uh,fo=e.supervised??ea(),go=e.replacementIO??{},B=e.repositoryActivity,ho=B?.intervalMs??6e4,fe=e.queueDiscovery,bn=fe?.transport??B?.transport,dt=fe?.unconfiguredReason??mh,yo=fe?.intervalMs??15e3,ko=e.demandMs??15e3,Ya=e.demandBackoffMs??3e4,x=new Map,le=new Set,Se=new Map,_n=new Map,ct=[],wn=[],A=new Map,ut=new Set,Ro={},pt=null,bo=null,mt=null,_o=!1,ft=0,gt=null,Ue="none",ht=null,wo=null,yt=null,ae=null,vn=null,Ve=[],Be=null,kt=!1,xe,Ke,Je,qe,Sn,Ge,ze,Z=!1,Rt=!1,xn=null,vo,bt=new Promise(c=>{vo=c});function Qe(c){So(c);let f=Date.parse(c),h=$i(A.values(),f);for(let w of h.lapsed)A.delete(w.project_label),Za(w,f);return h.lapsed}function Za(c,f){let h=Number.isFinite(f)?new Date(f).toISOString():c.renew_by;Ve.push({project_label:c.project_label,at:h,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`}),Ve.length>fa&&Ve.splice(0,Ve.length-fa)}function So(c){if(A.size===0)return;let f=Date.parse(c);if(!Number.isFinite(f))return;let h={};for(let v of x.values())h[v.project_label]=(h[v.project_label]??0)+1;let w=new Map((ae?.projects??[]).map(v=>[v.project_label,v]));for(let v of[...A.values()]){let P=w.get(v.project_label),ee=Di(v,{now:c,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:h[v.project_label]??0});ee.registration!==v&&A.set(v.project_label,ee.registration)}}function En(){let c=o();return Qe(c),rl({now:c,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:l.pid,startedAt:_,scope:xi(p.claimPath,u,d),workers:[...x.values()],registrations:[...A.values()],lapses:Ve,queue:ae,published:{version:bo,checkedAt:mt,newer:_o,replacement:Ue,newest:ht,majorHold:wo,checks:ft,holdReason:gt}})}function Pn(){return Gi({hostState:En(),ceiling:i,rss:Ro,sampledAt:pt,logLines:Object.fromEntries(Se),displays:Object.fromEntries(_n),now:o(),reattachedWorkerIds:[...le],repositoryActivity:yt,...e.deaths===void 0?{}:{deaths:e.deaths},metrics:Mi({observations:ct,outcomes:wn,now:o()})})}function Xa(c,f){ct=Yn([...ct,{worker_id:f,observed_at:c.published_at,tokens:c.display.tokens,tools:c.display.tools,runner:c.display.runner,model:c.display.model}],h=>h.observed_at,{now:o()})}function ed(c){wn=Yn([...wn,c],f=>f.ts,{now:o()})}async function _t(){return B==null||B.projects.length===0?null:(yt=await Vi({projects:B.projects,hostTokenRef:B.hostTokenRef,transport:B.transport,closedWindowMs:B.closedWindowMs,now:o()}),yt)}function nd(){if(!(bn!=null||fe?.armTransport==null))try{let c=fe.armTransport();if(c.transport!=null){bn=c.transport;return}c.unconfiguredReason!=null&&(dt=c.unconfiguredReason)}catch(c){dt=`this host could not resolve a tracker credential: ${c instanceof Error?c.message:String(c)}`}}async function xo(){let c=o();Qe(c);let f=[...A.values()].map(h=>({project_label:h.project_label,selector:h.selector})).sort((h,w)=>h.project_label.localeCompare(w.project_label));return f.length===0?null:(nd(),bn==null?(ae=Ol(f,c,dt),ae):(ae=await $l({projects:f,transport:bn,now:c,...fe?.batchSize==null?{}:{batchSize:fe.batchSize}}),So(o()),ae))}async function Eo(){let c=o();if(kt)return vn??gi(c);kt=!0;try{let f={};for(let L of x.values())f[L.project_label]=(f[L.project_label]??0)+1;let h={};for(let L of ae?.projects??[])h[L.project_label]=L.depth;let w=Date.parse(c),v=fi({projects:[...A.values()].map(L=>({project_label:L.project_label,selector:L.selector,argv:L.argv,workspace_path:L.workspace_path,target:L.target})),queue:h,live:f,nowMs:Number.isFinite(w)?w:0,backoffUntilMs:Be}),P=[],ee=null;for(let L of v.births){let Ln;try{Ln=wt({project_label:L.project_label,workspace_path:L.workspace_path,command:L.argv[0],args:L.argv.slice(1)})}catch(xt){ee=xt instanceof Error?xt.message:String(xt),Be=(Number.isFinite(w)?w:Date.now())+Ya;break}P.push({project_label:L.project_label,worker_id:Ln.worker.worker_id,pid:Ln.worker.pid,warnings:Ln.warnings})}return ee==null&&v.births.length>0&&(Be=null),vn={version:1,at:c,requested:v.births.length,granted:P,shortfall:v.births.length-P.length,refusal:ee,retry_after:Be==null?null:new Date(Be).toISOString(),projects:v.intents},vn}finally{kt=!1}}function td(c){return zi(Pn(),{...O,mode:c?.mode??O.mode,project:c?.project??O.project,maxWorkers:c?.max_workers??O.maxWorkers,maxProjects:c?.max_projects??O.maxProjects,maxWidth:c?.max_width??O.maxWidth,verbose:c?.verbose??O.verbose})}function rd(c){return el(Pn(),{mode:c?.mode??Ne.mode,project:c?.project??Ne.project,maxWidth:c?.max_width??Ne.maxWidth,maxRows:c?.max_rows??Ne.maxRows})}function Ee(c,f,h){return Ai({op:c,sessionProject:f??null,targetProject:h})}async function od(c){let f=x.get(c.worker_id),h=Ee(Li(c.command),c.session_project,f?.project_label??null);if(!h.permitted)throw new Error(h.reason);if(c.command!=="stop")throw new Error(`redskilled does not implement ${c.command}: it owns birth, death and limits, and ${c.command} is a work decision the project's own bundle makes on top of them`);let w=f!=null&&await ad(f,c.detail??"stopped by its own project");return{version:1,command:c.command,worker_id:c.worker_id,applied:w,reach:h,detail:w?`redskilled stopped Worker ${JSON.stringify(c.worker_id)} of project ${JSON.stringify(f.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function jn(c){x.delete(c),le.delete(c),Se.delete(c),_n.delete(c)}function Po(c){let f=x.get(c.worker_id),h=Ee("worker-heartbeat",c.session_project,f?.project_label??null);if(!h.permitted)throw new Error(h.reason);if(typeof c.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(f==null)return{version:1,worker_id:c.worker_id,accepted:!1,reach:h,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to publish a line for`};let w=o();Se.set(c.worker_id,{line:c.last_log_line,published_at:w,source:"heartbeat"});let v=c.display===void 0?null:Zi(c.display);if(v!=null){let P={display:v,published_at:w};_n.set(c.worker_id,P),Xa(P,c.worker_id)}return{version:1,worker_id:c.worker_id,accepted:!0,reach:h,published_at:w,detail:`redskilled stored a line for Worker ${JSON.stringify(c.worker_id)} without reading it`}}async function sd(c,f,h){let w=`exit code=${f??"null"} signal=${h??"null"}`;if(c.unit!=null&&c.unit!==""&&await id(c)){ld(c,`its launch client ended (${w}) while unit ${JSON.stringify(c.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}jn(c.worker_id),X("worker-death",c,w,{exitCode:f,signal:h}),$()}async function id(c){try{return await b(c)===!0}catch{return!1}}function ld(c,f){let h=c.unit==null?null:C(c.unit);x.set(c.worker_id,{...c,...h!=null&&h>0?{pid:h}:{},warnings:[...c.warnings,f]}),le.add(c.worker_id),$()}function jo(c,f){let h=Ee("project-register",f,c.project_label);if(!h.permitted)throw new Error(h.reason);let w=o();Qe(w);let v=Pi(c,{now:w,held:A.get(c.project_label)});return A.set(v.project_label,v),$(),{version:1,registration:v,reach:h,detail:`redskilled holds a registration for project ${JSON.stringify(v.project_label)} at a target of ${v.target} until ${v.renew_by}, and has read neither its selector nor its argv`}}function Do(c,f={}){let h=Ee("project-renew",f.sessionProject,c);if(!h.permitted)throw new Error(h.reason);let w=o();Qe(w);let v=A.get(c);if(v==null)throw new Qn(c);let P=ji(v,{now:w,...f.renewWithinMs==null?{}:{renew_within_ms:f.renewWithinMs},...f.launch==null?{}:{launch:f.launch}});return A.set(P.project_label,P),$(),{version:1,registration:P,reach:h,detail:`redskilled renewed the registration for project ${JSON.stringify(P.project_label)}, which now stands until ${P.renew_by} after renewal ${P.renewals}`+(f.launch==null?"":`, carrying launch revision ${P.launch_revision} for its next Worker`)}}function Oo(c,f){let h=Ee("project-deregister",f,c);if(!h.permitted)throw new Error(h.reason);let w=A.delete(c);return{version:1,project_label:c,released:w,reach:h,detail:w?`redskilled released the registration for project ${JSON.stringify(c)}`:`redskilled held no registration for project ${JSON.stringify(c)}, so there was nothing to release`}}async function ad(c,f){try{await D(c)}catch{}return jn(c.worker_id),X("worker-death",c,f),$(),!0}function $o(c){return li({ceiling:i,workers:[...x.values()],budget:c.budget,projectLabel:c.project_label})}function wt(c){let f=ai({ceiling:i,workers:[...x.values()],budget:c.budget}),h=s({spec:c,admission:$o(c),memoryCeiling:f,clock:o,onExit:(w,v,P)=>{let ee=x.get(w);if(ee==null){$();return}sd(ee,v,P).catch(()=>{})}});return x.set(h.worker.worker_id,h.worker),X("worker-birth",h.worker,null),$(),h}function X(c,f,h,w={}){if(Z)return;let v=o();(c==="worker-death"||c==="worker-budget-kill")&&ed({worker_id:f.worker_id,ts:v,outcome:c}),k.record({event:c,worker:f,ts:v,detail:h,...w.exitCode!==void 0?{exitCode:w.exitCode}:{},...w.signal!==void 0?{signal:w.signal}:{}}).catch(()=>{})}async function Lo(){let c=[...le].map(h=>x.get(h)).filter(h=>h!=null);if(c.length===0)return[];let{dead:f}=await Fr(c,b);for(let h of f)jn(h.worker_id),X("worker-death",h,"the host no longer confirms this Worker");return f.length>0&&$(),f}async function Ao(c,f){let h=x.get(c);if(!h)return!1;try{await D(h)}catch{}return jn(c),X("worker-budget-kill",h,f),$(),!0}async function Io(){let c=[...x.values()];if(c.length===0)return[];let f;try{f=await me(c)}catch{return[]}let h=f.rss;Ro=h,pt=o(),dd(f.cpu_seconds,pt);let{terminations:w}=Ci({workers:c,rss:h}),v=[];for(let P of w)await Ao(P.worker_id,P.reason)&&v.push(P);return v}function dd(c,f){for(let[h,w]of Object.entries(c)){if(typeof w!="number"||!Number.isFinite(w))continue;let v=x.get(h);v&&x.set(h,{...v,cpu:{cpu_seconds:w,sampled_at:f}})}}async function cd(){try{return po<=0?await co(t):await new Promise(c=>{let f=setTimeout(()=>c(vt()),po);f.unref(),co(t).then(h=>{clearTimeout(f),c(h)},()=>{clearTimeout(f),c(vt())})})}catch{return vt()}}function vt(){try{return za(t)}catch{return null}}async function To(){if(yn(t))return ft+=1,mt=o(),gt="local-build",{act:"hold",reason:"local-build"};let c=Yl(await cd()),f=c.version;bo=f,ht=c.newest??null,mt=o(),wo=Zl({running:t,newest:ht,supervised:fo});let h=Xl({running:t,published:f,supervised:fo});return _o=h.act==="replace",ft+=1,gt=h.act==="hold"?h.reason:null,Ue!=="in-progress"&&(Ue=h.act==="replace"?"pending":"none"),h}async function Dn(){let c=await To();if(c.act!=="replace"||Ue==="in-progress")return c;let f=na(c,go);return Ue="in-progress",await k.flush().catch(()=>{}),await $n({reason:"replaced"}),ta(f,n,{...r==null?{}:{idleMs:r},io:go}),c}function ud(){Z||qe!=null||uo<=0||(!Qa&&mo>0&&(Sn=setTimeout(()=>{Dn().catch(()=>{})},mo),Sn.unref()),qe=setInterval(()=>{Dn().catch(()=>{})},uo),qe.unref())}function pd(){Z||Ke!=null||Rn<=0||(Ke=setInterval(()=>{Io().catch(()=>{})},Rn),Ke.unref())}function md(){Z||Ge!=null||B==null||B.projects.length===0||ho<=0||(_t().catch(()=>{}),Ge=setInterval(()=>{_t().catch(()=>{})},ho),Ge.unref())}function fd(){Z||ze!=null||yo<=0||(ze=setInterval(()=>{xo().catch(()=>{})},yo),ze.unref())}function gd(){Z||Je!=null||ko<=0||(Je=setInterval(()=>{Eo().catch(()=>{})},ko),Je.unref())}function $(){Z||(xe&&clearTimeout(xe),xe=setTimeout(()=>{Lo().catch(()=>{}).then(()=>No())},r),xe.unref())}function No(){return x.size>0?($(),"held-by-workers"):(Qe(o()),A.size>0?($(),"held-by-registrations"):(hd(),"exited"))}async function hd(){if(!yn(t)){if((await Dn().catch(()=>null))?.act==="replace"||Rt||Z)return;if(x.size>0||A.size>0){$();return}}await $n({reason:"idle"})}function On(c){return yi({reason:c,socketPath:n.socketPath,daemonVersion:t,pid:l.pid,workers:[...x.values()],projects:[...A.keys()]})}function Wo(c){if(xn!=null)return xn;let f=c.reason??"requested",h=c.note?.trim();return xn=k.recordDaemonStop({ts:o(),pid:l.pid,socketPath:n.socketPath,reason:f,detail:h==null||h===""?On(f).detail:`${On(f).detail} \u2014 ${h}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),xn}async function $n(c={}){if(Rt)return await bt;Rt=!0,await Wo(c),Z=!0,xe&&clearTimeout(xe),Ke&&clearInterval(Ke),qe&&clearInterval(qe),Sn&&clearTimeout(Sn),Ge&&clearInterval(Ge),ze&&clearInterval(ze),Je&&clearInterval(Je),await k.flush().catch(()=>{}),y.close();for(let f of ut)f.destroy();return await new Promise(f=>y.once("close",()=>f())),await ga(n.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await p.release(d).catch(()=>{}),vo(),await bt}let Mo=await k.read().catch(()=>[]);wn=Yn(Mo.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 yd=mi(Mo),St=await Fr(yd,b);for(let c of St.alive){let f=Pl(c),h=f.unit==null||W(f.pid)?null:C(f.unit);x.set(f.worker_id,h!=null&&h>0?{...f,pid:h}:f),le.add(f.worker_id)}for(let c of St.dead)X("worker-death",c,"the Worker ended while no daemon was watching");let kd=El({units:await Promise.resolve(V()).catch(()=>[]),held:[...x.values()],mainPid:C,now:_});for(let c of kd)x.set(c.worker_id,c),le.add(c.worker_id),X("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of St.alive){if(c.log_path==null||Se.has(c.worker_id))continue;let f=await ve(c.log_path).catch(()=>null);f==null||f.trim()===""||Se.set(c.worker_id,{line:f,published_at:o(),source:"rehydrated"})}y.on("connection",c=>{ut.add(c),c.once("close",()=>ut.delete(c)),$(),gh(c,async(f,h)=>{$();let w=await Rd(f);h(w),f.op==="shutdown"&&setImmediate(()=>void $n({reason:"requested"}))})});async function Rd(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:et,daemon_version:t,pid:l.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:En()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:Pn()};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:td(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:rd(c.dashboard)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:Po(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:jo(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:Do(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:Oo(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await od(c.command)};if(c.op==="worker-start"){let h=Ee("worker-start",c.session_project,c.spec.project_label);if(!h.permitted)return{id:c.id,ok:!1,error:h.reason};let w=wt(c.spec);return await k.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:w.worker,admission:w.admission,warnings:w.warnings}}}if(c.op==="shutdown"){let h=On("requested");return await Wo({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:h}}let f=c;return{id:f.id??lt(),ok:!1,error:`unsupported redskilled op: ${f.op??"unknown"}`}}catch(f){return{id:c.id??lt(),ok:!1,error:f instanceof Error?f.message:String(f)}}}return $(),pd(),ud(),md(),fd(),gd(),{socketPath:n.socketPath,lease:g.lease,startedAt:_,closed:bt,startWorker:wt,admit:$o,ceiling:()=>i,killWorkerOverBudget:Ao,sampleMemoryBudgets:Io,pollRepositoryActivity:_t,pollQueueDiscovery:xo,queueDiscovery:()=>ae,driveDemand:Eo,demand:()=>vn,sweepReattached:Lo,publishWorkerHeartbeat:Po,reattached:()=>[...le].map(c=>x.get(c)).filter(c=>c!=null),flushEvents:()=>k.flush(),trackWorker(c){x.set(c.worker_id,c),X("worker-birth",c,null),$()},releaseWorker(c){let f=x.get(c),h=x.delete(c);return le.delete(c),Se.delete(c),_n.delete(c),f&&X("worker-death",f,"released by the daemon"),$(),h},workerCount:()=>x.size,registerProject:jo,renewProject:Do,deregisterProject:Oo,registrations:()=>En().registrations??[],hostState:En,statuslinePayload:Pn,evaluateIdle:No,observePublishedVersion:To,checkForReplacement:Dn,stopReport:On,stop:$n}}async function fh(e){for(let n=0;n<2;n++){let t=ah();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 se(e))throw new Ce(e);await ga(e,{force:!0})}}throw new Ce(e)}async function se(e,n=250){try{return(await Fn({socketPath:e,timeoutMs:n},{id:lt(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function gh(e,n){Gs(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??lt(),ok:!1,error:t instanceof Error?t.message:String(t)})})}re();var bh=1e4,Fe=class extends Error{constructor(t,r){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}`);this.socketPath=t;this.cause=r;this.name="RedskilledUnreachableError"}};async function Xr(e,n={}){try{return await _h(e,n)}catch(t){throw t instanceof pe||t instanceof Fe?t:new Fe(e.socketPath,t)}}async function _h(e,n){if(await yh(Rh(e.socketPath),{recursive:!0,mode:448}),await se(e.socketPath))return"already-running";await wh(e);let t=await zs(e.lockPath);if(!t)return await ya(e,n),"joined";try{if(await se(e.socketPath))return"already-running";let r=await xh(e,n);return await ya(e,n,r),"spawned"}finally{await t.close(),await kh(e.lockPath,{force:!0})}}async function wh(e){let t=await zn(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&W(t.pid))throw new pe(e.machineClaimPath,"held",t)}async function Ra(e,n,t={}){await Xr(e,t);let r;try{r=await fn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:ka()})}catch(o){throw new Fe(e.socketPath,o)}if(!r.ok)throw new Error(r.error);return r.value}async function ba(e,n={},t={}){if(!await se(e.socketPath))return ki(e.socketPath);let r;try{r=await fn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:ka(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new Fe(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!kr(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await vh(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 vh(e,n){let t=Date.now()+n;for(;;){if(!await se(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function _a(e,n={}){let t=await Ra(e,{op:"host-state"},n);if(!ol(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function wa(e,n=void 0,t={}){let r=await Ra(e,{op:"statusline-string",...t.sessionProject!=null?{session_project:t.sessionProject}:{},...n==null?{}:{render:Sh(n)}},t);if(!tl(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function Sh(e){return{mode:e.mode,project:e.project,max_workers:e.maxWorkers,max_projects:e.maxProjects,max_width:e.maxWidth,verbose:e.verbose}}async function ya(e,n,t){let r=Date.now()+(n.readyTimeoutMs??bh);for(;;){if(await se(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=r){let o=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${o}`)}await new Promise(o=>setTimeout(o,25))}}async function xh(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await ri({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,..._e(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=hh(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}re();import{chmod as Da,mkdir as $a,readFile as La,stat as Nh,writeFile as Wh}from"node:fs/promises";import{homedir as to}from"node:os";import{dirname as Mh,join as ro}from"node:path";import{join as Eh}from"node:path";var va=["local","tmp","host"],Ph="local",kn="plugins.dev.workspace.target";var eo=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function xa(e){let n=Le(e,kn),t=Oh(n??"").trim();return t===""?void 0:t}function Ea(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:Ph};let t=va.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 eo(`${kn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${va.join(", ")}) or an absolute parent directory for Workers.`)}function Pa(e,n){return e.kind==="preset"?e.preset==="host":Dh(jh(e.parentDir,n),be(n))}function jh(e,n){return e==="~"?Sa(n):e.startsWith("~/")?Eh(n,e.slice(2)):Sa(e)}function Dh(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Sa(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function Oh(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}re();import{createHash as $h}from"node:crypto";import{hostname as Lh}from"node:os";import{join as at}from"node:path";var He="redskilled.sock",Ah="REDSKILLED_SESSION";function Ih(e={}){let n=e.env??process.env,t=n[Ah]?.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 Th(e={}){return ja(e.host??Lh())}function ie(e={}){let n=Ih(e),t=e.runtimeDir??Hn({key:`redskilled:${n}`,socketFileName:He,env:e.env,uid:e.uid}),r=Th(e);return{sessionKey:n,sessionKeyHash:ja(n),machineIdHash:r,runtimeDir:t,socketPath:at(t,He),lockPath:at(t,"redskilled.spawn.lock"),leasePath:at(t,"redskilled.lease.toon"),eventLanePath:at(t,ui),machineClaimPath:e.machineClaimPath??Gn({env:e.env,machineIdHash:r,platform:e.platform})}}function ja(e){return $h("sha256").update(e).digest("hex").slice(0,12)}var no="run `/red-setup` (Section E3 \u2014 execution daemon), or `redskilled provision` directly";async function Aa(e=to()){let n=be(e),t=await so(n);return t===void 0?(await $a(n,{recursive:!0,mode:z}),await Da(n,z),{path:n,created:!0,tightened:!1,mode:z}):t===z?{path:n,created:!1,tightened:!1,mode:t}:(await Da(n,z),{path:n,created:!1,tightened:!0,mode:z})}var Ia={needed:!1,declaredBy:`no ${kn} in view`};async function oo(e={}){let n=e.homeDir??to(),t=e.declaredTarget?.trim();if(t)return Oa(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return Ia;let o=ro(r,".red","config.yaml"),s=await La(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=xa(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Oa(i,n,o)}function Oa(e,n,t){let r=`${kn}: ${e} (${t})`;try{return{needed:Pa(Ea(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function Ta(e){let n=[Ch(e),Fh(e),Hh(e),Uh(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 Ch(e){let n=e.homeNeed??Ia;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:no}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??z;return t!==z?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${z.toString(8)}`,fix:`${no} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function Fh(e){return Y(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 `redskilled provision`"}}function Hh(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:`${no} \u2014 it starts the daemon and waits for the socket`}}function Uh(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 Na(e={}){let n=e.env??process.env,t=e.homeDir??to(),r=e.paths??ie({env:n}),o=be(t),[s,i,l]=await Promise.all([so(o),se(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):oo({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:ue(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await Bh(Kh(e,n,t),n)}}var Vh="redskilled.service";function Wa(e){return ro(e,"systemd","user",Vh)}function Ma(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(`
69
- `)}async function Ca(e){let n=Wa(e.configHome);return await so(n)!==void 0?{path:n,status:"already-present"}:(await $a(Mh(n),{recursive:!0}),await Wh(n,e.unit,"utf8"),{path:n,status:"installed"})}async function Bh(e,n){if(process.platform!=="linux")return"unsupported";try{return await La(Wa(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function Kh(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??ro(t,".config")}async function so(e){try{return(await Nh(e)).mode&511}catch{return}}import{readdir as Ha,rm as Jh,stat as qh}from"node:fs/promises";import{dirname as Gh,join as io}from"node:path";var zh=5*6e4,Qh="redskilled.";function Yh(e={}){let n=e.env??process.env,t=i=>Gh(Hn({key:"redskilled:reclaim-probe",socketFileName:He,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 Ua(e={}){let n=e.roots??Yh(e),t=e.graceMs??zh,r=e.now??Date.now,o=e.isPidAlive??W,s=e.answers??ny,i=e.dryRun===!0,l=[];for(let a of n){let d;try{d=(await Ha(a,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name)}catch{continue}for(let u of d.sort())l.push(await Zh(io(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 Zh(e,n){let t;try{t=(await Ha(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:Va(i),removed:[]}}let r=t.filter(i=>i.startsWith(Qh));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await Xh(io(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 Fa(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(He)&&await n.answers(io(e,He)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await ey(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 Fa(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function Fa(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await Jh(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:Va(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function Xh(e){try{return await Yr(e)}catch{return}}async function ey(e,n){try{return Math.max(0,n()-(await qh(e)).mtimeMs)}catch{return}}async function ny(e){try{return(await fn({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function Va(e){return e instanceof Error?e.message:String(e)}var ty="plugins.dev.statusline",ry="dev.statusline";function oy(e){let n=[],t=l=>{for(let a of[ty,ry]){let d=`${a}.${l}`,u=Le(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 sy={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 Ba(e){let{values:n,positionals:t}=ke(e,sy),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 Ka(e={}){let n=e.configText==null?{config:{},warnings:[]}:oy(e.configText),t=e.flags??{};return{options:{...O,mode:t.mode??n.config.mode??O.mode,project:t.project!==void 0?t.project:e.project??O.project,maxWorkers:t.maxWorkers??n.config.maxWorkers??O.maxWorkers,maxProjects:t.maxProjects??n.config.maxProjects??O.maxProjects,maxWidth:t.maxWidth??n.config.maxWidth??O.maxWidth,verbose:t.verbose??n.config.verbose??O.verbose},warnings:n.warnings}}var ly=`Usage: redskilled <command> [options]
75
+ `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function sk(e,n={}){let t=n.env??process.env,r=n.exists??ek,o=n.execPath??process.execPath,i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,s=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[ad(mt(t),s),"bundle-cache"]];i&&l.push([ad(tk(rk(i)),s),"caller-sibling-bundle"]);for(let[d,p]of l)if(a.push(d),r(d))return{command:o,args:[d],version:e,source:p,searched:a};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new Io(e,a);return{command:t.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:a}}function kd(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>sk(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function Rd(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??ak)(dd),{...e,exitCode:dd};let o=[...e.entry.args,...Ae(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??lk(r.env))(e.entry,o),e}function lk(e){return(n,t)=>{let r=Zy(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[pd]:"1"}});r.on("error",()=>{}),r.unref()}}function ak(e){process.exitCode=e,process.exit(e)}async function bd(e,n=process.env,t=dk){let r=wd(n),o=xd(e,n);if(n[ok]==="1")return{version:o,newest:r};let i=Z(e)===null?"0.0.0":e;try{let s=await il({fetchText:t},i);return{version:s.sameMajor??o,newest:s.newest??r}}catch{return{version:o,newest:r}}}function _d(e,n=process.env,t){let r=t??To;return{version:xd(e,n,r),newest:wd(n,r)}}function wd(e=process.env,n=To){return vd(Sd(e,n))}function xd(e,n=process.env,t=To){let r=Z(e.trim())?.major;return r===void 0?null:vd(Sd(n,t).filter(o=>Z(o)?.major===r))}function Sd(e,n){let t=[];for(let r of n(mt(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||Z(o)===null||t.push(o)}return t}function vd(e){let n=null;for(let t of e)(n===null||Do(t,n)>0)&&(n=t);return n}function To(e){try{return nk(e)}catch{return[]}}async function dk(e){let n=await fetch(e,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`registry read failed with HTTP ${n.status}`);return await n.text()}import{mkdir as ck,readFile as uk,rename as pk,rm as No,writeFile as Ed}from"node:fs/promises";import{randomUUID as fk}from"node:crypto";import{dirname as mk}from"node:path";var It=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function In(e){let n;try{n=await uk(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=hk(n);return gk(t)?t:void 0}var Pd;function Dd(){return Pd??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Pd}function Od(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??U;async function i(){return await In(e)}async function s(l){let d=`${e}.${l.pid}.${fk()}.tmp`;await Ed(d,jd(l),{encoding:"utf8",mode:384}),await pk(d,e)}function a(l,d){return{version:1,pid:l.pid,start_time:l.startTime,session_key_hash:n.sessionKeyHash,machine_id_hash:n.machineIdHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}return{read:i,async acquire(l){await ck(mk(e),{recursive:!0,mode:448});let d=!1;for(;;){let p=r(),u=a(l,p);try{return await Ed(e,jd(u),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:u}}catch(m){if(m.code!=="EEXIST")throw m}let f=await i();if(!f){await No(e,{force:!0}),d=!0;continue}if(Co(f,l))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await No(e,{force:!0}),d=!0}},async renew(l){let d=await i();if(!d||!Co(d,l))throw new It(e);let p={...d,renewed_at:r()};return await s(p),p},async release(l){let d=await i();if(!d)return!1;if(!Co(d,l))throw new It(e);return await No(e,{force:!0}),!0}}}function Co(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function jd(e){return`${M(e,{keyedMapCollapse:!0})}
76
+ `}function hk(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Y(n)}catch{return null}}}function gk(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||!Number.isInteger(n.pid)||n.pid<=0)return!1;for(let t of["start_time","session_key_hash","machine_id_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var Mo=3e5,Sk=1e4,vk=6e4,Ek=15e3,Pk=3e4,Ad=16,tn=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},jk="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function $d(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??Mo,o=e.clock??(()=>new Date().toISOString()),i=e.launch??nd,s=e.ceiling??gl();e.repositoryActivity!=null&&mo(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??Dd(),l=e.leaseStore??Od(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??$l(),p={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},u=e.machineClaimStore??_t(n.machineClaimPath,p,{clock:o});await _k(xk(n.socketPath),{recursive:!0,mode:448});let f=await u.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new tn(n.socketPath):new be(u.claimPath,f.reason,f.claim);let m=await l.acquire(a);if(!m.acquired)throw await u.release(d).catch(()=>{}),new tn(n.socketPath,m.lease);let h;try{h=await Dk(n.socketPath)}catch(c){throw await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),c}let b=o(),k=e.eventLane??Rl(n.eventLanePath),w=e.liveness??Ca,j=e.stopWorker??Ka,ne=e.unitInventory??(()=>Ha(n.machineClaimPath,bt({machineIdHash:n.machineIdHash}))?Fa():[]),q=e.unitMainPid??Wa,we=e.treeSampler??zl,Ne=e.readLogTail??td,Cn=e.sampleMs??Ek,Xo=e.leaseRenewMs??Pk,Zo=e.publishedVersion??(c=>bd(c)),ei=e.replaceCheckMs??ud,ni=e.publishedProbeTimeoutMs??Sk,mc=e.localPublishedEvidence??(c=>_d(c,e.replacementIO?.env??process.env)),hc=e.bornByReplacement??fd(),ti=e.replaceBootCheckMs??vk,ri=e.supervised??yd(),oi=e.replacementIO??{},te=e.repositoryActivity,ii=te?.intervalMs??fo,xe=e.queueDiscovery,Mn=xe?.transport??te?.transport,Ct=xe?.unconfiguredReason??jk,Mt=xe?.intervalMs??15e3,si=e.demandMs??15e3,gc=e.demandBackoffMs??3e4,v=new Map,ge=new Set,Ce=new Map,Wn=new Map,Wt=[],Hn=[],I=new Map,Ht=new Set,li={},Ft=null,ai=null,Ut=null,di=!1,Bt=0,Kt=null,on="none",Vt=null,ci=null,qt=null,de=null,Fn=null,sn=[],ln=null,Un={},Gt=!1,Me,an,dn,cn,un,Bn,pn,Se,G=!1,Jt=!1,Kn=null,ui,Qt=new Promise(c=>{ui=c});function fn(c){pi(c);let g=Date.parse(c),y=Fl(I.values(),g);for(let _ of y.lapsed)I.delete(_.project_label),yc(_,g);return y.lapsed}function yc(c,g){let y=Number.isFinite(g)?new Date(g).toISOString():c.renew_by;sn.push({project_label:c.project_label,at:y,renew_by:c.renew_by,renewals:c.renewals,sustains:c.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(c.project_label)}: it stood until ${c.renew_by} and nothing renewed it \u2014 no session spoke for it, and no poll found it work or a Worker to hold it up`}),sn.length>Ad&&sn.splice(0,sn.length-Ad)}function pi(c){if(I.size===0)return;let g=Date.parse(c);if(!Number.isFinite(g))return;let y={};for(let x of v.values())y[x.project_label]=(y[x.project_label]??0)+1;let _=new Map((de?.projects??[]).map(x=>[x.project_label,x]));for(let x of[...I.values()]){let P=_.get(x.project_label),ue=Wl(x,{now:c,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:y[x.project_label]??0});ue.registration!==x&&I.set(x.project_label,ue.registration)}}function Vn(){let c=o();return fn(c),Ra({now:c,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:a.pid,startedAt:b,scope:Il(u.claimPath,p,d),workers:[...v.values()],hostCeilingBytes:s.memory_bytes,registrations:[...I.values()],lapses:sn,queue:de,published:{version:ai,checkedAt:Ut,newer:di,replacement:on,newest:Vt,majorHold:ci,checks:Bt,holdReason:Kt}})}function qn(){return ca({hostState:Vn(),ceiling:s,rss:li,sampledAt:Ft,logLines:Object.fromEntries(Ce),displays:Object.fromEntries(Wn),now:o(),reattachedWorkerIds:[...ge],repositoryActivity:qt,...e.deaths===void 0?{}:{deaths:e.deaths},metrics:Jl({observations:Wt,outcomes:Hn,now:o()})})}function kc(c,g){Wt=xt([...Wt,{worker_id:g,observed_at:c.published_at,tokens:c.display.tokens,tools:c.display.tools,runner:c.display.runner,model:c.display.model}],y=>y.observed_at,{now:o()})}function Rc(c){Hn=xt([...Hn,c],g=>g.ts,{now:o()})}async function zt(){return te==null||te.projects.length===0?null:(qt=await ia({projects:te.projects,hostTokenRef:te.hostTokenRef,transport:te.transport,closedWindowMs:te.closedWindowMs,now:o()}),qt)}function bc(){if(!(Mn!=null||xe?.armTransport==null))try{let c=xe.armTransport();if(c.transport!=null){Mn=c.transport;return}c.unconfiguredReason!=null&&(Ct=c.unconfiguredReason)}catch(c){Ct=`this host could not resolve a tracker credential: ${c instanceof Error?c.message:String(c)}`}}async function fi(){let c=o();fn(c);let g=[...I.values()].map(y=>({project_label:y.project_label,selector:y.selector})).sort((y,_)=>y.project_label.localeCompare(_.project_label));return g.length===0?null:(bc(),Mn==null?(de=qa(g,c,Ct),de):(de=await Ga({projects:g,transport:Mn,now:c,...xe?.batchSize==null?{}:{batchSize:xe.batchSize}}),pi(o()),de))}async function mi(){let c=o();if(Gt)return Fn??wl(c);Gt=!0;try{let g={};for(let O of v.values())g[O.project_label]=(g[O.project_label]??0)+1;let y={};for(let O of de?.projects??[])y[O.project_label]=O.depth;let _=Date.parse(c),x=_l({projects:[...I.values()].map(O=>({project_label:O.project_label,selector:O.selector,argv:O.argv,workspace_path:O.workspace_path,target:O.target})),queue:y,live:g,nowMs:Number.isFinite(_)?_:0,backoffUntilMs:ln,birthHaltUntilMs:Sl(Un,Number.isFinite(_)?_:0)}),P=[],ue=null;for(let O of x.births){let He,Uc=Tn(),Yn=I.get(O.project_label),ji=Nl({argv:O.argv,...Yn?.env==null?{}:{env:Yn.env},...Yn?.log_path==null?{}:{log_path:Yn.log_path}},{worker_id:Uc,slot:O.index,workspace_path:O.workspace_path},{project_label:O.project_label});try{He=Yt(ji)}catch(er){ue=er instanceof Error?er.message:String(er),ln=(Number.isFinite(_)?_:Date.now())+gc;break}P.push({project_label:O.project_label,worker_id:He.worker.worker_id,pid:He.worker.pid,warnings:ji.log_path==null?[...He.warnings,`project ${JSON.stringify(O.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(He.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:He.warnings})}return ue==null&&x.births.length>0&&(ln=null),Fn={version:1,at:c,requested:x.births.length,granted:P,shortfall:x.births.length-P.length,refusal:ue,retry_after:ln==null?null:new Date(ln).toISOString(),projects:x.intents},Fn}finally{Gt=!1}}function _c(c){return ua(qn(),{...$,mode:c?.mode??$.mode,project:c?.project??$.project,maxWorkers:c?.max_workers??$.maxWorkers,maxProjects:c?.max_projects??$.maxProjects,maxWidth:c?.max_width??$.maxWidth,verbose:c?.verbose??$.verbose})}function wc(c){return ga(qn(),{mode:c?.mode??Ze.mode,project:c?.project??Ze.project,maxWidth:c?.max_width??Ze.maxWidth,maxRows:c?.max_rows??Ze.maxRows})}function We(c,g,y){return Bl({op:c,sessionProject:g??null,targetProject:y})}async function xc(c){let g=v.get(c.worker_id),y=We(Ul(c.command),c.session_project,g?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(c.command!=="stop")throw new Error(`redskilled does not implement ${c.command}: it owns birth, death and limits, and ${c.command} is a work decision the project's own bundle makes on top of them`);let _=g!=null&&await jc(g,c.detail??"stopped by its own project");return{version:1,command:c.command,worker_id:c.worker_id,applied:_,reach:y,detail:_?`redskilled stopped Worker ${JSON.stringify(c.worker_id)} of project ${JSON.stringify(g.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function Gn(c){v.delete(c),ge.delete(c),Ce.delete(c),Wn.delete(c)}function hi(c){let g=v.get(c.worker_id),y=We("worker-heartbeat",c.session_project,g?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(typeof c.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(g==null)return{version:1,worker_id:c.worker_id,accepted:!1,reach:y,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to publish a line for`};let _=o();Ce.set(c.worker_id,{line:c.last_log_line,published_at:_,source:"heartbeat"});let x=c.display===void 0?null:ma(c.display);if(x!=null){let P={display:x,published_at:_};Wn.set(c.worker_id,P),kc(P,c.worker_id)}return{version:1,worker_id:c.worker_id,accepted:!0,reach:y,published_at:_,detail:`redskilled stored a line for Worker ${JSON.stringify(c.worker_id)} without reading it`}}async function Sc(c,g,y){let _=`exit code=${g??"null"} signal=${y??"null"}`;if(c.unit!=null&&c.unit!==""&&await Ec(c)){Pc(c,`its launch client ended (${_}) while unit ${JSON.stringify(c.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}Gn(c.worker_id),ce("worker-death",c,_,{exitCode:g,signal:y}),T()}function vc(c,g){if(!Number.isFinite(g)||g<0){Un[c]=Rt;return}let y=Un[c]??Rt,_=xl(y,g,Date.parse(o()));Un[c]=_,_.haltUntilMs!=null&&y.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(c)} lost ${_.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(_.haltUntilMs).toISOString()}
77
+ `)}async function Ec(c){try{return await w(c)===!0}catch{return!1}}function Pc(c,g){let y=c.unit==null?null:q(c.unit);v.set(c.worker_id,{...c,...y!=null&&y>0?{pid:y}:{},warnings:[...c.warnings,g]}),ge.add(c.worker_id),T()}function gi(c,g){let y=We("project-register",g,c.project_label);if(!y.permitted)throw new Error(y.reason);let _=o();fn(_);let x=Cl(c,{now:_,held:I.get(c.project_label)});return I.set(x.project_label,x),T(),{version:1,registration:x,reach:y,detail:`redskilled holds a registration for project ${JSON.stringify(x.project_label)} at a target of ${x.target} until ${x.renew_by}, and has read neither its selector nor its argv`}}function yi(c,g={}){let y=We("project-renew",g.sessionProject,c);if(!y.permitted)throw new Error(y.reason);let _=o();fn(_);let x=I.get(c);if(x==null)throw new wt(c);let P=Ml(x,{now:_,...g.renewWithinMs==null?{}:{renew_within_ms:g.renewWithinMs},...g.launch==null?{}:{launch:g.launch}});return I.set(P.project_label,P),T(),{version:1,registration:P,reach:y,detail:`redskilled renewed the registration for project ${JSON.stringify(P.project_label)}, which now stands until ${P.renew_by} after renewal ${P.renewals}`+(g.launch==null?"":`, carrying launch revision ${P.launch_revision} for its next Worker`)}}function ki(c,g){let y=We("project-deregister",g,c);if(!y.permitted)throw new Error(y.reason);let _=I.delete(c);return{version:1,project_label:c,released:_,reach:y,detail:_?`redskilled released the registration for project ${JSON.stringify(c)}`:`redskilled held no registration for project ${JSON.stringify(c)}, so there was nothing to release`}}async function jc(c,g){try{await j(c)}catch{}return Gn(c.worker_id),ce("worker-death",c,g),T(),!0}function Ri(c){return ml({ceiling:s,workers:[...v.values()],budget:c.budget,projectLabel:c.project_label})}function Yt(c){let g=hl({ceiling:s,workers:[...v.values()],budget:c.budget}),y=i({spec:c,admission:Ri(c),memoryCeiling:g,clock:o,onExit:(_,x,P)=>{let ue=v.get(_);if(ue==null){T();return}Sc(ue,x,P).catch(()=>{})}});return v.set(y.worker.worker_id,y.worker),ce("worker-birth",y.worker,null),T(),y}function ce(c,g,y,_={}){if(G)return;let x=o();(c==="worker-death"||c==="worker-budget-kill")&&(Rc({worker_id:g.worker_id,ts:x,outcome:c}),vc(g.project_label,Date.parse(x)-Date.parse(g.started_at))),k.record({event:c,worker:g,ts:x,detail:y,..._.exitCode!==void 0?{exitCode:_.exitCode}:{},..._.signal!==void 0?{signal:_.signal}:{}}).catch(()=>{})}async function bi(){let c=[...ge].map(y=>v.get(y)).filter(y=>y!=null);if(c.length===0)return[];let{dead:g}=await Po(c,w);for(let y of g)Gn(y.worker_id),ce("worker-death",y,"the host no longer confirms this Worker");return g.length>0&&T(),g}async function _i(c,g){let y=v.get(c);if(!y)return!1;try{await j(y)}catch{}return Gn(c),ce("worker-budget-kill",y,g),T(),!0}async function wi(){let c=[...v.values()];if(c.length===0)return[];let g;try{g=await we(c)}catch{return[]}let y=g.rss;li=y,Ft=o(),Dc(g.cpu_seconds,Ft),Oc(g.sources);let{terminations:_}=Ql({workers:c,rss:y,...g.sources==null?{}:{sources:g.sources}}),x=[];for(let P of _)await _i(P.worker_id,P.reason)&&x.push(P);return x}function Dc(c,g){for(let[y,_]of Object.entries(c)){if(typeof _!="number"||!Number.isFinite(_))continue;let x=v.get(y);x&&v.set(y,{...x,cpu:{cpu_seconds:_,sampled_at:g}})}}function Oc(c){for(let[g,y]of Object.entries(c??{})){let _=v.get(g);_&&v.set(g,{..._,rss_source:y})}}async function Ac(){try{return ni<=0?await Zo(t):await new Promise(c=>{let g=setTimeout(()=>c(Xt()),ni);g.unref(),Zo(t).then(y=>{clearTimeout(g),c(y)},()=>{clearTimeout(g),c(Xt())})})}catch{return Xt()}}function Xt(){try{return mc(t)}catch{return null}}async function xi(){if($n(t))return Bt+=1,Ut=o(),Kt="local-build",{act:"hold",reason:"local-build"};let c=md(await Ac()),g=c.version;ai=g,Vt=c.newest??null,Ut=o(),ci=hd({running:t,newest:Vt,supervised:ri});let y=gd({running:t,published:g,supervised:ri});return di=y.act==="replace",Bt+=1,Kt=y.act==="hold"?y.reason:null,on!=="in-progress"&&(on=y.act==="replace"?"pending":"none"),y}async function Jn(){let c=await xi();if(c.act!=="replace"||on==="in-progress")return c;let g=kd(c,oi);return on="in-progress",await k.flush().catch(()=>{}),await zn({reason:"replaced"}),Rd(g,n,{...r==null?{}:{idleMs:r},io:oi}),c}function Lc(){G||un!=null||ei<=0||(!hc&&ti>0&&(Bn=setTimeout(()=>{Jn().catch(()=>{})},ti),Bn.unref()),un=setInterval(()=>{Jn().catch(()=>{})},ei),un.unref())}async function Si(){return await l.renew(a).catch(()=>null)}function $c(){G||dn!=null||Xo<=0||(dn=setInterval(()=>{Si()},Xo),dn.unref())}function Ic(){G||an!=null||Cn<=0||(an=setInterval(()=>{wi().catch(()=>{})},Cn),an.unref())}function Tc(){G||pn!=null||te==null||te.projects.length===0||ii<=0||(zt().catch(()=>{}),pn=setInterval(()=>{zt().catch(()=>{})},ii),pn.unref())}function Nc(){if(G||Se!=null||Mt<=0)return;let c=g=>{G||(Se=setTimeout(()=>{Se=void 0,fi().catch(()=>{}).finally(()=>c(za(de,Mt,Date.parse(o()))))},g),Se.unref())};c(Mt)}function Cc(){G||cn!=null||si<=0||(cn=setInterval(()=>{mi().catch(()=>{})},si),cn.unref())}function T(){G||(Me&&clearTimeout(Me),Me=setTimeout(()=>{bi().catch(()=>{}).then(()=>vi())},r),Me.unref())}function vi(){return v.size>0?(T(),"held-by-workers"):(fn(o()),I.size>0?(T(),"held-by-registrations"):(Mc(),"exited"))}async function Mc(){if(!$n(t)){if((await Jn().catch(()=>null))?.act==="replace"||Jt||G)return;if(v.size>0||I.size>0){T();return}}await zn({reason:"idle"})}function Qn(c){return El({reason:c,socketPath:n.socketPath,daemonVersion:t,pid:a.pid,workers:[...v.values()],projects:[...I.keys()]})}function Ei(c){if(Kn!=null)return Kn;let g=c.reason??"requested",y=c.note?.trim();return Kn=k.recordDaemonStop({ts:o(),pid:a.pid,socketPath:n.socketPath,reason:g,detail:y==null||y===""?Qn(g).detail:`${Qn(g).detail} \u2014 ${y}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),Kn}async function zn(c={}){if(Jt)return await Qt;Jt=!0,await Ei(c),G=!0,Me&&clearTimeout(Me),an&&clearInterval(an),dn&&clearInterval(dn),un&&clearInterval(un),Bn&&clearTimeout(Bn),pn&&clearInterval(pn),Se&&clearTimeout(Se),Se=void 0,cn&&clearInterval(cn),await k.flush().catch(()=>{}),h.close();for(let g of Ht)g.destroy();return await new Promise(g=>h.once("close",()=>g())),await Ld(n.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),ui(),await Qt}let Pi=await k.read().catch(()=>[]);Hn=xt(Pi.filter(c=>c.event==="worker-death"||c.event==="worker-budget-kill").map(c=>({worker_id:c.worker_id,ts:c.ts,outcome:c.event})),c=>c.ts,{now:o()});let Wc=bl(Pi),Zt=await Po(Wc,w);for(let c of Zt.alive){let g=Ba(c),y=g.unit==null||U(g.pid)?null:q(g.unit);v.set(g.worker_id,y!=null&&y>0?{...g,pid:y}:g),ge.add(g.worker_id)}for(let c of Zt.dead)ce("worker-death",c,"the Worker ended while no daemon was watching");let Hc=Ua({units:await Promise.resolve(ne()).catch(()=>[]),held:[...v.values()],mainPid:q,now:b});for(let c of Hc)v.set(c.worker_id,c),ge.add(c.worker_id),ce("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of Zt.alive){if(c.log_path==null||Ce.has(c.worker_id))continue;let g=await Ne(c.log_path).catch(()=>null);g==null||g.trim()===""||Ce.set(c.worker_id,{line:g,published_at:o(),source:"rehydrated"})}h.on("connection",c=>{Ht.add(c),c.once("close",()=>Ht.delete(c)),T(),Ok(c,async(g,y)=>{T();let _=await Fc(g);y(_),g.op==="shutdown"&&setImmediate(()=>void zn({reason:"requested"}))})});async function Fc(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:jt,daemon_version:t,pid:a.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:Vn()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:qn()};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:_c(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:wc(c.dashboard)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:hi(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:gi(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:yi(c.project_label,{...c.session_project==null?{}:{sessionProject:c.session_project},...c.renew_within_ms==null?{}:{renewWithinMs:c.renew_within_ms},...c.launch==null?{}:{launch:c.launch}})};if(c.op==="project-deregister")return{id:c.id,ok:!0,value:ki(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await xc(c.command)};if(c.op==="worker-start"){let y=We("worker-start",c.session_project,c.spec.project_label);if(!y.permitted)return{id:c.id,ok:!1,error:y.reason};let _=Yt(c.spec);return await k.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:_.worker,admission:_.admission,warnings:_.warnings}}}if(c.op==="shutdown"){let y=Qn("requested");return await Ei({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:y}}let g=c;return{id:g.id??Tn(),ok:!1,error:`unsupported redskilled op: ${g.op??"unknown"}`}}catch(g){return{id:c.id??Tn(),ok:!1,error:g instanceof Error?g.message:String(g)}}}return T(),Ic(),$c(),Lc(),Tc(),Nc(),Cc(),{socketPath:n.socketPath,lease:m.lease,startedAt:b,closed:Qt,startWorker:Yt,admit:Ri,ceiling:()=>s,killWorkerOverBudget:_i,sampleMemoryBudgets:wi,renewLease:Si,pollRepositoryActivity:zt,pollQueueDiscovery:fi,queueDiscovery:()=>de,driveDemand:mi,demand:()=>Fn,sweepReattached:bi,publishWorkerHeartbeat:hi,reattached:()=>[...ge].map(c=>v.get(c)).filter(c=>c!=null),flushEvents:()=>k.flush(),trackWorker(c){v.set(c.worker_id,c),ce("worker-birth",c,null),T()},releaseWorker(c){let g=v.get(c),y=v.delete(c);return ge.delete(c),Ce.delete(c),Wn.delete(c),g&&ce("worker-death",g,"released by the daemon"),T(),y},workerCount:()=>v.size,registerProject:gi,renewProject:yi,deregisterProject:ki,registrations:()=>Vn().registrations??[],hostState:Vn,statuslinePayload:qn,evaluateIdle:vi,observePublishedVersion:xi,checkForReplacement:Jn,stopReport:Qn,stop:zn}}async function Dk(e){for(let n=0;n<2;n++){let t=wk();try{return await new Promise((r,o)=>{t.once("error",o),t.listen(e,()=>{t.off("error",o),r()})}),t}catch(r){if(t.close(),r.code!=="EADDRINUSE")throw r;if(await ee(e))throw new tn(e);await Ld(e,{force:!0})}}throw new tn(e)}async function ee(e,n=250){try{return(await ut({socketPath:e,timeoutMs:n},{id:Tn(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function Ok(e,n){el(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??Tn(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function Wo(e){let n=e.socketPath,t=Ak(e);return e.answers?{version:1,kind:"answering",socket_path:n,holder:t,reason:`a redskilled daemon answered on ${JSON.stringify(n)}`,repair:"nothing to repair"}:t!=null?{version:1,kind:"held-unresponsive",socket_path:n,holder:t,reason:`redskilled pid ${t.pid} is alive and has held ${JSON.stringify(n)} since ${t.acquired_at}${t.uptime_ms==null?"":` (up ${Id(t.uptime_ms)})`}, but it did not answer a ping \u2014 this is a daemon that could not be REACHED, not one that is missing.`,repair:`Do not provision: a daemon is already running. Inspect it (\`ps -p ${t.pid}\`), or stop it with \`${_e("red-skills-redskilled",["stop"])}\` and let the next client start a fresh one.`}:{version:1,kind:"absent",socket_path:n,holder:null,reason:`nothing answered on ${JSON.stringify(n)} and no live process holds its lease`,repair:`Install and start one with \`${_e("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function Ho(e){return`${e.reason} ${e.repair}`}function Ak(e){let n=e.lease;return n==null||e.holderAlive!==!0||n.socket_path!==e.socketPath?null:{pid:n.pid,socket_path:n.socket_path,acquired_at:n.acquired_at,renewed_at:n.renewed_at,uptime_ms:Lk(n.acquired_at,e.now??new Date().toISOString())}}function Lk(e,n){let t=Date.parse(e),r=Date.parse(n);return!Number.isFinite(t)||!Number.isFinite(r)?null:Math.max(0,r-t)}function Id(e){let n=Math.floor(e/1e3),t=Math.floor(n/3600),r=Math.floor(n%3600/60),o=n%60;return t>0?`${t}h${String(r).padStart(2,"0")}m`:r>0?`${r}m${String(o).padStart(2,"0")}s`:`${o}s`}fe();var Cd=1e4,Te=class extends Error{constructor(t,r,o){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}${o!=null&&o.kind==="held-unresponsive"?`. ${Ho(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},Fo=class extends Te{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}};async function Tt(e,n={}){let t=n.answers??await ee(e.socketPath),r=await In(e.leasePath).catch(()=>{});return Wo({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&U(r.pid)})}async function Uo(e,n={}){try{return await Ck(e,n)}catch(t){if(t instanceof be||t instanceof Te)throw t;let r=await Tt(e).catch(()=>{});throw new Te(e.socketPath,t,r)}}async function Ck(e,n){if(await Ik(Nk(e.socketPath),{recursive:!0,mode:448}),await ee(e.socketPath))return"already-running";await Wk(e);let t=await Mk(e,n);if(t!=null)return t;let r=await nl(e.lockPath);if(!r)return await Td(e,n),"joined";try{if(await ee(e.socketPath))return"already-running";let o=await Uk(e,n);return await Td(e,n,o),"spawned"}finally{await r.close(),await Tk(e.lockPath,{force:!0})}}async function Mk(e,n){let t=await Tt(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??Cd,o=Date.now()+r;for(;;){if(await ee(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(s=>setTimeout(s,25))}let i=await Tt(e).catch(()=>{});if(i==null||i.kind!=="held-unresponsive")return null;throw new Fo(e.socketPath,i,new Error(`it did not answer a ping within ${r}ms, and no second daemon was spawned because pid ${i.holder?.pid??"unknown"} still holds this socket`))}async function Wk(e){let t=await _t(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&U(t.pid))throw new be(e.machineClaimPath,"held",t)}async function Md(e,n,t={}){await Uo(e,t);let r;try{r=await On({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:Nd()})}catch(o){throw new Te(e.socketPath,o,await Tt(e).catch(()=>{}))}if(!r.ok)throw new Error(r.error);return r.value}async function Wd(e,n={},t={}){if(!await ee(e.socketPath))return Pl(e.socketPath);let r;try{r=await On({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Nd(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(s){throw new Te(e.socketPath,s)}if(!r.ok)throw new Error(r.error);if(!Zr(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await Hk(e.socketPath,n.settleTimeoutMs??5e3)?o:{...o,stopped:!1,detail:`${o.detail}; the daemon accepted the stop and is still answering on ${JSON.stringify(e.socketPath)}`}}async function Hk(e,n){let t=Date.now()+n;for(;;){if(!await ee(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function Hd(e,n={}){let t=await Md(e,{op:"host-state"},n);if(!ba(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Fd(e,n=void 0,t={}){let r=await Md(e,{op:"statusline-string",...t.sessionProject!=null?{session_project:t.sessionProject}:{},...n==null?{}:{render:Fk(n)}},t);if(!ka(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function Fk(e){return{mode:e.mode,project:e.project,max_workers:e.maxWorkers,max_projects:e.maxProjects,max_width:e.maxWidth,verbose:e.verbose}}async function Td(e,n,t){let r=Date.now()+(n.readyTimeoutMs??Cd);for(;;){if(await ee(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=r){let o=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${o}`)}await new Promise(o=>setTimeout(o,25))}}async function Uk(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await dl({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},i=[...r.args,...Ae(e,n.idleMs==null?{}:{idleMs:n.idleMs})],s=$k(r.command,i,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return s.on("error",a=>{o.failure=a}),s.on("exit",(a,l)=>{o.exit=l?`died on ${l}`:`exited with code ${a??-1}`}),s.unref(),o}fe();import{chmod as Jd,mkdir as zd,readFile as Yd,stat as Zk,writeFile as eR}from"node:fs/promises";import{homedir as Vo}from"node:os";import{dirname as nR,join as qo}from"node:path";import{join as Bk}from"node:path";var Ud=["local","tmp","host"],Kk="local",Nn="plugins.dev.workspace.target";var Bo=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function Kd(e){let n=Qe(e,Nn),t=Gk(n??"").trim();return t===""?void 0:t}function Vd(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:Kk};let t=Ud.find(r=>r===n.toLowerCase());if(t)return{kind:"preset",preset:t};if(n.startsWith("/")||n==="~"||n.startsWith("~/"))return{kind:"custom",parentDir:n};throw new Bo(`${Nn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${Ud.join(", ")}) or an absolute parent directory for Workers.`)}function qd(e,n){return e.kind==="preset"?e.preset==="host":qk(Vk(e.parentDir,n),Oe(n))}function Vk(e,n){return e==="~"?Bd(n):e.startsWith("~/")?Bk(n,e.slice(2)):Bd(e)}function qk(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Bd(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function Gk(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}fe();import{createHash as Jk}from"node:crypto";import{hostname as Qk}from"node:os";import{join as Nt}from"node:path";var rn="redskilled.sock",zk="REDSKILLED_SESSION";function Yk(e={}){let n=e.env??process.env,t=n[zk]?.trim();if(t)return t;let r=n.XDG_RUNTIME_DIR?.trim();return r||`uid:${e.uid??(typeof process.getuid=="function"?process.getuid():"nouid")}`}function Xk(e={}){return Gd(e.host??Qk())}function he(e={}){let n=Yk(e),t=e.runtimeDir??pt({key:`redskilled:${n}`,socketFileName:rn,env:e.env,uid:e.uid}),r=Xk(e);return{sessionKey:n,sessionKeyHash:Gd(n),machineIdHash:r,runtimeDir:t,socketPath:Nt(t,rn),lockPath:Nt(t,"redskilled.spawn.lock"),leasePath:Nt(t,"redskilled.lease.toon"),eventLanePath:Nt(t,kl),machineClaimPath:e.machineClaimPath??bt({env:e.env,machineIdHash:r,platform:e.platform})}}function Gd(e){return Jk("sha256").update(e).digest("hex").slice(0,12)}var Ko=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${_e("red-skills-redskilled",["provision"])}\` directly`;async function Xd(e=Vo()){let n=Oe(e),t=await Jo(n);return t===void 0?(await zd(n,{recursive:!0,mode:se}),await Jd(n,se),{path:n,created:!0,tightened:!1,mode:se}):t===se?{path:n,created:!1,tightened:!1,mode:t}:(await Jd(n,se),{path:n,created:!1,tightened:!0,mode:se})}var Zd={needed:!1,declaredBy:`no ${Nn} in view`};async function Go(e={}){let n=e.homeDir??Vo(),t=e.declaredTarget?.trim();if(t)return Qd(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return Zd;let o=qo(r,".red","config.yaml"),i=await Yd(o,"utf8").catch(()=>{});if(i===void 0)return{needed:!1,declaredBy:`no ${o}`};let s=Kd(i);return s===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Qd(s,n,o)}function Qd(e,n,t){let r=`${Nn}: ${e} (${t})`;try{return{needed:qd(Vd(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function ec(e){let n=[tR(e),rR(e),oR(e),iR(e)],t=n.filter(o=>o.verdict!=="ok");return{verdict:t.some(o=>o.verdict==="missing")?"missing":t.length>0?"degraded":"ok",rows:n,findings:t}}function tR(e){let n=e.homeNeed??Zd;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:Ko}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??se;return t!==se?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${se.toString(8)}`,fix:`${Ko} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function rR(e){return ae(e.entry)?{check:"daemon-entry",verdict:"ok",evidence:`${e.entry.entry??e.entry.command} (resolved as ${e.entry.source})`,fix:""}:{check:"daemon-entry",verdict:"missing",evidence:`no published redskilled bundle; probed ${e.entry.searched.join(", ")||"nothing"}`,fix:`install or warm the RedSkills bundle for this host, then re-run \`${_e("red-skills-redskilled",["provision"])}\``}}function oR(e){return e.reachable?{check:"reach",verdict:"ok",evidence:`daemon answered on ${e.socketPath}`,fix:""}:{check:"reach",verdict:"missing",evidence:`no daemon answered on ${e.socketPath}`,fix:`${Ko} \u2014 it starts the daemon and waits for the socket`}}function iR(e){return{check:"supervisor-unit",verdict:"ok",evidence:e.supervisorUnit==="installed"?"redskilled.service is installed (optional supervision, Restart=on-failure)":e.supervisorUnit==="unsupported"?"optional: this host has no systemd --user session; auto-spawn is the only start path":"optional: not installed; auto-spawn already starts the daemon on first use",fix:""}}async function nc(e={}){let n=e.env??process.env,t=e.homeDir??Vo(),r=e.paths??he({env:n}),o=Oe(t),[i,s,a]=await Promise.all([Jo(o),ee(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Go({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:i!==void 0,homeMode:i,homeNeed:a,entry:Re(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:s,supervisorUnit:await lR(aR(e,n,t),n)}}var sR="redskilled.service";function tc(e){return qo(e,"systemd","user",sR)}function rc(e){let n=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${n}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
78
+ `)}async function oc(e){let n=tc(e.configHome);return await Jo(n)!==void 0?{path:n,status:"already-present"}:(await zd(nR(n),{recursive:!0}),await eR(n,e.unit,"utf8"),{path:n,status:"installed"})}async function lR(e,n){if(process.platform!=="linux")return"unsupported";try{return await Yd(tc(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function aR(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??qo(t,".config")}async function Jo(e){try{return(await Zk(e)).mode&511}catch{return}}import{readdir as sc,rm as dR,stat as cR}from"node:fs/promises";import{dirname as uR,join as Qo}from"node:path";var pR=5*6e4,fR="redskilled.";function mR(e={}){let n=e.env??process.env,t=s=>uR(pt({key:"redskilled:reclaim-probe",socketFileName:rn,env:s,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=n,i=[t(n),t(o)];return[...new Set(i)]}async function lc(e={}){let n=e.roots??mR(e),t=e.graceMs??pR,r=e.now??Date.now,o=e.isPidAlive??U,i=e.answers??kR,s=e.dryRun===!0,a=[];for(let l of n){let d;try{d=(await sc(l,{withFileTypes:!0})).filter(p=>p.isDirectory()).map(p=>p.name)}catch{continue}for(let p of d.sort())a.push(await hR(Qo(l,p),{graceMs:t,now:r,pidAlive:o,answers:i,dryRun:s}))}return{roots:n,scanned:a.length,reclaimed:a.filter(l=>l.verdict==="reclaimed").length,dryRun:s,entries:a}}async function hR(e,n){let t;try{t=(await sc(e)).sort()}catch(s){return{dir:e,verdict:"failed",reason:ac(s),removed:[]}}let r=t.filter(s=>s.startsWith(fR));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await gR(Qo(e,"redskilled.lease.toon"));if(o!==void 0)return await n.pidAlive(o.pid)?{dir:e,verdict:"live",reason:`lease pid ${o.pid} is alive`,removed:[]}:await ic(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(rn)&&await n.answers(Qo(e,rn)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let i=await yR(e,n.now);return i!==void 0&&i<n.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(i/1e3)}s ago`,removed:[]}:await ic(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function ic(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await dR(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:ac(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function gR(e){try{return await In(e)}catch{return}}async function yR(e,n){try{return Math.max(0,n()-(await cR(e)).mtimeMs)}catch{return}}async function kR(e){try{return(await On({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function ac(e){return e instanceof Error?e.message:String(e)}var RR="plugins.dev.statusline",bR="dev.statusline";function _R(e){let n=[],t=a=>{for(let l of[RR,bR]){let d=`${l}.${a}`,p=Qe(e,d)?.trim();if(p!=null&&p!=="")return{key:d,value:p}}},r=t("mode"),o={};r!=null&&(r.value==="local"||r.value==="global"?o.mode=r.value:n.push({...r,reason:"expected `local` or `global`"}));let i=[{leaf:"max_workers",assign:a=>{o.maxWorkers=a}},{leaf:"max_projects",assign:a=>{o.maxProjects=a}},{leaf:"max_width",assign:a=>{o.maxWidth=a}}];for(let a of i){let l=t(a.leaf);if(l==null)continue;let d=Number(l.value);Number.isInteger(d)&&d>=0?a.assign(d):n.push({...l,reason:"expected a whole number of zero or more"})}let s=t("verbose");return s!=null&&(s.value==="true"||s.value==="false"?o.verbose=s.value==="true":n.push({...s,reason:"expected `true` or `false`"})),{config:o,warnings:n}}var wR={mode:{kind:"value",coerce:e=>e},verbose:{kind:"boolean"},project:{kind:"value",coerce:e=>e},"max-workers":{kind:"value",coerce:e=>e},"max-projects":{kind:"value",coerce:e=>e},"max-width":{kind:"value",coerce:e=>e}};function dc(e){let{values:n,positionals:t}=je(e,wR),r=[],o={},i=n.mode??t.find(a=>a==="global"||a==="local");i!=null&&(i==="local"||i==="global"?o.mode=i:r.push({key:"--mode",value:i,reason:"expected `local` or `global`"})),n.project!=null&&(o.project=n.project),n.verbose!==void 0&&(o.verbose=n.verbose===!0);let s=[{flag:"max-workers",assign:a=>{o.maxWorkers=a}},{flag:"max-projects",assign:a=>{o.maxProjects=a}},{flag:"max-width",assign:a=>{o.maxWidth=a}}];for(let a of s){let l=n[a.flag];if(l==null)continue;let d=Number(l);Number.isInteger(d)&&d>=0?a.assign(d):r.push({key:`--${a.flag}`,value:l,reason:"expected a whole number of zero or more"})}return{flags:o,warnings:r}}function cc(e={}){let n=e.configText==null?{config:{},warnings:[]}:_R(e.configText),t=e.flags??{};return{options:{...$,mode:t.mode??n.config.mode??$.mode,project:t.project!==void 0?t.project:e.project??$.project,maxWorkers:t.maxWorkers??n.config.maxWorkers??$.maxWorkers,maxProjects:t.maxProjects??n.config.maxProjects??$.maxProjects,maxWidth:t.maxWidth??n.config.maxWidth??$.maxWidth,verbose:t.verbose??n.config.verbose??$.verbose},warnings:n.warnings}}var SR=`Usage: redskilled <command> [options]
70
79
 
71
80
  Commands:
72
81
  host-state (default) print the host's state as JSON
@@ -78,7 +87,7 @@ Commands:
78
87
 
79
88
  Run \`redskilled <command> --help\` for a command's own usage.
80
89
  \`--version\` (\`-v\`) prints the build stamp; both answer offline.
81
- `,ay={serve:`Usage: redskilled serve [options]
90
+ `,vR={serve:`Usage: redskilled serve [options]
82
91
 
83
92
  Runs the daemon in this process. Every path is a flag and none is derived
84
93
  (ADR 0130 rule 3); what is absent falls back to the session derivation.
@@ -142,19 +151,19 @@ Reports every session runtime dir it looked at and why it kept or removed it.
142
151
 
143
152
  --dry-run the same report with nothing removed
144
153
  --grace-ms <n> how long a dir must be idle before it is reclaimed
145
- `};function dy(e){return e==="--help"||e==="-h"||e==="help"}var cy={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)}},Ga="REDSKILLED_HOST_TOKEN";function ao(){try{let n=iy("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function uy(e=process.env,n=ao){let t=(e[Ga]??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 py(e,n=process.env,t=ao){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...Ja(e,n,t),armTransport:()=>Ja(e,n,t)}}function Ja(e,n=process.env,t=ao){let r=uy(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${Ga}, 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:Ki({token:r.token,...o?{endpoint:o}:{}})}}async function my(e){if(e[0]==="--version"||e[0]==="-v"){let o=Ct("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
146
- `:`${is(o)}
147
- `),0}if(dy(e[0]))return process.stdout.write(ly),0;let{command:n,args:t}=cs(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(ay[n]),0;if(n==="serve"){let{values:o}=ke(t,cy),s=py(o),i=qa(be(lo()),"state"),l=Os({stateRoot:i});process.stderr.write(`${$s(l)}
148
- `);let a=xs({lanePath:rn(i),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),d=await ha({paths:Sy(o),idleMs:o["idle-ms"]??Zr,daemonVersion:o["daemon-version"]??Ct("redskilled").version,deaths:l.attributions,queueDiscovery:s,...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let u of["SIGTERM","SIGINT"])process.once(u,()=>void d.stop({reason:"signal",signal:u}).catch(()=>{}));return await d.closed,a.phase("closed"),0}if(n==="stop")return await gy(t);if(n==="statusline")return await yy(t);if(n==="unit")return await hy(t);if(n==="provision")return await Ry(t);if(n==="reclaim")return await _y(t);let r=await _a(ie());return process.stdout.write(`${JSON.stringify(r,null,2)}
149
- `),0}var fy={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function gy(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=ke(e,fy),o=await ba(n.paths??ie(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${I({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})}
150
- `),o.running&&!o.stopped?1:0}async function hy(e,n={}){let t=n.write??(s=>process.stdout.write(s)),r=n.paths??ie(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(Bl(n.unitIO??{}),null,2)}
151
- `),0;if(o==="install"){let s=await Ul(Fl(r),n.unitIO??{});return t(`${JSON.stringify(s,null,2)}
152
- `),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await Vl(n.unitIO??{}),null,2)}
153
- `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function yy(e,n={}){let t=n.write??(a=>process.stdout.write(a)),r=n.warn??(a=>process.stderr.write(a)),o=Ba(e),s=vy(n.cwd??process.cwd()),i=Ka({...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}
154
- `);let l;try{l=await wa(n.paths??ie(),i.options,{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(a){r(`redskilled statusline: ${a instanceof Error?a.message:String(a)}
155
- `),l=Qi({options:i.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${l.lines.join(`
154
+ `};function ER(e){return e==="--help"||e==="-h"||e==="help"}var PR={socket:{kind:"value",coerce:e=>e},lease:{kind:"value",coerce:e=>e},events:{kind:"value",coerce:e=>e},"session-key-hash":{kind:"value",coerce:e=>e},"machine-id-hash":{kind:"value",coerce:e=>e},"machine-claim":{kind:"value",coerce:e=>e},"idle-ms":{kind:"value",coerce:e=>Number(e)},"daemon-version":{kind:"value",coerce:e=>e},"queue-endpoint":{kind:"value",coerce:e=>e},"queue-ms":{kind:"value",coerce:e=>Number(e)},"demand-ms":{kind:"value",coerce:e=>Number(e)}},fc="REDSKILLED_HOST_TOKEN";function Yo(){try{let n=xR("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function jR(e=process.env,n=Yo){let t=(e[fc]??e.GITHUB_TOKEN??e.GH_TOKEN??"").trim();if(t!=="")return{token:t,source:"env"};let r=(n()??"").trim();return r!==""?{token:r,source:"tracker-cli"}:null}function DR(e,n=process.env,t=Yo){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...uc(e,n,t),armTransport:()=>uc(e,n,t)}}function uc(e,n=process.env,t=Yo){let r=jR(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${fc}, GITHUB_TOKEN and GH_TOKEN are all unset in the daemon's environment and \`gh auth token\` returned nothing \u2014 so no queue depth is asked for, and no depth is invented either`};let o=e["queue-endpoint"]??n.GITHUB_GRAPHQL_URL;return{transport:la({token:r.token,...o?{endpoint:o}:{}})}}async function OR(e){if(e[0]==="--version"||e[0]==="-v"){let o=br("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
155
+ `:`${ps(o)}
156
+ `),0}if(ER(e[0]))return process.stdout.write(SR),0;let{command:n,args:t}=gs(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(vR[n]),0;if(n==="serve"){let{values:o}=je(t,PR),i=DR(o),s=pc(Oe(zo()),"state"),a=Ns({stateRoot:s});process.stderr.write(`${Cs(a)}
157
+ `);let l=As({lanePath:bn(s),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),d=await $d({paths:FR(o),idleMs:o["idle-ms"]??Mo,daemonVersion:o["daemon-version"]??br("redskilled").version,deaths:a.attributions,queueDiscovery:i,...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let p of["SIGTERM","SIGINT"])process.once(p,()=>void d.stop({reason:"signal",signal:p}).catch(()=>{}));return await d.closed,l.phase("closed"),0}if(n==="stop")return await LR(t);if(n==="statusline")return await IR(t);if(n==="unit")return await $R(t);if(n==="provision")return await NR(t);if(n==="reclaim")return await MR(t);let r=await Hd(he());return process.stdout.write(`${JSON.stringify(r,null,2)}
158
+ `),0}var AR={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function LR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),{values:r}=je(e,AR),o=await Wd(n.paths??he(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${M({running:o.running,stopped:o.stopped,reason:o.reason,socket:o.socket_path,daemon_version:o.daemon_version,pid:o.pid,holding:{workers:o.holding.workers.length,projects:[...o.holding.projects]},surviving:[...o.surviving],workers:o.holding.workers.map(i=>({worker_id:i.worker_id,project_label:i.project_label,pid:i.pid,unit:i.unit,isolated:i.isolated,survives:i.survives})),detail:o.detail})}
159
+ `),o.running&&!o.stopped?1:0}async function $R(e,n={}){let t=n.write??(i=>process.stdout.write(i)),r=n.paths??he(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(ld(n.unitIO??{}),null,2)}
160
+ `),0;if(o==="install"){let i=await id(rd(r),n.unitIO??{});return t(`${JSON.stringify(i,null,2)}
161
+ `),i.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await sd(n.unitIO??{}),null,2)}
162
+ `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function IR(e,n={}){let t=n.write??(l=>process.stdout.write(l)),r=n.warn??(l=>process.stderr.write(l)),o=dc(e),i=HR(n.cwd??process.cwd()),s=cc({...i.configText==null?{}:{configText:i.configText},project:i.label,flags:o.flags});for(let l of[...s.warnings,...o.warnings])r(`redskilled statusline: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
163
+ `);let a;try{a=await Fd(n.paths??he(),s.options,{...n.client??{},...s.options.project==null?{}:{sessionProject:s.options.project}})}catch(l){r(`redskilled statusline: ${l instanceof Error?l.message:String(l)}
164
+ `),a=pa({options:s.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${a.lines.join(`
156
165
  `)}
157
- `),0}var ky={"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 Ry(e,n={}){let t=n.write??(m=>process.stdout.write(m)),{values:r}=ke(e,ky),o=n.paths??ie(),s=n.homeDir??lo(),i=await oo({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),l=r.check||!i.needed?void 0:await Aa(s),a;if(!r.check&&!r["no-start"])try{await Xr(o,n.client??{})}catch(m){a=m instanceof Error?m.message:String(m)}let d=await Na({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"]&&Y(d.entry)?await Ca({configHome:n.configHome??wy(),unit:Ma({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,p=Ta(d);return t(`${I({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(m=>({check:m.check,verdict:m.verdict,evidence:m.evidence})),fixes:p.findings.map(m=>({check:m.check,fix:m.fix}))})}
158
- `),p.verdict==="ok"?0:1}var by={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function _y(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=ke(e,by),o=await Ua({...n.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return t(`${I({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]}))})}
159
- `),o.entries.some(s=>s.verdict==="failed")?1:0}function wy(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:qa(lo(),".config")}function vy(e){let n=or(e);return n.configText==null?{label:null}:{configText:n.configText,label:Cs(e)}}function Sy(e){let n=ie();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 xy=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;xy&&my(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
160
- `),process.exitCode=1});export{Ga as REDSKILLED_HOST_TOKEN_ENV,ly as REDSKILLED_USAGE,Ja as armRedskilledQueueTransport,uy as resolveRedskilledHostToken,py as resolveServeQueueDiscovery,Ry as runProvision,_y as runReclaim,my as runRedskilledCli,yy as runStatusline,gy as runStop,hy as runUnit};
166
+ `),0}var TR={"no-start":{kind:"boolean"},"install-unit":{kind:"boolean"},check:{kind:"boolean"},project:{kind:"value",coerce:e=>e},workspace:{kind:"value",coerce:e=>e}};async function NR(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=je(e,TR),o=n.paths??he(),i=n.homeDir??zo(),s=await Go({homeDir:i,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),a=r.check||!s.needed?void 0:await Xd(i),l;if(!r.check&&!r["no-start"])try{await Uo(o,n.client??{})}catch(f){l=f instanceof Error?f.message:String(f)}let d=await nc({paths:o,homeNeed:s,...n.homeDir==null?{}:{homeDir:n.homeDir},...n.configHome==null?{}:{configHome:n.configHome},...n.client?.serverCommand==null?{}:{entryOverride:{serverCommand:n.client.serverCommand,serverArgs:n.client.serverArgs}}}),p=r["install-unit"]&&ae(d.entry)?await oc({configHome:n.configHome??WR(),unit:rc({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=ec(d);return t(`${M({verdict:u.verdict,home:{path:a?.path??d.homePath,created:a?.created??!1,tightened:a?.tightened??!1,needed:s.needed,needed_by:s.declaredBy},socket:d.socketPath,...l==null?{}:{start_error:l},...p==null?{}:{unit:{path:p.path,status:p.status}},checks:u.rows.map(f=>({check:f.check,verdict:f.verdict,evidence:f.evidence})),fixes:u.findings.map(f=>({check:f.check,fix:f.fix}))})}
167
+ `),u.verdict==="ok"?0:1}var CR={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function MR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),{values:r}=je(e,CR),o=await lc({...n.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return t(`${M({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(i=>({dir:i.dir,verdict:i.verdict,reason:i.reason,removed:[...i.removed]}))})}
168
+ `),o.entries.some(i=>i.verdict==="failed")?1:0}function WR(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:pc(zo(),".config")}function HR(e){let n=Wr(e);return n.configText==null?{label:null}:{configText:n.configText,label:Vs(e)}}function FR(e){let n=he();return{...n,socketPath:e.socket??n.socketPath,leasePath:e.lease??n.leasePath,eventLanePath:e.events??n.eventLanePath,sessionKeyHash:e["session-key-hash"]??n.sessionKeyHash,machineIdHash:e["machine-id-hash"]??n.machineIdHash,machineClaimPath:e["machine-claim"]??n.machineClaimPath}}var UR=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;UR&&OR(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
169
+ `),process.exitCode=1});export{fc as REDSKILLED_HOST_TOKEN_ENV,SR as REDSKILLED_USAGE,uc as armRedskilledQueueTransport,jR as resolveRedskilledHostToken,DR as resolveServeQueueDiscovery,NR as runProvision,MR as runReclaim,OR as runRedskilledCli,IR as runStatusline,LR as runStop,$R as runUnit};