@reddb-io/red-skills 3.3.8 → 3.3.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,72 +1,81 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var kd=Object.defineProperty;var Rd=(e,n)=>()=>(e&&(n=e(e=0)),n);var bd=(e,n)=>{for(var t in n)kd(e,t,{get:n[t],enumerable:!0})};var Zs={};bd(Zs,{REDSKILLED_BIN_ENV:()=>pr,REDSKILLED_BUNDLE_ASSET:()=>Q,REDSKILLED_ENTRY_UNRESOLVED:()=>ln,RedskilledDaemonEntryError:()=>an,isRedskilledEntryPath:()=>fr,isResolvedRedskilledEntry:()=>Y,redskilledBundleCacheRoot:()=>Vn,redskilledServeArgv:()=>_e,requireRedskilledEntry:()=>Bn,resolveRedskilledEntry:()=>ue});import{existsSync as Ju,readdirSync as qu}from"node:fs";import{homedir as Gu}from"node:os";import{basename as ur,dirname as cr,join as M,resolve as Hn}from"node:path";function Y(e){return"command"in e}function _e(e,n={}){let t=["serve","--socket",e.socketPath,"--lease",e.leasePath,"--events",e.eventLanePath,"--session-key-hash",e.sessionKeyHash,"--machine-id-hash",e.machineIdHash,"--machine-claim",e.machineClaimPath];return n.idleMs!=null&&t.push("--idle-ms",String(n.idleMs)),n.daemonVersion!=null&&t.push("--daemon-version",n.daemonVersion),t}function Vn(e=process.env){return Ys(e)}function ue(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??Ju,o=n.execPath??process.execPath,s=n.execArgv??[],i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,l=(u,p)=>({command:o,args:[...s,u],source:p,entry:u}),a=t[pr];if(a)return{command:a,args:[],source:"env-redskilled-bin",entry:a};if(i&&fr(i))return l(Hn(i),"caller-entry");let c=[];for(let[u,p]of Zu(i,n.rootDir,t,n.listDir??np))if(c.push(u),r(u))return l(u,p);return{diagnostic:ln,searched:c,...i?{callerEntry:Hn(i)}:{}}}function Bn(e={},n={}){let t=ue(e,n);if(Y(t))return t;throw new an(t)}function fr(e){let n=ur(e);return n===Q||mr.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:Yu(Hn(e))}function Yu(e){let n=cr(e);for(let t=0;t<4;t++){if(ur(n)==="redskilled")return!0;let r=cr(n);if(r===n)return!1;n=r}return!1}function*Zu(e,n,t,r){if(e){let s=cr(Hn(e));yield[M(s,Q),"caller-sibling-bundle"];let i=zu.exec(ur(e));i&&(yield[M(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[M(s,"..","dist",Q),"caller-sibling-bundle"]}for(let s of Qu){let i=t[s];i&&(yield[M(i,"dist",Q),"plugin-root-bundle"],yield[M(i,"..","..","dist",Q),"plugin-root-bundle"])}n&&(yield[M(n,"dist",Q),"repo-bundle"],yield[M(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[M(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=Ys(t);yield[M(o,Q),"bundle-cache"];for(let s of Xu(o,r))yield[M(o,s),"bundle-cache"]}function Ys(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||M(e.HOME||Gu(),".cache");return M(n,"red-skills","bundles")}function Xu(e,n){return n(e).filter(t=>mr.test(t)).sort((t,r)=>ep(Qs(r),Qs(t)))}function Qs(e){return mr.exec(e)?.[1]??""}function ep(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 np(e){try{return qu(e)}catch{return[]}}var Q,ln,pr,an,zu,mr,Qu,re=Rd(()=>{"use strict";Q="redskilled.bundle.min.mjs",ln="redskilled-daemon-entry-unresolved",pr="REDSKILLED_BIN";an=class extends Error{code=ln;searched;callerEntry;constructor(n){super(`${ln}: no published ${Q} found to spawn the redskilled daemon from${n.callerEntry?` (caller entry: ${n.callerEntry}, which is NOT used as a fallback)`:""}
3
+ var Uc=Object.defineProperty;var Bc=(e,n)=>()=>(e&&(n=e(e=0)),n);var Vc=(e,n)=>{for(var t in n)Uc(e,t,{get:n[t],enumerable:!0})};var ol={};Vc(ol,{REDSKILLED_BIN_ENV:()=>qr,REDSKILLED_BUNDLE_ASSET:()=>le,REDSKILLED_ENTRY_UNRESOLVED:()=>xn,RedskilledDaemonEntryError:()=>Sn,isRedskilledEntryPath:()=>Gr,isResolvedRedskilledEntry:()=>ae,redskilledBundleCacheRoot:()=>mt,redskilledServeArgv:()=>Oe,requireRedskilledEntry:()=>ht,resolveRedskilledEntry:()=>Re});import{existsSync as Uf,readdirSync as Bf}from"node:fs";import{homedir as Vf}from"node:os";import{basename as Kr,dirname as Vr,join as K,resolve as ft}from"node:path";function ae(e){return"command"in e}function Oe(e,n={}){let t=["serve","--socket",e.socketPath,"--lease",e.leasePath,"--events",e.eventLanePath,"--session-key-hash",e.sessionKeyHash,"--machine-id-hash",e.machineIdHash,"--machine-claim",e.machineClaimPath];return n.idleMs!=null&&t.push("--idle-ms",String(n.idleMs)),n.daemonVersion!=null&&t.push("--daemon-version",n.daemonVersion),t}function mt(e=process.env){return rl(e)}function Re(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??Uf,o=n.execPath??process.execPath,i=n.execArgv??[],s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,a=(p,u)=>({command:o,args:[...i,p],source:u,entry:p}),l=t[qr];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(s&&Gr(s))return a(ft(s),"caller-entry");let d=[];for(let[p,u]of Gf(s,n.rootDir,t,n.listDir??Yf))if(d.push(p),r(p))return a(p,u);return{diagnostic:xn,searched:d,...s?{callerEntry:ft(s)}:{}}}function ht(e={},n={}){let t=Re(e,n);if(ae(t))return t;throw new Sn(t)}function Gr(e){let n=Kr(e);return n===le||Jr.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:Jf(ft(e))}function Jf(e){let n=Vr(e);for(let t=0;t<4;t++){if(Kr(n)==="redskilled")return!0;let r=Vr(n);if(r===n)return!1;n=r}return!1}function*Gf(e,n,t,r){if(e){let i=Vr(ft(e));yield[K(i,le),"caller-sibling-bundle"];let s=Kf.exec(Kr(e));s&&(yield[K(i,`redskilled-${s[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[K(i,"..","dist",le),"caller-sibling-bundle"]}for(let i of qf){let s=t[i];s&&(yield[K(s,"dist",le),"plugin-root-bundle"],yield[K(s,"..","..","dist",le),"plugin-root-bundle"])}n&&(yield[K(n,"dist",le),"repo-bundle"],yield[K(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[K(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=rl(t);yield[K(o,le),"bundle-cache"];for(let i of Qf(o,r))yield[K(o,i),"bundle-cache"]}function rl(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||K(e.HOME||Vf(),".cache");return K(n,"red-skills","bundles")}function Qf(e,n){return n(e).filter(t=>Jr.test(t)).sort((t,r)=>zf(tl(r),tl(t)))}function tl(e){return Jr.exec(e)?.[1]??""}function zf(e,n){let t=i=>i.split(".").map(s=>Number.parseInt(s,10)),[r,o]=[t(e),t(n)];for(let i=0;i<Math.max(r.length,o.length);i++){let[s,a]=[r[i],o[i]];if(Number.isNaN(s)||s===void 0)return Number.isNaN(a)||a===void 0?e.localeCompare(n):-1;if(Number.isNaN(a)||a===void 0)return 1;if(s!==a)return s-a}return 0}function Yf(e){try{return Bf(e)}catch{return[]}}var le,xn,qr,Sn,Kf,Jr,qf,pe=Bc(()=>{"use strict";le="redskilled.bundle.min.mjs",xn="redskilled-daemon-entry-unresolved",qr="REDSKILLED_BIN";Sn=class extends Error{code=xn;searched;callerEntry;constructor(n){super(`${xn}: no published ${le} found to spawn the redskilled daemon from${n.callerEntry?` (caller entry: ${n.callerEntry}, which is NOT used as a fallback)`:""}
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)}};zu=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,mr=/^redskilled-(.+)\.bundle\.min\.mjs$/,Qu=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as ny}from"node:child_process";import{homedir as lo}from"node:os";import{join as Ka}from"node:path";var Ye=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},ge=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonlError",this.line=n,this.reason=t}};function R(e,n){return new Ye(e,n)}function S(e,n){return new ge(e,n)}function Pe(e){return e instanceof ge?e:e instanceof Ye?new ge(e.line,e.reason):new ge(0,String(e&&e.message?e.message:e))}var j=",";function An(e){let n=e.split(`
7
- `);return n.length>0&&n[n.length-1]===""&&n.pop(),n.map(t=>t.endsWith("\r")?t.slice(0,-1):t)}function K(e){return R(e,"invalid quoted string")}function J(e,n){if(e==="")return"";if(e.startsWith('"'))return Co(e,n);if(e.includes('"'))throw K(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:_d(e)?Number(e):e}function ne(e,n){let t=e.trim();if(t.startsWith('"'))return[Co(t,n),!0];if(t.includes('"')||/\s/.test(t))throw R(n,"expected non-empty field name");return[t,!1]}function Co(e,n){if(e[0]!=='"')throw K(n);let t="",r=1;for(;r<e.length;){let o=e[r];if(r+=1,o==='"'){if(e.slice(r).trim()==="")return t;throw K(n)}if(o==="\\"){let s=e[r];switch(r+=1,s){case'"':t+='"';break;case"\\":t+="\\";break;case"n":t+=`
8
- `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let i=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(i))throw K(n);let l=Number.parseInt(i,16);if(l>=55296&&l<=57343)throw K(n);t+=String.fromCharCode(l),r+=4;break}default:throw K(n)}continue}if(o<" "&&o!==" ")throw K(n);t+=o}throw K(n)}function he(e,n,t){if(e==="")return[];let r=[],o=0,s=!1,i=!1;for(let l=0;l<e.length;l+=1){let a=e[l];if(i){i=!1;continue}a==="\\"&&s?i=!0:a==='"'?s=!s:a===n&&!s&&(r.push(e.slice(o,l).trim()),o=l+1)}if(s||i)throw K(t);return r.push(e.slice(o).trim()),r}function T(e,n,t){let r=!1,o=!1;for(let s=0;s<e.length;s+=1){let i=e[s];if(o){o=!1;continue}if(i==="\\"&&r)o=!0;else if(i==='"')r=!r;else if(i===n&&!r)return s}if(r||o)throw K(t);return-1}function _d(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function wd(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function vd(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 vd(e);if(typeof e=="string")return xd(e,n);throw R(0,"not a primitive")}function Sd(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function F(e){return Sd(e)?e:Fo(e)}function xd(e,n){return Ed(e,n)?Fo(e):e}function Ed(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||wd(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}function Fo(e){let n='"';for(let t of e)switch(t){case'"':n+='\\"';break;case"\\":n+="\\\\";break;case`
9
- `:n+="\\n";break;case"\r":n+="\\r";break;case" ":n+="\\t";break;default:t<" "?n+=`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`:n+=t}return`${n}"`}function je(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}var Lt=2;function Pd(e={}){return{indent:Math.max(1,e.indent??Lt),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function jd(e,n){let t=[],r=!1;return An(e).forEach((o,s)=>{let i=s+1;if(o.trim()===""){r=!0;return}let l=o.length-o.replace(/^ +/,"").length;if(o[l]===" ")throw R(i,"invalid indentation");if(n.strict&&l%n.indent!==0)throw R(i,"invalid indentation");t.push({number:i,depth:Math.floor(l/n.indent),content:o.slice(l),blankBefore:r}),r=!1}),t}function G(e,n){let t=Pd(n),r=jd(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=Tt(o.content,T(o.content,":",o.number))}catch(u){if(t.strict)throw Ot(u,o.number);c=void 0}if(c!==void 0)return $d(c,r,t)}if(s&&T(o.content,":",o.number)===-1)return J(o.content.trim(),o.number);let i={index:0},l=At(r,i,0,t),a=r[i.index];if(a!==void 0)throw R(a.number,"expected end of document");return l}function At(e,n,t,r){let o={};for(;n.index<e.length;){let s=e[n.index];if(s.depth<t)break;if(s.depth>t)throw R(s.number,"invalid indentation");let{key:i,quoted:l,value:a}=Dd(e,n,t,r);Vo(o,i,l,a,r,s.number)}return o}function Dd(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 y;try{y=Td(l)}catch(k){if(r.strict)throw Ot(k,o.number);n.index+=1;let _=Et(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:_}}if(a.trim()!=="")throw R(o.number,"expected keyed map rows");let b=Od(y,e,n,t+1,r);return{key:y.key,quoted:y.keyQuoted,value:b}}if(c!==-1){let y;try{y=Tt(l,i)}catch(k){if(r.strict)throw Ot(k,o.number);n.index+=1;let _=Et(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:_}}if(y.key===""&&!y.keyQuoted)throw R(o.number,"expected non-empty field name");let b=It(y,a,e,n,t,r);return{key:y.key,quoted:y.keyQuoted,value:b}}let[p,m]=ne(l,o.number);if(p===""&&!m)throw R(o.number,"expected non-empty field name");n.index+=1;let g=Et(e,n,t,a,o.number,r);return{key:p,quoted:m,value:g}}function Et(e,n,t,r,o,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return J(i,o);let l=e[n.index];return l!==void 0&&l.depth>t?At(e,n,t+1,s):{}}function 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,c]=ne(i.content.slice(0,l),i.number);if(a===""&&!c)throw R(i.number,"expected non-empty field name");let u=he(i.content.slice(l+1).trim(),e.delimiter,i.number);if(u.length!==e.fields.length)throw R(i.number,"keyed map row length mismatch");let p={};e.fields.forEach((m,g)=>{Xe(p,m,J(u[g],i.number),o,i.number)}),Vo(s,a,c,p,o,i.number),t.index+=1}return s}function $d(e,n,t){let r=n[0],o=T(r.content,":",r.number);if(o===-1)throw R(r.number,"expected `key: value`");let s=r.content.slice(o+1),i={index:0},l=It(e,s,n,i,0,t),a=n[i.index];if(a!==void 0)throw R(a.number,"expected end of document");return l}function It(e,n,t,r,o,s){let i=t[r.index].number,l=n.trim();if(r.index+=1,e.fields!==void 0){if(l!=="")throw R(i,"expected tabular rows");return Ld(e,e.fields,t,r,o+1,s)}if(l!==""){let a=he(l,e.delimiter,i).map(c=>J(c,i));if(a.length!==e.len)throw R(i,"array length mismatch");return a}return Ad(e,t,r,o+1,s)}function Ld(e,n,t,r,o,s){let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0)throw jt(t,r.index);if(a.depth<o)break;if(a.depth>o)throw R(a.number,"invalid indentation");if(a.blankBefore&&s.strict)throw R(a.number,"blank line inside array");if(!Uo(a.content,e.delimiter,a.number))break;let c=he(a.content,e.delimiter,a.number);if(c.length!==n.length)throw R(a.number,"array row length mismatch");let u={};n.forEach((p,m)=>{Xe(u,p,J(c[m],a.number),s,a.number)}),i.push(u),r.index+=1}if(i.length!==e.len)throw jt(t,r.index);let l=t[r.index];if(l!==void 0&&l.depth>=o&&Uo(l.content,e.delimiter,l.number))throw R(l.number,"array length mismatch");return i}function Uo(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 Ad(e,n,t,r,o){let s=[];for(;s.length<e.len;){let l=n[t.index];if(l===void 0||l.depth<r)throw jt(n,t.index);if(l.depth>r)throw R(l.number,"invalid indentation");if(l.blankBefore&&o.strict)throw R(l.number,"blank line inside array");s.push(Id(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 Id(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw R(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return n.index+=1,{};if(s.startsWith("[")){let i=T(s,":",o.number),l;try{l=Tt(s,i)}catch{l=void 0}if(l!==void 0){let a=s.slice(i+1);return It(l,a,e,n,t,r)}}if(T(s,":",o.number)!==-1){let i=[{number:o.number,depth:t+1,content:s,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let l=e[n.index];if(l.depth<=t)break;i.push(l),n.index+=1}return At(i,{index:0},t+1,r)}return n.index+=1,J(s,o.number)}function jt(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function Tt(e,n){if(n===-1)throw R(0,"array header missing colon");let t=e.slice(0,n),r=T(t,"[",0);if(r===-1)throw R(0,"invalid array header");let o,s;try{[o,s]=ne(t.slice(0,r),0)}catch{throw R(0,"invalid array header")}let i=t.slice(r+1),l=i.indexOf("]");if(l===-1)throw R(0,"invalid array header");let a=i.slice(0,l),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 m=i.slice(l+1),g;if(m==="")g=void 0;else if(m.startsWith("{")&&m.endsWith("}")&&m.length>=2)try{g=Ho(m.slice(1,-1),p)}catch(y){throw R(0,y.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw R(0,"invalid array header");return{key:o,keyQuoted:s,len:u,delimiter:p,fields:g}}function Td(e){let n=T(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=ne(e.slice(0,n),0)}catch{throw R(0,"invalid keyed map header")}if(t===""&&!r)throw R(0,"expected non-empty field name");let o;try{o=Ho(e.slice(n+1,-1),j)}catch(s){throw R(0,s.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:j,fields:o}}function Ho(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 m=e[r];if(m==='"'){s();continue}if(m===n||m==="{"||m==="}")break;r+=1}let[p]=ne(e.slice(u,r),0);if(p==="")throw R(0,"invalid array header");if(c+=1,e[r]==="{"){r+=1;let m=t.length;if(o([...l,p],!0),e[r]!=="}"||t.length===m)throw R(0,"invalid array header");r+=1}else t.push([...l,p]);if(e[r]===n){if(r+=1,r>=e.length||e[r]==="}")throw R(0,"invalid array header");continue}if(a?e[r]==="}":r===e.length)break;throw R(0,"invalid array header")}if(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(Nd(t[l],t[a])||Dt(t[l],t[a])||Dt(t[a],t[l]))throw R(0,"duplicate key");for(let l of t){let a=l.join("\0");if(i.has(a))throw R(0,"duplicate key");i.add(a)}return t}function Nd(e,n){return e.length===n.length&&Dt(e,n)}function Dt(e,n){return n.every((t,r)=>e[r]===t)}function Ot(e,n){return R(n,e.reason??String(e.message))}function Vo(e,n,t,r,o,s){if(o.expandPaths&&!t&&n.includes(".")){let i=n.split(".");if(i.every(Wd)){Xe(e,i,r,o,s);return}}Xe(e,[n],r,o,s)}function Xe(e,n,t,r,o){let s=n[0],i=Object.prototype.hasOwnProperty.call(e,s);if(n.length===1){if(i&&r.strict)throw R(o,"duplicate key");je(e,s,t);return}if(i&&!De(e[s])){if(r.strict)throw R(o,"path expansion conflict");je(e,s,{})}else i||je(e,s,{});Xe(e[s],n.slice(1),t,r,o)}function Wd(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function De(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function I(e,n={}){let t={nestedTabularHeaders:n.nestedTabularHeaders===!0,keyedMapCollapse:n.keyedMapCollapse===!0},r=[];return Array.isArray(e)?Nt(r,void 0,e,0,!1,t):De(e)?Bo(r,e,0,t):r.push(q(e,j)),r.join("")}function en(e,n){e.push(" ".repeat(n*Lt))}function Bo(e,n,t,r){for(let[o,s]of Object.entries(n))en(e,t),$t(e,o,s,t,r)}function $t(e,n,t,r,o){if(Array.isArray(t)){Nt(e,n,t,r,!1,o);return}if(De(t)){let s=o.keyedMapCollapse?Cd(t,o):void 0;if(s!==void 0){e.push(F(n),"{",s.fields.map(Wt).join(j),`}:
10
- `);for(let[i,l]of Object.entries(t))en(e,r+1),e.push(F(i),": ",s.paths.map(a=>q(Go(l,a),j)).join(j),`
11
- `);return}e.push(F(n),`:
12
- `),Bo(e,t,r+1,o);return}e.push(F(n),": ",q(t,j),`
13
- `)}function Nt(e,n,t,r,o,s){if(t.length===0){n!==void 0?e.push(F(n),`: []
6
+ `)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};Kf=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Jr=/^redskilled-(.+)\.bundle\.min\.mjs$/,qf=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as RR}from"node:child_process";import{homedir as Qo}from"node:os";import{join as uc}from"node:path";var He=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},Se=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonlError",this.line=n,this.reason=t}};function R(e,n){return new He(e,n)}function S(e,n){return new Se(e,n)}function Fe(e){return e instanceof Se?e:e instanceof He?new Se(e.line,e.reason):new Se(0,String(e&&e.message?e.message:e))}var Di=["type","kind","event"],ve="|",Oi=new Set(["order","discriminator","rows","common"]);var D=",";function Xn(e){let n=e.split(`
7
+ `);return n.length>0&&n[n.length-1]===""&&n.pop(),n.map(t=>t.endsWith("\r")?t.slice(0,-1):t)}function re(e){return R(e,"invalid quoted string")}function B(e,n){if(e==="")return"";if(e.startsWith('"'))return $i(e,n);if(e.includes('"'))throw re(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:Kc(e)?Number(e):e}function J(e,n){let t=e.trim();if(t.startsWith('"'))return[$i(t,n),!0];if(t.includes('"')||/\s/.test(t))throw R(n,"expected non-empty field name");return[t,!1]}var Ai=/["\\\u0000-\u0008\u000a-\u001f]/g;function $i(e,n){if(e.charCodeAt(0)!==34)throw re(n);let t="",r=1;for(;r<e.length;){Ai.lastIndex=r;let o=Ai.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(r,o.index);throw re(n)}if(o[0]!=="\\")throw re(n);t+=e.slice(r,o.index);let i=e[o.index+1];switch(r=o.index+2,i){case'"':t+='"';break;case"\\":t+="\\";break;case"n":t+=`
8
+ `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let s=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw re(n);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw re(n);t+=String.fromCharCode(a),r+=4;break}default:throw re(n)}}throw re(n)}function Ii(e,n,t){for(;;){let r=e.indexOf('"',n),o=e.indexOf("\\",n);if(o!==-1&&(r===-1||o<r)){if(o===e.length-1)throw re(t);n=o+2;continue}if(r===-1)throw re(t);return r+1}}function G(e,n,t){if(e==="")return[];let r=[],o=0,i=0;for(;i<e.length;){let s=e.indexOf('"',i),a=e.indexOf(n,i);if(a!==-1&&(s===-1||a<s))r.push(e.slice(o,a).trim()),o=a+1,i=a+1;else if(s!==-1)i=Ii(e,s+1,t);else break}return r.push(e.slice(o).trim()),r}function W(e,n,t){let r=0;for(;r<e.length;){let o=e.indexOf('"',r),i=e.indexOf(n,r);if(i!==-1&&(o===-1||i<o))return i;if(o===-1)return-1;r=Ii(e,o+1,t)}return-1}function Kc(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function qc(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Jc(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw R(0,"number is not representable in TOON");return String(e)}function oe(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function H(e,n){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Jc(e);if(typeof e=="string")return Qc(e,n);throw R(0,"not a primitive")}function Gc(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function N(e){return Gc(e)?e:Zn(e)}function Qc(e,n){return er(e,n)?Zn(e):e}function er(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||qc(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}var Li=/["\\\u0000-\u001f]/g;function Zn(e){let n='"',t=0;Li.lastIndex=0;let r;for(;(r=Li.exec(e))!==null;){let o=e.charCodeAt(r.index),i;o===34?i='\\"':o===92?i="\\\\":o===10?i="\\n":o===13?i="\\r":o===9?i="\\t":i=`\\u${o.toString(16).padStart(4,"0")}`,n+=e.slice(t,r.index)+i,t=r.index+1}return`${n}${e.slice(t)}"`}function Q(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function A(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ti(e={}){let n=e.maxDepth??1e3,t=n===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(n));return{indent:Math.max(1,e.indent??2),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0,cyclicDiscriminatedArrays:e.cyclicDiscriminatedArrays!==!1,maxDepth:t}}function Ni(e,n){let t=[],r=!1;return Xn(e).forEach((o,i)=>{let s=i+1;if(o.trim()===""){r=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw R(s,"invalid indentation");if(n.strict&&a%n.indent!==0)throw R(s,"invalid indentation");let l=Math.floor(a/n.indent);ie(l,s,n),t.push({number:s,depth:l,content:o.slice(a),blankBefore:r}),r=!1}),t}function ie(e,n,t){if(t.maxDepth!==0&&e>t.maxDepth)throw R(n,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function gn(e,n,t){if(t.maxDepth===0)return;let r=0,o=!1,i=!1;for(let s of e){if(i){i=!1;continue}if(o&&s==="\\"){i=!0;continue}if(s==='"'){o=!o;continue}o||(s==="{"?(r+=1,ie(r,n,t)):s==="}"&&(r=Math.max(0,r-1)))}}function Wi(e){if(!A(e)||Object.keys(e).length===0)return e;let n={};for(let[t,r]of Object.entries(e)){let o=zc(r,1);if(o===void 0)return e;Q(n,t,o)}return n}function zc(e,n){if(!A(e)||!Yc(e))return;let{order:t,discriminator:r,rows:o}=e;if(typeof t!="string"||typeof r!="string"||!Number.isSafeInteger(o)||o<0)throw C(n);let i=Xc(t,o,n),s=e.common,a=s===void 0?Array.from({length:o},()=>({})):s;if(!Array.isArray(a)||a.length!==o||!a.every(A))throw Hi(n);let l=new Map;for(let[u,f]of Object.entries(e))if(!Oi.has(u)){if(!Array.isArray(f)||!f.every(A))throw C(n);l.set(u,f)}if(l.size===0)throw C(n);let d=new Map,p=i.map((u,f)=>{let m=l.get(u);if(m===void 0)throw nr(n);let h=d.get(u)??0,b=m[h];if(b===void 0)throw nr(n);return d.set(u,h+1),Zc(r,u,a[f],b,n)});for(let[u,f]of l)if((d.get(u)??0)!==f.length)throw nr(n);return p}function Yc(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function Xc(e,n,t){if(!e.startsWith("cycle("))throw C(t);let r=e.slice(6),o=r.indexOf(")*");if(o===-1)throw C(t);let i=r.slice(0,o),s=r.slice(o+2);if(i===""||s.includes("+tail("))throw C(t);let a=i.split(",").map(p=>ru(p,t));if(a.some(p=>p===""))throw C(t);let l=tu(s,t),d=a.length*l;if(!Number.isSafeInteger(d))throw C(t);if(d!==n)throw Hi(t);return Array.from({length:d},(p,u)=>a[u%a.length])}function Zc(e,n,t,r,o){let i={};Q(i,e,n);for(let[s,a]of Object.entries(t??{})){if(s===e||Object.prototype.hasOwnProperty.call(i,s))throw C(o);Q(i,s,a)}for(let[s,a]of Object.entries(eu(r,o))){if(s===e||Object.prototype.hasOwnProperty.call(i,s))throw C(o);Q(i,s,a)}return i}function eu(e,n){let t={};for(let[r,o]of Object.entries(e))nu(t,r.split("."),o,n);return et(t,n)}function nu(e,n,t,r){if(n.some(i=>i===""))throw C(r);let o=e;for(let i=0;i<n.length;i+=1){let s=n[i];if(i===n.length-1){o[s]=t;return}if(o[s]??={},o=o[s],!A(o))throw C(r)}}function et(e,n){return Array.isArray(e)?e.map(t=>et(t,n)):A(e)?Number.isSafeInteger(e.length)&&e.length>=0?Array.from({length:e.length},(t,r)=>{if(!Object.prototype.hasOwnProperty.call(e,String(r)))throw C(n);return et(e[String(r)],n)}):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,et(r,n)])):e}function tu(e,n){if(e===""||e.length>1&&e.startsWith("0")||!/^[0-9]+$/.test(e))throw C(n);let t=Number(e);if(!Number.isSafeInteger(t))throw C(n);return t}function ru(e,n){try{return decodeURIComponent(e)}catch{throw C(n)}}function Ci(e){return encodeURIComponent(e)}function C(e){return R(e,"invalid cyclic array wire")}function Hi(e){return R(e,"cyclic array length mismatch")}function nr(e){return R(e,"cyclic array group length mismatch")}function Fi(e){if(!A(e))return;let n=Object.entries(e);if(n.length===0)return;let t=[];for(let[o,i]of n){let s=ou(i);if(s===void 0)return;t.push([o,s])}let r=[];for(let[o,i]of t)au(r,o,i);return r.join("")}function ou(e){if(!Array.isArray(e)||e.length===0||!e.every(A))return;let n=iu(e);if(n===void 0)return;let t=e.map(a=>a[n]),r=su(t);if(r===void 0)return;let o=lu(e,n),i=new Map;for(let a of e){let l=a[n];i.has(l)||i.set(l,[]);let d={};for(let[p,u]of Object.entries(a))if(p!==n&&!o.includes(p)&&!tr(u,p,d))return;i.get(l).push(d)}let s=[];for(let a of r.cycle){let l=i.get(a),d=cu(l);if(d===void 0||d.length===0)return;s.push({fields:d,label:a,rows:l})}return{common:o,commonRows:e.map(a=>Object.fromEntries(o.map(l=>[l,a[l]]))),discriminator:n,groups:s,order:r,rows:e}}function iu(e){return Di.find(n=>e.every(t=>typeof t[n]=="string"))}function su(e){if(!(e.length<12))for(let n=2;n<=Math.min(8,Math.floor(e.length/3));n+=1){if(e.length%n!==0)continue;let t=e.slice(0,n);if(new Set(t).size<2||!e.every((s,a)=>s===t[a%n]))continue;let r=e.length/n;if(r<3)continue;let o=e.map(Ci).join(","),i=`cycle(${t.map(Ci).join(",")})*${r}`;if(i.length<=o.length*.4)return{cycle:t,encoded:i,repeats:r}}}function lu(e,n){let t=[],r=Object.keys(e[0]),o=r.indexOf(n)+1;for(let i of r.slice(o).filter(s=>s!==n)){if(!du(i)||!e.every(s=>Object.prototype.hasOwnProperty.call(s,i))||!e.every(s=>oe(s[i])))break;t.push(i)}return t}function au(e,n,t){e.push(N(n),`:
9
+ `),e.push(" order: ",H(t.order.encoded,ve),`
10
+ `),e.push(" discriminator: ",H(t.discriminator,ve),`
11
+ `),e.push(" rows: ",String(t.rows.length),`
12
+ `),t.common.length>0&&Mi(e,"common",t.common,t.commonRows);for(let r of t.groups)Mi(e,r.label,r.fields,r.rows)}function Mi(e,n,t,r){e.push(" ",N(n),"[",String(r.length),ve,"]{",t.map(N).join(ve),`}:
13
+ `);for(let o of r)e.push(" ",t.map(i=>H(o[i],ve)).join(ve),`
14
+ `)}function du(e){return e!==""&&rr(e)}function tr(e,n,t,r=new Set){if(!rr(n))return!1;if(oe(e))return t[n]=e,!0;if(Array.isArray(e)){if(r.has(e))return!1;r.add(e),t[`${n}.length`]=e.length;let o=e.every((i,s)=>tr(i,`${n}.${s}`,t,r));return r.delete(e),o}if(A(e)){if(r.has(e))return!1;r.add(e);let o=Object.entries(e).every(([i,s])=>!i.includes(".")&&tr(s,`${n}.${i}`,t,r));return r.delete(e),o}return!1}function cu(e){let n=Object.keys(e[0]??{});if(e.every(t=>uu(Object.keys(t),n)))return n.every(rr)?n:void 0}function uu(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function rr(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function Ue(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function nt(e,n){if(n===-1)throw R(0,"array header missing colon");let t=e.slice(0,n),r=W(t,"[",0);if(r===-1)throw R(0,"invalid array header");let o,i;try{[o,i]=J(t.slice(0,r),0)}catch{throw R(0,"invalid array header")}let s=t.slice(r+1),a=s.indexOf("]");if(a===-1)throw R(0,"invalid array header");let l=s.slice(0,a),d=/^[0-9]*/.exec(l)[0];if(d===""||d.length>1&&d.startsWith("0"))throw R(0,"invalid array header");let p=Number.parseInt(d,10),u;switch(l.slice(d.length)){case"":u=",";break;case" ":u=" ";break;case"|":u="|";break;default:throw R(0,"invalid array header")}let f=s.slice(a+1),m,h;if(f==="")m=void 0,h=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{h=fu(f.slice(1,-1),u),m=ir(h)}catch(b){throw R(0,b.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw R(0,"invalid array header");return{key:o,keyQuoted:i,len:p,delimiter:u,fields:m,fieldTree:h}}function Ui(e){let n=W(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=J(e.slice(0,n),0)}catch{throw R(0,"invalid keyed map header")}if(t===""&&!r)throw R(0,"expected non-empty field name");let o=e.slice(n+1,-1),i=D;(o.startsWith("|")||o.startsWith(" "))&&(i=o[0],o=o.slice(1));let s;try{s=pu(o,i,i)}catch(a){throw R(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:i,fields:s}}function pu(e,n,t){let r=[],o=0;function i(l,d){let p=0;for(;o<e.length&&!(d&&e[o]==="}");){if(e[o]===n||e[o]==="}")throw R(0,"invalid array header");let u=o;for(;o<e.length;){let h=e[o];if(h==='"'){s();continue}if(h===n||h==="{"||h==="}"||h==="[")break;o+=1}let[f,m]=J(e.slice(u,o),0);if(f===""&&!m)throw R(0,"invalid array header");if(p+=1,e[o]==="["){o+=1;let h=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw R(0,"invalid array header");let b=e.slice(h,o);if(!Bi(b,t))throw R(0,"invalid array header");o+=1,r.push({path:[...l,f],listDelimiter:b})}else if(e[o]==="{"){o+=1;let h=r.length;if(i([...l,f],!0),e[o]!=="}"||r.length===h)throw R(0,"invalid array header");o+=1}else r.push({path:[...l,f],listDelimiter:void 0});if(e[o]===n){if(o+=1,o>=e.length||e[o]==="}")throw R(0,"invalid array header");continue}if(d?e[o]==="}":o===e.length)break;throw R(0,"invalid array header")}if(p===0)throw R(0,"invalid array header")}function s(){for(o+=1;o<e.length;){let l=e[o];if(o+=1,l==="\\")o+=1;else if(l==='"')return}}if(i([],!1),o!==e.length)throw R(0,"invalid array header");let a=new Set;for(let l=0;l<r.length;l+=1)for(let d=l+1;d<r.length;d+=1)if(Vi(r[l].path,r[d].path)||yn(r[l].path,r[d].path)||yn(r[d].path,r[l].path))throw R(0,"duplicate key");for(let l of r){let p=l.path.join("\0");if(a.has(p))throw R(0,"duplicate key");a.add(p)}return r}function fu(e,n){if(n!==D&&e.includes(D)&&(e.includes("[")||e.includes("{")))return or(e,D,n);try{return or(e,n,n)}catch(t){if(n!==D&&t.reason!=="duplicate key")return or(e,D,n);throw t}}function or(e,n,t){let r=0;function o(l){let d=[];for(;r<e.length&&!(l&&e[r]==="}");){if(e[r]===n||e[r]==="}")throw R(0,"invalid array header");let p=r;for(;r<e.length;){let h=e[r];if(h==='"'){i();continue}if(h===n||h==="{"||h==="}"||h==="[")break;r+=1}let[u,f]=J(e.slice(p,r),0);if(u===""&&!f)throw R(0,"invalid array header");let m={key:u};if(e[r]==="["){r+=1;let h=r;for(;r<e.length&&e[r]!=="]";)r+=1;if(r>=e.length)throw R(0,"invalid array header");let b=e.slice(h,r);r+=1;let k=mu(b);if(k!==void 0){if(k.delimiter!==t)throw R(0,"invalid array header");m.fixedLength=k.len,m.fixedDelimiter=k.delimiter}else if(Bi(b,t))m.listDelimiter=b;else throw R(0,"invalid array header")}else if(e[r]==="{"){if(r+=1,m.children=o(!0),e[r]!=="}"||m.children.length===0)throw R(0,"invalid array header");r+=1}if(d.push(m),e[r]===n){if(r+=1,r>=e.length||e[r]==="}")throw R(0,"invalid array header");continue}if(l?e[r]==="}":r===e.length)break;throw R(0,"invalid array header")}if(d.length===0)throw R(0,"invalid array header");return d}function i(){for(r+=1;r<e.length;){let l=e[r];if(r+=1,l==="\\")r+=1;else if(l==='"')return}}let s=o(!1);if(r!==e.length)throw R(0,"invalid array header");let a=ir(s);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(Vi(a[l].path,a[d].path)||yn(a[l].path,a[d].path)||yn(a[d].path,a[l].path))throw R(0,"duplicate key");return s}function mu(e){let n=/^[0-9]+/.exec(e)?.[0];if(n===void 0||n.length>1&&n.startsWith("0"))return;let t=e.slice(n.length),r;switch(t){case"":r=D;break;case" ":r=" ";break;case"|":r="|";break;default:return}return{len:Number.parseInt(n,10),delimiter:r}}function ir(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?ir(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function tt(e,n,t){return e.listDelimiter===void 0?B(n,t):G(n,e.listDelimiter,t).map(r=>B(r,t))}function Bi(e,n){return e.length===1&&e!==n&&!/[ \t\r\n"[\]{}:]/.test(e)}function Vi(e,n){return e.length===n.length&&yn(e,n)}function yn(e,n){return n.every((t,r)=>e[r]===t)}function rt(e,n){return R(n,e.reason??String(e.message))}function z(e,n){let t=Ti(n),r=Ni(e,t),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw R(o.number,"invalid indentation");let i=r.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){gn(o.content,o.number,t);let d;try{d=nt(o.content,W(o.content,":",o.number))}catch(p){if(t.strict)throw rt(p,o.number);d=void 0}if(d!==void 0)return yu(d,r,t)}if(i&&W(o.content,":",o.number)===-1)return B(o.content.trim(),o.number);let s={index:0},a=lr(r,s,0,t),l=r[s.index];if(l!==void 0)throw R(l.number,"expected end of document");return t.cyclicDiscriminatedArrays?Wi(a):a}function lr(e,n,t,r){let o={};for(;n.index<e.length;){let i=e[n.index];if(i.depth<t)break;if(i.depth>t)throw R(i.number,"invalid indentation");let{key:s,quoted:a,value:l}=hu(e,n,t,r);Yi(o,s,a,l,r,i.number)}return o}function hu(e,n,t,r){let o=e[n.index],i=o.content,s=W(i,":",o.number);if(s===-1)throw R(o.number,"expected `key: value`");let a=i.slice(0,s),l=i.slice(s+1),d=W(a,"[",o.number),p=W(a,"{",o.number);if(p!==-1&&(d===-1||p<d)){gn(a,o.number,r);let h;try{h=Ui(a)}catch(k){if(r.strict)throw rt(k,o.number);n.index+=1;let w=sr(e,n,t,l,o.number,r);return{key:a.trim(),quoted:!1,value:w}}if(l.trim()!=="")throw R(o.number,"expected keyed map rows");let b=gu(h,e,n,t+1,r);return{key:h.key,quoted:h.keyQuoted,value:b}}if(d!==-1){gn(a,o.number,r);let h;try{h=nt(a,s)}catch(k){if(r.strict)throw rt(k,o.number);n.index+=1;let w=sr(e,n,t,l,o.number,r);return{key:a.trim(),quoted:!1,value:w}}if(h.key===""&&!h.keyQuoted)throw R(o.number,"expected non-empty field name");let b=ar(h,l,e,n,t,r);return{key:h.key,quoted:h.keyQuoted,value:b}}let[u,f]=J(a,o.number);if(u===""&&!f)throw R(o.number,"expected non-empty field name");n.index+=1;let m=sr(e,n,t,l,o.number,r);return{key:u,quoted:f,value:m}}function sr(e,n,t,r,o,i){let s=r.trim();if(s==="[]")return[];if(s!=="")return B(s,o);let a=e[n.index];return a!==void 0&&a.depth>t?lr(e,n,t+1,i):{}}function gu(e,n,t,r,o){let i={};for(t.index+=1;t.index<n.length;){let s=n[t.index];if(s.depth<r)break;if(s.depth>r)throw R(s.number,"invalid indentation");if(s.blankBefore&&o.strict)throw R(s.number,"blank line inside keyed map");let a=W(s.content,":",s.number);if(a===-1)throw R(s.number,"expected `key: value`");let[l,d]=J(s.content.slice(0,a),s.number);if(l===""&&!d)throw R(s.number,"expected non-empty field name");let p=G(s.content.slice(a+1).trim(),e.delimiter,s.number);if(p.length!==e.fields.length)throw R(s.number,"keyed map row length mismatch");let u={};e.fields.forEach((f,m)=>{Ve(u,f.path,tt(f,p[m],s.number),o,s.number)}),Yi(i,l,d,u,o,s.number),t.index+=1}return i}function yu(e,n,t){let r=n[0],o=W(r.content,":",r.number);if(o===-1)throw R(r.number,"expected `key: value`");let i=r.content.slice(o+1),s={index:0},a=ar(e,i,n,s,0,t),l=n[s.index];if(l!==void 0)throw R(l.number,"expected end of document");return a}function ar(e,n,t,r,o,i){let s=t[r.index].number,a=n.trim();if(r.index+=1,e.fields!==void 0){if(a!=="")throw R(s,"expected tabular rows");return ku(e,e.fields,t,r,o+1,i)}if(a!==""){let l=G(a,e.delimiter,s).map(d=>B(d,s));if(l.length!==e.len)throw R(s,"array length mismatch");return l}return vu(e,t,r,o+1,i)}function ku(e,n,t,r,o,i){if(e.fieldTree!==void 0&&xu(e.fieldTree))return Ru(e,t,r,o,i);let s=[];for(;s.length<e.len;){let l=t[r.index];if(l===void 0)throw Ue(t,r.index);if(l.depth<o)break;if(l.depth>o)throw R(l.number,"invalid indentation");if(l.blankBefore&&i.strict)throw R(l.number,"blank line inside array");if(!Be(l.content,e.delimiter,l.number))break;let d=G(l.content,e.delimiter,l.number);if(d.length!==n.length)throw R(l.number,"array row length mismatch");let p={};n.forEach((u,f)=>{Ve(p,u.path,tt(u,d[f],l.number),i,l.number)}),s.push(p),r.index+=1}if(s.length!==e.len)throw Ue(t,r.index);let a=t[r.index];if(a!==void 0&&a.depth>=o&&Be(a.content,e.delimiter,a.number))throw R(a.number,"array length mismatch");return s}function Ru(e,n,t,r,o){return Ki(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function Ki(e,n,t,r,o,i,s,a){let l=[],d=Ji(e,n,t,r,o.index,i,s);for(;l.length<e;){let u=r[o.index];if(u===void 0)throw Ue(r,o.index);if(u.depth<i)break;if(u.depth>i)throw R(u.number,"invalid indentation");if(u.blankBefore&&s.strict)throw R(u.number,"blank line inside array");if(!Be(u.content,t,u.number))break;let f=G(u.content,t,u.number),m={cellIndex:0,nextIndex:o.index+1,flatWidth:ot(n),childTableFields:d},h=qi(n,f,u.number,r,m,i+1,t,s);if(m.cellIndex!==f.length)throw R(u.number,"array row length mismatch");l.push(wu(n,h,a)),o.index=m.nextIndex}if(l.length!==e)throw Ue(r,o.index);let p=r[o.index];if(p!==void 0&&p.depth>=i&&Be(p.content,t,p.number))throw R(p.number,"array length mismatch");return l}function qi(e,n,t,r,o,i,s,a){let l={};return e.forEach((d,p)=>{let u=e.slice(p+1),f=bu(d,u,n,t,r,o,i,s,a);Ve(l,[d.key],f,a,t)}),l}function bu(e,n,t,r,o,i,s,a,l){if(e.fixedLength!==void 0){if(i.cellIndex+e.fixedLength>t.length)throw R(r,"array row length mismatch");let p=t.slice(i.cellIndex,i.cellIndex+e.fixedLength).map(u=>B(u,r));return i.cellIndex+=e.fixedLength,p}if(e.children!==void 0){let p=ot(e.children),u=t[i.cellIndex],f=Qi(u),m=t.length-i.cellIndex-1,h=o[i.nextIndex],b=h!==void 0&&h.depth===s,k=i.childTableFields===void 0?void 0:i.childTableFields.has(e);if(k===void 0?f!==void 0&&(b||t.length!==i.flatWidth&&m<p+Su(n)):k){if(f===void 0)throw R(r,"array row length mismatch");return i.cellIndex+=1,Ki(f,e.children,a,o,{get index(){return i.nextIndex},set index(j){i.nextIndex=j}},s,l,!1)}return qi(e.children,t,r,o,i,s,a,l)}let d=t[i.cellIndex];if(d===void 0)throw R(r,"array row length mismatch");return i.cellIndex+=1,tt(e,d,r)}function Ji(e,n,t,r,o,i,s){let a=n.filter(p=>p.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let l,d=1<<a.length;for(let p=0;p<d;p+=1){let u=new Set;a.forEach((m,h)=>{p&1<<h&&u.add(m)});let f=Gi(e,n,u,t,r,o,i,s);f!==void 0&&(l===void 0||f.consumedChildRows>l.consumedChildRows||f.consumedChildRows===l.consumedChildRows&&u.size<l.childTableFields.size)&&(l={childTableFields:u,consumedChildRows:f.consumedChildRows})}return l?.childTableFields}function Gi(e,n,t,r,o,i,s,a){let l=i,d=0;try{for(let u=0;u<e;u+=1){let f=o[l];if(f===void 0||f.depth!==s||f.blankBefore&&a.strict||!Be(f.content,r,f.number))return;let m=G(f.content,r,f.number),h=_u(n,t,m,r,o,l+1,s+1,a);if(h===void 0||o[h.nextIndex]?.depth>s)return;d+=h.consumedChildRows,l=h.nextIndex}let p=o[l];if(p!==void 0&&p.depth>=s&&Be(p.content,r,p.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function _u(e,n,t,r,o,i,s,a){let l=0,d=i,p=0;for(let u of e){if(u.fixedLength!==void 0)l+=u.fixedLength;else if(u.children!==void 0)if(n.has(u)){let f=Qi(t[l]);if(f===void 0)return;l+=1;let m=Ji(f,u.children,r,o,d,s,a);if(m===void 0)return;let h=Gi(f,u.children,m,r,o,d,s,a);if(h===void 0)return;d=h.nextIndex,p+=f+h.consumedChildRows}else l+=ot(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:p}}function wu(e,n,t){return t&&e.length===1&&e[0].fixedLength!==void 0?n[e[0].key]:n}function Qi(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function xu(e){return e.some(n=>n.fixedLength!==void 0||n.children!==void 0)}function ot(e){return e.reduce((n,t)=>n+zi(t),0)}function zi(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?ot(e.children):1}function Su(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+zi(t),0)}function Be(e,n,t){let r=W(e,":",t);if(r===-1)return!0;let o=W(e,n,t);return o===-1?!1:o<r}function vu(e,n,t,r,o){let i=[];for(;i.length<e.len;){let a=n[t.index];if(a===void 0||a.depth<r)throw Ue(n,t.index);if(a.depth>r)throw R(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw R(a.number,"blank line inside array");i.push(Eu(n,t,r,o))}let s=n[t.index];if(s!==void 0&&s.depth>=r)throw R(s.number,"array length mismatch");return i}function Eu(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw R(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return n.index+=1,{};if(i.startsWith("[")){let s=W(i,":",o.number);gn(i,o.number,r);let a;try{a=nt(i,s)}catch{a=void 0}if(a!==void 0){let l=i.slice(s+1);return ar(a,l,e,n,t,r)}}if(W(i,":",o.number)!==-1){let s=[{number:o.number,depth:t+1,content:i,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let a=e[n.index];if(a.depth<=t)break;s.push(a),n.index+=1}return lr(s,{index:0},t+1,r)}return n.index+=1,B(i,o.number)}function Yi(e,n,t,r,o,i){if(o.expandPaths&&!t&&n.includes(".")){let s=n.split(".");if(s.every(Pu)){Ve(e,s,r,o,i);return}}Ve(e,[n],r,o,i)}function Ve(e,n,t,r,o){ie(n.length-1,o,r);let i=n[0],s=Object.prototype.hasOwnProperty.call(e,i);if(n.length===1){if(s&&r.strict)throw R(o,"duplicate key");Q(e,i,t);return}if(s&&!A(e[i])){if(r.strict)throw R(o,"path expansion conflict");Q(e,i,{})}else s||Q(e,i,{});Ve(e[i],n.slice(1),t,r,o)}function Pu(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function M(e,n={}){let t=n.maxDepth??1e3,r=n.delimiter??D;if(![D,"|"," "].includes(r))throw R(0,"invalid array header");let o={nestedTabularHeaders:n.nestedTabularHeaders===!0,keyedMapCollapse:n.keyedMapCollapse===!0,primitiveArrayColumns:n.primitiveArrayColumns===!0,objectArrayColumns:n.objectArrayColumns===!0,cyclicDiscriminatedArrays:n.cyclicDiscriminatedArrays===!0,delimiter:r,maxDepth:t===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(t))};if(o.cyclicDiscriminatedArrays){let s=Fi(e);if(s!==void 0)return s}let i=[];return Array.isArray(e)?pr(i,void 0,e,0,!1,o):A(e)?Xi(i,e,0,o):i.push(H(e,r)),i.join("")}function Ke(e,n){e.push(" ".repeat(n*2))}function Xi(e,n,t,r){ie(t,0,r);for(let[o,i]of Object.entries(n))Ke(e,t),cr(e,o,i,t,r)}function cr(e,n,t,r,o){if(ie(r,0,o),Array.isArray(t)){pr(e,n,t,r,!1,o);return}if(A(t)){let i=o.keyedMapCollapse?Du(t,o,r+1):void 0;if(i!==void 0){e.push(N(n),"{",fr(o.delimiter),i.fields.map(s=>gr(s,o.delimiter)).join(o.delimiter),`}:
15
+ `);for(let[s,a]of Object.entries(t)){Ke(e,r+1);let l=[];e.push(N(s),": ",i.paths.map(d=>yr(hr(a,d.path),d,o.delimiter,o,l,r+2)).join(o.delimiter),`
16
+ `),e.push(...l)}return}e.push(N(n),`:
17
+ `),Xi(e,t,r+1,o);return}e.push(N(n),": ",H(t,o.delimiter),`
18
+ `)}function pr(e,n,t,r,o,i){if(ie(r,0,i),t.length===0){n!==void 0?e.push(N(n),`: []
14
19
  `):o?e.push(`[0]:
15
20
  `):e.push(`[]
16
- `);return}if(t.every(Ze)){Pt(e,n,t.length,void 0),e.push(" "),e.push(t.map(l=>q(l,j)).join(j)),e.push(`
17
- `);return}let i=o?void 0:Ko(t,s);if(i!==void 0){Pt(e,n,t.length,i.fields),e.push(`
18
- `);for(let l of t)en(e,r+1),e.push(i.paths.map(a=>q(Go(l,a),j)).join(j)),e.push(`
19
- `);return}Pt(e,n,t.length,void 0),e.push(`
20
- `);for(let l of t)en(e,r+1),Md(e,l,r+1,s)}function Md(e,n,t,r){if(Array.isArray(n)){e.push("- "),Nt(e,void 0,n,t,!0,r);return}if(De(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
21
- `);return}e.push("- "),$t(e,o[0][0],o[0][1],t+1,r);for(let[s,i]of o.slice(1))en(e,t+1),$t(e,s,i,t+1,r);return}e.push("- ",q(n,j),`
22
- `)}function Pt(e,n,t,r){n!==void 0&&e.push(F(n)),e.push("[",String(t),"]"),r!==void 0&&e.push("{",r.map(Wt).join(j),"}"),e.push(":")}function Ko(e,n){let t=Jo(e.map(r=>({value:r})),n);return t===void 0?void 0:{fields:t,paths:qo(t)}}function Cd(e,n){let t=Object.values(e);if(!(t.length<2))return Ko(t,n)}function Jo(e,n){let t=e[0]?.value;if(!De(t))return;let r=Object.keys(t).map(o=>({key:o}));if(r.length!==0){for(let{value:o}of e)if(!De(o)||Object.keys(o).length!==r.length||r.some(i=>!Object.prototype.hasOwnProperty.call(o,i.key)))return;for(let o of r){let s=e.map(({value:l})=>({value:l[o.key]}));if(s.every(({value:l})=>Ze(l)))continue;if(!n.nestedTabularHeaders)return;let i=Jo(s,n);if(i===void 0)return;o.children=i}return r}}function qo(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children===void 0?[r]:qo(t.children,r)})}function Go(e,n){let t=e;for(let r of n)t=t[r];return t}function Wt(e){return e.children===void 0?F(e.key):`${F(e.key)}{${e.children.map(Wt).join(j)}}`}var ts=[j,"|"," "];var rs=8,os=/^[A-Za-z0-9_-]+$/,Ay=new TextEncoder,Iy=new TextDecoder;function Ud(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw S(n,"invalid trailer count");return Number.parseInt(t,10)}function ss(e,n){if(!os.test(e))throw S(n,"invalid tag")}function Hd(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!os.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw S(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function Vd(e,n){if(!e.startsWith("["))return null;let t=e.slice(1),r=t.indexOf("]");if(r===-1)throw S(n,"invalid header");let o=t.slice(0,r),s=o.startsWith("~"),i=s?o.slice(1):o;if(!s&&i.startsWith("="))return null;if(!ts.includes(i)&&i!=="")throw S(n,"invalid header delimiter");let l=i===""?j:i,a=t.slice(r+1),c=null;if(!s&&a.startsWith("<")){let m=a.indexOf(">");if(m===-1)throw S(n,"invalid tag");if(c=a.slice(1,m),ss(c,n),i!=="")throw S(n,"invalid header delimiter");a=a.slice(m+1)}if(!a.startsWith("{")||!a.endsWith("}:"))throw S(n,"invalid header");let u=a.slice(1,-2),p;try{p=he(u,l,n).map(m=>ne(m,n)[0])}catch(m){throw Pe(m)}if(p.length===0||p.some(m=>m===""))throw S(n,"invalid header fields");return{delimiter:l,fields:p,fieldText:u,continuation:s,tag:c}}function Bd(e,n,t){if(e===null||e.delimiter===void 0)throw S(t,"continuation header before header");if(e.delimiter!==n.delimiter||e.fieldText!==n.fieldText)throw S(t,"continuation header mismatch")}function zo(e,n,t,r){let o;try{o=he(e,n,r)}catch(s){throw Pe(s)}if(o.length!==t)throw S(r,"row arity mismatch");for(let s of o)try{J(s,r)}catch(i){throw Pe(i)}return o}function Kd(e,n,t){let r={};return e.forEach((o,s)=>{try{je(r,o,J(n[s],t))}catch(i){throw Pe(i)}}),r}function Jd(e,n,t){if(e.startsWith("- "))throw S(n,"reserved line prefix");let r=Ud(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw S(n,"trailer without header");if(t.rowCount!==r)throw S(n,"trailer count mismatch");return{kind:"trailer"}}let o=Vd(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=Hd(e,n);if(s!==null){let i=t?.taggedLanes?.get(s.tag);if(i===void 0)throw S(n,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:zo(s.cellsText,i.delimiter,i.fields.length,n)}}if(t===null||t.delimiter===void 0)throw S(n,"row before header");return{kind:"row",cells:zo(e,t.delimiter,t.fields.length,n)}}function qd(e,n={}){let t=[],r=new Map,o=[],s=[],i=null,l=!1,a=!1;function c(g,y){let b=s.at(-1);if(b!==void 0&&b.lane===g.lane&&b.delimiter===g.delimiter&&b.fieldText===g.fieldText){b.rows.push(y);return}s.push({lane:g.lane,delimiter:g.delimiter,fields:g.fields,fieldText:g.fieldText,rows:[y]})}function u(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function p(g,y,b){let k=r.get(g);if(k===void 0){if(r.size>=rs)throw S(b,"too many tagged lanes");k={segments:[],current:null},r.set(g,k),t.push(g)}else k.current!==null&&k.segments.push(k.current);k.current={lane:g,delimiter:y.delimiter,fields:y.fields,fieldText:y.fieldText,rows:[]},k.delimiter=y.delimiter,k.fields=y.fields,k.fieldText=y.fieldText}if(An(e).forEach((g,y)=>{let b=y+1;if(g==="")return;let k=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},_=Jd(g,b,k);if(_.kind==="trailer"){u(),i=null;return}if(_.kind!=="continuation"){if(_.kind==="tag-header"){a=!0,p(_.header.tag,_.header,b);return}if(_.kind==="header"){u(),l||(t.push(null),l=!0),i={lane:null,delimiter:_.header.delimiter,fields:_.header.fields,fieldText:_.header.fieldText,rows:[]};return}if(_.kind==="tagged-row"){a=!0;let D=r.get(_.tag).current;D.rows.push(_.cells),c(D,_.cells);return}if(i===null)throw S(b,"row before header");i.rows.push(_.cells),c(i,_.cells)}}),!a)return u(),n.preserveInterleaving===!0,o;let m=[];u();for(let g of t){if(g===null){m.push(...o);continue}let y=r.get(g);m.push(...y.segments),y.current!==null&&m.push(y.current)}return n.preserveInterleaving===!0?s:m}function de(e){return qd(e).flatMap(n=>n.rows.map(t=>Kd(n.fields,t,0)))}function Gd(e){if(!ts.includes(e))throw S(0,"invalid header delimiter")}function Qo(e,n,t=!1){return`[${`${t?"~":""}${e===j?"":e}`}]{${n}}:
23
- `}function Yo(e,n){return`[]<${e}>{${n}}:
24
- `}function Mt(e,n){return n.map(F).join(e)}function zd(e){if(!Array.isArray(e)||e.length===0)throw S(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=ne(String(n),0)}catch(r){throw Pe(r)}if(t==="")throw S(0,"TOONL header requires fields");return t})}function Zo(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function Xo(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw S(0,"TOONL continuation cadence must be positive")}function Qd(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function es(e){if(e===null||typeof e!="object"||Array.isArray(e))throw S(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw S(0,"TOONL output requires object rows");if(n.some(t=>!Ze(e[t])))throw S(0,"TOONL rows must be flat objects");return n}function Yd(e){return JSON.stringify([...e].sort())}function ns(e,n){let t=Yd(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function te({delimiter:e=j,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){Gd(e),Xo(t),Xo(r);let o=null,s="",i=new Map,l=0,a=0,c=0,u=new Map,p=!1,m={continuationEveryRows:t,continuationEveryBytes:r},g=()=>o===null||!n?"":`[=${l}]
25
- `,y=()=>Qd(m,a,c)?(a=0,c=0,Qo(e,s,!0)):"",b=k=>{ss(k,0);let _=u.get(k);if(_===void 0){if(u.size>=rs)throw S(0,"too many tagged lanes");_={fields:null,fieldsByShape:new Map},u.set(k,_)}return _};return{push(k){if(p)throw S(0,"TOONL encoder is closed");let _=ns(es(k),i),D="";(o===null||o.length!==_.length||o.some((me,ve)=>me!==_[ve]))&&(D+=g(),o=_,s=Mt(e,o),l=0,a=0,c=0,D+=Qo(e,s));let V=o.map(me=>q(k[me],e));D+=y();let C=`${V.join(e)}
26
- `;return D+=C,l+=1,a+=1,c+=C.length,D},declareLane(k,_){if(p)throw S(0,"TOONL encoder is closed");let D=zd(_),V=Mt(j,D),C=b(k);return Zo(C.fields,D)?"":(C.fields=D,Yo(k,V))},pushTagged(k,_){if(p)throw S(0,"TOONL encoder is closed");let D=b(k),V=ns(es(_),D.fieldsByShape),C=Mt(j,V),me=V.map(Rn=>q(_[Rn],j)),ve="";return Zo(D.fields,V)||(D.fields=V,ve+=Yo(k,C)),`${ve}${k}:${me.join(j)}
27
- `},end(){return p?"":(p=!0,g())}}}function Ct(e){let n={app:e,version:Zd(Oe("__RED_BUILD_VERSION__",()=>"3.3.8")??"0.0.0-dev"),gitSha:Oe("__RED_BUILD_GIT_SHA__",()=>"237f92e38c2041901c29482b96ac88b303d979c0")??"unknown",buildTime:Oe("__RED_BUILD_TIME__",()=>"2026-08-02T13:10:23Z")??"unknown",bundleAsset:Oe("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=Oe("__REDDB_SDK_VERSION__",()=>""),r=Oe("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function Zd(e){return e.startsWith("v")?e.slice(1):e}function is(e){return`${e.app} ${e.version} ${e.gitSha}`}function Oe(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var ls={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Xd=/^[a-z][a-z0-9+.-]*:\/\//i;function ec(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 nc(e=ls){return Object.entries(e).map(([n,t])=>ec(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function tc(e){return/^-\d+(\.\d+)?$/.test(e)}function nn(e){return!(!e||e.startsWith("-")&&!tc(e))}function In(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e}function as(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e.includes(",")?e.split(",").map(t=>as(t.trim())):e}function ye(e,n){switch(n){case"boolean":return rc(e);case"number":return oc(e);case"array":return e.split(",").map(t=>In(t.trim()));case"string":default:return e}}function rc(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function oc(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let n=Number(e);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${e}" to number`);return n}function ce(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function sc(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 ic(e){let n=[],t=ac(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
21
+ `);return}if(t.every(oe)){dr(e,n,t.length,void 0,i.delimiter),e.push(" "),e.push(t.map(a=>H(a,i.delimiter)).join(i.delimiter)),e.push(`
22
+ `);return}let s=o?void 0:Zi(t,i,r+1);if(s!==void 0){dr(e,n,t.length,s.fields,i.delimiter),e.push(`
23
+ `);for(let a of t){Ke(e,r+1);let l=[];e.push(s.paths.map(d=>yr(hr(a,d.path),d,i.delimiter,i,l,r+2)).join(i.delimiter)),e.push(`
24
+ `),e.push(...l)}return}dr(e,n,t.length,void 0,i.delimiter),e.push(`
25
+ `);for(let a of t)Ke(e,r+1),ju(e,a,r+1,i)}function ju(e,n,t,r){if(ie(t,0,r),Array.isArray(n)){e.push("- "),pr(e,void 0,n,t,!0,r);return}if(A(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
26
+ `);return}e.push("- "),cr(e,o[0][0],o[0][1],t+1,r);for(let[i,s]of o.slice(1))Ke(e,t+1),cr(e,i,s,t+1,r);return}e.push("- ",H(n,r.delimiter),`
27
+ `)}function dr(e,n,t,r,o){n!==void 0&&e.push(N(n)),e.push("[",String(t),fr(o),"]"),r!==void 0&&e.push("{",r.map(i=>gr(i,o)).join(o),"}"),e.push(":")}function fr(e){return e===D?"":e}function Zi(e,n,t){let r=Ou(e,n);if(r!==void 0)return r;let o=ur(e.map(i=>({value:i})),n,t);return o===void 0?void 0:{fields:o,paths:mr(o)}}function Du(e,n,t){let r=Object.values(e);if(!(r.length<2))return Zi(r,n,t)}function ur(e,n,t){ie(t,0,n);let r=e[0]?.value;if(!A(r))return;let o=Object.keys(r).map(i=>({key:i}));if(o.length!==0){for(let{value:i}of e)if(!A(i)||Object.keys(i).length!==o.length||o.some(a=>!Object.prototype.hasOwnProperty.call(i,a.key)))return;for(let i of o){let s=e.map(({value:l})=>({value:l[i.key]}));if(s.every(({value:l})=>oe(l)))continue;if(n.primitiveArrayColumns&&s.every(({value:l})=>Array.isArray(l)&&l.every(oe))){i.listDelimiter=";";continue}if(n.objectArrayColumns&&s.every(({value:l})=>Array.isArray(l))){let l=es(s.map(({value:p})=>p));if(l!==void 0){i.fixedLength=l.fixedLength,i.fixedDelimiter=n.delimiter;continue}let d=ur(s.flatMap(({value:p})=>p.map(u=>({value:u}))),n,t+1);if(d!==void 0){i.children=d,i.childTable=!0;continue}}if(!n.nestedTabularHeaders)return;let a=ur(s,n,t+1);if(a===void 0)return;i.children=a}return o}}function Ou(e,n){if(!n.objectArrayColumns)return;let t=es(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:n.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function es(e){let n=e[0]?.length;if(!(!Number.isInteger(n)||n===0)&&e.every(t=>Array.isArray(t)&&t.length===n&&t.every(oe)))return{fixedLength:n}}function mr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.childTable===!0?[{path:r,childFields:t.children}]:t.fixedLength!==void 0?[{path:r,fixedLength:t.fixedLength}]:t.children===void 0?[{path:r,listDelimiter:t.listDelimiter}]:mr(t.children,r)})}function hr(e,n){let t=e;for(let r of n)t=t[r];return t}function gr(e,n){return e.listDelimiter!==void 0?`${N(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${N(e.key)}[${e.fixedLength}${fr(n)}]`:e.children===void 0?N(e.key):`${N(e.key)}{${e.children.map(t=>gr(t,n)).join(n)}}`}function yr(e,n,t,r,o,i){return n.childFields!==void 0?(Au(o,e,n.childFields,r,i),String(e.length)):n.fixedLength!==void 0?e.map(s=>H(s,t)).join(t):n.listDelimiter===void 0?H(e,t):e.map(s=>Lu(s,t,n.listDelimiter)).join(n.listDelimiter)}function Au(e,n,t,r,o){for(let i of n){Ke(e,o);let s=[];e.push(mr(t).map(a=>yr(hr(i,a.path),a,r.delimiter,r,s,o+1)).join(r.delimiter)),e.push(`
28
+ `),e.push(...s)}}function Lu(e,n,t){return typeof e!="string"?H(e,n):er(e,n)||e.includes(t)?Zn(e):e}var as=[D,"|"," "];var ds=8,cs=/^[A-Za-z0-9_-]+$/,Nb=new TextEncoder,Cb=new TextDecoder;function Nu(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw S(n,"invalid trailer count");return Number.parseInt(t,10)}function us(e,n){if(!cs.test(e))throw S(n,"invalid tag")}function Cu(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!cs.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw S(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function Mu(e,n){if(!e.startsWith("["))return null;let t=e.slice(1),r=t.indexOf("]");if(r===-1)throw S(n,"invalid header");let o=t.slice(0,r),i=o.startsWith("~"),s=i?o.slice(1):o;if(!i&&s.startsWith("="))return null;if(!as.includes(s)&&s!=="")throw S(n,"invalid header delimiter");let a=s===""?D:s,l=t.slice(r+1),d=null;if(!i&&l.startsWith("<")){let f=l.indexOf(">");if(f===-1)throw S(n,"invalid tag");if(d=l.slice(1,f),us(d,n),s!=="")throw S(n,"invalid header delimiter");l=l.slice(f+1)}if(!l.startsWith("{")||!l.endsWith("}:"))throw S(n,"invalid header");let p=l.slice(1,-2),u;try{u=G(p,a,n).map(f=>J(f,n)[0])}catch(f){throw Fe(f)}if(u.length===0||u.some(f=>f===""))throw S(n,"invalid header fields");return{delimiter:a,fields:u,fieldText:p,continuation:i,tag:d}}function Wu(e,n,t){if(e===null||e.delimiter===void 0)throw S(t,"continuation header before header");if(e.delimiter!==n.delimiter||e.fieldText!==n.fieldText)throw S(t,"continuation header mismatch")}function ns(e,n,t,r){let o;try{o=G(e,n,r)}catch(i){throw Fe(i)}if(o.length!==t)throw S(r,"row arity mismatch");for(let i of o)try{B(i,r)}catch(s){throw Fe(s)}return o}function Hu(e,n,t){let r={};return e.forEach((o,i)=>{try{Q(r,o,B(n[i],t))}catch(s){throw Fe(s)}}),r}function Fu(e,n,t){if(e.startsWith("- "))throw S(n,"reserved line prefix");let r=Nu(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw S(n,"trailer without header");if(t.rowCount!==r)throw S(n,"trailer count mismatch");return{kind:"trailer"}}let o=Mu(e,n);if(o!==null)return o.continuation?(Wu(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let i=Cu(e,n);if(i!==null){let s=t?.taggedLanes?.get(i.tag);if(s===void 0)throw S(n,"unknown tag");return{kind:"tagged-row",tag:i.tag,cells:ns(i.cellsText,s.delimiter,s.fields.length,n)}}if(t===null||t.delimiter===void 0)throw S(n,"row before header");return{kind:"row",cells:ns(e,t.delimiter,t.fields.length,n)}}function Uu(e,n={}){let t=[],r=new Map,o=[],i=[],s=null,a=!1,l=!1;function d(m,h){let b=i.at(-1);if(b!==void 0&&b.lane===m.lane&&b.delimiter===m.delimiter&&b.fieldText===m.fieldText){b.rows.push(h);return}i.push({lane:m.lane,delimiter:m.delimiter,fields:m.fields,fieldText:m.fieldText,rows:[h]})}function p(){s!==null&&o.push({delimiter:s.delimiter,fields:s.fields,fieldText:s.fieldText,lane:s.lane,rows:s.rows})}function u(m,h,b){let k=r.get(m);if(k===void 0){if(r.size>=ds)throw S(b,"too many tagged lanes");k={segments:[],current:null},r.set(m,k),t.push(m)}else k.current!==null&&k.segments.push(k.current);k.current={lane:m,delimiter:h.delimiter,fields:h.fields,fieldText:h.fieldText,rows:[]},k.delimiter=h.delimiter,k.fields=h.fields,k.fieldText=h.fieldText}if(Xn(e).forEach((m,h)=>{let b=h+1;if(m==="")return;let k=s===null?{taggedLanes:r}:{delimiter:s.delimiter,fields:s.fields,fieldText:s.fieldText,rowCount:s.rows.length,taggedLanes:r},w=Fu(m,b,k);if(w.kind==="trailer"){p(),s=null;return}if(w.kind!=="continuation"){if(w.kind==="tag-header"){l=!0,u(w.header.tag,w.header,b);return}if(w.kind==="header"){p(),a||(t.push(null),a=!0),s={lane:null,delimiter:w.header.delimiter,fields:w.header.fields,fieldText:w.header.fieldText,rows:[]};return}if(w.kind==="tagged-row"){l=!0;let j=r.get(w.tag).current;j.rows.push(w.cells),d(j,w.cells);return}if(s===null)throw S(b,"row before header");s.rows.push(w.cells),d(s,w.cells)}}),!l)return p(),n.preserveInterleaving===!0,o;let f=[];p();for(let m of t){if(m===null){f.push(...o);continue}let h=r.get(m);f.push(...h.segments),h.current!==null&&f.push(h.current)}return n.preserveInterleaving===!0?i:f}function ye(e){return Uu(e).flatMap(n=>n.rows.map(t=>Hu(n.fields,t,0)))}function Bu(e){if(!as.includes(e))throw S(0,"invalid header delimiter")}function ts(e,n,t=!1){return`[${`${t?"~":""}${e===D?"":e}`}]{${n}}:
29
+ `}function rs(e,n){return`[]<${e}>{${n}}:
30
+ `}function kr(e,n){return n.map(N).join(e)}function Vu(e){if(!Array.isArray(e)||e.length===0)throw S(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=J(String(n),0)}catch(r){throw Fe(r)}if(t==="")throw S(0,"TOONL header requires fields");return t})}function os(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function is(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw S(0,"TOONL continuation cadence must be positive")}function Ku(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function ss(e){if(e===null||typeof e!="object"||Array.isArray(e))throw S(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw S(0,"TOONL output requires object rows");if(n.some(t=>!oe(e[t])))throw S(0,"TOONL rows must be flat objects");return n}function qu(e){return JSON.stringify([...e].sort())}function ls(e,n){let t=qu(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function ue({delimiter:e=D,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){Bu(e),is(t),is(r);let o=null,i="",s=new Map,a=0,l=0,d=0,p=new Map,u=!1,f={continuationEveryRows:t,continuationEveryBytes:r},m=()=>o===null||!n?"":`[=${a}]
31
+ `,h=()=>Ku(f,l,d)?(l=0,d=0,ts(e,i,!0)):"",b=k=>{us(k,0);let w=p.get(k);if(w===void 0){if(p.size>=ds)throw S(0,"too many tagged lanes");w={fields:null,fieldsByShape:new Map},p.set(k,w)}return w};return{push(k){if(u)throw S(0,"TOONL encoder is closed");let w=ls(ss(k),s),j="";(o===null||o.length!==w.length||o.some((we,Te)=>we!==w[Te]))&&(j+=m(),o=w,i=kr(e,o),a=0,l=0,d=0,j+=ts(e,i));let ee=o.map(we=>H(k[we],e));j+=h();let q=`${ee.join(e)}
32
+ `;return j+=q,a+=1,l+=1,d+=q.length,j},declareLane(k,w){if(u)throw S(0,"TOONL encoder is closed");let j=Vu(w),ee=kr(D,j),q=b(k);return os(q.fields,j)?"":(q.fields=j,rs(k,ee))},pushTagged(k,w){if(u)throw S(0,"TOONL encoder is closed");let j=b(k),ee=ls(ss(w),j.fieldsByShape),q=kr(D,ee),we=ee.map(Cn=>H(w[Cn],D)),Te="";return os(j.fields,ee)||(j.fields=ee,Te+=rs(k,q)),`${Te}${k}:${we.join(D)}
33
+ `},end(){return u?"":(u=!0,m())}}}function Rr(e){let n={app:e,version:Ju(qe("__RED_BUILD_VERSION__",()=>"3.3.10")??"0.0.0-dev"),gitSha:qe("__RED_BUILD_GIT_SHA__",()=>"efacf48c6512520601e438c4e755e96b51509e23")??"unknown",buildTime:qe("__RED_BUILD_TIME__",()=>"2026-08-02T23:09:28-03:00")??"unknown",bundleAsset:qe("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=qe("__REDDB_SDK_VERSION__",()=>""),r=qe("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function Ju(e){return e.startsWith("v")?e.slice(1):e}function ps(e){return`${e.app} ${e.version} ${e.gitSha}`}function qe(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var fs={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Gu=/^[a-z][a-z0-9+.-]*:\/\//i;function Qu(e,n){return typeof n=="string"?{separator:e,to:n,typed:!1,prefix:!1}:{separator:e,to:n.to,typed:n.typed??!1,prefix:n.prefix??!1}}function zu(e=fs){return Object.entries(e).map(([n,t])=>Qu(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function Yu(e){return/^-\d+(\.\d+)?$/.test(e)}function kn(e){return!(!e||e.startsWith("-")&&!Yu(e))}function it(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e}function ms(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e.includes(",")?e.split(",").map(t=>ms(t.trim())):e}function Ee(e,n){switch(n){case"boolean":return Xu(e);case"number":return Zu(e);case"array":return e.split(",").map(t=>it(t.trim()));case"string":default:return e}}function Xu(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function Zu(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let n=Number(e);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${e}" to number`);return n}function ke(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function ep(e,n={}){return e.map(t=>{let r=n[t.type];return r?r(t.value):t.value}).join("")}function E(e,n){return{type:e,value:n}}function np(e){let n=[],t=rp(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
28
34
  `),E("newline",`
29
35
  `)),e.positional&&e.positional.length>0){n.push(E("section-header","Arguments:"),E("newline",`
30
36
  `));for(let r of e.positional)if(r.description){let o=r.variadic?`${r.name}...`:r.name;n.push(E("indent"," "),E("positional-name",`<${o}>`)),r.required||n.push(E("positional-optional"," (optional)")),n.push(E("newline",`
31
37
  `),E("indent"," "),E("option-description",r.description),E("newline",`
32
38
  `))}n.push(E("newline",`
33
39
  `))}if(e.options&&Object.keys(e.options).length>0){n.push(E("section-header","Options:"),E("newline",`
34
- `));let r=dc(e.options);n.push(...r)}return n}function lc(e,n){let t=ic(e);return sc(t,n)}function ac(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 dc(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=[],m=b=>{p.includes(b)||p.push(b)};u.short&&m(`-${u.short}`),m(`--${c}`);for(let b of u.aliases??[])b.length===1?m(`-${b}`):m(`--${b}`);let g=p.join(", "),y=u.type&&u.type!=="boolean"?`<${u.type}>`:void 0;r.push({flags:g,type:y,desc:u.description??"",default:u.default!==void 0?String(u.default):void 0})}let a=Math.max(...r.map(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 ds(e){let n=hc(e.options??{},e.autoShort??!1),t=nc(e.separators??ls);return{schema:e,parse(r){return cc(r,e,n,t)},help(){return lc(e,e.formatter)}}}function cc(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 m=l[i];if(m.variadic){let g=[];for(;a<e.length;){let y=e[a];g.push(m.type?ye(y,m.type):y),a++}o.positional[m.name]=g,i++}else{let g=m.type?ye(u,m.type):u;o.positional[m.name]=g,i++,a++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(u)),a++;continue}if(u.startsWith("--")){a=fc(u,a,e,o,t,n);continue}if(u.startsWith("-")&&u.length>1&&!_c(u)){a=gc(u,a,e,o,t,n);continue}let p=uc(u,r);if(p){let{key:m,value:g,config:y}=p,b=o,k=b[y.to]??(b[y.to]={});k[m]=y.typed?as(g):ce(g),a++;continue}if(i<l.length){let m=l[i];if(m.variadic){let y=[];for(;a<e.length&&!e[a].startsWith("-");){let b=e[a];y.push(m.type?ye(b,m.type):b),a++}o.positional[m.name]=y,i++;continue}let g=m.type?ye(u,m.type):u;o.positional[m.name]=g,i++}else n.allowUnknown!==!1?o.rest.push(u):o.errors.push(`Unexpected positional argument: ${u}`);a++}return kc(o,n,t),Rc(o,n,l),bc(o,n,t),o}function uc(e,n){if(Xd.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(pc(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(mc(o,s,t))return{key:o,value:s,config:t}}}return null}function pc(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function mc(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 fc(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 Tn(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)?Tn(l.name,a,n+2,r,o,s):(r.errors.push(`Option --${i} requires a value`),n+1)}return r.options[l.name]=!0,n+1}return s.strict?r.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(r.options[i]=!0),n+1}function gc(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=Ft(a,o);return u?Tn(u.name,c,n+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=In(ce(c))),n+1)}if(i.length===1){let l=Ft(i,o);if(l){if(l.type!=="boolean"){let a=t[n+1];return nn(a)?Tn(l.name,a,n+2,r,o,s):(r.errors.push(`Option -${i} requires a value`),n+1)}return r.options[l.name]=!0,n+1}if(s.strict)r.errors.push(`Unknown option: -${i}`);else if(s.allowUnknown!==!1){let a=t[n+1];if(nn(a))return r.options[i]=In(ce(a)),n+2;r.options[i]=!0}return n+1}for(let l of i){let a=Ft(l,o);a?a.type==="boolean"?r.options[a.name]=!0:r.errors.push(`Option -${l} requires a value`):s.strict?r.errors.push(`Unknown option: -${l}`):s.allowUnknown!==!1&&(r.options[l]=!0)}return n+1}function Tn(e,n,t,r,o,s){let i=o.get(e);if(i){if(i.choices){let a=i.type?ye(ce(n),i.type):ce(n);if(!i.choices.includes(a))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${i.choices.join(", ")}`),t}let l=i.type?ye(ce(n),i.type):ce(n);if(i.type==="array"){let a=r.options[e];Array.isArray(a)?a.push(...l):r.options[e]=l}else r.options[e]=l}else s.strict?r.errors.push(`Unknown option: --${e}`):s.allowUnknown!==!1&&(r.options[e]=In(ce(n)));return t}function hc(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=yc(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 yc(e,n){for(let t of e){if(!/[a-zA-Z]/.test(t))continue;let r=t.toLowerCase();if(!n.has(r))return r;let o=t.toUpperCase();if(!n.has(o))return o}return""}function Ft(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function kc(e,n,t){for(let r of t.values())if(e.options[r.name]===void 0)if(r.env&&process.env[r.env]!==void 0){let o=process.env[r.env];e.options[r.name]=r.type?ye(o,r.type):o}else r.default!==void 0&&(e.options[r.name]=r.default);for(let r of n.positional??[])e.positional[r.name]===void 0&&r.default!==void 0&&(e.positional[r.name]=r.default)}function Rc(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 bc(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 _c(e){return/^-\d+(\.\d+)?$/.test(e)}var Ut=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 wc(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 vc(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 ke(e,n,t={}){let o=ds({options:wc(n),separators:{},allowUnknown:!0}).parse([...e]),s={},i=vc(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 Ut(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 Ht=class extends Error{token;known;constructor(n,t){super(`unknown command '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownCommandError",this.token=n,this.known=t}};function cs(e,n){let[t,...r]=e;if(t!==void 0){for(let[s,i]of Object.entries(n.commands))if(t===s||(i.aliases??[]).includes(t))return{command:s,args:r};if(n.errorOnUnknownCommand&&!t.startsWith("-"))throw new Ht(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as Ic,mkdirSync as Tc,readFileSync as bs,statSync as Nc}from"node:fs";import{dirname as ws,join as Wc}from"node:path";var us="RED_WORKER_SCOPE",ps="RED_WORKER_MEMORY_CEILING",ms="RED_WORKER_SCOPE_DEGRADATION",Bt={scope:null,memory_ceiling:null,scope_degradation:null};function Kt(e){return{scope:Vt(e[us]),memory_ceiling:Vt(e[ps]),scope_degradation:Vt(e[ms])}}function tn(e){let n={};return e.scope!=null&&e.scope!==""&&(n[us]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[ps]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[ms]=e.scope_degradation),n}function Vt(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as Ec,readdirSync as Pc,readFileSync as ys,rmSync as jc,writeFileSync as Dc}from"node:fs";import{basename as Oc,join as $e}from"node:path";import{isAbsolute as pk,join as Nn,resolve as mk}from"node:path";function Sc(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var fs="deaths",gs="deaths.toonl";function Wn(e){return Nn(Sc(e),fs)}function rn(e){return Nn(Wn(e),gs)}var on="live",hs="attributions.toonl";function Mn(e){return Nn(Wn(e),on)}function Jt(e){return Nn(Wn(e),hs)}var Gt=$e("sys","kernel","random","boot_id"),ks=1;function zt(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:ks,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:Rs($e(t,Gt)),cgroup:$c(t,r),last_phase:e.last_phase}}function Rs(e){try{let n=ys(e,"utf8").trim();return n===""?null:n}catch{return null}}function $c(e,n){let t=Rs($e(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
36
- `),o=r.find(i=>i.startsWith("0::"));if(o)return o.slice(3)||null;let s=r[0]?.split(":").slice(2).join(":");return s===void 0||s===""?null:s}function Qt(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function Yt(e,n){let t=$e(e,Qt(n));try{return Ec(e,{recursive:!0,mode:448}),Dc(t,te({trailer:!1}).push(Ac(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function Re(e,n){try{jc($e(e,Qt(n)),{force:!0})}catch{}}function Zt(e,n){let t;try{t=Pc(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=$e(e,o);try{let l=de(ys(s,"utf8"))[0];if(l===void 0)throw new Error("anchor holds no record");r.push(Lc(l))}catch(i){n?.(Oc(s),i instanceof Error?i.message:String(i))}}return r}function Lc(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:qt(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:qt(e.pid),ppid:qt(e.ppid),boot_id:e.boot_id==null?null:String(e.boot_id),cgroup:e.cgroup==null?null:String(e.cgroup),last_phase:String(e.last_phase)}}function qt(e){return typeof e=="number"?e:Number(e)}function Ac(e){return{...e}}var Mc=1,Cc=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Fc(e){return typeof e=="string"&&Cc.has(e)}var Uc="startup";function Hc(e,n){return{...e.scope??Bt,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 Vc(e){let n=e.resourceUsage();return{uptime_s:Math.round(e.uptime()),rss_kb:Math.round(e.memoryUsage().rss/1024),max_rss_kb:n.maxRSS,user_cpu_us:n.userCPUTime,system_cpu_us:n.systemCPUTime,minor_page_faults:n.minorPageFault,major_page_faults:n.majorPageFault,voluntary_ctx_switches:n.voluntaryContextSwitches,involuntary_ctx_switches:n.involuntaryContextSwitches}}var er={mkdir(e){Tc(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=Nc(e).size}catch{return!0}if(n===0)return!0;try{return bs(e,"utf8").endsWith(`
37
- `)}catch{return!0}},append(e,n){Ic(e,n,{encoding:"utf8",mode:384})},read(e){return bs(e,"utf8")}};function Bc(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function Kc(e,n,t=er){let r=te({trailer:!1}).push(Bc(n));return t.mkdir(ws(e)),t.endsClean(e)||t.append(e,`
38
- `),t.append(e,r),n}function vs(e){let n=e.endsWith(`
40
+ `));let r=op(e.options);n.push(...r)}return n}function tp(e,n){let t=np(e);return ep(t,n)}function rp(e){let n=["[options]"];if(e.positional)for(let t of e.positional)t.variadic?n.push(t.required?`<${t.name}...>`:`[${t.name}...]`):n.push(t.required?`<${t.name}>`:`[${t.name}]`);return n.join(" ")}function op(e,n=!1){let t=[],r=[],o=n?"global-option-flag":"option-flag",i=n?"global-option-type":"option-type",s=n?"global-option-default":"option-default",a=n?"global-option-description":"option-description";for(let[d,p]of Object.entries(e)){if(p.hidden)continue;let u=[],f=b=>{u.includes(b)||u.push(b)};p.short&&f(`-${p.short}`),f(`--${d}`);for(let b of p.aliases??[])b.length===1?f(`-${b}`):f(`--${b}`);let m=u.join(", "),h=p.type&&p.type!=="boolean"?`<${p.type}>`:void 0;r.push({flags:m,type:h,desc:p.description??"",default:p.default!==void 0?String(p.default):void 0})}let l=Math.max(...r.map(d=>d.flags.length+(d.type?d.type.length+1:0)),20);for(let d of r){let p=d.flags.length+(d.type?d.type.length+1:0),u=" ".repeat(l-p+2);t.push(E("indent"," ")),t.push(E(o,d.flags)),d.type&&(t.push(E("text"," ")),t.push(E(i,d.type))),t.push(E("text",u)),t.push(E(a,d.desc)),d.default!==void 0&&(t.push(E("text"," ")),t.push(E(s,`(default: ${d.default})`))),t.push(E("newline",`
41
+ `))}return t}function hs(e){let n=up(e.options??{},e.autoShort??!1),t=zu(e.separators??fs);return{schema:e,parse(r){return ip(r,e,n,t)},help(){return tp(e,e.formatter)}}}function ip(e,n,t,r){let o={positional:{},options:{},errors:[],rest:[]},i=new Set(r.map(p=>p.to));for(let p of i)o[p]={};let s=0,a=n.positional??[],l=0,d=!1;for(;l<e.length;){let p=e[l];if(n.stopEarly&&s>0){o.rest=e.slice(l);break}if(p==="--"&&!d){d=!0,l++;continue}if(d){if(s<a.length){let f=a[s];if(f.variadic){let m=[];for(;l<e.length;){let h=e[l];m.push(f.type?Ee(h,f.type):h),l++}o.positional[f.name]=m,s++}else{let m=f.type?Ee(p,f.type):p;o.positional[f.name]=m,s++,l++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(p)),l++;continue}if(p.startsWith("--")){l=dp(p,l,e,o,t,n);continue}if(p.startsWith("-")&&p.length>1&&!gp(p)){l=cp(p,l,e,o,t,n);continue}let u=sp(p,r);if(u){let{key:f,value:m,config:h}=u,b=o,k=b[h.to]??(b[h.to]={});k[f]=h.typed?ms(m):ke(m),l++;continue}if(s<a.length){let f=a[s];if(f.variadic){let h=[];for(;l<e.length&&!e[l].startsWith("-");){let b=e[l];h.push(f.type?Ee(b,f.type):b),l++}o.positional[f.name]=h,s++;continue}let m=f.type?Ee(p,f.type):p;o.positional[f.name]=m,s++}else n.allowUnknown!==!1?o.rest.push(p):o.errors.push(`Unexpected positional argument: ${p}`);l++}return fp(o,n,t),mp(o,n,a),hp(o,n,t),o}function sp(e,n){if(Gu.test(e))return null;for(let t of n){if(t.prefix&&e.startsWith(t.separator)){let o=e.slice(t.separator.length),i=o.indexOf(":");if(i>0){let s=o.slice(0,i),a=o.slice(i+1);if(lp(s))return{key:s,value:a,config:t}}continue}let r=e.indexOf(t.separator);if(r>0){let o=e.slice(0,r),i=e.slice(r+t.separator.length);if(ap(o,i,t))return{key:o,value:i,config:t}}}return null}function lp(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function ap(e,n,t){return e?t.separator===":"?e.includes("/")||e.includes(".")||/^\d+$/.test(n)?!1:/^[A-Z][a-zA-Z0-9-]*$/.test(e):!((t.separator==="="||t.separator===":=")&&e.includes("/")):!1}function dp(e,n,t,r,o,i){let s=e.slice(2);if(s.startsWith("no-")){let l=s.slice(3),d=o.get(l);if(d?.negatable!==!1&&d?.type==="boolean")return r.options[d.name]=!1,n+1}if(s.includes("=")){let l=s.indexOf("="),d=s.slice(0,l),p=s.slice(l+1);return st(d,p,n+1,r,o,i)}let a=o.get(s);if(a){if(a.type!=="boolean"){let l=t[n+1];return kn(l)?st(a.name,l,n+2,r,o,i):(r.errors.push(`Option --${s} requires a value`),n+1)}return r.options[a.name]=!0,n+1}return i.strict?r.errors.push(`Unknown option: --${s}`):i.allowUnknown!==!1&&(r.options[s]=!0),n+1}function cp(e,n,t,r,o,i){let s=e.slice(1);if(s.includes("=")){let a=s.indexOf("="),l=s.slice(0,a),d=s.slice(a+1),p=br(l,o);return p?st(p.name,d,n+1,r,o,i):(i.strict?r.errors.push(`Unknown option: -${l}`):i.allowUnknown!==!1&&(r.options[l]=it(ke(d))),n+1)}if(s.length===1){let a=br(s,o);if(a){if(a.type!=="boolean"){let l=t[n+1];return kn(l)?st(a.name,l,n+2,r,o,i):(r.errors.push(`Option -${s} requires a value`),n+1)}return r.options[a.name]=!0,n+1}if(i.strict)r.errors.push(`Unknown option: -${s}`);else if(i.allowUnknown!==!1){let l=t[n+1];if(kn(l))return r.options[s]=it(ke(l)),n+2;r.options[s]=!0}return n+1}for(let a of s){let l=br(a,o);l?l.type==="boolean"?r.options[l.name]=!0:r.errors.push(`Option -${a} requires a value`):i.strict?r.errors.push(`Unknown option: -${a}`):i.allowUnknown!==!1&&(r.options[a]=!0)}return n+1}function st(e,n,t,r,o,i){let s=o.get(e);if(s){if(s.choices){let l=s.type?Ee(ke(n),s.type):ke(n);if(!s.choices.includes(l))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${s.choices.join(", ")}`),t}let a=s.type?Ee(ke(n),s.type):ke(n);if(s.type==="array"){let l=r.options[e];Array.isArray(l)?l.push(...a):r.options[e]=a}else r.options[e]=a}else i.strict?r.errors.push(`Unknown option: --${e}`):i.allowUnknown!==!1&&(r.options[e]=it(ke(n)));return t}function up(e,n=!1){let t=new Map,r=Object.entries(e).sort(([i],[s])=>i.localeCompare(s)),o=new Set;for(let[,i]of r)i.short&&o.add(i.short);for(let[i,s]of r){let a=s.short??"";n&&!a&&(a=pp(i,o),a&&o.add(a));let l={name:i,short:a,aliases:s.aliases??[],type:s.type??"string",description:s.description??"",required:s.required??!1,hidden:s.hidden??!1,negatable:s.negatable??!0,default:s.default,choices:s.choices,env:s.env,validate:s.validate};t.set(i,l);for(let d of l.aliases)t.set(d,l)}return t}function pp(e,n){for(let t of e){if(!/[a-zA-Z]/.test(t))continue;let r=t.toLowerCase();if(!n.has(r))return r;let o=t.toUpperCase();if(!n.has(o))return o}return""}function br(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function fp(e,n,t){for(let r of t.values())if(e.options[r.name]===void 0)if(r.env&&process.env[r.env]!==void 0){let o=process.env[r.env];e.options[r.name]=r.type?Ee(o,r.type):o}else r.default!==void 0&&(e.options[r.name]=r.default);for(let r of n.positional??[])e.positional[r.name]===void 0&&r.default!==void 0&&(e.positional[r.name]=r.default)}function mp(e,n,t){if(n.options)for(let[r,o]of Object.entries(n.options))o.required&&e.options[r]===void 0&&e.errors.push(`Missing required option: --${r}`);for(let r of t)r.required&&e.positional[r.name]===void 0&&e.errors.push(`Missing required argument: <${r.name}>`)}function hp(e,n,t){for(let r of t.values()){let o=e.options[r.name];if(r.validate&&o!==void 0){let i=r.validate(o);i!==!0&&e.errors.push(i)}}for(let r of n.positional??[]){let o=e.positional[r.name];if(r.validate&&o!==void 0){let i=r.validate(o);i!==!0&&e.errors.push(i)}}}function gp(e){return/^-\d+(\.\d+)?$/.test(e)}var _r=class extends Error{flag;known;constructor(n,t){super(`unknown flag '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownFlagError",this.flag=n,this.known=t}};function yp(e){let n={};for(let[t,r]of Object.entries(e))n[t]={type:r.kind==="boolean"?"boolean":"string",...t.length===1?{short:t}:{},...r.aliases===void 0?{}:{aliases:r.aliases}};return n}function kp(e,n){let t=new Map;for(let[o,i]of Object.entries(n))if(!(i.kind!=="value"||i.type!=="array")){t.set(o,o);for(let s of i.aliases??[])t.set(s,o)}let r=new Map;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="--")break;let s=i.match(/^--([^=]+)(?:=(.*))?$/)??i.match(/^-([^=])(?:=(.*))?$/);if(s===null)continue;let a=t.get(s[1]);if(a===void 0)continue;let l=s[2];if(l===void 0&&kn(e[o+1])&&(l=e[o+1],o+=1),l===void 0)continue;let d=r.get(a)??[];d.push(l),r.set(a,d)}return r}function Pe(e,n,t={}){let o=hs({options:yp(n),separators:{},allowUnknown:!0}).parse([...e]),i={},s=kp(e,n),a=o.errors.find(l=>/^Option --?\S+ requires a value$/.test(l));if(a!==void 0)throw new Error(a.replace(/^Option /,""));if(o.errors.length>0)throw new Error(o.errors[0]);if(t.unknownFlags==="error"){let l=new Set(Object.keys(n));for(let d of Object.keys(o.options))if(!l.has(d))throw new _r(d.length===1?`-${d}`:`--${d}`,Object.keys(n).map(p=>p.length===1?`-${p}`:`--${p}`))}for(let[l,d]of Object.entries(n)){let p=o.options[l];p!==void 0&&(d.kind==="boolean"?i[l]=p:d.type==="array"?i[l]=(s.get(l)??[]).map(u=>d.coerce(u)):i[l]=d.coerce(String(p)))}return{values:i,positionals:o.rest}}var wr=class extends Error{token;known;constructor(n,t){super(`unknown command '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownCommandError",this.token=n,this.known=t}};function gs(e,n){let[t,...r]=e;if(t!==void 0){for(let[i,s]of Object.entries(n.commands))if(t===i||(s.aliases??[]).includes(t))return{command:i,args:r};if(n.errorOnUnknownCommand&&!t.startsWith("-"))throw new wr(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as Dp,mkdirSync as Op,readFileSync as Es,statSync as Ap}from"node:fs";import{dirname as js,join as Lp}from"node:path";var ys="RED_WORKER_SCOPE",ks="RED_WORKER_MEMORY_CEILING",Rs="RED_WORKER_SCOPE_DEGRADATION",Sr={scope:null,memory_ceiling:null,scope_degradation:null};function vr(e){return{scope:xr(e[ys]),memory_ceiling:xr(e[ks]),scope_degradation:xr(e[Rs])}}function Rn(e){let n={};return e.scope!=null&&e.scope!==""&&(n[ys]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[ks]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[Rs]=e.scope_degradation),n}function xr(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as _p,readdirSync as wp,readFileSync as xs,rmSync as xp,writeFileSync as Sp}from"node:fs";import{basename as vp,join as Je}from"node:path";import{isAbsolute as g_,join as lt,resolve as y_}from"node:path";function Rp(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var bs="deaths",_s="deaths.toonl";function at(e){return lt(Rp(e),bs)}function bn(e){return lt(at(e),_s)}var _n="live",ws="attributions.toonl";function dt(e){return lt(at(e),_n)}function Er(e){return lt(at(e),ws)}var jr=Je("sys","kernel","random","boot_id"),Ss=1;function Dr(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:Ss,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:vs(Je(t,jr)),cgroup:Ep(t,r),last_phase:e.last_phase}}function vs(e){try{let n=xs(e,"utf8").trim();return n===""?null:n}catch{return null}}function Ep(e,n){let t=vs(Je(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
42
+ `),o=r.find(s=>s.startsWith("0::"));if(o)return o.slice(3)||null;let i=r[0]?.split(":").slice(2).join(":");return i===void 0||i===""?null:i}function Or(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function Ar(e,n){let t=Je(e,Or(n));try{return _p(e,{recursive:!0,mode:448}),Sp(t,ue({trailer:!1}).push(jp(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function je(e,n){try{xp(Je(e,Or(n)),{force:!0})}catch{}}function Lr(e,n){let t;try{t=wp(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let i=Je(e,o);try{let a=ye(xs(i,"utf8"))[0];if(a===void 0)throw new Error("anchor holds no record");r.push(Pp(a))}catch(s){n?.(vp(i),s instanceof Error?s.message:String(s))}}return r}function Pp(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:Pr(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:Pr(e.pid),ppid:Pr(e.ppid),boot_id:e.boot_id==null?null:String(e.boot_id),cgroup:e.cgroup==null?null:String(e.cgroup),last_phase:String(e.last_phase)}}function Pr(e){return typeof e=="number"?e:Number(e)}function jp(e){return{...e}}var $p=1,Ip=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Tp(e){return typeof e=="string"&&Ip.has(e)}var Np="startup";function Cp(e,n){return{...e.scope??Sr,version:$p,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,exit_path:e.exit_path,signal:e.signal??null,exit_code:e.exit_code??null,last_phase:e.last_phase,detail:e.detail??null,...n}}function Mp(e){let n=e.resourceUsage();return{uptime_s:Math.round(e.uptime()),rss_kb:Math.round(e.memoryUsage().rss/1024),max_rss_kb:n.maxRSS,user_cpu_us:n.userCPUTime,system_cpu_us:n.systemCPUTime,minor_page_faults:n.minorPageFault,major_page_faults:n.majorPageFault,voluntary_ctx_switches:n.voluntaryContextSwitches,involuntary_ctx_switches:n.involuntaryContextSwitches}}var Ir={mkdir(e){Op(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=Ap(e).size}catch{return!0}if(n===0)return!0;try{return Es(e,"utf8").endsWith(`
43
+ `)}catch{return!0}},append(e,n){Dp(e,n,{encoding:"utf8",mode:384})},read(e){return Es(e,"utf8")}};function Wp(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function Hp(e,n,t=Ir){let r=ue({trailer:!1}).push(Wp(n));return t.mkdir(js(e)),t.endsClean(e)||t.append(e,`
44
+ `),t.append(e,r),n}function Ds(e){let n=e.endsWith(`
39
45
  `)?e:e.slice(0,e.lastIndexOf(`
40
- `)+1);return n===""?[]:de(n).map(Jc)}function Jc(e){let n=e.exit_path;if(!Fc(n))throw new Error(`death record has unknown exit_path ${JSON.stringify(n)}`);let t=e.kind;if(t!=="launcher"&&t!=="worker"&&t!=="daemon")throw new Error(`death record has unknown kind ${JSON.stringify(t)}`);return{version:N(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:N(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:N(e.exit_code),last_phase:String(e.last_phase),detail:e.detail==null?null:String(e.detail),scope:e.scope==null?null:String(e.scope),memory_ceiling:e.memory_ceiling==null?null:String(e.memory_ceiling),scope_degradation:e.scope_degradation==null?null:String(e.scope_degradation),uptime_s:N(e.uptime_s),rss_kb:N(e.rss_kb),max_rss_kb:N(e.max_rss_kb),user_cpu_us:N(e.user_cpu_us),system_cpu_us:N(e.system_cpu_us),minor_page_faults:N(e.minor_page_faults),major_page_faults:N(e.major_page_faults),voluntary_ctx_switches:N(e.voluntary_ctx_switches),involuntary_ctx_switches:N(e.involuntary_ctx_switches)}}function N(e){return typeof e=="number"?e:Number(e)}function Ss(e,n=er){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return vs(t)}var qc=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],Xt=null;function xs(e){let n=e.host??process,t=e.io??er,r=e.clock??(()=>new Date().toISOString()),o=n.pid,s=e.scope??Kt(process.env),i=e.phase??Uc,l=null,a=e.presenceDir===void 0?Wc(ws(e.lanePath),on):e.presenceDir,c=null,u=()=>{a!==null&&(c=zt({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),Yt(a,c))},p=k=>{if(!l){try{l=Kc(e.lanePath,Hc({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...k},Vc(n)),t)}catch{}a!==null&&c!==null&&Re(a,c)}},m={signal(k){p({exit_path:"signal",signal:k})},exit(k){p({exit_path:"exit",exit_code:k})},uncaughtException(k){p({exit_path:"uncaught-exception",detail:_s(k)})},unhandledRejection(k){p({exit_path:"unhandled-rejection",detail:_s(k)})}},y=[...(e.signals??qc).map(k=>{let _=()=>{if(m.signal(k),!(n.listenerCount?.(k)!==1||!n.kill)){n.off(k,_);try{n.kill(o,k)}catch{}}};return[k,_]}),["uncaughtException",(...k)=>m.uncaughtException(k[0])],["unhandledRejection",(...k)=>m.unhandledRejection(k[0])],["exit",(...k)=>m.exit(typeof k[0]=="number"?k[0]:null)]];for(let[k,_]of y)n.on(k,_);let b={lanePath:e.lanePath,phase(k){i=k,l||u()},currentPhase:()=>i,written:()=>l,uninstall(){for(let[k,_]of y)n.off(k,_);a!==null&&c!==null&&Re(a,c),Xt===b&&(Xt=null)},handlers:m};return e.setActive!==!1&&(Xt=b),u(),b}function _s(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Gc,readdirSync as zc,readFileSync as Cn,statSync as Qc,writeFileSync as Yc}from"node:fs";import{join as Ds}from"node:path";var Zc=1,Xc=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],eu=512*1024;function nu(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??Xc,r=[],o=Ds(n,Gt),s=null;try{let a=Cn(o,"utf8").trim();s=a===""?null:a,r.push({source:o,result:s?"read":"empty",detail:s})}catch(a){r.push({source:o,result:nr(a),detail:null})}let i=new Set;try{for(let a of zc(n))/^\d+$/.test(a)&&i.add(Number(a));r.push({source:n,result:"read",detail:`${i.size} live pids`})}catch(a){r.push({source:n,result:nr(a),detail:null})}let l=[];for(let a of t)try{let u=tu(a,e.tailBytes??eu).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:nr(c),detail:null})}return{boot_id:s,live_pids:i,journal:l,probes:r}}function nr(e){return e.code==="ENOENT"?"absent":"unreadable"}function tu(e,n){let t=Qc(e).size,r=Cn(e,"utf8");return t<=n?r:r.slice(r.length-n)}var ru=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,ou=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,su=/Killed (\/\S*) due to memory pressure/,iu=/\bopid=(\d+)\b/,Es=/\bsig=(\d+)\b/,lu=/\buid=(\d+)\b/,au=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,du={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function cu(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,s=[...n.probes.map(p=>`${p.source}: ${p.result}${p.detail?` (${p.detail})`:""}`),`boot id: anchored under ${e.boot_id??"unknown"}, host now ${n.boot_id??"unknown"} (${o?"changed":"same"})`,`parent account: ppid ${e.ppid}`,`cgroup: ${e.cgroup??"unknown"}`],i=(p,m,g,y)=>({version:Zc,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:p,confidence:m,signal:g,host_boot_changed:o,evidence:y,checked:s}),l=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],a=n.journal.find(p=>Ps(p,e.pid,ru)||Ps(p,e.pid,ou));if(a!==void 0)return i("oomd",o?"medium":"high","SIGKILL",[a,...l]);if(e.cgroup!==null)for(let p of n.journal){let m=su.exec(p)?.[1];if(m!==void 0){if(m===e.cgroup)return i("oomd",o?"medium":"high","SIGKILL",[p,...l]);if(e.cgroup.startsWith(`${m}/`))return i("oomd","medium","SIGKILL",[p,`the killed scope ${m} is an ancestor of this process's ${e.cgroup}`,...l])}}let c=n.journal.find(p=>Number(iu.exec(p)?.[1])===e.pid&&Es.test(p));if(c!==void 0){let p=Number(Es.exec(c)?.[1]),m=lu.exec(c)?.[1];return i("user-signal",o?"medium":"high",du[p]??null,[c,...m===void 0?[]:[`sent by uid ${m}`],...l])}let u=t.find(p=>p.pid===e.ppid);if(u!==void 0&&!n.live_pids.has(e.ppid))return i("parent-death","medium",null,[`parent pid ${e.ppid} (${u.kind} ${u.id}) recorded its own death at ${u.ts} via ${u.exit_path}${u.signal?` ${u.signal}`:""}`]);if(o){let p=n.journal.find(m=>au.test(m));return p!==void 0?i("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,p]):i("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,"no shutdown record on any journal read: the host stopped without announcing it (a freeze or a power loss, not an orderly teardown)"])}return i("unknown","none",null,[])}function Ps(e,n,t){return Number(t.exec(e)?.[1])===n}var uu=" | ";function js(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(uu)}function pu(e){return{version:e.version,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.last_seen,last_phase:e.last_phase,sender_class:e.sender_class,confidence:e.confidence,signal:e.signal,host_boot_changed:e.host_boot_changed,evidence:js(e.evidence),checked:js(e.checked)}}function mu(e){let n=te({trailer:!1});return e.map(t=>n.push(pu(t))).join("")}function Os(e){let n=Mn(e.stateRoot),t=Jt(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??nu({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=Zt(n,p=>s.push(p)),l=Ss(rn(e.stateRoot)),a=[],c=[],u=[];for(let p of i){if(o.live_pids.has(p.pid)){c.push(p);continue}if(l.find(g=>g.pid===p.pid&&g.id===p.id)!==void 0){u.push(p),Re(n,p);continue}a.push(cu(p,o,l,r())),Re(n,p)}return a.length>0&&fu(t,a),{attributions:a,alive:c,self_recorded:u,skipped:s,laneText:()=>{try{return Cn(t,"utf8")}catch{return""}}}}function $s(e){let n=e.skipped.length===0?"":` | unreadable anchors=${e.skipped.join(",")}`;if(e.attributions.length===0)return`death reaper: no un-recorded deaths (live=${e.alive.length} self-recorded=${e.self_recorded.length})${n}`;let t=e.attributions.map(r=>` | ${r.kind} ${r.id} pid=${r.pid} ${r.sender_class}/${r.confidence} phase=${r.last_phase}`+(r.evidence[0]?` evidence="${r.evidence[0]}"`:"")).join("");return`death reaper: attributed ${e.attributions.length}${t}${n}`}function fu(e,n){try{Gc(Ds(e,".."),{recursive:!0,mode:448});let t=gu(e),r=t===""||t.endsWith(`
46
+ `)+1);return n===""?[]:ye(n).map(Fp)}function Fp(e){let n=e.exit_path;if(!Tp(n))throw new Error(`death record has unknown exit_path ${JSON.stringify(n)}`);let t=e.kind;if(t!=="launcher"&&t!=="worker"&&t!=="daemon")throw new Error(`death record has unknown kind ${JSON.stringify(t)}`);return{version:V(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:V(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:V(e.exit_code),last_phase:String(e.last_phase),detail:e.detail==null?null:String(e.detail),scope:e.scope==null?null:String(e.scope),memory_ceiling:e.memory_ceiling==null?null:String(e.memory_ceiling),scope_degradation:e.scope_degradation==null?null:String(e.scope_degradation),uptime_s:V(e.uptime_s),rss_kb:V(e.rss_kb),max_rss_kb:V(e.max_rss_kb),user_cpu_us:V(e.user_cpu_us),system_cpu_us:V(e.system_cpu_us),minor_page_faults:V(e.minor_page_faults),major_page_faults:V(e.major_page_faults),voluntary_ctx_switches:V(e.voluntary_ctx_switches),involuntary_ctx_switches:V(e.involuntary_ctx_switches)}}function V(e){return typeof e=="number"?e:Number(e)}function Os(e,n=Ir){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return Ds(t)}var Up=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],$r=null;function As(e){let n=e.host??process,t=e.io??Ir,r=e.clock??(()=>new Date().toISOString()),o=n.pid,i=e.scope??vr(process.env),s=e.phase??Np,a=null,l=e.presenceDir===void 0?Lp(js(e.lanePath),_n):e.presenceDir,d=null,p=()=>{l!==null&&(d=Dr({kind:e.kind,id:e.id,last_phase:s,pid:o},{procRoot:e.procRoot}),Ar(l,d))},u=k=>{if(!a){try{a=Hp(e.lanePath,Cp({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:s,scope:i,...k},Mp(n)),t)}catch{}l!==null&&d!==null&&je(l,d)}},f={signal(k){u({exit_path:"signal",signal:k})},exit(k){u({exit_path:"exit",exit_code:k})},uncaughtException(k){u({exit_path:"uncaught-exception",detail:Ps(k)})},unhandledRejection(k){u({exit_path:"unhandled-rejection",detail:Ps(k)})}},h=[...(e.signals??Up).map(k=>{let w=()=>{if(f.signal(k),!(n.listenerCount?.(k)!==1||!n.kill)){n.off(k,w);try{n.kill(o,k)}catch{}}};return[k,w]}),["uncaughtException",(...k)=>f.uncaughtException(k[0])],["unhandledRejection",(...k)=>f.unhandledRejection(k[0])],["exit",(...k)=>f.exit(typeof k[0]=="number"?k[0]:null)]];for(let[k,w]of h)n.on(k,w);let b={lanePath:e.lanePath,phase(k){s=k,a||p()},currentPhase:()=>s,written:()=>a,uninstall(){for(let[k,w]of h)n.off(k,w);l!==null&&d!==null&&je(l,d),$r===b&&($r=null)},handlers:f};return e.setActive!==!1&&($r=b),p(),b}function Ps(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Bp,readdirSync as Vp,readFileSync as ct,statSync as Kp,writeFileSync as qp}from"node:fs";import{join as Ts}from"node:path";var Jp=1,Gp=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],Qp=512*1024;function zp(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??Gp,r=[],o=Ts(n,jr),i=null;try{let l=ct(o,"utf8").trim();i=l===""?null:l,r.push({source:o,result:i?"read":"empty",detail:i})}catch(l){r.push({source:o,result:Tr(l),detail:null})}let s=new Set;try{for(let l of Vp(n))/^\d+$/.test(l)&&s.add(Number(l));r.push({source:n,result:"read",detail:`${s.size} live pids`})}catch(l){r.push({source:n,result:Tr(l),detail:null})}let a=[];for(let l of t)try{let p=Yp(l,e.tailBytes??Qp).split(`
47
+ `).filter(u=>u.trim()!=="");a.push(...p),r.push({source:l,result:p.length===0?"empty":"read",detail:`${p.length} lines`})}catch(d){r.push({source:l,result:Tr(d),detail:null})}return{boot_id:i,live_pids:s,journal:a,probes:r}}function Tr(e){return e.code==="ENOENT"?"absent":"unreadable"}function Yp(e,n){let t=Kp(e).size,r=ct(e,"utf8");return t<=n?r:r.slice(r.length-n)}var Xp=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,Zp=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,ef=/Killed (\/\S*) due to memory pressure/,nf=/\bopid=(\d+)\b/,Ls=/\bsig=(\d+)\b/,tf=/\buid=(\d+)\b/,rf=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,of={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function sf(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,i=[...n.probes.map(u=>`${u.source}: ${u.result}${u.detail?` (${u.detail})`:""}`),`boot id: anchored under ${e.boot_id??"unknown"}, host now ${n.boot_id??"unknown"} (${o?"changed":"same"})`,`parent account: ppid ${e.ppid}`,`cgroup: ${e.cgroup??"unknown"}`],s=(u,f,m,h)=>({version:Jp,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:u,confidence:f,signal:m,host_boot_changed:o,evidence:h,checked:i}),a=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],l=n.journal.find(u=>$s(u,e.pid,Xp)||$s(u,e.pid,Zp));if(l!==void 0)return s("oomd",o?"medium":"high","SIGKILL",[l,...a]);if(e.cgroup!==null)for(let u of n.journal){let f=ef.exec(u)?.[1];if(f!==void 0){if(f===e.cgroup)return s("oomd",o?"medium":"high","SIGKILL",[u,...a]);if(e.cgroup.startsWith(`${f}/`))return s("oomd","medium","SIGKILL",[u,`the killed scope ${f} is an ancestor of this process's ${e.cgroup}`,...a])}}let d=n.journal.find(u=>Number(nf.exec(u)?.[1])===e.pid&&Ls.test(u));if(d!==void 0){let u=Number(Ls.exec(d)?.[1]),f=tf.exec(d)?.[1];return s("user-signal",o?"medium":"high",of[u]??null,[d,...f===void 0?[]:[`sent by uid ${f}`],...a])}let p=t.find(u=>u.pid===e.ppid);if(p!==void 0&&!n.live_pids.has(e.ppid))return s("parent-death","medium",null,[`parent pid ${e.ppid} (${p.kind} ${p.id}) recorded its own death at ${p.ts} via ${p.exit_path}${p.signal?` ${p.signal}`:""}`]);if(o){let u=n.journal.find(f=>rf.test(f));return u!==void 0?s("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,u]):s("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,"no shutdown record on any journal read: the host stopped without announcing it (a freeze or a power loss, not an orderly teardown)"])}return s("unknown","none",null,[])}function $s(e,n,t){return Number(t.exec(e)?.[1])===n}var lf=" | ";function Is(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(lf)}function af(e){return{version:e.version,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.last_seen,last_phase:e.last_phase,sender_class:e.sender_class,confidence:e.confidence,signal:e.signal,host_boot_changed:e.host_boot_changed,evidence:Is(e.evidence),checked:Is(e.checked)}}function df(e){let n=ue({trailer:!1});return e.map(t=>n.push(af(t))).join("")}function Ns(e){let n=dt(e.stateRoot),t=Er(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??zp({procRoot:e.procRoot,journalPaths:e.journalPaths}),i=[],s=Lr(n,u=>i.push(u)),a=Os(bn(e.stateRoot)),l=[],d=[],p=[];for(let u of s){if(o.live_pids.has(u.pid)){d.push(u);continue}if(a.find(m=>m.pid===u.pid&&m.id===u.id)!==void 0){p.push(u),je(n,u);continue}l.push(sf(u,o,a,r())),je(n,u)}return l.length>0&&cf(t,l),{attributions:l,alive:d,self_recorded:p,skipped:i,laneText:()=>{try{return ct(t,"utf8")}catch{return""}}}}function Cs(e){let n=e.skipped.length===0?"":` | unreadable anchors=${e.skipped.join(",")}`;if(e.attributions.length===0)return`death reaper: no un-recorded deaths (live=${e.alive.length} self-recorded=${e.self_recorded.length})${n}`;let t=e.attributions.map(r=>` | ${r.kind} ${r.id} pid=${r.pid} ${r.sender_class}/${r.confidence} phase=${r.last_phase}`+(r.evidence[0]?` evidence="${r.evidence[0]}"`:"")).join("");return`death reaper: attributed ${e.attributions.length}${t}${n}`}function cf(e,n){try{Bp(Ts(e,".."),{recursive:!0,mode:448});let t=uf(e),r=t===""||t.endsWith(`
42
48
  `)?"":`
43
- `;Yc(e,`${t}${r}${mu(n)}`,{encoding:"utf8",mode:384})}catch{}}function gu(e){try{return Cn(e,"utf8")}catch{return""}}import{join as hu}from"node:path";var yu=[".red","redskilled"],z=448;function be(e){return hu(e,...yu)}import{execFileSync as $u}from"node:child_process";import{readFileSync as Lu}from"node:fs";import{dirname as Ms,join as Au}from"node:path";import{existsSync as ku,readFileSync as Bk}from"node:fs";import{dirname as Ru,join as bu}from"node:path";function Ls(e,n){let t=e;for(let r=0;r<16;r++){let o=bu(t,n);if(ku(o))return o;let s=Ru(t);if(s===t)break;t=s}return null}function _u(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 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 _u(c)}}import{createHash as wu}from"node:crypto";var vu="project.name";function Is(e){let n=Le(e,vu)?.trim();return n===void 0||n===""?void 0:n}var Su=8,Ts="project";function Ns(e){let n=Du(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:xu(e.remoteUrl)??{name:Eu(e.checkoutPath,n),source:"basename"},o=ju(n??tr(e.checkoutPath));return{name:r.name,slug:`${Pu(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 xu(e){let n=Ws(e);return n===void 0?void 0:{name:n,source:"remote"}}function Eu(e,n){let t=n===void 0?"":As(Ou(n));if(t!=="")return t;let r=As(tr(e));return r===""?Ts:r}function Pu(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?Ts:t}function ju(e){return wu("sha256").update(e).digest("hex").slice(0,Su)}function Du(e){let n=tr(e??"");return n===""?void 0:n}function tr(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function As(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function Ou(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var Iu=2e3;function Cs(e){return Tu(e).name}function Tu(e){let n=or(e),t=rr(e,["rev-parse","--absolute-git-dir"])??rr(e,["rev-parse","--git-common-dir"]),r=rr(e,["remote","get-url","origin"]);return Ns({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function or(e){let n=Ls(e,Au(".red","config.yaml"));if(n==null)return{};let t;try{t=Lu(n,"utf8")}catch{return{}}let r=Is(t),o=Ms(Ms(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function rr(e,n){try{let t=$u("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Iu}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as ha}from"node:crypto";import{spawn as uh}from"node:child_process";import{mkdir as ph,rm as mh}from"node:fs/promises";import{dirname as fh}from"node:path";import{createHash as Mu}from"node:crypto";import{constants as dr}from"node:fs";import{mkdir as Cu,open as Fu}from"node:fs/promises";import{createConnection as Uu}from"node:net";import{tmpdir as Hu}from"node:os";import{dirname as Vu,join as sn}from"node:path";var Nu="toon";function Hs(e){return e.trimStart().startsWith("{")?"json":"toon"}function ir(e){let n=0;for(;e[n]===`
45
- `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=Hs(t);if(r==="json"){let s=t.indexOf(`
46
- `);return s<0?null:{frame:t.slice(0,s),dialect:r,rest:t.slice(s+1)}}let o=t.indexOf(`
49
+ `;qp(e,`${t}${r}${df(n)}`,{encoding:"utf8",mode:384})}catch{}}function uf(e){try{return ct(e,"utf8")}catch{return""}}import{join as pf}from"node:path";var ff=[".red","redskilled"],se=448;function De(e){return pf(e,...ff)}import{execFileSync as Pf}from"node:child_process";import{readFileSync as jf}from"node:fs";import{dirname as Vs,join as Df}from"node:path";import{existsSync as mf,readFileSync as G_}from"node:fs";import{dirname as hf,join as gf}from"node:path";function Ms(e,n){let t=e;for(let r=0;r<16;r++){let o=gf(t,n);if(mf(o))return o;let i=hf(t);if(i===t)break;t=i}return null}function yf(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function Ge(e,n){let t=[];for(let r of e.split(`
50
+ `)){let o=r.replace(/\r$/,""),i=o.trim();if(!i||i.startsWith("#"))continue;let s=o.indexOf(":");if(s<0)continue;let a=o.length-o.trimStart().length,l=o.slice(0,s).trim();if(!l)continue;let d=o.slice(s+1).trim();for(;t.length&&t[t.length-1].indent>=a;)t.pop();if(t.push({indent:a,key:l}),d&&t.map(u=>u.key).join(".")===n)return yf(d)}}import{createHash as kf}from"node:crypto";var Rf="project.name";function Hs(e){let n=Ge(e,Rf)?.trim();return n===void 0||n===""?void 0:n}var bf=8,Fs="project";function Us(e){let n=vf(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:_f(e.remoteUrl)??{name:wf(e.checkoutPath,n),source:"basename"},o=Sf(n??Nr(e.checkoutPath));return{name:r.name,slug:`${xf(r.name)}-${o}`,hash:o,source:r.source}}function Bs(e){let n=(e??"").trim();if(n==="")return;let t=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),r=/^[^/]*?:(?!\d)(.+)$/.exec(t),i=(r?r[1]:t.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(s=>s.trim()).filter(s=>s!=="");if(i.length!==0)return i.slice(-2).join("/")}function _f(e){let n=Bs(e);return n===void 0?void 0:{name:n,source:"remote"}}function wf(e,n){let t=n===void 0?"":Ws(Ef(n));if(t!=="")return t;let r=Ws(Nr(e));return r===""?Fs:r}function xf(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?Fs:t}function Sf(e){return kf("sha256").update(e).digest("hex").slice(0,bf)}function vf(e){let n=Nr(e??"");return n===""?void 0:n}function Nr(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function Ws(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function Ef(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var Of=2e3;function Ks(e){return Af(e).name}function Af(e){let n=Mr(e),t=Cr(e,["rev-parse","--absolute-git-dir"])??Cr(e,["rev-parse","--git-common-dir"]),r=Cr(e,["remote","get-url","origin"]);return Us({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function Mr(e){let n=Ms(e,Df(".red","config.yaml"));if(n==null)return{};let t;try{t=jf(n,"utf8")}catch{return{}}let r=Hs(t),o=Vs(Vs(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function Cr(e,n){try{let t=Pf("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Of}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as Td}from"node:crypto";import{spawn as Dk}from"node:child_process";import{mkdir as Ok,rm as Ak}from"node:fs/promises";import{dirname as Lk}from"node:path";import{createHash as If}from"node:crypto";import{constants as Br}from"node:fs";import{mkdir as Tf,open as Nf}from"node:fs/promises";import{createConnection as Cf}from"node:net";import{tmpdir as Mf}from"node:os";import{dirname as Wf,join as wn}from"node:path";var Lf="toon";function Gs(e){return e.trimStart().startsWith("{")?"json":"toon"}function Hr(e){let n=0;for(;e[n]===`
51
+ `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=Gs(t);if(r==="json"){let i=t.indexOf(`
52
+ `);return i<0?null:{frame:t.slice(0,i),dialect:r,rest:t.slice(i+1)}}let o=t.indexOf(`
47
53
 
48
- `);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function lr(e){let n=Hs(e)==="json"?sr:Fs,t=n===sr?Fs:sr;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function sr(e){return JSON.parse(e)}function Fs(e){return G(e)}function ar(e,n){if(n==="toon"){let t=Wu(e);if(t!==null)return t.endsWith(`
54
+ `);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function Fr(e){let n=Gs(e)==="json"?Wr:qs,t=n===Wr?qs:Wr;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function Wr(e){return JSON.parse(e)}function qs(e){return z(e)}function Ur(e,n){if(n==="toon"){let t=$f(e);if(t!==null)return t.endsWith(`
49
55
  `)?`${t}
50
56
  `:`${t}
51
57
 
52
58
  `}return`${JSON.stringify(e)}
53
- `}function Wu(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=I(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function Vs(e,n){return!Us(e)||!Us(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function Us(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Bs=new Set;function Ks(e){return Bs.has(e)?"json":Nu}function Js(e){Bs.add(e)}var Bu=108;async function Fn(e,n,t="resident server"){let r=e.wire,o=r??Ks(e.socketPath),s=await qs(e,n,t,o);return r||o==="json"||!Vs(n,s)?s:(Js(e.socketPath),await qs(e,n,t,"json"))}async function qs(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=Uu(e.socketPath),a=!1,c="",u=setTimeout(()=>{p(()=>i(new Error(`${t} timed out`))),l.destroy()},o);function p(m){a||(a=!0,clearTimeout(u),m())}l.on("connect",()=>{l.write(ar(n,r))}),l.on("data",m=>{c+=m.toString("utf8");let g=ir(c);g&&(c=g.rest,p(()=>{try{s(lr(g.frame))}catch(y){i(y)}}),l.end())}),l.on("error",m=>p(()=>i(m))),l.on("close",()=>{a||p(()=>i(new Error(`${t} closed without response`)))})})}function Gs(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=ir(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(ar(l,s.dialect))}catch{}};(async()=>{let l;try{l=lr(s.frame),await n(l,i)}catch(a){t(a,l,i)}finally{e.end()}})()})}async function zs(e){await Cu(Vu(e),{recursive:!0,mode:448});try{return await Fu(e,dr.O_CREAT|dr.O_EXCL|dr.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}function W(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var Ku="/tmp";function Un(e){let n=e.env??process.env,t=Mu("sha256").update(e.key).digest("hex").slice(0,20),r=a=>sn(a,e.socketFileName).length<Bu,o=n.XDG_RUNTIME_DIR;if(o){let a=sn(o,"red-skills",t);if(r(a))return a}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=sn(`red-skills-${s}`,t),l=sn(Hu(),i);return r(l)||process.platform==="win32"?l:sn(Ku,i)}re();import{homedir as fp}from"node:os";import{join as yr}from"node:path";import{spawnSync as gp}from"node:child_process";import{createHash as hp}from"node:crypto";import{existsSync as yp}from"node:fs";import{mkdir as ti,readFile as kp,writeFile as Rp}from"node:fs/promises";import{dirname as bp}from"node:path";var dn="@reddb-io/red-skills",tp="https://registry.npmjs.org",rp="canary",Ae=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function op(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function Kn(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return Jn(r,op(n,t,o))}function sp(e){return e==="dev"?["rsp"]:[]}function ip(e){return`${e}.bundle.min.mjs`}function lp(e){return Jn("dist",ip(e))}function ap(e,n="stable"){return`${dn}@${n==="canary"?rp:e}`}function dp(e=dn){return`${tp}/${e.replace("/","%2F")}`}async function hr(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=Kn({plugin:t,version:r,cacheDir:o,channel:s}),l=sp(t),a=l.map(m=>Kn({plugin:m,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await cp(e,a))return i;let c=ap(r,s),u=Jn(o,`.staging-${t}-${s==="canary"?"canary":r}`),p;try{p=await e.materialize(c,u)}catch(m){throw ni(m,c)}for(let m of[t,...l]){let g=lp(m),y=Jn(p,g);if(!await e.exists(y))throw new Ae("bundle-missing",`npm package ${c} has no ${g}`);let b=m===t?i:Kn({plugin:m,version:r,cacheDir:o,channel:s});await e.writeFile(b,await e.readFile(y))}return i}async function cp(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function Xs(e,n,t=dn){let r;try{r=await e.fetchText(dp(t))}catch(s){throw ni(s,t)}let o=up(r);return{sameMajor:pp(o,n),newest:mp(o)}}function up(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 pp(e,n){let t=gr(n);if(t===null)return null;let r=null;for(let o of e)gr(o)===t&&(r===null||ei(o,r)>0)&&(r=o);return r}function mp(e){let n=null;for(let t of e){let r=String(t).trim();gr(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||ei(r,n)>0)&&(n=r)}return n}function gr(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function ei(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n.trim());return!t||!r?0:Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function ni(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Ae("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Ae("package-missing",`npm could not resolve ${n}: ${t}`,e):new Ae("network",`failed to resolve ${n}: ${t}`,e)}function Jn(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}re();var _p={async materialize(e,n){await ti(n,{recursive:!0});let t=gp("npm",["install",e,"--prefix",n,"--no-save","--no-audit","--no-fund","--ignore-scripts","--loglevel=error"],{stdio:["ignore","ignore","pipe"],encoding:"utf8"});if(t.error)throw t.error;if(t.status!==0)throw new Error(`npm install ${e} -> ${t.status}: ${(t.stderr||"").trim()}`);return yr(n,"node_modules",...dn.split("/"))},async readFile(e){return new Uint8Array(await kp(e))},async writeFile(e,n){await ti(bp(e),{recursive:!0}),await Rp(e,n)},async exists(e){return yp(e)},sha256(e){return hp("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()}},wp="redskilled";function vp(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||yr(e.HOME||fp(),".cache");return yr(n,"red-skills","bundles")}async function Sp(e={},n={},t={}){let r=ue(e,n);if(Y(r))return r;let o=t.env??n.env??process.env;try{await hr(t.bundleIO??_p,{plugin:wp,version:t.version??"",cacheDir:vp(o)})}catch{return r}return ue(e,n)}async function ri(e={},n={},t={}){let r=await Sp(e,n,t);if(Y(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(re(),Zs));throw new o(r)}import{randomUUID as lt}from"node:crypto";import{mkdir as th,rm as ma}from"node:fs/promises";import{createServer as rh}from"node:net";import{dirname as oh}from"node:path";import{totalmem as xp}from"node:os";function oi(e){let n=0,t=0,r=0,o=[],s=[];for(let i of e){let l=i.budget??{},a=!1;for(let[c,u]of[[l.memory_high,p=>n+=p],[l.memory_max,p=>t+=p]]){if(c==null)continue;let p=Ie(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 Ie(e){let n=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!n)return null;let t={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[n[2].toLowerCase()];return Math.round(Number(n[1])*t)}function si(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&Number.isInteger(n.worker_count)&&typeof n.memory_high_bytes=="number"&&typeof n.memory_max_bytes=="number"&&typeof n.cpu_weight_total=="number"&&Array.isArray(n.unaccounted_workers)&&Array.isArray(n.unisolated_workers)}var Ep="REDSKILLED_MEMORY_CEILING",Pp="REDSKILLED_WORKER_CEILING",jp=.7;function ii(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return Ie(n)}function qn(e){let n=0,t=[];for(let r of e){let o=ii(r.budget);o===null?t.push(r.worker_id):o!==void 0&&(n+=o)}return{worker_count:e.length,memory_bytes:n,unaccounted_workers:t.sort()}}function li(e){let{ceiling:n}=e,t=qn(e.workers),r=ii(e.budget),o=r===void 0?null:r,s=t.memory_bytes+(r??0),i=t.worker_count+1,l=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",a=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,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 ai(e){let n=e.budget?.memory_max??e.budget?.memory_high;if(n!=null)return{memory_max:n,reason:`the client declared this Worker's memory ceiling (${n}), so the host derived none`};if(e.ceiling.memory_bytes==null)return{memory_max:null,reason:"this host admits Workers against no memory ceiling, so there is no accounting to derive a per-Worker ceiling from; the daemon's RSS sampling floor is the only remaining ceiling"};let t=qn(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,s=o==null?r:Math.floor(e.ceiling.memory_bytes/o),i=Math.min(r,s);if(i<=0)return{memory_max:null,reason:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes is already fully committed to ${t.worker_count} Worker(s), so no positive per-Worker ceiling can be derived; the daemon's RSS sampling floor is the only remaining ceiling`};let l=o==null?`the headroom under this host's memory ceiling of ${e.ceiling.memory_bytes} bytes`:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes shared across its ${o} Worker slot(s)`;return{memory_max:String(i),reason:`derived from ${l} (ceiling source: ${e.ceiling.source})`}}function di(e=process.env,n=xp()){let t=(e[Ep]??"").trim(),r=(e[Pp]??"").trim(),o=Op(r);if(t!==""){let s=Dp(t,n);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(n*jp),worker_count:o,source:r!==""?"declared":"host-fraction"}}function Dp(e,n){let t=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(t))return null;let r=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return r?Math.floor(n*(Number(r[1])/100)):Ie(e)??void 0}function 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 $p,mkdir as Lp,open as Ap,readFile as Ip,stat as Tp,truncate as ci}from"node:fs/promises";import{dirname as Np}from"node:path";var ui="redskilled.events.toonl";function Wp(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 Cp(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 pi(e){let n=te({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await Lp(Np(e),{recursive:!0,mode:448}),await Fp(e),await $p(e,n.push(Bp(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(Wp(o)),recordDaemonStop:o=>r(Cp(o)),read:()=>Up(e),flush:async()=>{await t}}}async function Fp(e){let n;try{n=(await Tp(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await Ap(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let s=n;s>0;s-=t){let i=Math.min(t,s),l=Buffer.alloc(i);await r.read(l,0,i,s-i);let a=l.lastIndexOf(10);if(a>=0){await ci(e,s-i+a+1);return}}await ci(e,0)}finally{await r.close()}}async function Up(e){let n;try{n=await Ip(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return Hp(n)}function Hp(e){let n=e.split(`
54
- `);return n.pop(),n.length===0?[]:de(`${n.join(`
59
+ `}function $f(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=M(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function Qs(e,n){return!Js(e)||!Js(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function Js(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zs=new Set;function Ys(e){return zs.has(e)?"json":Lf}function Xs(e){zs.add(e)}var Hf=108;async function ut(e,n,t="resident server"){let r=e.wire,o=r??Ys(e.socketPath),i=await Zs(e,n,t,o);return r||o==="json"||!Qs(n,i)?i:(Xs(e.socketPath),await Zs(e,n,t,"json"))}async function Zs(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((i,s)=>{let a=Cf(e.socketPath),l=!1,d="",p=setTimeout(()=>{u(()=>s(new Error(`${t} timed out`))),a.destroy()},o);function u(f){l||(l=!0,clearTimeout(p),f())}a.on("connect",()=>{a.write(Ur(n,r))}),a.on("data",f=>{d+=f.toString("utf8");let m=Hr(d);m&&(d=m.rest,u(()=>{try{i(Fr(m.frame))}catch(h){s(h)}}),a.end())}),a.on("error",f=>u(()=>s(f))),a.on("close",()=>{l||u(()=>s(new Error(`${t} closed without response`)))})})}function el(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let i=Hr(r);if(!i)return;r=i.rest,e.pause();let s=a=>{if(!(e.destroyed||!e.writable))try{e.write(Ur(a,i.dialect))}catch{}};(async()=>{let a;try{a=Fr(i.frame),await n(a,s)}catch(l){t(l,a,s)}finally{e.end()}})()})}async function nl(e){await Tf(Wf(e),{recursive:!0,mode:448});try{return await Nf(e,Br.O_CREAT|Br.O_EXCL|Br.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}function U(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var Ff="/tmp";function pt(e){let n=e.env??process.env,t=If("sha256").update(e.key).digest("hex").slice(0,20),r=l=>wn(l,e.socketFileName).length<Hf,o=n.XDG_RUNTIME_DIR;if(o){let l=wn(o,"red-skills",t);if(r(l))return l}let i=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),s=wn(`red-skills-${i}`,t),a=wn(Mf(),s);return r(a)||process.platform==="win32"?a:wn(Ff,s)}pe();import{homedir as cm}from"node:os";import{join as Yr}from"node:path";import{spawnSync as um}from"node:child_process";import{createHash as pm}from"node:crypto";import{existsSync as fm}from"node:fs";import{mkdir as al,readFile as mm,writeFile as hm}from"node:fs/promises";import{dirname as gm}from"node:path";var Ae="@reddb-io/red-skills",Xf="https://registry.npmjs.org",Zf="canary",Qe=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function em(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function gt(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return yt(r,em(n,t,o))}function nm(e){return e==="dev"?["rsp","redskilled"]:[]}function tm(e){return`${e}.bundle.min.mjs`}function rm(e){return yt("dist",tm(e))}function om(e,n="stable"){return`${Ae}@${n==="canary"?Zf:e}`}function im(e=Ae){return`${Xf}/${e.replace("/","%2F")}`}async function zr(e,n){let{plugin:t,version:r,cacheDir:o,channel:i="stable"}=n,s=gt({plugin:t,version:r,cacheDir:o,channel:i}),a=nm(t),l=a.map(f=>gt({plugin:f,version:r,cacheDir:o,channel:i}));if(i!=="canary"&&await e.exists(s)&&await sm(e,l))return s;let d=om(r,i),p=yt(o,`.staging-${t}-${i==="canary"?"canary":r}`),u;try{u=await e.materialize(d,p)}catch(f){throw ll(f,d)}for(let f of[t,...a]){let m=rm(f),h=yt(u,m);if(!await e.exists(h))throw new Qe("bundle-missing",`npm package ${d} has no ${m}`);let b=f===t?s:gt({plugin:f,version:r,cacheDir:o,channel:i});await e.writeFile(b,await e.readFile(h))}return s}async function sm(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function il(e,n,t=Ae){let r;try{r=await e.fetchText(im(t))}catch(i){throw ll(i,t)}let o=lm(r);return{sameMajor:am(o,n),newest:dm(o)}}function lm(e){let n;try{n=JSON.parse(e)}catch{return[]}if(typeof n!="object"||n===null)return[];let t=n.versions;return typeof t!="object"||t===null?[]:Object.keys(t)}function am(e,n){let t=Qr(n);if(t===null)return null;let r=null;for(let o of e)Qr(o)===t&&(r===null||sl(o,r)>0)&&(r=o);return r}function dm(e){let n=null;for(let t of e){let r=String(t).trim();Qr(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||sl(r,n)>0)&&(n=r)}return n}function Qr(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function sl(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n.trim());return!t||!r?0:Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function ll(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Qe("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Qe("package-missing",`npm could not resolve ${n}: ${t}`,e):new Qe("network",`failed to resolve ${n}: ${t}`,e)}function yt(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}pe();var ym={async materialize(e,n){await al(n,{recursive:!0});let t=um("npm",["install",e,"--prefix",n,"--no-save","--no-audit","--no-fund","--ignore-scripts","--loglevel=error"],{stdio:["ignore","ignore","pipe"],encoding:"utf8"});if(t.error)throw t.error;if(t.status!==0)throw new Error(`npm install ${e} -> ${t.status}: ${(t.stderr||"").trim()}`);return Yr(n,"node_modules",...Ae.split("/"))},async readFile(e){return new Uint8Array(await mm(e))},async writeFile(e,n){await al(gm(e),{recursive:!0}),await hm(e,n)},async exists(e){return fm(e)},sha256(e){return pm("sha256").update(e).digest("hex")},async fetchText(e){let n=await fetch(e,{redirect:"follow"});if(!n.ok)throw new Error(`GET ${e} -> ${n.status}`);return await n.text()}},km="redskilled";function Rm(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Yr(e.HOME||cm(),".cache");return Yr(n,"red-skills","bundles")}async function bm(e={},n={},t={}){let r=Re(e,n);if(ae(r))return r;let o=t.env??n.env??process.env;try{await zr(t.bundleIO??ym,{plugin:km,version:t.version??"",cacheDir:Rm(o)})}catch{return r}return Re(e,n)}async function dl(e={},n={},t={}){let r=await bm(e,n,t);if(ae(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(pe(),ol));throw new o(r)}import{randomUUID as Tn}from"node:crypto";import{mkdir as yk,rm as Ad}from"node:fs/promises";import{createServer as kk}from"node:net";import{dirname as Rk}from"node:path";import{totalmem as wm}from"node:os";function vn(e){if(e.applied_budget!=null)return e.applied_budget;let n=e.budget??{};return n.memory_max==null&&n.memory_high==null&&e.memory_ceiling!=null?{...n,memory_max:e.memory_ceiling}:n}function cl(e,n={}){let t=0,r=0,o=0,i=[],s=[];for(let d of e){let p=vn(d),u=!1;for(let[f,m]of[[p.memory_high,h=>t+=h],[p.memory_max,h=>r+=h]]){if(f==null)continue;let h=ze(f);h==null?u=!0:m(h)}p.cpu_weight!=null&&(o+=p.cpu_weight),u&&i.push(d.worker_id),d.isolated||s.push(d.worker_id)}let a=n.hostCeilingBytes??null,l=a==null?0:Math.max(0,r-a);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:r,cpu_weight_total:o,unaccounted_workers:i.sort(),unisolated_workers:s.sort(),memory_ceiling_bytes:a,over_committed_bytes:l,over_commitment_reason:l===0?null:_m(e.length,r,a,l)}}function _m(e,n,t,r){return`this host's ${e} Worker(s) carry ${n} bytes of applied MemoryMax against a host ceiling of ${t} bytes \u2014 ${r} bytes over. A per-Worker MemoryMax is a wall rather than a reservation, so the host stays safe only while the Workers do not all peak together; the ceiling is not enforced host-wide.`}function ze(e){let n=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!n)return null;let t={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[n[2].toLowerCase()];return Math.round(Number(n[1])*t)}function ul(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&Number.isInteger(n.worker_count)&&typeof n.memory_high_bytes=="number"&&typeof n.memory_max_bytes=="number"&&typeof n.cpu_weight_total=="number"&&Array.isArray(n.unaccounted_workers)&&Array.isArray(n.unisolated_workers)}var xm="REDSKILLED_MEMORY_CEILING",pl="REDSKILLED_WORKER_CEILING",Sm=.7;function fl(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return ze(n)}function kt(e){let n=0,t=[];for(let r of e){let o=fl(r.budget);o===null?t.push(r.worker_id):o!==void 0&&(n+=o)}return{worker_count:e.length,memory_bytes:n,unaccounted_workers:t.sort()}}function ml(e){let{ceiling:n}=e,t=kt(e.workers),r=fl(e.budget),o=r===void 0?null:r,i=t.memory_bytes+(r??0),s=t.worker_count+1,a=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",l=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,d=(p,u)=>({version:1,admitted:!1,verdict:p,reason:u,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:s,projected_memory_bytes:i});return n.worker_count!=null&&s>n.worker_count?d("refused-over-worker-ceiling",`redskilled refused this Worker${a}: it would be Worker ${s} past a host ceiling of ${n.worker_count} Worker(s), and ${l}`):n.memory_bytes!=null&&r===null?d("refused-unaccountable-budget",`redskilled refused this Worker${a}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${n.memory_bytes} bytes, and ${l}`):n.memory_bytes!=null&&i>n.memory_bytes?d("refused-over-memory-ceiling",`redskilled refused this Worker${a}: it would take the host to ${i} bytes of declared Worker memory, past the host ceiling of ${n.memory_bytes} bytes, and ${l}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${a}: ${i} bytes of declared Worker memory against a host ceiling of ${n.memory_bytes??"unbounded"} bytes, and ${l}`,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:s,projected_memory_bytes:i}}function hl(e){let n=e.budget?.memory_max??e.budget?.memory_high;if(n!=null)return{memory_max:n,reason:`the client declared this Worker's memory ceiling (${n}), so the host derived none`};if(e.ceiling.memory_bytes==null)return{memory_max:null,reason:"this host admits Workers against no memory ceiling, so there is no accounting to derive a per-Worker ceiling from; the daemon's RSS sampling floor is the only remaining ceiling"};let t=kt(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,i=o==null?r:Math.floor(e.ceiling.memory_bytes/o),s=Math.min(r,i);if(s<=0)return{memory_max:null,reason:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes is already fully committed to ${t.worker_count} Worker(s), so no positive per-Worker ceiling can be derived; the daemon's RSS sampling floor is the only remaining ceiling`};let a=o==null?`the headroom under this host's memory ceiling of ${e.ceiling.memory_bytes} bytes; this host declares no Worker slot count (${pl} is unset), so this ceiling is a per-Worker wall and not memory the host sets aside \u2014 N Workers may carry N such walls, and the host ceiling is not enforced host-wide. Declare a slot count to make it divide into shares that sum to it`:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes shared across its ${o} Worker slot(s)`;return{memory_max:String(s),reason:`derived from ${a} (ceiling source: ${e.ceiling.source})`}}function gl(e=process.env,n=wm()){let t=(e[xm]??"").trim(),r=(e[pl]??"").trim(),o=Em(r);if(t!==""){let i=vm(t,n);if(i!==void 0)return{memory_bytes:i,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(n*Sm),worker_count:o,source:r!==""?"declared":"host-fraction"}}function vm(e,n){let t=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(t))return null;let r=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return r?Math.floor(n*(Number(r[1])/100)):ze(e)??void 0}function Em(e){if(e===""||["infinity","none","off","unbounded"].includes(e.toLowerCase()))return null;let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:null}import{appendFile as Pm,mkdir as jm,open as Dm,readFile as Om,stat as Am,truncate as yl}from"node:fs/promises";import{dirname as Lm}from"node:path";var kl="redskilled.events.toonl";function $m(e){let n=e.worker.budget??{};return{version:1,ts:e.ts,event:e.event,worker_id:e.worker.worker_id,project_label:e.worker.project_label,pid:e.worker.pid,workspace_path:e.worker.workspace_path,log_path:e.worker.log_path??null,isolated:e.worker.isolated,unit:e.worker.unit??null,memory_high:n.memory_high??null,memory_max:n.memory_max??null,cpu_weight:n.cpu_weight??null,detail:e.detail??null,exit_code:e.exitCode??null,signal:e.signal??null,reason:e.reason??null}}var Im="daemon:";function Tm(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${Im}${e.pid}`,project_label:"",pid:e.pid,workspace_path:e.socketPath,log_path:null,isolated:!1,unit:null,memory_high:null,memory_max:null,cpu_weight:null,detail:e.detail,exit_code:null,signal:e.signal??null,reason:e.reason}}function Rl(e){let n=ue({trailer:!1}),t=Promise.resolve();async function r(o){let i=t.then(async()=>{await jm(Lm(e),{recursive:!0,mode:448}),await Nm(e),await Pm(e,n.push(Hm(o)),{encoding:"utf8",mode:384})});return t=i.catch(()=>{}),await i,o}return{path:e,record:o=>r($m(o)),recordDaemonStop:o=>r(Tm(o)),read:()=>Cm(e),flush:async()=>{await t}}}async function Nm(e){let n;try{n=(await Am(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await Dm(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let i=n;i>0;i-=t){let s=Math.min(t,i),a=Buffer.alloc(s);await r.read(a,0,s,i-s);let l=a.lastIndexOf(10);if(l>=0){await yl(e,i-s+l+1);return}}await yl(e,0)}finally{await r.close()}}async function Cm(e){let n;try{n=await Om(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return Mm(n)}function Mm(e){let n=e.split(`
60
+ `);return n.pop(),n.length===0?[]:ye(`${n.join(`
55
61
  `)}
56
- `).filter(Kp).map(Jp)}function mi(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,Vp(t)):n.delete(t.worker_id));return[...n.values()]}function Vp(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 Kp(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 Jp(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:oe(e.project_label)??"",pid:Number(e.pid??0),workspace_path:oe(e.workspace_path)??"",log_path:oe(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:oe(e.unit),memory_high:oe(e.memory_high),memory_max:oe(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:oe(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:oe(e.signal),reason:oe(e.reason)}}function oe(e){return e==null||e===""?null:String(e)}function fi(e){let n=[...e.projects].sort((i,l)=>i.project_label.localeCompare(l.project_label)),t=e.backoffUntilMs??null,r=t!=null&&e.nowMs<t,o=[],s=[];for(let i of n){let l=Math.max(0,e.live[i.project_label]??0),a=Object.prototype.hasOwnProperty.call(e.queue,i.project_label),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 m=0;m<p;m+=1)(s[m]??(s[m]=[])).push({project_label:i.project_label,index:l+m,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function gi(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function yi(e){let n=e.workers.map(qp),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:zp({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function ki(e){return{version:1,running:!1,stopped:!1,reason:"not-running",socket_path:e,daemon_version:null,pid:null,holding:{workers:[],projects:[]},surviving:[],detail:`no redskilled daemon is answering on ${JSON.stringify(e)}, so there was nothing to stop`}}function qp(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 Gp(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 zp(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Gp(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${hi(e.held,"Worker")} across ${hi(e.projects,"project")}, and ${e.surviving} of them survive it \u2014 a Worker is an init-system unit, so this is a restart and not an evacuation`}function hi(e,n){return`${e} ${n}${e===1?"":"s"}`}function kr(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.holding;return n.version===1&&typeof n.running=="boolean"&&typeof n.stopped=="boolean"&&typeof n.reason=="string"&&typeof n.socket_path=="string"&&typeof n.detail=="string"&&(n.daemon_version===null||typeof n.daemon_version=="string")&&(n.pid===null||typeof n.pid=="number")&&t!=null&&Array.isArray(t.workers)&&Array.isArray(t.projects)&&Array.isArray(n.surviving)}import{chmod as Qp,mkdir as Yp,readFile as Zp,rm as Xp,writeFile as em}from"node:fs/promises";import{dirname as Ri,join as vi}from"node:path";import{tmpdir as bi}from"node:os";var nm="redskilled.machine.claim.toon",tm="REDSKILLED_MACHINE_DIR",rm=8,pe=class extends Error{constructor(t,r,o){super(sm(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},_i;function Si(){return _i??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},_i}function om(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[tm]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||bi():bi();return vi(o,`redskilled-${e.machineIdHash}`)}function Gn(e){return vi(om(e),nm)}function zn(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??W;async function s(){let a;try{a=await Zp(e,"utf8")}catch(u){if(u.code==="ENOENT"||Rr(u))return;throw u}let c=lm(a);return am(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 Xp(e,{force:!0}),!0}catch(a){if(Rr(a))return!1;throw a}}return{claimPath:e,read:s,async claim(a){await Yp(Ri(e),{recursive:!0,mode:1023})!=null&&await Qp(Ri(e),1023).catch(()=>{});let u=!1;for(let p=0;p<rm;p+=1){let m=i(a,r());try{return await em(e,im(m),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:u,claim:m}}catch(y){if(y.code!=="EEXIST"){if(Rr(y))return{claimed:!1,reason:"stale-claim-not-reapable"};throw y}}let g=await s();if(!g){if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable"};u=!0;continue}if(wi(g,a,n.socketPath))return{claimed:!0,reaped:u,claim:g};if(await o(g.pid))return{claimed:!1,reason:"held",claim:g};if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable",claim:g};u=!0}return{claimed:!1,reason:"contended"}},async release(a){let c=await s();return!c||!wi(c,a,n.socketPath)?!1:await l()}}}function xi(e,n,t){return{kind:"machine",claim_path:e,owner_uid:t.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath}}function Ei(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.kind==="machine"&&typeof n.claim_path=="string"&&typeof n.owner_uid=="number"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&typeof n.socket_path=="string"}function sm(e,n,t){let r=t==null?"":` \u2014 held by pid ${t.pid} (uid ${t.uid}) on socket ${JSON.stringify(t.socket_path)}`;return n==="held"?`this machine already has a redskilled daemon${r}; a second one would void the host budget, so none was started. Reach that daemon, or stop it before starting another.`:n==="stale-claim-not-reapable"?`the redskilled machine claim ${JSON.stringify(e)} is stale and cannot be removed by this user${r}; remove it as its owner, then start again. No second daemon was started.`:`the redskilled machine claim ${JSON.stringify(e)} changed hands repeatedly; no daemon was started.`}function Rr(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function wi(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function im(e){return`${I(e,{keyedMapCollapse:!0})}
57
- `}function lm(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return G(n)}catch{return null}}}function am(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||n.scope!=="machine"||!Number.isInteger(n.pid)||n.pid<=0||!Number.isInteger(n.uid))return!1;for(let t of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}function br(e,n){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(n)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((t,r)=>{if(typeof t!="string"||t==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${r} of project ${JSON.stringify(n)} is not`);return t})}function _r(e,n){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error(`redskilled needs a launch env to be a map of strings to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}`);let t={};for(let[r,o]of Object.entries(e)){if(r==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(n)} to be named`);if(typeof o!="string")throw new Error(`redskilled needs every launch env value to be a string, and ${JSON.stringify(r)} of project ${JSON.stringify(n)} is ${JSON.stringify(o)}`);t[r]=o}return t}var dm=3e5,cm=.5,vr=class extends Error{constructor(t){super(`redskilled already holds a registration for project ${JSON.stringify(t.project_label)}, registered at ${t.registered_at} for a target of ${t.target} and standing until ${t.renew_by}: a project contributes one registration, so a second one is refused rather than silently replacing the first`);this.held=t;this.name="RedskilledProjectRegisteredError"}};function Pi(e,n){if(n.held!=null)throw new vr(n.held);let t=wr(e.project_label,"a project label"),r=wr(e.selector,"a selector"),o=br(e.argv,t),s=_r(e.env,t),i=wr(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.target)}`);let l=e.renew_within_ms??dm;if(!Number.isFinite(l)||l<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let a=Date.parse(n.now);if(!Number.isFinite(a))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(n.now)}`);return{version:1,project_label:t,selector:r,argv:o,workspace_path:i,env:s,target:e.target,registered_at:new Date(a).toISOString(),renew_within_ms:l,renew_by:new Date(a+l).toISOString(),renewed_at:new Date(a).toISOString(),renewals:0,launch_revision:0}}var Qn=class extends Error{constructor(t){super(`redskilled holds no registration for project ${JSON.stringify(t)} to renew: it lapsed or was never held, and a renewal never mints a record \u2014 register again, stating the selector, the argv and the target`);this.projectLabel=t;this.name="RedskilledProjectUnregisteredError"}};function ji(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(n.now)}`);let r=n.renew_within_ms??e.renew_within_ms;if(!Number.isFinite(r)||r<=0)throw new Error(`redskilled needs a positive renewal window to renew project ${JSON.stringify(e.project_label)}, not ${JSON.stringify(n.renew_within_ms)}`);let o=n.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:br(n.launch.argv,e.project_label),env:_r(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1};return{...e,...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1}}function Di(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(n.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,n.liveWorkers??0),s=n.queue,i=s!=null&&s.outcome==="counted"?s.depth:null,l=i!=null&&i>0?"open-work":o>0?"live-worker":null;if(l==null){let a=i===0?"drained":"uncounted";return{registration:e,verdict:a,detail:a==="drained"?`project ${r} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${r}, and an uncounted queue never sustains a registration \u2014 it stands on its own deadline of ${e.renew_by}`}}return{registration:{...e,renew_by:new Date(t+e.renew_within_ms).toISOString(),sustained_at:new Date(t).toISOString(),sustains:(e.sustains??0)+1,sustained_by:l},verdict:l,detail:l==="open-work"?`project ${r} has ${i} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function um(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function Oi(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*cm;if(r(t))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return r(o)?"self-renewing":"running-on"}function $i(e,n){let t=[],r=[];for(let o of e)(um(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function Sr(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.project_label=="string"&&typeof n.selector=="string"&&Array.isArray(n.argv)&&n.argv.every(t=>typeof t=="string")&&typeof n.workspace_path=="string"&&Number.isInteger(n.target)&&typeof n.registered_at=="string"&&typeof n.renew_within_ms=="number"&&typeof n.renew_by=="string"&&(n.renewed_at===void 0||typeof n.renewed_at=="string")&&(n.renewals===void 0||Number.isInteger(n.renewals))&&(n.env===void 0||pm(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 pm(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function wr(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var mm={ping:"host-read","host-state":"host-read","statusline-payload":"host-read",shutdown:"daemon-life","worker-start":"project-write","worker-stop":"project-write","worker-recycle":"project-write","worker-steer":"project-write","worker-heartbeat":"project-write","project-register":"project-write","project-renew":"project-write","project-deregister":"project-write"};function Li(e){return`worker-${e}`}function Ai(e){let n=mm[e.op]??"project-write",t=e.sessionProject??null,r=e.targetProject??null,o={version:1,op:e.op,reach:n,session_project:t,target_project:r};return n==="host-read"?{...o,permitted:!0,verdict:"permitted-host-read",reason:`redskilled permitted ${e.op}: a session reads the whole host, whichever project it was started in`}:n==="daemon-life"?{...o,permitted:!0,verdict:"permitted-daemon-life",reason:`redskilled permitted ${e.op}: it acts on the daemon's own process, not on any project's Workers`}:t==null||t===""?{...o,permitted:!0,verdict:"permitted-unattributed",reason:`redskilled permitted ${e.op}: the session named no project of its own, so there is nothing to refuse it against`}:r!=null&&r===t?{...o,permitted:!0,verdict:"permitted-own-project",reason:`redskilled permitted ${e.op}: the target belongs to project ${JSON.stringify(t)}, which is this session's own`}:{...o,permitted:!1,verdict:"refused-cross-project",reason:`redskilled refused ${e.op} from a session in project ${JSON.stringify(t)}: ${r==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(r)}`}. A session reads the whole host and writes only its own project.`}}function Mi(e){return{generated_at:e.now,hour:Ii("hour",36e5,e),day:Ii("day",864e5,e)}}function Yn(e,n,t){let r=cn(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(l=>{let a=cn(n(l));return a==null?!1:r==null||r-a<=o});return i.length<=s?i:i.slice(i.length-s)}function Ii(e,n,t){let r=cn(t.now),o=r==null?null:r-n,s=e==="hour"?"1h":"24h",i=t.observations.map(p=>({observation:p,at:cn(p.observed_at)})).filter(p=>p.at!=null&&Wi(p.at,o,r)).sort((p,m)=>p.at-m.at),l=t.outcomes.map(p=>cn(p.ts)).filter(p=>p!=null&&Wi(p,o,r)),a=Ti(i,p=>p.tokens,"tokens",s),c=Ti(i,p=>p.tools,"tools",s),u=[];return i.length===0?u.push("worker-vitals"):(a.samples===0&&u.push("worker-vitals.tokens"),c.samples===0&&u.push("worker-vitals.tools")),l.length===0&&u.push("worker-outcomes"),{window:e,window_ms:n,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:a,tools_per_min:c,issues_per_hour:fm(l.length,n,s),runner_share:Ni("runner",i,p=>p.runner,s),model_share:Ni("model",i,p=>p.model,s),unavailable:u}}function Ti(e,n,t,r){let o=new Map,s=0;for(let c of e){let u=n(c.observation);if(u==null||!Number.isFinite(u))continue;s+=1;let p=o.get(c.observation.worker_id)??[];p.push({at:c.at,count:u}),o.set(c.observation.worker_id,p)}if(s===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${r}`,samples:0};let i=0,l=null,a=null;for(let c of o.values()){if(c.length<2)continue;for(let m=1;m<c.length;m++){let g=c[m-1],y=c[m];g==null||y==null||(i+=Math.max(0,y.count-g.count))}let u=c[0],p=c[c.length-1];u!=null&&(l=l==null?u.at:Math.min(l,u.at)),p!=null&&(a=a==null?p.at:Math.max(a,p.at))}return l==null||a==null||a<=l?{value:null,absent_reason:`the last ${r} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:s}:{value:i/((a-l)/6e4),absent_reason:null,samples:s}}function fm(e,n,t){return e===0?{value:null,absent_reason:`no Worker outcome was recorded in the last ${t}`,samples:0}:{value:e/(n/36e5),absent_reason:null,samples:e}}function Ni(e,n,t,r){let o=new Map;for(let c of n){let u=t(c.observation);u!=null?o.set(c.observation.worker_id,u):o.has(c.observation.worker_id)||o.set(c.observation.worker_id,null)}let s=new Map,i=0,l=0;for(let c of o.values()){if(c==null){l+=1;continue}i+=1,s.set(c,(s.get(c)??0)+1)}let a=[...s.entries()].map(([c,u])=>({key:c,worker_count:u,share:u/i})).sort((c,u)=>u.worker_count-c.worker_count||c.key.localeCompare(u.key));return{dimension:e,attributed_workers:i,unattributed_workers:l,shares:a,absent_reason:a.length>0?null:o.size===0?`no Worker was observed in the last ${r}`:`no Worker published a ${e} in the last ${r}`}}function Wi(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function cn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}import{execFileSync as gm}from"node:child_process";import{readFileSync as hm,readdirSync as ym}from"node:fs";import{join as km}from"node:path";function un(e){let n=e.budget??{},t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high],["MemoryMax",e.memory_ceiling]];for(let[r,o]of t){if(o==null)continue;let s=Ie(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function Ci(e){let n=[],t=[];for(let r of e.workers){let o=un(r);if(o==null){t.push({worker_id:r.worker_id,reason:(r.budget?.memory_max??r.budget?.memory_high??r.memory_ceiling)==null?"this Worker declared no memory budget and the host derived no ceiling for it, so the sampler has none to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let s=e.rss[r.worker_id];if(typeof s!="number"||!Number.isFinite(s)){t.push({worker_id:r.worker_id,reason:"the host produced no RSS reading for this Worker on this tick, and an unmeasured Worker is never killed on suspicion"});continue}s<=o.bytes||n.push(Rm(r,o,s))}return{terminations:n,unenforceable:t}}function Rm(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 bm=4096;function Fi(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{}};if(e.length===0)return r;let o=_m(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],m=new Set;for(;p.length>0;){let g=p.pop();if(m.has(g))continue;m.add(g);let y=o.get(g);if(y){c+=y.rssBytes,u+=y.cpuSeconds;for(let b of s.get(g)??[])p.push(b)}}i[a.worker_id]=c,l[a.worker_id]=u}return{rss:i,cpu_seconds:l}}function _m(e,n){return n.procRoot!=null||e==="linux"?Pm(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?xm(wm(n.psTable)):new Map}function wm(e){try{return(e??vm)()}catch{return""}}function vm(){return gm("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Sm=1024;function xm(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=Em(r[3]);l!=null&&n.set(o,{pid:o,ppid:s,rssBytes:i*Sm,cpuSeconds:l})}return n}function Em(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 Pm(e){let n=new Map,t;try{t=ym(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=hm(km(e,r,"stat"),"utf8")}catch{continue}let s=Dm(o);s&&n.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*bm,cpuSeconds:s.cpuTicks/jm})}return n}var jm=100;function Dm(e){let n=e.lastIndexOf(")");if(n<0)return null;let t=Number(e.slice(0,e.indexOf(" "))),r=e.slice(n+1).trim().split(/\s+/),o=Number(r[1]),s=Number(r[11]),i=Number(r[12]),l=Number(r[21]);return!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||!Number.isFinite(l)||!Number.isFinite(s)||!Number.isFinite(i)?null:{pid:t,ppid:o,rssPages:Math.max(0,l),cpuTicks:Math.max(0,s)+Math.max(0,i)}}var xr=class extends Error{constructor(t,r,o){super(`redskilled polls every repository with one host token ${JSON.stringify(o)}, and project ${JSON.stringify(t)} declares its own credential ${JSON.stringify(r)}: a project needing its own credential invalidates the host-scoped poller (ADR 0130 Amendment 1) rather than bending it, so the poller returns to the projects instead of reaching this repository under the wrong identity`);this.projectLabel=t;this.tokenRef=r;this.hostTokenRef=o;this.name="RedskilledSplitCredentialError"}};function Pr(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new xr(t.project_label,t.token_ref,n)}function Om(e,n={now:new Date(0).toISOString()}){Am(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),m=JSON.stringify(u.name),g=JSON.stringify(`repo:${u.owner}/${u.name} is:closed closed:>=${o}`);return[` ${a}: repository(owner: ${p}, name: ${m}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${c}: search(query: ${g}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
59
- `),aliases:s,closed_since:o}}function $m(e,n,t){let r=Te(n),o=Te(r.data),s=Array.isArray(r.errors)?r.errors.map(Te):[],i=Im(o.rateLimit,s),l=e.aliases.map(({alias:a,search_alias:c,project:u})=>{let p=u.owner+"/"+u.name,m=o[a],g=s.find(y=>Ui(y.path,a)||Ui(y.path,c));if(qi(m)){let y=Hi(m.open_pull_requests),b=Hi(m.open_issues),k=Tm(o[c]);if(y!=null&&b!=null&&k!=null)return{project_label:u.project_label,repository:p,outcome:"counted",counts:{open_pull_requests:y,open_issues:b,recently_closed:k},detail:`counted ${p} for project ${JSON.stringify(u.project_label)}`}}return i.exhausted||Ji(g)?{project_label:u.project_label,repository:p,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${p} answered, so this project has no counts rather than zero counts${i.reset_at==null?"":`; the quota resets at ${i.reset_at}`}`}:{project_label:u.project_label,repository:p,outcome:"unreachable",counts:null,detail:`${p} is not reachable with the host token: ${Er(g?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:l.length,rate_limit:i,projects:l}}function Lm(e){return{version:1,fetched_at:e,request_count:0,project_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}async function Vi(e){if(e.projects.length===0)return Lm(e.now);Pr(e.projects,e.hostTokenRef);let n=Om(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return $m(n,t,{fetchedAt:e.now})}catch(t){let r=t instanceof Error?t.message:String(t),o=/rate limit|secondary rate|429/i.test(r);return{version:1,fetched_at:e.now,request_count:1,project_count:e.projects.length,rate_limit:{remaining:null,reset_at:null,exhausted:o},projects:e.projects.map(s=>({project_label:s.project_label,repository:`${s.owner}/${s.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${s.owner}/${s.name} answered: ${r}`}))}}}function Bi(e){let n=e.stalenessMs??12e4,t=e.activity;if(t==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:n,stale:!1,request_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[],reason:"the daemon polls no repository, so there are no counts to age"};let r=Date.parse(e.now),o=Date.parse(t.fetched_at),s=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,i=s==null||s>n;return{version:1,fetched_at:t.fetched_at,age_ms:s,threshold_ms:n,stale:t.projects.length>0&&i,request_count:t.request_count,rate_limit:t.rate_limit,projects:t.projects.map(l=>({...l,fetched_at:t.fetched_at,age_ms:s,stale:i})),reason:t.projects.length===0?"the daemon polls no repository, so there are no counts to age":s==null?"these counts carry no readable instant, so they cannot be presented as current":i?`these counts are ${s}ms old, past the ${n}ms window`:`fetched ${s}ms ago, within the ${n}ms window`}}function Ki(e){let n=e.endpoint??"https://api.github.com/graphql",t=e.fetchImpl??fetch;return async r=>{let o=await t(n,{method:"POST",headers:{authorization:`bearer ${e.token}`,"content-type":"application/json",accept:"application/vnd.github+json"},body:JSON.stringify({query:r})});if(!o.ok){let s=o.headers.get("x-ratelimit-remaining"),i=o.status===429||s==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(i?": the host token's rate limit is spent":""))}return await o.json()}}function Am(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 Im(e,n){let t=Te(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(Ji);return{remaining:r,reset_at:o,exhausted:s||r===0}}function Ji(e){if(e==null)return!1;let n=Er(e.type),t=Er(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function Ui(e,n){return Array.isArray(e)&&e.includes(n)}function Hi(e){let n=Te(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function Tm(e){let n=Te(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Te(e){return qi(e)?e:{}}function qi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Er(e){return typeof e=="string"?e:""}var Nm=3e4,Wm=4;function Gi(e){let n=e.stalenessMs??Nm,t=pn(e.now),r=e.sampledAt==null?null:pn(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),s=o!=null&&o<=n,i=new Set(e.reattachedWorkerIds??[]),l=e.hostState.workers.map(m=>Fm(m,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[m.worker_id],display:e.displays?.[m.worker_id],state:i.has(m.worker_id)?"reattached":"running"})),a=l.filter(m=>m.vitals.rss_bytes==null).map(m=>m.worker_id).sort(),c=l.length-a.length,u=l.reduce((m,g)=>m+(g.vitals.rss_bytes??0),0),p=qn(e.hostState.workers);return{version:1,generated_at:e.now,daemon:{pid:e.hostState.pid,daemon_version:e.hostState.daemon_version,protocol_version:e.hostState.protocol_version,started_at:e.hostState.started_at,machine_id_hash:e.hostState.machine_id_hash,session_key_hash:e.hostState.session_key_hash},staleness:Bm({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:Vm(l),known_projects:Hm(e.hostState),registered_projects:(e.hostState.registrations??[]).map(m=>m.project_label).sort((m,g)=>m.localeCompare(g)),workers:l,repository_activity:Bi({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:Mm(e.deaths,e.recentDeathLimit??Wm)},engine:Cm(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function Mm(e,n){let t=[...e].sort((o,s)=>(pn(s.ts)??0)-(pn(o.ts)??0)),r=t.slice(0,Math.max(0,Math.floor(n))).map(o=>({kind:o.kind,id:o.id,pid:o.pid,ts:o.ts,last_seen:o.last_seen,last_phase:o.last_phase,sender_class:o.sender_class,confidence:o.confidence,signal:o.signal,evidence:o.evidence[0]??null}));return{count:t.length,recent:r,latest:r[0]??null,reaped_at:r[0]?.ts??null}}function Cm(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 Fm(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=un(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=pn(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms:n.nowMs==null||i==null?null:Math.max(0,n.nowMs-i),state:n.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:r,sampled_at:r==null?null:n.sampledAt,age_ms:r==null?null:n.ageMs,fresh:r!=null&&n.sampleFresh},budget:{name:o?.name??null,declared:o?.declared??s,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:Um(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function Um(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 Hm(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 Vm(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 Bm(e){let n={sampled_at:e.sampledAt,age_ms:e.ageMs,threshold_ms:e.threshold,measured_worker_count:e.measuredCount,unmeasured_workers:e.unmeasured};return e.workerCount===0?{...n,stale:!1,reason:"the host holds no Workers, so there is nothing to measure and nothing to age"}:e.sampledAt==null||e.ageMs==null?{...n,stale:!0,reason:`this answer is stale: the daemon has taken no measurement of its ${e.workerCount} live Worker(s) yet`}:e.ageMs>e.threshold?{...n,stale:!0,reason:`this answer is stale: its measurement is ${e.ageMs}ms old, past the ${e.threshold}ms staleness window`}:{...n,stale:!1,reason:`measured ${e.ageMs}ms ago, within the ${e.threshold}ms staleness window`}}function pn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}var O={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function zi(e,n=O){let t=Ym(e,n),r=zm(e,n),o=Qm(e,n),s=Zm(e,n,r,t),i=qm(n,r,o),l={detail:"host",line:s};for(let p of i){let m=df(s,Gm(p,n,r,o),n.separator);if(l={detail:p,line:m},cf(m)<=n.maxWidth)break}let a=$r(l.line,n.maxWidth),c=n.verbose&&l.detail==="workers"?of(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 Qi(e){let n=e.options??O,t=$r(Jm,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 Km="!unregistered",Dr="\u21E1",Zn="\u2020",Jm="redskilled unreachable \u2014 Worker state unknown";function qm(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 Gm(e,n,t,r){return e==="workers"?t.map(o=>rf(o,n)):e==="projects"?r.map(af):[]}function zm(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Qm(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function Ym(e,n){return Or(e,n.project)}function Or(e,n){return n==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(n)?e.registered_projects==null||e.registered_projects.includes(n)?"matched":"name-only":"unregistered"}function Zm(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(jr(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(jr(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(jr(e,n)),o.push(Km)):o.push(nf(n.project,r)),o.push(Xm(e));let s=ef(e);return s!=null&&o.push(s),e.staleness.stale&&o.push(tf(e)),o.join(" ")}function Xm(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${Dr}`}function ef(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Zn}${n.count} ${n.latest.sender_class}`}function nf(e,n){return n==="unregistered"?`project unknown \u2014 ${e} is not registered on this host`:"project unknown \u2014 this directory resolved to no project"}function jr(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,s)=>o+s.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${U(t)}/${U(r)}`:U(t)}function tf(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function rf(e,n){let t=Yi(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 of(e,n){let t=[];for(let r of e){let o=lf(r.log.last_line);o!=null&&t.push($r(` ${sf} ${Yi(r,n)}: ${o}`,n.maxWidth))}return t}var sf="\u21B3";function lf(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}function Yi(e,n){return n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function af(e){return`${e.project_label} ${e.worker_count}w ${U(e.observed_rss_bytes)}`}function df(e,n,t){return[e,...n].join(t)}function cf(e){return[...e].length}function $r(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}function 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 Lr={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},uf=["runner","model","effort","origin","issue","phase","step","heartbeat"],pf=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function Zi(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...Lr};for(let r of uf){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of pf){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}var Xn=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],Ne={mode:"local",project:null,maxWidth:200,maxRows:16};var mf=" ",Xi="\u2588",ff="\u25B6",gf="\u2717",hf="\u2591";function el(e,n=Ne){let t=Or(e,n.project),r=yf(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(p=>kf(p,n)),i=Pf(s),l=o.map((p,m)=>({worker_id:p.worker_id,project_label:p.project_label,mine:n.project!=null&&p.project_label===n.project,cells:s[m],line:mn(jf(s[m],i),n.maxWidth)})),a=bf(e,n,r,t),c=r.length-o.length,u=[a.line,...l.map(p=>p.line)];return c>0&&u.push(mn(`\u2026 ${c} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),u.push(...wf(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Xn,header:a,rows:l,lines:u,hidden_row_count:Math.max(0,c),stale:e.staleness.stale}}function yf(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function kf(e,n){let t=e.display??Lr,r=[t.runner,t.model,t.effort].filter(o=>!!o).join(" ");return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:r===""?"":`run=${r}`,org:t.origin==null?"":`org=${t.origin}`,iss:t.issue==null?"":`iss=${t.issue}`,bar:Rf(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:Ef(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:xf(t.added,t.removed),tks:t.tokens==null?"":`tks=${nl(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function Rf(e){let n=e.phase_total,t=e.phase_index;if(n==null||n<=0||t==null||t<0)return"";let r=Math.min(Math.floor(t),Math.floor(n));if(r>=n)return Xi.repeat(Math.floor(n));let o=e.failed?gf:ff;return`${Xi.repeat(r)}${o}${hf.repeat(Math.floor(n)-r-1)}`}function bf(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(_=>_.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=Sf(t),a=o?.repository??n.project,c=e.engine??null,u=c?.running_version??e.daemon.daemon_version,p=e.deaths??null,m=e.metrics??null,g=[`\xBB ${a??"host"} v${u}${c!=null&&c.current===!1?Dr:""}`];r==="unregistered"&&g.push("!unregistered"),r==="name-only"&&g.push("!lapsed"),l!=null&&g.push(l),g.push(`wrk=${t.length}/${e.host.worker_count}`),g.push(i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`),g.push(vf(i)),s.open_pull_requests!=null&&g.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&g.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&g.push(`iss=${s.open_issues}`),s.stale&&g.push("!counts stale");let y=m==null?null:_f(m.hour);if(y!=null&&g.push(y),p!=null&&p.count>0&&p.latest!=null&&g.push(`${Zn}${p.count} ${p.latest.sender_class}`),e.staleness.stale){let _=e.staleness.age_ms;g.push(_==null?"!unmeasured":`!stale ${Math.round(_/1e3)}s`)}let b=g.join(" \xB7 "),k=y!=null&&Ir(b)>n.maxWidth?g.filter(_=>_!==y).join(" \xB7 "):b;return{repo:a,project:n.project,project_match:r,version:u,engine:c,deaths:p,metrics:m,model:l,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:mn(k,n.maxWidth)}}function _f(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${Ar(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${Ar(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${Ar(e.issues_per_hour.value)}`);let t=e.runner_share.shares[0];return t!=null&&n.push(`${t.key}=${Math.round(t.share*100)}%`),n.length===0?null:n.join(" ")}function wf(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(s=>mn(`${Zn} ${s.kind} ${s.id} pid=${s.pid} ${s.sender_class}/${s.confidence} phase=${s.last_phase}`+(s.signal==null?"":` signal=${s.signal}`)+(s.evidence==null?"":` \u2014 ${s.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(mn(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function 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 Sf(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 nl(e){if(!Number.isFinite(e)||e<=0)return"0";let n=(t,r)=>{let o=(Math.round(t*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${r}`};return e>=1e9?n(e/1e9,"B"):e>=1e6?n(e/1e6,"M"):e>=1e3?n(e/1e3,"k"):String(Math.round(e))}function Ar(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return nl(e);if(e<=0)return"0";let n=(Math.round(e*10)/10).toFixed(1);return n.endsWith(".0")?n.slice(0,-2):n}function Ef(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 Pf(e){let n=Object.fromEntries(Xn.map(t=>[t,0]));for(let t of e)for(let r of Xn)n[r]=Math.max(n[r],Ir(t[r]));return n}function jf(e,n){return Xn.filter(r=>n[r]>0).map(r=>Df(e[r],n[r])).join(mf).replace(/\s+$/,"")}function Df(e,n){return e+" ".repeat(Math.max(0,n-Ir(e)))}function Ir(e){return[...e].length}function mn(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}var et=1;async function fn(e,n){return await Fn(e,n,"redskilled daemon")}function tl(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.line=="string"&&Array.isArray(n.lines)&&n.lines.every(t=>typeof t=="string")&&typeof n.verbose=="boolean"&&(n.mode==="local"||n.mode==="global")&&(n.project===null||typeof n.project=="string")&&typeof n.detail=="string"&&(n.project_match===void 0||typeof n.project_match=="string")&&typeof n.degraded=="boolean"&&typeof n.stale=="boolean"&&typeof n.generated_at=="string"}function rl(e){let n=[...e.workers??[]],t=new Map;for(let r of n)t.set(r.project_label,(t.get(r.project_label)??0)+1);return{version:1,protocol_version:et,daemon_version:e.daemonVersion,machine_id_hash:e.machineIdHash,session_key_hash:e.sessionKeyHash,pid:e.pid,started_at:e.startedAt,...e.scope==null?{}:{scope:e.scope},workers:n,projects:[...t.entries()].map(([r,o])=>({project_label:r,worker_count:o})).sort((r,o)=>r.project_label.localeCompare(o.project_label)),registrations:Lf(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:oi(n),upgrade:Af(e)}}function Lf(e){let n=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(n),r=e.queue??null,o=new Map(r==null?[]:r.projects.map(s=>[s.project_label,s]));return[...e.registrations??[]].map(s=>{let i=o.get(s.project_label);return{...s,...t?{renewal:Oi(s,n)}:{},...r==null||i==null?{}:{last_poll:{at:r.fetched_at,outcome:i.outcome,depth:i.depth,request_count:r.request_count,detail:i.detail}}}}).sort((s,i)=>s.project_label.localeCompare(i.project_label))}function Af(e){let n=e.daemonVersion,t=e.published?.version??null,r=e.published?.majorHold??null;return{running_version:n,published_version:t,published_unknown:+(t===null),newer_published:+(e.published?.newer===!0),replacement:e.published?.replacement??"none",checked_at:e.published?.checkedAt??null,checks:e.published?.checks??0,hold_reason:e.published?.holdReason??null,newest_published_version:e.published?.newest??null,major_held:+(r!==null),major_hold:r}}function ol(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.protocol_version=="number"&&typeof n.daemon_version=="string"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&Number.isInteger(n.pid)&&typeof n.started_at=="string"&&Array.isArray(n.workers)&&Array.isArray(n.projects)&&si(n.budget_accounting)&&(n.scope===void 0||Ei(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(Sr))&&(n.upgrade===void 0||If(n.upgrade))}function If(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||Tf(n.major_hold))}function Tf(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.version=="string"&&Number.isInteger(n.running_major)&&Number.isInteger(n.held_major)&&typeof n.reason=="string"&&typeof n.action=="string"&&n.action.trim()!==""}import{spawnSync as rt}from"node:child_process";import{existsSync as Cr}from"node:fs";import{delimiter as Bf,join as fl}from"node:path";import{join as sl}from"node:path";import{existsSync as Nf}from"node:fs";import{createRequire as Wf}from"node:module";var il="redskilled-job-object.node",we=100;function We(e){return{available:!1,reason:e}}function Mf(e,n,t){return[sl(t,"prebuilds",`${e}-${n}`,il),sl(t,"native","build","Release",il)]}function ll(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return We(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??Ff(),o=e.exists??Nf,s=Mf(n,t,r),i=s.find(c=>o(c));if(i==null)return We(`no Job Object addon was found for ${n}-${t} (looked in ${s.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let l=e.requireFn??Wf(import.meta.url),a;try{a=l(i)}catch(c){return We(`the Job Object addon at ${i} could not be loaded: ${c instanceof Error?c.message:String(c)}`)}return Cf(a)?{available:!0,binding:a}:We(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function Cf(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Ff(){return new URL("..",import.meta.url).pathname}function al(e){let n=e??{},t=[],r=Uf(n);r==null&&(n.memory_max??n.memory_high)!=null&&t.push("the declared memory budget could not be reduced to bytes, so the job carries no memory ceiling");let o;return n.cpu_weight!=null&&(n.cpu_weight<we?o=Math.max(1,Math.min(100,Math.round(n.cpu_weight))):t.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${we}, and Windows CPU rate control is an absolute cap rather than a share, so no rate limit is set`)),{...r!=null?{memory_limit_bytes:r.bytes,memory_budget_name:r.name,memory_budget_declared:r.declared}:{},...o!=null?{cpu_rate_percent:o}:{},kill_on_close:!0,...t.length>0?{note:t.join("; ")}:{}}}function Uf(e){return un({budget:e})}var nt=5,dl=19;function Tr(e){return{available:!1,reason:e}}var Hf="an address-space rlimit is not a resident-memory ceiling: a runtime that reserves address space it never faults in would die under a limit it never used, so no memory rlimit is set and the daemon's RSS sampling floor is the ceiling that actually holds";function ul(e,n){let t=e??{},r=[],o;if(!n.canRenice)r.push("nice is not on this host, so no priority control was applied and the Worker competes with interactive work");else if(t.cpu_weight==null)o=nt;else if(t.cpu_weight<we){let l=Math.round(dl*(we-t.cpu_weight)/we);o=Math.min(dl,Math.max(nt,l))}else o=nt,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${we}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${nt}`);let s=cl(t.max_processes);s==null&&t.max_processes!=null&&r.push(`max_processes=${t.max_processes} is not a positive whole number, so no ulimit -u is set`);let i=cl(t.cpu_seconds);return i==null&&t.cpu_seconds!=null&&r.push(`cpu_seconds=${t.cpu_seconds} is not a positive whole number, so no ulimit -t is set`),{...o!=null?{nice:o}:{},...s!=null?{max_processes:s}:{},...i!=null?{cpu_seconds:i}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:Hf,...r.length>0?{note:r.join("; ")}:{}}}function pl(e){let{limits:n}=e,t=[];return n.max_processes!=null&&t.push(`ulimit -u ${n.max_processes}`),n.cpu_seconds!=null&&t.push(`ulimit -t ${n.cpu_seconds}`),t.push(n.nice!=null&&e.nice!=null?`exec ${Vf(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
60
- `),e.command,...e.args]}function ml(e){let n=[];return e.nice!=null?n.push(`the Worker runs at nice ${e.nice} so it yields to interactive work`):n.push("no priority control was applied"),e.max_processes!=null&&n.push(`its processes are capped at ${e.max_processes}`),e.cpu_seconds!=null&&n.push(`its CPU time is capped at ${e.cpu_seconds} seconds`),`macOS placement applied POSIX limits: ${n.join(", ")}. macOS has no resource-group equivalent, so the Worker is charged to the daemon's own resource group, and ${e.memory_ceiling_reason}`+(e.note!=null?` (${e.note})`:"")}function Nr(e){let n=e??{},t=[n.max_processes!=null?"max_processes":null,n.cpu_seconds!=null?"cpu_seconds":null].filter(r=>r!=null);return t.length===0?null:`${t.join(" and ")} ${t.length===1?"is a POSIX rlimit":"are POSIX rlimits"} honoured only by the macOS placement backend, so this placement carries no equivalent`}function cl(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function Vf(e){return`'${e.replace(/'/g,"'\\''")}'`}var gl="REDSKILLED_PLACEMENT",tt="red-worker",Wr="/bin/sh";function hl(e=process.env,n=process.platform){let t=Tr(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:ll({platform:n}),posix:t};let r=We(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);if(n==="darwin")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:Kf(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Cr(fl(o,"systemd","private"));return{platform:n,systemdRun:bl("systemd-run",e),userSession:s,jobObjects:r,posix:t}}function Kf(e){return Cr(Wr)?{available:!0,shell:Wr,nice:bl("nice",e)}:Tr(`no POSIX shell was found at ${Wr}, so there is nothing to apply rlimits or priority in`)}function yl(e=process.env){let n=(e[gl]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Jf(e,n,t=tt){return kl(e,n,t).replace(/\.service$/,"")}function kl(e,n,t=tt){return`${Mr(t,"red-worker",24)}-${Mr(e,"project",32)}-${Mr(n,"worker",32)}.service`}function Rl(e){let n=[...e.args??[]],t={...e.budget??{},...e.budget?.memory_max==null&&e.memoryCeiling?.memory_max!=null?{memory_max:e.memoryCeiling.memory_max}:{}},r=t.memory_max??t.memory_high??null,o=t.memory_high!=null||t.memory_max!=null||t.cpu_weight!=null,s=e.target??{isolation:"transient-unit"},i=p=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:p,...r!=null?{memoryCeiling:r}:{},environment:tn({scope:null,memory_ceiling:r,scope_degradation:p}),...o?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(s.isolation==="inherit")return i("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return i(`worker isolation disabled by ${gl}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return Gf(e,n,t,r,o,i);if(e.probes.platform==="darwin")return qf(e,n,t,r,i);if(e.probes.platform!=="linux")return i(`transient-unit placement is the Linux backend (platform=${e.probes.platform}): the Worker is charged to the daemon's own resource group`);if(!e.probes.systemdRun)return i("transient-unit placement unavailable: systemd-run is not on PATH; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");if(!e.probes.userSession)return i("transient-unit placement unavailable: no systemd --user session; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");let l=kl(e.projectLabel,e.workerId,s.unit_prefix),a=["--user","--collect","--quiet","--wait",`--unit=${l}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&a.push("--pipe"),t.memory_high!=null&&a.push(`--property=MemoryHigh=${t.memory_high}`),t.memory_max!=null&&a.push(`--property=MemoryMax=${t.memory_max}`),t.cpu_weight!=null&&a.push(`--property=CPUWeight=${t.cpu_weight}`);let c=tn({scope:l,memory_ceiling:r,scope_degradation:null});for(let[p,m]of Object.entries({...e.env??{},...c}))a.push(`--setenv=${p}=${m}`);let u=Nr(e.budget);return{isolated:!0,backend:"transient-unit",unit:l,command:e.probes.systemdRun,args:[...a,"--",e.command,...n],...r!=null?{memoryCeiling:r}:{},environment:c,...u!=null?{budgetWarning:u}:{}}}function qf(e,n,t,r,o){let s=e.probes.posix;if(!s.available)return o(`POSIX limit placement unavailable: ${s.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let i=ul(t,{canRenice:s.nice!=null}),l=t.memory_high!=null||t.memory_max!=null,a=ml(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:pl({limits:i,nice:s.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:i,warning:a,...r!=null?{memoryCeiling:r}:{},environment:tn({scope:null,memory_ceiling:r,scope_degradation:a}),...l?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+i.memory_ceiling_reason}:{}}}function Gf(e,n,t,r,o,s){let i=e.probes.jobObjects;if(!i.available)return s(`Job Object placement unavailable: ${i.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let l=al(t),a=Jf(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...n],cwd:e.workspacePath,job:{name:a,limits:l},...r!=null?{memoryCeiling:r}:{},environment:tn({scope:a,memory_ceiling:r,scope_degradation:null}),...zf(o&&l.note!=null?`${l.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,Nr(e.budget))}}function zf(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function bl(e,n){for(let t of(n.PATH??"").split(Bf)){if(!t)continue;let r=fl(t,e);if(Cr(r))return r}return null}function Mr(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function Fr(e,n){let t=[],r=[];for(let o of e){let s=!1;try{s=await n(o)===!0}catch{s=!1}(s?t:r).push(o)}return{alive:t,dead:r}}function _l(e){return e.unit!=null&&e.unit!==""?Qf(e.unit):W(e.pid)}function Qf(e){let n=rt("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var Yf="REDSKILLED_UNIT_DISCOVERY",wl="(unowned)";function vl(e){let n=rt("systemctl",["--user","show","--property=MainPID","--value",e],{encoding:"utf8"});if(n.error!=null||n.status!==0)return null;let t=Number.parseInt((n.stdout??"").trim(),10);return Number.isInteger(t)&&t>0?t:null}function Zf(e=process.env){let n=(e[Yf]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Sl(e,n,t=process.env){return Zf(t)&&e===n}function xl(e=tt){let n=rt("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return n.error!=null||n.status!==0?[]:(n.stdout??"").split(`
61
- `).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function El(e){let n=new Set(e.held.map(o=>o.unit).filter(o=>o!=null&&o!=="")),t=new Set,r=[];for(let o of e.units)o===""||n.has(o)||t.has(o)||(t.add(o),r.push({worker_id:o.replace(/\.service$/,""),project_label:wl,pid:e.mainPid?.(o)??0,started_at:e.now,workspace_path:"",isolated:!0,unit:o,warnings:[`adopted from active unit ${JSON.stringify(o)}, which has no birth on this host's event lane: its project, its Worker id and its budget belonged to a daemon that is gone, so they are reported as unknown rather than guessed \u2014 it is counted against the host budget from here on instead of running outside it`]}));return r}function Pl(e){return e.project_label.trim()!==""?e:{...e,project_label:wl,warnings:[...e.warnings,"adopted at start with no owning project on the event lane: the daemon that birthed it recorded no project label, so it is held and counted under a stated placeholder rather than dropped"]}}function jl(e){if(e.unit!=null&&e.unit!==""){let n=rt("systemctl",["--user","stop",e.unit],{stdio:"ignore"});return n.error==null&&n.status===0}try{return process.kill(e.pid,"SIGTERM"),!0}catch{return!1}}function Xf(e,n=50){if(Ll(e),!Number.isInteger(n)||n<=0)throw new Error(`redskilled queue discovery needs a whole, positive batch size, not ${JSON.stringify(n)}`);let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}function eg(e,n={}){let t=n.batchSize??50;if(Ll(e),e.length>t)throw new Error(`redskilled queue discovery spans at most ${t} selectors in one query, and this batch holds ${e.length}: split it with planQueueDiscoveryBatches rather than dropping the remainder`);let r=e.map((i,l)=>({alias:`q${l}`,project:i}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...r.map(({alias:i,project:l})=>` ${i}: search(query: ${JSON.stringify(l.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
62
- `),aliases:r}}function ng(e,n){let t=gn(n),r=gn(t.data),o=Array.isArray(t.errors)?t.errors.map(gn):[],s=rg(r.rateLimit,o);return{projects:e.aliases.map(({alias:l,project:a})=>{let c=sg(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=>og(p.path,l));return s.exhausted||Al(u)?{project_label:a.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(a.project_label)} answered, so this queue has no depth rather than a depth of zero`+(s.reset_at==null?"":`; the quota resets at ${s.reset_at}`)}:{project_label:a.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(a.project_label)} could not be counted with the host token: ${Ur(u?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function tg(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function Ol(e,n,t){return{version:1,fetched_at:n,request_count:0,project_count:e.length,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:e.map(r=>({project_label:r.project_label,outcome:"unconfigured",depth:null,detail:`project ${JSON.stringify(r.project_label)} was not counted because this host polls no tracker: ${t}`}))}}async function $l(e){if(e.projects.length===0)return tg(e.now);let n=e.batchSize??50,t=Xf(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=eg(s,{batchSize:n});try{let l=await e.transport(i.query),a=ng(i,l);r.push(...a.projects),o=Dl(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=Dl(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 Ll(e){if(e.length===0)throw new Error("redskilled queue discovery needs at least one registered project");let n=new Set;for(let t of e){if(typeof t.project_label!="string"||t.project_label==="")throw new Error("redskilled queue discovery needs a project label for every registered project");if(typeof t.selector!="string"||t.selector==="")throw new Error(`redskilled queue discovery needs a selector for project ${JSON.stringify(t.project_label)}: a project that names no work has no queue to discover`);if(n.has(t.project_label))throw new Error(`redskilled holds one selector per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function Dl(e,n){return{remaining:n.remaining==null?e.remaining:e.remaining==null?n.remaining:Math.min(e.remaining,n.remaining),reset_at:n.reset_at??e.reset_at,exhausted:e.exhausted||n.exhausted}}function rg(e,n){let t=gn(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null;return{remaining:r,reset_at:o,exhausted:n.some(Al)||r===0}}function Al(e){return e==null?!1:Ur(e.type)==="RATE_LIMITED"||/rate limit/i.test(Ur(e.message))}function og(e,n){return Array.isArray(e)&&e.includes(n)}function sg(e){let n=gn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function gn(e){return ig(e)?e:{}}function ig(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ur(e){return typeof e=="string"?e:""}import{randomUUID as Il}from"node:crypto";import{spawn as lg}from"node:child_process";import{closeSync as ag,mkdirSync as dg,openSync as cg}from"node:fs";import{dirname as ug}from"node:path";var hn=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},ot=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function pg(e){if(e==null||e.trim()==="")return null;try{return dg(ug(e),{recursive:!0}),cg(e,"a")}catch{return null}}function mg(e){try{ag(e)}catch{}}function fg(e){let n=[["project_label",e.project_label],["workspace_path",e.workspace_path],["command",e.command]];for(let[t,r]of n)if(typeof r!="string"||r.trim()==="")throw new hn(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new hn("redskilled worker spec args must be an array")}function gg(e){if(e==null)throw new ot("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new ot(e.reason,e)}function Nl(e){let{spec:n,admission:t}=e;gg(t),fg(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(n.worker_id??e.workerId??Il()).trim()||Il(),i=e.probes??hl(r),l=e.openLog===!1?null:pg(n.log_path),a=Rl({workerId:s,projectLabel:n.project_label,workspacePath:n.workspace_path,command:n.command,args:n.args,budget:n.budget,...e.memoryCeiling!=null?{memoryCeiling:e.memoryCeiling}:{},target:n.placement,env:n.env,enabled:e.enabled??yl(r),probes:i,pipeOutput:l!==null}),u=(e.spawnFn??lg)(a.command,a.args,{...a.cwd!=null?{cwd:a.cwd}:{},detached:!0,stdio:l===null?"ignore":["ignore",l,l],env:a.backend==="transient-unit"?{...r}:{...r,...n.env??{},...a.environment}});if(l!==null&&mg(l),u.pid==null)throw u.once("error",()=>{}),new hn(`redskilled could not spawn ${JSON.stringify(a.command)} for worker ${s}`);let p=a.job!=null?hg(a,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(b,k)=>{try{p?.job?.close()}catch{}e.onExit?.(s,b,k)}),u.unref();let m=a.job!=null?p?.job!=null:a.isolated,g=[a.warning,p?.warning,a.budgetWarning].filter(b=>b!=null);return{worker:{worker_id:s,project_label:n.project_label,pid:u.pid,started_at:o(),workspace_path:n.workspace_path,...n.log_path!=null?{log_path:n.log_path}:{},isolated:m,...a.unit!=null?{unit:a.unit}:{},...n.budget!=null?{budget:n.budget}:{},...a.memoryCeiling!=null?{memory_ceiling:a.memoryCeiling,memory_ceiling_reason:e.memoryCeiling?.reason??"this Worker's ceiling is the budget its client declared"}:{},warnings:g},admission:t,warnings:g,plan:a,child:u,...p?.job!=null?{job:p.job}:{}}}function hg(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: ${Tl(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)}: ${Tl(i)}. ${o}`}}return{job:s}}function Tl(e){return e instanceof Error?e.message:String(e)}import{open as yg,stat as kg}from"node:fs/promises";var Rg=16*1024;async function Wl(e,n=Rg){let t;try{t=(await kg(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let s=await yg(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 bg(o)}function bg(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 Ig}from"node:child_process";import{existsSync as Tg,readdirSync as Ng}from"node:fs";import{dirname as Wg,join as Vl,resolve as Mg}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 Hr(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 r_=4*60*60*1e3;re();re();import{spawnSync as _g}from"node:child_process";import{mkdir as wg,rm as vg,writeFile as Sg}from"node:fs/promises";import{existsSync as xg}from"node:fs";import{homedir as Eg}from"node:os";import{dirname as Pg,join as Vr}from"node:path";var Me="redskilled.service",Br="REDSKILLED_SUPERVISED",jg="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function Dg(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||Vr(e.HOME?.trim()||Eg(),".config");return Vr(n,"systemd","user")}function Kr(e=process.env){return Vr(Dg(e),Me)}function Ml(e,n={}){let t=n.env??process.env,r=Bn(n.override??{},n.entryLookup??{}),o=[...r.args,..._e(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:Me,unitPath:Kr(t),command:r.command,args:o,text:Og(r.command,o,e)}}function Og(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${jg}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map($g).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Br}=1"`,`Environment="REDSKILLED_SESSION=${Cl(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
64
- `)}function $g(e){return/[\s"'\\$%]/.test(e)?`"${Cl(e)}"`:e}function Cl(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function Fl(e,n={}){let t=n.writeFile??Lg,r=n.run??Jr,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(st("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(st("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function Ul(e={}){let n=e.removeFile??Ag,t=e.run??Jr,r=Kr(e.env??process.env),o=[st("disable",t,["systemctl","--user","disable","--now",Me])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(st("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function Hl(e={}){let n=e.exists??xg,t=e.run??Jr,r=Kr(e.env??process.env),o=n(r);return{unitName:Me,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",Me]).status===0,active:o&&t(["systemctl","--user","is-active",Me]).status===0,floor:"auto-spawn"}}function st(e,n,t){let r=n(t),o=(r.stderr??r.stdout??"").trim();return{step:e,argv:t,ok:r.status===0,...o?{detail:o}:{}}}async function Lg(e,n){await wg(Pg(e),{recursive:!0}),await Sg(e,n,{encoding:"utf8",mode:420})}async function Ag(e){await vg(e,{force:!0})}function Jr(e){let n=_g(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,Jl=9e5,Kl="redskilled-replacement-entry-unresolved",Cg="REDSKILLED_NO_REGISTRY_PROBE",ql="REDSKILLED_BORN_BY_REPLACEMENT";function Gl(e=process.env){return e[ql]==="1"}function zl(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function Ql(e){let n=e.running.trim();if(yn(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:Fg(r.major,e.supervised)}}function Fg(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 Yl(e){let n=e.running.trim();if(yn(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||H(t)===null?{act:"hold",reason:"published-unknown"}:Hr(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function yn(e){let n=e.trim();return H(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function Zl(e=process.env){return e[Br]==="1"}var qr=class extends Error{code=Kl;searched;constructor(n,t){super(`${Kl}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
62
+ `).filter(Fm).map(Um)}function bl(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,Wm(t)):n.delete(t.worker_id));return[...n.values()]}function Wm(e){let n={...e.memory_high!=null?{memory_high:e.memory_high}:{},...e.memory_max!=null?{memory_max:e.memory_max}:{},...e.cpu_weight!=null?{cpu_weight:e.cpu_weight}:{}};return{worker_id:e.worker_id,project_label:e.project_label,pid:e.pid,started_at:e.ts,workspace_path:e.workspace_path,...e.log_path!=null?{log_path:e.log_path}:{},isolated:e.isolated,...e.unit!=null?{unit:e.unit}:{},...Object.keys(n).length>0?{budget:n}:{},warnings:[]}}function Hm(e){return{...e}}function Fm(e){return e.version===1&&typeof e.ts=="string"&&typeof e.worker_id=="string"&&(e.event==="worker-birth"||e.event==="worker-death"||e.event==="worker-budget-kill"||e.event==="daemon-stop")}function Um(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:fe(e.project_label)??"",pid:Number(e.pid??0),workspace_path:fe(e.workspace_path)??"",log_path:fe(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:fe(e.unit),memory_high:fe(e.memory_high),memory_max:fe(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:fe(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:fe(e.signal),reason:fe(e.reason)}}function fe(e){return e==null||e===""?null:String(e)}function _l(e){let n=[...e.projects].sort((s,a)=>s.project_label.localeCompare(a.project_label)),t=e.backoffUntilMs??null,r=t!=null&&e.nowMs<t,o=[],i=[];for(let s of n){let a=Math.max(0,e.live[s.project_label]??0),l=Object.prototype.hasOwnProperty.call(e.queue,s.project_label),d=l?e.queue[s.project_label]??null:null,p={project_label:s.project_label,queue_depth:d,target:s.target,live:a};if(r){o.push({...p,outcome:"backing-off",wanted:0,detail:`the host refused a Worker, so no project is asked for one again before ${new Date(t).toISOString()}`});continue}let u=e.birthHaltUntilMs?.[s.project_label];if(u!=null&&e.nowMs<u){o.push({...p,outcome:"birth-halted",wanted:0,detail:`project ${JSON.stringify(s.project_label)} lost 3 Workers in a row inside 60000ms of birth, so it is not asked for another before ${new Date(u).toISOString()} \u2014 a Worker that cannot survive boot will not survive the next one either, and every birth spends host quota shared with every project`});continue}if(d==null){o.push({...p,outcome:"queue-unknown",wanted:0,detail:l?`the last poll produced no depth for project ${JSON.stringify(s.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(s.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...p,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(s.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,s.target),d)-a);if(f===0){o.push({...p,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(s.project_label)} holds ${a} Worker(s) against a target of ${s.target} and a queue of ${d}, so it asks for none`});continue}o.push({...p,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(s.project_label)} holds ${a} Worker(s) against a target of ${s.target} and a queue of ${d}, so it asks for ${f} more`});for(let m=0;m<f;m+=1)(i[m]??(i[m]=[])).push({project_label:s.project_label,index:a+m,argv:s.argv,workspace_path:s.workspace_path})}return{intents:o,births:i.flat()}}function wl(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}var Rt={shortLifeStreak:0,haltUntilMs:null};function xl(e,n,t){if(n>=6e4)return Rt;let r=e.shortLifeStreak+1;return r<3?{shortLifeStreak:r,haltUntilMs:null}:{shortLifeStreak:r,haltUntilMs:t+6e5}}function Sl(e,n){let t={};for(let[r,o]of Object.entries(e))o.haltUntilMs!=null&&n<o.haltUntilMs&&(t[r]=o.haltUntilMs);return t}function El(e){let n=e.workers.map(Bm),t=[...new Set([...n.map(o=>o.project_label),...e.projects??[]])].filter(o=>o!=="").sort(),r=n.filter(o=>o.survives).map(o=>o.worker_id);return{version:1,running:!0,stopped:!0,reason:e.reason,socket_path:e.socketPath,daemon_version:e.daemonVersion,pid:e.pid,holding:{workers:n,projects:t},surviving:r,detail:Km({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function Pl(e){return{version:1,running:!1,stopped:!1,reason:"not-running",socket_path:e,daemon_version:null,pid:null,holding:{workers:[],projects:[]},surviving:[],detail:`no redskilled daemon is answering on ${JSON.stringify(e)}, so there was nothing to stop`}}function Bm(e){return{worker_id:e.worker_id,project_label:e.project_label,pid:e.pid,unit:e.unit??null,isolated:e.isolated,survives:!0}}function Vm(e){return e==="requested"?"an operator asked for it":e==="signal"?"the daemon was signalled":e==="idle"?"the daemon was idle and held nothing":e==="replaced"?"a newer published bundle is taking the session over":"no daemon was running"}function Km(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Vm(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${vl(e.held,"Worker")} across ${vl(e.projects,"project")}, and ${e.surviving} of them survive it \u2014 a Worker is an init-system unit, so this is a restart and not an evacuation`}function vl(e,n){return`${e} ${n}${e===1?"":"s"}`}function Xr(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.holding;return n.version===1&&typeof n.running=="boolean"&&typeof n.stopped=="boolean"&&typeof n.reason=="string"&&typeof n.socket_path=="string"&&typeof n.detail=="string"&&(n.daemon_version===null||typeof n.daemon_version=="string")&&(n.pid===null||typeof n.pid=="number")&&t!=null&&Array.isArray(t.workers)&&Array.isArray(t.projects)&&Array.isArray(n.surviving)}import{chmod as qm,mkdir as Jm,readFile as Gm,rm as Qm,writeFile as zm}from"node:fs/promises";import{dirname as jl,join as Ll}from"node:path";import{tmpdir as Dl}from"node:os";var Ym="redskilled.machine.claim.toon",Xm="REDSKILLED_MACHINE_DIR",Zm=8,be=class extends Error{constructor(t,r,o){super(nh(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},Ol;function $l(){return Ol??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},Ol}function eh(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[Xm]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||Dl():Dl();return Ll(o,`redskilled-${e.machineIdHash}`)}function bt(e){return Ll(eh(e),Ym)}function _t(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??U;async function i(){let l;try{l=await Gm(e,"utf8")}catch(p){if(p.code==="ENOENT"||Zr(p))return;throw p}let d=rh(l);return oh(d)?d:void 0}function s(l,d){return{version:1,scope:"machine",pid:l.pid,start_time:l.startTime,uid:l.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}async function a(){try{return await Qm(e,{force:!0}),!0}catch(l){if(Zr(l))return!1;throw l}}return{claimPath:e,read:i,async claim(l){await Jm(jl(e),{recursive:!0,mode:1023})!=null&&await qm(jl(e),1023).catch(()=>{});let p=!1;for(let u=0;u<Zm;u+=1){let f=s(l,r());try{return await zm(e,th(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:p,claim:f}}catch(h){if(h.code!=="EEXIST"){if(Zr(h))return{claimed:!1,reason:"stale-claim-not-reapable"};throw h}}let m=await i();if(!m){if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable"};p=!0;continue}if(Al(m,l,n.socketPath))return{claimed:!0,reaped:p,claim:m};if(await o(m.pid))return{claimed:!1,reason:"held",claim:m};if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable",claim:m};p=!0}return{claimed:!1,reason:"contended"}},async release(l){let d=await i();return!d||!Al(d,l,n.socketPath)?!1:await a()}}}function Il(e,n,t){return{kind:"machine",claim_path:e,owner_uid:t.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath}}function Tl(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.kind==="machine"&&typeof n.claim_path=="string"&&typeof n.owner_uid=="number"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&typeof n.socket_path=="string"}function nh(e,n,t){let r=t==null?"":` \u2014 held by pid ${t.pid} (uid ${t.uid}) on socket ${JSON.stringify(t.socket_path)}`;return n==="held"?`this machine already has a redskilled daemon${r}; a second one would void the host budget, so none was started. Reach that daemon, or stop it before starting another.`:n==="stale-claim-not-reapable"?`the redskilled machine claim ${JSON.stringify(e)} is stale and cannot be removed by this user${r}; remove it as its owner, then start again. No second daemon was started.`:`the redskilled machine claim ${JSON.stringify(e)} changed hands repeatedly; no daemon was started.`}function Zr(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function Al(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function th(e){return`${M(e,{keyedMapCollapse:!0})}
63
+ `}function rh(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return z(n)}catch{return null}}}function oh(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||n.scope!=="machine"||!Number.isInteger(n.pid)||n.pid<=0||!Number.isInteger(n.uid))return!1;for(let t of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var ih=["worker_id","slot","workspace_path","log_path"],eo=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${ih.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},sh=/\{\{([a-z_]+)\}\}/g;function lh(e,n){let t=(s,a)=>s.replace(sh,(l,d)=>{switch(d){case"worker_id":return n.worker_id;case"slot":return String(n.slot);case"workspace_path":return n.workspace_path;case"log_path":return n.log_path??"";default:throw new eo(d,a)}}),r=e.argv.map((s,a)=>t(s,`argv word ${a}`)),o={};for(let[s,a]of Object.entries(e.env??{}))o[s]=t(a,`env entry ${JSON.stringify(s)}`);let i=e.log_path==null?void 0:t(e.log_path,"the log path");return{argv:r,env:o,...i==null||i===""?{}:{log_path:i}}}function Nl(e,n,t){let r=lh(e,n),o=r.log_path??n.log_path,[i,...s]=r.argv;if(i===void 0||i==="")throw new Error(`redskilled cannot start a Worker for project ${JSON.stringify(t.project_label)}: its launch expanded to an argv with no command`);return{worker_id:n.worker_id,project_label:t.project_label,workspace_path:n.workspace_path,...o==null||o===""?{}:{log_path:o},command:i,args:s,env:r.env}}function no(e,n){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(n)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((t,r)=>{if(typeof t!="string"||t==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${r} of project ${JSON.stringify(n)} is not`);return t})}function to(e,n){if(e!=null){if(typeof e!="string"||e.trim()==="")throw new Error(`redskilled needs a declared log path to be a non-empty string to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}: a project that declares an empty path states a Worker whose output no surface can ever show, which reads as a Worker with nothing to say`);return e}}function ro(e,n){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error(`redskilled needs a launch env to be a map of strings to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}`);let t={};for(let[r,o]of Object.entries(e)){if(r==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(n)} to be named`);if(typeof o!="string")throw new Error(`redskilled needs every launch env value to be a string, and ${JSON.stringify(r)} of project ${JSON.stringify(n)} is ${JSON.stringify(o)}`);t[r]=o}return t}var ah=3e5,dh=.5,io=class extends Error{constructor(t){super(`redskilled already holds a registration for project ${JSON.stringify(t.project_label)}, registered at ${t.registered_at} for a target of ${t.target} and standing until ${t.renew_by}: a project contributes one registration, so a second one is refused rather than silently replacing the first`);this.held=t;this.name="RedskilledProjectRegisteredError"}};function Cl(e,n){if(n.held!=null)throw new io(n.held);let t=oo(e.project_label,"a project label"),r=oo(e.selector,"a selector"),o=no(e.argv,t),i=ro(e.env,t),s=to(e.log_path,t),a=oo(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.target)}`);let l=e.renew_within_ms??ah;if(!Number.isFinite(l)||l<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let d=Date.parse(n.now);if(!Number.isFinite(d))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(n.now)}`);return{version:1,project_label:t,selector:r,argv:o,workspace_path:a,env:i,...s==null?{}:{log_path:s},target:e.target,registered_at:new Date(d).toISOString(),renew_within_ms:l,renew_by:new Date(d+l).toISOString(),renewed_at:new Date(d).toISOString(),renewals:0,launch_revision:0}}var wt=class extends Error{constructor(t){super(`redskilled holds no registration for project ${JSON.stringify(t)} to renew: it lapsed or was never held, and a renewal never mints a record \u2014 register again, stating the selector, the argv and the target`);this.projectLabel=t;this.name="RedskilledProjectUnregisteredError"}};function Ml(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(n.now)}`);let r=n.renew_within_ms??e.renew_within_ms;if(!Number.isFinite(r)||r<=0)throw new Error(`redskilled needs a positive renewal window to renew project ${JSON.stringify(e.project_label)}, not ${JSON.stringify(n.renew_within_ms)}`);let o=n.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:no(n.launch.argv,e.project_label),env:ro(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},i=n.launch==null?e.log_path:to(n.launch.log_path,e.project_label),{log_path:s,...a}=e;return{...a,...i==null?{}:{log_path:i},...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1}}function Wl(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(n.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,n.liveWorkers??0),i=n.queue,s=i!=null&&i.outcome==="counted"?i.depth:null,a=s!=null&&s>0?"open-work":o>0?"live-worker":null;if(a==null){let l=s===0?"drained":"uncounted";return{registration:e,verdict:l,detail:l==="drained"?`project ${r} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${r}, and an uncounted queue never sustains a registration \u2014 it stands on its own deadline of ${e.renew_by}`}}return{registration:{...e,renew_by:new Date(t+e.renew_within_ms).toISOString(),sustained_at:new Date(t).toISOString(),sustains:(e.sustains??0)+1,sustained_by:a},verdict:a,detail:a==="open-work"?`project ${r} has ${s} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function ch(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function Hl(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=i=>Number.isFinite(i)&&n-i<=e.renew_within_ms*dh;if(r(t))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return r(o)?"self-renewing":"running-on"}function Fl(e,n){let t=[],r=[];for(let o of e)(ch(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function so(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.project_label=="string"&&typeof n.selector=="string"&&Array.isArray(n.argv)&&n.argv.every(t=>typeof t=="string")&&typeof n.workspace_path=="string"&&Number.isInteger(n.target)&&typeof n.registered_at=="string"&&typeof n.renew_within_ms=="number"&&typeof n.renew_by=="string"&&(n.renewed_at===void 0||typeof n.renewed_at=="string")&&(n.renewals===void 0||Number.isInteger(n.renewals))&&(n.env===void 0||uh(n.env))&&(n.log_path===void 0||typeof n.log_path=="string")&&(n.launch_revision===void 0||Number.isInteger(n.launch_revision))&&(n.sustained_at===void 0||typeof n.sustained_at=="string")&&(n.sustains===void 0||Number.isInteger(n.sustains))&&(n.sustained_by===void 0||n.sustained_by==="open-work"||n.sustained_by==="live-worker")}function uh(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function oo(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var ph={ping:"host-read","host-state":"host-read","statusline-payload":"host-read",shutdown:"daemon-life","worker-start":"project-write","worker-stop":"project-write","worker-recycle":"project-write","worker-steer":"project-write","worker-heartbeat":"project-write","project-register":"project-write","project-renew":"project-write","project-deregister":"project-write"};function Ul(e){return`worker-${e}`}function Bl(e){let n=ph[e.op]??"project-write",t=e.sessionProject??null,r=e.targetProject??null,o={version:1,op:e.op,reach:n,session_project:t,target_project:r};return n==="host-read"?{...o,permitted:!0,verdict:"permitted-host-read",reason:`redskilled permitted ${e.op}: a session reads the whole host, whichever project it was started in`}:n==="daemon-life"?{...o,permitted:!0,verdict:"permitted-daemon-life",reason:`redskilled permitted ${e.op}: it acts on the daemon's own process, not on any project's Workers`}:t==null||t===""?{...o,permitted:!0,verdict:"permitted-unattributed",reason:`redskilled permitted ${e.op}: the session named no project of its own, so there is nothing to refuse it against`}:r!=null&&r===t?{...o,permitted:!0,verdict:"permitted-own-project",reason:`redskilled permitted ${e.op}: the target belongs to project ${JSON.stringify(t)}, which is this session's own`}:{...o,permitted:!1,verdict:"refused-cross-project",reason:`redskilled refused ${e.op} from a session in project ${JSON.stringify(t)}: ${r==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(r)}`}. A session reads the whole host and writes only its own project.`}}function Gl(e){return{generated_at:e.now,hour:Vl("hour",36e5,e),day:Vl("day",864e5,e)}}function xt(e,n,t){let r=En(t.now),o=t.retentionMs??864e5,i=t.limit??8192,s=e.filter(a=>{let l=En(n(a));return l==null?!1:r==null||r-l<=o});return s.length<=i?s:s.slice(s.length-i)}function Vl(e,n,t){let r=En(t.now),o=r==null?null:r-n,i=e==="hour"?"1h":"24h",s=t.observations.map(u=>({observation:u,at:En(u.observed_at)})).filter(u=>u.at!=null&&Jl(u.at,o,r)).sort((u,f)=>u.at-f.at),a=t.outcomes.map(u=>En(u.ts)).filter(u=>u!=null&&Jl(u,o,r)),l=Kl(s,u=>u.tokens,"tokens",i),d=Kl(s,u=>u.tools,"tools",i),p=[];return s.length===0?p.push("worker-vitals"):(l.samples===0&&p.push("worker-vitals.tokens"),d.samples===0&&p.push("worker-vitals.tools")),a.length===0&&p.push("worker-outcomes"),{window:e,window_ms:n,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:l,tools_per_min:d,issues_per_hour:fh(a.length,n,i),runner_share:ql("runner",s,u=>u.runner,i),model_share:ql("model",s,u=>u.model,i),unavailable:p}}function Kl(e,n,t,r){let o=new Map,i=0;for(let d of e){let p=n(d.observation);if(p==null||!Number.isFinite(p))continue;i+=1;let u=o.get(d.observation.worker_id)??[];u.push({at:d.at,count:p}),o.set(d.observation.worker_id,u)}if(i===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${r}`,samples:0};let s=0,a=null,l=null;for(let d of o.values()){if(d.length<2)continue;for(let f=1;f<d.length;f++){let m=d[f-1],h=d[f];m==null||h==null||(s+=Math.max(0,h.count-m.count))}let p=d[0],u=d[d.length-1];p!=null&&(a=a==null?p.at:Math.min(a,p.at)),u!=null&&(l=l==null?u.at:Math.max(l,u.at))}return a==null||l==null||l<=a?{value:null,absent_reason:`the last ${r} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:i}:{value:s/((l-a)/6e4),absent_reason:null,samples:i}}function fh(e,n,t){return e===0?{value:null,absent_reason:`no Worker outcome was recorded in the last ${t}`,samples:0}:{value:e/(n/36e5),absent_reason:null,samples:e}}function ql(e,n,t,r){let o=new Map;for(let d of n){let p=t(d.observation);p!=null?o.set(d.observation.worker_id,p):o.has(d.observation.worker_id)||o.set(d.observation.worker_id,null)}let i=new Map,s=0,a=0;for(let d of o.values()){if(d==null){a+=1;continue}s+=1,i.set(d,(i.get(d)??0)+1)}let l=[...i.entries()].map(([d,p])=>({key:d,worker_count:p,share:p/s})).sort((d,p)=>p.worker_count-d.worker_count||d.key.localeCompare(p.key));return{dimension:e,attributed_workers:s,unattributed_workers:a,shares:l,absent_reason:l.length>0?null:o.size===0?`no Worker was observed in the last ${r}`:`no Worker published a ${e} in the last ${r}`}}function Jl(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function En(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}import{execFileSync as mh}from"node:child_process";import{existsSync as hh,readFileSync as St,readdirSync as gh}from"node:fs";import{dirname as yh,join as Le}from"node:path";function Pn(e){let n=vn(e),t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let i=ze(o);return i==null?null:{name:r,declared:o,bytes:i}}return null}function Ql(e){let n=[],t=[];for(let r of e.workers){let o=Pn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(vn(r).memory_max??vn(r).memory_high)==null?"this Worker declared no memory budget and the host derived no ceiling for it, so the sampler has none to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let i=e.rss[r.worker_id];if(typeof i!="number"||!Number.isFinite(i)){t.push({worker_id:r.worker_id,reason:"the host produced no RSS reading for this Worker on this tick, and an unmeasured Worker is never killed on suspicion"});continue}if(!(i<=o.bytes)){if(e.sources?.[r.worker_id]==="cgroup"&&o.name==="MemoryMax"){t.push({worker_id:r.worker_id,reason:`this Worker's ${o.name} of ${o.declared} is held by the kernel on its own cgroup, and the reading is memory.current \u2014 which counts reclaimable page cache the kernel drops before it kills anything, so the daemon does not duplicate an enforcement that can tell cache from anonymous memory`});continue}n.push(kh(r,o,i))}}return{terminations:n,unenforceable:t}}function kh(e,n,t){let r=`Worker ${JSON.stringify(e.worker_id)} of project ${JSON.stringify(e.project_label)}`;return{version:1,worker_id:e.worker_id,project_label:e.project_label,outcome:"terminated-over-memory-budget",classification:"budget-exceeded",stall:!1,budget_name:n.name,budget_declared:n.declared,budget_bytes:n.bytes,observed_rss_bytes:t,workspace_path:e.workspace_path,reason:`redskilled terminated ${r}: its tree RSS of ${t} bytes exceeded its ${n.name} budget of ${n.declared} (${n.bytes} bytes). This is a budget termination, not a stall, and the work in ${JSON.stringify(e.workspace_path)} is handed forward.`}}var Rh=4096;function zl(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return r;let o={},i={},s={},a=_h(e,t,n);for(let[u,f]of a){let m=Sh(f);m!=null&&(o[u]=m.memoryBytes,m.cpuSeconds!=null&&(i[u]=m.cpuSeconds),s[u]="cgroup")}let l=e.filter(u=>s[u.worker_id]==null);if(l.length===0)return{rss:o,cpu_seconds:i,sources:s};let d=Ph(t,n);if(d.size===0)return{rss:o,cpu_seconds:i,sources:s};let p=new Map;for(let u of d.values()){let f=p.get(u.ppid);f?f.push(u.pid):p.set(u.ppid,[u.pid])}for(let u of l){if(!d.has(u.pid))continue;let f=0,m=0,h=[u.pid],b=new Set;for(;h.length>0;){let k=h.pop();if(b.has(k))continue;b.add(k);let w=d.get(k);if(w){f+=w.rssBytes,m+=w.cpuSeconds;for(let j of p.get(k)??[])h.push(j)}}o[u.worker_id]=f,i[u.worker_id]=m,s[u.worker_id]="process-tree"}return{rss:o,cpu_seconds:i,sources:s}}var bh="/sys/fs/cgroup";function _h(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let i=t.cgroupRoot??bh,s=e.filter(l=>l.unit!=null&&l.unit!=="");if(s.length===0)return r;let a=wh(i,t);for(let l of s)for(let d of a){let p=Le(d,l.unit);if(hh(Le(p,"memory.current"))){r.set(l.worker_id,p);break}}return r}function wh(e,n){let t=n.selfCgroupPath??xh(),r=[],o=a=>{r.includes(a)||r.push(a)},i=t;for(;i!=null&&i!==""&&i!=="/"&&i!==".";){o(Le(e,i));let a=yh(i);if(a===i)break;i=a}o(e);let s=n.uid??process.getuid?.();return s!=null&&o(Le(e,"user.slice",`user-${s}.slice`,`user@${s}.service`,"app.slice")),r}function xh(){try{for(let e of St("/proc/self/cgroup","utf8").split(`
64
+ `))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function Sh(e){let n;try{n=St(Le(e,"memory.current"),"utf8")}catch{return null}let t=Number(n.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:vh(e)}}function vh(e){let n;try{n=St(Le(e,"cpu.stat"),"utf8")}catch{return null}return Eh(n)}function Eh(e){for(let n of e.split(`
65
+ `)){let[t,r]=n.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(r);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function Ph(e,n){return n.procRoot!=null||e==="linux"?$h(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?Ah(jh(n.psTable)):new Map}function jh(e){try{return(e??Dh)()}catch{return""}}function Dh(){return mh("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Oh=1024;function Ah(e){let n=new Map;for(let t of e.split(`
66
+ `)){let r=t.trim().split(/\s+/);if(r.length!==4)continue;let[o,i,s]=r.slice(0,3).map(Number);if(![o,i,s].every(l=>l!=null&&Number.isSafeInteger(l)&&l>=0))continue;let a=Lh(r[3]);a!=null&&n.set(o,{pid:o,ppid:i,rssBytes:s*Oh,cpuSeconds:a})}return n}function Lh(e){let n=e.indexOf("-"),t=n<0?0:Number(e.slice(0,n));if(!Number.isFinite(t)||t<0)return null;let r=e.slice(n+1).split(":"),o=t*86400,i=1;for(let s=r.length-1;s>=0;s--){let a=Number(r[s]);if(!Number.isFinite(a)||a<0||r[s]==="")return null;o+=a*i,i*=60}return o}function $h(e){let n=new Map,t;try{t=gh(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=St(Le(e,r,"stat"),"utf8")}catch{continue}let i=Th(o);i&&n.set(i.pid,{pid:i.pid,ppid:i.ppid,rssBytes:i.rssPages*Rh,cpuSeconds:i.cpuTicks/Ih})}return n}var Ih=100;function Th(e){let n=e.lastIndexOf(")");if(n<0)return null;let t=Number(e.slice(0,e.indexOf(" "))),r=e.slice(n+1).trim().split(/\s+/),o=Number(r[1]),i=Number(r[11]),s=Number(r[12]),a=Number(r[21]);return!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||!Number.isFinite(a)||!Number.isFinite(i)||!Number.isFinite(s)?null:{pid:t,ppid:o,rssPages:Math.max(0,a),cpuTicks:Math.max(0,i)+Math.max(0,s)}}function Yl(e){return e==="single-object"?"rest":"graphql"}function L(e,n,t,r,o){return{key:e,kind:"read",cardinality:n,surface:o??Yl(n),budget:t,...o?{only:o}:{},why:r}}function F(e,n,t,r){return{key:e,kind:"write",cardinality:"single-object",surface:n,budget:t,why:r}}var Xl=[L("issue view","single-object","rest","one issue by number; REST answers it in one request against the idle pool"),L("pr view","single-object","rest","one pull request by number, polled per Worker per iteration"),L("repo view","single-object","rest","one repository's own metadata"),L("run view","single-object","rest","one Actions run; the Actions API has no GraphQL surface either way"),L("release view","single-object","rest","one release by tag"),L("pr diff","single-object","rest","one pull request's diff, served by a REST media type"),L("issue list","multi-node","graphql","a connection of issues; one GraphQL query beats N REST pages"),L("pr list","multi-node","graphql","a connection of pull requests; one GraphQL query beats N REST pages"),L("pr checks","multi-node","graphql","every check context on one commit, which is a connection, not an object"),L("release list","multi-node","rest","Releases have no GraphQL connection gh reads; REST pages them","rest"),L("run list","multi-node","rest","the Actions API has no GraphQL surface, so a listing draws the request pool","rest"),L("label list","multi-node","graphql","a connection of labels inside one repository"),L("issue list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),L("pr list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),L("search issues","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),L("search prs","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),L("search repos","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),L("api graphql","multi-node","graphql","the caller wrote the query; `gh api graphql` is GraphQL by construction"),L("api rest","single-object","rest","any `gh api <path>` that is not `graphql` is a REST request"),F("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),F("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),F("issue close","graphql","graphql","gh closes with the closeIssue mutation"),F("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),F("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),F("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),F("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),F("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),F("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),F("pr close","graphql","graphql","gh closes with a GraphQL mutation"),F("pr edit","graphql","graphql","gh edits with GraphQL mutations"),F("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),F("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),F("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],Nh=new Map(Xl.map(e=>[e.key,e]));function Zl(e){let n=[],t=0;for(;t<e.length&&e[t].startsWith("-");)t+=e[t]==="-R"||e[t]==="--repo"?2:1;for(;t<e.length&&!e[t].startsWith("-")&&n.length<2;)n.push(e[t]),t+=1;return n}function lo(e){let n=Zl(e);if(n.length===0)return"";if(n[0]==="api")return n[1]==="graphql"?"api graphql":"api rest";let t=n.length===1?n[0]:`${n[0]} ${n[1]}`;return n[1]==="list"&&e.includes("--search")?`${t} (search)`:t}var vt=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(n){let t=lo(n);super(`unclassified GitHub operation ${JSON.stringify(t||"(empty argv)")}: add an entry to GITHUB_OPERATIONS in packages/github/surface.ts stating its cardinality. Defaulting to GraphQL is what sent every single-object poll to the node-point pool (ADR 0132 decision 4).`),this.operation=t,this.args=[...n]}};function ea(e){return Nh.get(lo(e))??null}function na(e){let n=ea(e);if(!n)throw new vt(e);return n}function ao(e){return na(e).surface}var Ch=["api","graphql"],Mh=ao(Ch);function Wh(e,n="https://api.github.com"){return e==="graphql"?`${n}/graphql`:n}var ta=100,po=6e4,Hh=2*po,Fh=7*24*60*60*1e3,co=class extends Error{constructor(t,r,o){super(`redskilled polls every repository with one host token ${JSON.stringify(o)}, and project ${JSON.stringify(t)} declares its own credential ${JSON.stringify(r)}: a project needing its own credential invalidates the host-scoped poller (ADR 0130 Amendment 1) rather than bending it, so the poller returns to the projects instead of reaching this repository under the wrong identity`);this.projectLabel=t;this.tokenRef=r;this.hostTokenRef=o;this.name="RedskilledSplitCredentialError"}};function fo(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new co(t.project_label,t.token_ref,n)}function Uh(e,n={now:new Date(0).toISOString()}){Kh(e);let t=n.closedWindowMs??Fh,r=Date.parse(n.now);if(!Number.isFinite(r))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(n.now)}`);let o=new Date(r-Math.max(0,t)).toISOString(),i=e.map((l,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:l}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { remaining resetAt }",...i.flatMap(({alias:l,search_alias:d,project:p})=>{let u=JSON.stringify(p.owner),f=JSON.stringify(p.name),m=JSON.stringify(`repo:${p.owner}/${p.name} is:closed closed:>=${o}`);return[` ${l}: repository(owner: ${u}, name: ${f}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${d}: search(query: ${m}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
67
+ `),aliases:i,closed_since:o}}function Bh(e,n,t){let r=Ye(n),o=Ye(r.data),i=Array.isArray(r.errors)?r.errors.map(Ye):[],s=qh(o.rateLimit,i),a=e.aliases.map(({alias:l,search_alias:d,project:p})=>{let u=p.owner+"/"+p.name,f=o[l],m=i.find(h=>ra(h.path,l)||ra(h.path,d));if(da(f)){let h=oa(f.open_pull_requests),b=oa(f.open_issues),k=Jh(o[d]);if(h!=null&&b!=null&&k!=null)return{project_label:p.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:h,open_issues:b,recently_closed:k},detail:`counted ${u} for project ${JSON.stringify(p.project_label)}`}}return s.exhausted||aa(m)?{project_label:p.project_label,repository:u,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${u} answered, so this project has no counts rather than zero counts${s.reset_at==null?"":`; the quota resets at ${s.reset_at}`}`}:{project_label:p.project_label,repository:u,outcome:"unreachable",counts:null,detail:`${u} is not reachable with the host token: ${uo(m?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:a.length,rate_limit:s,projects:a}}function Vh(e){return{version:1,fetched_at:e,request_count:0,project_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}async function ia(e){if(e.projects.length===0)return Vh(e.now);fo(e.projects,e.hostTokenRef);let n=Uh(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return Bh(n,t,{fetchedAt:e.now})}catch(t){let r=t instanceof Error?t.message:String(t),o=/rate limit|secondary rate|429/i.test(r);return{version:1,fetched_at:e.now,request_count:1,project_count:e.projects.length,rate_limit:{remaining:null,reset_at:null,exhausted:o},projects:e.projects.map(i=>({project_label:i.project_label,repository:`${i.owner}/${i.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${i.owner}/${i.name} answered: ${r}`}))}}}function sa(e){let n=e.stalenessMs??Hh,t=e.activity;if(t==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:n,stale:!1,request_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[],reason:"the daemon polls no repository, so there are no counts to age"};let r=Date.parse(e.now),o=Date.parse(t.fetched_at),i=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,s=i==null||i>n;return{version:1,fetched_at:t.fetched_at,age_ms:i,threshold_ms:n,stale:t.projects.length>0&&s,request_count:t.request_count,rate_limit:t.rate_limit,projects:t.projects.map(a=>({...a,fetched_at:t.fetched_at,age_ms:i,stale:s})),reason:t.projects.length===0?"the daemon polls no repository, so there are no counts to age":i==null?"these counts carry no readable instant, so they cannot be presented as current":s?`these counts are ${i}ms old, past the ${n}ms window`:`fetched ${i}ms ago, within the ${n}ms window`}}function la(e){let n=e.endpoint??Wh(Mh),t=e.fetchImpl??fetch;return async r=>{let o=await t(n,{method:"POST",headers:{authorization:`bearer ${e.token}`,"content-type":"application/json",accept:"application/vnd.github+json"},body:JSON.stringify({query:r})});if(!o.ok){let i=o.headers.get("x-ratelimit-remaining"),s=o.status===429||i==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(s?": the host token's rate limit is spent":""))}return await o.json()}}function Kh(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>ta)throw new Error(`redskilled activity fetch spans at most ${ta} repositories in one query`);let n=new Set;for(let t of e){if(t.project_label===""||t.owner===""||t.name==="")throw new Error("redskilled activity fetch needs a project label and an owner/name for every registered project");if(n.has(t.project_label))throw new Error(`redskilled holds one repository per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function qh(e,n){let t=Ye(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,i=n.some(aa);return{remaining:r,reset_at:o,exhausted:i||r===0}}function aa(e){if(e==null)return!1;let n=uo(e.type),t=uo(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function ra(e,n){return Array.isArray(e)&&e.includes(n)}function oa(e){let n=Ye(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function Jh(e){let n=Ye(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Ye(e){return da(e)?e:{}}function da(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function uo(e){return typeof e=="string"?e:""}var Gh=3e4,Qh=4;function ca(e){let n=e.stalenessMs??Gh,t=jn(e.now),r=e.sampledAt==null?null:jn(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),i=o!=null&&o<=n,s=new Set(e.reattachedWorkerIds??[]),a=e.hostState.workers.map(f=>Xh(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:i,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:s.has(f.worker_id)?"reattached":"running"})),l=a.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=a.length-l.length,p=a.reduce((f,m)=>f+(m.vitals.rss_bytes??0),0),u=kt(e.hostState.workers);return{version:1,generated_at:e.now,daemon:{pid:e.hostState.pid,daemon_version:e.hostState.daemon_version,protocol_version:e.hostState.protocol_version,started_at:e.hostState.started_at,machine_id_hash:e.hostState.machine_id_hash,session_key_hash:e.hostState.session_key_hash},staleness:tg({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:a.length,measuredCount:d,unmeasured:l}),host:{worker_count:a.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:u,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:p,measured_worker_count:d,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:u.memory_bytes/e.ceiling.memory_bytes},projects:ng(a),known_projects:eg(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,m)=>f.localeCompare(m)),workers:a,repository_activity:sa({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:zh(e.deaths,e.recentDeathLimit??Qh)},engine:Yh(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function zh(e,n){let t=[...e].sort((o,i)=>(jn(i.ts)??0)-(jn(o.ts)??0)),r=t.slice(0,Math.max(0,Math.floor(n))).map(o=>({kind:o.kind,id:o.id,pid:o.pid,ts:o.ts,last_seen:o.last_seen,last_phase:o.last_phase,sender_class:o.sender_class,confidence:o.confidence,signal:o.signal,evidence:o.evidence[0]??null}));return{count:t.length,recent:r,latest:r[0]??null,reaped_at:r[0]?.ts??null}}function Yh(e){let n=e.upgrade,t=n?.running_version??e.daemon_version,r=n?.published_version??null,o=n?.newest_published_version??null,i=(n?.newer_published??0)>0,s=(n?.major_held??0)>0;return{running_version:t,published_version:r,newer_published:i,major_held:s,current:r==null&&o==null?null:!i&&!s}}function Xh(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=Pn(e),i=e.budget?.memory_max??e.budget?.memory_high??null,s=jn(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms:n.nowMs==null||s==null?null:Math.max(0,n.nowMs-s),state:n.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:r,sampled_at:r==null?null:n.sampledAt,age_ms:r==null?null:n.ageMs,fresh:r!=null&&n.sampleFresh,rss_source:r==null?null:e.rss_source??null},budget:{name:o?.name??null,declared:o?.declared??i,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:Zh(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function Zh(e){let n={last_line:null,published_at:null,source:null};return e==null||e.line.trim()===""?n:{last_line:e.line,published_at:e.published_at,source:e.source}}function eg(e){let n=new Set;for(let t of e.registrations??[])n.add(t.project_label);for(let t of e.projects)n.add(t.project_label);return[...n].sort((t,r)=>t.localeCompare(r))}function ng(e){let n=new Map;for(let t of e){let r=n.get(t.project_label)??{workers:0,declared:0,observed:0,measured:0};r.workers+=1,r.declared+=t.budget.bytes??0,r.observed+=t.vitals.rss_bytes??0,r.measured+=t.vitals.rss_bytes==null?0:1,n.set(t.project_label,r)}return[...n.entries()].map(([t,r])=>({project_label:t,worker_count:r.workers,declared_memory_bytes:r.declared,observed_rss_bytes:r.observed,measured_worker_count:r.measured})).sort((t,r)=>t.project_label.localeCompare(r.project_label))}function tg(e){let n={sampled_at:e.sampledAt,age_ms:e.ageMs,threshold_ms:e.threshold,measured_worker_count:e.measuredCount,unmeasured_workers:e.unmeasured};return e.workerCount===0?{...n,stale:!1,reason:"the host holds no Workers, so there is nothing to measure and nothing to age"}:e.sampledAt==null||e.ageMs==null?{...n,stale:!0,reason:`this answer is stale: the daemon has taken no measurement of its ${e.workerCount} live Worker(s) yet`}:e.ageMs>e.threshold?{...n,stale:!0,reason:`this answer is stale: its measurement is ${e.ageMs}ms old, past the ${e.threshold}ms staleness window`}:{...n,stale:!1,reason:`measured ${e.ageMs}ms ago, within the ${e.threshold}ms staleness window`}}function jn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}var $={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function ua(e,n=$){let t=dg(e,n),r=lg(e,n),o=ag(e,n),i=cg(e,n,r,t),s=ig(n,r,o),a={detail:"host",line:i};for(let u of s){let f=bg(i,sg(u,n,r,o),n.separator);if(a={detail:u,line:f},_g(f)<=n.maxWidth)break}let l=yo(a.line,n.maxWidth),d=n.verbose&&a.detail==="workers"?gg(r,n):[],p=r.length>0?"workers":"host";return{version:1,line:l,lines:[l,...d],verbose:n.verbose,mode:n.mode,project:n.project,project_match:t,detail:a.detail,degraded:a.detail!==p||l!==a.line,stale:e.staleness.stale,generated_at:e.generated_at}}function pa(e){let n=e.options??$,t=yo(og,n.maxWidth);return{version:1,line:t,lines:[t],verbose:n.verbose,mode:n.mode,project:n.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}var rg="!unregistered",ho="\u21E1",Et="\u2020",og="redskilled unreachable \u2014 Worker state unknown";function ig(e,n,t){let r=[];return n.length>0&&n.length<=e.maxWorkers&&r.push("workers"),e.mode==="global"&&t.length>0&&t.length<=e.maxProjects&&r.push("projects"),r.push("host"),r}function sg(e,n,t,r){return e==="workers"?t.map(o=>hg(o,n)):e==="projects"?r.map(Rg):[]}function lg(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function ag(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function dg(e,n){return go(e,n.project)}function go(e,n){return n==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(n)?e.registered_projects==null||e.registered_projects.includes(n)?"matched":"name-only":"unregistered"}function cg(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(mo(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(mo(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(mo(e,n)),o.push(rg)):o.push(fg(n.project,r)),o.push(ug(e));let i=pg(e);return i!=null&&o.push(i),e.staleness.stale&&o.push(mg(e)),o.join(" ")}function ug(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${ho}`}function pg(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Et}${n.count} ${n.latest.sender_class}`}function fg(e,n){return n==="unregistered"?`project unknown \u2014 ${e} is not registered on this host`:"project unknown \u2014 this directory resolved to no project"}function mo(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,i)=>o+i.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${Y(t)}/${Y(r)}`:Y(t)}function mg(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function hg(e,n){let t=fa(e,n),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?Y(r):`${Y(r)}/${Y(e.budget.bytes)}`;return`${t} ${o}`}function gg(e,n){let t=[];for(let r of e){let o=kg(r.log.last_line);o!=null&&t.push(yo(` ${yg} ${fa(r,n)}: ${o}`,n.maxWidth))}return t}var yg="\u21B3";function kg(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}function fa(e,n){return n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Rg(e){return`${e.project_label} ${e.worker_count}w ${Y(e.observed_rss_bytes)}`}function bg(e,n,t){return[e,...n].join(t)}function _g(e){return[...e].length}function yo(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}function Y(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}var ko={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},wg=["runner","model","effort","origin","issue","phase","step","heartbeat"],xg=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function ma(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...ko};for(let r of wg){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of xg){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}var Pt=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],Xe={mode:"local",project:null,maxWidth:200,maxRows:16};var Sg=" ",ha="\u2588",vg="\u25B6",Eg="\u2717",Pg="\u2591";function ga(e,n=Xe){let t=go(e,n.project),r=jg(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),i=o.map(u=>Dg(u,n)),s=Mg(i),a=o.map((u,f)=>({worker_id:u.worker_id,project_label:u.project_label,mine:n.project!=null&&u.project_label===n.project,cells:i[f],line:Dn(Wg(i[f],s),n.maxWidth)})),l=Ag(e,n,r,t),d=r.length-o.length,p=[l.line,...a.map(u=>u.line)];return d>0&&p.push(Dn(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),p.push(...$g(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Pt,header:l,rows:a,lines:p,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function jg(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Dg(e,n){let t=e.display??ko,r=[t.runner,t.model,t.effort].filter(o=>!!o).join(" ");return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:r===""?"":`run=${r}`,org:t.origin==null?"":`org=${t.origin}`,iss:t.issue==null?"":`iss=${t.issue}`,bar:Og(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:Cg(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:Ng(t.added,t.removed),tks:t.tokens==null?"":`tks=${ya(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function Og(e){let n=e.phase_total,t=e.phase_index;if(n==null||n<=0||t==null||t<0)return"";let r=Math.min(Math.floor(t),Math.floor(n));if(r>=n)return ha.repeat(Math.floor(n));let o=e.failed?Eg:vg;return`${ha.repeat(r)}${o}${Pg.repeat(Math.floor(n)-r-1)}`}function Ag(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(w=>w.project_label===n.project),i={open_pull_requests:o?.counts?.open_pull_requests??null,recently_closed:o?.counts?.recently_closed??null,open_issues:o?.counts?.open_issues??null,stale:o?.stale===!0},s={memory_used_fraction:e.host.ceiling_used_fraction,memory_used_bytes:e.host.consumption.memory_bytes,memory_ceiling_bytes:e.host.ceiling.memory_bytes,worker_count:e.host.worker_count,worker_ceiling:e.host.ceiling.worker_count},a=Tg(t),l=o?.repository??n.project,d=e.engine??null,p=d?.running_version??e.daemon.daemon_version,u=e.deaths??null,f=e.metrics??null,m=[`\xBB ${l??"host"} v${p}${d!=null&&d.current===!1?ho:""}`];r==="unregistered"&&m.push("!unregistered"),r==="name-only"&&m.push("!lapsed"),a!=null&&m.push(a),m.push(`wrk=${t.length}/${e.host.worker_count}`),m.push(s.worker_ceiling==null?"slots=\u221E":`slots=${s.worker_count}/${s.worker_ceiling}`),m.push(Ig(s)),i.open_pull_requests!=null&&m.push(`prs=${i.open_pull_requests}`),i.recently_closed!=null&&m.push(`cpr=${i.recently_closed}`),i.open_issues!=null&&m.push(`iss=${i.open_issues}`),i.stale&&m.push("!counts stale");let h=f==null?null:Lg(f.hour);if(h!=null&&m.push(h),u!=null&&u.count>0&&u.latest!=null&&m.push(`${Et}${u.count} ${u.latest.sender_class}`),e.staleness.stale){let w=e.staleness.age_ms;m.push(w==null?"!unmeasured":`!stale ${Math.round(w/1e3)}s`)}let b=m.join(" \xB7 "),k=h!=null&&bo(b)>n.maxWidth?m.filter(w=>w!==h).join(" \xB7 "):b;return{repo:l,project:n.project,project_match:r,version:p,engine:d,deaths:u,metrics:f,model:a,windows:s,counts:i,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:Dn(k,n.maxWidth)}}function Lg(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${Ro(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${Ro(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${Ro(e.issues_per_hour.value)}`);let t=e.runner_share.shares[0];return t!=null&&n.push(`${t.key}=${Math.round(t.share*100)}%`),n.length===0?null:n.join(" ")}function $g(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(i=>Dn(`${Et} ${i.kind} ${i.id} pid=${i.pid} ${i.sender_class}/${i.confidence} phase=${i.last_phase}`+(i.signal==null?"":` signal=${i.signal}`)+(i.evidence==null?"":` \u2014 ${i.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(Dn(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function Ig(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${Y(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${Y(e.memory_used_bytes)}/${Y(e.memory_ceiling_bytes)}${n}`}function Tg(e){for(let n of e){let t=n.display;if(t==null)continue;let r=[t.runner,t.model,t.effort].filter(o=>!!o);if(r.length>0)return r.join("\xB7")}return null}function Ng(e,n){if(e==null&&n==null)return"";let t=[];return e!=null&&e>0&&t.push(`+${e}`),n!=null&&n>0&&t.push(`-${n}`),`loc=${t.length>0?t.join(" "):"0"}`}function ya(e){if(!Number.isFinite(e)||e<=0)return"0";let n=(t,r)=>{let o=(Math.round(t*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${r}`};return e>=1e9?n(e/1e9,"B"):e>=1e6?n(e/1e6,"M"):e>=1e3?n(e/1e3,"k"):String(Math.round(e))}function Ro(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return ya(e);if(e<=0)return"0";let n=(Math.round(e*10)/10).toFixed(1);return n.endsWith(".0")?n.slice(0,-2):n}function Cg(e){if(e==null||!Number.isFinite(e)||e<0)return"\u2014";let n=Math.floor(e/1e3);if(n<60)return`${n}s`;let t=Math.floor(n/60);if(t<60)return`${t}m${n%60}s`;let r=Math.floor(t/60);return r<24?`${r}h${t%60}m`:`${Math.floor(r/24)}d${r%24}h`}function Mg(e){let n=Object.fromEntries(Pt.map(t=>[t,0]));for(let t of e)for(let r of Pt)n[r]=Math.max(n[r],bo(t[r]));return n}function Wg(e,n){return Pt.filter(r=>n[r]>0).map(r=>Hg(e[r],n[r])).join(Sg).replace(/\s+$/,"")}function Hg(e,n){return e+" ".repeat(Math.max(0,n-bo(e)))}function bo(e){return[...e].length}function Dn(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}var jt=1;async function On(e,n){return await ut(e,n,"redskilled daemon")}function ka(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.line=="string"&&Array.isArray(n.lines)&&n.lines.every(t=>typeof t=="string")&&typeof n.verbose=="boolean"&&(n.mode==="local"||n.mode==="global")&&(n.project===null||typeof n.project=="string")&&typeof n.detail=="string"&&(n.project_match===void 0||typeof n.project_match=="string")&&typeof n.degraded=="boolean"&&typeof n.stale=="boolean"&&typeof n.generated_at=="string"}function Ra(e){let n=[...e.workers??[]],t=new Map;for(let r of n)t.set(r.project_label,(t.get(r.project_label)??0)+1);return{version:1,protocol_version:jt,daemon_version:e.daemonVersion,machine_id_hash:e.machineIdHash,session_key_hash:e.sessionKeyHash,pid:e.pid,started_at:e.startedAt,...e.scope==null?{}:{scope:e.scope},workers:n,projects:[...t.entries()].map(([r,o])=>({project_label:r,worker_count:o})).sort((r,o)=>r.project_label.localeCompare(o.project_label)),registrations:Bg(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:cl(n,{hostCeilingBytes:e.hostCeilingBytes??null}),upgrade:Vg(e)}}function Bg(e){let n=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(n),r=e.queue??null,o=new Map(r==null?[]:r.projects.map(i=>[i.project_label,i]));return[...e.registrations??[]].map(i=>{let s=o.get(i.project_label);return{...i,...t?{renewal:Hl(i,n)}:{},...r==null||s==null?{}:{last_poll:{at:r.fetched_at,outcome:s.outcome,depth:s.depth,request_count:r.request_count,detail:s.detail}}}}).sort((i,s)=>i.project_label.localeCompare(s.project_label))}function Vg(e){let n=e.daemonVersion,t=e.published?.version??null,r=e.published?.majorHold??null;return{running_version:n,published_version:t,published_unknown:+(t===null),newer_published:+(e.published?.newer===!0),replacement:e.published?.replacement??"none",checked_at:e.published?.checkedAt??null,checks:e.published?.checks??0,hold_reason:e.published?.holdReason??null,newest_published_version:e.published?.newest??null,major_held:+(r!==null),major_hold:r}}function ba(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.protocol_version=="number"&&typeof n.daemon_version=="string"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&Number.isInteger(n.pid)&&typeof n.started_at=="string"&&Array.isArray(n.workers)&&Array.isArray(n.projects)&&ul(n.budget_accounting)&&(n.scope===void 0||Tl(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(so))&&(n.upgrade===void 0||Kg(n.upgrade))}function Kg(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")&&typeof n.published_unknown=="number"&&typeof n.newer_published=="number"&&(n.replacement==="none"||n.replacement==="pending"||n.replacement==="in-progress")&&(n.checked_at===null||typeof n.checked_at=="string")&&(n.newest_published_version===void 0||n.newest_published_version===null||typeof n.newest_published_version=="string")&&(n.major_held===void 0||typeof n.major_held=="number")&&(n.checks===void 0||typeof n.checks=="number")&&(n.hold_reason===void 0||n.hold_reason===null||typeof n.hold_reason=="string")&&(n.major_hold===void 0||n.major_hold===null||qg(n.major_hold))}function qg(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.version=="string"&&Number.isInteger(n.running_major)&&Number.isInteger(n.held_major)&&typeof n.reason=="string"&&typeof n.action=="string"&&n.action.trim()!==""}import{spawnSync as At}from"node:child_process";import{existsSync as vo}from"node:fs";import{delimiter as ny,join as Oa}from"node:path";import{join as _a}from"node:path";import{existsSync as Jg}from"node:fs";import{createRequire as Gg}from"node:module";var wa="redskilled-job-object.node",$e=100;function Ze(e){return{available:!1,reason:e}}function Qg(e,n,t){return[_a(t,"prebuilds",`${e}-${n}`,wa),_a(t,"native","build","Release",wa)]}function xa(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return Ze(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??Yg(),o=e.exists??Jg,i=Qg(n,t,r),s=i.find(d=>o(d));if(s==null)return Ze(`no Job Object addon was found for ${n}-${t} (looked in ${i.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let a=e.requireFn??Gg(import.meta.url),l;try{l=a(s)}catch(d){return Ze(`the Job Object addon at ${s} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return zg(l)?{available:!0,binding:l}:Ze(`the Job Object addon at ${s} does not export createJobObject, so it cannot be the native reach`)}function zg(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Yg(){return new URL("..",import.meta.url).pathname}function Sa(e){let n=e??{},t=[],r=Xg(n);r==null&&(n.memory_max??n.memory_high)!=null&&t.push("the declared memory budget could not be reduced to bytes, so the job carries no memory ceiling");let o;return n.cpu_weight!=null&&(n.cpu_weight<$e?o=Math.max(1,Math.min(100,Math.round(n.cpu_weight))):t.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${$e}, and Windows CPU rate control is an absolute cap rather than a share, so no rate limit is set`)),{...r!=null?{memory_limit_bytes:r.bytes,memory_budget_name:r.name,memory_budget_declared:r.declared}:{},...o!=null?{cpu_rate_percent:o}:{},kill_on_close:!0,...t.length>0?{note:t.join("; ")}:{}}}function Xg(e){return Pn({budget:e})}var Dt=5,va=19;function _o(e){return{available:!1,reason:e}}var Zg="an address-space rlimit is not a resident-memory ceiling: a runtime that reserves address space it never faults in would die under a limit it never used, so no memory rlimit is set and the daemon's RSS sampling floor is the ceiling that actually holds";function Pa(e,n){let t=e??{},r=[],o;if(!n.canRenice)r.push("nice is not on this host, so no priority control was applied and the Worker competes with interactive work");else if(t.cpu_weight==null)o=Dt;else if(t.cpu_weight<$e){let a=Math.round(va*($e-t.cpu_weight)/$e);o=Math.min(va,Math.max(Dt,a))}else o=Dt,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${$e}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Dt}`);let i=Ea(t.max_processes);i==null&&t.max_processes!=null&&r.push(`max_processes=${t.max_processes} is not a positive whole number, so no ulimit -u is set`);let s=Ea(t.cpu_seconds);return s==null&&t.cpu_seconds!=null&&r.push(`cpu_seconds=${t.cpu_seconds} is not a positive whole number, so no ulimit -t is set`),{...o!=null?{nice:o}:{},...i!=null?{max_processes:i}:{},...s!=null?{cpu_seconds:s}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:Zg,...r.length>0?{note:r.join("; ")}:{}}}function ja(e){let{limits:n}=e,t=[];return n.max_processes!=null&&t.push(`ulimit -u ${n.max_processes}`),n.cpu_seconds!=null&&t.push(`ulimit -t ${n.cpu_seconds}`),t.push(n.nice!=null&&e.nice!=null?`exec ${ey(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
68
+ `),e.command,...e.args]}function Da(e){let n=[];return e.nice!=null?n.push(`the Worker runs at nice ${e.nice} so it yields to interactive work`):n.push("no priority control was applied"),e.max_processes!=null&&n.push(`its processes are capped at ${e.max_processes}`),e.cpu_seconds!=null&&n.push(`its CPU time is capped at ${e.cpu_seconds} seconds`),`macOS placement applied POSIX limits: ${n.join(", ")}. macOS has no resource-group equivalent, so the Worker is charged to the daemon's own resource group, and ${e.memory_ceiling_reason}`+(e.note!=null?` (${e.note})`:"")}function wo(e){let n=e??{},t=[n.max_processes!=null?"max_processes":null,n.cpu_seconds!=null?"cpu_seconds":null].filter(r=>r!=null);return t.length===0?null:`${t.join(" and ")} ${t.length===1?"is a POSIX rlimit":"are POSIX rlimits"} honoured only by the macOS placement backend, so this placement carries no equivalent`}function Ea(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function ey(e){return`'${e.replace(/'/g,"'\\''")}'`}var Aa="REDSKILLED_PLACEMENT",Ot="red-worker",xo="/bin/sh";function La(e=process.env,n=process.platform){let t=_o(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:xa({platform:n}),posix:t};let r=Ze(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);if(n==="darwin")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:ty(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),i=o!==""&&vo(Oa(o,"systemd","private"));return{platform:n,systemdRun:Na("systemd-run",e),userSession:i,jobObjects:r,posix:t}}function ty(e){return vo(xo)?{available:!0,shell:xo,nice:Na("nice",e)}:_o(`no POSIX shell was found at ${xo}, so there is nothing to apply rlimits or priority in`)}function $a(e=process.env){let n=(e[Aa]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function ry(e,n,t=Ot){return Ia(e,n,t).replace(/\.service$/,"")}function Ia(e,n,t=Ot){return`${So(t,"red-worker",24)}-${So(e,"project",32)}-${So(n,"worker",32)}.service`}function Ta(e){let n=[...e.args??[]],t={...e.budget??{},...e.budget?.memory_max==null&&e.memoryCeiling?.memory_max!=null?{memory_max:e.memoryCeiling.memory_max}:{}},r=t.memory_max??t.memory_high??null,o=t.memory_high!=null||t.memory_max!=null||t.cpu_weight!=null,i=e.target??{isolation:"transient-unit"},s=u=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:u,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Rn({scope:null,memory_ceiling:r,scope_degradation:u}),...o?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(i.isolation==="inherit")return s("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return s(`worker isolation disabled by ${Aa}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return iy(e,n,t,r,o,s);if(e.probes.platform==="darwin")return oy(e,n,t,r,s);if(e.probes.platform!=="linux")return s(`transient-unit placement is the Linux backend (platform=${e.probes.platform}): the Worker is charged to the daemon's own resource group`);if(!e.probes.systemdRun)return s("transient-unit placement unavailable: systemd-run is not on PATH; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");if(!e.probes.userSession)return s("transient-unit placement unavailable: no systemd --user session; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");let a=Ia(e.projectLabel,e.workerId,i.unit_prefix),l=["--user","--collect","--quiet","--wait",`--unit=${a}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&l.push("--pipe"),t.memory_high!=null&&l.push(`--property=MemoryHigh=${t.memory_high}`),t.memory_max!=null&&l.push(`--property=MemoryMax=${t.memory_max}`),t.cpu_weight!=null&&l.push(`--property=CPUWeight=${t.cpu_weight}`);let d=Rn({scope:a,memory_ceiling:r,scope_degradation:null});for(let[u,f]of Object.entries({...e.env??{},...d}))l.push(`--setenv=${u}=${f}`);let p=wo(e.budget);return{isolated:!0,backend:"transient-unit",unit:a,command:e.probes.systemdRun,args:[...l,"--",e.command,...n],budget:t,...r!=null?{memoryCeiling:r}:{},environment:d,...p!=null?{budgetWarning:p}:{}}}function oy(e,n,t,r,o){let i=e.probes.posix;if(!i.available)return o(`POSIX limit placement unavailable: ${i.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let s=Pa(t,{canRenice:i.nice!=null}),a=t.memory_high!=null||t.memory_max!=null,l=Da(s);return{isolated:!1,backend:"posix-limits",command:i.shell,args:ja({limits:s,nice:i.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:s,warning:l,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Rn({scope:null,memory_ceiling:r,scope_degradation:l}),...a?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+s.memory_ceiling_reason}:{}}}function iy(e,n,t,r,o,i){let s=e.probes.jobObjects;if(!s.available)return i(`Job Object placement unavailable: ${s.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let a=Sa(t),l=ry(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...n],cwd:e.workspacePath,job:{name:l,limits:a},budget:t,...r!=null?{memoryCeiling:r}:{},environment:Rn({scope:l,memory_ceiling:r,scope_degradation:null}),...sy(o&&a.note!=null?`${a.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,wo(e.budget))}}function sy(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function Na(e,n){for(let t of(n.PATH??"").split(ny)){if(!t)continue;let r=Oa(t,e);if(vo(r))return r}return null}function So(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function Eo(e,n){let t=[],r=[];for(let o of e){let i=!1;try{i=await n(o)===!0}catch{i=!1}(i?t:r).push(o)}return{alive:t,dead:r}}function Ca(e){return e.unit!=null&&e.unit!==""?ly(e.unit):U(e.pid)}function ly(e){let n=At("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var ay="REDSKILLED_UNIT_DISCOVERY",Ma="(unowned)";function Wa(e){let n=At("systemctl",["--user","show","--property=MainPID","--value",e],{encoding:"utf8"});if(n.error!=null||n.status!==0)return null;let t=Number.parseInt((n.stdout??"").trim(),10);return Number.isInteger(t)&&t>0?t:null}function dy(e=process.env){let n=(e[ay]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Ha(e,n,t=process.env){return dy(t)&&e===n}function Fa(e=Ot){let n=At("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return n.error!=null||n.status!==0?[]:(n.stdout??"").split(`
69
+ `).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function Ua(e){let n=new Set(e.held.map(o=>o.unit).filter(o=>o!=null&&o!=="")),t=new Set,r=[];for(let o of e.units)o===""||n.has(o)||t.has(o)||(t.add(o),r.push({worker_id:o.replace(/\.service$/,""),project_label:Ma,pid:e.mainPid?.(o)??0,started_at:e.now,workspace_path:"",isolated:!0,unit:o,warnings:[`adopted from active unit ${JSON.stringify(o)}, which has no birth on this host's event lane: its project, its Worker id and its budget belonged to a daemon that is gone, so they are reported as unknown rather than guessed \u2014 it is counted against the host budget from here on instead of running outside it`]}));return r}function Ba(e){return e.project_label.trim()!==""?e:{...e,project_label:Ma,warnings:[...e.warnings,"adopted at start with no owning project on the event lane: the daemon that birthed it recorded no project label, so it is held and counted under a stated placeholder rather than dropped"]}}function Va(e){if(e.unit!=null&&e.unit!==""){let n=At("systemctl",["--user","stop",e.unit],{stdio:"ignore"});return n.error==null&&n.status===0}try{return process.kill(e.pid,"SIGTERM"),!0}catch{return!1}}function cy(e,n=50){if(Ga(e),!Number.isInteger(n)||n<=0)throw new Error(`redskilled queue discovery needs a whole, positive batch size, not ${JSON.stringify(n)}`);let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}function uy(e,n={}){let t=n.batchSize??50;if(Ga(e),e.length>t)throw new Error(`redskilled queue discovery spans at most ${t} selectors in one query, and this batch holds ${e.length}: split it with planQueueDiscoveryBatches rather than dropping the remainder`);let r=e.map((s,a)=>({alias:`q${a}`,project:s}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...r.map(({alias:s,project:a})=>` ${s}: search(query: ${JSON.stringify(a.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
70
+ `),aliases:r}}function py(e,n){let t=An(n),r=An(t.data),o=Array.isArray(t.errors)?t.errors.map(An):[],i=my(r.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=gy(r[a]);if(d!=null)return{project_label:l.project_label,outcome:"counted",depth:d,detail:`project ${JSON.stringify(l.project_label)} has ${d} item(s) matching its selector`};let p=o.find(u=>hy(u.path,a));return i.exhausted||Qa(p)?{project_label:l.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(l.project_label)} answered, so this queue has no depth rather than a depth of zero`+(i.reset_at==null?"":`; the quota resets at ${i.reset_at}`)}:{project_label:l.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(l.project_label)} could not be counted with the host token: ${Po(p?.message)||"the query returned no count for this selector"}`}}),rate_limit:i}}function fy(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function qa(e,n,t){return{version:1,fetched_at:n,request_count:0,project_count:e.length,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:e.map(r=>({project_label:r.project_label,outcome:"unconfigured",depth:null,detail:`project ${JSON.stringify(r.project_label)} was not counted because this host polls no tracker: ${t}`}))}}async function Ja(e){if(e.projects.length===0)return fy(e.now);let n=e.batchSize??50,t=cy(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let i of t){let s=uy(i,{batchSize:n});try{let a=await e.transport(s.query),l=py(s,a);r.push(...l.projects),o=Ka(o,l.rate_limit)}catch(a){let l=a instanceof Error?a.message:String(a),d=/rate limit|secondary rate|429/i.test(l);o=Ka(o,{remaining:null,reset_at:null,exhausted:d});for(let p of i)r.push({project_label:p.project_label,outcome:d?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(p.project_label)} answered: ${l}`})}}return{version:1,fetched_at:e.now,request_count:t.length,project_count:r.length,batch_size:n,rate_limit:o,projects:r}}function Ga(e){if(e.length===0)throw new Error("redskilled queue discovery needs at least one registered project");let n=new Set;for(let t of e){if(typeof t.project_label!="string"||t.project_label==="")throw new Error("redskilled queue discovery needs a project label for every registered project");if(typeof t.selector!="string"||t.selector==="")throw new Error(`redskilled queue discovery needs a selector for project ${JSON.stringify(t.project_label)}: a project that names no work has no queue to discover`);if(n.has(t.project_label))throw new Error(`redskilled holds one selector per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function Ka(e,n){return{remaining:n.remaining==null?e.remaining:e.remaining==null?n.remaining:Math.min(e.remaining,n.remaining),reset_at:n.reset_at??e.reset_at,exhausted:e.exhausted||n.exhausted}}function my(e,n){let t=An(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null;return{remaining:r,reset_at:o,exhausted:n.some(Qa)||r===0}}function Qa(e){return e==null?!1:Po(e.type)==="RATE_LIMITED"||/rate limit/i.test(Po(e.message))}function hy(e,n){return Array.isArray(e)&&e.includes(n)}function gy(e){let n=An(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function An(e){return yy(e)?e:{}}function yy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Po(e){return typeof e=="string"?e:""}import{randomUUID as Xa}from"node:crypto";import{spawn as _y}from"node:child_process";import{closeSync as wy,mkdirSync as xy,openSync as Sy}from"node:fs";import{dirname as vy}from"node:path";import{delimiter as za,dirname as ky}from"node:path";function Ry(e,n=za){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function by(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=ky(n);return t===""||t==="."?null:t}function Ya(e,n=process.execPath,t=za){let r=Ry(e,t),o=by(n);return o==null?r.join(t):[o,...r.filter(i=>i!==o)].join(t)}var Ln=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},Lt=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function Ey(e){if(e==null||e.trim()==="")return null;try{return xy(vy(e),{recursive:!0}),Sy(e,"a")}catch{return null}}function Py(e){try{wy(e)}catch{}}function jy(e){let n=[["project_label",e.project_label],["workspace_path",e.workspace_path],["command",e.command]];for(let[t,r]of n)if(typeof r!="string"||r.trim()==="")throw new Ln(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new Ln("redskilled worker spec args must be an array")}function Dy(e){if(e==null)throw new Lt("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new Lt(e.reason,e)}function ed(e){let{spec:n,admission:t}=e;Dy(t),jy(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),i=(n.worker_id??e.workerId??Xa()).trim()||Xa(),s=e.probes??La(r),a=e.openLog===!1?null:Ey(n.log_path),l={...n.env??{},PATH:Ya(n.env?.PATH??r.PATH,e.execPath??process.execPath)},d=Ta({workerId:i,projectLabel:n.project_label,workspacePath:n.workspace_path,command:n.command,args:n.args,budget:n.budget,...e.memoryCeiling!=null?{memoryCeiling:e.memoryCeiling}:{},target:n.placement,env:l,enabled:e.enabled??$a(r),probes:s,pipeOutput:a!==null}),u=(e.spawnFn??_y)(d.command,d.args,{...d.cwd!=null?{cwd:d.cwd}:{},detached:!0,stdio:a===null?"ignore":["ignore",a,a],env:d.backend==="transient-unit"?{...r}:{...r,...l,...d.environment}});if(a!==null&&Py(a),u.pid==null)throw u.once("error",()=>{}),new Ln(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${i}`);let f=d.job!=null?Oy(d,s,u.pid):null;u.once("error",()=>{}),u.once("exit",(k,w)=>{try{f?.job?.close()}catch{}e.onExit?.(i,k,w)}),u.unref();let m=d.job!=null?f?.job!=null:d.isolated,h=[d.warning,f?.warning,d.budgetWarning].filter(k=>k!=null);return{worker:{worker_id:i,project_label:n.project_label,pid:u.pid,started_at:o(),workspace_path:n.workspace_path,...n.log_path!=null?{log_path:n.log_path}:{},isolated:m,...d.unit!=null?{unit:d.unit}:{},...n.budget!=null?{budget:n.budget}:{},...Object.keys(d.budget).length>0?{applied_budget:d.budget}:{},...d.memoryCeiling!=null?{memory_ceiling:d.memoryCeiling,memory_ceiling_reason:e.memoryCeiling?.reason??"this Worker's ceiling is the budget its client declared"}:{},warnings:h},admission:t,warnings:h,plan:d,child:u,...f?.job!=null?{job:f.job}:{}}}function Oy(e,n,t){let r=e.job;if(r==null)return{};let o="the Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling";if(!n.jobObjects.available)return{warning:`Job Object placement unavailable: ${n.jobObjects.reason}. ${o}`};let i;try{i=n.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(s){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${Za(s)}. ${o}`}}try{i.assign(t)}catch(s){try{i.close()}catch{}return{warning:`Worker pid ${t} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${Za(s)}. ${o}`}}return{job:i}}function Za(e){return e instanceof Error?e.message:String(e)}import{open as Ay,stat as Ly}from"node:fs/promises";var $y=16*1024;async function nd(e,n=$y){let t;try{t=(await Ly(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let i=await Ay(e,"r");try{let s=Buffer.alloc(r);await i.read(s,0,r,t-r),o=s.toString("utf8")}finally{await i.close()}}catch{return null}return Iy(o)}function Iy(e){let n=e.split(`
71
+ `);for(let t=n.length-1;t>=0;t-=1){let r=n[t].replace(/\r$/,"");if(r.trim()!=="")return r}return null}import{spawn as Qy}from"node:child_process";import{existsSync as zy,readdirSync as Yy}from"node:fs";import{dirname as Xy,join as ld,resolve as Zy}from"node:path";var Ty="<version>";function _e(e,n=[],t){let r=t&&t.trim().length>0?t.trim():Ty;return[`npx -y -p ${Ae}@${r}`,e,...n].join(" ")}function X(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?{major:Number(n[1]),minor:Number(n[2]),patch:Number(n[3])}:null}function jo(e,n){let t=X(e),r=X(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var KS=4*60*60*1e3;pe();pe();import{spawnSync as Ny}from"node:child_process";import{mkdir as Cy,rm as My,writeFile as Wy}from"node:fs/promises";import{existsSync as Hy}from"node:fs";import{homedir as Fy}from"node:os";import{dirname as Uy,join as Do}from"node:path";var en="redskilled.service",Oo="REDSKILLED_SUPERVISED",By="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function Vy(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||Do(e.HOME?.trim()||Fy(),".config");return Do(n,"systemd","user")}function Ao(e=process.env){return Do(Vy(e),en)}function td(e,n={}){let t=n.env??process.env,r=ht(n.override??{},n.entryLookup??{}),o=[...r.args,...Oe(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:en,unitPath:Ao(t),command:r.command,args:o,text:Ky(r.command,o,e)}}function Ky(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${By}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(qy).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Oo}=1"`,`Environment="REDSKILLED_SESSION=${rd(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
72
+ `)}function qy(e){return/[\s"'\\$%]/.test(e)?`"${rd(e)}"`:e}function rd(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function od(e,n={}){let t=n.writeFile??Jy,r=n.run??Lo,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push($t("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push($t("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(i=>i.ok),steps:o}}async function id(e={}){let n=e.removeFile??Gy,t=e.run??Lo,r=Ao(e.env??process.env),o=[$t("disable",t,["systemctl","--user","disable","--now",en])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push($t("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function sd(e={}){let n=e.exists??Hy,t=e.run??Lo,r=Ao(e.env??process.env),o=n(r);return{unitName:en,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",en]).status===0,active:o&&t(["systemctl","--user","is-active",en]).status===0,floor:"auto-spawn"}}function $t(e,n,t){let r=n(t),o=(r.stderr??r.stdout??"").trim();return{step:e,argv:t,ok:r.status===0,...o?{detail:o}:{}}}async function Jy(e,n){await Cy(Uy(e),{recursive:!0}),await Wy(e,n,{encoding:"utf8",mode:420})}async function Gy(e){await My(e,{force:!0})}function Lo(e){let n=Ny(e[0],[...e.slice(1)],{encoding:"utf8"});return n.error!=null?{status:null,stderr:n.error.message}:{status:n.status,stdout:n.stdout??"",stderr:n.stderr??""}}var ad=75,cd=9e5,dd="redskilled-replacement-entry-unresolved",ek="REDSKILLED_NO_REGISTRY_PROBE",ud="REDSKILLED_BORN_BY_REPLACEMENT";function pd(e=process.env){return e[ud]==="1"}function fd(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function md(e){let n=e.running.trim();if($n(n))return null;let t=e.newest?.trim()??"",r=X(t),o=X(n);return r===null||o===null||r.major<=o.major?null:{version:t,running_major:o.major,held_major:r.major,reason:`redskilled ${t} is published and this daemon runs ${n}; a major version is deliberately never adopted by the background check, because a breaking change must not arrive on a machine that is holding Workers`,action:nk(r.major,e.supervised)}}function nk(e,n){let t=`install the ${e}.x bundle (update this machine's plugin pin), then `;return n?`${t}re-point the unit and restart it: ${_e("red-skills-redskilled",["unit","install"])} && systemctl --user restart redskilled.service`:`${t}stop this daemon \u2014 the next client start resolves the newly installed bundle`}function hd(e){let n=e.running.trim();if($n(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||X(t)===null?{act:"hold",reason:"published-unknown"}:jo(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function $n(e){let n=e.trim();return X(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function gd(e=process.env){return e[Oo]==="1"}var $o=class extends Error{code=dd;searched;constructor(n,t){super(`${dd}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
65
73
  searched:
66
74
  ${t.map(r=>` ${r}`).join(`
67
- `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function Ug(e,n={}){let t=n.env??process.env,r=n.exists??Tg,o=n.execPath??process.execPath,s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,l=[],a=[[Vl(Vn(t),i),"bundle-cache"]];s&&a.push([Vl(Wg(Mg(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 qr(e,l);return{command:t.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:l}}function Xl(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>Ug(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function ea(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??Vg)(Bl),{...e,exitCode:Bl};let o=[...e.entry.args,..._e(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??Hg(r.env))(e.entry,o),e}function Hg(e){return(n,t)=>{let r=Ig(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[ql]:"1"}});r.on("error",()=>{}),r.unref()}}function Vg(e){process.exitCode=e,process.exit(e)}async function na(e,n=process.env,t=Bg){let r=ra(n),o=oa(e,n);if(n[Cg]==="1")return{version:o,newest:r};let s=H(e)===null?"0.0.0":e;try{let i=await Xs({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function ta(e,n=process.env,t){let r=t??Gr;return{version:oa(e,n,r),newest:ra(n,r)}}function ra(e=process.env,n=Gr){return ia(sa(e,n))}function oa(e,n=process.env,t=Gr){let r=H(e.trim())?.major;return r===void 0?null:ia(sa(n,t).filter(o=>H(o)?.major===r))}function sa(e,n){let t=[];for(let r of n(Vn(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||H(o)===null||t.push(o)}return t}function ia(e){let n=null;for(let t of e)(n===null||Hr(t,n)>0)&&(n=t);return n}function Gr(e){try{return Ng(e)}catch{return[]}}async function Bg(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 Kg,readFile as Jg,rename as qg,rm as zr,writeFile as la}from"node:fs/promises";import{randomUUID as Gg}from"node:crypto";import{dirname as zg}from"node:path";var it=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function Yr(e){let n;try{n=await Jg(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=Qg(n);return Yg(t)?t:void 0}var aa;function ca(){return aa??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},aa}function ua(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??W;async function s(){return await Yr(e)}async function i(a){let c=`${e}.${a.pid}.${Gg()}.tmp`;await la(c,da(a),{encoding:"utf8",mode:384}),await qg(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 Kg(zg(e),{recursive:!0,mode:448});let c=!1;for(;;){let u=r(),p=l(a,u);try{return await la(e,da(p),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:c,lease:p}}catch(g){if(g.code!=="EEXIST")throw g}let m=await s();if(!m){await zr(e,{force:!0}),c=!0;continue}if(Qr(m,a))return{acquired:!0,reaped:c,lease:m};if(await o(m.pid))return{acquired:!1,lease:m};await zr(e,{force:!0}),c=!0}},async renew(a){let c=await s();if(!c||!Qr(c,a))throw new it(e);let u={...c,renewed_at:r()};return await i(u),u},async release(a){let c=await s();if(!c)return!1;if(!Qr(c,a))throw new it(e);return await zr(e,{force:!0}),!0}}}function Qr(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function da(e){return`${I(e,{keyedMapCollapse:!0})}
68
- `}function Qg(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return G(n)}catch{return null}}}function Yg(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||!Number.isInteger(n.pid)||n.pid<=0)return!1;for(let t of["start_time","session_key_hash","machine_id_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var Zr=3e5,sh=1e4,ih=6e4,lh=15e3,pa=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"}},ah="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function fa(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??Zr,o=e.clock??(()=>new Date().toISOString()),s=e.launch??Nl,i=e.ceiling??di();e.repositoryActivity!=null&&Pr(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??ca(),a=e.leaseStore??ua(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),c=e.machineOwner??Si(),u={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},p=e.machineClaimStore??zn(n.machineClaimPath,u,{clock:o});await th(oh(n.socketPath),{recursive:!0,mode:448});let m=await p.claim(c);if(!m.claimed)throw m.claim?.socket_path===n.socketPath?new Ce(n.socketPath):new pe(p.claimPath,m.reason,m.claim);let g=await a.acquire(l);if(!g.acquired)throw await p.release(c).catch(()=>{}),new Ce(n.socketPath,g.lease);let y;try{y=await dh(n.socketPath)}catch(d){throw await a.release(l).catch(()=>{}),await p.release(c).catch(()=>{}),d}let b=o(),k=e.eventLane??pi(n.eventLanePath),_=e.liveness??_l,D=e.stopWorker??jl,V=e.unitInventory??(()=>Sl(n.machineClaimPath,Gn({machineIdHash:n.machineIdHash}))?xl():[]),C=e.unitMainPid??vl,me=e.treeSampler??Fi,ve=e.readLogTail??Wl,Rn=e.sampleMs??lh,co=e.publishedVersion??(d=>na(d)),uo=e.replaceCheckMs??Jl,po=e.publishedProbeTimeoutMs??sh,qa=e.localPublishedEvidence??(d=>ta(d,e.replacementIO?.env??process.env)),Ga=e.bornByReplacement??Gl(),mo=e.replaceBootCheckMs??ih,fo=e.supervised??Zl(),go=e.replacementIO??{},B=e.repositoryActivity,ho=B?.intervalMs??6e4,fe=e.queueDiscovery,bn=fe?.transport??B?.transport,dt=fe?.unconfiguredReason??ah,yo=fe?.intervalMs??15e3,ko=e.demandMs??15e3,za=e.demandBackoffMs??3e4,x=new Map,le=new Set,Se=new Map,_n=new Map,ct=[],wn=[],A=new Map,ut=new Set,Ro={},pt=null,bo=null,mt=null,_o=!1,ft=0,gt=null,He="none",ht=null,wo=null,yt=null,ae=null,vn=null,Ve=[],Be=null,kt=!1,xe,Ke,Je,qe,Sn,Ge,ze,Z=!1,Rt=!1,xn=null,vo,bt=new Promise(d=>{vo=d});function Qe(d){So(d);let f=Date.parse(d),h=$i(A.values(),f);for(let w of h.lapsed)A.delete(w.project_label),Qa(w,f);return h.lapsed}function Qa(d,f){let h=Number.isFinite(f)?new Date(f).toISOString():d.renew_by;Ve.push({project_label:d.project_label,at:h,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`}),Ve.length>pa&&Ve.splice(0,Ve.length-pa)}function So(d){if(A.size===0)return;let f=Date.parse(d);if(!Number.isFinite(f))return;let h={};for(let v of x.values())h[v.project_label]=(h[v.project_label]??0)+1;let w=new Map((ae?.projects??[]).map(v=>[v.project_label,v]));for(let v of[...A.values()]){let P=w.get(v.project_label),ee=Di(v,{now:d,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:h[v.project_label]??0});ee.registration!==v&&A.set(v.project_label,ee.registration)}}function En(){let d=o();return Qe(d),rl({now:d,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:l.pid,startedAt:b,scope:xi(p.claimPath,u,c),workers:[...x.values()],registrations:[...A.values()],lapses:Ve,queue:ae,published:{version:bo,checkedAt:mt,newer:_o,replacement:He,newest:ht,majorHold:wo,checks:ft,holdReason:gt}})}function Pn(){return Gi({hostState:En(),ceiling:i,rss:Ro,sampledAt:pt,logLines:Object.fromEntries(Se),displays:Object.fromEntries(_n),now:o(),reattachedWorkerIds:[...le],repositoryActivity:yt,...e.deaths===void 0?{}:{deaths:e.deaths},metrics:Mi({observations:ct,outcomes:wn,now:o()})})}function Ya(d,f){ct=Yn([...ct,{worker_id:f,observed_at:d.published_at,tokens:d.display.tokens,tools:d.display.tools,runner:d.display.runner,model:d.display.model}],h=>h.observed_at,{now:o()})}function Za(d){wn=Yn([...wn,d],f=>f.ts,{now:o()})}async function _t(){return B==null||B.projects.length===0?null:(yt=await Vi({projects:B.projects,hostTokenRef:B.hostTokenRef,transport:B.transport,closedWindowMs:B.closedWindowMs,now:o()}),yt)}function Xa(){if(!(bn!=null||fe?.armTransport==null))try{let d=fe.armTransport();if(d.transport!=null){bn=d.transport;return}d.unconfiguredReason!=null&&(dt=d.unconfiguredReason)}catch(d){dt=`this host could not resolve a tracker credential: ${d instanceof Error?d.message:String(d)}`}}async function xo(){let d=o();Qe(d);let f=[...A.values()].map(h=>({project_label:h.project_label,selector:h.selector})).sort((h,w)=>h.project_label.localeCompare(w.project_label));return f.length===0?null:(Xa(),bn==null?(ae=Ol(f,d,dt),ae):(ae=await $l({projects:f,transport:bn,now:d,...fe?.batchSize==null?{}:{batchSize:fe.batchSize}}),So(o()),ae))}async function Eo(){let d=o();if(kt)return vn??gi(d);kt=!0;try{let f={};for(let L of x.values())f[L.project_label]=(f[L.project_label]??0)+1;let h={};for(let L of ae?.projects??[])h[L.project_label]=L.depth;let w=Date.parse(d),v=fi({projects:[...A.values()].map(L=>({project_label:L.project_label,selector:L.selector,argv:L.argv,workspace_path:L.workspace_path,target:L.target})),queue:h,live:f,nowMs:Number.isFinite(w)?w:0,backoffUntilMs:Be}),P=[],ee=null;for(let L of v.births){let Ln;try{Ln=wt({project_label:L.project_label,workspace_path:L.workspace_path,command:L.argv[0],args:L.argv.slice(1)})}catch(xt){ee=xt instanceof Error?xt.message:String(xt),Be=(Number.isFinite(w)?w:Date.now())+za;break}P.push({project_label:L.project_label,worker_id:Ln.worker.worker_id,pid:Ln.worker.pid,warnings:Ln.warnings})}return ee==null&&v.births.length>0&&(Be=null),vn={version:1,at:d,requested:v.births.length,granted:P,shortfall:v.births.length-P.length,refusal:ee,retry_after:Be==null?null:new Date(Be).toISOString(),projects:v.intents},vn}finally{kt=!1}}function ed(d){return zi(Pn(),{...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 nd(d){return el(Pn(),{mode:d?.mode??Ne.mode,project:d?.project??Ne.project,maxWidth:d?.max_width??Ne.maxWidth,maxRows:d?.max_rows??Ne.maxRows})}function Ee(d,f,h){return Ai({op:d,sessionProject:f??null,targetProject:h})}async function td(d){let f=x.get(d.worker_id),h=Ee(Li(d.command),d.session_project,f?.project_label??null);if(!h.permitted)throw new Error(h.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=f!=null&&await id(f,d.detail??"stopped by its own project");return{version:1,command:d.command,worker_id:d.worker_id,applied:w,reach:h,detail:w?`redskilled stopped Worker ${JSON.stringify(d.worker_id)} of project ${JSON.stringify(f.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(d.worker_id)} to stop`}}function jn(d){x.delete(d),le.delete(d),Se.delete(d),_n.delete(d)}function Po(d){let f=x.get(d.worker_id),h=Ee("worker-heartbeat",d.session_project,f?.project_label??null);if(!h.permitted)throw new Error(h.reason);if(typeof d.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(f==null)return{version:1,worker_id:d.worker_id,accepted:!1,reach:h,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(d.worker_id)} to publish a line for`};let w=o();Se.set(d.worker_id,{line:d.last_log_line,published_at:w,source:"heartbeat"});let v=d.display===void 0?null:Zi(d.display);if(v!=null){let P={display:v,published_at:w};_n.set(d.worker_id,P),Ya(P,d.worker_id)}return{version:1,worker_id:d.worker_id,accepted:!0,reach:h,published_at:w,detail:`redskilled stored a line for Worker ${JSON.stringify(d.worker_id)} without reading it`}}async function rd(d,f,h){let w=`exit code=${f??"null"} signal=${h??"null"}`;if(d.unit!=null&&d.unit!==""&&await od(d)){sd(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}jn(d.worker_id),X("worker-death",d,w,{exitCode:f,signal:h}),$()}async function od(d){try{return await _(d)===!0}catch{return!1}}function sd(d,f){let h=d.unit==null?null:C(d.unit);x.set(d.worker_id,{...d,...h!=null&&h>0?{pid:h}:{},warnings:[...d.warnings,f]}),le.add(d.worker_id),$()}function jo(d,f){let h=Ee("project-register",f,d.project_label);if(!h.permitted)throw new Error(h.reason);let w=o();Qe(w);let v=Pi(d,{now:w,held:A.get(d.project_label)});return A.set(v.project_label,v),$(),{version:1,registration:v,reach:h,detail:`redskilled holds a registration for project ${JSON.stringify(v.project_label)} at a target of ${v.target} until ${v.renew_by}, and has read neither its selector nor its argv`}}function Do(d,f={}){let h=Ee("project-renew",f.sessionProject,d);if(!h.permitted)throw new Error(h.reason);let w=o();Qe(w);let v=A.get(d);if(v==null)throw new Qn(d);let P=ji(v,{now:w,...f.renewWithinMs==null?{}:{renew_within_ms:f.renewWithinMs},...f.launch==null?{}:{launch:f.launch}});return A.set(P.project_label,P),$(),{version:1,registration:P,reach:h,detail:`redskilled renewed the registration for project ${JSON.stringify(P.project_label)}, which now stands until ${P.renew_by} after renewal ${P.renewals}`+(f.launch==null?"":`, carrying launch revision ${P.launch_revision} for its next Worker`)}}function Oo(d,f){let h=Ee("project-deregister",f,d);if(!h.permitted)throw new Error(h.reason);let w=A.delete(d);return{version:1,project_label:d,released:w,reach:h,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 id(d,f){try{await D(d)}catch{}return jn(d.worker_id),X("worker-death",d,f),$(),!0}function $o(d){return li({ceiling:i,workers:[...x.values()],budget:d.budget,projectLabel:d.project_label})}function wt(d){let f=ai({ceiling:i,workers:[...x.values()],budget:d.budget}),h=s({spec:d,admission:$o(d),memoryCeiling:f,clock:o,onExit:(w,v,P)=>{let ee=x.get(w);if(ee==null){$();return}rd(ee,v,P).catch(()=>{})}});return x.set(h.worker.worker_id,h.worker),X("worker-birth",h.worker,null),$(),h}function X(d,f,h,w={}){if(Z)return;let v=o();(d==="worker-death"||d==="worker-budget-kill")&&Za({worker_id:f.worker_id,ts:v,outcome:d}),k.record({event:d,worker:f,ts:v,detail:h,...w.exitCode!==void 0?{exitCode:w.exitCode}:{},...w.signal!==void 0?{signal:w.signal}:{}}).catch(()=>{})}async function Lo(){let d=[...le].map(h=>x.get(h)).filter(h=>h!=null);if(d.length===0)return[];let{dead:f}=await Fr(d,_);for(let h of f)jn(h.worker_id),X("worker-death",h,"the host no longer confirms this Worker");return f.length>0&&$(),f}async function Ao(d,f){let h=x.get(d);if(!h)return!1;try{await D(h)}catch{}return jn(d),X("worker-budget-kill",h,f),$(),!0}async function Io(){let d=[...x.values()];if(d.length===0)return[];let f;try{f=await me(d)}catch{return[]}let h=f.rss;Ro=h,pt=o(),ld(f.cpu_seconds,pt);let{terminations:w}=Ci({workers:d,rss:h}),v=[];for(let P of w)await Ao(P.worker_id,P.reason)&&v.push(P);return v}function ld(d,f){for(let[h,w]of Object.entries(d)){if(typeof w!="number"||!Number.isFinite(w))continue;let v=x.get(h);v&&x.set(h,{...v,cpu:{cpu_seconds:w,sampled_at:f}})}}async function ad(){try{return po<=0?await co(t):await new Promise(d=>{let f=setTimeout(()=>d(vt()),po);f.unref(),co(t).then(h=>{clearTimeout(f),d(h)},()=>{clearTimeout(f),d(vt())})})}catch{return vt()}}function vt(){try{return qa(t)}catch{return null}}async function To(){if(yn(t))return ft+=1,mt=o(),gt="local-build",{act:"hold",reason:"local-build"};let d=zl(await ad()),f=d.version;bo=f,ht=d.newest??null,mt=o(),wo=Ql({running:t,newest:ht,supervised:fo});let h=Yl({running:t,published:f,supervised:fo});return _o=h.act==="replace",ft+=1,gt=h.act==="hold"?h.reason:null,He!=="in-progress"&&(He=h.act==="replace"?"pending":"none"),h}async function Dn(){let d=await To();if(d.act!=="replace"||He==="in-progress")return d;let f=Xl(d,go);return He="in-progress",await k.flush().catch(()=>{}),await $n({reason:"replaced"}),ea(f,n,{...r==null?{}:{idleMs:r},io:go}),d}function dd(){Z||qe!=null||uo<=0||(!Ga&&mo>0&&(Sn=setTimeout(()=>{Dn().catch(()=>{})},mo),Sn.unref()),qe=setInterval(()=>{Dn().catch(()=>{})},uo),qe.unref())}function cd(){Z||Ke!=null||Rn<=0||(Ke=setInterval(()=>{Io().catch(()=>{})},Rn),Ke.unref())}function ud(){Z||Ge!=null||B==null||B.projects.length===0||ho<=0||(_t().catch(()=>{}),Ge=setInterval(()=>{_t().catch(()=>{})},ho),Ge.unref())}function pd(){Z||ze!=null||yo<=0||(ze=setInterval(()=>{xo().catch(()=>{})},yo),ze.unref())}function md(){Z||Je!=null||ko<=0||(Je=setInterval(()=>{Eo().catch(()=>{})},ko),Je.unref())}function $(){Z||(xe&&clearTimeout(xe),xe=setTimeout(()=>{Lo().catch(()=>{}).then(()=>No())},r),xe.unref())}function No(){return x.size>0?($(),"held-by-workers"):(Qe(o()),A.size>0?($(),"held-by-registrations"):(fd(),"exited"))}async function fd(){if(!yn(t)){if((await Dn().catch(()=>null))?.act==="replace"||Rt||Z)return;if(x.size>0||A.size>0){$();return}}await $n({reason:"idle"})}function On(d){return yi({reason:d,socketPath:n.socketPath,daemonVersion:t,pid:l.pid,workers:[...x.values()],projects:[...A.keys()]})}function Wo(d){if(xn!=null)return xn;let f=d.reason??"requested",h=d.note?.trim();return xn=k.recordDaemonStop({ts:o(),pid:l.pid,socketPath:n.socketPath,reason:f,detail:h==null||h===""?On(f).detail:`${On(f).detail} \u2014 ${h}`,...d.signal==null?{}:{signal:d.signal}}).catch(()=>{}),xn}async function $n(d={}){if(Rt)return await bt;Rt=!0,await Wo(d),Z=!0,xe&&clearTimeout(xe),Ke&&clearInterval(Ke),qe&&clearInterval(qe),Sn&&clearTimeout(Sn),Ge&&clearInterval(Ge),ze&&clearInterval(ze),Je&&clearInterval(Je),await k.flush().catch(()=>{}),y.close();for(let f of ut)f.destroy();return await new Promise(f=>y.once("close",()=>f())),await ma(n.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await p.release(c).catch(()=>{}),vo(),await bt}let Mo=await k.read().catch(()=>[]);wn=Yn(Mo.filter(d=>d.event==="worker-death"||d.event==="worker-budget-kill").map(d=>({worker_id:d.worker_id,ts:d.ts,outcome:d.event})),d=>d.ts,{now:o()});let gd=mi(Mo),St=await Fr(gd,_);for(let d of St.alive){let f=Pl(d),h=f.unit==null||W(f.pid)?null:C(f.unit);x.set(f.worker_id,h!=null&&h>0?{...f,pid:h}:f),le.add(f.worker_id)}for(let d of St.dead)X("worker-death",d,"the Worker ended while no daemon was watching");let hd=El({units:await Promise.resolve(V()).catch(()=>[]),held:[...x.values()],mainPid:C,now:b});for(let d of hd)x.set(d.worker_id,d),le.add(d.worker_id),X("worker-birth",d,"adopted from an active unit with no birth on this lane");for(let d of St.alive){if(d.log_path==null||Se.has(d.worker_id))continue;let f=await ve(d.log_path).catch(()=>null);f==null||f.trim()===""||Se.set(d.worker_id,{line:f,published_at:o(),source:"rehydrated"})}y.on("connection",d=>{ut.add(d),d.once("close",()=>ut.delete(d)),$(),ch(d,async(f,h)=>{$();let w=await yd(f);h(w),f.op==="shutdown"&&setImmediate(()=>void $n({reason:"requested"}))})});async function yd(d){try{if(d.op==="ping")return{id:d.id,ok:!0,value:{pong:!0,protocol_version:et,daemon_version:t,pid:l.pid}};if(d.op==="host-state")return{id:d.id,ok:!0,value:En()};if(d.op==="statusline-payload")return{id:d.id,ok:!0,value:Pn()};if(d.op==="statusline-string")return{id:d.id,ok:!0,value:ed(d.render)};if(d.op==="statusline-dashboard")return{id:d.id,ok:!0,value:nd(d.dashboard)};if(d.op==="worker-heartbeat")return{id:d.id,ok:!0,value:Po(d.heartbeat)};if(d.op==="project-register")return{id:d.id,ok:!0,value:jo(d.registration,d.session_project)};if(d.op==="project-renew")return{id:d.id,ok:!0,value:Do(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:Oo(d.project_label,d.session_project)};if(d.op==="worker-command")return{id:d.id,ok:!0,value:await td(d.command)};if(d.op==="worker-start"){let h=Ee("worker-start",d.session_project,d.spec.project_label);if(!h.permitted)return{id:d.id,ok:!1,error:h.reason};let w=wt(d.spec);return await k.flush().catch(()=>{}),{id:d.id,ok:!0,value:{worker:w.worker,admission:w.admission,warnings:w.warnings}}}if(d.op==="shutdown"){let h=On("requested");return await Wo({reason:"requested",...d.detail==null?{}:{note:d.detail}}),{id:d.id,ok:!0,value:h}}let f=d;return{id:f.id??lt(),ok:!1,error:`unsupported redskilled op: ${f.op??"unknown"}`}}catch(f){return{id:d.id??lt(),ok:!1,error:f instanceof Error?f.message:String(f)}}}return $(),cd(),dd(),ud(),pd(),md(),{socketPath:n.socketPath,lease:g.lease,startedAt:b,closed:bt,startWorker:wt,admit:$o,ceiling:()=>i,killWorkerOverBudget:Ao,sampleMemoryBudgets:Io,pollRepositoryActivity:_t,pollQueueDiscovery:xo,queueDiscovery:()=>ae,driveDemand:Eo,demand:()=>vn,sweepReattached:Lo,publishWorkerHeartbeat:Po,reattached:()=>[...le].map(d=>x.get(d)).filter(d=>d!=null),flushEvents:()=>k.flush(),trackWorker(d){x.set(d.worker_id,d),X("worker-birth",d,null),$()},releaseWorker(d){let f=x.get(d),h=x.delete(d);return le.delete(d),Se.delete(d),_n.delete(d),f&&X("worker-death",f,"released by the daemon"),$(),h},workerCount:()=>x.size,registerProject:jo,renewProject:Do,deregisterProject:Oo,registrations:()=>En().registrations??[],hostState:En,statuslinePayload:Pn,evaluateIdle:No,observePublishedVersion:To,checkForReplacement:Dn,stopReport:On,stop:$n}}async function dh(e){for(let n=0;n<2;n++){let t=rh();try{return await new Promise((r,o)=>{t.once("error",o),t.listen(e,()=>{t.off("error",o),r()})}),t}catch(r){if(t.close(),r.code!=="EADDRINUSE")throw r;if(await se(e))throw new Ce(e);await ma(e,{force:!0})}}throw new Ce(e)}async function se(e,n=250){try{return(await Fn({socketPath:e,timeoutMs:n},{id:lt(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function ch(e,n){Gs(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??lt(),ok:!1,error:t instanceof Error?t.message:String(t)})})}re();var gh=1e4,Fe=class extends Error{constructor(t,r){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}`);this.socketPath=t;this.cause=r;this.name="RedskilledUnreachableError"}};async function Xr(e,n={}){try{return await hh(e,n)}catch(t){throw t instanceof pe||t instanceof Fe?t:new Fe(e.socketPath,t)}}async function hh(e,n){if(await ph(fh(e.socketPath),{recursive:!0,mode:448}),await se(e.socketPath))return"already-running";await yh(e);let t=await zs(e.lockPath);if(!t)return await ga(e,n),"joined";try{if(await se(e.socketPath))return"already-running";let r=await bh(e,n);return await ga(e,n,r),"spawned"}finally{await t.close(),await mh(e.lockPath,{force:!0})}}async function yh(e){let t=await zn(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&W(t.pid))throw new pe(e.machineClaimPath,"held",t)}async function ya(e,n,t={}){await Xr(e,t);let r;try{r=await fn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:ha()})}catch(o){throw new Fe(e.socketPath,o)}if(!r.ok)throw new Error(r.error);return r.value}async function ka(e,n={},t={}){if(!await se(e.socketPath))return ki(e.socketPath);let r;try{r=await fn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:ha(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new Fe(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!kr(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await kh(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 kh(e,n){let t=Date.now()+n;for(;;){if(!await se(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function Ra(e,n={}){let t=await ya(e,{op:"host-state"},n);if(!ol(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function ba(e,n=void 0,t={}){let r=await ya(e,{op:"statusline-string",...t.sessionProject!=null?{session_project:t.sessionProject}:{},...n==null?{}:{render:Rh(n)}},t);if(!tl(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function Rh(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 ga(e,n,t){let r=Date.now()+(n.readyTimeoutMs??gh);for(;;){if(await se(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=r){let o=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${o}`)}await new Promise(o=>setTimeout(o,25))}}async function bh(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await ri({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,..._e(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=uh(r.command,s,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return i.on("error",l=>{o.failure=l}),i.on("exit",(l,a)=>{o.exit=a?`died on ${a}`:`exited with code ${l??-1}`}),i.unref(),o}re();import{chmod as Pa,mkdir as Da,readFile as Oa,stat as $h,writeFile as Lh}from"node:fs/promises";import{homedir as to}from"node:os";import{dirname as Ah,join as ro}from"node:path";import{join as _h}from"node:path";var _a=["local","tmp","host"],wh="local",kn="plugins.dev.workspace.target";var eo=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function va(e){let n=Le(e,kn),t=xh(n??"").trim();return t===""?void 0:t}function Sa(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:wh};let t=_a.find(r=>r===n.toLowerCase());if(t)return{kind:"preset",preset:t};if(n.startsWith("/")||n==="~"||n.startsWith("~/"))return{kind:"custom",parentDir:n};throw new eo(`${kn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${_a.join(", ")}) or an absolute parent directory for Workers.`)}function xa(e,n){return e.kind==="preset"?e.preset==="host":Sh(vh(e.parentDir,n),be(n))}function vh(e,n){return e==="~"?wa(n):e.startsWith("~/")?_h(n,e.slice(2)):wa(e)}function Sh(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function wa(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function xh(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}re();import{createHash as Eh}from"node:crypto";import{hostname as Ph}from"node:os";import{join as at}from"node:path";var Ue="redskilled.sock",jh="REDSKILLED_SESSION";function Dh(e={}){let n=e.env??process.env,t=n[jh]?.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 Oh(e={}){return Ea(e.host??Ph())}function ie(e={}){let n=Dh(e),t=e.runtimeDir??Un({key:`redskilled:${n}`,socketFileName:Ue,env:e.env,uid:e.uid}),r=Oh(e);return{sessionKey:n,sessionKeyHash:Ea(n),machineIdHash:r,runtimeDir:t,socketPath:at(t,Ue),lockPath:at(t,"redskilled.spawn.lock"),leasePath:at(t,"redskilled.lease.toon"),eventLanePath:at(t,ui),machineClaimPath:e.machineClaimPath??Gn({env:e.env,machineIdHash:r,platform:e.platform})}}function Ea(e){return Eh("sha256").update(e).digest("hex").slice(0,12)}var no="run `/red-setup` (Section E3 \u2014 execution daemon), or `redskilled provision` directly";async function $a(e=to()){let n=be(e),t=await so(n);return t===void 0?(await Da(n,{recursive:!0,mode:z}),await Pa(n,z),{path:n,created:!0,tightened:!1,mode:z}):t===z?{path:n,created:!1,tightened:!1,mode:t}:(await Pa(n,z),{path:n,created:!1,tightened:!0,mode:z})}var La={needed:!1,declaredBy:`no ${kn} in view`};async function oo(e={}){let n=e.homeDir??to(),t=e.declaredTarget?.trim();if(t)return ja(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return La;let o=ro(r,".red","config.yaml"),s=await Oa(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=va(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:ja(i,n,o)}function ja(e,n,t){let r=`${kn}: ${e} (${t})`;try{return{needed:xa(Sa(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function Aa(e){let n=[Ih(e),Th(e),Nh(e),Wh(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 Ih(e){let n=e.homeNeed??La;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:no}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??z;return t!==z?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${z.toString(8)}`,fix:`${no} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function Th(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 Nh(e){return e.reachable?{check:"reach",verdict:"ok",evidence:`daemon answered on ${e.socketPath}`,fix:""}:{check:"reach",verdict:"missing",evidence:`no daemon answered on ${e.socketPath}`,fix:`${no} \u2014 it starts the daemon and waits for the socket`}}function Wh(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 Ia(e={}){let n=e.env??process.env,t=e.homeDir??to(),r=e.paths??ie({env:n}),o=be(t),[s,i,l]=await Promise.all([so(o),se(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):oo({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:ue(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await Ch(Fh(e,n,t),n)}}var Mh="redskilled.service";function Ta(e){return ro(e,"systemd","user",Mh)}function Na(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 Wa(e){let n=Ta(e.configHome);return await so(n)!==void 0?{path:n,status:"already-present"}:(await Da(Ah(n),{recursive:!0}),await Lh(n,e.unit,"utf8"),{path:n,status:"installed"})}async function Ch(e,n){if(process.platform!=="linux")return"unsupported";try{return await Oa(Ta(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function Fh(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??ro(t,".config")}async function so(e){try{return(await $h(e)).mode&511}catch{return}}import{readdir as Ca,rm as Uh,stat as Hh}from"node:fs/promises";import{dirname as Vh,join as io}from"node:path";var Bh=5*6e4,Kh="redskilled.";function Jh(e={}){let n=e.env??process.env,t=i=>Vh(Un({key:"redskilled:reclaim-probe",socketFileName:Ue,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 Fa(e={}){let n=e.roots??Jh(e),t=e.graceMs??Bh,r=e.now??Date.now,o=e.isPidAlive??W,s=e.answers??Qh,i=e.dryRun===!0,l=[];for(let a of n){let c;try{c=(await Ca(a,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name)}catch{continue}for(let u of c.sort())l.push(await qh(io(a,u),{graceMs:t,now:r,pidAlive:o,answers:s,dryRun:i}))}return{roots:n,scanned:l.length,reclaimed:l.filter(a=>a.verdict==="reclaimed").length,dryRun:i,entries:l}}async function qh(e,n){let t;try{t=(await Ca(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:Ua(i),removed:[]}}let r=t.filter(i=>i.startsWith(Kh));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await Gh(io(e,"redskilled.lease.toon"));if(o!==void 0)return await n.pidAlive(o.pid)?{dir:e,verdict:"live",reason:`lease pid ${o.pid} is alive`,removed:[]}:await Ma(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(Ue)&&await n.answers(io(e,Ue)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await zh(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 Uh(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:Ua(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function Gh(e){try{return await Yr(e)}catch{return}}async function zh(e,n){try{return Math.max(0,n()-(await Hh(e)).mtimeMs)}catch{return}}async function Qh(e){try{return(await fn({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function Ua(e){return e instanceof Error?e.message:String(e)}var Yh="plugins.dev.statusline",Zh="dev.statusline";function Xh(e){let n=[],t=l=>{for(let a of[Yh,Zh]){let c=`${a}.${l}`,u=Le(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 ey={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 Ha(e){let{values:n,positionals:t}=ke(e,ey),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 Va(e={}){let n=e.configText==null?{config:{},warnings:[]}:Xh(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 ty=`Usage: redskilled <command> [options]
75
+ `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function tk(e,n={}){let t=n.env??process.env,r=n.exists??zy,o=n.execPath??process.execPath,i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,s=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[ld(mt(t),s),"bundle-cache"]];i&&l.push([ld(Xy(Zy(i)),s),"caller-sibling-bundle"]);for(let[d,p]of l)if(a.push(d),r(d))return{command:o,args:[d],version:e,source:p,searched:a};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new $o(e,a);return{command:t.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:a}}function yd(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>tk(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function kd(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??ok)(ad),{...e,exitCode:ad};let o=[...e.entry.args,...Oe(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??rk(r.env))(e.entry,o),e}function rk(e){return(n,t)=>{let r=Qy(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[ud]:"1"}});r.on("error",()=>{}),r.unref()}}function ok(e){process.exitCode=e,process.exit(e)}async function Rd(e,n=process.env,t=ik){let r=_d(n),o=wd(e,n);if(n[ek]==="1")return{version:o,newest:r};let i=X(e)===null?"0.0.0":e;try{let s=await il({fetchText:t},i);return{version:s.sameMajor??o,newest:s.newest??r}}catch{return{version:o,newest:r}}}function bd(e,n=process.env,t){let r=t??Io;return{version:wd(e,n,r),newest:_d(n,r)}}function _d(e=process.env,n=Io){return Sd(xd(e,n))}function wd(e,n=process.env,t=Io){let r=X(e.trim())?.major;return r===void 0?null:Sd(xd(n,t).filter(o=>X(o)?.major===r))}function xd(e,n){let t=[];for(let r of n(mt(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||X(o)===null||t.push(o)}return t}function Sd(e){let n=null;for(let t of e)(n===null||jo(t,n)>0)&&(n=t);return n}function Io(e){try{return Yy(e)}catch{return[]}}async function ik(e){let n=await fetch(e,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`registry read failed with HTTP ${n.status}`);return await n.text()}import{mkdir as sk,readFile as lk,rename as ak,rm as To,writeFile as vd}from"node:fs/promises";import{randomUUID as dk}from"node:crypto";import{dirname as ck}from"node:path";var It=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function In(e){let n;try{n=await lk(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=uk(n);return pk(t)?t:void 0}var Ed;function jd(){return Ed??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Ed}function Dd(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??U;async function i(){return await In(e)}async function s(l){let d=`${e}.${l.pid}.${dk()}.tmp`;await vd(d,Pd(l),{encoding:"utf8",mode:384}),await ak(d,e)}function a(l,d){return{version:1,pid:l.pid,start_time:l.startTime,session_key_hash:n.sessionKeyHash,machine_id_hash:n.machineIdHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}return{read:i,async acquire(l){await sk(ck(e),{recursive:!0,mode:448});let d=!1;for(;;){let p=r(),u=a(l,p);try{return await vd(e,Pd(u),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:u}}catch(m){if(m.code!=="EEXIST")throw m}let f=await i();if(!f){await To(e,{force:!0}),d=!0;continue}if(No(f,l))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await To(e,{force:!0}),d=!0}},async renew(l){let d=await i();if(!d||!No(d,l))throw new It(e);let p={...d,renewed_at:r()};return await s(p),p},async release(l){let d=await i();if(!d)return!1;if(!No(d,l))throw new It(e);return await To(e,{force:!0}),!0}}}function No(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function Pd(e){return`${M(e,{keyedMapCollapse:!0})}
76
+ `}function uk(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return z(n)}catch{return null}}}function pk(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||!Number.isInteger(n.pid)||n.pid<=0)return!1;for(let t of["start_time","session_key_hash","machine_id_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var Co=3e5,bk=1e4,_k=6e4,wk=15e3,xk=3e4,Od=16,nn=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},Sk="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Ld(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??Co,o=e.clock??(()=>new Date().toISOString()),i=e.launch??ed,s=e.ceiling??gl();e.repositoryActivity!=null&&fo(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??jd(),l=e.leaseStore??Dd(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??$l(),p={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},u=e.machineClaimStore??_t(n.machineClaimPath,p,{clock:o});await yk(Rk(n.socketPath),{recursive:!0,mode:448});let f=await u.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new nn(n.socketPath):new be(u.claimPath,f.reason,f.claim);let m=await l.acquire(a);if(!m.acquired)throw await u.release(d).catch(()=>{}),new nn(n.socketPath,m.lease);let h;try{h=await vk(n.socketPath)}catch(c){throw await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),c}let b=o(),k=e.eventLane??Rl(n.eventLanePath),w=e.liveness??Ca,j=e.stopWorker??Va,ee=e.unitInventory??(()=>Ha(n.machineClaimPath,bt({machineIdHash:n.machineIdHash}))?Fa():[]),q=e.unitMainPid??Wa,we=e.treeSampler??zl,Te=e.readLogTail??nd,Cn=e.sampleMs??wk,Yo=e.leaseRenewMs??xk,Xo=e.publishedVersion??(c=>Rd(c)),Zo=e.replaceCheckMs??cd,ei=e.publishedProbeTimeoutMs??bk,fc=e.localPublishedEvidence??(c=>bd(c,e.replacementIO?.env??process.env)),mc=e.bornByReplacement??pd(),ni=e.replaceBootCheckMs??_k,ti=e.supervised??gd(),ri=e.replacementIO??{},ne=e.repositoryActivity,oi=ne?.intervalMs??po,xe=e.queueDiscovery,Mn=xe?.transport??ne?.transport,Ct=xe?.unconfiguredReason??Sk,ii=xe?.intervalMs??15e3,si=e.demandMs??15e3,hc=e.demandBackoffMs??3e4,v=new Map,he=new Set,Ne=new Map,Wn=new Map,Mt=[],Hn=[],I=new Map,Wt=new Set,li={},Ht=null,ai=null,Ft=null,di=!1,Ut=0,Bt=null,rn="none",Vt=null,ci=null,Kt=null,ge=null,Fn=null,on=[],sn=null,Un={},qt=!1,Ce,ln,an,dn,cn,Bn,un,pn,te=!1,Jt=!1,Vn=null,ui,Gt=new Promise(c=>{ui=c});function fn(c){pi(c);let g=Date.parse(c),y=Fl(I.values(),g);for(let _ of y.lapsed)I.delete(_.project_label),gc(_,g);return y.lapsed}function gc(c,g){let y=Number.isFinite(g)?new Date(g).toISOString():c.renew_by;on.push({project_label:c.project_label,at:y,renew_by:c.renew_by,renewals:c.renewals,sustains:c.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(c.project_label)}: it stood until ${c.renew_by} and nothing renewed it \u2014 no session spoke for it, and no poll found it work or a Worker to hold it up`}),on.length>Od&&on.splice(0,on.length-Od)}function pi(c){if(I.size===0)return;let g=Date.parse(c);if(!Number.isFinite(g))return;let y={};for(let x of v.values())y[x.project_label]=(y[x.project_label]??0)+1;let _=new Map((ge?.projects??[]).map(x=>[x.project_label,x]));for(let x of[...I.values()]){let P=_.get(x.project_label),ce=Wl(x,{now:c,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:y[x.project_label]??0});ce.registration!==x&&I.set(x.project_label,ce.registration)}}function Kn(){let c=o();return fn(c),Ra({now:c,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:a.pid,startedAt:b,scope:Il(u.claimPath,p,d),workers:[...v.values()],hostCeilingBytes:s.memory_bytes,registrations:[...I.values()],lapses:on,queue:ge,published:{version:ai,checkedAt:Ft,newer:di,replacement:rn,newest:Vt,majorHold:ci,checks:Ut,holdReason:Bt}})}function qn(){return ca({hostState:Kn(),ceiling:s,rss:li,sampledAt:Ht,logLines:Object.fromEntries(Ne),displays:Object.fromEntries(Wn),now:o(),reattachedWorkerIds:[...he],repositoryActivity:Kt,...e.deaths===void 0?{}:{deaths:e.deaths},metrics:Gl({observations:Mt,outcomes:Hn,now:o()})})}function yc(c,g){Mt=xt([...Mt,{worker_id:g,observed_at:c.published_at,tokens:c.display.tokens,tools:c.display.tools,runner:c.display.runner,model:c.display.model}],y=>y.observed_at,{now:o()})}function kc(c){Hn=xt([...Hn,c],g=>g.ts,{now:o()})}async function Qt(){return ne==null||ne.projects.length===0?null:(Kt=await ia({projects:ne.projects,hostTokenRef:ne.hostTokenRef,transport:ne.transport,closedWindowMs:ne.closedWindowMs,now:o()}),Kt)}function Rc(){if(!(Mn!=null||xe?.armTransport==null))try{let c=xe.armTransport();if(c.transport!=null){Mn=c.transport;return}c.unconfiguredReason!=null&&(Ct=c.unconfiguredReason)}catch(c){Ct=`this host could not resolve a tracker credential: ${c instanceof Error?c.message:String(c)}`}}async function fi(){let c=o();fn(c);let g=[...I.values()].map(y=>({project_label:y.project_label,selector:y.selector})).sort((y,_)=>y.project_label.localeCompare(_.project_label));return g.length===0?null:(Rc(),Mn==null?(ge=qa(g,c,Ct),ge):(ge=await Ja({projects:g,transport:Mn,now:c,...xe?.batchSize==null?{}:{batchSize:xe.batchSize}}),pi(o()),ge))}async function mi(){let c=o();if(qt)return Fn??wl(c);qt=!0;try{let g={};for(let O of v.values())g[O.project_label]=(g[O.project_label]??0)+1;let y={};for(let O of ge?.projects??[])y[O.project_label]=O.depth;let _=Date.parse(c),x=_l({projects:[...I.values()].map(O=>({project_label:O.project_label,selector:O.selector,argv:O.argv,workspace_path:O.workspace_path,target:O.target})),queue:y,live:g,nowMs:Number.isFinite(_)?_:0,backoffUntilMs:sn,birthHaltUntilMs:Sl(Un,Number.isFinite(_)?_:0)}),P=[],ce=null;for(let O of x.births){let We,Fc=Tn(),Yn=I.get(O.project_label),ji=Nl({argv:O.argv,...Yn?.env==null?{}:{env:Yn.env},...Yn?.log_path==null?{}:{log_path:Yn.log_path}},{worker_id:Fc,slot:O.index,workspace_path:O.workspace_path},{project_label:O.project_label});try{We=zt(ji)}catch(Zt){ce=Zt instanceof Error?Zt.message:String(Zt),sn=(Number.isFinite(_)?_:Date.now())+hc;break}P.push({project_label:O.project_label,worker_id:We.worker.worker_id,pid:We.worker.pid,warnings:ji.log_path==null?[...We.warnings,`project ${JSON.stringify(O.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(We.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:We.warnings})}return ce==null&&x.births.length>0&&(sn=null),Fn={version:1,at:c,requested:x.births.length,granted:P,shortfall:x.births.length-P.length,refusal:ce,retry_after:sn==null?null:new Date(sn).toISOString(),projects:x.intents},Fn}finally{qt=!1}}function bc(c){return ua(qn(),{...$,mode:c?.mode??$.mode,project:c?.project??$.project,maxWorkers:c?.max_workers??$.maxWorkers,maxProjects:c?.max_projects??$.maxProjects,maxWidth:c?.max_width??$.maxWidth,verbose:c?.verbose??$.verbose})}function _c(c){return ga(qn(),{mode:c?.mode??Xe.mode,project:c?.project??Xe.project,maxWidth:c?.max_width??Xe.maxWidth,maxRows:c?.max_rows??Xe.maxRows})}function Me(c,g,y){return Bl({op:c,sessionProject:g??null,targetProject:y})}async function wc(c){let g=v.get(c.worker_id),y=Me(Ul(c.command),c.session_project,g?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(c.command!=="stop")throw new Error(`redskilled does not implement ${c.command}: it owns birth, death and limits, and ${c.command} is a work decision the project's own bundle makes on top of them`);let _=g!=null&&await Pc(g,c.detail??"stopped by its own project");return{version:1,command:c.command,worker_id:c.worker_id,applied:_,reach:y,detail:_?`redskilled stopped Worker ${JSON.stringify(c.worker_id)} of project ${JSON.stringify(g.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function Jn(c){v.delete(c),he.delete(c),Ne.delete(c),Wn.delete(c)}function hi(c){let g=v.get(c.worker_id),y=Me("worker-heartbeat",c.session_project,g?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(typeof c.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(g==null)return{version:1,worker_id:c.worker_id,accepted:!1,reach:y,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to publish a line for`};let _=o();Ne.set(c.worker_id,{line:c.last_log_line,published_at:_,source:"heartbeat"});let x=c.display===void 0?null:ma(c.display);if(x!=null){let P={display:x,published_at:_};Wn.set(c.worker_id,P),yc(P,c.worker_id)}return{version:1,worker_id:c.worker_id,accepted:!0,reach:y,published_at:_,detail:`redskilled stored a line for Worker ${JSON.stringify(c.worker_id)} without reading it`}}async function xc(c,g,y){let _=`exit code=${g??"null"} signal=${y??"null"}`;if(c.unit!=null&&c.unit!==""&&await vc(c)){Ec(c,`its launch client ended (${_}) while unit ${JSON.stringify(c.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}Jn(c.worker_id),de("worker-death",c,_,{exitCode:g,signal:y}),T()}function Sc(c,g){if(!Number.isFinite(g)||g<0){Un[c]=Rt;return}let y=Un[c]??Rt,_=xl(y,g,Date.parse(o()));Un[c]=_,_.haltUntilMs!=null&&y.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(c)} lost ${_.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(_.haltUntilMs).toISOString()}
77
+ `)}async function vc(c){try{return await w(c)===!0}catch{return!1}}function Ec(c,g){let y=c.unit==null?null:q(c.unit);v.set(c.worker_id,{...c,...y!=null&&y>0?{pid:y}:{},warnings:[...c.warnings,g]}),he.add(c.worker_id),T()}function gi(c,g){let y=Me("project-register",g,c.project_label);if(!y.permitted)throw new Error(y.reason);let _=o();fn(_);let x=Cl(c,{now:_,held:I.get(c.project_label)});return I.set(x.project_label,x),T(),{version:1,registration:x,reach:y,detail:`redskilled holds a registration for project ${JSON.stringify(x.project_label)} at a target of ${x.target} until ${x.renew_by}, and has read neither its selector nor its argv`}}function yi(c,g={}){let y=Me("project-renew",g.sessionProject,c);if(!y.permitted)throw new Error(y.reason);let _=o();fn(_);let x=I.get(c);if(x==null)throw new wt(c);let P=Ml(x,{now:_,...g.renewWithinMs==null?{}:{renew_within_ms:g.renewWithinMs},...g.launch==null?{}:{launch:g.launch}});return I.set(P.project_label,P),T(),{version:1,registration:P,reach:y,detail:`redskilled renewed the registration for project ${JSON.stringify(P.project_label)}, which now stands until ${P.renew_by} after renewal ${P.renewals}`+(g.launch==null?"":`, carrying launch revision ${P.launch_revision} for its next Worker`)}}function ki(c,g){let y=Me("project-deregister",g,c);if(!y.permitted)throw new Error(y.reason);let _=I.delete(c);return{version:1,project_label:c,released:_,reach:y,detail:_?`redskilled released the registration for project ${JSON.stringify(c)}`:`redskilled held no registration for project ${JSON.stringify(c)}, so there was nothing to release`}}async function Pc(c,g){try{await j(c)}catch{}return Jn(c.worker_id),de("worker-death",c,g),T(),!0}function Ri(c){return ml({ceiling:s,workers:[...v.values()],budget:c.budget,projectLabel:c.project_label})}function zt(c){let g=hl({ceiling:s,workers:[...v.values()],budget:c.budget}),y=i({spec:c,admission:Ri(c),memoryCeiling:g,clock:o,onExit:(_,x,P)=>{let ce=v.get(_);if(ce==null){T();return}xc(ce,x,P).catch(()=>{})}});return v.set(y.worker.worker_id,y.worker),de("worker-birth",y.worker,null),T(),y}function de(c,g,y,_={}){if(te)return;let x=o();(c==="worker-death"||c==="worker-budget-kill")&&(kc({worker_id:g.worker_id,ts:x,outcome:c}),Sc(g.project_label,Date.parse(x)-Date.parse(g.started_at))),k.record({event:c,worker:g,ts:x,detail:y,..._.exitCode!==void 0?{exitCode:_.exitCode}:{},..._.signal!==void 0?{signal:_.signal}:{}}).catch(()=>{})}async function bi(){let c=[...he].map(y=>v.get(y)).filter(y=>y!=null);if(c.length===0)return[];let{dead:g}=await Eo(c,w);for(let y of g)Jn(y.worker_id),de("worker-death",y,"the host no longer confirms this Worker");return g.length>0&&T(),g}async function _i(c,g){let y=v.get(c);if(!y)return!1;try{await j(y)}catch{}return Jn(c),de("worker-budget-kill",y,g),T(),!0}async function wi(){let c=[...v.values()];if(c.length===0)return[];let g;try{g=await we(c)}catch{return[]}let y=g.rss;li=y,Ht=o(),jc(g.cpu_seconds,Ht),Dc(g.sources);let{terminations:_}=Ql({workers:c,rss:y,...g.sources==null?{}:{sources:g.sources}}),x=[];for(let P of _)await _i(P.worker_id,P.reason)&&x.push(P);return x}function jc(c,g){for(let[y,_]of Object.entries(c)){if(typeof _!="number"||!Number.isFinite(_))continue;let x=v.get(y);x&&v.set(y,{...x,cpu:{cpu_seconds:_,sampled_at:g}})}}function Dc(c){for(let[g,y]of Object.entries(c??{})){let _=v.get(g);_&&v.set(g,{..._,rss_source:y})}}async function Oc(){try{return ei<=0?await Xo(t):await new Promise(c=>{let g=setTimeout(()=>c(Yt()),ei);g.unref(),Xo(t).then(y=>{clearTimeout(g),c(y)},()=>{clearTimeout(g),c(Yt())})})}catch{return Yt()}}function Yt(){try{return fc(t)}catch{return null}}async function xi(){if($n(t))return Ut+=1,Ft=o(),Bt="local-build",{act:"hold",reason:"local-build"};let c=fd(await Oc()),g=c.version;ai=g,Vt=c.newest??null,Ft=o(),ci=md({running:t,newest:Vt,supervised:ti});let y=hd({running:t,published:g,supervised:ti});return di=y.act==="replace",Ut+=1,Bt=y.act==="hold"?y.reason:null,rn!=="in-progress"&&(rn=y.act==="replace"?"pending":"none"),y}async function Gn(){let c=await xi();if(c.act!=="replace"||rn==="in-progress")return c;let g=yd(c,ri);return rn="in-progress",await k.flush().catch(()=>{}),await zn({reason:"replaced"}),kd(g,n,{...r==null?{}:{idleMs:r},io:ri}),c}function Ac(){te||cn!=null||Zo<=0||(!mc&&ni>0&&(Bn=setTimeout(()=>{Gn().catch(()=>{})},ni),Bn.unref()),cn=setInterval(()=>{Gn().catch(()=>{})},Zo),cn.unref())}async function Si(){return await l.renew(a).catch(()=>null)}function Lc(){te||an!=null||Yo<=0||(an=setInterval(()=>{Si()},Yo),an.unref())}function $c(){te||ln!=null||Cn<=0||(ln=setInterval(()=>{wi().catch(()=>{})},Cn),ln.unref())}function Ic(){te||un!=null||ne==null||ne.projects.length===0||oi<=0||(Qt().catch(()=>{}),un=setInterval(()=>{Qt().catch(()=>{})},oi),un.unref())}function Tc(){te||pn!=null||ii<=0||(pn=setInterval(()=>{fi().catch(()=>{})},ii),pn.unref())}function Nc(){te||dn!=null||si<=0||(dn=setInterval(()=>{mi().catch(()=>{})},si),dn.unref())}function T(){te||(Ce&&clearTimeout(Ce),Ce=setTimeout(()=>{bi().catch(()=>{}).then(()=>vi())},r),Ce.unref())}function vi(){return v.size>0?(T(),"held-by-workers"):(fn(o()),I.size>0?(T(),"held-by-registrations"):(Cc(),"exited"))}async function Cc(){if(!$n(t)){if((await Gn().catch(()=>null))?.act==="replace"||Jt||te)return;if(v.size>0||I.size>0){T();return}}await zn({reason:"idle"})}function Qn(c){return El({reason:c,socketPath:n.socketPath,daemonVersion:t,pid:a.pid,workers:[...v.values()],projects:[...I.keys()]})}function Ei(c){if(Vn!=null)return Vn;let g=c.reason??"requested",y=c.note?.trim();return Vn=k.recordDaemonStop({ts:o(),pid:a.pid,socketPath:n.socketPath,reason:g,detail:y==null||y===""?Qn(g).detail:`${Qn(g).detail} \u2014 ${y}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),Vn}async function zn(c={}){if(Jt)return await Gt;Jt=!0,await Ei(c),te=!0,Ce&&clearTimeout(Ce),ln&&clearInterval(ln),an&&clearInterval(an),cn&&clearInterval(cn),Bn&&clearTimeout(Bn),un&&clearInterval(un),pn&&clearInterval(pn),dn&&clearInterval(dn),await k.flush().catch(()=>{}),h.close();for(let g of Wt)g.destroy();return await new Promise(g=>h.once("close",()=>g())),await Ad(n.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),ui(),await Gt}let Pi=await k.read().catch(()=>[]);Hn=xt(Pi.filter(c=>c.event==="worker-death"||c.event==="worker-budget-kill").map(c=>({worker_id:c.worker_id,ts:c.ts,outcome:c.event})),c=>c.ts,{now:o()});let Mc=bl(Pi),Xt=await Eo(Mc,w);for(let c of Xt.alive){let g=Ba(c),y=g.unit==null||U(g.pid)?null:q(g.unit);v.set(g.worker_id,y!=null&&y>0?{...g,pid:y}:g),he.add(g.worker_id)}for(let c of Xt.dead)de("worker-death",c,"the Worker ended while no daemon was watching");let Wc=Ua({units:await Promise.resolve(ee()).catch(()=>[]),held:[...v.values()],mainPid:q,now:b});for(let c of Wc)v.set(c.worker_id,c),he.add(c.worker_id),de("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of Xt.alive){if(c.log_path==null||Ne.has(c.worker_id))continue;let g=await Te(c.log_path).catch(()=>null);g==null||g.trim()===""||Ne.set(c.worker_id,{line:g,published_at:o(),source:"rehydrated"})}h.on("connection",c=>{Wt.add(c),c.once("close",()=>Wt.delete(c)),T(),Ek(c,async(g,y)=>{T();let _=await Hc(g);y(_),g.op==="shutdown"&&setImmediate(()=>void zn({reason:"requested"}))})});async function Hc(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:jt,daemon_version:t,pid:a.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:Kn()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:qn()};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:bc(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:_c(c.dashboard)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:hi(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:gi(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:yi(c.project_label,{...c.session_project==null?{}:{sessionProject:c.session_project},...c.renew_within_ms==null?{}:{renewWithinMs:c.renew_within_ms},...c.launch==null?{}:{launch:c.launch}})};if(c.op==="project-deregister")return{id:c.id,ok:!0,value:ki(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await wc(c.command)};if(c.op==="worker-start"){let y=Me("worker-start",c.session_project,c.spec.project_label);if(!y.permitted)return{id:c.id,ok:!1,error:y.reason};let _=zt(c.spec);return await k.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:_.worker,admission:_.admission,warnings:_.warnings}}}if(c.op==="shutdown"){let y=Qn("requested");return await Ei({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:y}}let g=c;return{id:g.id??Tn(),ok:!1,error:`unsupported redskilled op: ${g.op??"unknown"}`}}catch(g){return{id:c.id??Tn(),ok:!1,error:g instanceof Error?g.message:String(g)}}}return T(),$c(),Lc(),Ac(),Ic(),Tc(),Nc(),{socketPath:n.socketPath,lease:m.lease,startedAt:b,closed:Gt,startWorker:zt,admit:Ri,ceiling:()=>s,killWorkerOverBudget:_i,sampleMemoryBudgets:wi,renewLease:Si,pollRepositoryActivity:Qt,pollQueueDiscovery:fi,queueDiscovery:()=>ge,driveDemand:mi,demand:()=>Fn,sweepReattached:bi,publishWorkerHeartbeat:hi,reattached:()=>[...he].map(c=>v.get(c)).filter(c=>c!=null),flushEvents:()=>k.flush(),trackWorker(c){v.set(c.worker_id,c),de("worker-birth",c,null),T()},releaseWorker(c){let g=v.get(c),y=v.delete(c);return he.delete(c),Ne.delete(c),Wn.delete(c),g&&de("worker-death",g,"released by the daemon"),T(),y},workerCount:()=>v.size,registerProject:gi,renewProject:yi,deregisterProject:ki,registrations:()=>Kn().registrations??[],hostState:Kn,statuslinePayload:qn,evaluateIdle:vi,observePublishedVersion:xi,checkForReplacement:Gn,stopReport:Qn,stop:zn}}async function vk(e){for(let n=0;n<2;n++){let t=kk();try{return await new Promise((r,o)=>{t.once("error",o),t.listen(e,()=>{t.off("error",o),r()})}),t}catch(r){if(t.close(),r.code!=="EADDRINUSE")throw r;if(await Z(e))throw new nn(e);await Ad(e,{force:!0})}}throw new nn(e)}async function Z(e,n=250){try{return(await ut({socketPath:e,timeoutMs:n},{id:Tn(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function Ek(e,n){el(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??Tn(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function Mo(e){let n=e.socketPath,t=Pk(e);return e.answers?{version:1,kind:"answering",socket_path:n,holder:t,reason:`a redskilled daemon answered on ${JSON.stringify(n)}`,repair:"nothing to repair"}:t!=null?{version:1,kind:"held-unresponsive",socket_path:n,holder:t,reason:`redskilled pid ${t.pid} is alive and has held ${JSON.stringify(n)} since ${t.acquired_at}${t.uptime_ms==null?"":` (up ${$d(t.uptime_ms)})`}, but it did not answer a ping \u2014 this is a daemon that could not be REACHED, not one that is missing.`,repair:`Do not provision: a daemon is already running. Inspect it (\`ps -p ${t.pid}\`), or stop it with \`${_e("red-skills-redskilled",["stop"])}\` and let the next client start a fresh one.`}:{version:1,kind:"absent",socket_path:n,holder:null,reason:`nothing answered on ${JSON.stringify(n)} and no live process holds its lease`,repair:`Install and start one with \`${_e("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function Wo(e){return`${e.reason} ${e.repair}`}function Pk(e){let n=e.lease;return n==null||e.holderAlive!==!0||n.socket_path!==e.socketPath?null:{pid:n.pid,socket_path:n.socket_path,acquired_at:n.acquired_at,renewed_at:n.renewed_at,uptime_ms:jk(n.acquired_at,e.now??new Date().toISOString())}}function jk(e,n){let t=Date.parse(e),r=Date.parse(n);return!Number.isFinite(t)||!Number.isFinite(r)?null:Math.max(0,r-t)}function $d(e){let n=Math.floor(e/1e3),t=Math.floor(n/3600),r=Math.floor(n%3600/60),o=n%60;return t>0?`${t}h${String(r).padStart(2,"0")}m`:r>0?`${r}m${String(o).padStart(2,"0")}s`:`${o}s`}pe();var Nd=1e4,Ie=class extends Error{constructor(t,r,o){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}${o!=null&&o.kind==="held-unresponsive"?`. ${Wo(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},Ho=class extends Ie{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}};async function Tt(e,n={}){let t=n.answers??await Z(e.socketPath),r=await In(e.leasePath).catch(()=>{});return Mo({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&U(r.pid)})}async function Fo(e,n={}){try{return await $k(e,n)}catch(t){if(t instanceof be||t instanceof Ie)throw t;let r=await Tt(e).catch(()=>{});throw new Ie(e.socketPath,t,r)}}async function $k(e,n){if(await Ok(Lk(e.socketPath),{recursive:!0,mode:448}),await Z(e.socketPath))return"already-running";await Tk(e);let t=await Ik(e,n);if(t!=null)return t;let r=await nl(e.lockPath);if(!r)return await Id(e,n),"joined";try{if(await Z(e.socketPath))return"already-running";let o=await Mk(e,n);return await Id(e,n,o),"spawned"}finally{await r.close(),await Ak(e.lockPath,{force:!0})}}async function Ik(e,n){let t=await Tt(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??Nd,o=Date.now()+r;for(;;){if(await Z(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(s=>setTimeout(s,25))}let i=await Tt(e).catch(()=>{});if(i==null||i.kind!=="held-unresponsive")return null;throw new Ho(e.socketPath,i,new Error(`it did not answer a ping within ${r}ms, and no second daemon was spawned because pid ${i.holder?.pid??"unknown"} still holds this socket`))}async function Tk(e){let t=await _t(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&U(t.pid))throw new be(e.machineClaimPath,"held",t)}async function Cd(e,n,t={}){await Fo(e,t);let r;try{r=await On({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:Td()})}catch(o){throw new Ie(e.socketPath,o,await Tt(e).catch(()=>{}))}if(!r.ok)throw new Error(r.error);return r.value}async function Md(e,n={},t={}){if(!await Z(e.socketPath))return Pl(e.socketPath);let r;try{r=await On({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Td(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(s){throw new Ie(e.socketPath,s)}if(!r.ok)throw new Error(r.error);if(!Xr(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await Nk(e.socketPath,n.settleTimeoutMs??5e3)?o:{...o,stopped:!1,detail:`${o.detail}; the daemon accepted the stop and is still answering on ${JSON.stringify(e.socketPath)}`}}async function Nk(e,n){let t=Date.now()+n;for(;;){if(!await Z(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function Wd(e,n={}){let t=await Cd(e,{op:"host-state"},n);if(!ba(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Hd(e,n=void 0,t={}){let r=await Cd(e,{op:"statusline-string",...t.sessionProject!=null?{session_project:t.sessionProject}:{},...n==null?{}:{render:Ck(n)}},t);if(!ka(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function Ck(e){return{mode:e.mode,project:e.project,max_workers:e.maxWorkers,max_projects:e.maxProjects,max_width:e.maxWidth,verbose:e.verbose}}async function Id(e,n,t){let r=Date.now()+(n.readyTimeoutMs??Nd);for(;;){if(await Z(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=r){let o=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${o}`)}await new Promise(o=>setTimeout(o,25))}}async function Mk(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await dl({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},i=[...r.args,...Oe(e,n.idleMs==null?{}:{idleMs:n.idleMs})],s=Dk(r.command,i,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return s.on("error",a=>{o.failure=a}),s.on("exit",(a,l)=>{o.exit=l?`died on ${l}`:`exited with code ${a??-1}`}),s.unref(),o}pe();import{chmod as Jd,mkdir as Qd,readFile as zd,stat as Qk,writeFile as zk}from"node:fs/promises";import{homedir as Vo}from"node:os";import{dirname as Yk,join as Ko}from"node:path";import{join as Wk}from"node:path";var Fd=["local","tmp","host"],Hk="local",Nn="plugins.dev.workspace.target";var Uo=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function Bd(e){let n=Ge(e,Nn),t=Bk(n??"").trim();return t===""?void 0:t}function Vd(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:Hk};let t=Fd.find(r=>r===n.toLowerCase());if(t)return{kind:"preset",preset:t};if(n.startsWith("/")||n==="~"||n.startsWith("~/"))return{kind:"custom",parentDir:n};throw new Uo(`${Nn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${Fd.join(", ")}) or an absolute parent directory for Workers.`)}function Kd(e,n){return e.kind==="preset"?e.preset==="host":Uk(Fk(e.parentDir,n),De(n))}function Fk(e,n){return e==="~"?Ud(n):e.startsWith("~/")?Wk(n,e.slice(2)):Ud(e)}function Uk(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Ud(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function Bk(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}pe();import{createHash as Vk}from"node:crypto";import{hostname as Kk}from"node:os";import{join as Nt}from"node:path";var tn="redskilled.sock",qk="REDSKILLED_SESSION";function Jk(e={}){let n=e.env??process.env,t=n[qk]?.trim();if(t)return t;let r=n.XDG_RUNTIME_DIR?.trim();return r||`uid:${e.uid??(typeof process.getuid=="function"?process.getuid():"nouid")}`}function Gk(e={}){return qd(e.host??Kk())}function me(e={}){let n=Jk(e),t=e.runtimeDir??pt({key:`redskilled:${n}`,socketFileName:tn,env:e.env,uid:e.uid}),r=Gk(e);return{sessionKey:n,sessionKeyHash:qd(n),machineIdHash:r,runtimeDir:t,socketPath:Nt(t,tn),lockPath:Nt(t,"redskilled.spawn.lock"),leasePath:Nt(t,"redskilled.lease.toon"),eventLanePath:Nt(t,kl),machineClaimPath:e.machineClaimPath??bt({env:e.env,machineIdHash:r,platform:e.platform})}}function qd(e){return Vk("sha256").update(e).digest("hex").slice(0,12)}var Bo=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${_e("red-skills-redskilled",["provision"])}\` directly`;async function Yd(e=Vo()){let n=De(e),t=await Jo(n);return t===void 0?(await Qd(n,{recursive:!0,mode:se}),await Jd(n,se),{path:n,created:!0,tightened:!1,mode:se}):t===se?{path:n,created:!1,tightened:!1,mode:t}:(await Jd(n,se),{path:n,created:!1,tightened:!0,mode:se})}var Xd={needed:!1,declaredBy:`no ${Nn} in view`};async function qo(e={}){let n=e.homeDir??Vo(),t=e.declaredTarget?.trim();if(t)return Gd(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return Xd;let o=Ko(r,".red","config.yaml"),i=await zd(o,"utf8").catch(()=>{});if(i===void 0)return{needed:!1,declaredBy:`no ${o}`};let s=Bd(i);return s===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Gd(s,n,o)}function Gd(e,n,t){let r=`${Nn}: ${e} (${t})`;try{return{needed:Kd(Vd(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function Zd(e){let n=[Xk(e),Zk(e),eR(e),nR(e)],t=n.filter(o=>o.verdict!=="ok");return{verdict:t.some(o=>o.verdict==="missing")?"missing":t.length>0?"degraded":"ok",rows:n,findings:t}}function Xk(e){let n=e.homeNeed??Xd;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:Bo}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??se;return t!==se?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${se.toString(8)}`,fix:`${Bo} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function Zk(e){return ae(e.entry)?{check:"daemon-entry",verdict:"ok",evidence:`${e.entry.entry??e.entry.command} (resolved as ${e.entry.source})`,fix:""}:{check:"daemon-entry",verdict:"missing",evidence:`no published redskilled bundle; probed ${e.entry.searched.join(", ")||"nothing"}`,fix:`install or warm the RedSkills bundle for this host, then re-run \`${_e("red-skills-redskilled",["provision"])}\``}}function eR(e){return e.reachable?{check:"reach",verdict:"ok",evidence:`daemon answered on ${e.socketPath}`,fix:""}:{check:"reach",verdict:"missing",evidence:`no daemon answered on ${e.socketPath}`,fix:`${Bo} \u2014 it starts the daemon and waits for the socket`}}function nR(e){return{check:"supervisor-unit",verdict:"ok",evidence:e.supervisorUnit==="installed"?"redskilled.service is installed (optional supervision, Restart=on-failure)":e.supervisorUnit==="unsupported"?"optional: this host has no systemd --user session; auto-spawn is the only start path":"optional: not installed; auto-spawn already starts the daemon on first use",fix:""}}async function ec(e={}){let n=e.env??process.env,t=e.homeDir??Vo(),r=e.paths??me({env:n}),o=De(t),[i,s,a]=await Promise.all([Jo(o),Z(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):qo({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:i!==void 0,homeMode:i,homeNeed:a,entry:Re(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:s,supervisorUnit:await rR(oR(e,n,t),n)}}var tR="redskilled.service";function nc(e){return Ko(e,"systemd","user",tR)}function tc(e){let n=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${n}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
78
+ `)}async function rc(e){let n=nc(e.configHome);return await Jo(n)!==void 0?{path:n,status:"already-present"}:(await Qd(Yk(n),{recursive:!0}),await zk(n,e.unit,"utf8"),{path:n,status:"installed"})}async function rR(e,n){if(process.platform!=="linux")return"unsupported";try{return await zd(nc(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function oR(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??Ko(t,".config")}async function Jo(e){try{return(await Qk(e)).mode&511}catch{return}}import{readdir as ic,rm as iR,stat as sR}from"node:fs/promises";import{dirname as lR,join as Go}from"node:path";var aR=5*6e4,dR="redskilled.";function cR(e={}){let n=e.env??process.env,t=s=>lR(pt({key:"redskilled:reclaim-probe",socketFileName:tn,env:s,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=n,i=[t(n),t(o)];return[...new Set(i)]}async function sc(e={}){let n=e.roots??cR(e),t=e.graceMs??aR,r=e.now??Date.now,o=e.isPidAlive??U,i=e.answers??mR,s=e.dryRun===!0,a=[];for(let l of n){let d;try{d=(await ic(l,{withFileTypes:!0})).filter(p=>p.isDirectory()).map(p=>p.name)}catch{continue}for(let p of d.sort())a.push(await uR(Go(l,p),{graceMs:t,now:r,pidAlive:o,answers:i,dryRun:s}))}return{roots:n,scanned:a.length,reclaimed:a.filter(l=>l.verdict==="reclaimed").length,dryRun:s,entries:a}}async function uR(e,n){let t;try{t=(await ic(e)).sort()}catch(s){return{dir:e,verdict:"failed",reason:lc(s),removed:[]}}let r=t.filter(s=>s.startsWith(dR));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await pR(Go(e,"redskilled.lease.toon"));if(o!==void 0)return await n.pidAlive(o.pid)?{dir:e,verdict:"live",reason:`lease pid ${o.pid} is alive`,removed:[]}:await oc(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(tn)&&await n.answers(Go(e,tn)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let i=await fR(e,n.now);return i!==void 0&&i<n.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(i/1e3)}s ago`,removed:[]}:await oc(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function oc(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await iR(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:lc(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function pR(e){try{return await In(e)}catch{return}}async function fR(e,n){try{return Math.max(0,n()-(await sR(e)).mtimeMs)}catch{return}}async function mR(e){try{return(await On({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function lc(e){return e instanceof Error?e.message:String(e)}var hR="plugins.dev.statusline",gR="dev.statusline";function yR(e){let n=[],t=a=>{for(let l of[hR,gR]){let d=`${l}.${a}`,p=Ge(e,d)?.trim();if(p!=null&&p!=="")return{key:d,value:p}}},r=t("mode"),o={};r!=null&&(r.value==="local"||r.value==="global"?o.mode=r.value:n.push({...r,reason:"expected `local` or `global`"}));let i=[{leaf:"max_workers",assign:a=>{o.maxWorkers=a}},{leaf:"max_projects",assign:a=>{o.maxProjects=a}},{leaf:"max_width",assign:a=>{o.maxWidth=a}}];for(let a of i){let l=t(a.leaf);if(l==null)continue;let d=Number(l.value);Number.isInteger(d)&&d>=0?a.assign(d):n.push({...l,reason:"expected a whole number of zero or more"})}let s=t("verbose");return s!=null&&(s.value==="true"||s.value==="false"?o.verbose=s.value==="true":n.push({...s,reason:"expected `true` or `false`"})),{config:o,warnings:n}}var kR={mode:{kind:"value",coerce:e=>e},verbose:{kind:"boolean"},project:{kind:"value",coerce:e=>e},"max-workers":{kind:"value",coerce:e=>e},"max-projects":{kind:"value",coerce:e=>e},"max-width":{kind:"value",coerce:e=>e}};function ac(e){let{values:n,positionals:t}=Pe(e,kR),r=[],o={},i=n.mode??t.find(a=>a==="global"||a==="local");i!=null&&(i==="local"||i==="global"?o.mode=i:r.push({key:"--mode",value:i,reason:"expected `local` or `global`"})),n.project!=null&&(o.project=n.project),n.verbose!==void 0&&(o.verbose=n.verbose===!0);let s=[{flag:"max-workers",assign:a=>{o.maxWorkers=a}},{flag:"max-projects",assign:a=>{o.maxProjects=a}},{flag:"max-width",assign:a=>{o.maxWidth=a}}];for(let a of s){let l=n[a.flag];if(l==null)continue;let d=Number(l);Number.isInteger(d)&&d>=0?a.assign(d):r.push({key:`--${a.flag}`,value:l,reason:"expected a whole number of zero or more"})}return{flags:o,warnings:r}}function dc(e={}){let n=e.configText==null?{config:{},warnings:[]}:yR(e.configText),t=e.flags??{};return{options:{...$,mode:t.mode??n.config.mode??$.mode,project:t.project!==void 0?t.project:e.project??$.project,maxWorkers:t.maxWorkers??n.config.maxWorkers??$.maxWorkers,maxProjects:t.maxProjects??n.config.maxProjects??$.maxProjects,maxWidth:t.maxWidth??n.config.maxWidth??$.maxWidth,verbose:t.verbose??n.config.verbose??$.verbose},warnings:n.warnings}}var bR=`Usage: redskilled <command> [options]
70
79
 
71
80
  Commands:
72
81
  host-state (default) print the host's state as JSON
@@ -78,7 +87,7 @@ Commands:
78
87
 
79
88
  Run \`redskilled <command> --help\` for a command's own usage.
80
89
  \`--version\` (\`-v\`) prints the build stamp; both answer offline.
81
- `,ry={serve:`Usage: redskilled serve [options]
90
+ `,_R={serve:`Usage: redskilled serve [options]
82
91
 
83
92
  Runs the daemon in this process. Every path is a flag and none is derived
84
93
  (ADR 0130 rule 3); what is absent falls back to the session derivation.
@@ -142,19 +151,19 @@ Reports every session runtime dir it looked at and why it kept or removed it.
142
151
 
143
152
  --dry-run the same report with nothing removed
144
153
  --grace-ms <n> how long a dir must be idle before it is reclaimed
145
- `};function oy(e){return e==="--help"||e==="-h"||e==="help"}var sy={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)}},Ja="REDSKILLED_HOST_TOKEN";function ao(){try{let n=ny("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function iy(e=process.env,n=ao){let t=(e[Ja]??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 ly(e,n=process.env,t=ao){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...Ba(e,n,t),armTransport:()=>Ba(e,n,t)}}function Ba(e,n=process.env,t=ao){let r=iy(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${Ja}, GITHUB_TOKEN and GH_TOKEN are all unset in the daemon's environment and \`gh auth token\` returned nothing \u2014 so no queue depth is asked for, and no depth is invented either`};let o=e["queue-endpoint"]??n.GITHUB_GRAPHQL_URL;return{transport:Ki({token:r.token,...o?{endpoint:o}:{}})}}async function ay(e){if(e[0]==="--version"||e[0]==="-v"){let o=Ct("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
146
- `:`${is(o)}
147
- `),0}if(oy(e[0]))return process.stdout.write(ty),0;let{command:n,args:t}=cs(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(ry[n]),0;if(n==="serve"){let{values:o}=ke(t,sy),s=ly(o),i=Ka(be(lo()),"state"),l=Os({stateRoot:i});process.stderr.write(`${$s(l)}
148
- `);let a=xs({lanePath:rn(i),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),c=await fa({paths:Ry(o),idleMs:o["idle-ms"]??Zr,daemonVersion:o["daemon-version"]??Ct("redskilled").version,deaths:l.attributions,queueDiscovery:s,...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let u of["SIGTERM","SIGINT"])process.once(u,()=>void c.stop({reason:"signal",signal:u}).catch(()=>{}));return await c.closed,a.phase("closed"),0}if(n==="stop")return await cy(t);if(n==="statusline")return await py(t);if(n==="unit")return await uy(t);if(n==="provision")return await fy(t);if(n==="reclaim")return await hy(t);let r=await Ra(ie());return process.stdout.write(`${JSON.stringify(r,null,2)}
149
- `),0}var dy={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function cy(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=ke(e,dy),o=await ka(n.paths??ie(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${I({running:o.running,stopped:o.stopped,reason:o.reason,socket:o.socket_path,daemon_version:o.daemon_version,pid:o.pid,holding:{workers:o.holding.workers.length,projects:[...o.holding.projects]},surviving:[...o.surviving],workers:o.holding.workers.map(s=>({worker_id:s.worker_id,project_label:s.project_label,pid:s.pid,unit:s.unit,isolated:s.isolated,survives:s.survives})),detail:o.detail})}
150
- `),o.running&&!o.stopped?1:0}async function uy(e,n={}){let t=n.write??(s=>process.stdout.write(s)),r=n.paths??ie(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(Hl(n.unitIO??{}),null,2)}
151
- `),0;if(o==="install"){let s=await Fl(Ml(r),n.unitIO??{});return t(`${JSON.stringify(s,null,2)}
152
- `),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await Ul(n.unitIO??{}),null,2)}
153
- `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function py(e,n={}){let t=n.write??(a=>process.stdout.write(a)),r=n.warn??(a=>process.stderr.write(a)),o=Ha(e),s=ky(n.cwd??process.cwd()),i=Va({...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 ba(n.paths??ie(),i.options,{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(a){r(`redskilled statusline: ${a instanceof Error?a.message:String(a)}
155
- `),l=Qi({options:i.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${l.lines.join(`
154
+ `};function wR(e){return e==="--help"||e==="-h"||e==="help"}var xR={socket:{kind:"value",coerce:e=>e},lease:{kind:"value",coerce:e=>e},events:{kind:"value",coerce:e=>e},"session-key-hash":{kind:"value",coerce:e=>e},"machine-id-hash":{kind:"value",coerce:e=>e},"machine-claim":{kind:"value",coerce:e=>e},"idle-ms":{kind:"value",coerce:e=>Number(e)},"daemon-version":{kind:"value",coerce:e=>e},"queue-endpoint":{kind:"value",coerce:e=>e},"queue-ms":{kind:"value",coerce:e=>Number(e)},"demand-ms":{kind:"value",coerce:e=>Number(e)}},pc="REDSKILLED_HOST_TOKEN";function zo(){try{let n=RR("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function SR(e=process.env,n=zo){let t=(e[pc]??e.GITHUB_TOKEN??e.GH_TOKEN??"").trim();if(t!=="")return{token:t,source:"env"};let r=(n()??"").trim();return r!==""?{token:r,source:"tracker-cli"}:null}function vR(e,n=process.env,t=zo){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...cc(e,n,t),armTransport:()=>cc(e,n,t)}}function cc(e,n=process.env,t=zo){let r=SR(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${pc}, GITHUB_TOKEN and GH_TOKEN are all unset in the daemon's environment and \`gh auth token\` returned nothing \u2014 so no queue depth is asked for, and no depth is invented either`};let o=e["queue-endpoint"]??n.GITHUB_GRAPHQL_URL;return{transport:la({token:r.token,...o?{endpoint:o}:{}})}}async function ER(e){if(e[0]==="--version"||e[0]==="-v"){let o=Rr("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
155
+ `:`${ps(o)}
156
+ `),0}if(wR(e[0]))return process.stdout.write(bR),0;let{command:n,args:t}=gs(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(_R[n]),0;if(n==="serve"){let{values:o}=Pe(t,xR),i=vR(o),s=uc(De(Qo()),"state"),a=Ns({stateRoot:s});process.stderr.write(`${Cs(a)}
157
+ `);let l=As({lanePath:bn(s),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),d=await Ld({paths:CR(o),idleMs:o["idle-ms"]??Co,daemonVersion:o["daemon-version"]??Rr("redskilled").version,deaths:a.attributions,queueDiscovery:i,...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let p of["SIGTERM","SIGINT"])process.once(p,()=>void d.stop({reason:"signal",signal:p}).catch(()=>{}));return await d.closed,l.phase("closed"),0}if(n==="stop")return await jR(t);if(n==="statusline")return await OR(t);if(n==="unit")return await DR(t);if(n==="provision")return await LR(t);if(n==="reclaim")return await IR(t);let r=await Wd(me());return process.stdout.write(`${JSON.stringify(r,null,2)}
158
+ `),0}var PR={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function jR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),{values:r}=Pe(e,PR),o=await Md(n.paths??me(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${M({running:o.running,stopped:o.stopped,reason:o.reason,socket:o.socket_path,daemon_version:o.daemon_version,pid:o.pid,holding:{workers:o.holding.workers.length,projects:[...o.holding.projects]},surviving:[...o.surviving],workers:o.holding.workers.map(i=>({worker_id:i.worker_id,project_label:i.project_label,pid:i.pid,unit:i.unit,isolated:i.isolated,survives:i.survives})),detail:o.detail})}
159
+ `),o.running&&!o.stopped?1:0}async function DR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),r=n.paths??me(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(sd(n.unitIO??{}),null,2)}
160
+ `),0;if(o==="install"){let i=await od(td(r),n.unitIO??{});return t(`${JSON.stringify(i,null,2)}
161
+ `),i.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await id(n.unitIO??{}),null,2)}
162
+ `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function OR(e,n={}){let t=n.write??(l=>process.stdout.write(l)),r=n.warn??(l=>process.stderr.write(l)),o=ac(e),i=NR(n.cwd??process.cwd()),s=dc({...i.configText==null?{}:{configText:i.configText},project:i.label,flags:o.flags});for(let l of[...s.warnings,...o.warnings])r(`redskilled statusline: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
163
+ `);let a;try{a=await Hd(n.paths??me(),s.options,{...n.client??{},...s.options.project==null?{}:{sessionProject:s.options.project}})}catch(l){r(`redskilled statusline: ${l instanceof Error?l.message:String(l)}
164
+ `),a=pa({options:s.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${a.lines.join(`
156
165
  `)}
157
- `),0}var my={"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 fy(e,n={}){let t=n.write??(m=>process.stdout.write(m)),{values:r}=ke(e,my),o=n.paths??ie(),s=n.homeDir??lo(),i=await oo({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),l=r.check||!i.needed?void 0:await $a(s),a;if(!r.check&&!r["no-start"])try{await Xr(o,n.client??{})}catch(m){a=m instanceof Error?m.message:String(m)}let c=await Ia({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 Wa({configHome:n.configHome??yy(),unit:Na({command:[c.entry.command,...c.entry.args].join(" "),socketPath:o.socketPath})}):void 0,p=Aa(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(m=>({check:m.check,verdict:m.verdict,evidence:m.evidence})),fixes:p.findings.map(m=>({check:m.check,fix:m.fix}))})}
158
- `),p.verdict==="ok"?0:1}var gy={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function hy(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=ke(e,gy),o=await Fa({...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 yy(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:Ka(lo(),".config")}function ky(e){let n=or(e);return n.configText==null?{label:null}:{configText:n.configText,label:Cs(e)}}function Ry(e){let n=ie();return{...n,socketPath:e.socket??n.socketPath,leasePath:e.lease??n.leasePath,eventLanePath:e.events??n.eventLanePath,sessionKeyHash:e["session-key-hash"]??n.sessionKeyHash,machineIdHash:e["machine-id-hash"]??n.machineIdHash,machineClaimPath:e["machine-claim"]??n.machineClaimPath}}var by=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;by&&ay(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{Ja as REDSKILLED_HOST_TOKEN_ENV,ty as REDSKILLED_USAGE,Ba as armRedskilledQueueTransport,iy as resolveRedskilledHostToken,ly as resolveServeQueueDiscovery,fy as runProvision,hy as runReclaim,ay as runRedskilledCli,py as runStatusline,cy as runStop,uy as runUnit};
166
+ `),0}var AR={"no-start":{kind:"boolean"},"install-unit":{kind:"boolean"},check:{kind:"boolean"},project:{kind:"value",coerce:e=>e},workspace:{kind:"value",coerce:e=>e}};async function LR(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=Pe(e,AR),o=n.paths??me(),i=n.homeDir??Qo(),s=await qo({homeDir:i,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),a=r.check||!s.needed?void 0:await Yd(i),l;if(!r.check&&!r["no-start"])try{await Fo(o,n.client??{})}catch(f){l=f instanceof Error?f.message:String(f)}let d=await ec({paths:o,homeNeed:s,...n.homeDir==null?{}:{homeDir:n.homeDir},...n.configHome==null?{}:{configHome:n.configHome},...n.client?.serverCommand==null?{}:{entryOverride:{serverCommand:n.client.serverCommand,serverArgs:n.client.serverArgs}}}),p=r["install-unit"]&&ae(d.entry)?await rc({configHome:n.configHome??TR(),unit:tc({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=Zd(d);return t(`${M({verdict:u.verdict,home:{path:a?.path??d.homePath,created:a?.created??!1,tightened:a?.tightened??!1,needed:s.needed,needed_by:s.declaredBy},socket:d.socketPath,...l==null?{}:{start_error:l},...p==null?{}:{unit:{path:p.path,status:p.status}},checks:u.rows.map(f=>({check:f.check,verdict:f.verdict,evidence:f.evidence})),fixes:u.findings.map(f=>({check:f.check,fix:f.fix}))})}
167
+ `),u.verdict==="ok"?0:1}var $R={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function IR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),{values:r}=Pe(e,$R),o=await sc({...n.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return t(`${M({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(i=>({dir:i.dir,verdict:i.verdict,reason:i.reason,removed:[...i.removed]}))})}
168
+ `),o.entries.some(i=>i.verdict==="failed")?1:0}function TR(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:uc(Qo(),".config")}function NR(e){let n=Mr(e);return n.configText==null?{label:null}:{configText:n.configText,label:Ks(e)}}function CR(e){let n=me();return{...n,socketPath:e.socket??n.socketPath,leasePath:e.lease??n.leasePath,eventLanePath:e.events??n.eventLanePath,sessionKeyHash:e["session-key-hash"]??n.sessionKeyHash,machineIdHash:e["machine-id-hash"]??n.machineIdHash,machineClaimPath:e["machine-claim"]??n.machineClaimPath}}var MR=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;MR&&ER(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
169
+ `),process.exitCode=1});export{pc as REDSKILLED_HOST_TOKEN_ENV,bR as REDSKILLED_USAGE,cc as armRedskilledQueueTransport,SR as resolveRedskilledHostToken,vR as resolveServeQueueDiscovery,LR as runProvision,IR as runReclaim,ER as runRedskilledCli,OR as runStatusline,jR as runStop,DR as runUnit};