@reddb-io/red-skills 3.3.3 → 3.3.5

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,72 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var Ka=Object.defineProperty;var qa=(e,n)=>()=>(e&&(n=e(e=0)),n);var Ga=(e,n)=>{for(var t in n)Ka(e,t,{get:n[t],enumerable:!0})};var Is={};Ga(Is,{REDSKILLED_BIN_ENV:()=>Zt,REDSKILLED_BUNDLE_ASSET:()=>Q,REDSKILLED_ENTRY_UNRESOLVED:()=>sn,RedskilledDaemonEntryError:()=>ln,isRedskilledEntryPath:()=>er,isResolvedRedskilledEntry:()=>Y,redskilledBundleCacheRoot:()=>Wn,redskilledServeArgv:()=>Re,requireRedskilledEntry:()=>Cn,resolveRedskilledEntry:()=>ce});import{existsSync as bu,readdirSync as wu}from"node:fs";import{homedir as _u}from"node:os";import{basename as Yt,dirname as Qt,join as C,resolve as Nn}from"node:path";function Y(e){return"command"in e}function Re(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 Wn(e=process.env){return As(e)}function ce(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??bu,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[Zt];if(a)return{command:a,args:[],source:"env-redskilled-bin",entry:a};if(i&&er(i))return l(Nn(i),"caller-entry");let d=[];for(let[u,p]of Eu(i,n.rootDir,t,n.listDir??Du))if(d.push(u),r(u))return l(u,p);return{diagnostic:sn,searched:d,...i?{callerEntry:Nn(i)}:{}}}function Cn(e={},n={}){let t=ce(e,n);if(Y(t))return t;throw new ln(t)}function er(e){let n=Yt(e);return n===Q||Xt.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:Su(Nn(e))}function Su(e){let n=Qt(e);for(let t=0;t<4;t++){if(Yt(n)==="redskilled")return!0;let r=Qt(n);if(r===n)return!1;n=r}return!1}function*Eu(e,n,t,r){if(e){let s=Qt(Nn(e));yield[C(s,Q),"caller-sibling-bundle"];let i=vu.exec(Yt(e));i&&(yield[C(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[C(s,"..","dist",Q),"caller-sibling-bundle"]}for(let s of xu){let i=t[s];i&&(yield[C(i,"dist",Q),"plugin-root-bundle"],yield[C(i,"..","..","dist",Q),"plugin-root-bundle"])}n&&(yield[C(n,"dist",Q),"repo-bundle"],yield[C(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[C(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=As(t);yield[C(o,Q),"bundle-cache"];for(let s of Pu(o,r))yield[C(o,s),"bundle-cache"]}function As(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||C(e.HOME||_u(),".cache");return C(n,"red-skills","bundles")}function Pu(e,n){return n(e).filter(t=>Xt.test(t)).sort((t,r)=>ju($s(r),$s(t)))}function $s(e){return Xt.exec(e)?.[1]??""}function ju(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 Du(e){try{return wu(e)}catch{return[]}}var Q,sn,Zt,ln,vu,Xt,xu,te=qa(()=>{"use strict";Q="redskilled.bundle.min.mjs",sn="redskilled-daemon-entry-unresolved",Zt="REDSKILLED_BIN";ln=class extends Error{code=sn;searched;callerEntry;constructor(n){super(`${sn}: 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 Ga=Object.defineProperty;var za=(e,n)=>()=>(e&&(n=e(e=0)),n);var Qa=(e,n)=>{for(var t in n)Ga(e,t,{get:n[t],enumerable:!0})};var Ns={};Qa(Ns,{REDSKILLED_BIN_ENV:()=>nr,REDSKILLED_BUNDLE_ASSET:()=>Q,REDSKILLED_ENTRY_UNRESOLVED:()=>sn,RedskilledDaemonEntryError:()=>ln,isRedskilledEntryPath:()=>rr,isResolvedRedskilledEntry:()=>Y,redskilledBundleCacheRoot:()=>Mn,redskilledServeArgv:()=>Re,requireRedskilledEntry:()=>Fn,resolveRedskilledEntry:()=>ce});import{existsSync as _u,readdirSync as vu}from"node:fs";import{homedir as xu}from"node:os";import{basename as er,dirname as Xt,join as C,resolve as Cn}from"node:path";function Y(e){return"command"in e}function Re(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 Mn(e=process.env){return Ts(e)}function ce(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??_u,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[nr];if(a)return{command:a,args:[],source:"env-redskilled-bin",entry:a};if(i&&rr(i))return l(Cn(i),"caller-entry");let c=[];for(let[u,p]of ju(i,n.rootDir,t,n.listDir??$u))if(c.push(u),r(u))return l(u,p);return{diagnostic:sn,searched:c,...i?{callerEntry:Cn(i)}:{}}}function Fn(e={},n={}){let t=ce(e,n);if(Y(t))return t;throw new ln(t)}function rr(e){let n=er(e);return n===Q||tr.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:Pu(Cn(e))}function Pu(e){let n=Xt(e);for(let t=0;t<4;t++){if(er(n)==="redskilled")return!0;let r=Xt(n);if(r===n)return!1;n=r}return!1}function*ju(e,n,t,r){if(e){let s=Xt(Cn(e));yield[C(s,Q),"caller-sibling-bundle"];let i=Su.exec(er(e));i&&(yield[C(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[C(s,"..","dist",Q),"caller-sibling-bundle"]}for(let s of Eu){let i=t[s];i&&(yield[C(i,"dist",Q),"plugin-root-bundle"],yield[C(i,"..","..","dist",Q),"plugin-root-bundle"])}n&&(yield[C(n,"dist",Q),"repo-bundle"],yield[C(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[C(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=Ts(t);yield[C(o,Q),"bundle-cache"];for(let s of Du(o,r))yield[C(o,s),"bundle-cache"]}function Ts(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||C(e.HOME||xu(),".cache");return C(n,"red-skills","bundles")}function Du(e,n){return n(e).filter(t=>tr.test(t)).sort((t,r)=>Ou(Is(r),Is(t)))}function Is(e){return tr.exec(e)?.[1]??""}function Ou(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 $u(e){try{return vu(e)}catch{return[]}}var Q,sn,nr,ln,Su,tr,Eu,te=za(()=>{"use strict";Q="redskilled.bundle.min.mjs",sn="redskilled-daemon-entry-unresolved",nr="REDSKILLED_BIN";ln=class extends Error{code=sn;searched;callerEntry;constructor(n){super(`${sn}: no published ${Q} 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)}};vu=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Xt=/^redskilled-(.+)\.bundle\.min\.mjs$/,xu=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as _g}from"node:child_process";import{homedir as qr}from"node:os";import{join as ba}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}},fe=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 x(e,n){return new fe(e,n)}function Ee(e){return e instanceof fe?e:e instanceof Ye?new fe(e.line,e.reason):new fe(0,String(e&&e.message?e.message:e))}var P=",";function Pn(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 J(e){return R(e,"invalid quoted string")}function K(e,n){if(e==="")return"";if(e.startsWith('"'))return xo(e,n);if(e.includes('"'))throw J(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:za(e)?Number(e):e}function ee(e,n){let t=e.trim();if(t.startsWith('"'))return[xo(t,n),!0];if(t.includes('"')||/\s/.test(t))throw R(n,"expected non-empty field name");return[t,!1]}function xo(e,n){if(e[0]!=='"')throw J(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 J(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 J(n);let l=Number.parseInt(i,16);if(l>=55296&&l<=57343)throw J(n);t+=String.fromCharCode(l),r+=4;break}default:throw J(n)}continue}if(o<" "&&o!==" ")throw J(n);t+=o}throw J(n)}function me(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 J(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 J(t);return-1}function za(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Qa(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Ya(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 Ya(e);if(typeof e=="string")return Xa(e,n);throw R(0,"not a primitive")}function Za(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function F(e){return Za(e)?e:So(e)}function Xa(e,n){return ed(e,n)?So(e):e}function ed(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Qa(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}function So(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 Pe(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}var wt=2;function nd(e={}){return{indent:Math.max(1,e.indent??wt),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function td(e,n){let t=[],r=!1;return Pn(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=nd(n),r=td(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=xt(o.content,T(o.content,":",o.number))}catch(u){if(t.strict)throw Rt(u,o.number);d=void 0}if(d!==void 0)return sd(d,r,t)}if(s&&T(o.content,":",o.number)===-1)return K(o.content.trim(),o.number);let i={index:0},l=_t(r,i,0,t),a=r[i.index];if(a!==void 0)throw R(a.number,"expected end of document");return l}function _t(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}=rd(e,n,t,r);jo(o,i,l,a,r,s.number)}return o}function rd(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 k;try{k=dd(l)}catch(b){if(r.strict)throw Rt(b,o.number);n.index+=1;let v=ht(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:v}}if(a.trim()!=="")throw R(o.number,"expected keyed map rows");let y=od(k,e,n,t+1,r);return{key:k.key,quoted:k.keyQuoted,value:y}}if(d!==-1){let k;try{k=xt(l,i)}catch(b){if(r.strict)throw Rt(b,o.number);n.index+=1;let v=ht(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:v}}if(k.key===""&&!k.keyQuoted)throw R(o.number,"expected non-empty field name");let y=vt(k,a,e,n,t,r);return{key:k.key,quoted:k.keyQuoted,value:y}}let[p,f]=ee(l,o.number);if(p===""&&!f)throw R(o.number,"expected non-empty field name");n.index+=1;let g=ht(e,n,t,a,o.number,r);return{key:p,quoted:f,value:g}}function ht(e,n,t,r,o,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return K(i,o);let l=e[n.index];return l!==void 0&&l.depth>t?_t(e,n,t+1,s):{}}function od(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]=ee(i.content.slice(0,l),i.number);if(a===""&&!d)throw R(i.number,"expected non-empty field name");let u=me(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((f,g)=>{Xe(p,f,K(u[g],i.number),o,i.number)}),jo(s,a,d,p,o,i.number),t.index+=1}return s}function sd(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=vt(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 vt(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=me(l,e.delimiter,i).map(d=>K(d,i));if(a.length!==e.len)throw R(i,"array length mismatch");return a}return ld(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 yt(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(!Eo(a.content,e.delimiter,a.number))break;let d=me(a.content,e.delimiter,a.number);if(d.length!==n.length)throw R(a.number,"array row length mismatch");let u={};n.forEach((p,f)=>{Xe(u,p,K(d[f],a.number),s,a.number)}),i.push(u),r.index+=1}if(i.length!==e.len)throw yt(t,r.index);let l=t[r.index];if(l!==void 0&&l.depth>=o&&Eo(l.content,e.delimiter,l.number))throw R(l.number,"array length mismatch");return i}function Eo(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 ld(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 yt(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(ad(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 ad(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=xt(s,i)}catch{l=void 0}if(l!==void 0){let a=s.slice(i+1);return vt(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 _t(i,{index:0},t+1,r)}return n.index+=1,K(s,o.number)}function yt(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function xt(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]=ee(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 f=i.slice(l+1),g;if(f==="")g=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{g=Po(f.slice(1,-1),p)}catch(k){throw R(0,k.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 dd(e){let n=T(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=ee(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=Po(e.slice(n+1,-1),P)}catch(s){throw R(0,s.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:P,fields:o}}function Po(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 f=e[r];if(f==='"'){s();continue}if(f===n||f==="{"||f==="}")break;r+=1}let[p]=ee(e.slice(u,r),0);if(p==="")throw R(0,"invalid array header");if(d+=1,e[r]==="{"){r+=1;let f=t.length;if(o([...l,p],!0),e[r]!=="}"||t.length===f)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(cd(t[l],t[a])||kt(t[l],t[a])||kt(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 cd(e,n){return e.length===n.length&&kt(e,n)}function kt(e,n){return n.every((t,r)=>e[r]===t)}function Rt(e,n){return R(n,e.reason??String(e.message))}function jo(e,n,t,r,o,s){if(o.expandPaths&&!t&&n.includes(".")){let i=n.split(".");if(i.every(ud)){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");Pe(e,s,t);return}if(i&&!je(e[s])){if(r.strict)throw R(o,"path expansion conflict");Pe(e,s,{})}else i||Pe(e,s,{});Xe(e[s],n.slice(1),t,r,o)}function ud(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function je(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)?St(r,void 0,e,0,!1,t):je(e)?Do(r,e,0,t):r.push(q(e,P)),r.join("")}function en(e,n){e.push(" ".repeat(n*wt))}function Do(e,n,t,r){for(let[o,s]of Object.entries(n))en(e,t),bt(e,o,s,t,r)}function bt(e,n,t,r,o){if(Array.isArray(t)){St(e,n,t,r,!1,o);return}if(je(t)){let s=o.keyedMapCollapse?fd(t,o):void 0;if(s!==void 0){e.push(F(n),"{",s.fields.map(Et).join(P),`}:
10
- `);for(let[i,l]of Object.entries(t))en(e,r+1),e.push(F(i),": ",s.paths.map(a=>q(Ao(l,a),P)).join(P),`
6
+ `)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};Su=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,tr=/^redskilled-(.+)\.bundle\.min\.mjs$/,Eu=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as Og}from"node:child_process";import{homedir as zr}from"node:os";import{join as _a}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}},fe=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 x(e,n){return new fe(e,n)}function Ee(e){return e instanceof fe?e:e instanceof Ye?new fe(e.line,e.reason):new fe(0,String(e&&e.message?e.message:e))}var P=",";function Dn(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 Eo(e,n);if(e.includes('"'))throw K(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:Ya(e)?Number(e):e}function ee(e,n){let t=e.trim();if(t.startsWith('"'))return[Eo(t,n),!0];if(t.includes('"')||/\s/.test(t))throw R(n,"expected non-empty field name");return[t,!1]}function Eo(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 me(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 Ya(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Za(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Xa(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 Xa(e);if(typeof e=="string")return nd(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:Po(e)}function nd(e,n){return td(e,n)?Po(e):e}function td(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Za(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}function Po(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 Pe(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}var xt=2;function rd(e={}){return{indent:Math.max(1,e.indent??xt),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function od(e,n){let t=[],r=!1;return Dn(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=rd(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 c;try{c=Pt(o.content,T(o.content,":",o.number))}catch(u){if(t.strict)throw _t(u,o.number);c=void 0}if(c!==void 0)return ld(c,r,t)}if(s&&T(o.content,":",o.number)===-1)return J(o.content.trim(),o.number);let i={index:0},l=St(r,i,0,t),a=r[i.index];if(a!==void 0)throw R(a.number,"expected end of document");return l}function St(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}=sd(e,n,t,r);Oo(o,i,l,a,r,s.number)}return o}function sd(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),c=T(l,"[",o.number),u=T(l,"{",o.number);if(u!==-1&&(c===-1||u<c)){let k;try{k=ud(l)}catch(b){if(r.strict)throw _t(b,o.number);n.index+=1;let v=kt(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:v}}if(a.trim()!=="")throw R(o.number,"expected keyed map rows");let y=id(k,e,n,t+1,r);return{key:k.key,quoted:k.keyQuoted,value:y}}if(c!==-1){let k;try{k=Pt(l,i)}catch(b){if(r.strict)throw _t(b,o.number);n.index+=1;let v=kt(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:v}}if(k.key===""&&!k.keyQuoted)throw R(o.number,"expected non-empty field name");let y=Et(k,a,e,n,t,r);return{key:k.key,quoted:k.keyQuoted,value:y}}let[p,f]=ee(l,o.number);if(p===""&&!f)throw R(o.number,"expected non-empty field name");n.index+=1;let h=kt(e,n,t,a,o.number,r);return{key:p,quoted:f,value:h}}function kt(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?St(e,n,t+1,s):{}}function id(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,c]=ee(i.content.slice(0,l),i.number);if(a===""&&!c)throw R(i.number,"expected non-empty field name");let u=me(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((f,h)=>{Xe(p,f,J(u[h],i.number),o,i.number)}),Oo(s,a,c,p,o,i.number),t.index+=1}return s}function ld(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=Et(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 Et(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 ad(e,e.fields,t,r,o+1,s)}if(l!==""){let a=me(l,e.delimiter,i).map(c=>J(c,i));if(a.length!==e.len)throw R(i,"array length mismatch");return a}return dd(e,t,r,o+1,s)}function ad(e,n,t,r,o,s){let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0)throw bt(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(!jo(a.content,e.delimiter,a.number))break;let c=me(a.content,e.delimiter,a.number);if(c.length!==n.length)throw R(a.number,"array row length mismatch");let u={};n.forEach((p,f)=>{Xe(u,p,J(c[f],a.number),s,a.number)}),i.push(u),r.index+=1}if(i.length!==e.len)throw bt(t,r.index);let l=t[r.index];if(l!==void 0&&l.depth>=o&&jo(l.content,e.delimiter,l.number))throw R(l.number,"array length mismatch");return i}function jo(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 dd(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 bt(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(cd(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 cd(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=Pt(s,i)}catch{l=void 0}if(l!==void 0){let a=s.slice(i+1);return Et(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 St(i,{index:0},t+1,r)}return n.index+=1,J(s,o.number)}function bt(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function Pt(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]=ee(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),c=/^[0-9]*/.exec(a)[0];if(c===""||c.length>1&&c.startsWith("0"))throw R(0,"invalid array header");let u=Number.parseInt(c,10),p;switch(a.slice(c.length)){case"":p=",";break;case" ":p=" ";break;case"|":p="|";break;default:throw R(0,"invalid array header")}let f=i.slice(l+1),h;if(f==="")h=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{h=Do(f.slice(1,-1),p)}catch(k){throw R(0,k.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:h}}function ud(e){let n=T(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=ee(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=Do(e.slice(n+1,-1),P)}catch(s){throw R(0,s.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:P,fields:o}}function Do(e,n){let t=[],r=0;function o(l,a){let c=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 f=e[r];if(f==='"'){s();continue}if(f===n||f==="{"||f==="}")break;r+=1}let[p]=ee(e.slice(u,r),0);if(p==="")throw R(0,"invalid array header");if(c+=1,e[r]==="{"){r+=1;let f=t.length;if(o([...l,p],!0),e[r]!=="}"||t.length===f)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(c===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(pd(t[l],t[a])||wt(t[l],t[a])||wt(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 pd(e,n){return e.length===n.length&&wt(e,n)}function wt(e,n){return n.every((t,r)=>e[r]===t)}function _t(e,n){return R(n,e.reason??String(e.message))}function Oo(e,n,t,r,o,s){if(o.expandPaths&&!t&&n.includes(".")){let i=n.split(".");if(i.every(fd)){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");Pe(e,s,t);return}if(i&&!je(e[s])){if(r.strict)throw R(o,"path expansion conflict");Pe(e,s,{})}else i||Pe(e,s,{});Xe(e[s],n.slice(1),t,r,o)}function fd(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function je(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)?jt(r,void 0,e,0,!1,t):je(e)?$o(r,e,0,t):r.push(q(e,P)),r.join("")}function en(e,n){e.push(" ".repeat(n*xt))}function $o(e,n,t,r){for(let[o,s]of Object.entries(n))en(e,t),vt(e,o,s,t,r)}function vt(e,n,t,r,o){if(Array.isArray(t)){jt(e,n,t,r,!1,o);return}if(je(t)){let s=o.keyedMapCollapse?hd(t,o):void 0;if(s!==void 0){e.push(F(n),"{",s.fields.map(Dt).join(P),`}:
10
+ `);for(let[i,l]of Object.entries(t))en(e,r+1),e.push(F(i),": ",s.paths.map(a=>q(To(l,a),P)).join(P),`
11
11
  `);return}e.push(F(n),`:
12
- `),Do(e,t,r+1,o);return}e.push(F(n),": ",q(t,P),`
13
- `)}function St(e,n,t,r,o,s){if(t.length===0){n!==void 0?e.push(F(n),`: []
12
+ `),$o(e,t,r+1,o);return}e.push(F(n),": ",q(t,P),`
13
+ `)}function jt(e,n,t,r,o,s){if(t.length===0){n!==void 0?e.push(F(n),`: []
14
14
  `):o?e.push(`[0]:
15
15
  `):e.push(`[]
16
- `);return}if(t.every(Ze)){gt(e,n,t.length,void 0),e.push(" "),e.push(t.map(l=>q(l,P)).join(P)),e.push(`
17
- `);return}let i=o?void 0:Oo(t,s);if(i!==void 0){gt(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(Ao(l,a),P)).join(P)),e.push(`
19
- `);return}gt(e,n,t.length,void 0),e.push(`
20
- `);for(let l of t)en(e,r+1),pd(e,l,r+1,s)}function pd(e,n,t,r){if(Array.isArray(n)){e.push("- "),St(e,void 0,n,t,!0,r);return}if(je(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
21
- `);return}e.push("- "),bt(e,o[0][0],o[0][1],t+1,r);for(let[s,i]of o.slice(1))en(e,t+1),bt(e,s,i,t+1,r);return}e.push("- ",q(n,P),`
22
- `)}function gt(e,n,t,r){n!==void 0&&e.push(F(n)),e.push("[",String(t),"]"),r!==void 0&&e.push("{",r.map(Et).join(P),"}"),e.push(":")}function Oo(e,n){let t=Lo(e.map(r=>({value:r})),n);return t===void 0?void 0:{fields:t,paths:$o(t)}}function fd(e,n){let t=Object.values(e);if(!(t.length<2))return Oo(t,n)}function Lo(e,n){let t=e[0]?.value;if(!je(t))return;let r=Object.keys(t).map(o=>({key:o}));if(r.length!==0){for(let{value:o}of e)if(!je(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=Lo(s,n);if(i===void 0)return;o.children=i}return r}}function $o(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children===void 0?[r]:$o(t.children,r)})}function Ao(e,n){let t=e;for(let r of n)t=t[r];return t}function Et(e){return e.children===void 0?F(e.key):`${F(e.key)}{${e.children.map(Et).join(P)}}`}var Uo=[P,"|"," "];var Ho=8,Vo=/^[A-Za-z0-9_-]+$/,ey=new TextEncoder,ny=new TextDecoder;function hd(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw x(n,"invalid trailer count");return Number.parseInt(t,10)}function Bo(e,n){if(!Vo.test(e))throw x(n,"invalid tag")}function gd(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!Vo.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw x(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function yd(e,n){if(!e.startsWith("["))return null;let t=e.slice(1),r=t.indexOf("]");if(r===-1)throw x(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(!Uo.includes(i)&&i!=="")throw x(n,"invalid header delimiter");let l=i===""?P:i,a=t.slice(r+1),d=null;if(!s&&a.startsWith("<")){let f=a.indexOf(">");if(f===-1)throw x(n,"invalid tag");if(d=a.slice(1,f),Bo(d,n),i!=="")throw x(n,"invalid header delimiter");a=a.slice(f+1)}if(!a.startsWith("{")||!a.endsWith("}:"))throw x(n,"invalid header");let u=a.slice(1,-2),p;try{p=me(u,l,n).map(f=>ee(f,n)[0])}catch(f){throw Ee(f)}if(p.length===0||p.some(f=>f===""))throw x(n,"invalid header fields");return{delimiter:l,fields:p,fieldText:u,continuation:s,tag:d}}function kd(e,n,t){if(e===null||e.delimiter===void 0)throw x(t,"continuation header before header");if(e.delimiter!==n.delimiter||e.fieldText!==n.fieldText)throw x(t,"continuation header mismatch")}function Io(e,n,t,r){let o;try{o=me(e,n,r)}catch(s){throw Ee(s)}if(o.length!==t)throw x(r,"row arity mismatch");for(let s of o)try{K(s,r)}catch(i){throw Ee(i)}return o}function Rd(e,n,t){let r={};return e.forEach((o,s)=>{try{Pe(r,o,K(n[s],t))}catch(i){throw Ee(i)}}),r}function bd(e,n,t){if(e.startsWith("- "))throw x(n,"reserved line prefix");let r=hd(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw x(n,"trailer without header");if(t.rowCount!==r)throw x(n,"trailer count mismatch");return{kind:"trailer"}}let o=yd(e,n);if(o!==null)return o.continuation?(kd(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=gd(e,n);if(s!==null){let i=t?.taggedLanes?.get(s.tag);if(i===void 0)throw x(n,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:Io(s.cellsText,i.delimiter,i.fields.length,n)}}if(t===null||t.delimiter===void 0)throw x(n,"row before header");return{kind:"row",cells:Io(e,t.delimiter,t.fields.length,n)}}function wd(e,n={}){let t=[],r=new Map,o=[],s=[],i=null,l=!1,a=!1;function d(g,k){let y=s.at(-1);if(y!==void 0&&y.lane===g.lane&&y.delimiter===g.delimiter&&y.fieldText===g.fieldText){y.rows.push(k);return}s.push({lane:g.lane,delimiter:g.delimiter,fields:g.fields,fieldText:g.fieldText,rows:[k]})}function u(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function p(g,k,y){let b=r.get(g);if(b===void 0){if(r.size>=Ho)throw x(y,"too many tagged lanes");b={segments:[],current:null},r.set(g,b),t.push(g)}else b.current!==null&&b.segments.push(b.current);b.current={lane:g,delimiter:k.delimiter,fields:k.fields,fieldText:k.fieldText,rows:[]},b.delimiter=k.delimiter,b.fields=k.fields,b.fieldText=k.fieldText}if(Pn(e).forEach((g,k)=>{let y=k+1;if(g==="")return;let b=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},v=bd(g,y,b);if(v.kind==="trailer"){u(),i=null;return}if(v.kind!=="continuation"){if(v.kind==="tag-header"){a=!0,p(v.header.tag,v.header,y);return}if(v.kind==="header"){u(),l||(t.push(null),l=!0),i={lane:null,delimiter:v.header.delimiter,fields:v.header.fields,fieldText:v.header.fieldText,rows:[]};return}if(v.kind==="tagged-row"){a=!0;let D=r.get(v.tag).current;D.rows.push(v.cells),d(D,v.cells);return}if(i===null)throw x(y,"row before header");i.rows.push(v.cells),d(i,v.cells)}}),!a)return u(),n.preserveInterleaving===!0,o;let f=[];u();for(let g of t){if(g===null){f.push(...o);continue}let k=r.get(g);f.push(...k.segments),k.current!==null&&f.push(k.current)}return n.preserveInterleaving===!0?s:f}function ae(e){return wd(e).flatMap(n=>n.rows.map(t=>Rd(n.fields,t,0)))}function _d(e){if(!Uo.includes(e))throw x(0,"invalid header delimiter")}function To(e,n,t=!1){return`[${`${t?"~":""}${e===P?"":e}`}]{${n}}:
23
- `}function No(e,n){return`[]<${e}>{${n}}:
24
- `}function Pt(e,n){return n.map(F).join(e)}function vd(e){if(!Array.isArray(e)||e.length===0)throw x(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=ee(String(n),0)}catch(r){throw Ee(r)}if(t==="")throw x(0,"TOONL header requires fields");return t})}function Wo(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function Co(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw x(0,"TOONL continuation cadence must be positive")}function xd(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function Mo(e){if(e===null||typeof e!="object"||Array.isArray(e))throw x(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw x(0,"TOONL output requires object rows");if(n.some(t=>!Ze(e[t])))throw x(0,"TOONL rows must be flat objects");return n}function Sd(e){return JSON.stringify([...e].sort())}function Fo(e,n){let t=Sd(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function ne({delimiter:e=P,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){_d(e),Co(t),Co(r);let o=null,s="",i=new Map,l=0,a=0,d=0,u=new Map,p=!1,f={continuationEveryRows:t,continuationEveryBytes:r},g=()=>o===null||!n?"":`[=${l}]
25
- `,k=()=>xd(f,a,d)?(a=0,d=0,To(e,s,!0)):"",y=b=>{Bo(b,0);let v=u.get(b);if(v===void 0){if(u.size>=Ho)throw x(0,"too many tagged lanes");v={fields:null,fieldsByShape:new Map},u.set(b,v)}return v};return{push(b){if(p)throw x(0,"TOONL encoder is closed");let v=Fo(Mo(b),i),D="";(o===null||o.length!==v.length||o.some((pe,we)=>pe!==v[we]))&&(D+=g(),o=v,s=Pt(e,o),l=0,a=0,d=0,D+=To(e,s));let V=o.map(pe=>q(b[pe],e));D+=k();let M=`${V.join(e)}
26
- `;return D+=M,l+=1,a+=1,d+=M.length,D},declareLane(b,v){if(p)throw x(0,"TOONL encoder is closed");let D=vd(v),V=Pt(P,D),M=y(b);return Wo(M.fields,D)?"":(M.fields=D,No(b,V))},pushTagged(b,v){if(p)throw x(0,"TOONL encoder is closed");let D=y(b),V=Fo(Mo(v),D.fieldsByShape),M=Pt(P,V),pe=V.map(hn=>q(v[hn],P)),we="";return Wo(D.fields,V)||(D.fields=V,we+=No(b,M)),`${we}${b}:${pe.join(P)}
27
- `},end(){return p?"":(p=!0,g())}}}function jt(e){let n={app:e,version:Ed(De("__RED_BUILD_VERSION__",()=>"3.3.3")??"0.0.0-dev"),gitSha:De("__RED_BUILD_GIT_SHA__",()=>"48bced2cd328d5bdba9643bb4019f89d054bcdfe")??"unknown",buildTime:De("__RED_BUILD_TIME__",()=>"2026-08-02T01:21:24Z")??"unknown",bundleAsset:De("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=De("__REDDB_SDK_VERSION__",()=>""),r=De("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function Ed(e){return e.startsWith("v")?e.slice(1):e}function Jo(e){return`${e.app} ${e.version} ${e.gitSha}`}function De(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var Ko={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Pd=/^[a-z][a-z0-9+.-]*:\/\//i;function jd(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 Dd(e=Ko){return Object.entries(e).map(([n,t])=>jd(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function Od(e){return/^-\d+(\.\d+)?$/.test(e)}function nn(e){return!(!e||e.startsWith("-")&&!Od(e))}function jn(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 qo(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=>qo(t.trim())):e}function he(e,n){switch(n){case"boolean":return Ld(e);case"number":return $d(e);case"array":return e.split(",").map(t=>jn(t.trim()));case"string":default:return e}}function Ld(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function $d(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 de(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Ad(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 Id(e){let n=[],t=Nd(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
16
+ `);return}if(t.every(Ze)){Rt(e,n,t.length,void 0),e.push(" "),e.push(t.map(l=>q(l,P)).join(P)),e.push(`
17
+ `);return}let i=o?void 0:Ao(t,s);if(i!==void 0){Rt(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(To(l,a),P)).join(P)),e.push(`
19
+ `);return}Rt(e,n,t.length,void 0),e.push(`
20
+ `);for(let l of t)en(e,r+1),md(e,l,r+1,s)}function md(e,n,t,r){if(Array.isArray(n)){e.push("- "),jt(e,void 0,n,t,!0,r);return}if(je(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
21
+ `);return}e.push("- "),vt(e,o[0][0],o[0][1],t+1,r);for(let[s,i]of o.slice(1))en(e,t+1),vt(e,s,i,t+1,r);return}e.push("- ",q(n,P),`
22
+ `)}function Rt(e,n,t,r){n!==void 0&&e.push(F(n)),e.push("[",String(t),"]"),r!==void 0&&e.push("{",r.map(Dt).join(P),"}"),e.push(":")}function Ao(e,n){let t=Lo(e.map(r=>({value:r})),n);return t===void 0?void 0:{fields:t,paths:Io(t)}}function hd(e,n){let t=Object.values(e);if(!(t.length<2))return Ao(t,n)}function Lo(e,n){let t=e[0]?.value;if(!je(t))return;let r=Object.keys(t).map(o=>({key:o}));if(r.length!==0){for(let{value:o}of e)if(!je(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=Lo(s,n);if(i===void 0)return;o.children=i}return r}}function Io(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children===void 0?[r]:Io(t.children,r)})}function To(e,n){let t=e;for(let r of n)t=t[r];return t}function Dt(e){return e.children===void 0?F(e.key):`${F(e.key)}{${e.children.map(Dt).join(P)}}`}var Bo=[P,"|"," "];var Vo=8,Ko=/^[A-Za-z0-9_-]+$/,ay=new TextEncoder,dy=new TextDecoder;function yd(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw x(n,"invalid trailer count");return Number.parseInt(t,10)}function Jo(e,n){if(!Ko.test(e))throw x(n,"invalid tag")}function kd(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!Ko.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw x(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function Rd(e,n){if(!e.startsWith("["))return null;let t=e.slice(1),r=t.indexOf("]");if(r===-1)throw x(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(!Bo.includes(i)&&i!=="")throw x(n,"invalid header delimiter");let l=i===""?P:i,a=t.slice(r+1),c=null;if(!s&&a.startsWith("<")){let f=a.indexOf(">");if(f===-1)throw x(n,"invalid tag");if(c=a.slice(1,f),Jo(c,n),i!=="")throw x(n,"invalid header delimiter");a=a.slice(f+1)}if(!a.startsWith("{")||!a.endsWith("}:"))throw x(n,"invalid header");let u=a.slice(1,-2),p;try{p=me(u,l,n).map(f=>ee(f,n)[0])}catch(f){throw Ee(f)}if(p.length===0||p.some(f=>f===""))throw x(n,"invalid header fields");return{delimiter:l,fields:p,fieldText:u,continuation:s,tag:c}}function bd(e,n,t){if(e===null||e.delimiter===void 0)throw x(t,"continuation header before header");if(e.delimiter!==n.delimiter||e.fieldText!==n.fieldText)throw x(t,"continuation header mismatch")}function No(e,n,t,r){let o;try{o=me(e,n,r)}catch(s){throw Ee(s)}if(o.length!==t)throw x(r,"row arity mismatch");for(let s of o)try{J(s,r)}catch(i){throw Ee(i)}return o}function wd(e,n,t){let r={};return e.forEach((o,s)=>{try{Pe(r,o,J(n[s],t))}catch(i){throw Ee(i)}}),r}function _d(e,n,t){if(e.startsWith("- "))throw x(n,"reserved line prefix");let r=yd(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw x(n,"trailer without header");if(t.rowCount!==r)throw x(n,"trailer count mismatch");return{kind:"trailer"}}let o=Rd(e,n);if(o!==null)return o.continuation?(bd(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=kd(e,n);if(s!==null){let i=t?.taggedLanes?.get(s.tag);if(i===void 0)throw x(n,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:No(s.cellsText,i.delimiter,i.fields.length,n)}}if(t===null||t.delimiter===void 0)throw x(n,"row before header");return{kind:"row",cells:No(e,t.delimiter,t.fields.length,n)}}function vd(e,n={}){let t=[],r=new Map,o=[],s=[],i=null,l=!1,a=!1;function c(h,k){let y=s.at(-1);if(y!==void 0&&y.lane===h.lane&&y.delimiter===h.delimiter&&y.fieldText===h.fieldText){y.rows.push(k);return}s.push({lane:h.lane,delimiter:h.delimiter,fields:h.fields,fieldText:h.fieldText,rows:[k]})}function u(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function p(h,k,y){let b=r.get(h);if(b===void 0){if(r.size>=Vo)throw x(y,"too many tagged lanes");b={segments:[],current:null},r.set(h,b),t.push(h)}else b.current!==null&&b.segments.push(b.current);b.current={lane:h,delimiter:k.delimiter,fields:k.fields,fieldText:k.fieldText,rows:[]},b.delimiter=k.delimiter,b.fields=k.fields,b.fieldText=k.fieldText}if(Dn(e).forEach((h,k)=>{let y=k+1;if(h==="")return;let b=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},v=_d(h,y,b);if(v.kind==="trailer"){u(),i=null;return}if(v.kind!=="continuation"){if(v.kind==="tag-header"){a=!0,p(v.header.tag,v.header,y);return}if(v.kind==="header"){u(),l||(t.push(null),l=!0),i={lane:null,delimiter:v.header.delimiter,fields:v.header.fields,fieldText:v.header.fieldText,rows:[]};return}if(v.kind==="tagged-row"){a=!0;let D=r.get(v.tag).current;D.rows.push(v.cells),c(D,v.cells);return}if(i===null)throw x(y,"row before header");i.rows.push(v.cells),c(i,v.cells)}}),!a)return u(),n.preserveInterleaving===!0,o;let f=[];u();for(let h of t){if(h===null){f.push(...o);continue}let k=r.get(h);f.push(...k.segments),k.current!==null&&f.push(k.current)}return n.preserveInterleaving===!0?s:f}function ae(e){return vd(e).flatMap(n=>n.rows.map(t=>wd(n.fields,t,0)))}function xd(e){if(!Bo.includes(e))throw x(0,"invalid header delimiter")}function Wo(e,n,t=!1){return`[${`${t?"~":""}${e===P?"":e}`}]{${n}}:
23
+ `}function Co(e,n){return`[]<${e}>{${n}}:
24
+ `}function Ot(e,n){return n.map(F).join(e)}function Sd(e){if(!Array.isArray(e)||e.length===0)throw x(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=ee(String(n),0)}catch(r){throw Ee(r)}if(t==="")throw x(0,"TOONL header requires fields");return t})}function Mo(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function Fo(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw x(0,"TOONL continuation cadence must be positive")}function Ed(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function Ho(e){if(e===null||typeof e!="object"||Array.isArray(e))throw x(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw x(0,"TOONL output requires object rows");if(n.some(t=>!Ze(e[t])))throw x(0,"TOONL rows must be flat objects");return n}function Pd(e){return JSON.stringify([...e].sort())}function Uo(e,n){let t=Pd(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function ne({delimiter:e=P,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){xd(e),Fo(t),Fo(r);let o=null,s="",i=new Map,l=0,a=0,c=0,u=new Map,p=!1,f={continuationEveryRows:t,continuationEveryBytes:r},h=()=>o===null||!n?"":`[=${l}]
25
+ `,k=()=>Ed(f,a,c)?(a=0,c=0,Wo(e,s,!0)):"",y=b=>{Jo(b,0);let v=u.get(b);if(v===void 0){if(u.size>=Vo)throw x(0,"too many tagged lanes");v={fields:null,fieldsByShape:new Map},u.set(b,v)}return v};return{push(b){if(p)throw x(0,"TOONL encoder is closed");let v=Uo(Ho(b),i),D="";(o===null||o.length!==v.length||o.some((pe,we)=>pe!==v[we]))&&(D+=h(),o=v,s=Ot(e,o),l=0,a=0,c=0,D+=Wo(e,s));let B=o.map(pe=>q(b[pe],e));D+=k();let M=`${B.join(e)}
26
+ `;return D+=M,l+=1,a+=1,c+=M.length,D},declareLane(b,v){if(p)throw x(0,"TOONL encoder is closed");let D=Sd(v),B=Ot(P,D),M=y(b);return Mo(M.fields,D)?"":(M.fields=D,Co(b,B))},pushTagged(b,v){if(p)throw x(0,"TOONL encoder is closed");let D=y(b),B=Uo(Ho(v),D.fieldsByShape),M=Ot(P,B),pe=B.map(yn=>q(v[yn],P)),we="";return Mo(D.fields,B)||(D.fields=B,we+=Co(b,M)),`${we}${b}:${pe.join(P)}
27
+ `},end(){return p?"":(p=!0,h())}}}function $t(e){let n={app:e,version:jd(De("__RED_BUILD_VERSION__",()=>"3.3.5")??"0.0.0-dev"),gitSha:De("__RED_BUILD_GIT_SHA__",()=>"d998784c44f7106d92ded51ffab6e8e18e98c962")??"unknown",buildTime:De("__RED_BUILD_TIME__",()=>"2026-08-02T02:14:05Z")??"unknown",bundleAsset:De("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=De("__REDDB_SDK_VERSION__",()=>""),r=De("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function jd(e){return e.startsWith("v")?e.slice(1):e}function qo(e){return`${e.app} ${e.version} ${e.gitSha}`}function De(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var Go={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Dd=/^[a-z][a-z0-9+.-]*:\/\//i;function Od(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 $d(e=Go){return Object.entries(e).map(([n,t])=>Od(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function Ad(e){return/^-\d+(\.\d+)?$/.test(e)}function nn(e){return!(!e||e.startsWith("-")&&!Ad(e))}function On(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 zo(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=>zo(t.trim())):e}function he(e,n){switch(n){case"boolean":return Ld(e);case"number":return Id(e);case"array":return e.split(",").map(t=>On(t.trim()));case"string":default:return e}}function Ld(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function Id(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 de(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Td(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 Nd(e){let n=[],t=Cd(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
28
28
  `),E("newline",`
29
29
  `)),e.positional&&e.positional.length>0){n.push(E("section-header","Arguments:"),E("newline",`
30
30
  `));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
31
  `),E("indent"," "),E("option-description",r.description),E("newline",`
32
32
  `))}n.push(E("newline",`
33
33
  `))}if(e.options&&Object.keys(e.options).length>0){n.push(E("section-header","Options:"),E("newline",`
34
- `));let r=Wd(e.options);n.push(...r)}return n}function Td(e,n){let t=Id(e);return Ad(t,n)}function Nd(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 Wd(e,n=!1){let t=[],r=[],o=n?"global-option-flag":"option-flag",s=n?"global-option-type":"option-type",i=n?"global-option-default":"option-default",l=n?"global-option-description":"option-description";for(let[d,u]of Object.entries(e)){if(u.hidden)continue;let p=[],f=y=>{p.includes(y)||p.push(y)};u.short&&f(`-${u.short}`),f(`--${d}`);for(let y of u.aliases??[])y.length===1?f(`-${y}`):f(`--${y}`);let g=p.join(", "),k=u.type&&u.type!=="boolean"?`<${u.type}>`:void 0;r.push({flags:g,type:k,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 Go(e){let n=Bd(e.options??{},e.autoShort??!1),t=Dd(e.separators??Ko);return{schema:e,parse(r){return Cd(r,e,n,t)},help(){return Td(e,e.formatter)}}}function Cd(e,n,t,r){let o={positional:{},options:{},errors:[],rest:[]},s=new Set(r.map(u=>u.to));for(let u of s)o[u]={};let i=0,l=n.positional??[],a=0,d=!1;for(;a<e.length;){let u=e[a];if(n.stopEarly&&i>0){o.rest=e.slice(a);break}if(u==="--"&&!d){d=!0,a++;continue}if(d){if(i<l.length){let f=l[i];if(f.variadic){let g=[];for(;a<e.length;){let k=e[a];g.push(f.type?he(k,f.type):k),a++}o.positional[f.name]=g,i++}else{let g=f.type?he(u,f.type):u;o.positional[f.name]=g,i++,a++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(u)),a++;continue}if(u.startsWith("--")){a=Hd(u,a,e,o,t,n);continue}if(u.startsWith("-")&&u.length>1&&!zd(u)){a=Vd(u,a,e,o,t,n);continue}let p=Md(u,r);if(p){let{key:f,value:g,config:k}=p,y=o,b=y[k.to]??(y[k.to]={});b[f]=k.typed?qo(g):de(g),a++;continue}if(i<l.length){let f=l[i];if(f.variadic){let k=[];for(;a<e.length&&!e[a].startsWith("-");){let y=e[a];k.push(f.type?he(y,f.type):y),a++}o.positional[f.name]=k,i++;continue}let g=f.type?he(u,f.type):u;o.positional[f.name]=g,i++}else n.allowUnknown!==!1?o.rest.push(u):o.errors.push(`Unexpected positional argument: ${u}`);a++}return Kd(o,n,t),qd(o,n,l),Gd(o,n,t),o}function Md(e,n){if(Pd.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(Fd(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(Ud(o,s,t))return{key:o,value:s,config:t}}}return null}function Fd(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function Ud(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 Hd(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 Dn(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)?Dn(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 Vd(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=Dt(a,o);return u?Dn(u.name,d,n+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=jn(de(d))),n+1)}if(i.length===1){let l=Dt(i,o);if(l){if(l.type!=="boolean"){let a=t[n+1];return nn(a)?Dn(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]=jn(de(a)),n+2;r.options[i]=!0}return n+1}for(let l of i){let a=Dt(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 Dn(e,n,t,r,o,s){let i=o.get(e);if(i){if(i.choices){let a=i.type?he(de(n),i.type):de(n);if(!i.choices.includes(a))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${i.choices.join(", ")}`),t}let l=i.type?he(de(n),i.type):de(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]=jn(de(n)));return t}function Bd(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=Jd(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 Jd(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 Dt(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function Kd(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?he(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 qd(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 Gd(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 zd(e){return/^-\d+(\.\d+)?$/.test(e)}var Ot=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 Qd(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 Yd(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 ge(e,n,t={}){let o=Go({options:Qd(n),separators:{},allowUnknown:!0}).parse([...e]),s={},i=Yd(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 Ot(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 Lt=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 zo(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 Lt(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as ac,mkdirSync as dc,readFileSync as ts,statSync as cc}from"node:fs";import{dirname as os,join as uc}from"node:path";import{mkdirSync as ec,readdirSync as nc,readFileSync as Xo,rmSync as tc,writeFileSync as rc}from"node:fs";import{basename as oc,join as Oe}from"node:path";import{isAbsolute as $y,join as On,resolve as Ay}from"node:path";function Zd(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var Qo="deaths",Yo="deaths.toonl";function Ln(e){return On(Zd(e),Qo)}function tn(e){return On(Ln(e),Yo)}var rn="live",Zo="attributions.toonl";function $n(e){return On(Ln(e),rn)}function $t(e){return On(Ln(e),Zo)}var It=Oe("sys","kernel","random","boot_id"),es=1;function Tt(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:es,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:ns(Oe(t,It)),cgroup:sc(t,r),last_phase:e.last_phase}}function ns(e){try{let n=Xo(e,"utf8").trim();return n===""?null:n}catch{return null}}function sc(e,n){let t=ns(Oe(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 Nt(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function Wt(e,n){let t=Oe(e,Nt(n));try{return ec(e,{recursive:!0,mode:448}),rc(t,ne({trailer:!1}).push(lc(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function ye(e,n){try{tc(Oe(e,Nt(n)),{force:!0})}catch{}}function Ct(e,n){let t;try{t=nc(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=Oe(e,o);try{let l=ae(Xo(s,"utf8"))[0];if(l===void 0)throw new Error("anchor holds no record");r.push(ic(l))}catch(i){n?.(oc(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:At(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:At(e.pid),ppid:At(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 At(e){return typeof e=="number"?e:Number(e)}function lc(e){return{...e}}var pc=1,fc=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function mc(e){return typeof e=="string"&&fc.has(e)}var hc="startup";function gc(e,n){return{version:pc,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 yc(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 Ft={mkdir(e){dc(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=cc(e).size}catch{return!0}if(n===0)return!0;try{return ts(e,"utf8").endsWith(`
37
- `)}catch{return!0}},append(e,n){ac(e,n,{encoding:"utf8",mode:384})},read(e){return ts(e,"utf8")}};function kc(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function Rc(e,n,t=Ft){let r=ne({trailer:!1}).push(kc(n));return t.mkdir(os(e)),t.endsClean(e)||t.append(e,`
38
- `),t.append(e,r),n}function ss(e){let n=e.endsWith(`
34
+ `));let r=Md(e.options);n.push(...r)}return n}function Wd(e,n){let t=Nd(e);return Td(t,n)}function Cd(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 Md(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[c,u]of Object.entries(e)){if(u.hidden)continue;let p=[],f=y=>{p.includes(y)||p.push(y)};u.short&&f(`-${u.short}`),f(`--${c}`);for(let y of u.aliases??[])y.length===1?f(`-${y}`):f(`--${y}`);let h=p.join(", "),k=u.type&&u.type!=="boolean"?`<${u.type}>`:void 0;r.push({flags:h,type:k,desc:u.description??"",default:u.default!==void 0?String(u.default):void 0})}let a=Math.max(...r.map(c=>c.flags.length+(c.type?c.type.length+1:0)),20);for(let c of r){let u=c.flags.length+(c.type?c.type.length+1:0),p=" ".repeat(a-u+2);t.push(E("indent"," ")),t.push(E(o,c.flags)),c.type&&(t.push(E("text"," ")),t.push(E(s,c.type))),t.push(E("text",p)),t.push(E(l,c.desc)),c.default!==void 0&&(t.push(E("text"," ")),t.push(E(i,`(default: ${c.default})`))),t.push(E("newline",`
35
+ `))}return t}function Qo(e){let n=Jd(e.options??{},e.autoShort??!1),t=$d(e.separators??Go);return{schema:e,parse(r){return Fd(r,e,n,t)},help(){return Wd(e,e.formatter)}}}function Fd(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,c=!1;for(;a<e.length;){let u=e[a];if(n.stopEarly&&i>0){o.rest=e.slice(a);break}if(u==="--"&&!c){c=!0,a++;continue}if(c){if(i<l.length){let f=l[i];if(f.variadic){let h=[];for(;a<e.length;){let k=e[a];h.push(f.type?he(k,f.type):k),a++}o.positional[f.name]=h,i++}else{let h=f.type?he(u,f.type):u;o.positional[f.name]=h,i++,a++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(u)),a++;continue}if(u.startsWith("--")){a=Vd(u,a,e,o,t,n);continue}if(u.startsWith("-")&&u.length>1&&!Yd(u)){a=Kd(u,a,e,o,t,n);continue}let p=Hd(u,r);if(p){let{key:f,value:h,config:k}=p,y=o,b=y[k.to]??(y[k.to]={});b[f]=k.typed?zo(h):de(h),a++;continue}if(i<l.length){let f=l[i];if(f.variadic){let k=[];for(;a<e.length&&!e[a].startsWith("-");){let y=e[a];k.push(f.type?he(y,f.type):y),a++}o.positional[f.name]=k,i++;continue}let h=f.type?he(u,f.type):u;o.positional[f.name]=h,i++}else n.allowUnknown!==!1?o.rest.push(u):o.errors.push(`Unexpected positional argument: ${u}`);a++}return Gd(o,n,t),zd(o,n,l),Qd(o,n,t),o}function Hd(e,n){if(Dd.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(Ud(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(Bd(o,s,t))return{key:o,value:s,config:t}}}return null}function Ud(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function Bd(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 Vd(e,n,t,r,o,s){let i=e.slice(2);if(i.startsWith("no-")){let a=i.slice(3),c=o.get(a);if(c?.negatable!==!1&&c?.type==="boolean")return r.options[c.name]=!1,n+1}if(i.includes("=")){let a=i.indexOf("="),c=i.slice(0,a),u=i.slice(a+1);return $n(c,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)?$n(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 Kd(e,n,t,r,o,s){let i=e.slice(1);if(i.includes("=")){let l=i.indexOf("="),a=i.slice(0,l),c=i.slice(l+1),u=At(a,o);return u?$n(u.name,c,n+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=On(de(c))),n+1)}if(i.length===1){let l=At(i,o);if(l){if(l.type!=="boolean"){let a=t[n+1];return nn(a)?$n(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]=On(de(a)),n+2;r.options[i]=!0}return n+1}for(let l of i){let a=At(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 $n(e,n,t,r,o,s){let i=o.get(e);if(i){if(i.choices){let a=i.type?he(de(n),i.type):de(n);if(!i.choices.includes(a))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${i.choices.join(", ")}`),t}let l=i.type?he(de(n),i.type):de(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]=On(de(n)));return t}function Jd(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=qd(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 c of a.aliases)t.set(c,a)}return t}function qd(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 At(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function Gd(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?he(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 zd(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 Qd(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 Yd(e){return/^-\d+(\.\d+)?$/.test(e)}var Lt=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 Zd(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 Xd(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 c=r.get(l)??[];c.push(a),r.set(l,c)}return r}function ge(e,n,t={}){let o=Qo({options:Zd(n),separators:{},allowUnknown:!0}).parse([...e]),s={},i=Xd(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 c of Object.keys(o.options))if(!a.has(c))throw new Lt(c.length===1?`-${c}`:`--${c}`,Object.keys(n).map(u=>u.length===1?`-${u}`:`--${u}`))}for(let[a,c]of Object.entries(n)){let u=o.options[a];u!==void 0&&(c.kind==="boolean"?s[a]=u:c.type==="array"?s[a]=(i.get(a)??[]).map(p=>c.coerce(p)):s[a]=c.coerce(String(u)))}return{values:s,positionals:o.rest}}var It=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 Yo(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 It(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as cc,mkdirSync as uc,readFileSync as os,statSync as pc}from"node:fs";import{dirname as is,join as fc}from"node:path";import{mkdirSync as tc,readdirSync as rc,readFileSync as ns,rmSync as oc,writeFileSync as sc}from"node:fs";import{basename as ic,join as Oe}from"node:path";import{isAbsolute as Fy,join as An,resolve as Hy}from"node:path";function ec(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var Zo="deaths",Xo="deaths.toonl";function Ln(e){return An(ec(e),Zo)}function tn(e){return An(Ln(e),Xo)}var rn="live",es="attributions.toonl";function In(e){return An(Ln(e),rn)}function Tt(e){return An(Ln(e),es)}var Wt=Oe("sys","kernel","random","boot_id"),ts=1;function Ct(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:ts,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:rs(Oe(t,Wt)),cgroup:lc(t,r),last_phase:e.last_phase}}function rs(e){try{let n=ns(e,"utf8").trim();return n===""?null:n}catch{return null}}function lc(e,n){let t=rs(Oe(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 Mt(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function Ft(e,n){let t=Oe(e,Mt(n));try{return tc(e,{recursive:!0,mode:448}),sc(t,ne({trailer:!1}).push(dc(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function ye(e,n){try{oc(Oe(e,Mt(n)),{force:!0})}catch{}}function Ht(e,n){let t;try{t=rc(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=Oe(e,o);try{let l=ae(ns(s,"utf8"))[0];if(l===void 0)throw new Error("anchor holds no record");r.push(ac(l))}catch(i){n?.(ic(s),i instanceof Error?i.message:String(i))}}return r}function ac(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:Nt(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:Nt(e.pid),ppid:Nt(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 Nt(e){return typeof e=="number"?e:Number(e)}function dc(e){return{...e}}var mc=1,hc=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function gc(e){return typeof e=="string"&&hc.has(e)}var yc="startup";function kc(e,n){return{version:mc,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 Rc(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 Bt={mkdir(e){uc(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=pc(e).size}catch{return!0}if(n===0)return!0;try{return os(e,"utf8").endsWith(`
37
+ `)}catch{return!0}},append(e,n){cc(e,n,{encoding:"utf8",mode:384})},read(e){return os(e,"utf8")}};function bc(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function wc(e,n,t=Bt){let r=ne({trailer:!1}).push(bc(n));return t.mkdir(is(e)),t.endsClean(e)||t.append(e,`
38
+ `),t.append(e,r),n}function ls(e){let n=e.endsWith(`
39
39
  `)?e:e.slice(0,e.lastIndexOf(`
40
- `)+1);return n===""?[]:ae(n).map(bc)}function bc(e){let n=e.exit_path;if(!mc(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),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 is(e,n=Ft){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return ss(t)}var wc=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],Mt=null;function ls(e){let n=e.host??process,t=e.io??Ft,r=e.clock??(()=>new Date().toISOString()),o=n.pid,s=e.phase??hc,i=null,l=e.presenceDir===void 0?uc(os(e.lanePath),rn):e.presenceDir,a=null,d=()=>{l!==null&&(a=Tt({kind:e.kind,id:e.id,last_phase:s,pid:o},{procRoot:e.procRoot}),Wt(l,a))},u=y=>{if(!i){try{i=Rc(e.lanePath,gc({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:s,...y},yc(n)),t)}catch{}l!==null&&a!==null&&ye(l,a)}},p={signal(y){u({exit_path:"signal",signal:y})},exit(y){u({exit_path:"exit",exit_code:y})},uncaughtException(y){u({exit_path:"uncaught-exception",detail:rs(y)})},unhandledRejection(y){u({exit_path:"unhandled-rejection",detail:rs(y)})}},g=[...(e.signals??wc).map(y=>{let b=()=>{if(p.signal(y),!(n.listenerCount?.(y)!==1||!n.kill)){n.off(y,b);try{n.kill(o,y)}catch{}}};return[y,b]}),["uncaughtException",(...y)=>p.uncaughtException(y[0])],["unhandledRejection",(...y)=>p.unhandledRejection(y[0])],["exit",(...y)=>p.exit(typeof y[0]=="number"?y[0]:null)]];for(let[y,b]of g)n.on(y,b);let k={lanePath:e.lanePath,phase(y){s=y,i||d()},currentPhase:()=>s,written:()=>i,uninstall(){for(let[y,b]of g)n.off(y,b);l!==null&&a!==null&&ye(l,a),Mt===k&&(Mt=null)},handlers:p};return e.setActive!==!1&&(Mt=k),d(),k}function rs(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as _c,readdirSync as vc,readFileSync as An,statSync as xc,writeFileSync as Sc}from"node:fs";import{join as us}from"node:path";var Ec=1,Pc=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],jc=512*1024;function Dc(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??Pc,r=[],o=us(n,It),s=null;try{let a=An(o,"utf8").trim();s=a===""?null:a,r.push({source:o,result:s?"read":"empty",detail:s})}catch(a){r.push({source:o,result:Ut(a),detail:null})}let i=new Set;try{for(let a of vc(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:Ut(a),detail:null})}let l=[];for(let a of t)try{let u=Oc(a,e.tailBytes??jc).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:Ut(d),detail:null})}return{boot_id:s,live_pids:i,journal:l,probes:r}}function Ut(e){return e.code==="ENOENT"?"absent":"unreadable"}function Oc(e,n){let t=xc(e).size,r=An(e,"utf8");return t<=n?r:r.slice(r.length-n)}var Lc=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,$c=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,Ac=/Killed (\/\S*) due to memory pressure/,Ic=/\bopid=(\d+)\b/,as=/\bsig=(\d+)\b/,Tc=/\buid=(\d+)\b/,Nc=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,Wc={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function Cc(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,s=[...n.probes.map(p=>`${p.source}: ${p.result}${p.detail?` (${p.detail})`:""}`),`boot id: anchored under ${e.boot_id??"unknown"}, host now ${n.boot_id??"unknown"} (${o?"changed":"same"})`,`parent account: ppid ${e.ppid}`,`cgroup: ${e.cgroup??"unknown"}`],i=(p,f,g,k)=>({version:Ec,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:p,confidence:f,signal:g,host_boot_changed:o,evidence:k,checked:s}),l=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],a=n.journal.find(p=>ds(p,e.pid,Lc)||ds(p,e.pid,$c));if(a!==void 0)return i("oomd",o?"medium":"high","SIGKILL",[a,...l]);if(e.cgroup!==null)for(let p of n.journal){let f=Ac.exec(p)?.[1];if(f!==void 0){if(f===e.cgroup)return i("oomd",o?"medium":"high","SIGKILL",[p,...l]);if(e.cgroup.startsWith(`${f}/`))return i("oomd","medium","SIGKILL",[p,`the killed scope ${f} is an ancestor of this process's ${e.cgroup}`,...l])}}let d=n.journal.find(p=>Number(Ic.exec(p)?.[1])===e.pid&&as.test(p));if(d!==void 0){let p=Number(as.exec(d)?.[1]),f=Tc.exec(d)?.[1];return i("user-signal",o?"medium":"high",Wc[p]??null,[d,...f===void 0?[]:[`sent by uid ${f}`],...l])}let u=t.find(p=>p.pid===e.ppid);if(u!==void 0&&!n.live_pids.has(e.ppid))return i("parent-death","medium",null,[`parent pid ${e.ppid} (${u.kind} ${u.id}) recorded its own death at ${u.ts} via ${u.exit_path}${u.signal?` ${u.signal}`:""}`]);if(o){let p=n.journal.find(f=>Nc.test(f));return p!==void 0?i("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,p]):i("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,"no shutdown record on any journal read: the host stopped without announcing it (a freeze or a power loss, not an orderly teardown)"])}return i("unknown","none",null,[])}function ds(e,n,t){return Number(t.exec(e)?.[1])===n}var Mc=" | ";function cs(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(Mc)}function Fc(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:cs(e.evidence),checked:cs(e.checked)}}function Uc(e){let n=ne({trailer:!1});return e.map(t=>n.push(Fc(t))).join("")}function ps(e){let n=$n(e.stateRoot),t=$t(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??Dc({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=Ct(n,p=>s.push(p)),l=is(tn(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),ye(n,p);continue}a.push(Cc(p,o,l,r())),ye(n,p)}return a.length>0&&Hc(t,a),{attributions:a,alive:d,self_recorded:u,skipped:s,laneText:()=>{try{return An(t,"utf8")}catch{return""}}}}function fs(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 Hc(e,n){try{_c(us(e,".."),{recursive:!0,mode:448});let t=Vc(e),r=t===""||t.endsWith(`
40
+ `)+1);return n===""?[]:ae(n).map(_c)}function _c(e){let n=e.exit_path;if(!gc(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),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 as(e,n=Bt){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return ls(t)}var vc=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],Ut=null;function ds(e){let n=e.host??process,t=e.io??Bt,r=e.clock??(()=>new Date().toISOString()),o=n.pid,s=e.phase??yc,i=null,l=e.presenceDir===void 0?fc(is(e.lanePath),rn):e.presenceDir,a=null,c=()=>{l!==null&&(a=Ct({kind:e.kind,id:e.id,last_phase:s,pid:o},{procRoot:e.procRoot}),Ft(l,a))},u=y=>{if(!i){try{i=wc(e.lanePath,kc({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:s,...y},Rc(n)),t)}catch{}l!==null&&a!==null&&ye(l,a)}},p={signal(y){u({exit_path:"signal",signal:y})},exit(y){u({exit_path:"exit",exit_code:y})},uncaughtException(y){u({exit_path:"uncaught-exception",detail:ss(y)})},unhandledRejection(y){u({exit_path:"unhandled-rejection",detail:ss(y)})}},h=[...(e.signals??vc).map(y=>{let b=()=>{if(p.signal(y),!(n.listenerCount?.(y)!==1||!n.kill)){n.off(y,b);try{n.kill(o,y)}catch{}}};return[y,b]}),["uncaughtException",(...y)=>p.uncaughtException(y[0])],["unhandledRejection",(...y)=>p.unhandledRejection(y[0])],["exit",(...y)=>p.exit(typeof y[0]=="number"?y[0]:null)]];for(let[y,b]of h)n.on(y,b);let k={lanePath:e.lanePath,phase(y){s=y,i||c()},currentPhase:()=>s,written:()=>i,uninstall(){for(let[y,b]of h)n.off(y,b);l!==null&&a!==null&&ye(l,a),Ut===k&&(Ut=null)},handlers:p};return e.setActive!==!1&&(Ut=k),c(),k}function ss(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as xc,readdirSync as Sc,readFileSync as Tn,statSync as Ec,writeFileSync as Pc}from"node:fs";import{join as fs}from"node:path";var jc=1,Dc=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],Oc=512*1024;function $c(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??Dc,r=[],o=fs(n,Wt),s=null;try{let a=Tn(o,"utf8").trim();s=a===""?null:a,r.push({source:o,result:s?"read":"empty",detail:s})}catch(a){r.push({source:o,result:Vt(a),detail:null})}let i=new Set;try{for(let a of Sc(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:Vt(a),detail:null})}let l=[];for(let a of t)try{let u=Ac(a,e.tailBytes??Oc).split(`
41
+ `).filter(p=>p.trim()!=="");l.push(...u),r.push({source:a,result:u.length===0?"empty":"read",detail:`${u.length} lines`})}catch(c){r.push({source:a,result:Vt(c),detail:null})}return{boot_id:s,live_pids:i,journal:l,probes:r}}function Vt(e){return e.code==="ENOENT"?"absent":"unreadable"}function Ac(e,n){let t=Ec(e).size,r=Tn(e,"utf8");return t<=n?r:r.slice(r.length-n)}var Lc=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,Ic=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,Tc=/Killed (\/\S*) due to memory pressure/,Nc=/\bopid=(\d+)\b/,cs=/\bsig=(\d+)\b/,Wc=/\buid=(\d+)\b/,Cc=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,Mc={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function Fc(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,s=[...n.probes.map(p=>`${p.source}: ${p.result}${p.detail?` (${p.detail})`:""}`),`boot id: anchored under ${e.boot_id??"unknown"}, host now ${n.boot_id??"unknown"} (${o?"changed":"same"})`,`parent account: ppid ${e.ppid}`,`cgroup: ${e.cgroup??"unknown"}`],i=(p,f,h,k)=>({version:jc,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:p,confidence:f,signal:h,host_boot_changed:o,evidence:k,checked:s}),l=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],a=n.journal.find(p=>us(p,e.pid,Lc)||us(p,e.pid,Ic));if(a!==void 0)return i("oomd",o?"medium":"high","SIGKILL",[a,...l]);if(e.cgroup!==null)for(let p of n.journal){let f=Tc.exec(p)?.[1];if(f!==void 0){if(f===e.cgroup)return i("oomd",o?"medium":"high","SIGKILL",[p,...l]);if(e.cgroup.startsWith(`${f}/`))return i("oomd","medium","SIGKILL",[p,`the killed scope ${f} is an ancestor of this process's ${e.cgroup}`,...l])}}let c=n.journal.find(p=>Number(Nc.exec(p)?.[1])===e.pid&&cs.test(p));if(c!==void 0){let p=Number(cs.exec(c)?.[1]),f=Wc.exec(c)?.[1];return i("user-signal",o?"medium":"high",Mc[p]??null,[c,...f===void 0?[]:[`sent by uid ${f}`],...l])}let u=t.find(p=>p.pid===e.ppid);if(u!==void 0&&!n.live_pids.has(e.ppid))return i("parent-death","medium",null,[`parent pid ${e.ppid} (${u.kind} ${u.id}) recorded its own death at ${u.ts} via ${u.exit_path}${u.signal?` ${u.signal}`:""}`]);if(o){let p=n.journal.find(f=>Cc.test(f));return p!==void 0?i("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,p]):i("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,"no shutdown record on any journal read: the host stopped without announcing it (a freeze or a power loss, not an orderly teardown)"])}return i("unknown","none",null,[])}function us(e,n,t){return Number(t.exec(e)?.[1])===n}var Hc=" | ";function ps(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(Hc)}function Uc(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:ps(e.evidence),checked:ps(e.checked)}}function Bc(e){let n=ne({trailer:!1});return e.map(t=>n.push(Uc(t))).join("")}function ms(e){let n=In(e.stateRoot),t=Tt(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??$c({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=Ht(n,p=>s.push(p)),l=as(tn(e.stateRoot)),a=[],c=[],u=[];for(let p of i){if(o.live_pids.has(p.pid)){c.push(p);continue}if(l.find(h=>h.pid===p.pid&&h.id===p.id)!==void 0){u.push(p),ye(n,p);continue}a.push(Fc(p,o,l,r())),ye(n,p)}return a.length>0&&Vc(t,a),{attributions:a,alive:c,self_recorded:u,skipped:s,laneText:()=>{try{return Tn(t,"utf8")}catch{return""}}}}function hs(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 Vc(e,n){try{xc(fs(e,".."),{recursive:!0,mode:448});let t=Kc(e),r=t===""||t.endsWith(`
42
42
  `)?"":`
43
- `;Sc(e,`${t}${r}${Uc(n)}`,{encoding:"utf8",mode:384})}catch{}}function Vc(e){try{return An(e,"utf8")}catch{return""}}import{join as Bc}from"node:path";var Jc=[".red","redskilled"],z=448;function ke(e){return Bc(e,...Jc)}import{execFileSync as su}from"node:child_process";import{readFileSync as iu}from"node:fs";import{dirname as bs,join as lu}from"node:path";import{existsSync as Kc,readFileSync as ak}from"node:fs";import{dirname as qc,join as Gc}from"node:path";function ms(e,n){let t=e;for(let r=0;r<16;r++){let o=Gc(t,n);if(Kc(o))return o;let s=qc(t);if(s===t)break;t=s}return null}function zc(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 zc(d)}}import{createHash as Qc}from"node:crypto";var Yc="project.name";function gs(e){let n=Le(e,Yc)?.trim();return n===void 0||n===""?void 0:n}var Zc=8,ys="project";function ks(e){let n=ru(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:Xc(e.remoteUrl)??{name:eu(e.checkoutPath,n),source:"basename"},o=tu(n??Ht(e.checkoutPath));return{name:r.name,slug:`${nu(r.name)}-${o}`,hash:o,source:r.source}}function Rs(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 Xc(e){let n=Rs(e);return n===void 0?void 0:{name:n,source:"remote"}}function eu(e,n){let t=n===void 0?"":hs(ou(n));if(t!=="")return t;let r=hs(Ht(e));return r===""?ys:r}function nu(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?ys:t}function tu(e){return Qc("sha256").update(e).digest("hex").slice(0,Zc)}function ru(e){let n=Ht(e??"");return n===""?void 0:n}function Ht(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function hs(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function ou(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var au=2e3;function ws(e){return du(e).name}function du(e){let n=Bt(e),t=Vt(e,["rev-parse","--absolute-git-dir"])??Vt(e,["rev-parse","--git-common-dir"]),r=Vt(e,["remote","get-url","origin"]);return ks({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function Bt(e){let n=ms(e,lu(".red","config.yaml"));if(n==null)return{};let t;try{t=iu(n,"utf8")}catch{return{}}let r=gs(t),o=bs(bs(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function Vt(e,n){try{let t=su("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:au}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as Kl}from"node:crypto";import{spawn as $h}from"node:child_process";import{mkdir as Ah,rm as Ih}from"node:fs/promises";import{dirname as Th}from"node:path";import{createHash as pu}from"node:crypto";import{constants as zt}from"node:fs";import{mkdir as fu,open as mu}from"node:fs/promises";import{createConnection as hu}from"node:net";import{tmpdir as gu}from"node:os";import{dirname as yu,join as on}from"node:path";var cu="toon";function xs(e){return e.trimStart().startsWith("{")?"json":"toon"}function Kt(e){let n=0;for(;e[n]===`
45
- `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=xs(t);if(r==="json"){let s=t.indexOf(`
43
+ `;Pc(e,`${t}${r}${Bc(n)}`,{encoding:"utf8",mode:384})}catch{}}function Kc(e){try{return Tn(e,"utf8")}catch{return""}}import{join as Jc}from"node:path";var qc=[".red","redskilled"],z=448;function ke(e){return Jc(e,...qc)}import{execFileSync as lu}from"node:child_process";import{readFileSync as au}from"node:fs";import{dirname as _s,join as du}from"node:path";import{existsSync as Gc,readFileSync as gk}from"node:fs";import{dirname as zc,join as Qc}from"node:path";function gs(e,n){let t=e;for(let r=0;r<16;r++){let o=Qc(t,n);if(Gc(o))return o;let s=zc(t);if(s===t)break;t=s}return null}function Yc(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function $e(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 c=o.slice(i+1).trim();for(;t.length&&t[t.length-1].indent>=l;)t.pop();if(t.push({indent:l,key:a}),c&&t.map(p=>p.key).join(".")===n)return Yc(c)}}import{createHash as Zc}from"node:crypto";var Xc="project.name";function ks(e){let n=$e(e,Xc)?.trim();return n===void 0||n===""?void 0:n}var eu=8,Rs="project";function bs(e){let n=su(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:nu(e.remoteUrl)??{name:tu(e.checkoutPath,n),source:"basename"},o=ou(n??Kt(e.checkoutPath));return{name:r.name,slug:`${ru(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 nu(e){let n=ws(e);return n===void 0?void 0:{name:n,source:"remote"}}function tu(e,n){let t=n===void 0?"":ys(iu(n));if(t!=="")return t;let r=ys(Kt(e));return r===""?Rs:r}function ru(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?Rs:t}function ou(e){return Zc("sha256").update(e).digest("hex").slice(0,eu)}function su(e){let n=Kt(e??"");return n===""?void 0:n}function Kt(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function ys(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function iu(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var cu=2e3;function vs(e){return uu(e).name}function uu(e){let n=qt(e),t=Jt(e,["rev-parse","--absolute-git-dir"])??Jt(e,["rev-parse","--git-common-dir"]),r=Jt(e,["remote","get-url","origin"]);return bs({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function qt(e){let n=gs(e,du(".red","config.yaml"));if(n==null)return{};let t;try{t=au(n,"utf8")}catch{return{}}let r=ks(t),o=_s(_s(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function Jt(e,n){try{let t=lu("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:cu}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as Gl}from"node:crypto";import{spawn as Fh}from"node:child_process";import{mkdir as Hh,rm as Uh}from"node:fs/promises";import{dirname as Bh}from"node:path";import{createHash as mu}from"node:crypto";import{constants as Zt}from"node:fs";import{mkdir as hu,open as gu}from"node:fs/promises";import{createConnection as yu}from"node:net";import{tmpdir as ku}from"node:os";import{dirname as Ru,join as on}from"node:path";var pu="toon";function Es(e){return e.trimStart().startsWith("{")?"json":"toon"}function zt(e){let n=0;for(;e[n]===`
45
+ `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=Es(t);if(r==="json"){let s=t.indexOf(`
46
46
  `);return s<0?null:{frame:t.slice(0,s),dialect:r,rest:t.slice(s+1)}}let o=t.indexOf(`
47
47
 
48
- `);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function qt(e){let n=xs(e)==="json"?Jt:_s,t=n===Jt?_s:Jt;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function Jt(e){return JSON.parse(e)}function _s(e){return G(e)}function Gt(e,n){if(n==="toon"){let t=uu(e);if(t!==null)return t.endsWith(`
48
+ `);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function Qt(e){let n=Es(e)==="json"?Gt:xs,t=n===Gt?xs:Gt;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function Gt(e){return JSON.parse(e)}function xs(e){return G(e)}function Yt(e,n){if(n==="toon"){let t=fu(e);if(t!==null)return t.endsWith(`
49
49
  `)?`${t}
50
50
  `:`${t}
51
51
 
52
52
  `}return`${JSON.stringify(e)}
53
- `}function uu(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 Ss(e,n){return!vs(e)||!vs(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function vs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Es=new Set;function Ps(e){return Es.has(e)?"json":cu}function js(e){Es.add(e)}var ku=108;async function In(e,n,t="resident server"){let r=e.wire,o=r??Ps(e.socketPath),s=await Ds(e,n,t,o);return r||o==="json"||!Ss(n,s)?s:(js(e.socketPath),await Ds(e,n,t,"json"))}async function Ds(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=hu(e.socketPath),a=!1,d="",u=setTimeout(()=>{p(()=>i(new Error(`${t} timed out`))),l.destroy()},o);function p(f){a||(a=!0,clearTimeout(u),f())}l.on("connect",()=>{l.write(Gt(n,r))}),l.on("data",f=>{d+=f.toString("utf8");let g=Kt(d);g&&(d=g.rest,p(()=>{try{s(qt(g.frame))}catch(k){i(k)}}),l.end())}),l.on("error",f=>p(()=>i(f))),l.on("close",()=>{a||p(()=>i(new Error(`${t} closed without response`)))})})}function Os(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=Kt(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(Gt(l,s.dialect))}catch{}};(async()=>{let l;try{l=qt(s.frame),await n(l,i)}catch(a){t(a,l,i)}finally{e.end()}})()})}async function Ls(e){await fu(yu(e),{recursive:!0,mode:448});try{return await mu(e,zt.O_CREAT|zt.O_EXCL|zt.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 Ru="/tmp";function Tn(e){let n=e.env??process.env,t=pu("sha256").update(e.key).digest("hex").slice(0,20),r=a=>on(a,e.socketFileName).length<ku,o=n.XDG_RUNTIME_DIR;if(o){let a=on(o,"red-skills",t);if(r(a))return a}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=on(`red-skills-${s}`,t),l=on(gu(),i);return r(l)||process.platform==="win32"?l:on(Ru,i)}te();import{homedir as Hu}from"node:os";import{join as rr}from"node:path";import{spawnSync as Vu}from"node:child_process";import{createHash as Bu}from"node:crypto";import{existsSync as Ju}from"node:fs";import{mkdir as Cs,readFile as Ku,writeFile as qu}from"node:fs/promises";import{dirname as Gu}from"node:path";var an="@reddb-io/red-skills",Ou="https://registry.npmjs.org",Lu="canary",$e=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function $u(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function Mn(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return Fn(r,$u(n,t,o))}function Au(e){return e==="dev"?["rsp"]:[]}function Iu(e){return`${e}.bundle.min.mjs`}function Tu(e){return Fn("dist",Iu(e))}function Nu(e,n="stable"){return`${an}@${n==="canary"?Lu:e}`}function Wu(e=an){return`${Ou}/${e.replace("/","%2F")}`}async function tr(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=Mn({plugin:t,version:r,cacheDir:o,channel:s}),l=Au(t),a=l.map(f=>Mn({plugin:f,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await Cu(e,a))return i;let d=Nu(r,s),u=Fn(o,`.staging-${t}-${s==="canary"?"canary":r}`),p;try{p=await e.materialize(d,u)}catch(f){throw Ws(f,d)}for(let f of[t,...l]){let g=Tu(f),k=Fn(p,g);if(!await e.exists(k))throw new $e("bundle-missing",`npm package ${d} has no ${g}`);let y=f===t?i:Mn({plugin:f,version:r,cacheDir:o,channel:s});await e.writeFile(y,await e.readFile(k))}return i}async function Cu(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function Ts(e,n,t=an){let r;try{r=await e.fetchText(Wu(t))}catch(s){throw Ws(s,t)}let o=Mu(r);return{sameMajor:Fu(o,n),newest:Uu(o)}}function Mu(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 Fu(e,n){let t=nr(n);if(t===null)return null;let r=null;for(let o of e)nr(o)===t&&(r===null||Ns(o,r)>0)&&(r=o);return r}function Uu(e){let n=null;for(let t of e){let r=String(t).trim();nr(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||Ns(r,n)>0)&&(n=r)}return n}function nr(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function Ns(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 Ws(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new $e("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new $e("package-missing",`npm could not resolve ${n}: ${t}`,e):new $e("network",`failed to resolve ${n}: ${t}`,e)}function Fn(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}te();var zu={async materialize(e,n){await Cs(n,{recursive:!0});let t=Vu("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 rr(n,"node_modules",...an.split("/"))},async readFile(e){return new Uint8Array(await Ku(e))},async writeFile(e,n){await Cs(Gu(e),{recursive:!0}),await qu(e,n)},async exists(e){return Ju(e)},sha256(e){return Bu("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()}},Qu="redskilled";function Yu(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||rr(e.HOME||Hu(),".cache");return rr(n,"red-skills","bundles")}async function Zu(e={},n={},t={}){let r=ce(e,n);if(Y(r))return r;let o=t.env??n.env??process.env;try{await tr(t.bundleIO??zu,{plugin:Qu,version:t.version??"",cacheDir:Yu(o)})}catch{return r}return ce(e,n)}async function Ms(e={},n={},t={}){let r=await Zu(e,n,t);if(Y(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(te(),Is));throw new o(r)}import{randomUUID as Zn}from"node:crypto";import{mkdir as vh,rm as Vl}from"node:fs/promises";import{createServer as xh}from"node:net";import{dirname as Sh}from"node:path";import{totalmem as Xu}from"node:os";function Fs(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=Ae(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 Ae(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 Us(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 ep="REDSKILLED_MEMORY_CEILING",np="REDSKILLED_WORKER_CEILING",tp=.7;function Hs(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return Ae(n)}function or(e){let n=0,t=[];for(let r of e){let o=Hs(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 Vs(e){let{ceiling:n}=e,t=or(e.workers),r=Hs(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 Bs(e=process.env,n=Xu()){let t=(e[ep]??"").trim(),r=(e[np]??"").trim(),o=op(r);if(t!==""){let s=rp(t,n);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(n*tp),worker_count:o,source:r!==""?"declared":"host-fraction"}}function rp(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)):Ae(e)??void 0}function op(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 sp,mkdir as ip,open as lp,readFile as ap,stat as dp,truncate as Js}from"node:fs/promises";import{dirname as cp}from"node:path";var Ks="redskilled.events.toonl";function up(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 pp="daemon:";function fp(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${pp}${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 qs(e){let n=ne({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await ip(cp(e),{recursive:!0,mode:448}),await mp(e),await sp(e,n.push(kp(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(up(o)),recordDaemonStop:o=>r(fp(o)),read:()=>hp(e),flush:async()=>{await t}}}async function mp(e){let n;try{n=(await dp(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await lp(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 Js(e,s-i+a+1);return}}await Js(e,0)}finally{await r.close()}}async function hp(e){let n;try{n=await ap(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return gp(n)}function gp(e){let n=e.split(`
53
+ `}function fu(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 Ps(e,n){return!Ss(e)||!Ss(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function Ss(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var js=new Set;function Ds(e){return js.has(e)?"json":pu}function Os(e){js.add(e)}var bu=108;async function Nn(e,n,t="resident server"){let r=e.wire,o=r??Ds(e.socketPath),s=await $s(e,n,t,o);return r||o==="json"||!Ps(n,s)?s:(Os(e.socketPath),await $s(e,n,t,"json"))}async function $s(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=yu(e.socketPath),a=!1,c="",u=setTimeout(()=>{p(()=>i(new Error(`${t} timed out`))),l.destroy()},o);function p(f){a||(a=!0,clearTimeout(u),f())}l.on("connect",()=>{l.write(Yt(n,r))}),l.on("data",f=>{c+=f.toString("utf8");let h=zt(c);h&&(c=h.rest,p(()=>{try{s(Qt(h.frame))}catch(k){i(k)}}),l.end())}),l.on("error",f=>p(()=>i(f))),l.on("close",()=>{a||p(()=>i(new Error(`${t} closed without response`)))})})}function As(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=zt(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(Yt(l,s.dialect))}catch{}};(async()=>{let l;try{l=Qt(s.frame),await n(l,i)}catch(a){t(a,l,i)}finally{e.end()}})()})}async function Ls(e){await hu(Ru(e),{recursive:!0,mode:448});try{return await gu(e,Zt.O_CREAT|Zt.O_EXCL|Zt.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 wu="/tmp";function Wn(e){let n=e.env??process.env,t=mu("sha256").update(e.key).digest("hex").slice(0,20),r=a=>on(a,e.socketFileName).length<bu,o=n.XDG_RUNTIME_DIR;if(o){let a=on(o,"red-skills",t);if(r(a))return a}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=on(`red-skills-${s}`,t),l=on(ku(),i);return r(l)||process.platform==="win32"?l:on(wu,i)}te();import{homedir as Vu}from"node:os";import{join as ir}from"node:path";import{spawnSync as Ku}from"node:child_process";import{createHash as Ju}from"node:crypto";import{existsSync as qu}from"node:fs";import{mkdir as Fs,readFile as Gu,writeFile as zu}from"node:fs/promises";import{dirname as Qu}from"node:path";var an="@reddb-io/red-skills",Au="https://registry.npmjs.org",Lu="canary",Ae=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function Iu(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function Hn(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return Un(r,Iu(n,t,o))}function Tu(e){return e==="dev"?["rsp"]:[]}function Nu(e){return`${e}.bundle.min.mjs`}function Wu(e){return Un("dist",Nu(e))}function Cu(e,n="stable"){return`${an}@${n==="canary"?Lu:e}`}function Mu(e=an){return`${Au}/${e.replace("/","%2F")}`}async function sr(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=Hn({plugin:t,version:r,cacheDir:o,channel:s}),l=Tu(t),a=l.map(f=>Hn({plugin:f,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await Fu(e,a))return i;let c=Cu(r,s),u=Un(o,`.staging-${t}-${s==="canary"?"canary":r}`),p;try{p=await e.materialize(c,u)}catch(f){throw Ms(f,c)}for(let f of[t,...l]){let h=Wu(f),k=Un(p,h);if(!await e.exists(k))throw new Ae("bundle-missing",`npm package ${c} has no ${h}`);let y=f===t?i:Hn({plugin:f,version:r,cacheDir:o,channel:s});await e.writeFile(y,await e.readFile(k))}return i}async function Fu(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function Ws(e,n,t=an){let r;try{r=await e.fetchText(Mu(t))}catch(s){throw Ms(s,t)}let o=Hu(r);return{sameMajor:Uu(o,n),newest:Bu(o)}}function Hu(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 Uu(e,n){let t=or(n);if(t===null)return null;let r=null;for(let o of e)or(o)===t&&(r===null||Cs(o,r)>0)&&(r=o);return r}function Bu(e){let n=null;for(let t of e){let r=String(t).trim();or(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||Cs(r,n)>0)&&(n=r)}return n}function or(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function Cs(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 Ms(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 Un(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}te();var Yu={async materialize(e,n){await Fs(n,{recursive:!0});let t=Ku("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 ir(n,"node_modules",...an.split("/"))},async readFile(e){return new Uint8Array(await Gu(e))},async writeFile(e,n){await Fs(Qu(e),{recursive:!0}),await zu(e,n)},async exists(e){return qu(e)},sha256(e){return Ju("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()}},Zu="redskilled";function Xu(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||ir(e.HOME||Vu(),".cache");return ir(n,"red-skills","bundles")}async function ep(e={},n={},t={}){let r=ce(e,n);if(Y(r))return r;let o=t.env??n.env??process.env;try{await sr(t.bundleIO??Yu,{plugin:Zu,version:t.version??"",cacheDir:Xu(o)})}catch{return r}return ce(e,n)}async function Hs(e={},n={},t={}){let r=await ep(e,n,t);if(Y(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(te(),Ns));throw new o(r)}import{randomUUID as nt}from"node:crypto";import{mkdir as $h,rm as Kl}from"node:fs/promises";import{createServer as Ah}from"node:net";import{dirname as Lh}from"node:path";import{totalmem as np}from"node:os";function Us(e){let n=0,t=0,r=0,o=[],s=[];for(let i of e){let l=i.budget??{},a=!1;for(let[c,u]of[[l.memory_high,p=>n+=p],[l.memory_max,p=>t+=p]]){if(c==null)continue;let p=Le(c);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 Le(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 Bs(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 tp="REDSKILLED_MEMORY_CEILING",rp="REDSKILLED_WORKER_CEILING",op=.7;function Vs(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return Le(n)}function lr(e){let n=0,t=[];for(let r of e){let o=Vs(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 Ks(e){let{ceiling:n}=e,t=lr(e.workers),r=Vs(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)`,c=(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?c("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?c("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?c("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 Js(e=process.env,n=np()){let t=(e[tp]??"").trim(),r=(e[rp]??"").trim(),o=ip(r);if(t!==""){let s=sp(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 sp(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)):Le(e)??void 0}function ip(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 lp,mkdir as ap,open as dp,readFile as cp,stat as up,truncate as qs}from"node:fs/promises";import{dirname as pp}from"node:path";var Gs="redskilled.events.toonl";function fp(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 mp="daemon:";function hp(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${mp}${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 zs(e){let n=ne({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await ap(pp(e),{recursive:!0,mode:448}),await gp(e),await lp(e,n.push(bp(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(fp(o)),recordDaemonStop:o=>r(hp(o)),read:()=>yp(e),flush:async()=>{await t}}}async function gp(e){let n;try{n=(await up(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await dp(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 qs(e,s-i+a+1);return}}await qs(e,0)}finally{await r.close()}}async function yp(e){let n;try{n=await cp(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return kp(n)}function kp(e){let n=e.split(`
54
54
  `);return n.pop(),n.length===0?[]:ae(`${n.join(`
55
55
  `)}
56
- `).filter(Rp).map(bp)}function Gs(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,yp(t)):n.delete(t.worker_id));return[...n.values()]}function yp(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 kp(e){return{...e}}function Rp(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 bp(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:re(e.project_label)??"",pid:Number(e.pid??0),workspace_path:re(e.workspace_path)??"",log_path:re(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:re(e.unit),memory_high:re(e.memory_high),memory_max:re(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:re(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:re(e.signal),reason:re(e.reason)}}function re(e){return e==null||e===""?null:String(e)}function zs(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 f=0;f<p;f+=1)(s[f]??(s[f]=[])).push({project_label:i.project_label,index:l+f,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function Qs(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function Zs(e){let n=e.workers.map(wp),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:vp({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function Xs(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 wp(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 _p(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 vp(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${_p(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${Ys(e.held,"Worker")} across ${Ys(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 Ys(e,n){return`${e} ${n}${e===1?"":"s"}`}function sr(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 xp,mkdir as Sp,readFile as Ep,rm as Pp,writeFile as jp}from"node:fs/promises";import{dirname as ei,join as oi}from"node:path";import{tmpdir as ni}from"node:os";var Dp="redskilled.machine.claim.toon",Op="REDSKILLED_MACHINE_DIR",Lp=8,ue=class extends Error{constructor(t,r,o){super(Ap(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},ti;function si(){return ti??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},ti}function $p(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[Op]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||ni():ni();return oi(o,`redskilled-${e.machineIdHash}`)}function Un(e){return oi($p(e),Dp)}function Hn(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??W;async function s(){let a;try{a=await Ep(e,"utf8")}catch(u){if(u.code==="ENOENT"||ir(u))return;throw u}let d=Tp(a);return Np(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 Pp(e,{force:!0}),!0}catch(a){if(ir(a))return!1;throw a}}return{claimPath:e,read:s,async claim(a){await Sp(ei(e),{recursive:!0,mode:1023})!=null&&await xp(ei(e),1023).catch(()=>{});let u=!1;for(let p=0;p<Lp;p+=1){let f=i(a,r());try{return await jp(e,Ip(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:u,claim:f}}catch(k){if(k.code!=="EEXIST"){if(ir(k))return{claimed:!1,reason:"stale-claim-not-reapable"};throw k}}let g=await s();if(!g){if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable"};u=!0;continue}if(ri(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||!ri(d,a,n.socketPath)?!1:await l()}}}function ii(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 li(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 Ap(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 ir(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function ri(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function Ip(e){return`${I(e,{keyedMapCollapse:!0})}
57
- `}function Tp(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return G(n)}catch{return null}}}function Np(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 lr(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 ar(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 Wp=3e5,Cp=.5,cr=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 ai(e,n){if(n.held!=null)throw new cr(n.held);let t=dr(e.project_label,"a project label"),r=dr(e.selector,"a selector"),o=lr(e.argv,t),s=ar(e.env,t),i=dr(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??Wp;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 Vn=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 di(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:lr(n.launch.argv,e.project_label),env:ar(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 ci(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 Mp(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function ui(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*Cp;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 pi(e,n){let t=[],r=[];for(let o of e)(Mp(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function ur(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||Fp(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 Fp(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function dr(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var Up={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 fi(e){return`worker-${e}`}function mi(e){let n=Up[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.`}}import{execFileSync as Hp}from"node:child_process";import{readFileSync as Vp,readdirSync as Bp}from"node:fs";import{join as Jp}from"node:path";function dn(e){let n=e.budget??{},t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let s=Ae(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function hi(e){let n=[],t=[];for(let r of e.workers){let o=dn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(r.budget?.memory_max??r.budget?.memory_high)==null?"this Worker declared no memory budget, so the sampler has no ceiling 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(Kp(r,o,s))}return{terminations:n,unenforceable:t}}function Kp(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 qp=4096;function gi(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{}};if(e.length===0)return r;let o=Gp(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],f=new Set;for(;p.length>0;){let g=p.pop();if(f.has(g))continue;f.add(g);let k=o.get(g);if(k){d+=k.rssBytes,u+=k.cpuSeconds;for(let y of s.get(g)??[])p.push(y)}}i[a.worker_id]=d,l[a.worker_id]=u}return{rss:i,cpu_seconds:l}}function Gp(e,n){return n.procRoot!=null||e==="linux"?ef(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?Zp(zp(n.psTable)):new Map}function zp(e){try{return(e??Qp)()}catch{return""}}function Qp(){return Hp("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Yp=1024;function Zp(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=Xp(r[3]);l!=null&&n.set(o,{pid:o,ppid:s,rssBytes:i*Yp,cpuSeconds:l})}return n}function Xp(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 ef(e){let n=new Map,t;try{t=Bp(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=Vp(Jp(e,r,"stat"),"utf8")}catch{continue}let s=tf(o);s&&n.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*qp,cpuSeconds:s.cpuTicks/nf})}return n}var nf=100;function tf(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 pr=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 mr(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new pr(t.project_label,t.token_ref,n)}function rf(e,n={now:new Date(0).toISOString()}){lf(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),f=JSON.stringify(u.name),g=JSON.stringify(`repo:${u.owner}/${u.name} is:closed closed:>=${o}`);return[` ${a}: repository(owner: ${p}, name: ${f}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${d}: search(query: ${g}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
59
- `),aliases:s,closed_since:o}}function of(e,n,t){let r=Ie(n),o=Ie(r.data),s=Array.isArray(r.errors)?r.errors.map(Ie):[],i=af(o.rateLimit,s),l=e.aliases.map(({alias:a,search_alias:d,project:u})=>{let p=u.owner+"/"+u.name,f=o[a],g=s.find(k=>yi(k.path,a)||yi(k.path,d));if(vi(f)){let k=ki(f.open_pull_requests),y=ki(f.open_issues),b=df(o[d]);if(k!=null&&y!=null&&b!=null)return{project_label:u.project_label,repository:p,outcome:"counted",counts:{open_pull_requests:k,open_issues:y,recently_closed:b},detail:`counted ${p} for project ${JSON.stringify(u.project_label)}`}}return i.exhausted||_i(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: ${fr(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 sf(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 Ri(e){if(e.projects.length===0)return sf(e.now);mr(e.projects,e.hostTokenRef);let n=rf(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return of(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 wi(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 lf(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 af(e,n){let t=Ie(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(_i);return{remaining:r,reset_at:o,exhausted:s||r===0}}function _i(e){if(e==null)return!1;let n=fr(e.type),t=fr(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function yi(e,n){return Array.isArray(e)&&e.includes(n)}function ki(e){let n=Ie(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function df(e){let n=Ie(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Ie(e){return vi(e)?e:{}}function vi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fr(e){return typeof e=="string"?e:""}var cf=3e4;function xi(e){let n=e.stalenessMs??cf,t=hr(e.now),r=e.sampledAt==null?null:hr(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),s=o!=null&&o<=n,i=new Set(e.reattachedWorkerIds??[]),l=e.hostState.workers.map(f=>uf(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:i.has(f.worker_id)?"reattached":"running"})),a=l.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=l.length-a.length,u=l.reduce((f,g)=>f+(g.vitals.rss_bytes??0),0),p=or(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:hf({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:mf(l),known_projects:ff(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,g)=>f.localeCompare(g)),workers:l,repository_activity:bi({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs})}}function uf(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=dn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=hr(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:pf(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function pf(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 ff(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 mf(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 hf(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 hr(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 Si(e,n=O){let t=_f(e,n),r=bf(e,n),o=wf(e,n),s=vf(e,n,r,t),i=kf(n,r,o),l={detail:"host",line:s};for(let p of i){let f=Lf(s,Rf(p,n,r,o),n.separator);if(l={detail:p,line:f},$f(f)<=n.maxWidth)break}let a=kr(l.line,n.maxWidth),d=n.verbose&&l.detail==="workers"?Pf(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 Ei(e){let n=e.options??O,t=kr(yf,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 gf="!unregistered",yf="redskilled unreachable \u2014 Worker state unknown";function kf(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 Rf(e,n,t,r){return e==="workers"?t.map(o=>Ef(o,n)):e==="projects"?r.map(Of):[]}function bf(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function wf(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function _f(e,n){return yr(e,n.project)}function yr(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 vf(e,n,t,r){let o=[];return n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(gr(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(gr(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(gr(e,n)),o.push(gf)):o.push(xf(n.project,r)),e.staleness.stale&&o.push(Sf(e)),o.join(" ")}function xf(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 gr(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,s)=>o+s.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${U(t)}/${U(r)}`:U(t)}function Sf(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function Ef(e,n){let t=Pi(e,n),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?U(r):`${U(r)}/${U(e.budget.bytes)}`;return`${t} ${o}`}function Pf(e,n){let t=[];for(let r of e){let o=Df(r.log.last_line);o!=null&&t.push(kr(` ${jf} ${Pi(r,n)}: ${o}`,n.maxWidth))}return t}var jf="\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 Pi(e,n){return n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Of(e){return`${e.project_label} ${e.worker_count}w ${U(e.observed_rss_bytes)}`}function Lf(e,n,t){return[e,...n].join(t)}function $f(e){return[...e].length}function kr(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 U(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}var Rr={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},Af=["runner","model","effort","origin","issue","phase","step","heartbeat"],If=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function ji(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...Rr};for(let r of Af){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of If){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}var Bn=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],Te={mode:"local",project:null,maxWidth:200,maxRows:16};var Tf=" ",Di="\u2588",Nf="\u25B6",Wf="\u2717",Cf="\u2591";function Oi(e,n=Te){let t=yr(e,n.project),r=Mf(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(p=>Ff(p,n)),i=Gf(s),l=o.map((p,f)=>({worker_id:p.worker_id,project_label:p.project_label,mine:n.project!=null&&p.project_label===n.project,cells:s[f],line:br(zf(s[f],i),n.maxWidth)})),a=Hf(e,n,r,t),d=r.length-o.length,u=[a.line,...l.map(p=>p.line)];return d>0&&u.push(br(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Bn,header:a,rows:l,lines:u,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Mf(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Ff(e,n){let t=e.display??Rr,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:Uf(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:qf(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:Jf(t.added,t.removed),tks:t.tokens==null?"":`tks=${Kf(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function Uf(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 Di.repeat(Math.floor(n));let o=e.failed?Wf:Nf;return`${Di.repeat(r)}${o}${Cf.repeat(Math.floor(n)-r-1)}`}function Hf(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(u=>u.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=Bf(t),a=o?.repository??n.project,d=[`\xBB ${a??"host"} v${e.daemon.daemon_version}`];if(r==="unregistered"&&d.push("!unregistered"),r==="name-only"&&d.push("!lapsed"),l!=null&&d.push(l),d.push(`wrk=${t.length}/${e.host.worker_count}`),d.push(i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`),d.push(Vf(i)),s.open_pull_requests!=null&&d.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&d.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&d.push(`iss=${s.open_issues}`),s.stale&&d.push("!counts stale"),e.staleness.stale){let u=e.staleness.age_ms;d.push(u==null?"!unmeasured":`!stale ${Math.round(u/1e3)}s`)}return{repo:a,project:n.project,project_match:r,version:e.daemon.daemon_version,model:l,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:br(d.join(" \xB7 "),n.maxWidth)}}function Vf(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${U(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${U(e.memory_used_bytes)}/${U(e.memory_ceiling_bytes)}${n}`}function Bf(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 Jf(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 Kf(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 qf(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 Gf(e){let n=Object.fromEntries(Bn.map(t=>[t,0]));for(let t of e)for(let r of Bn)n[r]=Math.max(n[r],Li(t[r]));return n}function zf(e,n){return Bn.filter(r=>n[r]>0).map(r=>Qf(e[r],n[r])).join(Tf).replace(/\s+$/,"")}function Qf(e,n){return e+" ".repeat(Math.max(0,n-Li(e)))}function Li(e){return[...e].length}function br(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 Jn=1;async function cn(e,n){return await In(e,n,"redskilled daemon")}function $i(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 Ai(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:Jn,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:Xf(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:Fs(n),upgrade:em(e)}}function Xf(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:ui(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 em(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 Ii(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)&&Us(n.budget_accounting)&&(n.scope===void 0||li(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(ur))&&(n.upgrade===void 0||nm(n.upgrade))}function nm(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||tm(n.major_hold))}function tm(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 Gn}from"node:child_process";import{existsSync as Sr}from"node:fs";import{delimiter as um,join as Bi}from"node:path";import{join as Ti}from"node:path";import{existsSync as rm}from"node:fs";import{createRequire as om}from"node:module";var Ni="redskilled-job-object.node",be=100;function Ne(e){return{available:!1,reason:e}}function sm(e,n,t){return[Ti(t,"prebuilds",`${e}-${n}`,Ni),Ti(t,"native","build","Release",Ni)]}function Wi(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return Ne(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??lm(),o=e.exists??rm,s=sm(n,t,r),i=s.find(d=>o(d));if(i==null)return Ne(`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??om(import.meta.url),a;try{a=l(i)}catch(d){return Ne(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return im(a)?{available:!0,binding:a}:Ne(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function im(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function lm(){return new URL("..",import.meta.url).pathname}function Ci(e){let n=e??{},t=[],r=am(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<be?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 ${be}, 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 am(e){return dn({budget:e})}var Kn=5,Mi=19;function wr(e){return{available:!1,reason:e}}var dm="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 Ui(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=Kn;else if(t.cpu_weight<be){let l=Math.round(Mi*(be-t.cpu_weight)/be);o=Math.min(Mi,Math.max(Kn,l))}else o=Kn,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${be}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Kn}`);let s=Fi(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=Fi(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:dm,...r.length>0?{note:r.join("; ")}:{}}}function Hi(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 ${cm(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
60
- `),e.command,...e.args]}function Vi(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 _r(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 Fi(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function cm(e){return`'${e.replace(/'/g,"'\\''")}'`}var Ji="REDSKILLED_PLACEMENT",qn="red-worker",vr="/bin/sh";function Ki(e=process.env,n=process.platform){let t=wr(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:Wi({platform:n}),posix:t};let r=Ne(`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:pm(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Sr(Bi(o,"systemd","private"));return{platform:n,systemdRun:Qi("systemd-run",e),userSession:s,jobObjects:r,posix:t}}function pm(e){return Sr(vr)?{available:!0,shell:vr,nice:Qi("nice",e)}:wr(`no POSIX shell was found at ${vr}, so there is nothing to apply rlimits or priority in`)}function qi(e=process.env){let n=(e[Ji]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function fm(e,n,t=qn){return Gi(e,n,t).replace(/\.service$/,"")}function Gi(e,n,t=qn){return`${xr(t,"red-worker",24)}-${xr(e,"project",32)}-${xr(n,"worker",32)}.service`}function zi(e){let n=[...e.args??[]],t=e.budget??{},r=t.memory_high!=null||t.memory_max!=null||t.cpu_weight!=null,o=e.target??{isolation:"transient-unit"},s=d=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:d,...r?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(o.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 ${Ji}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return hm(e,n,r,s);if(e.probes.platform==="darwin")return mm(e,n,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 i=Gi(e.projectLabel,e.workerId,o.unit_prefix),l=["--user","--collect","--quiet","--wait",`--unit=${i}`,`--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}`);for(let[d,u]of Object.entries(e.env??{}))l.push(`--setenv=${d}=${u}`);let a=_r(e.budget);return{isolated:!0,backend:"transient-unit",unit:i,command:e.probes.systemdRun,args:[...l,"--",e.command,...n],...a!=null?{budgetWarning:a}:{}}}function mm(e,n,t){let r=e.probes.posix;if(!r.available)return t(`POSIX limit placement unavailable: ${r.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 o=Ui(e.budget,{canRenice:r.nice!=null}),s=e.budget??{},i=s.memory_high!=null||s.memory_max!=null;return{isolated:!1,backend:"posix-limits",command:r.shell,args:Hi({limits:o,nice:r.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:o,warning:Vi(o),...i?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+o.memory_ceiling_reason}:{}}}function hm(e,n,t,r){let o=e.probes.jobObjects;if(!o.available)return r(`Job Object placement unavailable: ${o.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=Ci(e.budget),i=fm(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...n],cwd:e.workspacePath,job:{name:i,limits:s},...gm(t&&s.note!=null?`${s.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,_r(e.budget))}}function gm(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function Qi(e,n){for(let t of(n.PATH??"").split(um)){if(!t)continue;let r=Bi(t,e);if(Sr(r))return r}return null}function xr(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function Er(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 Yi(e){return e.unit!=null&&e.unit!==""?ym(e.unit):W(e.pid)}function ym(e){let n=Gn("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var km="REDSKILLED_UNIT_DISCOVERY",Zi="(unowned)";function Xi(e){let n=Gn("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 Rm(e=process.env){let n=(e[km]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function el(e,n,t=process.env){return Rm(t)&&e===n}function nl(e=qn){let n=Gn("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 tl(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:Zi,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 rl(e){return e.project_label.trim()!==""?e:{...e,project_label:Zi,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 ol(e){if(e.unit!=null&&e.unit!==""){let n=Gn("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 bm(e,n=50){if(al(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 wm(e,n={}){let t=n.batchSize??50;if(al(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 _m(e,n){let t=un(n),r=un(t.data),o=Array.isArray(t.errors)?t.errors.map(un):[],s=xm(r.rateLimit,o);return{projects:e.aliases.map(({alias:l,project:a})=>{let d=Em(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=>Sm(p.path,l));return s.exhausted||dl(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: ${Pr(u?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function vm(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 il(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 ll(e){if(e.projects.length===0)return vm(e.now);let n=e.batchSize??50,t=bm(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=wm(s,{batchSize:n});try{let l=await e.transport(i.query),a=_m(i,l);r.push(...a.projects),o=sl(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=sl(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 al(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 sl(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 xm(e,n){let t=un(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(dl)||r===0}}function dl(e){return e==null?!1:Pr(e.type)==="RATE_LIMITED"||/rate limit/i.test(Pr(e.message))}function Sm(e,n){return Array.isArray(e)&&e.includes(n)}function Em(e){let n=un(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function un(e){return Pm(e)?e:{}}function Pm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pr(e){return typeof e=="string"?e:""}import{randomUUID as cl}from"node:crypto";import{spawn as jm}from"node:child_process";import{closeSync as Dm,mkdirSync as Om,openSync as Lm}from"node:fs";import{dirname as $m}from"node:path";var pn=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},zn=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function Am(e){if(e==null||e.trim()==="")return null;try{return Om($m(e),{recursive:!0}),Lm(e,"a")}catch{return null}}function Im(e){try{Dm(e)}catch{}}function Tm(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 pn(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new pn("redskilled worker spec args must be an array")}function Nm(e){if(e==null)throw new zn("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new zn(e.reason,e)}function pl(e){let{spec:n,admission:t}=e;Nm(t),Tm(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(n.worker_id??e.workerId??cl()).trim()||cl(),i=e.probes??Ki(r),l=e.openLog===!1?null:Am(n.log_path),a=zi({workerId:s,projectLabel:n.project_label,workspacePath:n.workspace_path,command:n.command,args:n.args,budget:n.budget,target:n.placement,env:n.env,enabled:e.enabled??qi(r),probes:i,pipeOutput:l!==null}),u=(e.spawnFn??jm)(a.command,a.args,{...a.cwd!=null?{cwd:a.cwd}:{},detached:!0,stdio:l===null?"ignore":["ignore",l,l],env:a.isolated?{...r}:{...r,...n.env??{}}});if(l!==null&&Im(l),u.pid==null)throw u.once("error",()=>{}),new pn(`redskilled could not spawn ${JSON.stringify(a.command)} for worker ${s}`);let p=a.job!=null?Wm(a,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(y,b)=>{try{p?.job?.close()}catch{}e.onExit?.(s,y,b)}),u.unref();let f=a.job!=null?p?.job!=null:a.isolated,g=[a.warning,p?.warning,a.budgetWarning].filter(y=>y!=null);return{worker:{worker_id:s,project_label:n.project_label,pid:u.pid,started_at:o(),workspace_path:n.workspace_path,...n.log_path!=null?{log_path:n.log_path}:{},isolated:f,...a.unit!=null?{unit:a.unit}:{},...n.budget!=null?{budget:n.budget}:{},warnings:g},admission:t,warnings:g,plan:a,child:u,...p?.job!=null?{job:p.job}:{}}}function Wm(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: ${ul(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)}: ${ul(i)}. ${o}`}}return{job:s}}function ul(e){return e instanceof Error?e.message:String(e)}import{open as Cm,stat as Mm}from"node:fs/promises";var Fm=16*1024;async function fl(e,n=Fm){let t;try{t=(await Mm(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let s=await Cm(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 Um(o)}function Um(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 nh}from"node:child_process";import{existsSync as th,readdirSync as rh}from"node:fs";import{dirname as oh,join as Rl,resolve as sh}from"node:path";function H(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 jr(e,n){let t=H(e),r=H(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var yb=4*60*60*1e3;te();te();import{spawnSync as Hm}from"node:child_process";import{mkdir as Vm,rm as Bm,writeFile as Jm}from"node:fs/promises";import{existsSync as Km}from"node:fs";import{homedir as qm}from"node:os";import{dirname as Gm,join as Dr}from"node:path";var We="redskilled.service",Or="REDSKILLED_SUPERVISED",zm="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function Qm(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||Dr(e.HOME?.trim()||qm(),".config");return Dr(n,"systemd","user")}function Lr(e=process.env){return Dr(Qm(e),We)}function ml(e,n={}){let t=n.env??process.env,r=Cn(n.override??{},n.entryLookup??{}),o=[...r.args,...Re(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:We,unitPath:Lr(t),command:r.command,args:o,text:Ym(r.command,o,e)}}function Ym(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${zm}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(Zm).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Or}=1"`,`Environment="REDSKILLED_SESSION=${hl(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
64
- `)}function Zm(e){return/[\s"'\\$%]/.test(e)?`"${hl(e)}"`:e}function hl(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function gl(e,n={}){let t=n.writeFile??Xm,r=n.run??$r,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(Qn("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(Qn("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function yl(e={}){let n=e.removeFile??eh,t=e.run??$r,r=Lr(e.env??process.env),o=[Qn("disable",t,["systemctl","--user","disable","--now",We])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(Qn("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function kl(e={}){let n=e.exists??Km,t=e.run??$r,r=Lr(e.env??process.env),o=n(r);return{unitName:We,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",We]).status===0,active:o&&t(["systemctl","--user","is-active",We]).status===0,floor:"auto-spawn"}}function Qn(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 Xm(e,n){await Vm(Gm(e),{recursive:!0}),await Jm(e,n,{encoding:"utf8",mode:420})}async function eh(e){await Bm(e,{force:!0})}function $r(e){let n=Hm(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 bl=75,_l=9e5,wl="redskilled-replacement-entry-unresolved",ih="REDSKILLED_NO_REGISTRY_PROBE",vl="REDSKILLED_BORN_BY_REPLACEMENT";function xl(e=process.env){return e[vl]==="1"}function Sl(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function El(e){let n=e.running.trim();if(fn(n))return null;let t=e.newest?.trim()??"",r=H(t),o=H(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:lh(r.major,e.supervised)}}function lh(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 Pl(e){let n=e.running.trim();if(fn(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||H(t)===null?{act:"hold",reason:"published-unknown"}:jr(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function fn(e){let n=e.trim();return H(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function jl(e=process.env){return e[Or]==="1"}var Ar=class extends Error{code=wl;searched;constructor(n,t){super(`${wl}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
56
+ `).filter(wp).map(_p)}function Qs(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,Rp(t)):n.delete(t.worker_id));return[...n.values()]}function Rp(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 bp(e){return{...e}}function wp(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 _p(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:re(e.project_label)??"",pid:Number(e.pid??0),workspace_path:re(e.workspace_path)??"",log_path:re(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:re(e.unit),memory_high:re(e.memory_high),memory_max:re(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:re(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:re(e.signal),reason:re(e.reason)}}function re(e){return e==null||e===""?null:String(e)}function Ys(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),c=a?e.queue[i.project_label]??null:null,u={project_label:i.project_label,queue_depth:c,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(c==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(c===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),c)-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 ${c}, 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 ${c}, so it asks for ${p} more`});for(let f=0;f<p;f+=1)(s[f]??(s[f]=[])).push({project_label:i.project_label,index:l+f,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function Zs(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function ei(e){let n=e.workers.map(vp),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:Sp({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function ni(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 vp(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 xp(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 Sp(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${xp(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${Xs(e.held,"Worker")} across ${Xs(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 Xs(e,n){return`${e} ${n}${e===1?"":"s"}`}function ar(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 Ep,mkdir as Pp,readFile as jp,rm as Dp,writeFile as Op}from"node:fs/promises";import{dirname as ti,join as ii}from"node:path";import{tmpdir as ri}from"node:os";var $p="redskilled.machine.claim.toon",Ap="REDSKILLED_MACHINE_DIR",Lp=8,ue=class extends Error{constructor(t,r,o){super(Tp(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},oi;function li(){return oi??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},oi}function Ip(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[Ap]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||ri():ri();return ii(o,`redskilled-${e.machineIdHash}`)}function Bn(e){return ii(Ip(e),$p)}function Vn(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??W;async function s(){let a;try{a=await jp(e,"utf8")}catch(u){if(u.code==="ENOENT"||dr(u))return;throw u}let c=Wp(a);return Cp(c)?c:void 0}function i(a,c){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:c,renewed_at:c}}async function l(){try{return await Dp(e,{force:!0}),!0}catch(a){if(dr(a))return!1;throw a}}return{claimPath:e,read:s,async claim(a){await Pp(ti(e),{recursive:!0,mode:1023})!=null&&await Ep(ti(e),1023).catch(()=>{});let u=!1;for(let p=0;p<Lp;p+=1){let f=i(a,r());try{return await Op(e,Np(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:u,claim:f}}catch(k){if(k.code!=="EEXIST"){if(dr(k))return{claimed:!1,reason:"stale-claim-not-reapable"};throw k}}let h=await s();if(!h){if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable"};u=!0;continue}if(si(h,a,n.socketPath))return{claimed:!0,reaped:u,claim:h};if(await o(h.pid))return{claimed:!1,reason:"held",claim:h};if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable",claim:h};u=!0}return{claimed:!1,reason:"contended"}},async release(a){let c=await s();return!c||!si(c,a,n.socketPath)?!1:await l()}}}function ai(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 di(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 Tp(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 dr(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function si(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function Np(e){return`${I(e,{keyedMapCollapse:!0})}
57
+ `}function Wp(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return G(n)}catch{return null}}}function Cp(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 cr(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 ur(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 Mp=3e5,Fp=.5,fr=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 ci(e,n){if(n.held!=null)throw new fr(n.held);let t=pr(e.project_label,"a project label"),r=pr(e.selector,"a selector"),o=cr(e.argv,t),s=ur(e.env,t),i=pr(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??Mp;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 Kn=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 ui(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:cr(n.launch.argv,e.project_label),env:ur(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 pi(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 Hp(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function fi(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*Fp;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 mi(e,n){let t=[],r=[];for(let o of e)(Hp(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function mr(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||Up(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 Up(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function pr(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var Bp={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 hi(e){return`worker-${e}`}function gi(e){let n=Bp[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.`}}import{execFileSync as Vp}from"node:child_process";import{readFileSync as Kp,readdirSync as Jp}from"node:fs";import{join as qp}from"node:path";function dn(e){let n=e.budget??{},t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let s=Le(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function yi(e){let n=[],t=[];for(let r of e.workers){let o=dn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(r.budget?.memory_max??r.budget?.memory_high)==null?"this Worker declared no memory budget, so the sampler has no ceiling 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(Gp(r,o,s))}return{terminations:n,unenforceable:t}}function Gp(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 zp=4096;function ki(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{}};if(e.length===0)return r;let o=Qp(t,n);if(o.size===0)return r;let s=new Map;for(let a of o.values()){let c=s.get(a.ppid);c?c.push(a.pid):s.set(a.ppid,[a.pid])}let i={},l={};for(let a of e){if(!o.has(a.pid))continue;let c=0,u=0,p=[a.pid],f=new Set;for(;p.length>0;){let h=p.pop();if(f.has(h))continue;f.add(h);let k=o.get(h);if(k){c+=k.rssBytes,u+=k.cpuSeconds;for(let y of s.get(h)??[])p.push(y)}}i[a.worker_id]=c,l[a.worker_id]=u}return{rss:i,cpu_seconds:l}}function Qp(e,n){return n.procRoot!=null||e==="linux"?tf(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?ef(Yp(n.psTable)):new Map}function Yp(e){try{return(e??Zp)()}catch{return""}}function Zp(){return Vp("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Xp=1024;function ef(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=nf(r[3]);l!=null&&n.set(o,{pid:o,ppid:s,rssBytes:i*Xp,cpuSeconds:l})}return n}function nf(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 tf(e){let n=new Map,t;try{t=Jp(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=Kp(qp(e,r,"stat"),"utf8")}catch{continue}let s=of(o);s&&n.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*zp,cpuSeconds:s.cpuTicks/rf})}return n}var rf=100;function of(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 hr=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 yr(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new hr(t.project_label,t.token_ref,n)}function sf(e,n={now:new Date(0).toISOString()}){df(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,c)=>({alias:`r${c}`,search_alias:`c${c}`,project:a}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { remaining resetAt }",...s.flatMap(({alias:a,search_alias:c,project:u})=>{let p=JSON.stringify(u.owner),f=JSON.stringify(u.name),h=JSON.stringify(`repo:${u.owner}/${u.name} is:closed closed:>=${o}`);return[` ${a}: repository(owner: ${p}, name: ${f}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${c}: search(query: ${h}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
59
+ `),aliases:s,closed_since:o}}function lf(e,n,t){let r=Ie(n),o=Ie(r.data),s=Array.isArray(r.errors)?r.errors.map(Ie):[],i=cf(o.rateLimit,s),l=e.aliases.map(({alias:a,search_alias:c,project:u})=>{let p=u.owner+"/"+u.name,f=o[a],h=s.find(k=>Ri(k.path,a)||Ri(k.path,c));if(Si(f)){let k=bi(f.open_pull_requests),y=bi(f.open_issues),b=uf(o[c]);if(k!=null&&y!=null&&b!=null)return{project_label:u.project_label,repository:p,outcome:"counted",counts:{open_pull_requests:k,open_issues:y,recently_closed:b},detail:`counted ${p} for project ${JSON.stringify(u.project_label)}`}}return i.exhausted||xi(h)?{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: ${gr(h?.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 af(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 wi(e){if(e.projects.length===0)return af(e.now);yr(e.projects,e.hostTokenRef);let n=sf(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return lf(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 _i(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 vi(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 df(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 cf(e,n){let t=Ie(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(xi);return{remaining:r,reset_at:o,exhausted:s||r===0}}function xi(e){if(e==null)return!1;let n=gr(e.type),t=gr(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function Ri(e,n){return Array.isArray(e)&&e.includes(n)}function bi(e){let n=Ie(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function uf(e){let n=Ie(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Ie(e){return Si(e)?e:{}}function Si(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gr(e){return typeof e=="string"?e:""}var pf=3e4,ff=4;function Ei(e){let n=e.stalenessMs??pf,t=cn(e.now),r=e.sampledAt==null?null:cn(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),s=o!=null&&o<=n,i=new Set(e.reattachedWorkerIds??[]),l=e.hostState.workers.map(f=>gf(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:i.has(f.worker_id)?"reattached":"running"})),a=l.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),c=l.length-a.length,u=l.reduce((f,h)=>f+(h.vitals.rss_bytes??0),0),p=lr(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:bf({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:l.length,measuredCount:c,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:c,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:p.memory_bytes/e.ceiling.memory_bytes},projects:Rf(l),known_projects:kf(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,h)=>f.localeCompare(h)),workers:l,repository_activity:_i({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:mf(e.deaths,e.recentDeathLimit??ff)},engine:hf(e.hostState)}}function mf(e,n){let t=[...e].sort((o,s)=>(cn(s.ts)??0)-(cn(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 hf(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 gf(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=dn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=cn(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:yf(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function yf(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 kf(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 Rf(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 bf(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 cn(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 Pi(e,n=O){let t=Pf(e,n),r=Sf(e,n),o=Ef(e,n),s=jf(e,n,r,t),i=vf(n,r,o),l={detail:"host",line:s};for(let p of i){let f=Cf(s,xf(p,n,r,o),n.separator);if(l={detail:p,line:f},Mf(f)<=n.maxWidth)break}let a=wr(l.line,n.maxWidth),c=n.verbose&&l.detail==="workers"?If(r,n):[],u=r.length>0?"workers":"host";return{version:1,line:a,lines:[a,...c],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 ji(e){let n=e.options??O,t=wr(_f,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 wf="!unregistered",Rr="\u21E1",Jn="\u2020",_f="redskilled unreachable \u2014 Worker state unknown";function vf(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 xf(e,n,t,r){return e==="workers"?t.map(o=>Lf(o,n)):e==="projects"?r.map(Wf):[]}function Sf(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Ef(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function Pf(e,n){return br(e,n.project)}function br(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 jf(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(kr(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(kr(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(kr(e,n)),o.push(wf)):o.push($f(n.project,r)),o.push(Df(e));let s=Of(e);return s!=null&&o.push(s),e.staleness.stale&&o.push(Af(e)),o.join(" ")}function Df(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${Rr}`}function Of(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Jn}${n.count} ${n.latest.sender_class}`}function $f(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 kr(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 Af(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function Lf(e,n){let t=Di(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 If(e,n){let t=[];for(let r of e){let o=Nf(r.log.last_line);o!=null&&t.push(wr(` ${Tf} ${Di(r,n)}: ${o}`,n.maxWidth))}return t}var Tf="\u21B3";function Nf(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}function Di(e,n){return n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Wf(e){return`${e.project_label} ${e.worker_count}w ${H(e.observed_rss_bytes)}`}function Cf(e,n,t){return[e,...n].join(t)}function Mf(e){return[...e].length}function wr(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 _r={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},Ff=["runner","model","effort","origin","issue","phase","step","heartbeat"],Hf=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function Oi(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={..._r};for(let r of Ff){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of Hf){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}var qn=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],Te={mode:"local",project:null,maxWidth:200,maxRows:16};var Uf=" ",$i="\u2588",Bf="\u25B6",Vf="\u2717",Kf="\u2591";function Ai(e,n=Te){let t=br(e,n.project),r=Jf(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(p=>qf(p,n)),i=tm(s),l=o.map((p,f)=>({worker_id:p.worker_id,project_label:p.project_label,mine:n.project!=null&&p.project_label===n.project,cells:s[f],line:un(rm(s[f],i),n.maxWidth)})),a=zf(e,n,r,t),c=r.length-o.length,u=[a.line,...l.map(p=>p.line)];return c>0&&u.push(un(`\u2026 ${c} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),u.push(...Qf(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:qn,header:a,rows:l,lines:u,hidden_row_count:Math.max(0,c),stale:e.staleness.stale}}function Jf(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function qf(e,n){let t=e.display??_r,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:Gf(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:nm(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:Xf(t.added,t.removed),tks:t.tokens==null?"":`tks=${em(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function Gf(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 $i.repeat(Math.floor(n));let o=e.failed?Vf:Bf;return`${$i.repeat(r)}${o}${Kf.repeat(Math.floor(n)-r-1)}`}function zf(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(h=>h.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=Zf(t),a=o?.repository??n.project,c=e.engine??null,u=c?.running_version??e.daemon.daemon_version,p=e.deaths??null,f=[`\xBB ${a??"host"} v${u}${c!=null&&c.current===!1?Rr:""}`];if(r==="unregistered"&&f.push("!unregistered"),r==="name-only"&&f.push("!lapsed"),l!=null&&f.push(l),f.push(`wrk=${t.length}/${e.host.worker_count}`),f.push(i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`),f.push(Yf(i)),s.open_pull_requests!=null&&f.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&f.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&f.push(`iss=${s.open_issues}`),s.stale&&f.push("!counts stale"),p!=null&&p.count>0&&p.latest!=null&&f.push(`${Jn}${p.count} ${p.latest.sender_class}`),e.staleness.stale){let h=e.staleness.age_ms;f.push(h==null?"!unmeasured":`!stale ${Math.round(h/1e3)}s`)}return{repo:a,project:n.project,project_match:r,version:u,engine:c,deaths:p,model:l,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:un(f.join(" \xB7 "),n.maxWidth)}}function Qf(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(s=>un(`${Jn} ${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(un(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function Yf(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 Zf(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 Xf(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 em(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 nm(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 tm(e){let n=Object.fromEntries(qn.map(t=>[t,0]));for(let t of e)for(let r of qn)n[r]=Math.max(n[r],Li(t[r]));return n}function rm(e,n){return qn.filter(r=>n[r]>0).map(r=>om(e[r],n[r])).join(Uf).replace(/\s+$/,"")}function om(e,n){return e+" ".repeat(Math.max(0,n-Li(e)))}function Li(e){return[...e].length}function un(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 Gn=1;async function pn(e,n){return await Nn(e,n,"redskilled daemon")}function Ii(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 Ti(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:Gn,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:lm(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:Us(n),upgrade:am(e)}}function lm(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:fi(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 am(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 Ni(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)&&Bs(n.budget_accounting)&&(n.scope===void 0||di(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(mr))&&(n.upgrade===void 0||dm(n.upgrade))}function dm(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||cm(n.major_hold))}function cm(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 Yn}from"node:child_process";import{existsSync as Pr}from"node:fs";import{delimiter as Rm,join as Ji}from"node:path";import{join as Wi}from"node:path";import{existsSync as um}from"node:fs";import{createRequire as pm}from"node:module";var Ci="redskilled-job-object.node",be=100;function Ne(e){return{available:!1,reason:e}}function fm(e,n,t){return[Wi(t,"prebuilds",`${e}-${n}`,Ci),Wi(t,"native","build","Release",Ci)]}function Mi(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return Ne(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??hm(),o=e.exists??um,s=fm(n,t,r),i=s.find(c=>o(c));if(i==null)return Ne(`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??pm(import.meta.url),a;try{a=l(i)}catch(c){return Ne(`the Job Object addon at ${i} could not be loaded: ${c instanceof Error?c.message:String(c)}`)}return mm(a)?{available:!0,binding:a}:Ne(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function mm(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function hm(){return new URL("..",import.meta.url).pathname}function Fi(e){let n=e??{},t=[],r=gm(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<be?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 ${be}, 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 gm(e){return dn({budget:e})}var zn=5,Hi=19;function vr(e){return{available:!1,reason:e}}var ym="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 Bi(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=zn;else if(t.cpu_weight<be){let l=Math.round(Hi*(be-t.cpu_weight)/be);o=Math.min(Hi,Math.max(zn,l))}else o=zn,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${be}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${zn}`);let s=Ui(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=Ui(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:ym,...r.length>0?{note:r.join("; ")}:{}}}function Vi(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 ${km(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
60
+ `),e.command,...e.args]}function Ki(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 xr(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 Ui(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function km(e){return`'${e.replace(/'/g,"'\\''")}'`}var qi="REDSKILLED_PLACEMENT",Qn="red-worker",Sr="/bin/sh";function Gi(e=process.env,n=process.platform){let t=vr(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:Mi({platform:n}),posix:t};let r=Ne(`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:bm(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Pr(Ji(o,"systemd","private"));return{platform:n,systemdRun:Zi("systemd-run",e),userSession:s,jobObjects:r,posix:t}}function bm(e){return Pr(Sr)?{available:!0,shell:Sr,nice:Zi("nice",e)}:vr(`no POSIX shell was found at ${Sr}, so there is nothing to apply rlimits or priority in`)}function zi(e=process.env){let n=(e[qi]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function wm(e,n,t=Qn){return Qi(e,n,t).replace(/\.service$/,"")}function Qi(e,n,t=Qn){return`${Er(t,"red-worker",24)}-${Er(e,"project",32)}-${Er(n,"worker",32)}.service`}function Yi(e){let n=[...e.args??[]],t=e.budget??{},r=t.memory_high!=null||t.memory_max!=null||t.cpu_weight!=null,o=e.target??{isolation:"transient-unit"},s=c=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:c,...r?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(o.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 ${qi}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return vm(e,n,r,s);if(e.probes.platform==="darwin")return _m(e,n,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 i=Qi(e.projectLabel,e.workerId,o.unit_prefix),l=["--user","--collect","--quiet","--wait",`--unit=${i}`,`--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}`);for(let[c,u]of Object.entries(e.env??{}))l.push(`--setenv=${c}=${u}`);let a=xr(e.budget);return{isolated:!0,backend:"transient-unit",unit:i,command:e.probes.systemdRun,args:[...l,"--",e.command,...n],...a!=null?{budgetWarning:a}:{}}}function _m(e,n,t){let r=e.probes.posix;if(!r.available)return t(`POSIX limit placement unavailable: ${r.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 o=Bi(e.budget,{canRenice:r.nice!=null}),s=e.budget??{},i=s.memory_high!=null||s.memory_max!=null;return{isolated:!1,backend:"posix-limits",command:r.shell,args:Vi({limits:o,nice:r.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:o,warning:Ki(o),...i?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+o.memory_ceiling_reason}:{}}}function vm(e,n,t,r){let o=e.probes.jobObjects;if(!o.available)return r(`Job Object placement unavailable: ${o.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=Fi(e.budget),i=wm(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...n],cwd:e.workspacePath,job:{name:i,limits:s},...xm(t&&s.note!=null?`${s.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,xr(e.budget))}}function xm(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function Zi(e,n){for(let t of(n.PATH??"").split(Rm)){if(!t)continue;let r=Ji(t,e);if(Pr(r))return r}return null}function Er(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function jr(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 Xi(e){return e.unit!=null&&e.unit!==""?Sm(e.unit):W(e.pid)}function Sm(e){let n=Yn("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var Em="REDSKILLED_UNIT_DISCOVERY",el="(unowned)";function nl(e){let n=Yn("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 Pm(e=process.env){let n=(e[Em]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function tl(e,n,t=process.env){return Pm(t)&&e===n}function rl(e=Qn){let n=Yn("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 ol(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:el,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 sl(e){return e.project_label.trim()!==""?e:{...e,project_label:el,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 il(e){if(e.unit!=null&&e.unit!==""){let n=Yn("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 jm(e,n=50){if(cl(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 Dm(e,n={}){let t=n.batchSize??50;if(cl(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 Om(e,n){let t=fn(n),r=fn(t.data),o=Array.isArray(t.errors)?t.errors.map(fn):[],s=Am(r.rateLimit,o);return{projects:e.aliases.map(({alias:l,project:a})=>{let c=Im(r[l]);if(c!=null)return{project_label:a.project_label,outcome:"counted",depth:c,detail:`project ${JSON.stringify(a.project_label)} has ${c} item(s) matching its selector`};let u=o.find(p=>Lm(p.path,l));return s.exhausted||ul(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: ${Dr(u?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function $m(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 al(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 dl(e){if(e.projects.length===0)return $m(e.now);let n=e.batchSize??50,t=jm(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=Dm(s,{batchSize:n});try{let l=await e.transport(i.query),a=Om(i,l);r.push(...a.projects),o=ll(o,a.rate_limit)}catch(l){let a=l instanceof Error?l.message:String(l),c=/rate limit|secondary rate|429/i.test(a);o=ll(o,{remaining:null,reset_at:null,exhausted:c});for(let u of s)r.push({project_label:u.project_label,outcome:c?"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 cl(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 ll(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 Am(e,n){let t=fn(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(ul)||r===0}}function ul(e){return e==null?!1:Dr(e.type)==="RATE_LIMITED"||/rate limit/i.test(Dr(e.message))}function Lm(e,n){return Array.isArray(e)&&e.includes(n)}function Im(e){let n=fn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function fn(e){return Tm(e)?e:{}}function Tm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dr(e){return typeof e=="string"?e:""}import{randomUUID as pl}from"node:crypto";import{spawn as Nm}from"node:child_process";import{closeSync as Wm,mkdirSync as Cm,openSync as Mm}from"node:fs";import{dirname as Fm}from"node:path";var mn=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},Zn=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function Hm(e){if(e==null||e.trim()==="")return null;try{return Cm(Fm(e),{recursive:!0}),Mm(e,"a")}catch{return null}}function Um(e){try{Wm(e)}catch{}}function Bm(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 mn(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new mn("redskilled worker spec args must be an array")}function Vm(e){if(e==null)throw new Zn("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new Zn(e.reason,e)}function ml(e){let{spec:n,admission:t}=e;Vm(t),Bm(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(n.worker_id??e.workerId??pl()).trim()||pl(),i=e.probes??Gi(r),l=e.openLog===!1?null:Hm(n.log_path),a=Yi({workerId:s,projectLabel:n.project_label,workspacePath:n.workspace_path,command:n.command,args:n.args,budget:n.budget,target:n.placement,env:n.env,enabled:e.enabled??zi(r),probes:i,pipeOutput:l!==null}),u=(e.spawnFn??Nm)(a.command,a.args,{...a.cwd!=null?{cwd:a.cwd}:{},detached:!0,stdio:l===null?"ignore":["ignore",l,l],env:a.isolated?{...r}:{...r,...n.env??{}}});if(l!==null&&Um(l),u.pid==null)throw u.once("error",()=>{}),new mn(`redskilled could not spawn ${JSON.stringify(a.command)} for worker ${s}`);let p=a.job!=null?Km(a,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(y,b)=>{try{p?.job?.close()}catch{}e.onExit?.(s,y,b)}),u.unref();let f=a.job!=null?p?.job!=null:a.isolated,h=[a.warning,p?.warning,a.budgetWarning].filter(y=>y!=null);return{worker:{worker_id:s,project_label:n.project_label,pid:u.pid,started_at:o(),workspace_path:n.workspace_path,...n.log_path!=null?{log_path:n.log_path}:{},isolated:f,...a.unit!=null?{unit:a.unit}:{},...n.budget!=null?{budget:n.budget}:{},warnings:h},admission:t,warnings:h,plan:a,child:u,...p?.job!=null?{job:p.job}:{}}}function Km(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: ${fl(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)}: ${fl(i)}. ${o}`}}return{job:s}}function fl(e){return e instanceof Error?e.message:String(e)}import{open as Jm,stat as qm}from"node:fs/promises";var Gm=16*1024;async function hl(e,n=Gm){let t;try{t=(await qm(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let s=await Jm(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 zm(o)}function zm(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 dh}from"node:child_process";import{existsSync as ch,readdirSync as uh}from"node:fs";import{dirname as ph,join as wl,resolve as fh}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 Or(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 Sb=4*60*60*1e3;te();te();import{spawnSync as Qm}from"node:child_process";import{mkdir as Ym,rm as Zm,writeFile as Xm}from"node:fs/promises";import{existsSync as eh}from"node:fs";import{homedir as nh}from"node:os";import{dirname as th,join as $r}from"node:path";var We="redskilled.service",Ar="REDSKILLED_SUPERVISED",rh="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function oh(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||$r(e.HOME?.trim()||nh(),".config");return $r(n,"systemd","user")}function Lr(e=process.env){return $r(oh(e),We)}function gl(e,n={}){let t=n.env??process.env,r=Fn(n.override??{},n.entryLookup??{}),o=[...r.args,...Re(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:We,unitPath:Lr(t),command:r.command,args:o,text:sh(r.command,o,e)}}function sh(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${rh}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(ih).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Ar}=1"`,`Environment="REDSKILLED_SESSION=${yl(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
64
+ `)}function ih(e){return/[\s"'\\$%]/.test(e)?`"${yl(e)}"`:e}function yl(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function kl(e,n={}){let t=n.writeFile??lh,r=n.run??Ir,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(Xn("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(Xn("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function Rl(e={}){let n=e.removeFile??ah,t=e.run??Ir,r=Lr(e.env??process.env),o=[Xn("disable",t,["systemctl","--user","disable","--now",We])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(Xn("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function bl(e={}){let n=e.exists??eh,t=e.run??Ir,r=Lr(e.env??process.env),o=n(r);return{unitName:We,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",We]).status===0,active:o&&t(["systemctl","--user","is-active",We]).status===0,floor:"auto-spawn"}}function Xn(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 lh(e,n){await Ym(th(e),{recursive:!0}),await Xm(e,n,{encoding:"utf8",mode:420})}async function ah(e){await Zm(e,{force:!0})}function Ir(e){let n=Qm(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 _l=75,xl=9e5,vl="redskilled-replacement-entry-unresolved",mh="REDSKILLED_NO_REGISTRY_PROBE",Sl="REDSKILLED_BORN_BY_REPLACEMENT";function El(e=process.env){return e[Sl]==="1"}function Pl(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function jl(e){let n=e.running.trim();if(hn(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:hh(r.major,e.supervised)}}function hh(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 Dl(e){let n=e.running.trim();if(hn(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||U(t)===null?{act:"hold",reason:"published-unknown"}:Or(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function hn(e){let n=e.trim();return U(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function Ol(e=process.env){return e[Ar]==="1"}var Tr=class extends Error{code=vl;searched;constructor(n,t){super(`${vl}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
65
65
  searched:
66
66
  ${t.map(r=>` ${r}`).join(`
67
- `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function ah(e,n={}){let t=n.env??process.env,r=n.exists??th,o=n.execPath??process.execPath,s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,l=[],a=[[Rl(Wn(t),i),"bundle-cache"]];s&&a.push([Rl(oh(sh(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 Ar(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 Dl(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>ah(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function Ol(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??ch)(bl),{...e,exitCode:bl};let o=[...e.entry.args,...Re(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??dh(r.env))(e.entry,o),e}function dh(e){return(n,t)=>{let r=nh(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[vl]:"1"}});r.on("error",()=>{}),r.unref()}}function ch(e){process.exitCode=e,process.exit(e)}async function Ll(e,n=process.env,t=uh){let r=Al(n),o=Il(e,n);if(n[ih]==="1")return{version:o,newest:r};let s=H(e)===null?"0.0.0":e;try{let i=await Ts({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function $l(e,n=process.env,t){let r=t??Ir;return{version:Il(e,n,r),newest:Al(n,r)}}function Al(e=process.env,n=Ir){return Nl(Tl(e,n))}function Il(e,n=process.env,t=Ir){let r=H(e.trim())?.major;return r===void 0?null:Nl(Tl(n,t).filter(o=>H(o)?.major===r))}function Tl(e,n){let t=[];for(let r of n(Wn(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||H(o)===null||t.push(o)}return t}function Nl(e){let n=null;for(let t of e)(n===null||jr(t,n)>0)&&(n=t);return n}function Ir(e){try{return rh(e)}catch{return[]}}async function uh(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 ph,readFile as fh,rename as mh,rm as Tr,writeFile as Wl}from"node:fs/promises";import{randomUUID as hh}from"node:crypto";import{dirname as gh}from"node:path";var Yn=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function Wr(e){let n;try{n=await fh(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=yh(n);return kh(t)?t:void 0}var Cl;function Fl(){return Cl??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Cl}function Ul(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??W;async function s(){return await Wr(e)}async function i(a){let d=`${e}.${a.pid}.${hh()}.tmp`;await Wl(d,Ml(a),{encoding:"utf8",mode:384}),await mh(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 ph(gh(e),{recursive:!0,mode:448});let d=!1;for(;;){let u=r(),p=l(a,u);try{return await Wl(e,Ml(p),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:p}}catch(g){if(g.code!=="EEXIST")throw g}let f=await s();if(!f){await Tr(e,{force:!0}),d=!0;continue}if(Nr(f,a))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await Tr(e,{force:!0}),d=!0}},async renew(a){let d=await s();if(!d||!Nr(d,a))throw new Yn(e);let u={...d,renewed_at:r()};return await i(u),u},async release(a){let d=await s();if(!d)return!1;if(!Nr(d,a))throw new Yn(e);return await Tr(e,{force:!0}),!0}}}function Nr(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function Ml(e){return`${I(e,{keyedMapCollapse:!0})}
68
- `}function yh(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return G(n)}catch{return null}}}function kh(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 Cr=3e5,Eh=1e4,Ph=6e4,jh=15e3,Hl=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"}},Dh="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Bl(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??Cr,o=e.clock??(()=>new Date().toISOString()),s=e.launch??pl,i=e.ceiling??Bs();e.repositoryActivity!=null&&mr(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??Fl(),a=e.leaseStore??Ul(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??Hn(n.machineClaimPath,u,{clock:o});await vh(Sh(n.socketPath),{recursive:!0,mode:448});let f=await p.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new Ce(n.socketPath):new ue(p.claimPath,f.reason,f.claim);let g=await a.acquire(l);if(!g.acquired)throw await p.release(d).catch(()=>{}),new Ce(n.socketPath,g.lease);let k;try{k=await Oh(n.socketPath)}catch(c){throw await a.release(l).catch(()=>{}),await p.release(d).catch(()=>{}),c}let y=o(),b=e.eventLane??qs(n.eventLanePath),v=e.liveness??Yi,D=e.stopWorker??ol,V=e.unitInventory??(()=>el(n.machineClaimPath,Un({machineIdHash:n.machineIdHash}))?nl():[]),M=e.unitMainPid??Xi,pe=e.treeSampler??gi,we=e.readLogTail??fl,hn=e.sampleMs??jh,Gr=e.publishedVersion??(c=>Ll(c)),zr=e.replaceCheckMs??_l,Qr=e.publishedProbeTimeoutMs??Eh,va=e.localPublishedEvidence??(c=>$l(c,e.replacementIO?.env??process.env)),xa=e.bornByReplacement??xl(),Yr=e.replaceBootCheckMs??Ph,Zr=e.supervised??jl(),Xr=e.replacementIO??{},B=e.repositoryActivity,eo=B?.intervalMs??6e4,Ue=e.queueDiscovery,no=Ue?.transport??B?.transport,Sa=Ue?.unconfiguredReason??Dh,to=Ue?.intervalMs??15e3,ro=e.demandMs??15e3,Ea=e.demandBackoffMs??3e4,S=new Map,ie=new Set,_e=new Map,gn=new Map,A=new Map,et=new Set,oo={},nt=null,so=null,tt=null,io=!1,rt=0,ot=null,He="none",st=null,lo=null,it=null,le=null,yn=null,Ve=[],Be=null,lt=!1,ve,Je,Ke,qe,kn,Ge,ze,Z=!1,at=!1,Rn=null,ao,dt=new Promise(c=>{ao=c});function Qe(c){co(c);let m=Date.parse(c),h=pi(A.values(),m);for(let w of h.lapsed)A.delete(w.project_label),Pa(w,m);return h.lapsed}function Pa(c,m){let h=Number.isFinite(m)?new Date(m).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>Hl&&Ve.splice(0,Ve.length-Hl)}function co(c){if(A.size===0)return;let m=Date.parse(c);if(!Number.isFinite(m))return;let h={};for(let _ of S.values())h[_.project_label]=(h[_.project_label]??0)+1;let w=new Map((le?.projects??[]).map(_=>[_.project_label,_]));for(let _ of[...A.values()]){let j=w.get(_.project_label),Se=ci(_,{now:c,...j==null?{}:{queue:{outcome:j.outcome,depth:j.depth}},liveWorkers:h[_.project_label]??0});Se.registration!==_&&A.set(_.project_label,Se.registration)}}function bn(){let c=o();return Qe(c),Ai({now:c,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:l.pid,startedAt:y,scope:ii(p.claimPath,u,d),workers:[...S.values()],registrations:[...A.values()],lapses:Ve,queue:le,published:{version:so,checkedAt:tt,newer:io,replacement:He,newest:st,majorHold:lo,checks:rt,holdReason:ot}})}function wn(){return xi({hostState:bn(),ceiling:i,rss:oo,sampledAt:nt,logLines:Object.fromEntries(_e),displays:Object.fromEntries(gn),now:o(),reattachedWorkerIds:[...ie],repositoryActivity:it})}async function ct(){return B==null||B.projects.length===0?null:(it=await Ri({projects:B.projects,hostTokenRef:B.hostTokenRef,transport:B.transport,closedWindowMs:B.closedWindowMs,now:o()}),it)}async function uo(){let c=o();Qe(c);let m=[...A.values()].map(h=>({project_label:h.project_label,selector:h.selector})).sort((h,w)=>h.project_label.localeCompare(w.project_label));return m.length===0?null:no==null?(le=il(m,c,Sa),le):(le=await ll({projects:m,transport:no,now:c,...Ue?.batchSize==null?{}:{batchSize:Ue.batchSize}}),co(o()),le)}async function po(){let c=o();if(lt)return yn??Qs(c);lt=!0;try{let m={};for(let $ of S.values())m[$.project_label]=(m[$.project_label]??0)+1;let h={};for(let $ of le?.projects??[])h[$.project_label]=$.depth;let w=Date.parse(c),_=zs({projects:[...A.values()].map($=>({project_label:$.project_label,selector:$.selector,argv:$.argv,workspace_path:$.workspace_path,target:$.target})),queue:h,live:m,nowMs:Number.isFinite(w)?w:0,backoffUntilMs:Be}),j=[],Se=null;for(let $ of _.births){let En;try{En=ut({project_label:$.project_label,workspace_path:$.workspace_path,command:$.argv[0],args:$.argv.slice(1)})}catch(mt){Se=mt instanceof Error?mt.message:String(mt),Be=(Number.isFinite(w)?w:Date.now())+Ea;break}j.push({project_label:$.project_label,worker_id:En.worker.worker_id,pid:En.worker.pid,warnings:En.warnings})}return Se==null&&_.births.length>0&&(Be=null),yn={version:1,at:c,requested:_.births.length,granted:j,shortfall:_.births.length-j.length,refusal:Se,retry_after:Be==null?null:new Date(Be).toISOString(),projects:_.intents},yn}finally{lt=!1}}function ja(c){return Si(wn(),{...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 Da(c){return Oi(wn(),{mode:c?.mode??Te.mode,project:c?.project??Te.project,maxWidth:c?.max_width??Te.maxWidth,maxRows:c?.max_rows??Te.maxRows})}function xe(c,m,h){return mi({op:c,sessionProject:m??null,targetProject:h})}async function Oa(c){let m=S.get(c.worker_id),h=xe(fi(c.command),c.session_project,m?.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=m!=null&&await Ia(m,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(m.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function _n(c){S.delete(c),ie.delete(c),_e.delete(c),gn.delete(c)}function fo(c){let m=S.get(c.worker_id),h=xe("worker-heartbeat",c.session_project,m?.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(m==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();_e.set(c.worker_id,{line:c.last_log_line,published_at:w,source:"heartbeat"});let _=c.display===void 0?null:ji(c.display);return _!=null&&gn.set(c.worker_id,{display:_,published_at:w}),{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 La(c,m,h){let w=`exit code=${m??"null"} signal=${h??"null"}`;if(c.unit!=null&&c.unit!==""&&await $a(c)){Aa(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}_n(c.worker_id),X("worker-death",c,w,{exitCode:m,signal:h}),L()}async function $a(c){try{return await v(c)===!0}catch{return!1}}function Aa(c,m){let h=c.unit==null?null:M(c.unit);S.set(c.worker_id,{...c,...h!=null&&h>0?{pid:h}:{},warnings:[...c.warnings,m]}),ie.add(c.worker_id),L()}function mo(c,m){let h=xe("project-register",m,c.project_label);if(!h.permitted)throw new Error(h.reason);let w=o();Qe(w);let _=ai(c,{now:w,held:A.get(c.project_label)});return A.set(_.project_label,_),L(),{version:1,registration:_,reach:h,detail:`redskilled holds a registration for project ${JSON.stringify(_.project_label)} at a target of ${_.target} until ${_.renew_by}, and has read neither its selector nor its argv`}}function ho(c,m={}){let h=xe("project-renew",m.sessionProject,c);if(!h.permitted)throw new Error(h.reason);let w=o();Qe(w);let _=A.get(c);if(_==null)throw new Vn(c);let j=di(_,{now:w,...m.renewWithinMs==null?{}:{renew_within_ms:m.renewWithinMs},...m.launch==null?{}:{launch:m.launch}});return A.set(j.project_label,j),L(),{version:1,registration:j,reach:h,detail:`redskilled renewed the registration for project ${JSON.stringify(j.project_label)}, which now stands until ${j.renew_by} after renewal ${j.renewals}`+(m.launch==null?"":`, carrying launch revision ${j.launch_revision} for its next Worker`)}}function go(c,m){let h=xe("project-deregister",m,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 Ia(c,m){try{await D(c)}catch{}return _n(c.worker_id),X("worker-death",c,m),L(),!0}function yo(c){return Vs({ceiling:i,workers:[...S.values()],budget:c.budget,projectLabel:c.project_label})}function ut(c){let m=s({spec:c,admission:yo(c),clock:o,onExit:(h,w,_)=>{let j=S.get(h);if(j==null){L();return}La(j,w,_).catch(()=>{})}});return S.set(m.worker.worker_id,m.worker),X("worker-birth",m.worker,null),L(),m}function X(c,m,h,w={}){Z||b.record({event:c,worker:m,ts:o(),detail:h,...w.exitCode!==void 0?{exitCode:w.exitCode}:{},...w.signal!==void 0?{signal:w.signal}:{}}).catch(()=>{})}async function ko(){let c=[...ie].map(h=>S.get(h)).filter(h=>h!=null);if(c.length===0)return[];let{dead:m}=await Er(c,v);for(let h of m)_n(h.worker_id),X("worker-death",h,"the host no longer confirms this Worker");return m.length>0&&L(),m}async function Ro(c,m){let h=S.get(c);if(!h)return!1;try{await D(h)}catch{}return _n(c),X("worker-budget-kill",h,m),L(),!0}async function bo(){let c=[...S.values()];if(c.length===0)return[];let m;try{m=await pe(c)}catch{return[]}let h=m.rss;oo=h,nt=o(),Ta(m.cpu_seconds,nt);let{terminations:w}=hi({workers:c,rss:h}),_=[];for(let j of w)await Ro(j.worker_id,j.reason)&&_.push(j);return _}function Ta(c,m){for(let[h,w]of Object.entries(c)){if(typeof w!="number"||!Number.isFinite(w))continue;let _=S.get(h);_&&S.set(h,{..._,cpu:{cpu_seconds:w,sampled_at:m}})}}async function Na(){try{return Qr<=0?await Gr(t):await new Promise(c=>{let m=setTimeout(()=>c(pt()),Qr);m.unref(),Gr(t).then(h=>{clearTimeout(m),c(h)},()=>{clearTimeout(m),c(pt())})})}catch{return pt()}}function pt(){try{return va(t)}catch{return null}}async function wo(){if(fn(t))return rt+=1,tt=o(),ot="local-build",{act:"hold",reason:"local-build"};let c=Sl(await Na()),m=c.version;so=m,st=c.newest??null,tt=o(),lo=El({running:t,newest:st,supervised:Zr});let h=Pl({running:t,published:m,supervised:Zr});return io=h.act==="replace",rt+=1,ot=h.act==="hold"?h.reason:null,He!=="in-progress"&&(He=h.act==="replace"?"pending":"none"),h}async function vn(){let c=await wo();if(c.act!=="replace"||He==="in-progress")return c;let m=Dl(c,Xr);return He="in-progress",await b.flush().catch(()=>{}),await Sn({reason:"replaced"}),Ol(m,n,{...r==null?{}:{idleMs:r},io:Xr}),c}function Wa(){Z||qe!=null||zr<=0||(!xa&&Yr>0&&(kn=setTimeout(()=>{vn().catch(()=>{})},Yr),kn.unref()),qe=setInterval(()=>{vn().catch(()=>{})},zr),qe.unref())}function Ca(){Z||Je!=null||hn<=0||(Je=setInterval(()=>{bo().catch(()=>{})},hn),Je.unref())}function Ma(){Z||Ge!=null||B==null||B.projects.length===0||eo<=0||(ct().catch(()=>{}),Ge=setInterval(()=>{ct().catch(()=>{})},eo),Ge.unref())}function Fa(){Z||ze!=null||to<=0||(ze=setInterval(()=>{uo().catch(()=>{})},to),ze.unref())}function Ua(){Z||Ke!=null||ro<=0||(Ke=setInterval(()=>{po().catch(()=>{})},ro),Ke.unref())}function L(){Z||(ve&&clearTimeout(ve),ve=setTimeout(()=>{ko().catch(()=>{}).then(()=>_o())},r),ve.unref())}function _o(){return S.size>0?(L(),"held-by-workers"):(Qe(o()),A.size>0?(L(),"held-by-registrations"):(Ha(),"exited"))}async function Ha(){if(!fn(t)){if((await vn().catch(()=>null))?.act==="replace"||at||Z)return;if(S.size>0||A.size>0){L();return}}await Sn({reason:"idle"})}function xn(c){return Zs({reason:c,socketPath:n.socketPath,daemonVersion:t,pid:l.pid,workers:[...S.values()],projects:[...A.keys()]})}function vo(c){if(Rn!=null)return Rn;let m=c.reason??"requested",h=c.note?.trim();return Rn=b.recordDaemonStop({ts:o(),pid:l.pid,socketPath:n.socketPath,reason:m,detail:h==null||h===""?xn(m).detail:`${xn(m).detail} \u2014 ${h}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),Rn}async function Sn(c={}){if(at)return await dt;at=!0,await vo(c),Z=!0,ve&&clearTimeout(ve),Je&&clearInterval(Je),qe&&clearInterval(qe),kn&&clearTimeout(kn),Ge&&clearInterval(Ge),ze&&clearInterval(ze),Ke&&clearInterval(Ke),await b.flush().catch(()=>{}),k.close();for(let m of et)m.destroy();return await new Promise(m=>k.once("close",()=>m())),await Vl(n.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await p.release(d).catch(()=>{}),ao(),await dt}let Va=Gs(await b.read().catch(()=>[])),ft=await Er(Va,v);for(let c of ft.alive){let m=rl(c),h=m.unit==null||W(m.pid)?null:M(m.unit);S.set(m.worker_id,h!=null&&h>0?{...m,pid:h}:m),ie.add(m.worker_id)}for(let c of ft.dead)X("worker-death",c,"the Worker ended while no daemon was watching");let Ba=tl({units:await Promise.resolve(V()).catch(()=>[]),held:[...S.values()],mainPid:M,now:y});for(let c of Ba)S.set(c.worker_id,c),ie.add(c.worker_id),X("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of ft.alive){if(c.log_path==null||_e.has(c.worker_id))continue;let m=await we(c.log_path).catch(()=>null);m==null||m.trim()===""||_e.set(c.worker_id,{line:m,published_at:o(),source:"rehydrated"})}k.on("connection",c=>{et.add(c),c.once("close",()=>et.delete(c)),L(),Lh(c,async(m,h)=>{L();let w=await Ja(m);h(w),m.op==="shutdown"&&setImmediate(()=>void Sn({reason:"requested"}))})});async function Ja(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:Jn,daemon_version:t,pid:l.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:bn()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:wn()};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:ja(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:Da(c.dashboard)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:fo(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:mo(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:ho(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:go(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await Oa(c.command)};if(c.op==="worker-start"){let h=xe("worker-start",c.session_project,c.spec.project_label);if(!h.permitted)return{id:c.id,ok:!1,error:h.reason};let w=ut(c.spec);return await b.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:w.worker,admission:w.admission,warnings:w.warnings}}}if(c.op==="shutdown"){let h=xn("requested");return await vo({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:h}}let m=c;return{id:m.id??Zn(),ok:!1,error:`unsupported redskilled op: ${m.op??"unknown"}`}}catch(m){return{id:c.id??Zn(),ok:!1,error:m instanceof Error?m.message:String(m)}}}return L(),Ca(),Wa(),Ma(),Fa(),Ua(),{socketPath:n.socketPath,lease:g.lease,startedAt:y,closed:dt,startWorker:ut,admit:yo,ceiling:()=>i,killWorkerOverBudget:Ro,sampleMemoryBudgets:bo,pollRepositoryActivity:ct,pollQueueDiscovery:uo,queueDiscovery:()=>le,driveDemand:po,demand:()=>yn,sweepReattached:ko,publishWorkerHeartbeat:fo,reattached:()=>[...ie].map(c=>S.get(c)).filter(c=>c!=null),flushEvents:()=>b.flush(),trackWorker(c){S.set(c.worker_id,c),X("worker-birth",c,null),L()},releaseWorker(c){let m=S.get(c),h=S.delete(c);return ie.delete(c),_e.delete(c),gn.delete(c),m&&X("worker-death",m,"released by the daemon"),L(),h},workerCount:()=>S.size,registerProject:mo,renewProject:ho,deregisterProject:go,registrations:()=>bn().registrations??[],hostState:bn,statuslinePayload:wn,evaluateIdle:_o,observePublishedVersion:wo,checkForReplacement:vn,stopReport:xn,stop:Sn}}async function Oh(e){for(let n=0;n<2;n++){let t=xh();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 oe(e))throw new Ce(e);await Vl(e,{force:!0})}}throw new Ce(e)}async function oe(e,n=250){try{return(await In({socketPath:e,timeoutMs:n},{id:Zn(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function Lh(e,n){Os(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??Zn(),ok:!1,error:t instanceof Error?t.message:String(t)})})}te();var Nh=1e4,Me=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 Mr(e,n={}){try{return await Wh(e,n)}catch(t){throw t instanceof ue||t instanceof Me?t:new Me(e.socketPath,t)}}async function Wh(e,n){if(await Ah(Th(e.socketPath),{recursive:!0,mode:448}),await oe(e.socketPath))return"already-running";await Ch(e);let t=await Ls(e.lockPath);if(!t)return await Jl(e,n),"joined";try{if(await oe(e.socketPath))return"already-running";let r=await Uh(e,n);return await Jl(e,n,r),"spawned"}finally{await t.close(),await Ih(e.lockPath,{force:!0})}}async function Ch(e){let t=await Hn(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 ue(e.machineClaimPath,"held",t)}async function ql(e,n,t={}){await Mr(e,t);let r;try{r=await cn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:Kl()})}catch(o){throw new Me(e.socketPath,o)}if(!r.ok)throw new Error(r.error);return r.value}async function Gl(e,n={},t={}){if(!await oe(e.socketPath))return Xs(e.socketPath);let r;try{r=await cn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Kl(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new Me(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!sr(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await Mh(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 Mh(e,n){let t=Date.now()+n;for(;;){if(!await oe(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function zl(e,n={}){let t=await ql(e,{op:"host-state"},n);if(!Ii(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Ql(e,n=void 0,t={}){let r=await ql(e,{op:"statusline-string",...t.sessionProject!=null?{session_project:t.sessionProject}:{},...n==null?{}:{render:Fh(n)}},t);if(!$i(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function Fh(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 Jl(e,n,t){let r=Date.now()+(n.readyTimeoutMs??Nh);for(;;){if(await oe(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 Uh(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await Ms({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,...Re(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=$h(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}te();import{chmod as ra,mkdir as sa,readFile as ia,stat as Zh,writeFile as Xh}from"node:fs/promises";import{homedir as Hr}from"node:os";import{dirname as eg,join as Vr}from"node:path";import{join as Hh}from"node:path";var Yl=["local","tmp","host"],Vh="local",mn="plugins.dev.workspace.target";var Fr=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function Xl(e){let n=Le(e,mn),t=Kh(n??"").trim();return t===""?void 0:t}function ea(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:Vh};let t=Yl.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 Fr(`${mn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${Yl.join(", ")}) or an absolute parent directory for Workers.`)}function na(e,n){return e.kind==="preset"?e.preset==="host":Jh(Bh(e.parentDir,n),ke(n))}function Bh(e,n){return e==="~"?Zl(n):e.startsWith("~/")?Hh(n,e.slice(2)):Zl(e)}function Jh(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Zl(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function Kh(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}te();import{createHash as qh}from"node:crypto";import{hostname as Gh}from"node:os";import{join as Xn}from"node:path";var Fe="redskilled.sock",zh="REDSKILLED_SESSION";function Qh(e={}){let n=e.env??process.env,t=n[zh]?.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 Yh(e={}){return ta(e.host??Gh())}function se(e={}){let n=Qh(e),t=e.runtimeDir??Tn({key:`redskilled:${n}`,socketFileName:Fe,env:e.env,uid:e.uid}),r=Yh(e);return{sessionKey:n,sessionKeyHash:ta(n),machineIdHash:r,runtimeDir:t,socketPath:Xn(t,Fe),lockPath:Xn(t,"redskilled.spawn.lock"),leasePath:Xn(t,"redskilled.lease.toon"),eventLanePath:Xn(t,Ks),machineClaimPath:e.machineClaimPath??Un({env:e.env,machineIdHash:r,platform:e.platform})}}function ta(e){return qh("sha256").update(e).digest("hex").slice(0,12)}var Ur="run `/red-setup` (Section E3 \u2014 execution daemon), or `redskilled provision` directly";async function la(e=Hr()){let n=ke(e),t=await Jr(n);return t===void 0?(await sa(n,{recursive:!0,mode:z}),await ra(n,z),{path:n,created:!0,tightened:!1,mode:z}):t===z?{path:n,created:!1,tightened:!1,mode:t}:(await ra(n,z),{path:n,created:!1,tightened:!0,mode:z})}var aa={needed:!1,declaredBy:`no ${mn} in view`};async function Br(e={}){let n=e.homeDir??Hr(),t=e.declaredTarget?.trim();if(t)return oa(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return aa;let o=Vr(r,".red","config.yaml"),s=await ia(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=Xl(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=`${mn}: ${e} (${t})`;try{return{needed:na(ea(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function da(e){let n=[ng(e),tg(e),rg(e),og(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 ng(e){let n=e.homeNeed??aa;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:Ur}:{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:`${Ur} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function tg(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 rg(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:`${Ur} \u2014 it starts the daemon and waits for the socket`}}function og(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 ca(e={}){let n=e.env??process.env,t=e.homeDir??Hr(),r=e.paths??se({env:n}),o=ke(t),[s,i,l]=await Promise.all([Jr(o),oe(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Br({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:ce(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await ig(lg(e,n,t),n)}}var sg="redskilled.service";function ua(e){return Vr(e,"systemd","user",sg)}function pa(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 fa(e){let n=ua(e.configHome);return await Jr(n)!==void 0?{path:n,status:"already-present"}:(await sa(eg(n),{recursive:!0}),await Xh(n,e.unit,"utf8"),{path:n,status:"installed"})}async function ig(e,n){if(process.platform!=="linux")return"unsupported";try{return await ia(ua(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function lg(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??Vr(t,".config")}async function Jr(e){try{return(await Zh(e)).mode&511}catch{return}}import{readdir as ha,rm as ag,stat as dg}from"node:fs/promises";import{dirname as cg,join as Kr}from"node:path";var ug=5*6e4,pg="redskilled.";function fg(e={}){let n=e.env??process.env,t=i=>cg(Tn({key:"redskilled:reclaim-probe",socketFileName:Fe,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 ga(e={}){let n=e.roots??fg(e),t=e.graceMs??ug,r=e.now??Date.now,o=e.isPidAlive??W,s=e.answers??yg,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 mg(Kr(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 mg(e,n){let t;try{t=(await ha(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:ya(i),removed:[]}}let r=t.filter(i=>i.startsWith(pg));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await hg(Kr(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 ma(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(Fe)&&await n.answers(Kr(e,Fe)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await gg(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 ma(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function ma(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await ag(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:ya(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function hg(e){try{return await Wr(e)}catch{return}}async function gg(e,n){try{return Math.max(0,n()-(await dg(e)).mtimeMs)}catch{return}}async function yg(e){try{return(await cn({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function ya(e){return e instanceof Error?e.message:String(e)}var kg="plugins.dev.statusline",Rg="dev.statusline";function bg(e){let n=[],t=l=>{for(let a of[kg,Rg]){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 wg={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 ka(e){let{values:n,positionals:t}=ge(e,wg),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 Ra(e={}){let n=e.configText==null?{config:{},warnings:[]}:bg(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 vg=`Usage: redskilled <command> [options]
67
+ `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function gh(e,n={}){let t=n.env??process.env,r=n.exists??ch,o=n.execPath??process.execPath,s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,l=[],a=[[wl(Mn(t),i),"bundle-cache"]];s&&a.push([wl(ph(fh(s)),i),"caller-sibling-bundle"]);for(let[c,u]of a)if(l.push(c),r(c))return{command:o,args:[c],version:e,source:u,searched:l};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new Tr(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 $l(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>gh(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function Al(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??kh)(_l),{...e,exitCode:_l};let o=[...e.entry.args,...Re(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??yh(r.env))(e.entry,o),e}function yh(e){return(n,t)=>{let r=dh(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[Sl]:"1"}});r.on("error",()=>{}),r.unref()}}function kh(e){process.exitCode=e,process.exit(e)}async function Ll(e,n=process.env,t=Rh){let r=Tl(n),o=Nl(e,n);if(n[mh]==="1")return{version:o,newest:r};let s=U(e)===null?"0.0.0":e;try{let i=await Ws({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function Il(e,n=process.env,t){let r=t??Nr;return{version:Nl(e,n,r),newest:Tl(n,r)}}function Tl(e=process.env,n=Nr){return Cl(Wl(e,n))}function Nl(e,n=process.env,t=Nr){let r=U(e.trim())?.major;return r===void 0?null:Cl(Wl(n,t).filter(o=>U(o)?.major===r))}function Wl(e,n){let t=[];for(let r of n(Mn(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||U(o)===null||t.push(o)}return t}function Cl(e){let n=null;for(let t of e)(n===null||Or(t,n)>0)&&(n=t);return n}function Nr(e){try{return uh(e)}catch{return[]}}async function Rh(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 bh,readFile as wh,rename as _h,rm as Wr,writeFile as Ml}from"node:fs/promises";import{randomUUID as vh}from"node:crypto";import{dirname as xh}from"node:path";var et=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function Mr(e){let n;try{n=await wh(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=Sh(n);return Eh(t)?t:void 0}var Fl;function Ul(){return Fl??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Fl}function Bl(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??W;async function s(){return await Mr(e)}async function i(a){let c=`${e}.${a.pid}.${vh()}.tmp`;await Ml(c,Hl(a),{encoding:"utf8",mode:384}),await _h(c,e)}function l(a,c){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:c,renewed_at:c}}return{read:s,async acquire(a){await bh(xh(e),{recursive:!0,mode:448});let c=!1;for(;;){let u=r(),p=l(a,u);try{return await Ml(e,Hl(p),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:c,lease:p}}catch(h){if(h.code!=="EEXIST")throw h}let f=await s();if(!f){await Wr(e,{force:!0}),c=!0;continue}if(Cr(f,a))return{acquired:!0,reaped:c,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await Wr(e,{force:!0}),c=!0}},async renew(a){let c=await s();if(!c||!Cr(c,a))throw new et(e);let u={...c,renewed_at:r()};return await i(u),u},async release(a){let c=await s();if(!c)return!1;if(!Cr(c,a))throw new et(e);return await Wr(e,{force:!0}),!0}}}function Cr(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function Hl(e){return`${I(e,{keyedMapCollapse:!0})}
68
+ `}function Sh(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return G(n)}catch{return null}}}function Eh(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 Fr=3e5,Ih=1e4,Th=6e4,Nh=15e3,Vl=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"}},Wh="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Jl(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??Fr,o=e.clock??(()=>new Date().toISOString()),s=e.launch??ml,i=e.ceiling??Js();e.repositoryActivity!=null&&yr(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??Ul(),a=e.leaseStore??Bl(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),c=e.machineOwner??li(),u={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},p=e.machineClaimStore??Vn(n.machineClaimPath,u,{clock:o});await $h(Lh(n.socketPath),{recursive:!0,mode:448});let f=await p.claim(c);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new Ce(n.socketPath):new ue(p.claimPath,f.reason,f.claim);let h=await a.acquire(l);if(!h.acquired)throw await p.release(c).catch(()=>{}),new Ce(n.socketPath,h.lease);let k;try{k=await Ch(n.socketPath)}catch(d){throw await a.release(l).catch(()=>{}),await p.release(c).catch(()=>{}),d}let y=o(),b=e.eventLane??zs(n.eventLanePath),v=e.liveness??Xi,D=e.stopWorker??il,B=e.unitInventory??(()=>tl(n.machineClaimPath,Bn({machineIdHash:n.machineIdHash}))?rl():[]),M=e.unitMainPid??nl,pe=e.treeSampler??ki,we=e.readLogTail??hl,yn=e.sampleMs??Nh,Qr=e.publishedVersion??(d=>Ll(d)),Yr=e.replaceCheckMs??xl,Zr=e.publishedProbeTimeoutMs??Ih,Sa=e.localPublishedEvidence??(d=>Il(d,e.replacementIO?.env??process.env)),Ea=e.bornByReplacement??El(),Xr=e.replaceBootCheckMs??Th,eo=e.supervised??Ol(),no=e.replacementIO??{},V=e.repositoryActivity,to=V?.intervalMs??6e4,He=e.queueDiscovery,ro=He?.transport??V?.transport,Pa=He?.unconfiguredReason??Wh,oo=He?.intervalMs??15e3,so=e.demandMs??15e3,ja=e.demandBackoffMs??3e4,S=new Map,ie=new Set,_e=new Map,kn=new Map,L=new Map,rt=new Set,io={},ot=null,lo=null,st=null,ao=!1,it=0,lt=null,Ue="none",at=null,co=null,dt=null,le=null,Rn=null,Be=[],Ve=null,ct=!1,ve,Ke,Je,qe,bn,Ge,ze,Z=!1,ut=!1,wn=null,uo,pt=new Promise(d=>{uo=d});function Qe(d){po(d);let m=Date.parse(d),g=mi(L.values(),m);for(let w of g.lapsed)L.delete(w.project_label),Da(w,m);return g.lapsed}function Da(d,m){let g=Number.isFinite(m)?new Date(m).toISOString():d.renew_by;Be.push({project_label:d.project_label,at:g,renew_by:d.renew_by,renewals:d.renewals,sustains:d.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(d.project_label)}: it stood until ${d.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`}),Be.length>Vl&&Be.splice(0,Be.length-Vl)}function po(d){if(L.size===0)return;let m=Date.parse(d);if(!Number.isFinite(m))return;let g={};for(let _ of S.values())g[_.project_label]=(g[_.project_label]??0)+1;let w=new Map((le?.projects??[]).map(_=>[_.project_label,_]));for(let _ of[...L.values()]){let j=w.get(_.project_label),Se=pi(_,{now:d,...j==null?{}:{queue:{outcome:j.outcome,depth:j.depth}},liveWorkers:g[_.project_label]??0});Se.registration!==_&&L.set(_.project_label,Se.registration)}}function _n(){let d=o();return Qe(d),Ti({now:d,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:l.pid,startedAt:y,scope:ai(p.claimPath,u,c),workers:[...S.values()],registrations:[...L.values()],lapses:Be,queue:le,published:{version:lo,checkedAt:st,newer:ao,replacement:Ue,newest:at,majorHold:co,checks:it,holdReason:lt}})}function vn(){return Ei({hostState:_n(),ceiling:i,rss:io,sampledAt:ot,logLines:Object.fromEntries(_e),displays:Object.fromEntries(kn),now:o(),reattachedWorkerIds:[...ie],repositoryActivity:dt,...e.deaths===void 0?{}:{deaths:e.deaths}})}async function ft(){return V==null||V.projects.length===0?null:(dt=await wi({projects:V.projects,hostTokenRef:V.hostTokenRef,transport:V.transport,closedWindowMs:V.closedWindowMs,now:o()}),dt)}async function fo(){let d=o();Qe(d);let m=[...L.values()].map(g=>({project_label:g.project_label,selector:g.selector})).sort((g,w)=>g.project_label.localeCompare(w.project_label));return m.length===0?null:ro==null?(le=al(m,d,Pa),le):(le=await dl({projects:m,transport:ro,now:d,...He?.batchSize==null?{}:{batchSize:He.batchSize}}),po(o()),le)}async function mo(){let d=o();if(ct)return Rn??Zs(d);ct=!0;try{let m={};for(let A of S.values())m[A.project_label]=(m[A.project_label]??0)+1;let g={};for(let A of le?.projects??[])g[A.project_label]=A.depth;let w=Date.parse(d),_=Ys({projects:[...L.values()].map(A=>({project_label:A.project_label,selector:A.selector,argv:A.argv,workspace_path:A.workspace_path,target:A.target})),queue:g,live:m,nowMs:Number.isFinite(w)?w:0,backoffUntilMs:Ve}),j=[],Se=null;for(let A of _.births){let jn;try{jn=mt({project_label:A.project_label,workspace_path:A.workspace_path,command:A.argv[0],args:A.argv.slice(1)})}catch(yt){Se=yt instanceof Error?yt.message:String(yt),Ve=(Number.isFinite(w)?w:Date.now())+ja;break}j.push({project_label:A.project_label,worker_id:jn.worker.worker_id,pid:jn.worker.pid,warnings:jn.warnings})}return Se==null&&_.births.length>0&&(Ve=null),Rn={version:1,at:d,requested:_.births.length,granted:j,shortfall:_.births.length-j.length,refusal:Se,retry_after:Ve==null?null:new Date(Ve).toISOString(),projects:_.intents},Rn}finally{ct=!1}}function Oa(d){return Pi(vn(),{...O,mode:d?.mode??O.mode,project:d?.project??O.project,maxWorkers:d?.max_workers??O.maxWorkers,maxProjects:d?.max_projects??O.maxProjects,maxWidth:d?.max_width??O.maxWidth,verbose:d?.verbose??O.verbose})}function $a(d){return Ai(vn(),{mode:d?.mode??Te.mode,project:d?.project??Te.project,maxWidth:d?.max_width??Te.maxWidth,maxRows:d?.max_rows??Te.maxRows})}function xe(d,m,g){return gi({op:d,sessionProject:m??null,targetProject:g})}async function Aa(d){let m=S.get(d.worker_id),g=xe(hi(d.command),d.session_project,m?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(d.command!=="stop")throw new Error(`redskilled does not implement ${d.command}: it owns birth, death and limits, and ${d.command} is a work decision the project's own bundle makes on top of them`);let w=m!=null&&await Na(m,d.detail??"stopped by its own project");return{version:1,command:d.command,worker_id:d.worker_id,applied:w,reach:g,detail:w?`redskilled stopped Worker ${JSON.stringify(d.worker_id)} of project ${JSON.stringify(m.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(d.worker_id)} to stop`}}function xn(d){S.delete(d),ie.delete(d),_e.delete(d),kn.delete(d)}function ho(d){let m=S.get(d.worker_id),g=xe("worker-heartbeat",d.session_project,m?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(typeof d.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(m==null)return{version:1,worker_id:d.worker_id,accepted:!1,reach:g,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(d.worker_id)} to publish a line for`};let w=o();_e.set(d.worker_id,{line:d.last_log_line,published_at:w,source:"heartbeat"});let _=d.display===void 0?null:Oi(d.display);return _!=null&&kn.set(d.worker_id,{display:_,published_at:w}),{version:1,worker_id:d.worker_id,accepted:!0,reach:g,published_at:w,detail:`redskilled stored a line for Worker ${JSON.stringify(d.worker_id)} without reading it`}}async function La(d,m,g){let w=`exit code=${m??"null"} signal=${g??"null"}`;if(d.unit!=null&&d.unit!==""&&await Ia(d)){Ta(d,`its launch client ended (${w}) while unit ${JSON.stringify(d.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}xn(d.worker_id),X("worker-death",d,w,{exitCode:m,signal:g}),$()}async function Ia(d){try{return await v(d)===!0}catch{return!1}}function Ta(d,m){let g=d.unit==null?null:M(d.unit);S.set(d.worker_id,{...d,...g!=null&&g>0?{pid:g}:{},warnings:[...d.warnings,m]}),ie.add(d.worker_id),$()}function go(d,m){let g=xe("project-register",m,d.project_label);if(!g.permitted)throw new Error(g.reason);let w=o();Qe(w);let _=ci(d,{now:w,held:L.get(d.project_label)});return L.set(_.project_label,_),$(),{version:1,registration:_,reach:g,detail:`redskilled holds a registration for project ${JSON.stringify(_.project_label)} at a target of ${_.target} until ${_.renew_by}, and has read neither its selector nor its argv`}}function yo(d,m={}){let g=xe("project-renew",m.sessionProject,d);if(!g.permitted)throw new Error(g.reason);let w=o();Qe(w);let _=L.get(d);if(_==null)throw new Kn(d);let j=ui(_,{now:w,...m.renewWithinMs==null?{}:{renew_within_ms:m.renewWithinMs},...m.launch==null?{}:{launch:m.launch}});return L.set(j.project_label,j),$(),{version:1,registration:j,reach:g,detail:`redskilled renewed the registration for project ${JSON.stringify(j.project_label)}, which now stands until ${j.renew_by} after renewal ${j.renewals}`+(m.launch==null?"":`, carrying launch revision ${j.launch_revision} for its next Worker`)}}function ko(d,m){let g=xe("project-deregister",m,d);if(!g.permitted)throw new Error(g.reason);let w=L.delete(d);return{version:1,project_label:d,released:w,reach:g,detail:w?`redskilled released the registration for project ${JSON.stringify(d)}`:`redskilled held no registration for project ${JSON.stringify(d)}, so there was nothing to release`}}async function Na(d,m){try{await D(d)}catch{}return xn(d.worker_id),X("worker-death",d,m),$(),!0}function Ro(d){return Ks({ceiling:i,workers:[...S.values()],budget:d.budget,projectLabel:d.project_label})}function mt(d){let m=s({spec:d,admission:Ro(d),clock:o,onExit:(g,w,_)=>{let j=S.get(g);if(j==null){$();return}La(j,w,_).catch(()=>{})}});return S.set(m.worker.worker_id,m.worker),X("worker-birth",m.worker,null),$(),m}function X(d,m,g,w={}){Z||b.record({event:d,worker:m,ts:o(),detail:g,...w.exitCode!==void 0?{exitCode:w.exitCode}:{},...w.signal!==void 0?{signal:w.signal}:{}}).catch(()=>{})}async function bo(){let d=[...ie].map(g=>S.get(g)).filter(g=>g!=null);if(d.length===0)return[];let{dead:m}=await jr(d,v);for(let g of m)xn(g.worker_id),X("worker-death",g,"the host no longer confirms this Worker");return m.length>0&&$(),m}async function wo(d,m){let g=S.get(d);if(!g)return!1;try{await D(g)}catch{}return xn(d),X("worker-budget-kill",g,m),$(),!0}async function _o(){let d=[...S.values()];if(d.length===0)return[];let m;try{m=await pe(d)}catch{return[]}let g=m.rss;io=g,ot=o(),Wa(m.cpu_seconds,ot);let{terminations:w}=yi({workers:d,rss:g}),_=[];for(let j of w)await wo(j.worker_id,j.reason)&&_.push(j);return _}function Wa(d,m){for(let[g,w]of Object.entries(d)){if(typeof w!="number"||!Number.isFinite(w))continue;let _=S.get(g);_&&S.set(g,{..._,cpu:{cpu_seconds:w,sampled_at:m}})}}async function Ca(){try{return Zr<=0?await Qr(t):await new Promise(d=>{let m=setTimeout(()=>d(ht()),Zr);m.unref(),Qr(t).then(g=>{clearTimeout(m),d(g)},()=>{clearTimeout(m),d(ht())})})}catch{return ht()}}function ht(){try{return Sa(t)}catch{return null}}async function vo(){if(hn(t))return it+=1,st=o(),lt="local-build",{act:"hold",reason:"local-build"};let d=Pl(await Ca()),m=d.version;lo=m,at=d.newest??null,st=o(),co=jl({running:t,newest:at,supervised:eo});let g=Dl({running:t,published:m,supervised:eo});return ao=g.act==="replace",it+=1,lt=g.act==="hold"?g.reason:null,Ue!=="in-progress"&&(Ue=g.act==="replace"?"pending":"none"),g}async function Sn(){let d=await vo();if(d.act!=="replace"||Ue==="in-progress")return d;let m=$l(d,no);return Ue="in-progress",await b.flush().catch(()=>{}),await Pn({reason:"replaced"}),Al(m,n,{...r==null?{}:{idleMs:r},io:no}),d}function Ma(){Z||qe!=null||Yr<=0||(!Ea&&Xr>0&&(bn=setTimeout(()=>{Sn().catch(()=>{})},Xr),bn.unref()),qe=setInterval(()=>{Sn().catch(()=>{})},Yr),qe.unref())}function Fa(){Z||Ke!=null||yn<=0||(Ke=setInterval(()=>{_o().catch(()=>{})},yn),Ke.unref())}function Ha(){Z||Ge!=null||V==null||V.projects.length===0||to<=0||(ft().catch(()=>{}),Ge=setInterval(()=>{ft().catch(()=>{})},to),Ge.unref())}function Ua(){Z||ze!=null||oo<=0||(ze=setInterval(()=>{fo().catch(()=>{})},oo),ze.unref())}function Ba(){Z||Je!=null||so<=0||(Je=setInterval(()=>{mo().catch(()=>{})},so),Je.unref())}function $(){Z||(ve&&clearTimeout(ve),ve=setTimeout(()=>{bo().catch(()=>{}).then(()=>xo())},r),ve.unref())}function xo(){return S.size>0?($(),"held-by-workers"):(Qe(o()),L.size>0?($(),"held-by-registrations"):(Va(),"exited"))}async function Va(){if(!hn(t)){if((await Sn().catch(()=>null))?.act==="replace"||ut||Z)return;if(S.size>0||L.size>0){$();return}}await Pn({reason:"idle"})}function En(d){return ei({reason:d,socketPath:n.socketPath,daemonVersion:t,pid:l.pid,workers:[...S.values()],projects:[...L.keys()]})}function So(d){if(wn!=null)return wn;let m=d.reason??"requested",g=d.note?.trim();return wn=b.recordDaemonStop({ts:o(),pid:l.pid,socketPath:n.socketPath,reason:m,detail:g==null||g===""?En(m).detail:`${En(m).detail} \u2014 ${g}`,...d.signal==null?{}:{signal:d.signal}}).catch(()=>{}),wn}async function Pn(d={}){if(ut)return await pt;ut=!0,await So(d),Z=!0,ve&&clearTimeout(ve),Ke&&clearInterval(Ke),qe&&clearInterval(qe),bn&&clearTimeout(bn),Ge&&clearInterval(Ge),ze&&clearInterval(ze),Je&&clearInterval(Je),await b.flush().catch(()=>{}),k.close();for(let m of rt)m.destroy();return await new Promise(m=>k.once("close",()=>m())),await Kl(n.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await p.release(c).catch(()=>{}),uo(),await pt}let Ka=Qs(await b.read().catch(()=>[])),gt=await jr(Ka,v);for(let d of gt.alive){let m=sl(d),g=m.unit==null||W(m.pid)?null:M(m.unit);S.set(m.worker_id,g!=null&&g>0?{...m,pid:g}:m),ie.add(m.worker_id)}for(let d of gt.dead)X("worker-death",d,"the Worker ended while no daemon was watching");let Ja=ol({units:await Promise.resolve(B()).catch(()=>[]),held:[...S.values()],mainPid:M,now:y});for(let d of Ja)S.set(d.worker_id,d),ie.add(d.worker_id),X("worker-birth",d,"adopted from an active unit with no birth on this lane");for(let d of gt.alive){if(d.log_path==null||_e.has(d.worker_id))continue;let m=await we(d.log_path).catch(()=>null);m==null||m.trim()===""||_e.set(d.worker_id,{line:m,published_at:o(),source:"rehydrated"})}k.on("connection",d=>{rt.add(d),d.once("close",()=>rt.delete(d)),$(),Mh(d,async(m,g)=>{$();let w=await qa(m);g(w),m.op==="shutdown"&&setImmediate(()=>void Pn({reason:"requested"}))})});async function qa(d){try{if(d.op==="ping")return{id:d.id,ok:!0,value:{pong:!0,protocol_version:Gn,daemon_version:t,pid:l.pid}};if(d.op==="host-state")return{id:d.id,ok:!0,value:_n()};if(d.op==="statusline-payload")return{id:d.id,ok:!0,value:vn()};if(d.op==="statusline-string")return{id:d.id,ok:!0,value:Oa(d.render)};if(d.op==="statusline-dashboard")return{id:d.id,ok:!0,value:$a(d.dashboard)};if(d.op==="worker-heartbeat")return{id:d.id,ok:!0,value:ho(d.heartbeat)};if(d.op==="project-register")return{id:d.id,ok:!0,value:go(d.registration,d.session_project)};if(d.op==="project-renew")return{id:d.id,ok:!0,value:yo(d.project_label,{...d.session_project==null?{}:{sessionProject:d.session_project},...d.renew_within_ms==null?{}:{renewWithinMs:d.renew_within_ms},...d.launch==null?{}:{launch:d.launch}})};if(d.op==="project-deregister")return{id:d.id,ok:!0,value:ko(d.project_label,d.session_project)};if(d.op==="worker-command")return{id:d.id,ok:!0,value:await Aa(d.command)};if(d.op==="worker-start"){let g=xe("worker-start",d.session_project,d.spec.project_label);if(!g.permitted)return{id:d.id,ok:!1,error:g.reason};let w=mt(d.spec);return await b.flush().catch(()=>{}),{id:d.id,ok:!0,value:{worker:w.worker,admission:w.admission,warnings:w.warnings}}}if(d.op==="shutdown"){let g=En("requested");return await So({reason:"requested",...d.detail==null?{}:{note:d.detail}}),{id:d.id,ok:!0,value:g}}let m=d;return{id:m.id??nt(),ok:!1,error:`unsupported redskilled op: ${m.op??"unknown"}`}}catch(m){return{id:d.id??nt(),ok:!1,error:m instanceof Error?m.message:String(m)}}}return $(),Fa(),Ma(),Ha(),Ua(),Ba(),{socketPath:n.socketPath,lease:h.lease,startedAt:y,closed:pt,startWorker:mt,admit:Ro,ceiling:()=>i,killWorkerOverBudget:wo,sampleMemoryBudgets:_o,pollRepositoryActivity:ft,pollQueueDiscovery:fo,queueDiscovery:()=>le,driveDemand:mo,demand:()=>Rn,sweepReattached:bo,publishWorkerHeartbeat:ho,reattached:()=>[...ie].map(d=>S.get(d)).filter(d=>d!=null),flushEvents:()=>b.flush(),trackWorker(d){S.set(d.worker_id,d),X("worker-birth",d,null),$()},releaseWorker(d){let m=S.get(d),g=S.delete(d);return ie.delete(d),_e.delete(d),kn.delete(d),m&&X("worker-death",m,"released by the daemon"),$(),g},workerCount:()=>S.size,registerProject:go,renewProject:yo,deregisterProject:ko,registrations:()=>_n().registrations??[],hostState:_n,statuslinePayload:vn,evaluateIdle:xo,observePublishedVersion:vo,checkForReplacement:Sn,stopReport:En,stop:Pn}}async function Ch(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 oe(e))throw new Ce(e);await Kl(e,{force:!0})}}throw new Ce(e)}async function oe(e,n=250){try{return(await Nn({socketPath:e,timeoutMs:n},{id:nt(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function Mh(e,n){As(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??nt(),ok:!1,error:t instanceof Error?t.message:String(t)})})}te();var Vh=1e4,Me=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 Hr(e,n={}){try{return await Kh(e,n)}catch(t){throw t instanceof ue||t instanceof Me?t:new Me(e.socketPath,t)}}async function Kh(e,n){if(await Hh(Bh(e.socketPath),{recursive:!0,mode:448}),await oe(e.socketPath))return"already-running";await Jh(e);let t=await Ls(e.lockPath);if(!t)return await ql(e,n),"joined";try{if(await oe(e.socketPath))return"already-running";let r=await zh(e,n);return await ql(e,n,r),"spawned"}finally{await t.close(),await Uh(e.lockPath,{force:!0})}}async function Jh(e){let t=await Vn(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 ue(e.machineClaimPath,"held",t)}async function zl(e,n,t={}){await Hr(e,t);let r;try{r=await pn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:Gl()})}catch(o){throw new Me(e.socketPath,o)}if(!r.ok)throw new Error(r.error);return r.value}async function Ql(e,n={},t={}){if(!await oe(e.socketPath))return ni(e.socketPath);let r;try{r=await pn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Gl(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new Me(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!ar(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await qh(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 qh(e,n){let t=Date.now()+n;for(;;){if(!await oe(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function Yl(e,n={}){let t=await zl(e,{op:"host-state"},n);if(!Ni(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Zl(e,n=void 0,t={}){let r=await zl(e,{op:"statusline-string",...t.sessionProject!=null?{session_project:t.sessionProject}:{},...n==null?{}:{render:Gh(n)}},t);if(!Ii(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function Gh(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 ql(e,n,t){let r=Date.now()+(n.readyTimeoutMs??Vh);for(;;){if(await oe(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 zh(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await Hs({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,...Re(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=Fh(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}te();import{chmod as sa,mkdir as la,readFile as aa,stat as ig,writeFile as lg}from"node:fs/promises";import{homedir as Vr}from"node:os";import{dirname as ag,join as Kr}from"node:path";import{join as Qh}from"node:path";var Xl=["local","tmp","host"],Yh="local",gn="plugins.dev.workspace.target";var Ur=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function na(e){let n=$e(e,gn),t=eg(n??"").trim();return t===""?void 0:t}function ta(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:Yh};let t=Xl.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 Ur(`${gn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${Xl.join(", ")}) or an absolute parent directory for Workers.`)}function ra(e,n){return e.kind==="preset"?e.preset==="host":Xh(Zh(e.parentDir,n),ke(n))}function Zh(e,n){return e==="~"?ea(n):e.startsWith("~/")?Qh(n,e.slice(2)):ea(e)}function Xh(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function ea(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function eg(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}te();import{createHash as ng}from"node:crypto";import{hostname as tg}from"node:os";import{join as tt}from"node:path";var Fe="redskilled.sock",rg="REDSKILLED_SESSION";function og(e={}){let n=e.env??process.env,t=n[rg]?.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 sg(e={}){return oa(e.host??tg())}function se(e={}){let n=og(e),t=e.runtimeDir??Wn({key:`redskilled:${n}`,socketFileName:Fe,env:e.env,uid:e.uid}),r=sg(e);return{sessionKey:n,sessionKeyHash:oa(n),machineIdHash:r,runtimeDir:t,socketPath:tt(t,Fe),lockPath:tt(t,"redskilled.spawn.lock"),leasePath:tt(t,"redskilled.lease.toon"),eventLanePath:tt(t,Gs),machineClaimPath:e.machineClaimPath??Bn({env:e.env,machineIdHash:r,platform:e.platform})}}function oa(e){return ng("sha256").update(e).digest("hex").slice(0,12)}var Br="run `/red-setup` (Section E3 \u2014 execution daemon), or `redskilled provision` directly";async function da(e=Vr()){let n=ke(e),t=await qr(n);return t===void 0?(await la(n,{recursive:!0,mode:z}),await sa(n,z),{path:n,created:!0,tightened:!1,mode:z}):t===z?{path:n,created:!1,tightened:!1,mode:t}:(await sa(n,z),{path:n,created:!1,tightened:!0,mode:z})}var ca={needed:!1,declaredBy:`no ${gn} in view`};async function Jr(e={}){let n=e.homeDir??Vr(),t=e.declaredTarget?.trim();if(t)return ia(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return ca;let o=Kr(r,".red","config.yaml"),s=await aa(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=na(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:ia(i,n,o)}function ia(e,n,t){let r=`${gn}: ${e} (${t})`;try{return{needed:ra(ta(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function ua(e){let n=[dg(e),cg(e),ug(e),pg(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 dg(e){let n=e.homeNeed??ca;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:Br}:{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:`${Br} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function cg(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 ug(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:`${Br} \u2014 it starts the daemon and waits for the socket`}}function pg(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 pa(e={}){let n=e.env??process.env,t=e.homeDir??Vr(),r=e.paths??se({env:n}),o=ke(t),[s,i,l]=await Promise.all([qr(o),oe(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Jr({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:ce(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await mg(hg(e,n,t),n)}}var fg="redskilled.service";function fa(e){return Kr(e,"systemd","user",fg)}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 ha(e){let n=fa(e.configHome);return await qr(n)!==void 0?{path:n,status:"already-present"}:(await la(ag(n),{recursive:!0}),await lg(n,e.unit,"utf8"),{path:n,status:"installed"})}async function mg(e,n){if(process.platform!=="linux")return"unsupported";try{return await aa(fa(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function hg(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??Kr(t,".config")}async function qr(e){try{return(await ig(e)).mode&511}catch{return}}import{readdir as ya,rm as gg,stat as yg}from"node:fs/promises";import{dirname as kg,join as Gr}from"node:path";var Rg=5*6e4,bg="redskilled.";function wg(e={}){let n=e.env??process.env,t=i=>kg(Wn({key:"redskilled:reclaim-probe",socketFileName:Fe,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 ka(e={}){let n=e.roots??wg(e),t=e.graceMs??Rg,r=e.now??Date.now,o=e.isPidAlive??W,s=e.answers??Sg,i=e.dryRun===!0,l=[];for(let a of n){let c;try{c=(await ya(a,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name)}catch{continue}for(let u of c.sort())l.push(await _g(Gr(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 _g(e,n){let t;try{t=(await ya(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:Ra(i),removed:[]}}let r=t.filter(i=>i.startsWith(bg));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await vg(Gr(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 ga(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(Fe)&&await n.answers(Gr(e,Fe)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await xg(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 ga(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function ga(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await gg(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:Ra(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function vg(e){try{return await Mr(e)}catch{return}}async function xg(e,n){try{return Math.max(0,n()-(await yg(e)).mtimeMs)}catch{return}}async function Sg(e){try{return(await pn({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function Ra(e){return e instanceof Error?e.message:String(e)}var Eg="plugins.dev.statusline",Pg="dev.statusline";function jg(e){let n=[],t=l=>{for(let a of[Eg,Pg]){let c=`${a}.${l}`,u=$e(e,c)?.trim();if(u!=null&&u!=="")return{key:c,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 c=Number(a.value);Number.isInteger(c)&&c>=0?l.assign(c):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 Dg={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}=ge(e,Dg),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 c=Number(a);Number.isInteger(c)&&c>=0?l.assign(c):r.push({key:`--${l.flag}`,value:a,reason:"expected a whole number of zero or more"})}return{flags:o,warnings:r}}function wa(e={}){let n=e.configText==null?{config:{},warnings:[]}:jg(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 $g=`Usage: redskilled <command> [options]
70
70
 
71
71
  Commands:
72
72
  host-state (default) print the host's state as JSON
@@ -78,7 +78,7 @@ Commands:
78
78
 
79
79
  Run \`redskilled <command> --help\` for a command's own usage.
80
80
  \`--version\` (\`-v\`) prints the build stamp; both answer offline.
81
- `,xg={serve:`Usage: redskilled serve [options]
81
+ `,Ag={serve:`Usage: redskilled serve [options]
82
82
 
83
83
  Runs the daemon in this process. Every path is a flag and none is derived
84
84
  (ADR 0130 rule 3); what is absent falls back to the session derivation.
@@ -142,19 +142,19 @@ Reports every session runtime dir it looked at and why it kept or removed it.
142
142
 
143
143
  --dry-run the same report with nothing removed
144
144
  --grace-ms <n> how long a dir must be idle before it is reclaimed
145
- `};function Sg(e){return e==="--help"||e==="-h"||e==="help"}var Eg={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)}},wa="REDSKILLED_HOST_TOKEN";function _a(){try{let n=_g("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function Pg(e=process.env,n=_a){let t=(e[wa]??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 jg(e,n=process.env,t=_a){let r=e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},o=Pg(n,t);if(o==null)return{...r,unconfiguredReason:`no credential names a tracker for this host: ${wa}, 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 s=e["queue-endpoint"]??n.GITHUB_GRAPHQL_URL;return{...r,transport:wi({token:o.token,...s?{endpoint:s}:{}})}}async function Dg(e){if(e[0]==="--version"||e[0]==="-v"){let o=jt("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
146
- `:`${Jo(o)}
147
- `),0}if(Sg(e[0]))return process.stdout.write(vg),0;let{command:n,args:t}=zo(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(xg[n]),0;if(n==="serve"){let{values:o}=ge(t,Eg),s=jg(o),i=ba(ke(qr()),"state");process.stderr.write(`${fs(ps({stateRoot:i}))}
148
- `);let l=ls({lanePath:tn(i),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),a=await Bl({paths:Fg(o),idleMs:o["idle-ms"]??Cr,daemonVersion:o["daemon-version"]??jt("redskilled").version,queueDiscovery:s,...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let d of["SIGTERM","SIGINT"])process.once(d,()=>void a.stop({reason:"signal",signal:d}).catch(()=>{}));return await a.closed,l.phase("closed"),0}if(n==="stop")return await Lg(t);if(n==="statusline")return await Ag(t);if(n==="unit")return await $g(t);if(n==="provision")return await Tg(t);if(n==="reclaim")return await Wg(t);let r=await zl(se());return process.stdout.write(`${JSON.stringify(r,null,2)}
149
- `),0}var Og={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function Lg(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=ge(e,Og),o=await Gl(n.paths??se(),{...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 $g(e,n={}){let t=n.write??(s=>process.stdout.write(s)),r=n.paths??se(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(kl(n.unitIO??{}),null,2)}
151
- `),0;if(o==="install"){let s=await gl(ml(r),n.unitIO??{});return t(`${JSON.stringify(s,null,2)}
152
- `),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await yl(n.unitIO??{}),null,2)}
153
- `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function Ag(e,n={}){let t=n.write??(a=>process.stdout.write(a)),r=n.warn??(a=>process.stderr.write(a)),o=ka(e),s=Mg(n.cwd??process.cwd()),i=Ra({...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 Ql(n.paths??se(),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=Ei({options:i.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${l.lines.join(`
145
+ `};function Lg(e){return e==="--help"||e==="-h"||e==="help"}var Ig={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)}},va="REDSKILLED_HOST_TOKEN";function xa(){try{let n=Og("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function Tg(e=process.env,n=xa){let t=(e[va]??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 Ng(e,n=process.env,t=xa){let r=e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},o=Tg(n,t);if(o==null)return{...r,unconfiguredReason:`no credential names a tracker for this host: ${va}, 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 s=e["queue-endpoint"]??n.GITHUB_GRAPHQL_URL;return{...r,transport:vi({token:o.token,...s?{endpoint:s}:{}})}}async function Wg(e){if(e[0]==="--version"||e[0]==="-v"){let o=$t("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
146
+ `:`${qo(o)}
147
+ `),0}if(Lg(e[0]))return process.stdout.write($g),0;let{command:n,args:t}=Yo(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(Ag[n]),0;if(n==="serve"){let{values:o}=ge(t,Ig),s=Ng(o),i=_a(ke(zr()),"state"),l=ms({stateRoot:i});process.stderr.write(`${hs(l)}
148
+ `);let a=ds({lanePath:tn(i),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),c=await Jl({paths:Gg(o),idleMs:o["idle-ms"]??Fr,daemonVersion:o["daemon-version"]??$t("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 c.stop({reason:"signal",signal:u}).catch(()=>{}));return await c.closed,a.phase("closed"),0}if(n==="stop")return await Mg(t);if(n==="statusline")return await Hg(t);if(n==="unit")return await Fg(t);if(n==="provision")return await Bg(t);if(n==="reclaim")return await Kg(t);let r=await Yl(se());return process.stdout.write(`${JSON.stringify(r,null,2)}
149
+ `),0}var Cg={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function Mg(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=ge(e,Cg),o=await Ql(n.paths??se(),{...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 Fg(e,n={}){let t=n.write??(s=>process.stdout.write(s)),r=n.paths??se(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(bl(n.unitIO??{}),null,2)}
151
+ `),0;if(o==="install"){let s=await kl(gl(r),n.unitIO??{});return t(`${JSON.stringify(s,null,2)}
152
+ `),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await Rl(n.unitIO??{}),null,2)}
153
+ `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function Hg(e,n={}){let t=n.write??(a=>process.stdout.write(a)),r=n.warn??(a=>process.stderr.write(a)),o=ba(e),s=qg(n.cwd??process.cwd()),i=wa({...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 Zl(n.paths??se(),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=ji({options:i.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${l.lines.join(`
156
156
  `)}
157
- `),0}var Ig={"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 Tg(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=ge(e,Ig),o=n.paths??se(),s=n.homeDir??qr(),i=await Br({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),l=r.check||!i.needed?void 0:await la(s),a;if(!r.check&&!r["no-start"])try{await Mr(o,n.client??{})}catch(f){a=f instanceof Error?f.message:String(f)}let d=await ca({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 fa({configHome:n.configHome??Cg(),unit:pa({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,p=da(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(f=>({check:f.check,verdict:f.verdict,evidence:f.evidence})),fixes:p.findings.map(f=>({check:f.check,fix:f.fix}))})}
158
- `),p.verdict==="ok"?0:1}var Ng={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function Wg(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=ge(e,Ng),o=await ga({...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 Cg(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:ba(qr(),".config")}function Mg(e){let n=Bt(e);return n.configText==null?{label:null}:{configText:n.configText,label:ws(e)}}function Fg(e){let n=se();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 Ug=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;Ug&&Dg(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{wa as REDSKILLED_HOST_TOKEN_ENV,vg as REDSKILLED_USAGE,Pg as resolveRedskilledHostToken,jg as resolveServeQueueDiscovery,Tg as runProvision,Wg as runReclaim,Dg as runRedskilledCli,Ag as runStatusline,Lg as runStop,$g as runUnit};
157
+ `),0}var Ug={"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 Bg(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=ge(e,Ug),o=n.paths??se(),s=n.homeDir??zr(),i=await Jr({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),l=r.check||!i.needed?void 0:await da(s),a;if(!r.check&&!r["no-start"])try{await Hr(o,n.client??{})}catch(f){a=f instanceof Error?f.message:String(f)}let c=await pa({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(c.entry)?await ha({configHome:n.configHome??Jg(),unit:ma({command:[c.entry.command,...c.entry.args].join(" "),socketPath:o.socketPath})}):void 0,p=ua(c);return t(`${I({verdict:p.verdict,home:{path:l?.path??c.homePath,created:l?.created??!1,tightened:l?.tightened??!1,needed:i.needed,needed_by:i.declaredBy},socket:c.socketPath,...a==null?{}:{start_error:a},...u==null?{}:{unit:{path:u.path,status:u.status}},checks:p.rows.map(f=>({check:f.check,verdict:f.verdict,evidence:f.evidence})),fixes:p.findings.map(f=>({check:f.check,fix:f.fix}))})}
158
+ `),p.verdict==="ok"?0:1}var Vg={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function Kg(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=ge(e,Vg),o=await ka({...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 Jg(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:_a(zr(),".config")}function qg(e){let n=qt(e);return n.configText==null?{label:null}:{configText:n.configText,label:vs(e)}}function Gg(e){let n=se();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 zg=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;zg&&Wg(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{va as REDSKILLED_HOST_TOKEN_ENV,$g as REDSKILLED_USAGE,Tg as resolveRedskilledHostToken,Ng as resolveServeQueueDiscovery,Bg as runProvision,Kg as runReclaim,Wg as runRedskilledCli,Hg as runStatusline,Mg as runStop,Fg as runUnit};