@reddb-io/red-skills 3.1.2 → 3.2.0

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,30 +1,30 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var Yl=Object.defineProperty;var Zl=(e,t)=>()=>(e&&(t=e(e=0)),t);var Xl=(e,t)=>{for(var n in t)Yl(e,n,{get:t[n],enumerable:!0})};var Bo={};Xl(Bo,{REDSKILLED_BIN_ENV:()=>Dn,REDSKILLED_BUNDLE_ASSET:()=>q,REDSKILLED_ENTRY_UNRESOLVED:()=>ze,RedskilledDaemonEntryError:()=>Qe,isRedskilledEntryPath:()=>$n,isResolvedRedskilledEntry:()=>G,redskilledBundleCacheRoot:()=>bt,redskilledServeArgv:()=>fe,requireRedskilledEntry:()=>_t,resolveRedskilledEntry:()=>ie});import{existsSync as Dd,readdirSync as Ld}from"node:fs";import{homedir as $d}from"node:os";import{basename as On,dirname as Pn,join as W,resolve as wt}from"node:path";function G(e){return"command"in e}function fe(e,t={}){let n=["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 t.idleMs!=null&&n.push("--idle-ms",String(t.idleMs)),t.daemonVersion!=null&&n.push("--daemon-version",t.daemonVersion),n}function bt(e=process.env){return Vo(e)}function ie(e={},t={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let n=t.env??process.env,r=t.exists??Dd,o=t.execPath??process.execPath,s=t.execArgv??[],i=t.callerEntry===void 0?process.argv[1]:t.callerEntry,l=(u,f)=>({command:o,args:[...s,u],source:f,entry:u}),a=n[Dn];if(a)return{command:a,args:[],source:"env-redskilled-bin",entry:a};if(i&&$n(i))return l(wt(i),"caller-entry");let c=[];for(let[u,f]of Nd(i,t.rootDir,n,t.listDir??Cd))if(c.push(u),r(u))return l(u,f);return{diagnostic:ze,searched:c,...i?{callerEntry:wt(i)}:{}}}function _t(e={},t={}){let n=ie(e,t);if(G(n))return n;throw new Qe(n)}function $n(e){let t=On(e);return t===q||Ln.test(t)||t==="red-skills-redskilled"||t==="red-skills-redskilled.mjs"?!0:t!=="cli.js"&&t!=="cli.mjs"&&t!=="cli.ts"?!1:Td(wt(e))}function Td(e){let t=Pn(e);for(let n=0;n<4;n++){if(On(t)==="redskilled")return!0;let r=Pn(t);if(r===t)return!1;t=r}return!1}function*Nd(e,t,n,r){if(e){let s=Pn(wt(e));yield[W(s,q),"caller-sibling-bundle"];let i=Ad.exec(On(e));i&&(yield[W(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[W(s,"..","dist",q),"caller-sibling-bundle"]}for(let s of Id){let i=n[s];i&&(yield[W(i,"dist",q),"plugin-root-bundle"],yield[W(i,"..","..","dist",q),"plugin-root-bundle"])}t&&(yield[W(t,"dist",q),"repo-bundle"],yield[W(t,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[W(t,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=Vo(n);yield[W(o,q),"bundle-cache"];for(let s of Wd(o,r))yield[W(o,s),"bundle-cache"]}function Vo(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let t=e.XDG_CACHE_HOME||W(e.HOME||$d(),".cache");return W(t,"red-skills","bundles")}function Wd(e,t){return t(e).filter(n=>Ln.test(n)).sort((n,r)=>Md(Ho(r),Ho(n)))}function Ho(e){return Ln.exec(e)?.[1]??""}function Md(e,t){let n=s=>s.split(".").map(i=>Number.parseInt(i,10)),[r,o]=[n(e),n(t)];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(t):-1;if(Number.isNaN(l)||l===void 0)return 1;if(i!==l)return i-l}return 0}function Cd(e){try{return Ld(e)}catch{return[]}}var q,ze,Dn,Qe,Ad,Ln,Id,X=Zl(()=>{"use strict";q="redskilled.bundle.min.mjs",ze="redskilled-daemon-entry-unresolved",Dn="REDSKILLED_BIN";Qe=class extends Error{code=ze;searched;callerEntry;constructor(t){super(`${ze}: no published ${q} found to spawn the redskilled daemon from${t.callerEntry?` (caller entry: ${t.callerEntry}, which is NOT used as a fallback)`:""}
3
+ var Yl=Object.defineProperty;var Zl=(e,t)=>()=>(e&&(t=e(e=0)),t);var Xl=(e,t)=>{for(var n in t)Yl(e,n,{get:t[n],enumerable:!0})};var Bo={};Xl(Bo,{REDSKILLED_BIN_ENV:()=>Ln,REDSKILLED_BUNDLE_ASSET:()=>q,REDSKILLED_ENTRY_UNRESOLVED:()=>Qe,RedskilledDaemonEntryError:()=>Ye,isRedskilledEntryPath:()=>$n,isResolvedRedskilledEntry:()=>G,redskilledBundleCacheRoot:()=>_t,redskilledServeArgv:()=>fe,requireRedskilledEntry:()=>vt,resolveRedskilledEntry:()=>ie});import{existsSync as Dd,readdirSync as $d}from"node:fs";import{homedir as Ad}from"node:os";import{basename as On,dirname as Pn,join as W,resolve as bt}from"node:path";function G(e){return"command"in e}function fe(e,t={}){let n=["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 t.idleMs!=null&&n.push("--idle-ms",String(t.idleMs)),t.daemonVersion!=null&&n.push("--daemon-version",t.daemonVersion),n}function _t(e=process.env){return Vo(e)}function ie(e={},t={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let n=t.env??process.env,r=t.exists??Dd,o=t.execPath??process.execPath,s=t.execArgv??[],i=t.callerEntry===void 0?process.argv[1]:t.callerEntry,l=(u,f)=>({command:o,args:[...s,u],source:f,entry:u}),a=n[Ln];if(a)return{command:a,args:[],source:"env-redskilled-bin",entry:a};if(i&&$n(i))return l(bt(i),"caller-entry");let c=[];for(let[u,f]of Wd(i,t.rootDir,n,t.listDir??Ud))if(c.push(u),r(u))return l(u,f);return{diagnostic:Qe,searched:c,...i?{callerEntry:bt(i)}:{}}}function vt(e={},t={}){let n=ie(e,t);if(G(n))return n;throw new Ye(n)}function $n(e){let t=On(e);return t===q||Dn.test(t)||t==="red-skills-redskilled"||t==="red-skills-redskilled.mjs"?!0:t!=="cli.js"&&t!=="cli.mjs"&&t!=="cli.ts"?!1:Nd(bt(e))}function Nd(e){let t=Pn(e);for(let n=0;n<4;n++){if(On(t)==="redskilled")return!0;let r=Pn(t);if(r===t)return!1;t=r}return!1}function*Wd(e,t,n,r){if(e){let s=Pn(bt(e));yield[W(s,q),"caller-sibling-bundle"];let i=Id.exec(On(e));i&&(yield[W(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[W(s,"..","dist",q),"caller-sibling-bundle"]}for(let s of Td){let i=n[s];i&&(yield[W(i,"dist",q),"plugin-root-bundle"],yield[W(i,"..","..","dist",q),"plugin-root-bundle"])}t&&(yield[W(t,"dist",q),"repo-bundle"],yield[W(t,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[W(t,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=Vo(n);yield[W(o,q),"bundle-cache"];for(let s of Md(o,r))yield[W(o,s),"bundle-cache"]}function Vo(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let t=e.XDG_CACHE_HOME||W(e.HOME||Ad(),".cache");return W(t,"red-skills","bundles")}function Md(e,t){return t(e).filter(n=>Dn.test(n)).sort((n,r)=>Cd(Ho(r),Ho(n)))}function Ho(e){return Dn.exec(e)?.[1]??""}function Cd(e,t){let n=s=>s.split(".").map(i=>Number.parseInt(i,10)),[r,o]=[n(e),n(t)];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(t):-1;if(Number.isNaN(l)||l===void 0)return 1;if(i!==l)return i-l}return 0}function Ud(e){try{return $d(e)}catch{return[]}}var q,Qe,Ln,Ye,Id,Dn,Td,X=Zl(()=>{"use strict";q="redskilled.bundle.min.mjs",Qe="redskilled-daemon-entry-unresolved",Ln="REDSKILLED_BIN";Ye=class extends Error{code=Qe;searched;callerEntry;constructor(t){super(`${Qe}: no published ${q} found to spawn the redskilled daemon from${t.callerEntry?` (caller entry: ${t.callerEntry}, which is NOT used as a fallback)`:""}
4
4
  searched:
5
5
  ${t.searched.map(n=>` ${n}`).join(`
6
- `)}`),this.name="RedskilledDaemonEntryError",this.searched=t.searched,t.callerEntry!=null&&(this.callerEntry=t.callerEntry)}};Ad=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Ln=/^redskilled-(.+)\.bundle\.min\.mjs$/,Id=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as gm}from"node:child_process";import{homedir as El}from"node:os";import{join as hm}from"node:path";var Be=class extends Error{constructor(t,n){super(t===0?n:`line ${t}: ${n}`),this.name="ToonError",this.line=t,this.reason=n}},de=class extends Error{constructor(t,n){super(t===0?n:`line ${t}: ${n}`),this.name="ToonlError",this.line=t,this.reason=n}};function k(e,t){return new Be(e,t)}function S(e,t){return new de(e,t)}function be(e){return e instanceof de?e:e instanceof Be?new de(e.line,e.reason):new de(0,String(e&&e.message?e.message:e))}var j=",";function gt(e){let t=e.split(`
6
+ `)}`),this.name="RedskilledDaemonEntryError",this.searched=t.searched,t.callerEntry!=null&&(this.callerEntry=t.callerEntry)}};Id=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Dn=/^redskilled-(.+)\.bundle\.min\.mjs$/,Td=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as hm}from"node:child_process";import{homedir as El}from"node:os";import{join as ym}from"node:path";var Be=class extends Error{constructor(t,n){super(t===0?n:`line ${t}: ${n}`),this.name="ToonError",this.line=t,this.reason=n}},de=class extends Error{constructor(t,n){super(t===0?n:`line ${t}: ${n}`),this.name="ToonlError",this.line=t,this.reason=n}};function k(e,t){return new Be(e,t)}function S(e,t){return new de(e,t)}function be(e){return e instanceof de?e:e instanceof Be?new de(e.line,e.reason):new de(0,String(e&&e.message?e.message:e))}var j=",";function ht(e){let t=e.split(`
7
7
  `);return t.length>0&&t[t.length-1]===""&&t.pop(),t.map(n=>n.endsWith("\r")?n.slice(0,-1):n)}function V(e){return k(e,"invalid quoted string")}function B(e,t){if(e==="")return"";if(e.startsWith('"'))return Yr(e,t);if(e.includes('"'))throw V(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:ea(e)?Number(e):e}function Z(e,t){let n=e.trim();if(n.startsWith('"'))return[Yr(n,t),!0];if(n.includes('"')||/\s/.test(n))throw k(t,"expected non-empty field name");return[n,!1]}function Yr(e,t){if(e[0]!=='"')throw V(t);let n="",r=1;for(;r<e.length;){let o=e[r];if(r+=1,o==='"'){if(e.slice(r).trim()==="")return n;throw V(t)}if(o==="\\"){let s=e[r];switch(r+=1,s){case'"':n+='"';break;case"\\":n+="\\";break;case"n":n+=`
8
8
  `;break;case"r":n+="\r";break;case"t":n+=" ";break;case"u":{let i=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(i))throw V(t);let l=Number.parseInt(i,16);if(l>=55296&&l<=57343)throw V(t);n+=String.fromCharCode(l),r+=4;break}default:throw V(t)}continue}if(o<" "&&o!==" ")throw V(t);n+=o}throw V(t)}function ce(e,t,n){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===t&&!s&&(r.push(e.slice(o,l).trim()),o=l+1)}if(s||i)throw V(n);return r.push(e.slice(o).trim()),r}function T(e,t,n){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===t&&!r)return s}if(r||o)throw V(n);return-1}function ea(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function ta(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function na(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw k(0,"number is not representable in TOON");return String(e)}function Je(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function J(e,t){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return na(e);if(typeof e=="string")return oa(e,t);throw k(0,"not a primitive")}function ra(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function C(e){return ra(e)?e:Zr(e)}function oa(e,t){return sa(e,t)?Zr(e):e}function sa(e,t){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||ta(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")}function Zr(e){let t='"';for(let n of e)switch(n){case'"':t+='\\"';break;case"\\":t+="\\\\";break;case`
9
- `:t+="\\n";break;case"\r":t+="\\r";break;case" ":t+="\\t";break;default:n<" "?t+=`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`:t+=n}return`${t}"`}function _e(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}var sn=2;function ia(e={}){return{indent:Math.max(1,e.indent??sn),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function la(e,t){let n=[],r=!1;return gt(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 k(i,"invalid indentation");if(t.strict&&l%t.indent!==0)throw k(i,"invalid indentation");n.push({number:i,depth:Math.floor(l/t.indent),content:o.slice(l),blankBefore:r}),r=!1}),n}function K(e,t){let n=ia(t),r=la(e,n),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw k(o.number,"invalid indentation");let s=r.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){let c;try{c=dn(o.content,T(o.content,":",o.number))}catch(u){if(n.strict)throw rn(u,o.number);c=void 0}if(c!==void 0)return ca(c,r,n)}if(s&&T(o.content,":",o.number)===-1)return B(o.content.trim(),o.number);let i={index:0},l=ln(r,i,0,n),a=r[i.index];if(a!==void 0)throw k(a.number,"expected end of document");return l}function ln(e,t,n,r){let o={};for(;t.index<e.length;){let s=e[t.index];if(s.depth<n)break;if(s.depth>n)throw k(s.number,"invalid indentation");let{key:i,quoted:l,value:a}=aa(e,t,n,r);to(o,i,l,a,r,s.number)}return o}function aa(e,t,n,r){let o=e[t.index],s=o.content,i=T(s,":",o.number);if(i===-1)throw k(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=ma(l)}catch(b){if(r.strict)throw rn(b,o.number);t.index+=1;let _=Xt(e,t,n,a,o.number,r);return{key:l.trim(),quoted:!1,value:_}}if(a.trim()!=="")throw k(o.number,"expected keyed map rows");let w=da(y,e,t,n+1,r);return{key:y.key,quoted:y.keyQuoted,value:w}}if(c!==-1){let y;try{y=dn(l,i)}catch(b){if(r.strict)throw rn(b,o.number);t.index+=1;let _=Xt(e,t,n,a,o.number,r);return{key:l.trim(),quoted:!1,value:_}}if(y.key===""&&!y.keyQuoted)throw k(o.number,"expected non-empty field name");let w=an(y,a,e,t,n,r);return{key:y.key,quoted:y.keyQuoted,value:w}}let[f,p]=Z(l,o.number);if(f===""&&!p)throw k(o.number,"expected non-empty field name");t.index+=1;let h=Xt(e,t,n,a,o.number,r);return{key:f,quoted:p,value:h}}function Xt(e,t,n,r,o,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return B(i,o);let l=e[t.index];return l!==void 0&&l.depth>n?ln(e,t,n+1,s):{}}function da(e,t,n,r,o){let s={};for(n.index+=1;n.index<t.length;){let i=t[n.index];if(i.depth<r)break;if(i.depth>r)throw k(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw k(i.number,"blank line inside keyed map");let l=T(i.content,":",i.number);if(l===-1)throw k(i.number,"expected `key: value`");let[a,c]=Z(i.content.slice(0,l),i.number);if(a===""&&!c)throw k(i.number,"expected non-empty field name");let u=ce(i.content.slice(l+1).trim(),e.delimiter,i.number);if(u.length!==e.fields.length)throw k(i.number,"keyed map row length mismatch");let f={};e.fields.forEach((p,h)=>{Ke(f,p,B(u[h],i.number),o,i.number)}),to(s,a,c,f,o,i.number),n.index+=1}return s}function ca(e,t,n){let r=t[0],o=T(r.content,":",r.number);if(o===-1)throw k(r.number,"expected `key: value`");let s=r.content.slice(o+1),i={index:0},l=an(e,s,t,i,0,n),a=t[i.index];if(a!==void 0)throw k(a.number,"expected end of document");return l}function an(e,t,n,r,o,s){let i=n[r.index].number,l=t.trim();if(r.index+=1,e.fields!==void 0){if(l!=="")throw k(i,"expected tabular rows");return ua(e,e.fields,n,r,o+1,s)}if(l!==""){let a=ce(l,e.delimiter,i).map(c=>B(c,i));if(a.length!==e.len)throw k(i,"array length mismatch");return a}return pa(e,n,r,o+1,s)}function ua(e,t,n,r,o,s){let i=[];for(;i.length<e.len;){let a=n[r.index];if(a===void 0)throw tn(n,r.index);if(a.depth<o)break;if(a.depth>o)throw k(a.number,"invalid indentation");if(a.blankBefore&&s.strict)throw k(a.number,"blank line inside array");if(!Xr(a.content,e.delimiter,a.number))break;let c=ce(a.content,e.delimiter,a.number);if(c.length!==t.length)throw k(a.number,"array row length mismatch");let u={};t.forEach((f,p)=>{Ke(u,f,B(c[p],a.number),s,a.number)}),i.push(u),r.index+=1}if(i.length!==e.len)throw tn(n,r.index);let l=n[r.index];if(l!==void 0&&l.depth>=o&&Xr(l.content,e.delimiter,l.number))throw k(l.number,"array length mismatch");return i}function Xr(e,t,n){let r=T(e,":",n);if(r===-1)return!0;let o=T(e,t,n);return o===-1?!1:o<r}function pa(e,t,n,r,o){let s=[];for(;s.length<e.len;){let l=t[n.index];if(l===void 0||l.depth<r)throw tn(t,n.index);if(l.depth>r)throw k(l.number,"invalid indentation");if(l.blankBefore&&o.strict)throw k(l.number,"blank line inside array");s.push(fa(t,n,r,o))}let i=t[n.index];if(i!==void 0&&i.depth>=r)throw k(i.number,"array length mismatch");return s}function fa(e,t,n,r){let o=e[t.index];if(!o.content.startsWith("-"))throw k(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return t.index+=1,{};if(s.startsWith("[")){let i=T(s,":",o.number),l;try{l=dn(s,i)}catch{l=void 0}if(l!==void 0){let a=s.slice(i+1);return an(l,a,e,t,n,r)}}if(T(s,":",o.number)!==-1){let i=[{number:o.number,depth:n+1,content:s,blankBefore:!1}];for(t.index+=1;t.index<e.length;){let l=e[t.index];if(l.depth<=n)break;i.push(l),t.index+=1}return ln(i,{index:0},n+1,r)}return t.index+=1,B(s,o.number)}function tn(e,t){let n=e[t]??e[e.length-1];return k(n===void 0?1:n.number,"array length mismatch")}function dn(e,t){if(t===-1)throw k(0,"array header missing colon");let n=e.slice(0,t),r=T(n,"[",0);if(r===-1)throw k(0,"invalid array header");let o,s;try{[o,s]=Z(n.slice(0,r),0)}catch{throw k(0,"invalid array header")}let i=n.slice(r+1),l=i.indexOf("]");if(l===-1)throw k(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 k(0,"invalid array header");let u=Number.parseInt(c,10),f;switch(a.slice(c.length)){case"":f=",";break;case" ":f=" ";break;case"|":f="|";break;default:throw k(0,"invalid array header")}let p=i.slice(l+1),h;if(p==="")h=void 0;else if(p.startsWith("{")&&p.endsWith("}")&&p.length>=2)try{h=eo(p.slice(1,-1),f)}catch(y){throw k(0,y.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw k(0,"invalid array header");return{key:o,keyQuoted:s,len:u,delimiter:f,fields:h}}function ma(e){let t=T(e,"{",0);if(t===-1||!e.endsWith("}"))throw k(0,"invalid keyed map header");let n,r;try{[n,r]=Z(e.slice(0,t),0)}catch{throw k(0,"invalid keyed map header")}if(n===""&&!r)throw k(0,"expected non-empty field name");let o;try{o=eo(e.slice(t+1,-1),j)}catch(s){throw k(0,s.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:n,keyQuoted:r,delimiter:j,fields:o}}function eo(e,t){let n=[],r=0;function o(l,a){let c=0;for(;r<e.length&&!(a&&e[r]==="}");){if(e[r]===t||e[r]==="}")throw k(0,"invalid array header");let u=r;for(;r<e.length;){let p=e[r];if(p==='"'){s();continue}if(p===t||p==="{"||p==="}")break;r+=1}let[f]=Z(e.slice(u,r),0);if(f==="")throw k(0,"invalid array header");if(c+=1,e[r]==="{"){r+=1;let p=n.length;if(o([...l,f],!0),e[r]!=="}"||n.length===p)throw k(0,"invalid array header");r+=1}else n.push([...l,f]);if(e[r]===t){if(r+=1,r>=e.length||e[r]==="}")throw k(0,"invalid array header");continue}if(a?e[r]==="}":r===e.length)break;throw k(0,"invalid array header")}if(c===0)throw k(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 k(0,"invalid array header");let i=new Set;for(let l=0;l<n.length;l+=1)for(let a=l+1;a<n.length;a+=1)if(ga(n[l],n[a])||nn(n[l],n[a])||nn(n[a],n[l]))throw k(0,"duplicate key");for(let l of n){let a=l.join("\0");if(i.has(a))throw k(0,"duplicate key");i.add(a)}return n}function ga(e,t){return e.length===t.length&&nn(e,t)}function nn(e,t){return t.every((n,r)=>e[r]===n)}function rn(e,t){return k(t,e.reason??String(e.message))}function to(e,t,n,r,o,s){if(o.expandPaths&&!n&&t.includes(".")){let i=t.split(".");if(i.every(ha)){Ke(e,i,r,o,s);return}}Ke(e,[t],r,o,s)}function Ke(e,t,n,r,o){let s=t[0],i=Object.prototype.hasOwnProperty.call(e,s);if(t.length===1){if(i&&r.strict)throw k(o,"duplicate key");_e(e,s,n);return}if(i&&!ve(e[s])){if(r.strict)throw k(o,"path expansion conflict");_e(e,s,{})}else i||_e(e,s,{});Ke(e[s],t.slice(1),n,r,o)}function ha(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function I(e,t={}){let n={nestedTabularHeaders:t.nestedTabularHeaders===!0,keyedMapCollapse:t.keyedMapCollapse===!0},r=[];return Array.isArray(e)?cn(r,void 0,e,0,!1,n):ve(e)?no(r,e,0,n):r.push(J(e,j)),r.join("")}function qe(e,t){e.push(" ".repeat(t*sn))}function no(e,t,n,r){for(let[o,s]of Object.entries(t))qe(e,n),on(e,o,s,n,r)}function on(e,t,n,r,o){if(Array.isArray(n)){cn(e,t,n,r,!1,o);return}if(ve(n)){let s=o.keyedMapCollapse?ka(n,o):void 0;if(s!==void 0){e.push(C(t),"{",s.fields.map(un).join(j),`}:
9
+ `:t+="\\n";break;case"\r":t+="\\r";break;case" ":t+="\\t";break;default:n<" "?t+=`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`:t+=n}return`${t}"`}function _e(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}var ln=2;function ia(e={}){return{indent:Math.max(1,e.indent??ln),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function la(e,t){let n=[],r=!1;return ht(e).forEach((o,s)=>{let i=s+1;if(o.trim()===""){r=!0;return}let l=o.length-o.replace(/^ +/,"").length;if(o[l]===" ")throw k(i,"invalid indentation");if(t.strict&&l%t.indent!==0)throw k(i,"invalid indentation");n.push({number:i,depth:Math.floor(l/t.indent),content:o.slice(l),blankBefore:r}),r=!1}),n}function K(e,t){let n=ia(t),r=la(e,n),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw k(o.number,"invalid indentation");let s=r.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){let c;try{c=cn(o.content,T(o.content,":",o.number))}catch(u){if(n.strict)throw on(u,o.number);c=void 0}if(c!==void 0)return ca(c,r,n)}if(s&&T(o.content,":",o.number)===-1)return B(o.content.trim(),o.number);let i={index:0},l=an(r,i,0,n),a=r[i.index];if(a!==void 0)throw k(a.number,"expected end of document");return l}function an(e,t,n,r){let o={};for(;t.index<e.length;){let s=e[t.index];if(s.depth<n)break;if(s.depth>n)throw k(s.number,"invalid indentation");let{key:i,quoted:l,value:a}=aa(e,t,n,r);to(o,i,l,a,r,s.number)}return o}function aa(e,t,n,r){let o=e[t.index],s=o.content,i=T(s,":",o.number);if(i===-1)throw k(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=ma(l)}catch(b){if(r.strict)throw on(b,o.number);t.index+=1;let _=en(e,t,n,a,o.number,r);return{key:l.trim(),quoted:!1,value:_}}if(a.trim()!=="")throw k(o.number,"expected keyed map rows");let w=da(y,e,t,n+1,r);return{key:y.key,quoted:y.keyQuoted,value:w}}if(c!==-1){let y;try{y=cn(l,i)}catch(b){if(r.strict)throw on(b,o.number);t.index+=1;let _=en(e,t,n,a,o.number,r);return{key:l.trim(),quoted:!1,value:_}}if(y.key===""&&!y.keyQuoted)throw k(o.number,"expected non-empty field name");let w=dn(y,a,e,t,n,r);return{key:y.key,quoted:y.keyQuoted,value:w}}let[f,p]=Z(l,o.number);if(f===""&&!p)throw k(o.number,"expected non-empty field name");t.index+=1;let h=en(e,t,n,a,o.number,r);return{key:f,quoted:p,value:h}}function en(e,t,n,r,o,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return B(i,o);let l=e[t.index];return l!==void 0&&l.depth>n?an(e,t,n+1,s):{}}function da(e,t,n,r,o){let s={};for(n.index+=1;n.index<t.length;){let i=t[n.index];if(i.depth<r)break;if(i.depth>r)throw k(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw k(i.number,"blank line inside keyed map");let l=T(i.content,":",i.number);if(l===-1)throw k(i.number,"expected `key: value`");let[a,c]=Z(i.content.slice(0,l),i.number);if(a===""&&!c)throw k(i.number,"expected non-empty field name");let u=ce(i.content.slice(l+1).trim(),e.delimiter,i.number);if(u.length!==e.fields.length)throw k(i.number,"keyed map row length mismatch");let f={};e.fields.forEach((p,h)=>{Ke(f,p,B(u[h],i.number),o,i.number)}),to(s,a,c,f,o,i.number),n.index+=1}return s}function ca(e,t,n){let r=t[0],o=T(r.content,":",r.number);if(o===-1)throw k(r.number,"expected `key: value`");let s=r.content.slice(o+1),i={index:0},l=dn(e,s,t,i,0,n),a=t[i.index];if(a!==void 0)throw k(a.number,"expected end of document");return l}function dn(e,t,n,r,o,s){let i=n[r.index].number,l=t.trim();if(r.index+=1,e.fields!==void 0){if(l!=="")throw k(i,"expected tabular rows");return ua(e,e.fields,n,r,o+1,s)}if(l!==""){let a=ce(l,e.delimiter,i).map(c=>B(c,i));if(a.length!==e.len)throw k(i,"array length mismatch");return a}return pa(e,n,r,o+1,s)}function ua(e,t,n,r,o,s){let i=[];for(;i.length<e.len;){let a=n[r.index];if(a===void 0)throw nn(n,r.index);if(a.depth<o)break;if(a.depth>o)throw k(a.number,"invalid indentation");if(a.blankBefore&&s.strict)throw k(a.number,"blank line inside array");if(!Xr(a.content,e.delimiter,a.number))break;let c=ce(a.content,e.delimiter,a.number);if(c.length!==t.length)throw k(a.number,"array row length mismatch");let u={};t.forEach((f,p)=>{Ke(u,f,B(c[p],a.number),s,a.number)}),i.push(u),r.index+=1}if(i.length!==e.len)throw nn(n,r.index);let l=n[r.index];if(l!==void 0&&l.depth>=o&&Xr(l.content,e.delimiter,l.number))throw k(l.number,"array length mismatch");return i}function Xr(e,t,n){let r=T(e,":",n);if(r===-1)return!0;let o=T(e,t,n);return o===-1?!1:o<r}function pa(e,t,n,r,o){let s=[];for(;s.length<e.len;){let l=t[n.index];if(l===void 0||l.depth<r)throw nn(t,n.index);if(l.depth>r)throw k(l.number,"invalid indentation");if(l.blankBefore&&o.strict)throw k(l.number,"blank line inside array");s.push(fa(t,n,r,o))}let i=t[n.index];if(i!==void 0&&i.depth>=r)throw k(i.number,"array length mismatch");return s}function fa(e,t,n,r){let o=e[t.index];if(!o.content.startsWith("-"))throw k(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return t.index+=1,{};if(s.startsWith("[")){let i=T(s,":",o.number),l;try{l=cn(s,i)}catch{l=void 0}if(l!==void 0){let a=s.slice(i+1);return dn(l,a,e,t,n,r)}}if(T(s,":",o.number)!==-1){let i=[{number:o.number,depth:n+1,content:s,blankBefore:!1}];for(t.index+=1;t.index<e.length;){let l=e[t.index];if(l.depth<=n)break;i.push(l),t.index+=1}return an(i,{index:0},n+1,r)}return t.index+=1,B(s,o.number)}function nn(e,t){let n=e[t]??e[e.length-1];return k(n===void 0?1:n.number,"array length mismatch")}function cn(e,t){if(t===-1)throw k(0,"array header missing colon");let n=e.slice(0,t),r=T(n,"[",0);if(r===-1)throw k(0,"invalid array header");let o,s;try{[o,s]=Z(n.slice(0,r),0)}catch{throw k(0,"invalid array header")}let i=n.slice(r+1),l=i.indexOf("]");if(l===-1)throw k(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 k(0,"invalid array header");let u=Number.parseInt(c,10),f;switch(a.slice(c.length)){case"":f=",";break;case" ":f=" ";break;case"|":f="|";break;default:throw k(0,"invalid array header")}let p=i.slice(l+1),h;if(p==="")h=void 0;else if(p.startsWith("{")&&p.endsWith("}")&&p.length>=2)try{h=eo(p.slice(1,-1),f)}catch(y){throw k(0,y.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw k(0,"invalid array header");return{key:o,keyQuoted:s,len:u,delimiter:f,fields:h}}function ma(e){let t=T(e,"{",0);if(t===-1||!e.endsWith("}"))throw k(0,"invalid keyed map header");let n,r;try{[n,r]=Z(e.slice(0,t),0)}catch{throw k(0,"invalid keyed map header")}if(n===""&&!r)throw k(0,"expected non-empty field name");let o;try{o=eo(e.slice(t+1,-1),j)}catch(s){throw k(0,s.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:n,keyQuoted:r,delimiter:j,fields:o}}function eo(e,t){let n=[],r=0;function o(l,a){let c=0;for(;r<e.length&&!(a&&e[r]==="}");){if(e[r]===t||e[r]==="}")throw k(0,"invalid array header");let u=r;for(;r<e.length;){let p=e[r];if(p==='"'){s();continue}if(p===t||p==="{"||p==="}")break;r+=1}let[f]=Z(e.slice(u,r),0);if(f==="")throw k(0,"invalid array header");if(c+=1,e[r]==="{"){r+=1;let p=n.length;if(o([...l,f],!0),e[r]!=="}"||n.length===p)throw k(0,"invalid array header");r+=1}else n.push([...l,f]);if(e[r]===t){if(r+=1,r>=e.length||e[r]==="}")throw k(0,"invalid array header");continue}if(a?e[r]==="}":r===e.length)break;throw k(0,"invalid array header")}if(c===0)throw k(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 k(0,"invalid array header");let i=new Set;for(let l=0;l<n.length;l+=1)for(let a=l+1;a<n.length;a+=1)if(ga(n[l],n[a])||rn(n[l],n[a])||rn(n[a],n[l]))throw k(0,"duplicate key");for(let l of n){let a=l.join("\0");if(i.has(a))throw k(0,"duplicate key");i.add(a)}return n}function ga(e,t){return e.length===t.length&&rn(e,t)}function rn(e,t){return t.every((n,r)=>e[r]===n)}function on(e,t){return k(t,e.reason??String(e.message))}function to(e,t,n,r,o,s){if(o.expandPaths&&!n&&t.includes(".")){let i=t.split(".");if(i.every(ha)){Ke(e,i,r,o,s);return}}Ke(e,[t],r,o,s)}function Ke(e,t,n,r,o){let s=t[0],i=Object.prototype.hasOwnProperty.call(e,s);if(t.length===1){if(i&&r.strict)throw k(o,"duplicate key");_e(e,s,n);return}if(i&&!ve(e[s])){if(r.strict)throw k(o,"path expansion conflict");_e(e,s,{})}else i||_e(e,s,{});Ke(e[s],t.slice(1),n,r,o)}function ha(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function I(e,t={}){let n={nestedTabularHeaders:t.nestedTabularHeaders===!0,keyedMapCollapse:t.keyedMapCollapse===!0},r=[];return Array.isArray(e)?un(r,void 0,e,0,!1,n):ve(e)?no(r,e,0,n):r.push(J(e,j)),r.join("")}function qe(e,t){e.push(" ".repeat(t*ln))}function no(e,t,n,r){for(let[o,s]of Object.entries(t))qe(e,n),sn(e,o,s,n,r)}function sn(e,t,n,r,o){if(Array.isArray(n)){un(e,t,n,r,!1,o);return}if(ve(n)){let s=o.keyedMapCollapse?ka(n,o):void 0;if(s!==void 0){e.push(C(t),"{",s.fields.map(pn).join(j),`}:
10
10
  `);for(let[i,l]of Object.entries(n))qe(e,r+1),e.push(C(i),": ",s.paths.map(a=>J(io(l,a),j)).join(j),`
11
11
  `);return}e.push(C(t),`:
12
12
  `),no(e,n,r+1,o);return}e.push(C(t),": ",J(n,j),`
13
- `)}function cn(e,t,n,r,o,s){if(n.length===0){t!==void 0?e.push(C(t),`: []
13
+ `)}function un(e,t,n,r,o,s){if(n.length===0){t!==void 0?e.push(C(t),`: []
14
14
  `):o?e.push(`[0]:
15
15
  `):e.push(`[]
16
- `);return}if(n.every(Je)){en(e,t,n.length,void 0),e.push(" "),e.push(n.map(l=>J(l,j)).join(j)),e.push(`
17
- `);return}let i=o?void 0:ro(n,s);if(i!==void 0){en(e,t,n.length,i.fields),e.push(`
16
+ `);return}if(n.every(Je)){tn(e,t,n.length,void 0),e.push(" "),e.push(n.map(l=>J(l,j)).join(j)),e.push(`
17
+ `);return}let i=o?void 0:ro(n,s);if(i!==void 0){tn(e,t,n.length,i.fields),e.push(`
18
18
  `);for(let l of n)qe(e,r+1),e.push(i.paths.map(a=>J(io(l,a),j)).join(j)),e.push(`
19
- `);return}en(e,t,n.length,void 0),e.push(`
20
- `);for(let l of n)qe(e,r+1),ya(e,l,r+1,s)}function ya(e,t,n,r){if(Array.isArray(t)){e.push("- "),cn(e,void 0,t,n,!0,r);return}if(ve(t)){let o=Object.entries(t);if(o.length===0){e.push(`-
21
- `);return}e.push("- "),on(e,o[0][0],o[0][1],n+1,r);for(let[s,i]of o.slice(1))qe(e,n+1),on(e,s,i,n+1,r);return}e.push("- ",J(t,j),`
22
- `)}function en(e,t,n,r){t!==void 0&&e.push(C(t)),e.push("[",String(n),"]"),r!==void 0&&e.push("{",r.map(un).join(j),"}"),e.push(":")}function ro(e,t){let n=oo(e.map(r=>({value:r})),t);return n===void 0?void 0:{fields:n,paths:so(n)}}function ka(e,t){let n=Object.values(e);if(!(n.length<2))return ro(n,t)}function oo(e,t){let n=e[0]?.value;if(!ve(n))return;let r=Object.keys(n).map(o=>({key:o}));if(r.length!==0){for(let{value:o}of e)if(!ve(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})=>Je(l)))continue;if(!t.nestedTabularHeaders)return;let i=oo(s,t);if(i===void 0)return;o.children=i}return r}}function so(e,t=[]){return e.flatMap(n=>{let r=[...t,n.key];return n.children===void 0?[r]:so(n.children,r)})}function io(e,t){let n=e;for(let r of t)n=n[r];return n}function un(e){return e.children===void 0?C(e.key):`${C(e.key)}{${e.children.map(un).join(j)}}`}var go=[j,"|"," "];var ho=8,yo=/^[A-Za-z0-9_-]+$/,Gm=new TextEncoder,zm=new TextDecoder;function wa(e,t){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let n=e.slice(2,-1);if(!/^[0-9]+$/.test(n))throw S(t,"invalid trailer count");return Number.parseInt(n,10)}function ko(e,t){if(!yo.test(e))throw S(t,"invalid tag")}function ba(e,t){let n=e.indexOf(":");if(n<=0)return null;let r=e.slice(0,n);if(!yo.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw S(t,"invalid tag");return null}return{tag:r,cellsText:e.slice(n+1)}}function _a(e,t){if(!e.startsWith("["))return null;let n=e.slice(1),r=n.indexOf("]");if(r===-1)throw S(t,"invalid header");let o=n.slice(0,r),s=o.startsWith("~"),i=s?o.slice(1):o;if(!s&&i.startsWith("="))return null;if(!go.includes(i)&&i!=="")throw S(t,"invalid header delimiter");let l=i===""?j:i,a=n.slice(r+1),c=null;if(!s&&a.startsWith("<")){let p=a.indexOf(">");if(p===-1)throw S(t,"invalid tag");if(c=a.slice(1,p),ko(c,t),i!=="")throw S(t,"invalid header delimiter");a=a.slice(p+1)}if(!a.startsWith("{")||!a.endsWith("}:"))throw S(t,"invalid header");let u=a.slice(1,-2),f;try{f=ce(u,l,t).map(p=>Z(p,t)[0])}catch(p){throw be(p)}if(f.length===0||f.some(p=>p===""))throw S(t,"invalid header fields");return{delimiter:l,fields:f,fieldText:u,continuation:s,tag:c}}function va(e,t,n){if(e===null||e.delimiter===void 0)throw S(n,"continuation header before header");if(e.delimiter!==t.delimiter||e.fieldText!==t.fieldText)throw S(n,"continuation header mismatch")}function lo(e,t,n,r){let o;try{o=ce(e,t,r)}catch(s){throw be(s)}if(o.length!==n)throw S(r,"row arity mismatch");for(let s of o)try{B(s,r)}catch(i){throw be(i)}return o}function Sa(e,t,n){let r={};return e.forEach((o,s)=>{try{_e(r,o,B(t[s],n))}catch(i){throw be(i)}}),r}function xa(e,t,n){if(e.startsWith("- "))throw S(t,"reserved line prefix");let r=wa(e,t);if(r!==null){if(n===null||n.delimiter===void 0)throw S(t,"trailer without header");if(n.rowCount!==r)throw S(t,"trailer count mismatch");return{kind:"trailer"}}let o=_a(e,t);if(o!==null)return o.continuation?(va(n,o,t),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=ba(e,t);if(s!==null){let i=n?.taggedLanes?.get(s.tag);if(i===void 0)throw S(t,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:lo(s.cellsText,i.delimiter,i.fields.length,t)}}if(n===null||n.delimiter===void 0)throw S(t,"row before header");return{kind:"row",cells:lo(e,n.delimiter,n.fields.length,t)}}function Ea(e,t={}){let n=[],r=new Map,o=[],s=[],i=null,l=!1,a=!1;function c(h,y){let w=s.at(-1);if(w!==void 0&&w.lane===h.lane&&w.delimiter===h.delimiter&&w.fieldText===h.fieldText){w.rows.push(y);return}s.push({lane:h.lane,delimiter:h.delimiter,fields:h.fields,fieldText:h.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 f(h,y,w){let b=r.get(h);if(b===void 0){if(r.size>=ho)throw S(w,"too many tagged lanes");b={segments:[],current:null},r.set(h,b),n.push(h)}else b.current!==null&&b.segments.push(b.current);b.current={lane:h,delimiter:y.delimiter,fields:y.fields,fieldText:y.fieldText,rows:[]},b.delimiter=y.delimiter,b.fields=y.fields,b.fieldText=y.fieldText}if(gt(e).forEach((h,y)=>{let w=y+1;if(h==="")return;let b=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},_=xa(h,w,b);if(_.kind==="trailer"){u(),i=null;return}if(_.kind!=="continuation"){if(_.kind==="tag-header"){a=!0,f(_.header.tag,_.header,w);return}if(_.kind==="header"){u(),l||(n.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 O=r.get(_.tag).current;O.rows.push(_.cells),c(O,_.cells);return}if(i===null)throw S(w,"row before header");i.rows.push(_.cells),c(i,_.cells)}}),!a)return u(),t.preserveInterleaving===!0,o;let p=[];u();for(let h of n){if(h===null){p.push(...o);continue}let y=r.get(h);p.push(...y.segments),y.current!==null&&p.push(y.current)}return t.preserveInterleaving===!0?s:p}function fn(e){return Ea(e).flatMap(t=>t.rows.map(n=>Sa(t.fields,n,0)))}function ja(e){if(!go.includes(e))throw S(0,"invalid header delimiter")}function ao(e,t,n=!1){return`[${`${n?"~":""}${e===j?"":e}`}]{${t}}:
19
+ `);return}tn(e,t,n.length,void 0),e.push(`
20
+ `);for(let l of n)qe(e,r+1),ya(e,l,r+1,s)}function ya(e,t,n,r){if(Array.isArray(t)){e.push("- "),un(e,void 0,t,n,!0,r);return}if(ve(t)){let o=Object.entries(t);if(o.length===0){e.push(`-
21
+ `);return}e.push("- "),sn(e,o[0][0],o[0][1],n+1,r);for(let[s,i]of o.slice(1))qe(e,n+1),sn(e,s,i,n+1,r);return}e.push("- ",J(t,j),`
22
+ `)}function tn(e,t,n,r){t!==void 0&&e.push(C(t)),e.push("[",String(n),"]"),r!==void 0&&e.push("{",r.map(pn).join(j),"}"),e.push(":")}function ro(e,t){let n=oo(e.map(r=>({value:r})),t);return n===void 0?void 0:{fields:n,paths:so(n)}}function ka(e,t){let n=Object.values(e);if(!(n.length<2))return ro(n,t)}function oo(e,t){let n=e[0]?.value;if(!ve(n))return;let r=Object.keys(n).map(o=>({key:o}));if(r.length!==0){for(let{value:o}of e)if(!ve(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})=>Je(l)))continue;if(!t.nestedTabularHeaders)return;let i=oo(s,t);if(i===void 0)return;o.children=i}return r}}function so(e,t=[]){return e.flatMap(n=>{let r=[...t,n.key];return n.children===void 0?[r]:so(n.children,r)})}function io(e,t){let n=e;for(let r of t)n=n[r];return n}function pn(e){return e.children===void 0?C(e.key):`${C(e.key)}{${e.children.map(pn).join(j)}}`}var go=[j,"|"," "];var ho=8,yo=/^[A-Za-z0-9_-]+$/,zm=new TextEncoder,Qm=new TextDecoder;function wa(e,t){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let n=e.slice(2,-1);if(!/^[0-9]+$/.test(n))throw S(t,"invalid trailer count");return Number.parseInt(n,10)}function ko(e,t){if(!yo.test(e))throw S(t,"invalid tag")}function ba(e,t){let n=e.indexOf(":");if(n<=0)return null;let r=e.slice(0,n);if(!yo.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw S(t,"invalid tag");return null}return{tag:r,cellsText:e.slice(n+1)}}function _a(e,t){if(!e.startsWith("["))return null;let n=e.slice(1),r=n.indexOf("]");if(r===-1)throw S(t,"invalid header");let o=n.slice(0,r),s=o.startsWith("~"),i=s?o.slice(1):o;if(!s&&i.startsWith("="))return null;if(!go.includes(i)&&i!=="")throw S(t,"invalid header delimiter");let l=i===""?j:i,a=n.slice(r+1),c=null;if(!s&&a.startsWith("<")){let p=a.indexOf(">");if(p===-1)throw S(t,"invalid tag");if(c=a.slice(1,p),ko(c,t),i!=="")throw S(t,"invalid header delimiter");a=a.slice(p+1)}if(!a.startsWith("{")||!a.endsWith("}:"))throw S(t,"invalid header");let u=a.slice(1,-2),f;try{f=ce(u,l,t).map(p=>Z(p,t)[0])}catch(p){throw be(p)}if(f.length===0||f.some(p=>p===""))throw S(t,"invalid header fields");return{delimiter:l,fields:f,fieldText:u,continuation:s,tag:c}}function va(e,t,n){if(e===null||e.delimiter===void 0)throw S(n,"continuation header before header");if(e.delimiter!==t.delimiter||e.fieldText!==t.fieldText)throw S(n,"continuation header mismatch")}function lo(e,t,n,r){let o;try{o=ce(e,t,r)}catch(s){throw be(s)}if(o.length!==n)throw S(r,"row arity mismatch");for(let s of o)try{B(s,r)}catch(i){throw be(i)}return o}function Sa(e,t,n){let r={};return e.forEach((o,s)=>{try{_e(r,o,B(t[s],n))}catch(i){throw be(i)}}),r}function xa(e,t,n){if(e.startsWith("- "))throw S(t,"reserved line prefix");let r=wa(e,t);if(r!==null){if(n===null||n.delimiter===void 0)throw S(t,"trailer without header");if(n.rowCount!==r)throw S(t,"trailer count mismatch");return{kind:"trailer"}}let o=_a(e,t);if(o!==null)return o.continuation?(va(n,o,t),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=ba(e,t);if(s!==null){let i=n?.taggedLanes?.get(s.tag);if(i===void 0)throw S(t,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:lo(s.cellsText,i.delimiter,i.fields.length,t)}}if(n===null||n.delimiter===void 0)throw S(t,"row before header");return{kind:"row",cells:lo(e,n.delimiter,n.fields.length,t)}}function Ea(e,t={}){let n=[],r=new Map,o=[],s=[],i=null,l=!1,a=!1;function c(h,y){let w=s.at(-1);if(w!==void 0&&w.lane===h.lane&&w.delimiter===h.delimiter&&w.fieldText===h.fieldText){w.rows.push(y);return}s.push({lane:h.lane,delimiter:h.delimiter,fields:h.fields,fieldText:h.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 f(h,y,w){let b=r.get(h);if(b===void 0){if(r.size>=ho)throw S(w,"too many tagged lanes");b={segments:[],current:null},r.set(h,b),n.push(h)}else b.current!==null&&b.segments.push(b.current);b.current={lane:h,delimiter:y.delimiter,fields:y.fields,fieldText:y.fieldText,rows:[]},b.delimiter=y.delimiter,b.fields=y.fields,b.fieldText=y.fieldText}if(ht(e).forEach((h,y)=>{let w=y+1;if(h==="")return;let b=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},_=xa(h,w,b);if(_.kind==="trailer"){u(),i=null;return}if(_.kind!=="continuation"){if(_.kind==="tag-header"){a=!0,f(_.header.tag,_.header,w);return}if(_.kind==="header"){u(),l||(n.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 O=r.get(_.tag).current;O.rows.push(_.cells),c(O,_.cells);return}if(i===null)throw S(w,"row before header");i.rows.push(_.cells),c(i,_.cells)}}),!a)return u(),t.preserveInterleaving===!0,o;let p=[];u();for(let h of n){if(h===null){p.push(...o);continue}let y=r.get(h);p.push(...y.segments),y.current!==null&&p.push(y.current)}return t.preserveInterleaving===!0?s:p}function mn(e){return Ea(e).flatMap(t=>t.rows.map(n=>Sa(t.fields,n,0)))}function ja(e){if(!go.includes(e))throw S(0,"invalid header delimiter")}function ao(e,t,n=!1){return`[${`${n?"~":""}${e===j?"":e}`}]{${t}}:
23
23
  `}function co(e,t){return`[]<${e}>{${t}}:
24
- `}function pn(e,t){return t.map(C).join(e)}function Pa(e){if(!Array.isArray(e)||e.length===0)throw S(0,"TOONL header requires fields");return e.map(t=>{let n;try{[n]=Z(String(t),0)}catch(r){throw be(r)}if(n==="")throw S(0,"TOONL header requires fields");return n})}function uo(e,t){return e!==null&&e.length===t.length&&e.every((n,r)=>n===t[r])}function po(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw S(0,"TOONL continuation cadence must be positive")}function Oa(e,t,n){return e.continuationEveryRows!==void 0&&t>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&n>=e.continuationEveryBytes}function fo(e){if(e===null||typeof e!="object"||Array.isArray(e))throw S(0,"TOONL output requires object rows");let t=Object.keys(e);if(t.length===0)throw S(0,"TOONL output requires object rows");if(t.some(n=>!Je(e[n])))throw S(0,"TOONL rows must be flat objects");return t}function Da(e){return JSON.stringify([...e].sort())}function mo(e,t){let n=Da(e),r=t.get(n);return r!==void 0?r:(t.set(n,e),e)}function mn({delimiter:e=j,trailer:t=!0,continuationEveryRows:n,continuationEveryBytes:r}={}){ja(e),po(n),po(r);let o=null,s="",i=new Map,l=0,a=0,c=0,u=new Map,f=!1,p={continuationEveryRows:n,continuationEveryBytes:r},h=()=>o===null||!t?"":`[=${l}]
25
- `,y=()=>Oa(p,a,c)?(a=0,c=0,ao(e,s,!0)):"",w=b=>{ko(b,0);let _=u.get(b);if(_===void 0){if(u.size>=ho)throw S(0,"too many tagged lanes");_={fields:null,fieldsByShape:new Map},u.set(b,_)}return _};return{push(b){if(f)throw S(0,"TOONL encoder is closed");let _=mo(fo(b),i),O="";(o===null||o.length!==_.length||o.some((ae,he)=>ae!==_[he]))&&(O+=h(),o=_,s=pn(e,o),l=0,a=0,c=0,O+=ao(e,s));let F=o.map(ae=>J(b[ae],e));O+=y();let M=`${F.join(e)}
26
- `;return O+=M,l+=1,a+=1,c+=M.length,O},declareLane(b,_){if(f)throw S(0,"TOONL encoder is closed");let O=Pa(_),F=pn(j,O),M=w(b);return uo(M.fields,O)?"":(M.fields=O,co(b,F))},pushTagged(b,_){if(f)throw S(0,"TOONL encoder is closed");let O=w(b),F=mo(fo(_),O.fieldsByShape),M=pn(j,F),ae=F.map(st=>J(_[st],j)),he="";return uo(O.fields,F)||(O.fields=F,he+=co(b,M)),`${he}${b}:${ae.join(j)}
27
- `},end(){return f?"":(f=!0,h())}}}function gn(e){let t={app:e,version:La(Se("__RED_BUILD_VERSION__",()=>"3.1.2")??"0.0.0-dev"),gitSha:Se("__RED_BUILD_GIT_SHA__",()=>"f2c351a37c544900447dd6b5775fe0a0fb63f4b7")??"unknown",buildTime:Se("__RED_BUILD_TIME__",()=>"2026-08-01T08:18:40Z")??"unknown",bundleAsset:Se("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},n=Se("__REDDB_SDK_VERSION__",()=>""),r=Se("__REDDB_BINARY_TAG__",()=>"");return n&&(t.reddbSdkVersion=n),r&&(t.reddbBinaryTag=r),t}function La(e){return e.startsWith("v")?e.slice(1):e}function Ro(e){return`${e.app} ${e.version} ${e.gitSha}`}function Se(e,t){try{let n=t();return typeof n=="string"&&n.length>0?n:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var wo={"=":"data",":=":{to:"data",typed:!0},":":"meta"},$a=/^[a-z][a-z0-9+.-]*:\/\//i;function Aa(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function Ia(e=wo){return Object.entries(e).map(([t,n])=>Aa(t,n)).sort((t,n)=>n.separator.length-t.separator.length)}function Ta(e){return/^-\d+(\.\d+)?$/.test(e)}function Ge(e){return!(!e||e.startsWith("-")&&!Ta(e))}function ht(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function bo(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 t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(n=>bo(n.trim())):e}function ue(e,t){switch(t){case"boolean":return Na(e);case"number":return Wa(e);case"array":return e.split(",").map(n=>ht(n.trim()));case"string":default:return e}}function Na(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function Wa(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function se(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Ma(e,t={}){return e.map(n=>{let r=t[n.type];return r?r(n.value):n.value}).join("")}function E(e,t){return{type:e,value:t}}function Ca(e){let t=[],n=Fa(e);if(t.push(E("section-header","Usage:"),E("text"," "),E("usage-text",n),E("newline",`
24
+ `}function fn(e,t){return t.map(C).join(e)}function Pa(e){if(!Array.isArray(e)||e.length===0)throw S(0,"TOONL header requires fields");return e.map(t=>{let n;try{[n]=Z(String(t),0)}catch(r){throw be(r)}if(n==="")throw S(0,"TOONL header requires fields");return n})}function uo(e,t){return e!==null&&e.length===t.length&&e.every((n,r)=>n===t[r])}function po(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw S(0,"TOONL continuation cadence must be positive")}function Oa(e,t,n){return e.continuationEveryRows!==void 0&&t>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&n>=e.continuationEveryBytes}function fo(e){if(e===null||typeof e!="object"||Array.isArray(e))throw S(0,"TOONL output requires object rows");let t=Object.keys(e);if(t.length===0)throw S(0,"TOONL output requires object rows");if(t.some(n=>!Je(e[n])))throw S(0,"TOONL rows must be flat objects");return t}function La(e){return JSON.stringify([...e].sort())}function mo(e,t){let n=La(e),r=t.get(n);return r!==void 0?r:(t.set(n,e),e)}function gn({delimiter:e=j,trailer:t=!0,continuationEveryRows:n,continuationEveryBytes:r}={}){ja(e),po(n),po(r);let o=null,s="",i=new Map,l=0,a=0,c=0,u=new Map,f=!1,p={continuationEveryRows:n,continuationEveryBytes:r},h=()=>o===null||!t?"":`[=${l}]
25
+ `,y=()=>Oa(p,a,c)?(a=0,c=0,ao(e,s,!0)):"",w=b=>{ko(b,0);let _=u.get(b);if(_===void 0){if(u.size>=ho)throw S(0,"too many tagged lanes");_={fields:null,fieldsByShape:new Map},u.set(b,_)}return _};return{push(b){if(f)throw S(0,"TOONL encoder is closed");let _=mo(fo(b),i),O="";(o===null||o.length!==_.length||o.some((ae,he)=>ae!==_[he]))&&(O+=h(),o=_,s=fn(e,o),l=0,a=0,c=0,O+=ao(e,s));let F=o.map(ae=>J(b[ae],e));O+=y();let M=`${F.join(e)}
26
+ `;return O+=M,l+=1,a+=1,c+=M.length,O},declareLane(b,_){if(f)throw S(0,"TOONL encoder is closed");let O=Pa(_),F=fn(j,O),M=w(b);return uo(M.fields,O)?"":(M.fields=O,co(b,F))},pushTagged(b,_){if(f)throw S(0,"TOONL encoder is closed");let O=w(b),F=mo(fo(_),O.fieldsByShape),M=fn(j,F),ae=F.map(it=>J(_[it],j)),he="";return uo(O.fields,F)||(O.fields=F,he+=co(b,M)),`${he}${b}:${ae.join(j)}
27
+ `},end(){return f?"":(f=!0,h())}}}function hn(e){let t={app:e,version:Da(Se("__RED_BUILD_VERSION__",()=>"3.2.0")??"0.0.0-dev"),gitSha:Se("__RED_BUILD_GIT_SHA__",()=>"bc031bb41bb2483b8b2f83d2f3e0d77120904fe4")??"unknown",buildTime:Se("__RED_BUILD_TIME__",()=>"2026-08-01T11:57:11Z")??"unknown",bundleAsset:Se("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},n=Se("__REDDB_SDK_VERSION__",()=>""),r=Se("__REDDB_BINARY_TAG__",()=>"");return n&&(t.reddbSdkVersion=n),r&&(t.reddbBinaryTag=r),t}function Da(e){return e.startsWith("v")?e.slice(1):e}function Ro(e){return`${e.app} ${e.version} ${e.gitSha}`}function Se(e,t){try{let n=t();return typeof n=="string"&&n.length>0?n:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var wo={"=":"data",":=":{to:"data",typed:!0},":":"meta"},$a=/^[a-z][a-z0-9+.-]*:\/\//i;function Aa(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function Ia(e=wo){return Object.entries(e).map(([t,n])=>Aa(t,n)).sort((t,n)=>n.separator.length-t.separator.length)}function Ta(e){return/^-\d+(\.\d+)?$/.test(e)}function Ge(e){return!(!e||e.startsWith("-")&&!Ta(e))}function yt(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function bo(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 t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(n=>bo(n.trim())):e}function ue(e,t){switch(t){case"boolean":return Na(e);case"number":return Wa(e);case"array":return e.split(",").map(n=>yt(n.trim()));case"string":default:return e}}function Na(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function Wa(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function se(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Ma(e,t={}){return e.map(n=>{let r=t[n.type];return r?r(n.value):n.value}).join("")}function E(e,t){return{type:e,value:t}}function Ca(e){let t=[],n=Fa(e);if(t.push(E("section-header","Usage:"),E("text"," "),E("usage-text",n),E("newline",`
28
28
  `),E("newline",`
29
29
  `)),e.positional&&e.positional.length>0){t.push(E("section-header","Arguments:"),E("newline",`
30
30
  `));for(let r of e.positional)if(r.description){let o=r.variadic?`${r.name}...`:r.name;t.push(E("indent"," "),E("positional-name",`<${o}>`)),r.required||t.push(E("positional-optional"," (optional)")),t.push(E("newline",`
@@ -32,33 +32,33 @@ ${t.searched.map(n=>` ${n}`).join(`
32
32
  `))}t.push(E("newline",`
33
33
  `))}if(e.options&&Object.keys(e.options).length>0){t.push(E("section-header","Options:"),E("newline",`
34
34
  `));let r=Ha(e.options);t.push(...r)}return t}function Ua(e,t){let n=Ca(e);return Ma(n,t)}function Fa(e){let t=["[options]"];if(e.positional)for(let n of e.positional)n.variadic?t.push(n.required?`<${n.name}...>`:`[${n.name}...]`):t.push(n.required?`<${n.name}>`:`[${n.name}]`);return t.join(" ")}function Ha(e,t=!1){let n=[],r=[],o=t?"global-option-flag":"option-flag",s=t?"global-option-type":"option-type",i=t?"global-option-default":"option-default",l=t?"global-option-description":"option-description";for(let[c,u]of Object.entries(e)){if(u.hidden)continue;let f=[],p=w=>{f.includes(w)||f.push(w)};u.short&&p(`-${u.short}`),p(`--${c}`);for(let w of u.aliases??[])w.length===1?p(`-${w}`):p(`--${w}`);let h=f.join(", "),y=u.type&&u.type!=="boolean"?`<${u.type}>`:void 0;r.push({flags:h,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),f=" ".repeat(a-u+2);n.push(E("indent"," ")),n.push(E(o,c.flags)),c.type&&(n.push(E("text"," ")),n.push(E(s,c.type))),n.push(E("text",f)),n.push(E(l,c.desc)),c.default!==void 0&&(n.push(E("text"," ")),n.push(E(i,`(default: ${c.default})`))),n.push(E("newline",`
35
- `))}return n}function _o(e){let t=za(e.options??{},e.autoShort??!1),n=Ia(e.separators??wo);return{schema:e,parse(r){return Va(r,e,t,n)},help(){return Ua(e,e.formatter)}}}function Va(e,t,n,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=t.positional??[],a=0,c=!1;for(;a<e.length;){let u=e[a];if(t.stopEarly&&i>0){o.rest=e.slice(a);break}if(u==="--"&&!c){c=!0,a++;continue}if(c){if(i<l.length){let p=l[i];if(p.variadic){let h=[];for(;a<e.length;){let y=e[a];h.push(p.type?ue(y,p.type):y),a++}o.positional[p.name]=h,i++}else{let h=p.type?ue(u,p.type):u;o.positional[p.name]=h,i++,a++}}else t.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(u)),a++;continue}if(u.startsWith("--")){a=qa(u,a,e,o,n,t);continue}if(u.startsWith("-")&&u.length>1&&!ed(u)){a=Ga(u,a,e,o,n,t);continue}let f=Ba(u,r);if(f){let{key:p,value:h,config:y}=f,w=o,b=w[y.to]??(w[y.to]={});b[p]=y.typed?bo(h):se(h),a++;continue}if(i<l.length){let p=l[i];if(p.variadic){let y=[];for(;a<e.length&&!e[a].startsWith("-");){let w=e[a];y.push(p.type?ue(w,p.type):w),a++}o.positional[p.name]=y,i++;continue}let h=p.type?ue(u,p.type):u;o.positional[p.name]=h,i++}else t.allowUnknown!==!1?o.rest.push(u):o.errors.push(`Unexpected positional argument: ${u}`);a++}return Ya(o,t,n),Za(o,t,l),Xa(o,t,n),o}function Ba(e,t){if($a.test(e))return null;for(let n of t){if(n.prefix&&e.startsWith(n.separator)){let o=e.slice(n.separator.length),s=o.indexOf(":");if(s>0){let i=o.slice(0,s),l=o.slice(s+1);if(Ja(i))return{key:i,value:l,config:n}}continue}let r=e.indexOf(n.separator);if(r>0){let o=e.slice(0,r),s=e.slice(r+n.separator.length);if(Ka(o,s,n))return{key:o,value:s,config:n}}}return null}function Ja(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function Ka(e,t,n){return e?n.separator===":"?e.includes("/")||e.includes(".")||/^\d+$/.test(t)?!1:/^[A-Z][a-zA-Z0-9-]*$/.test(e):!((n.separator==="="||n.separator===":=")&&e.includes("/")):!1}function qa(e,t,n,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,t+1}if(i.includes("=")){let a=i.indexOf("="),c=i.slice(0,a),u=i.slice(a+1);return yt(c,u,t+1,r,o,s)}let l=o.get(i);if(l){if(l.type!=="boolean"){let a=n[t+1];return Ge(a)?yt(l.name,a,t+2,r,o,s):(r.errors.push(`Option --${i} requires a value`),t+1)}return r.options[l.name]=!0,t+1}return s.strict?r.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(r.options[i]=!0),t+1}function Ga(e,t,n,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=hn(a,o);return u?yt(u.name,c,t+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=ht(se(c))),t+1)}if(i.length===1){let l=hn(i,o);if(l){if(l.type!=="boolean"){let a=n[t+1];return Ge(a)?yt(l.name,a,t+2,r,o,s):(r.errors.push(`Option -${i} requires a value`),t+1)}return r.options[l.name]=!0,t+1}if(s.strict)r.errors.push(`Unknown option: -${i}`);else if(s.allowUnknown!==!1){let a=n[t+1];if(Ge(a))return r.options[i]=ht(se(a)),t+2;r.options[i]=!0}return t+1}for(let l of i){let a=hn(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 t+1}function yt(e,t,n,r,o,s){let i=o.get(e);if(i){if(i.choices){let a=i.type?ue(se(t),i.type):se(t);if(!i.choices.includes(a))return r.errors.push(`Invalid value for '${e}': '${t}'. Allowed: ${i.choices.join(", ")}`),n}let l=i.type?ue(se(t),i.type):se(t);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]=ht(se(t)));return n}function za(e,t=!1){let n=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??"";t&&!l&&(l=Qa(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};n.set(s,a);for(let c of a.aliases)n.set(c,a)}return n}function Qa(e,t){for(let n of e){if(!/[a-zA-Z]/.test(n))continue;let r=n.toLowerCase();if(!t.has(r))return r;let o=n.toUpperCase();if(!t.has(o))return o}return""}function hn(e,t){for(let n of t.values())if(n.short===e||n.aliases.includes(e))return n}function Ya(e,t,n){for(let r of n.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?ue(o,r.type):o}else r.default!==void 0&&(e.options[r.name]=r.default);for(let r of t.positional??[])e.positional[r.name]===void 0&&r.default!==void 0&&(e.positional[r.name]=r.default)}function Za(e,t,n){if(t.options)for(let[r,o]of Object.entries(t.options))o.required&&e.options[r]===void 0&&e.errors.push(`Missing required option: --${r}`);for(let r of n)r.required&&e.positional[r.name]===void 0&&e.errors.push(`Missing required argument: <${r.name}>`)}function Xa(e,t,n){for(let r of n.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 t.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 ed(e){return/^-\d+(\.\d+)?$/.test(e)}var yn=class extends Error{flag;known;constructor(t,n){super(`unknown flag '${t}'; expected one of: ${n.join(", ")}`),this.name="UnknownFlagError",this.flag=t,this.known=n}};function td(e){let t={};for(let[n,r]of Object.entries(e))t[n]={type:r.kind==="boolean"?"boolean":"string",...n.length===1?{short:n}:{},...r.aliases===void 0?{}:{aliases:r.aliases}};return t}function nd(e,t){let n=new Map;for(let[o,s]of Object.entries(t))if(!(s.kind!=="value"||s.type!=="array")){n.set(o,o);for(let i of s.aliases??[])n.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=n.get(i[1]);if(l===void 0)continue;let a=i[2];if(a===void 0&&Ge(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 pe(e,t,n={}){let o=_o({options:td(t),separators:{},allowUnknown:!0}).parse([...e]),s={},i=nd(e,t),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(n.unknownFlags==="error"){let a=new Set(Object.keys(t));for(let c of Object.keys(o.options))if(!a.has(c))throw new yn(c.length===1?`-${c}`:`--${c}`,Object.keys(t).map(u=>u.length===1?`-${u}`:`--${u}`))}for(let[a,c]of Object.entries(t)){let u=o.options[a];u!==void 0&&(c.kind==="boolean"?s[a]=u:c.type==="array"?s[a]=(i.get(a)??[]).map(f=>c.coerce(f)):s[a]=c.coerce(String(u)))}return{values:s,positionals:o.rest}}var kn=class extends Error{token;known;constructor(t,n){super(`unknown command '${t}'; expected one of: ${n.join(", ")}`),this.name="UnknownCommandError",this.token=t,this.known=n}};function vo(e,t){let[n,...r]=e;if(n!==void 0){for(let[s,i]of Object.entries(t.commands))if(n===s||(i.aliases??[]).includes(n))return{command:s,args:r};if(t.errorOnUnknownCommand&&!n.startsWith("-"))throw new kn(n,Object.keys(t.commands))}let o=t.keepArgvOnDefault??!0;return{command:t.default,args:o?[...e]:r}}import{execFileSync as hd}from"node:child_process";import{readFileSync as yd}from"node:fs";import{dirname as Do,join as kd}from"node:path";import{existsSync as rd,readFileSync as Eg}from"node:fs";import{dirname as od,join as sd}from"node:path";function So(e,t){let n=e;for(let r=0;r<16;r++){let o=sd(n,t);if(rd(o))return o;let s=od(n);if(s===n)break;n=s}return null}function id(e){let t=e.indexOf(" #");return(t>=0?e.slice(0,t):e).trim()}function xe(e,t){let n=[];for(let r of e.split(`
36
- `)){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(;n.length&&n[n.length-1].indent>=l;)n.pop();if(n.push({indent:l,key:a}),c&&n.map(f=>f.key).join(".")===t)return id(c)}}import{createHash as ld}from"node:crypto";var ad="project.name";function Eo(e){let t=xe(e,ad)?.trim();return t===void 0||t===""?void 0:t}var dd=8,jo="project";function Po(e){let t=md(e.gitCommonDir),n=(e.declaredName??"").trim(),r=n!==""?{name:n,source:"declared"}:cd(e.remoteUrl)??{name:ud(e.checkoutPath,t),source:"basename"},o=fd(t??Rn(e.checkoutPath));return{name:r.name,slug:`${pd(r.name)}-${o}`,hash:o,source:r.source}}function Oo(e){let t=(e??"").trim();if(t==="")return;let n=t.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),r=/^[^/]*?:(?!\d)(.+)$/.exec(n),s=(r?r[1]:n.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(i=>i.trim()).filter(i=>i!=="");if(s.length!==0)return s.slice(-2).join("/")}function cd(e){let t=Oo(e);return t===void 0?void 0:{name:t,source:"remote"}}function ud(e,t){let n=t===void 0?"":xo(gd(t));if(n!=="")return n;let r=xo(Rn(e));return r===""?jo:r}function pd(e){let n=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return n===""?jo:n}function fd(e){return ld("sha256").update(e).digest("hex").slice(0,dd)}function md(e){let t=Rn(e??"");return t===""?void 0:t}function Rn(e){let t=e.trim().replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t}function xo(e){let t=e.split("/").filter(n=>n!=="");return t[t.length-1]??""}function gd(e){return e.split("/").filter(n=>n!=="").slice(0,-1).join("/")}var Rd=2e3;function Lo(e){return wd(e).name}function wd(e){let t=bn(e),n=wn(e,["rev-parse","--absolute-git-dir"])??wn(e,["rev-parse","--git-common-dir"]),r=wn(e,["remote","get-url","origin"]);return Po({checkoutPath:t.root??e,...n!==void 0?{gitCommonDir:n}:{},...r!==void 0?{remoteUrl:r}:{},...t.name!==void 0?{declaredName:t.name}:{}})}function bn(e){let t=So(e,kd(".red","config.yaml"));if(t==null)return{};let n;try{n=yd(t,"utf8")}catch{return{}}let r=Eo(n),o=Do(Do(t));return{...r===void 0?{}:{name:r},configText:n,root:o}}function wn(e,t){try{let n=hd("git",[...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Rd}).trim();return n===""?void 0:n}catch{return}}import{randomUUID as Zi}from"node:crypto";import{spawn as vf}from"node:child_process";import{mkdir as Sf,rm as xf}from"node:fs/promises";import{dirname as Ef}from"node:path";import{createHash as vd}from"node:crypto";import{constants as En}from"node:fs";import{mkdir as Sd,open as xd}from"node:fs/promises";import{createConnection as Ed}from"node:net";import{tmpdir as jd}from"node:os";import{dirname as Pd,join as jn}from"node:path";var bd="toon";function Io(e){return e.trimStart().startsWith("{")?"json":"toon"}function vn(e){let t=0;for(;e[t]===`
35
+ `))}return n}function _o(e){let t=za(e.options??{},e.autoShort??!1),n=Ia(e.separators??wo);return{schema:e,parse(r){return Va(r,e,t,n)},help(){return Ua(e,e.formatter)}}}function Va(e,t,n,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=t.positional??[],a=0,c=!1;for(;a<e.length;){let u=e[a];if(t.stopEarly&&i>0){o.rest=e.slice(a);break}if(u==="--"&&!c){c=!0,a++;continue}if(c){if(i<l.length){let p=l[i];if(p.variadic){let h=[];for(;a<e.length;){let y=e[a];h.push(p.type?ue(y,p.type):y),a++}o.positional[p.name]=h,i++}else{let h=p.type?ue(u,p.type):u;o.positional[p.name]=h,i++,a++}}else t.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(u)),a++;continue}if(u.startsWith("--")){a=qa(u,a,e,o,n,t);continue}if(u.startsWith("-")&&u.length>1&&!ed(u)){a=Ga(u,a,e,o,n,t);continue}let f=Ba(u,r);if(f){let{key:p,value:h,config:y}=f,w=o,b=w[y.to]??(w[y.to]={});b[p]=y.typed?bo(h):se(h),a++;continue}if(i<l.length){let p=l[i];if(p.variadic){let y=[];for(;a<e.length&&!e[a].startsWith("-");){let w=e[a];y.push(p.type?ue(w,p.type):w),a++}o.positional[p.name]=y,i++;continue}let h=p.type?ue(u,p.type):u;o.positional[p.name]=h,i++}else t.allowUnknown!==!1?o.rest.push(u):o.errors.push(`Unexpected positional argument: ${u}`);a++}return Ya(o,t,n),Za(o,t,l),Xa(o,t,n),o}function Ba(e,t){if($a.test(e))return null;for(let n of t){if(n.prefix&&e.startsWith(n.separator)){let o=e.slice(n.separator.length),s=o.indexOf(":");if(s>0){let i=o.slice(0,s),l=o.slice(s+1);if(Ja(i))return{key:i,value:l,config:n}}continue}let r=e.indexOf(n.separator);if(r>0){let o=e.slice(0,r),s=e.slice(r+n.separator.length);if(Ka(o,s,n))return{key:o,value:s,config:n}}}return null}function Ja(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function Ka(e,t,n){return e?n.separator===":"?e.includes("/")||e.includes(".")||/^\d+$/.test(t)?!1:/^[A-Z][a-zA-Z0-9-]*$/.test(e):!((n.separator==="="||n.separator===":=")&&e.includes("/")):!1}function qa(e,t,n,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,t+1}if(i.includes("=")){let a=i.indexOf("="),c=i.slice(0,a),u=i.slice(a+1);return kt(c,u,t+1,r,o,s)}let l=o.get(i);if(l){if(l.type!=="boolean"){let a=n[t+1];return Ge(a)?kt(l.name,a,t+2,r,o,s):(r.errors.push(`Option --${i} requires a value`),t+1)}return r.options[l.name]=!0,t+1}return s.strict?r.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(r.options[i]=!0),t+1}function Ga(e,t,n,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=yn(a,o);return u?kt(u.name,c,t+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=yt(se(c))),t+1)}if(i.length===1){let l=yn(i,o);if(l){if(l.type!=="boolean"){let a=n[t+1];return Ge(a)?kt(l.name,a,t+2,r,o,s):(r.errors.push(`Option -${i} requires a value`),t+1)}return r.options[l.name]=!0,t+1}if(s.strict)r.errors.push(`Unknown option: -${i}`);else if(s.allowUnknown!==!1){let a=n[t+1];if(Ge(a))return r.options[i]=yt(se(a)),t+2;r.options[i]=!0}return t+1}for(let l of i){let a=yn(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 t+1}function kt(e,t,n,r,o,s){let i=o.get(e);if(i){if(i.choices){let a=i.type?ue(se(t),i.type):se(t);if(!i.choices.includes(a))return r.errors.push(`Invalid value for '${e}': '${t}'. Allowed: ${i.choices.join(", ")}`),n}let l=i.type?ue(se(t),i.type):se(t);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]=yt(se(t)));return n}function za(e,t=!1){let n=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??"";t&&!l&&(l=Qa(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};n.set(s,a);for(let c of a.aliases)n.set(c,a)}return n}function Qa(e,t){for(let n of e){if(!/[a-zA-Z]/.test(n))continue;let r=n.toLowerCase();if(!t.has(r))return r;let o=n.toUpperCase();if(!t.has(o))return o}return""}function yn(e,t){for(let n of t.values())if(n.short===e||n.aliases.includes(e))return n}function Ya(e,t,n){for(let r of n.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?ue(o,r.type):o}else r.default!==void 0&&(e.options[r.name]=r.default);for(let r of t.positional??[])e.positional[r.name]===void 0&&r.default!==void 0&&(e.positional[r.name]=r.default)}function Za(e,t,n){if(t.options)for(let[r,o]of Object.entries(t.options))o.required&&e.options[r]===void 0&&e.errors.push(`Missing required option: --${r}`);for(let r of n)r.required&&e.positional[r.name]===void 0&&e.errors.push(`Missing required argument: <${r.name}>`)}function Xa(e,t,n){for(let r of n.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 t.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 ed(e){return/^-\d+(\.\d+)?$/.test(e)}var kn=class extends Error{flag;known;constructor(t,n){super(`unknown flag '${t}'; expected one of: ${n.join(", ")}`),this.name="UnknownFlagError",this.flag=t,this.known=n}};function td(e){let t={};for(let[n,r]of Object.entries(e))t[n]={type:r.kind==="boolean"?"boolean":"string",...n.length===1?{short:n}:{},...r.aliases===void 0?{}:{aliases:r.aliases}};return t}function nd(e,t){let n=new Map;for(let[o,s]of Object.entries(t))if(!(s.kind!=="value"||s.type!=="array")){n.set(o,o);for(let i of s.aliases??[])n.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=n.get(i[1]);if(l===void 0)continue;let a=i[2];if(a===void 0&&Ge(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 pe(e,t,n={}){let o=_o({options:td(t),separators:{},allowUnknown:!0}).parse([...e]),s={},i=nd(e,t),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(n.unknownFlags==="error"){let a=new Set(Object.keys(t));for(let c of Object.keys(o.options))if(!a.has(c))throw new kn(c.length===1?`-${c}`:`--${c}`,Object.keys(t).map(u=>u.length===1?`-${u}`:`--${u}`))}for(let[a,c]of Object.entries(t)){let u=o.options[a];u!==void 0&&(c.kind==="boolean"?s[a]=u:c.type==="array"?s[a]=(i.get(a)??[]).map(f=>c.coerce(f)):s[a]=c.coerce(String(u)))}return{values:s,positionals:o.rest}}var Rn=class extends Error{token;known;constructor(t,n){super(`unknown command '${t}'; expected one of: ${n.join(", ")}`),this.name="UnknownCommandError",this.token=t,this.known=n}};function vo(e,t){let[n,...r]=e;if(n!==void 0){for(let[s,i]of Object.entries(t.commands))if(n===s||(i.aliases??[]).includes(n))return{command:s,args:r};if(t.errorOnUnknownCommand&&!n.startsWith("-"))throw new Rn(n,Object.keys(t.commands))}let o=t.keepArgvOnDefault??!0;return{command:t.default,args:o?[...e]:r}}import{execFileSync as hd}from"node:child_process";import{readFileSync as yd}from"node:fs";import{dirname as Lo,join as kd}from"node:path";import{existsSync as rd,readFileSync as jg}from"node:fs";import{dirname as od,join as sd}from"node:path";function So(e,t){let n=e;for(let r=0;r<16;r++){let o=sd(n,t);if(rd(o))return o;let s=od(n);if(s===n)break;n=s}return null}function id(e){let t=e.indexOf(" #");return(t>=0?e.slice(0,t):e).trim()}function xe(e,t){let n=[];for(let r of e.split(`
36
+ `)){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(;n.length&&n[n.length-1].indent>=l;)n.pop();if(n.push({indent:l,key:a}),c&&n.map(f=>f.key).join(".")===t)return id(c)}}import{createHash as ld}from"node:crypto";var ad="project.name";function Eo(e){let t=xe(e,ad)?.trim();return t===void 0||t===""?void 0:t}var dd=8,jo="project";function Po(e){let t=md(e.gitCommonDir),n=(e.declaredName??"").trim(),r=n!==""?{name:n,source:"declared"}:cd(e.remoteUrl)??{name:ud(e.checkoutPath,t),source:"basename"},o=fd(t??wn(e.checkoutPath));return{name:r.name,slug:`${pd(r.name)}-${o}`,hash:o,source:r.source}}function Oo(e){let t=(e??"").trim();if(t==="")return;let n=t.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),r=/^[^/]*?:(?!\d)(.+)$/.exec(n),s=(r?r[1]:n.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(i=>i.trim()).filter(i=>i!=="");if(s.length!==0)return s.slice(-2).join("/")}function cd(e){let t=Oo(e);return t===void 0?void 0:{name:t,source:"remote"}}function ud(e,t){let n=t===void 0?"":xo(gd(t));if(n!=="")return n;let r=xo(wn(e));return r===""?jo:r}function pd(e){let n=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return n===""?jo:n}function fd(e){return ld("sha256").update(e).digest("hex").slice(0,dd)}function md(e){let t=wn(e??"");return t===""?void 0:t}function wn(e){let t=e.trim().replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t}function xo(e){let t=e.split("/").filter(n=>n!=="");return t[t.length-1]??""}function gd(e){return e.split("/").filter(n=>n!=="").slice(0,-1).join("/")}var Rd=2e3;function Do(e){return wd(e).name}function wd(e){let t=_n(e),n=bn(e,["rev-parse","--absolute-git-dir"])??bn(e,["rev-parse","--git-common-dir"]),r=bn(e,["remote","get-url","origin"]);return Po({checkoutPath:t.root??e,...n!==void 0?{gitCommonDir:n}:{},...r!==void 0?{remoteUrl:r}:{},...t.name!==void 0?{declaredName:t.name}:{}})}function _n(e){let t=So(e,kd(".red","config.yaml"));if(t==null)return{};let n;try{n=yd(t,"utf8")}catch{return{}}let r=Eo(n),o=Lo(Lo(t));return{...r===void 0?{}:{name:r},configText:n,root:o}}function bn(e,t){try{let n=hd("git",[...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Rd}).trim();return n===""?void 0:n}catch{return}}import{randomUUID as Zi}from"node:crypto";import{spawn as Sf}from"node:child_process";import{mkdir as xf,rm as Ef}from"node:fs/promises";import{dirname as jf}from"node:path";import{createHash as vd}from"node:crypto";import{constants as jn}from"node:fs";import{mkdir as Sd,open as xd}from"node:fs/promises";import{createConnection as Ed}from"node:net";import{tmpdir as jd}from"node:os";import{dirname as Pd,join as ze}from"node:path";var bd="toon";function Io(e){return e.trimStart().startsWith("{")?"json":"toon"}function Sn(e){let t=0;for(;e[t]===`
37
37
  `||e[t]==="\r";)t+=1;let n=e.slice(t);if(n==="")return null;let r=Io(n);if(r==="json"){let s=n.indexOf(`
38
38
  `);return s<0?null:{frame:n.slice(0,s),dialect:r,rest:n.slice(s+1)}}let o=n.indexOf(`
39
39
 
40
- `);return o<0?null:{frame:n.slice(0,o+1),dialect:r,rest:n.slice(o+2)}}function Sn(e){let t=Io(e)==="json"?_n:$o,n=t===_n?$o:_n;try{return t(e)}catch(r){try{return n(e)}catch{throw r}}}function _n(e){return JSON.parse(e)}function $o(e){return K(e)}function xn(e,t){if(t==="toon"){let n=_d(e);if(n!==null)return n.endsWith(`
40
+ `);return o<0?null:{frame:n.slice(0,o+1),dialect:r,rest:n.slice(o+2)}}function xn(e){let t=Io(e)==="json"?vn:$o,n=t===vn?$o:vn;try{return t(e)}catch(r){try{return n(e)}catch{throw r}}}function vn(e){return JSON.parse(e)}function $o(e){return K(e)}function En(e,t){if(t==="toon"){let n=_d(e);if(n!==null)return n.endsWith(`
41
41
  `)?`${n}
42
42
  `:`${n}
43
43
 
44
44
  `}return`${JSON.stringify(e)}
45
- `}function _d(e){try{let t=JSON.stringify(e);if(t===void 0)return null;let n=I(JSON.parse(t));return n.trim()===""?null:n}catch{return null}}function To(e,t){return!Ao(e)||!Ao(t)||t.ok!==!1?!1:typeof e.id=="string"&&typeof t.id=="string"&&t.id!==e.id}function Ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var No=new Set;function Wo(e){return No.has(e)?"json":bd}function Mo(e){No.add(e)}var Od=108;async function kt(e,t,n="resident server"){let r=e.wire,o=r??Wo(e.socketPath),s=await Co(e,t,n,o);return r||o==="json"||!To(t,s)?s:(Mo(e.socketPath),await Co(e,t,n,"json"))}async function Co(e,t,n,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=Ed(e.socketPath),a=!1,c="",u=setTimeout(()=>{f(()=>i(new Error(`${n} timed out`))),l.destroy()},o);function f(p){a||(a=!0,clearTimeout(u),p())}l.on("connect",()=>{l.write(xn(t,r))}),l.on("data",p=>{c+=p.toString("utf8");let h=vn(c);h&&(c=h.rest,f(()=>{try{s(Sn(h.frame))}catch(y){i(y)}}),l.end())}),l.on("error",p=>f(()=>i(p))),l.on("close",()=>{a||f(()=>i(new Error(`${n} closed without response`)))})})}function Uo(e,t,n){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=vn(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(xn(l,s.dialect))}catch{}};(async()=>{let l;try{l=Sn(s.frame),await t(l,i)}catch(a){n(a,l,i)}finally{e.end()}})()})}async function Fo(e){await Sd(Pd(e),{recursive:!0,mode:448});try{return await xd(e,En.O_CREAT|En.O_EXCL|En.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function N(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Rt(e){let t=e.env??process.env,n=vd("sha256").update(e.key).digest("hex").slice(0,20),r=t.XDG_RUNTIME_DIR;if(r){let s=jn(r,"red-skills",n);if(jn(s,e.socketFileName).length<Od)return s}let o=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid");return jn(jd(),`red-skills-${o}`,n)}X();import{homedir as Zd}from"node:os";import{join as Tn}from"node:path";import{spawnSync as Xd}from"node:child_process";import{createHash as ec}from"node:crypto";import{existsSync as tc}from"node:fs";import{mkdir as Go,readFile as nc,writeFile as rc}from"node:fs/promises";import{dirname as oc}from"node:path";var Ye="@reddb-io/red-skills",Ud="https://registry.npmjs.org",Fd="canary",Ee=class extends Error{kind;cause;constructor(t,n,r){super(n),this.name="BundleFetchError",this.kind=t,this.cause=r}};function Hd(e,t,n="stable"){return`${e}-${n==="canary"?"canary":t}.bundle.min.mjs`}function vt(e){let{plugin:t,version:n,cacheDir:r,channel:o}=e;return St(r,Hd(t,n,o))}function Vd(e){return e==="dev"?["rsp"]:[]}function Bd(e){return`${e}.bundle.min.mjs`}function Jd(e){return St("dist",Bd(e))}function Kd(e,t="stable"){return`${Ye}@${t==="canary"?Fd:e}`}function qd(e=Ye){return`${Ud}/${e.replace("/","%2F")}`}async function In(e,t){let{plugin:n,version:r,cacheDir:o,channel:s="stable"}=t,i=vt({plugin:n,version:r,cacheDir:o,channel:s}),l=Vd(n),a=l.map(p=>vt({plugin:p,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await Gd(e,a))return i;let c=Kd(r,s),u=St(o,`.staging-${n}-${s==="canary"?"canary":r}`),f;try{f=await e.materialize(c,u)}catch(p){throw qo(p,c)}for(let p of[n,...l]){let h=Jd(p),y=St(f,h);if(!await e.exists(y))throw new Ee("bundle-missing",`npm package ${c} has no ${h}`);let w=p===n?i:vt({plugin:p,version:r,cacheDir:o,channel:s});await e.writeFile(w,await e.readFile(y))}return i}async function Gd(e,t){for(let n of t)if(!await e.exists(n))return!1;return!0}async function Jo(e,t,n=Ye){let r;try{r=await e.fetchText(qd(n))}catch(s){throw qo(s,n)}let o=zd(r);return{sameMajor:Qd(o,t),newest:Yd(o)}}function zd(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.versions;return typeof n!="object"||n===null?[]:Object.keys(n)}function Qd(e,t){let n=An(t);if(n===null)return null;let r=null;for(let o of e)An(o)===n&&(r===null||Ko(o,r)>0)&&(r=o);return r}function Yd(e){let t=null;for(let n of e){let r=String(n).trim();An(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(t===null||Ko(r,t)>0)&&(t=r)}return t}function An(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?Number(t[1]):null}function Ko(e,t){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),r=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());return!n||!r?0:Number(n[1])-Number(r[1])||Number(n[2])-Number(r[2])||Number(n[3])-Number(r[3])}function qo(e,t){let n=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(n)?new Ee("npm-unavailable",`npm is unavailable while resolving ${t}: ${n}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(n)?new Ee("package-missing",`npm could not resolve ${t}: ${n}`,e):new Ee("network",`failed to resolve ${t}: ${n}`,e)}function St(e,t){return e.endsWith("/")?`${e}${t}`:`${e}/${t}`}X();var sc={async materialize(e,t){await Go(t,{recursive:!0});let n=Xd("npm",["install",e,"--prefix",t,"--no-save","--no-audit","--no-fund","--ignore-scripts","--loglevel=error"],{stdio:["ignore","ignore","pipe"],encoding:"utf8"});if(n.error)throw n.error;if(n.status!==0)throw new Error(`npm install ${e} -> ${n.status}: ${(n.stderr||"").trim()}`);return Tn(t,"node_modules",...Ye.split("/"))},async readFile(e){return new Uint8Array(await nc(e))},async writeFile(e,t){await Go(oc(e),{recursive:!0}),await rc(e,t)},async exists(e){return tc(e)},sha256(e){return ec("sha256").update(e).digest("hex")},async fetchText(e){let t=await fetch(e,{redirect:"follow"});if(!t.ok)throw new Error(`GET ${e} -> ${t.status}`);return await t.text()}},ic="redskilled";function lc(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let t=e.XDG_CACHE_HOME||Tn(e.HOME||Zd(),".cache");return Tn(t,"red-skills","bundles")}async function ac(e={},t={},n={}){let r=ie(e,t);if(G(r))return r;let o=n.env??t.env??process.env;try{await In(n.bundleIO??sc,{plugin:ic,version:n.version??"",cacheDir:lc(o)})}catch{return r}return ie(e,t)}async function zo(e={},t={},n={}){let r=await ac(e,t,n);if(G(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(X(),Bo));throw new o(r)}import{randomUUID as Tt}from"node:crypto";import{mkdir as mf,rm as zi}from"node:fs/promises";import{createServer as gf}from"node:net";import{dirname as hf}from"node:path";import{totalmem as dc}from"node:os";function Qo(e){let t=0,n=0,r=0,o=[],s=[];for(let i of e){let l=i.budget??{},a=!1;for(let[c,u]of[[l.memory_high,f=>t+=f],[l.memory_max,f=>n+=f]]){if(c==null)continue;let f=je(c);f==null?a=!0:u(f)}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:t,memory_max_bytes:n,cpu_weight_total:r,unaccounted_workers:o.sort(),unisolated_workers:s.sort()}}function je(e){let t=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!t)return null;let n={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[t[2].toLowerCase()];return Math.round(Number(t[1])*n)}function Yo(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&Number.isInteger(t.worker_count)&&typeof t.memory_high_bytes=="number"&&typeof t.memory_max_bytes=="number"&&typeof t.cpu_weight_total=="number"&&Array.isArray(t.unaccounted_workers)&&Array.isArray(t.unisolated_workers)}var cc="REDSKILLED_MEMORY_CEILING",uc="REDSKILLED_WORKER_CEILING",pc=.7;function Zo(e){let t=e?.memory_max??e?.memory_high;if(t!=null)return je(t)}function Nn(e){let t=0,n=[];for(let r of e){let o=Zo(r.budget);o===null?n.push(r.worker_id):o!==void 0&&(t+=o)}return{worker_count:e.length,memory_bytes:t,unaccounted_workers:n.sort()}}function Xo(e){let{ceiling:t}=e,n=Nn(e.workers),r=Zo(e.budget),o=r===void 0?null:r,s=n.memory_bytes+(r??0),i=n.worker_count+1,l=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",a=`the host is already holding ${n.memory_bytes} bytes across ${n.worker_count} Worker(s)`,c=(u,f)=>({version:1,admitted:!1,verdict:u,reason:f,ceiling:t,consumption:n,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s});return t.worker_count!=null&&i>t.worker_count?c("refused-over-worker-ceiling",`redskilled refused this Worker${l}: it would be Worker ${i} past a host ceiling of ${t.worker_count} Worker(s), and ${a}`):t.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 ${t.memory_bytes} bytes, and ${a}`):t.memory_bytes!=null&&s>t.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 ${t.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 ${t.memory_bytes??"unbounded"} bytes, and ${a}`,ceiling:t,consumption:n,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function es(e=process.env,t=dc()){let n=(e[cc]??"").trim(),r=(e[uc]??"").trim(),o=mc(r);if(n!==""){let s=fc(n,t);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(t*pc),worker_count:o,source:r!==""?"declared":"host-fraction"}}function fc(e,t){let n=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(n))return null;let r=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return r?Math.floor(t*(Number(r[1])/100)):je(e)??void 0}function mc(e){if(e===""||["infinity","none","off","unbounded"].includes(e.toLowerCase()))return null;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:null}import{appendFile as gc,mkdir as hc,open as yc,readFile as kc,stat as Rc,truncate as ts}from"node:fs/promises";import{dirname as wc}from"node:path";var ns="redskilled.events.toonl";function bc(e){let t=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:t.memory_high??null,memory_max:t.memory_max??null,cpu_weight:t.cpu_weight??null,detail:e.detail??null,exit_code:e.exitCode??null,signal:e.signal??null,reason:e.reason??null}}var _c="daemon:";function vc(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${_c}${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 rs(e){let t=mn({trailer:!1}),n=Promise.resolve();async function r(o){let s=n.then(async()=>{await hc(wc(e),{recursive:!0,mode:448}),await Sc(e),await gc(e,t.push(Pc(o)),{encoding:"utf8",mode:384})});return n=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(bc(o)),recordDaemonStop:o=>r(vc(o)),read:()=>xc(e),flush:async()=>{await n}}}async function Sc(e){let t;try{t=(await Rc(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(t===0)return;let n=64*1024,r=await yc(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,t-1),o[0]===10)return;for(let s=t;s>0;s-=n){let i=Math.min(n,s),l=Buffer.alloc(i);await r.read(l,0,i,s-i);let a=l.lastIndexOf(10);if(a>=0){await ts(e,s-i+a+1);return}}await ts(e,0)}finally{await r.close()}}async function xc(e){let t;try{t=await kc(e,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return Ec(t)}function Ec(e){let t=e.split(`
46
- `);return t.pop(),t.length===0?[]:fn(`${t.join(`
45
+ `}function _d(e){try{let t=JSON.stringify(e);if(t===void 0)return null;let n=I(JSON.parse(t));return n.trim()===""?null:n}catch{return null}}function To(e,t){return!Ao(e)||!Ao(t)||t.ok!==!1?!1:typeof e.id=="string"&&typeof t.id=="string"&&t.id!==e.id}function Ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var No=new Set;function Wo(e){return No.has(e)?"json":bd}function Mo(e){No.add(e)}var Od=108;async function Rt(e,t,n="resident server"){let r=e.wire,o=r??Wo(e.socketPath),s=await Co(e,t,n,o);return r||o==="json"||!To(t,s)?s:(Mo(e.socketPath),await Co(e,t,n,"json"))}async function Co(e,t,n,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=Ed(e.socketPath),a=!1,c="",u=setTimeout(()=>{f(()=>i(new Error(`${n} timed out`))),l.destroy()},o);function f(p){a||(a=!0,clearTimeout(u),p())}l.on("connect",()=>{l.write(En(t,r))}),l.on("data",p=>{c+=p.toString("utf8");let h=Sn(c);h&&(c=h.rest,f(()=>{try{s(xn(h.frame))}catch(y){i(y)}}),l.end())}),l.on("error",p=>f(()=>i(p))),l.on("close",()=>{a||f(()=>i(new Error(`${n} closed without response`)))})})}function Uo(e,t,n){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=Sn(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(En(l,s.dialect))}catch{}};(async()=>{let l;try{l=xn(s.frame),await t(l,i)}catch(a){n(a,l,i)}finally{e.end()}})()})}async function Fo(e){await Sd(Pd(e),{recursive:!0,mode:448});try{return await xd(e,jn.O_CREAT|jn.O_EXCL|jn.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function N(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var Ld="/tmp";function wt(e){let t=e.env??process.env,n=vd("sha256").update(e.key).digest("hex").slice(0,20),r=a=>ze(a,e.socketFileName).length<Od,o=t.XDG_RUNTIME_DIR;if(o){let a=ze(o,"red-skills",n);if(r(a))return a}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=ze(`red-skills-${s}`,n),l=ze(jd(),i);return r(l)||process.platform==="win32"?l:ze(Ld,i)}X();import{homedir as Xd}from"node:os";import{join as Tn}from"node:path";import{spawnSync as ec}from"node:child_process";import{createHash as tc}from"node:crypto";import{existsSync as nc}from"node:fs";import{mkdir as Go,readFile as rc,writeFile as oc}from"node:fs/promises";import{dirname as sc}from"node:path";var Ze="@reddb-io/red-skills",Fd="https://registry.npmjs.org",Hd="canary",Ee=class extends Error{kind;cause;constructor(t,n,r){super(n),this.name="BundleFetchError",this.kind=t,this.cause=r}};function Vd(e,t,n="stable"){return`${e}-${n==="canary"?"canary":t}.bundle.min.mjs`}function St(e){let{plugin:t,version:n,cacheDir:r,channel:o}=e;return xt(r,Vd(t,n,o))}function Bd(e){return e==="dev"?["rsp"]:[]}function Jd(e){return`${e}.bundle.min.mjs`}function Kd(e){return xt("dist",Jd(e))}function qd(e,t="stable"){return`${Ze}@${t==="canary"?Hd:e}`}function Gd(e=Ze){return`${Fd}/${e.replace("/","%2F")}`}async function In(e,t){let{plugin:n,version:r,cacheDir:o,channel:s="stable"}=t,i=St({plugin:n,version:r,cacheDir:o,channel:s}),l=Bd(n),a=l.map(p=>St({plugin:p,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await zd(e,a))return i;let c=qd(r,s),u=xt(o,`.staging-${n}-${s==="canary"?"canary":r}`),f;try{f=await e.materialize(c,u)}catch(p){throw qo(p,c)}for(let p of[n,...l]){let h=Kd(p),y=xt(f,h);if(!await e.exists(y))throw new Ee("bundle-missing",`npm package ${c} has no ${h}`);let w=p===n?i:St({plugin:p,version:r,cacheDir:o,channel:s});await e.writeFile(w,await e.readFile(y))}return i}async function zd(e,t){for(let n of t)if(!await e.exists(n))return!1;return!0}async function Jo(e,t,n=Ze){let r;try{r=await e.fetchText(Gd(n))}catch(s){throw qo(s,n)}let o=Qd(r);return{sameMajor:Yd(o,t),newest:Zd(o)}}function Qd(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.versions;return typeof n!="object"||n===null?[]:Object.keys(n)}function Yd(e,t){let n=An(t);if(n===null)return null;let r=null;for(let o of e)An(o)===n&&(r===null||Ko(o,r)>0)&&(r=o);return r}function Zd(e){let t=null;for(let n of e){let r=String(n).trim();An(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(t===null||Ko(r,t)>0)&&(t=r)}return t}function An(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?Number(t[1]):null}function Ko(e,t){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),r=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());return!n||!r?0:Number(n[1])-Number(r[1])||Number(n[2])-Number(r[2])||Number(n[3])-Number(r[3])}function qo(e,t){let n=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(n)?new Ee("npm-unavailable",`npm is unavailable while resolving ${t}: ${n}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(n)?new Ee("package-missing",`npm could not resolve ${t}: ${n}`,e):new Ee("network",`failed to resolve ${t}: ${n}`,e)}function xt(e,t){return e.endsWith("/")?`${e}${t}`:`${e}/${t}`}X();var ic={async materialize(e,t){await Go(t,{recursive:!0});let n=ec("npm",["install",e,"--prefix",t,"--no-save","--no-audit","--no-fund","--ignore-scripts","--loglevel=error"],{stdio:["ignore","ignore","pipe"],encoding:"utf8"});if(n.error)throw n.error;if(n.status!==0)throw new Error(`npm install ${e} -> ${n.status}: ${(n.stderr||"").trim()}`);return Tn(t,"node_modules",...Ze.split("/"))},async readFile(e){return new Uint8Array(await rc(e))},async writeFile(e,t){await Go(sc(e),{recursive:!0}),await oc(e,t)},async exists(e){return nc(e)},sha256(e){return tc("sha256").update(e).digest("hex")},async fetchText(e){let t=await fetch(e,{redirect:"follow"});if(!t.ok)throw new Error(`GET ${e} -> ${t.status}`);return await t.text()}},lc="redskilled";function ac(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let t=e.XDG_CACHE_HOME||Tn(e.HOME||Xd(),".cache");return Tn(t,"red-skills","bundles")}async function dc(e={},t={},n={}){let r=ie(e,t);if(G(r))return r;let o=n.env??t.env??process.env;try{await In(n.bundleIO??ic,{plugin:lc,version:n.version??"",cacheDir:ac(o)})}catch{return r}return ie(e,t)}async function zo(e={},t={},n={}){let r=await dc(e,t,n);if(G(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(X(),Bo));throw new o(r)}import{randomUUID as Nt}from"node:crypto";import{mkdir as gf,rm as zi}from"node:fs/promises";import{createServer as hf}from"node:net";import{dirname as yf}from"node:path";import{totalmem as cc}from"node:os";function Qo(e){let t=0,n=0,r=0,o=[],s=[];for(let i of e){let l=i.budget??{},a=!1;for(let[c,u]of[[l.memory_high,f=>t+=f],[l.memory_max,f=>n+=f]]){if(c==null)continue;let f=je(c);f==null?a=!0:u(f)}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:t,memory_max_bytes:n,cpu_weight_total:r,unaccounted_workers:o.sort(),unisolated_workers:s.sort()}}function je(e){let t=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!t)return null;let n={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[t[2].toLowerCase()];return Math.round(Number(t[1])*n)}function Yo(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&Number.isInteger(t.worker_count)&&typeof t.memory_high_bytes=="number"&&typeof t.memory_max_bytes=="number"&&typeof t.cpu_weight_total=="number"&&Array.isArray(t.unaccounted_workers)&&Array.isArray(t.unisolated_workers)}var uc="REDSKILLED_MEMORY_CEILING",pc="REDSKILLED_WORKER_CEILING",fc=.7;function Zo(e){let t=e?.memory_max??e?.memory_high;if(t!=null)return je(t)}function Nn(e){let t=0,n=[];for(let r of e){let o=Zo(r.budget);o===null?n.push(r.worker_id):o!==void 0&&(t+=o)}return{worker_count:e.length,memory_bytes:t,unaccounted_workers:n.sort()}}function Xo(e){let{ceiling:t}=e,n=Nn(e.workers),r=Zo(e.budget),o=r===void 0?null:r,s=n.memory_bytes+(r??0),i=n.worker_count+1,l=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",a=`the host is already holding ${n.memory_bytes} bytes across ${n.worker_count} Worker(s)`,c=(u,f)=>({version:1,admitted:!1,verdict:u,reason:f,ceiling:t,consumption:n,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s});return t.worker_count!=null&&i>t.worker_count?c("refused-over-worker-ceiling",`redskilled refused this Worker${l}: it would be Worker ${i} past a host ceiling of ${t.worker_count} Worker(s), and ${a}`):t.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 ${t.memory_bytes} bytes, and ${a}`):t.memory_bytes!=null&&s>t.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 ${t.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 ${t.memory_bytes??"unbounded"} bytes, and ${a}`,ceiling:t,consumption:n,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function es(e=process.env,t=cc()){let n=(e[uc]??"").trim(),r=(e[pc]??"").trim(),o=gc(r);if(n!==""){let s=mc(n,t);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(t*fc),worker_count:o,source:r!==""?"declared":"host-fraction"}}function mc(e,t){let n=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(n))return null;let r=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return r?Math.floor(t*(Number(r[1])/100)):je(e)??void 0}function gc(e){if(e===""||["infinity","none","off","unbounded"].includes(e.toLowerCase()))return null;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:null}import{appendFile as hc,mkdir as yc,open as kc,readFile as Rc,stat as wc,truncate as ts}from"node:fs/promises";import{dirname as bc}from"node:path";var ns="redskilled.events.toonl";function _c(e){let t=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:t.memory_high??null,memory_max:t.memory_max??null,cpu_weight:t.cpu_weight??null,detail:e.detail??null,exit_code:e.exitCode??null,signal:e.signal??null,reason:e.reason??null}}var vc="daemon:";function Sc(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${vc}${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 rs(e){let t=gn({trailer:!1}),n=Promise.resolve();async function r(o){let s=n.then(async()=>{await yc(bc(e),{recursive:!0,mode:448}),await xc(e),await hc(e,t.push(Oc(o)),{encoding:"utf8",mode:384})});return n=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(_c(o)),recordDaemonStop:o=>r(Sc(o)),read:()=>Ec(e),flush:async()=>{await n}}}async function xc(e){let t;try{t=(await wc(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(t===0)return;let n=64*1024,r=await kc(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,t-1),o[0]===10)return;for(let s=t;s>0;s-=n){let i=Math.min(n,s),l=Buffer.alloc(i);await r.read(l,0,i,s-i);let a=l.lastIndexOf(10);if(a>=0){await ts(e,s-i+a+1);return}}await ts(e,0)}finally{await r.close()}}async function Ec(e){let t;try{t=await Rc(e,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return jc(t)}function jc(e){let t=e.split(`
46
+ `);return t.pop(),t.length===0?[]:mn(`${t.join(`
47
47
  `)}
48
- `).filter(Oc).map(Dc)}function os(e){let t=new Map;for(let n of e)n.event!=="daemon-stop"&&(n.event==="worker-birth"?t.set(n.worker_id,jc(n)):t.delete(n.worker_id));return[...t.values()]}function jc(e){let t={...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(t).length>0?{budget:t}:{},warnings:[]}}function Pc(e){return{...e}}function Oc(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 Dc(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:ee(e.project_label)??"",pid:Number(e.pid??0),workspace_path:ee(e.workspace_path)??"",log_path:ee(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:ee(e.unit),memory_high:ee(e.memory_high),memory_max:ee(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:ee(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:ee(e.signal),reason:ee(e.reason)}}function ee(e){return e==null||e===""?null:String(e)}function ss(e){let t=[...e.projects].sort((i,l)=>i.project_label.localeCompare(l.project_label)),n=e.backoffUntilMs??null,r=n!=null&&e.nowMs<n,o=[],s=[];for(let i of t){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(n).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 f=Math.max(0,Math.min(Math.max(0,i.target),c)-l);if(f===0){o.push({...u,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${c}, so it asks for none`});continue}o.push({...u,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${c}, so it asks for ${f} more`});for(let p=0;p<f;p+=1)(s[p]??(s[p]=[])).push({project_label:i.project_label,index:l+p,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function is(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function as(e){let t=e.workers.map(Lc),n=[...new Set([...t.map(o=>o.project_label),...e.projects??[]])].filter(o=>o!=="").sort(),r=t.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:t,projects:n},surviving:r,detail:Ac({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:t.length,projects:n.length,surviving:r.length})}}function ds(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 Lc(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 $c(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 Ac(e){let t=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${$c(e.reason)}`;return e.held===0?`${t}; it holds no Workers, so nothing survives the stop`:`${t}; it holds ${ls(e.held,"Worker")} across ${ls(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 ls(e,t){return`${e} ${t}${e===1?"":"s"}`}function Wn(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=t.holding;return t.version===1&&typeof t.running=="boolean"&&typeof t.stopped=="boolean"&&typeof t.reason=="string"&&typeof t.socket_path=="string"&&typeof t.detail=="string"&&(t.daemon_version===null||typeof t.daemon_version=="string")&&(t.pid===null||typeof t.pid=="number")&&n!=null&&Array.isArray(n.workers)&&Array.isArray(n.projects)&&Array.isArray(t.surviving)}import{chmod as Ic,mkdir as Tc,readFile as Nc,rm as Wc,writeFile as Mc}from"node:fs/promises";import{dirname as cs,join as ms}from"node:path";import{tmpdir as us}from"node:os";var Cc="redskilled.machine.claim.toon",Uc="REDSKILLED_MACHINE_DIR",Fc=8,le=class extends Error{constructor(n,r,o){super(Vc(n,r,o));this.claimPath=n;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},ps;function gs(){return ps??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},ps}function Hc(e={machineIdHash:"unknown"}){let t=e.env??process.env,n=t[Uc]?.trim();if(n)return n;let o=(e.platform??process.platform)==="win32"?t.PROGRAMDATA?.trim()||us():us();return ms(o,`redskilled-${e.machineIdHash}`)}function xt(e){return ms(Hc(e),Cc)}function Et(e,t,n={}){let r=n.clock??(()=>new Date().toISOString()),o=n.isPidAlive??N;async function s(){let a;try{a=await Nc(e,"utf8")}catch(u){if(u.code==="ENOENT"||Mn(u))return;throw u}let c=Jc(a);return Kc(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:t.machineIdHash,session_key_hash:t.sessionKeyHash,socket_path:t.socketPath,acquired_at:c,renewed_at:c}}async function l(){try{return await Wc(e,{force:!0}),!0}catch(a){if(Mn(a))return!1;throw a}}return{claimPath:e,read:s,async claim(a){await Tc(cs(e),{recursive:!0,mode:1023})!=null&&await Ic(cs(e),1023).catch(()=>{});let u=!1;for(let f=0;f<Fc;f+=1){let p=i(a,r());try{return await Mc(e,Bc(p),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:u,claim:p}}catch(y){if(y.code!=="EEXIST"){if(Mn(y))return{claimed:!1,reason:"stale-claim-not-reapable"};throw y}}let h=await s();if(!h){if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable"};u=!0;continue}if(fs(h,a,t.socketPath))return{claimed:!0,reaped:u,claim:h};if(await o(h.pid))return{claimed:!1,reason:"held",claim:h};if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable",claim:h};u=!0}return{claimed:!1,reason:"contended"}},async release(a){let c=await s();return!c||!fs(c,a,t.socketPath)?!1:await l()}}}function hs(e,t,n){return{kind:"machine",claim_path:e,owner_uid:n.uid,machine_id_hash:t.machineIdHash,session_key_hash:t.sessionKeyHash,socket_path:t.socketPath}}function ys(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.kind==="machine"&&typeof t.claim_path=="string"&&typeof t.owner_uid=="number"&&typeof t.machine_id_hash=="string"&&typeof t.session_key_hash=="string"&&typeof t.socket_path=="string"}function Vc(e,t,n){let r=n==null?"":` \u2014 held by pid ${n.pid} (uid ${n.uid}) on socket ${JSON.stringify(n.socket_path)}`;return t==="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.`:t==="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 Mn(e){let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"}function fs(e,t,n){return e.pid===t.pid&&e.start_time===t.startTime&&e.socket_path===n}function Bc(e){return`${I(e,{keyedMapCollapse:!0})}
49
- `}function Jc(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{try{return K(t)}catch{return null}}}function Kc(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(t.version!==1||t.scope!=="machine"||!Number.isInteger(t.pid)||t.pid<=0||!Number.isInteger(t.uid))return!1;for(let n of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof t[n]!="string"||t[n].length===0)return!1;return!0}function Cn(e,t){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(t)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((n,r)=>{if(typeof n!="string"||n==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${r} of project ${JSON.stringify(t)} is not`);return n})}function Un(e,t){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(t)}, not ${JSON.stringify(e)}`);let n={};for(let[r,o]of Object.entries(e)){if(r==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(t)} 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(t)} is ${JSON.stringify(o)}`);n[r]=o}return n}var qc=3e5,Gc=.5,Hn=class extends Error{constructor(n){super(`redskilled already holds a registration for project ${JSON.stringify(n.project_label)}, registered at ${n.registered_at} for a target of ${n.target} and standing until ${n.renew_by}: a project contributes one registration, so a second one is refused rather than silently replacing the first`);this.held=n;this.name="RedskilledProjectRegisteredError"}};function ks(e,t){if(t.held!=null)throw new Hn(t.held);let n=Fn(e.project_label,"a project label"),r=Fn(e.selector,"a selector"),o=Cn(e.argv,n),s=Un(e.env,n),i=Fn(e.workspace_path,`a workspace path for project ${JSON.stringify(n)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(n)}, not ${JSON.stringify(e.target)}`);let l=e.renew_within_ms??qc;if(!Number.isFinite(l)||l<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(n)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let a=Date.parse(t.now);if(!Number.isFinite(a))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(t.now)}`);return{version:1,project_label:n,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 jt=class extends Error{constructor(n){super(`redskilled holds no registration for project ${JSON.stringify(n)} 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=n;this.name="RedskilledProjectUnregisteredError"}};function Rs(e,t){let n=Date.parse(t.now);if(!Number.isFinite(n))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(t.now)}`);let r=t.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(t.renew_within_ms)}`);let o=t.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:Cn(t.launch.argv,e.project_label),env:Un(t.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1};return{...e,...o,renew_within_ms:r,renewed_at:new Date(n).toISOString(),renew_by:new Date(n+r).toISOString(),renewals:e.renewals+1}}function ws(e,t){let n=Date.parse(t.now);if(!Number.isFinite(n))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(t.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,t.liveWorkers??0),s=t.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(n+e.renew_within_ms).toISOString(),sustained_at:new Date(n).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 zc(e,t){let n=Date.parse(e.renew_by);return Number.isFinite(n)?t>=n:!1}function bs(e,t){let n=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&t-s<=e.renew_within_ms*Gc;if(r(n))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return r(o)?"self-renewing":"running-on"}function _s(e,t){let n=[],r=[];for(let o of e)(zc(o,t)?r:n).push(o);return{standing:n,lapsed:r}}function Vn(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&typeof t.project_label=="string"&&typeof t.selector=="string"&&Array.isArray(t.argv)&&t.argv.every(n=>typeof n=="string")&&typeof t.workspace_path=="string"&&Number.isInteger(t.target)&&typeof t.registered_at=="string"&&typeof t.renew_within_ms=="number"&&typeof t.renew_by=="string"&&(t.renewed_at===void 0||typeof t.renewed_at=="string")&&(t.renewals===void 0||Number.isInteger(t.renewals))&&(t.env===void 0||Qc(t.env))&&(t.launch_revision===void 0||Number.isInteger(t.launch_revision))&&(t.sustained_at===void 0||typeof t.sustained_at=="string")&&(t.sustains===void 0||Number.isInteger(t.sustains))&&(t.sustained_by===void 0||t.sustained_by==="open-work"||t.sustained_by==="live-worker")}function Qc(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function Fn(e,t){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${t} to register a project, not ${JSON.stringify(e)}`);return e}var Yc={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 vs(e){return`worker-${e}`}function Ss(e){let t=Yc[e.op]??"project-write",n=e.sessionProject??null,r=e.targetProject??null,o={version:1,op:e.op,reach:t,session_project:n,target_project:r};return t==="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`}:t==="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`}:n==null||n===""?{...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===n?{...o,permitted:!0,verdict:"permitted-own-project",reason:`redskilled permitted ${e.op}: the target belongs to project ${JSON.stringify(n)}, 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(n)}: ${r==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(r)}`}. A session reads the whole host and writes only its own project.`}}import{execFileSync as Zc}from"node:child_process";import{readFileSync as Xc,readdirSync as eu}from"node:fs";import{join as tu}from"node:path";function Ze(e){let t=e.budget??{},n=[["MemoryMax",t.memory_max],["MemoryHigh",t.memory_high]];for(let[r,o]of n){if(o==null)continue;let s=je(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function xs(e){let t=[],n=[];for(let r of e.workers){let o=Ze(r);if(o==null){n.push({worker_id:r.worker_id,reason:(r.budget?.memory_max??r.budget?.memory_high)==null?"this Worker declared no memory budget, so the sampler has no ceiling to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let s=e.rss[r.worker_id];if(typeof s!="number"||!Number.isFinite(s)){n.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||t.push(nu(r,o,s))}return{terminations:t,unenforceable:n}}function nu(e,t,n){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:t.name,budget_declared:t.declared,budget_bytes:t.bytes,observed_rss_bytes:n,workspace_path:e.workspace_path,reason:`redskilled terminated ${r}: its tree RSS of ${n} bytes exceeded its ${t.name} budget of ${t.declared} (${t.bytes} bytes). This is a budget termination, not a stall, and the work in ${JSON.stringify(e.workspace_path)} is handed forward.`}}var ru=4096;function Es(e,t={}){let n=t.platform??process.platform,r={rss:{},cpu_seconds:{}};if(e.length===0)return r;let o=ou(n,t);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,f=[a.pid],p=new Set;for(;f.length>0;){let h=f.pop();if(p.has(h))continue;p.add(h);let y=o.get(h);if(y){c+=y.rssBytes,u+=y.cpuSeconds;for(let w of s.get(h)??[])f.push(w)}}i[a.worker_id]=c,l[a.worker_id]=u}return{rss:i,cpu_seconds:l}}function ou(e,t){return t.procRoot!=null||e==="linux"?cu(t.procRoot??"/proc"):t.psTable!=null||e==="darwin"?au(su(t.psTable)):new Map}function su(e){try{return(e??iu)()}catch{return""}}function iu(){return Zc("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var lu=1024;function au(e){let t=new Map;for(let n of e.split(`
50
- `)){let r=n.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=du(r[3]);l!=null&&t.set(o,{pid:o,ppid:s,rssBytes:i*lu,cpuSeconds:l})}return t}function du(e){let t=e.indexOf("-"),n=t<0?0:Number(e.slice(0,t));if(!Number.isFinite(n)||n<0)return null;let r=e.slice(t+1).split(":"),o=n*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 cu(e){let t=new Map,n;try{n=eu(e)}catch{return t}for(let r of n){if(!/^\d+$/.test(r))continue;let o;try{o=Xc(tu(e,r,"stat"),"utf8")}catch{continue}let s=pu(o);s&&t.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*ru,cpuSeconds:s.cpuTicks/uu})}return t}var uu=100;function pu(e){let t=e.lastIndexOf(")");if(t<0)return null;let n=Number(e.slice(0,e.indexOf(" "))),r=e.slice(t+1).trim().split(/\s+/),o=Number(r[1]),s=Number(r[11]),i=Number(r[12]),l=Number(r[21]);return!Number.isSafeInteger(n)||!Number.isSafeInteger(o)||!Number.isFinite(l)||!Number.isFinite(s)||!Number.isFinite(i)?null:{pid:n,ppid:o,rssPages:Math.max(0,l),cpuTicks:Math.max(0,s)+Math.max(0,i)}}var Bn=class extends Error{constructor(n,r,o){super(`redskilled polls every repository with one host token ${JSON.stringify(o)}, and project ${JSON.stringify(n)} 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=n;this.tokenRef=r;this.hostTokenRef=o;this.name="RedskilledSplitCredentialError"}};function Kn(e,t){for(let n of e)if(n.token_ref!=null&&n.token_ref!==t)throw new Bn(n.project_label,n.token_ref,t)}function fu(e,t={now:new Date(0).toISOString()}){hu(e);let n=t.closedWindowMs??6048e5,r=Date.parse(t.now);if(!Number.isFinite(r))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(t.now)}`);let o=new Date(r-Math.max(0,n)).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 f=JSON.stringify(u.owner),p=JSON.stringify(u.name),h=JSON.stringify(`repo:${u.owner}/${u.name} is:closed closed:>=${o}`);return[` ${a}: repository(owner: ${f}, name: ${p}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${c}: search(query: ${h}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
51
- `),aliases:s,closed_since:o}}function mu(e,t,n){let r=Pe(t),o=Pe(r.data),s=Array.isArray(r.errors)?r.errors.map(Pe):[],i=yu(o.rateLimit,s),l=e.aliases.map(({alias:a,search_alias:c,project:u})=>{let f=u.owner+"/"+u.name,p=o[a],h=s.find(y=>js(y.path,a)||js(y.path,c));if(As(p)){let y=Ps(p.open_pull_requests),w=Ps(p.open_issues),b=ku(o[c]);if(y!=null&&w!=null&&b!=null)return{project_label:u.project_label,repository:f,outcome:"counted",counts:{open_pull_requests:y,open_issues:w,recently_closed:b},detail:`counted ${f} for project ${JSON.stringify(u.project_label)}`}}return i.exhausted||$s(h)?{project_label:u.project_label,repository:f,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${f} 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:f,outcome:"unreachable",counts:null,detail:`${f} is not reachable with the host token: ${Jn(h?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:n.fetchedAt,request_count:1,project_count:l.length,rate_limit:i,projects:l}}function gu(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 Os(e){if(e.projects.length===0)return gu(e.now);Kn(e.projects,e.hostTokenRef);let t=fu(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let n=await e.transport(t.query);return mu(t,n,{fetchedAt:e.now})}catch(n){let r=n instanceof Error?n.message:String(n),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 Ds(e){let t=e.stalenessMs??12e4,n=e.activity;if(n==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:t,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(n.fetched_at),s=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,i=s==null||s>t;return{version:1,fetched_at:n.fetched_at,age_ms:s,threshold_ms:t,stale:n.projects.length>0&&i,request_count:n.request_count,rate_limit:n.rate_limit,projects:n.projects.map(l=>({...l,fetched_at:n.fetched_at,age_ms:s,stale:i})),reason:n.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 ${t}ms window`:`fetched ${s}ms ago, within the ${t}ms window`}}function Ls(e){let t=e.endpoint??"https://api.github.com/graphql",n=e.fetchImpl??fetch;return async r=>{let o=await n(t,{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 hu(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 t=new Set;for(let n of e){if(n.project_label===""||n.owner===""||n.name==="")throw new Error("redskilled activity fetch needs a project label and an owner/name for every registered project");if(t.has(n.project_label))throw new Error(`redskilled holds one repository per project, and ${JSON.stringify(n.project_label)} is registered twice`);t.add(n.project_label)}}function yu(e,t){let n=Pe(e),r=typeof n.remaining=="number"&&Number.isFinite(n.remaining)?n.remaining:null,o=typeof n.resetAt=="string"?n.resetAt:null,s=t.some($s);return{remaining:r,reset_at:o,exhausted:s||r===0}}function $s(e){if(e==null)return!1;let t=Jn(e.type),n=Jn(e.message);return t==="RATE_LIMITED"||/rate limit/i.test(n)}function js(e,t){return Array.isArray(e)&&e.includes(t)}function Ps(e){let t=Pe(e);return Number.isInteger(t.totalCount)?t.totalCount:null}function ku(e){let t=Pe(e);return Number.isInteger(t.issueCount)?t.issueCount:null}function Pe(e){return As(e)?e:{}}function As(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jn(e){return typeof e=="string"?e:""}var Ru=3e4;function Is(e){let t=e.stalenessMs??Ru,n=qn(e.now),r=e.sampledAt==null?null:qn(e.sampledAt),o=n==null||r==null?null:Math.max(0,n-r),s=o!=null&&o<=t,i=new Set(e.reattachedWorkerIds??[]),l=e.hostState.workers.map(p=>wu(p,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:n,log:e.logLines?.[p.worker_id],state:i.has(p.worker_id)?"reattached":"running"})),a=l.filter(p=>p.vitals.rss_bytes==null).map(p=>p.worker_id).sort(),c=l.length-a.length,u=l.reduce((p,h)=>p+(h.vitals.rss_bytes??0),0),f=Nn(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:Su({sampledAt:e.sampledAt,ageMs:o,threshold:t,workerCount:l.length,measuredCount:c,unmeasured:a}),host:{worker_count:l.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:f,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:f.memory_bytes/e.ceiling.memory_bytes},projects:vu(l),known_projects:_u(e.hostState),registered_projects:(e.hostState.registrations??[]).map(p=>p.project_label).sort((p,h)=>p.localeCompare(h)),workers:l,repository_activity:Ds({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs})}}function wu(e,t){let n=t.rss[e.worker_id],r=typeof n=="number"&&Number.isFinite(n)?n:null,o=Ze(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=qn(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms:t.nowMs==null||i==null?null:Math.max(0,t.nowMs-i),state:t.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:r,sampled_at:r==null?null:t.sampledAt,age_ms:r==null?null:t.ageMs,fresh:r!=null&&t.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:bu(t.log)}}function bu(e){let t={last_line:null,published_at:null,source:null};return e==null||e.line.trim()===""?t:{last_line:e.line,published_at:e.published_at,source:e.source}}function _u(e){let t=new Set;for(let n of e.registrations??[])t.add(n.project_label);for(let n of e.projects)t.add(n.project_label);return[...t].sort((n,r)=>n.localeCompare(r))}function vu(e){let t=new Map;for(let n of e){let r=t.get(n.project_label)??{workers:0,declared:0,observed:0,measured:0};r.workers+=1,r.declared+=n.budget.bytes??0,r.observed+=n.vitals.rss_bytes??0,r.measured+=n.vitals.rss_bytes==null?0:1,t.set(n.project_label,r)}return[...t.entries()].map(([n,r])=>({project_label:n,worker_count:r.workers,declared_memory_bytes:r.declared,observed_rss_bytes:r.observed,measured_worker_count:r.measured})).sort((n,r)=>n.project_label.localeCompare(r.project_label))}function Su(e){let t={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?{...t,stale:!1,reason:"the host holds no Workers, so there is nothing to measure and nothing to age"}:e.sampledAt==null||e.ageMs==null?{...t,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?{...t,stale:!0,reason:`this answer is stale: its measurement is ${e.ageMs}ms old, past the ${e.threshold}ms staleness window`}:{...t,stale:!1,reason:`measured ${e.ageMs}ms ago, within the ${e.threshold}ms staleness window`}}function qn(e){let t=Date.parse(e);return Number.isFinite(t)?t:null}var Pt=1;async function Xe(e,t){return await kt(e,t,"redskilled daemon")}function Ts(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&typeof t.line=="string"&&Array.isArray(t.lines)&&t.lines.every(n=>typeof n=="string")&&typeof t.verbose=="boolean"&&(t.mode==="local"||t.mode==="global")&&(t.project===null||typeof t.project=="string")&&typeof t.detail=="string"&&(t.project_match===void 0||typeof t.project_match=="string")&&typeof t.degraded=="boolean"&&typeof t.stale=="boolean"&&typeof t.generated_at=="string"}function Ns(e){let t=[...e.workers??[]],n=new Map;for(let r of t)n.set(r.project_label,(n.get(r.project_label)??0)+1);return{version:1,protocol_version:Pt,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:t,projects:[...n.entries()].map(([r,o])=>({project_label:r,worker_count:o})).sort((r,o)=>r.project_label.localeCompare(o.project_label)),registrations:Eu(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:Qo(t),upgrade:ju(e)}}function Eu(e){let t=e.now==null?Number.NaN:Date.parse(e.now),n=Number.isFinite(t),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,...n?{renewal:bs(s,t)}:{},...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 ju(e){let t=e.daemonVersion,n=e.published?.version??null,r=e.published?.majorHold??null;return{running_version:t,published_version:n,published_unknown:+(n===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 Ws(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&typeof t.protocol_version=="number"&&typeof t.daemon_version=="string"&&typeof t.machine_id_hash=="string"&&typeof t.session_key_hash=="string"&&Number.isInteger(t.pid)&&typeof t.started_at=="string"&&Array.isArray(t.workers)&&Array.isArray(t.projects)&&Yo(t.budget_accounting)&&(t.scope===void 0||ys(t.scope))&&(t.registrations===void 0||Array.isArray(t.registrations)&&t.registrations.every(Vn))&&(t.upgrade===void 0||Pu(t.upgrade))}function Pu(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.running_version=="string"&&(t.published_version===null||typeof t.published_version=="string")&&typeof t.published_unknown=="number"&&typeof t.newer_published=="number"&&(t.replacement==="none"||t.replacement==="pending"||t.replacement==="in-progress")&&(t.checked_at===null||typeof t.checked_at=="string")&&(t.newest_published_version===void 0||t.newest_published_version===null||typeof t.newest_published_version=="string")&&(t.major_held===void 0||typeof t.major_held=="number")&&(t.checks===void 0||typeof t.checks=="number")&&(t.hold_reason===void 0||t.hold_reason===null||typeof t.hold_reason=="string")&&(t.major_hold===void 0||t.major_hold===null||Ou(t.major_hold))}function Ou(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.version=="string"&&Number.isInteger(t.running_major)&&Number.isInteger(t.held_major)&&typeof t.reason=="string"&&typeof t.action=="string"&&t.action.trim()!==""}import{spawnSync as Lt}from"node:child_process";import{existsSync as Zn}from"node:fs";import{delimiter as Mu,join as qs}from"node:path";import{join as Ms}from"node:path";import{existsSync as Du}from"node:fs";import{createRequire as Lu}from"node:module";var Cs="redskilled-job-object.node",me=100;function Oe(e){return{available:!1,reason:e}}function $u(e,t,n){return[Ms(n,"prebuilds",`${e}-${t}`,Cs),Ms(n,"native","build","Release",Cs)]}function Us(e={}){let t=e.platform??process.platform,n=e.arch??process.arch;if(t!=="win32")return Oe(`Job Object placement is the Windows backend (platform=${t}), so there is no native reach to load here`);let r=e.packageRoot??Iu(),o=e.exists??Du,s=$u(t,n,r),i=s.find(c=>o(c));if(i==null)return Oe(`no Job Object addon was found for ${t}-${n} (looked in ${s.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let l=e.requireFn??Lu(import.meta.url),a;try{a=l(i)}catch(c){return Oe(`the Job Object addon at ${i} could not be loaded: ${c instanceof Error?c.message:String(c)}`)}return Au(a)?{available:!0,binding:a}:Oe(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function Au(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Iu(){return new URL("..",import.meta.url).pathname}function Fs(e){let t=e??{},n=[],r=Tu(t);r==null&&(t.memory_max??t.memory_high)!=null&&n.push("the declared memory budget could not be reduced to bytes, so the job carries no memory ceiling");let o;return t.cpu_weight!=null&&(t.cpu_weight<me?o=Math.max(1,Math.min(100,Math.round(t.cpu_weight))):n.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${me}, 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,...n.length>0?{note:n.join("; ")}:{}}}function Tu(e){return Ze({budget:e})}var Ot=5,Hs=19;function Gn(e){return{available:!1,reason:e}}var Nu="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 Bs(e,t){let n=e??{},r=[],o;if(!t.canRenice)r.push("nice is not on this host, so no priority control was applied and the Worker competes with interactive work");else if(n.cpu_weight==null)o=Ot;else if(n.cpu_weight<me){let l=Math.round(Hs*(me-n.cpu_weight)/me);o=Math.min(Hs,Math.max(Ot,l))}else o=Ot,r.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${me}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Ot}`);let s=Vs(n.max_processes);s==null&&n.max_processes!=null&&r.push(`max_processes=${n.max_processes} is not a positive whole number, so no ulimit -u is set`);let i=Vs(n.cpu_seconds);return i==null&&n.cpu_seconds!=null&&r.push(`cpu_seconds=${n.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:Nu,...r.length>0?{note:r.join("; ")}:{}}}function Js(e){let{limits:t}=e,n=[];return t.max_processes!=null&&n.push(`ulimit -u ${t.max_processes}`),t.cpu_seconds!=null&&n.push(`ulimit -t ${t.cpu_seconds}`),n.push(t.nice!=null&&e.nice!=null?`exec ${Wu(e.nice)} -n ${t.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",n.join(`
52
- `),e.command,...e.args]}function Ks(e){let t=[];return e.nice!=null?t.push(`the Worker runs at nice ${e.nice} so it yields to interactive work`):t.push("no priority control was applied"),e.max_processes!=null&&t.push(`its processes are capped at ${e.max_processes}`),e.cpu_seconds!=null&&t.push(`its CPU time is capped at ${e.cpu_seconds} seconds`),`macOS placement applied POSIX limits: ${t.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 zn(e){let t=e??{},n=[t.max_processes!=null?"max_processes":null,t.cpu_seconds!=null?"cpu_seconds":null].filter(r=>r!=null);return n.length===0?null:`${n.join(" and ")} ${n.length===1?"is a POSIX rlimit":"are POSIX rlimits"} honoured only by the macOS placement backend, so this placement carries no equivalent`}function Vs(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function Wu(e){return`'${e.replace(/'/g,"'\\''")}'`}var Gs="REDSKILLED_PLACEMENT",Dt="red-worker",Qn="/bin/sh";function zs(e=process.env,t=process.platform){let n=Gn(`POSIX rlimit and priority placement is the macOS backend (platform=${t})`);if(t==="win32")return{platform:t,systemdRun:null,userSession:!1,jobObjects:Us({platform:t}),posix:n};let r=Oe(`Job Object placement is the Windows backend (platform=${t}), so there is no native reach to load here`);if(t==="darwin")return{platform:t,systemdRun:null,userSession:!1,jobObjects:r,posix:Cu(e)};if(t!=="linux")return{platform:t,systemdRun:null,userSession:!1,jobObjects:r,posix:n};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Zn(qs(o,"systemd","private"));return{platform:t,systemdRun:Xs("systemd-run",e),userSession:s,jobObjects:r,posix:n}}function Cu(e){return Zn(Qn)?{available:!0,shell:Qn,nice:Xs("nice",e)}:Gn(`no POSIX shell was found at ${Qn}, so there is nothing to apply rlimits or priority in`)}function Qs(e=process.env){let t=(e[Gs]??"").trim().toLowerCase();return t===""?!0:!["off","false","0","no"].includes(t)}function Uu(e,t,n=Dt){return Ys(e,t,n).replace(/\.service$/,"")}function Ys(e,t,n=Dt){return`${Yn(n,"red-worker",24)}-${Yn(e,"project",32)}-${Yn(t,"worker",32)}.service`}function Zs(e){let t=[...e.args??[]],n=e.budget??{},r=n.memory_high!=null||n.memory_max!=null||n.cpu_weight!=null,o=e.target??{isolation:"transient-unit"},s=c=>({isolated:!1,backend:"none",command:e.command,args:t,cwd:e.workspacePath,warning:c,...r?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(o.isolation==="inherit")return s("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return s(`worker isolation disabled by ${Gs}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return Hu(e,t,r,s);if(e.probes.platform==="darwin")return Fu(e,t,s);if(e.probes.platform!=="linux")return s(`transient-unit placement is the Linux backend (platform=${e.probes.platform}): the Worker is charged to the daemon's own resource group`);if(!e.probes.systemdRun)return s("transient-unit placement unavailable: systemd-run is not on PATH; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");if(!e.probes.userSession)return s("transient-unit placement unavailable: no systemd --user session; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");let i=Ys(e.projectLabel,e.workerId,o.unit_prefix),l=["--user","--collect","--quiet","--wait",`--unit=${i}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&l.push("--pipe"),n.memory_high!=null&&l.push(`--property=MemoryHigh=${n.memory_high}`),n.memory_max!=null&&l.push(`--property=MemoryMax=${n.memory_max}`),n.cpu_weight!=null&&l.push(`--property=CPUWeight=${n.cpu_weight}`);for(let[c,u]of Object.entries(e.env??{}))l.push(`--setenv=${c}=${u}`);let a=zn(e.budget);return{isolated:!0,backend:"transient-unit",unit:i,command:e.probes.systemdRun,args:[...l,"--",e.command,...t],...a!=null?{budgetWarning:a}:{}}}function Fu(e,t,n){let r=e.probes.posix;if(!r.available)return n(`POSIX limit placement unavailable: ${r.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let o=Bs(e.budget,{canRenice:r.nice!=null}),s=e.budget??{},i=s.memory_high!=null||s.memory_max!=null;return{isolated:!1,backend:"posix-limits",command:r.shell,args:Js({limits:o,nice:r.nice,command:e.command,args:t}),cwd:e.workspacePath,posix:o,warning:Ks(o),...i?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+o.memory_ceiling_reason}:{}}}function Hu(e,t,n,r){let o=e.probes.jobObjects;if(!o.available)return r(`Job Object placement unavailable: ${o.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let s=Fs(e.budget),i=Uu(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...t],cwd:e.workspacePath,job:{name:i,limits:s},...Vu(n&&s.note!=null?`${s.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,zn(e.budget))}}function Vu(...e){let t=e.filter(n=>n!=null&&n!=="");return t.length>0?{budgetWarning:t.join("; ")}:{}}function Xs(e,t){for(let n of(t.PATH??"").split(Mu)){if(!n)continue;let r=qs(n,e);if(Zn(r))return r}return null}function Yn(e,t,n){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,n).replace(/-+$/g,"")||t}async function Xn(e,t){let n=[],r=[];for(let o of e){let s=!1;try{s=await t(o)===!0}catch{s=!1}(s?n:r).push(o)}return{alive:n,dead:r}}function ei(e){return e.unit!=null&&e.unit!==""?Bu(e.unit):N(e.pid)}function Bu(e){let t=Lt("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return t.error!=null?!1:t.status===0}var Ju="REDSKILLED_UNIT_DISCOVERY",ti="(unowned)";function ni(e){let t=Lt("systemctl",["--user","show","--property=MainPID","--value",e],{encoding:"utf8"});if(t.error!=null||t.status!==0)return null;let n=Number.parseInt((t.stdout??"").trim(),10);return Number.isInteger(n)&&n>0?n:null}function Ku(e=process.env){let t=(e[Ju]??"").trim().toLowerCase();return t===""?!0:!["off","false","0","no"].includes(t)}function ri(e,t,n=process.env){return Ku(n)&&e===t}function oi(e=Dt){let t=Lt("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return t.error!=null||t.status!==0?[]:(t.stdout??"").split(`
53
- `).map(n=>n.trim().split(/\s+/)[0]??"").filter(n=>n.startsWith(`${e}-`)&&n.endsWith(".service"))}function si(e){let t=new Set(e.held.map(o=>o.unit).filter(o=>o!=null&&o!=="")),n=new Set,r=[];for(let o of e.units)o===""||t.has(o)||n.has(o)||(n.add(o),r.push({worker_id:o.replace(/\.service$/,""),project_label:ti,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 ii(e){return e.project_label.trim()!==""?e:{...e,project_label:ti,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 li(e){if(e.unit!=null&&e.unit!==""){let t=Lt("systemctl",["--user","stop",e.unit],{stdio:"ignore"});return t.error==null&&t.status===0}try{return process.kill(e.pid,"SIGTERM"),!0}catch{return!1}}function qu(e,t=50){if(ui(e),!Number.isInteger(t)||t<=0)throw new Error(`redskilled queue discovery needs a whole, positive batch size, not ${JSON.stringify(t)}`);let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Gu(e,t={}){let n=t.batchSize??50;if(ui(e),e.length>n)throw new Error(`redskilled queue discovery spans at most ${n} 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(`
54
- `),aliases:r}}function zu(e,t){let n=et(t),r=et(n.data),o=Array.isArray(n.errors)?n.errors.map(et):[],s=Yu(r.rateLimit,o);return{projects:e.aliases.map(({alias:l,project:a})=>{let c=Xu(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(f=>Zu(f.path,l));return s.exhausted||pi(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: ${er(u?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function Qu(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 di(e,t,n){return{version:1,fetched_at:t,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: ${n}`}))}}async function ci(e){if(e.projects.length===0)return Qu(e.now);let t=e.batchSize??50,n=qu(e.projects,t),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of n){let i=Gu(s,{batchSize:t});try{let l=await e.transport(i.query),a=zu(i,l);r.push(...a.projects),o=ai(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=ai(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:n.length,project_count:r.length,batch_size:t,rate_limit:o,projects:r}}function ui(e){if(e.length===0)throw new Error("redskilled queue discovery needs at least one registered project");let t=new Set;for(let n of e){if(typeof n.project_label!="string"||n.project_label==="")throw new Error("redskilled queue discovery needs a project label for every registered project");if(typeof n.selector!="string"||n.selector==="")throw new Error(`redskilled queue discovery needs a selector for project ${JSON.stringify(n.project_label)}: a project that names no work has no queue to discover`);if(t.has(n.project_label))throw new Error(`redskilled holds one selector per project, and ${JSON.stringify(n.project_label)} is registered twice`);t.add(n.project_label)}}function ai(e,t){return{remaining:t.remaining==null?e.remaining:e.remaining==null?t.remaining:Math.min(e.remaining,t.remaining),reset_at:t.reset_at??e.reset_at,exhausted:e.exhausted||t.exhausted}}function Yu(e,t){let n=et(e),r=typeof n.remaining=="number"&&Number.isFinite(n.remaining)?n.remaining:null,o=typeof n.resetAt=="string"?n.resetAt:null;return{remaining:r,reset_at:o,exhausted:t.some(pi)||r===0}}function pi(e){return e==null?!1:er(e.type)==="RATE_LIMITED"||/rate limit/i.test(er(e.message))}function Zu(e,t){return Array.isArray(e)&&e.includes(t)}function Xu(e){let t=et(e);return Number.isInteger(t.issueCount)?t.issueCount:null}function et(e){return ep(e)?e:{}}function ep(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function er(e){return typeof e=="string"?e:""}var D={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function fi(e,t=D){let n=lp(e,t),r=sp(e,t),o=ip(e,t),s=ap(e,t,r,n),i=rp(t,r,o),l={detail:"host",line:s};for(let f of i){let p=hp(s,op(f,t,r,o),t.separator);if(l={detail:f,line:p},yp(p)<=t.maxWidth)break}let a=nr(l.line,t.maxWidth),c=t.verbose&&l.detail==="workers"?pp(r,t):[],u=r.length>0?"workers":"host";return{version:1,line:a,lines:[a,...c],verbose:t.verbose,mode:t.mode,project:t.project,project_match:n,detail:l.detail,degraded:l.detail!==u||a!==l.line,stale:e.staleness.stale,generated_at:e.generated_at}}function mi(e){let t=e.options??D,n=nr(np,t.maxWidth);return{version:1,line:n,lines:[n],verbose:t.verbose,mode:t.mode,project:t.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}var tp="!unregistered",np="redskilled unreachable \u2014 Worker state unknown";function rp(e,t,n){let r=[];return t.length>0&&t.length<=e.maxWorkers&&r.push("workers"),e.mode==="global"&&n.length>0&&n.length<=e.maxProjects&&r.push("projects"),r.push("host"),r}function op(e,t,n,r){return e==="workers"?n.map(o=>up(o,t)):e==="projects"?r.map(gp):[]}function sp(e,t){return t.mode==="global"?e.workers:t.project==null?[]:e.workers.filter(n=>n.project_label===t.project)}function ip(e,t){return t.mode==="global"?e.projects:e.projects.filter(n=>n.project_label===t.project)}function lp(e,t){return t.project==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(t.project)?e.registered_projects==null||e.registered_projects.includes(t.project)?"matched":"name-only":"unregistered"}function ap(e,t,n,r){let o=[];return t.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(tr(e,t))):r==="matched"?(o.push(`${t.project} ${n.length}w`),o.push(tr(e,t)),n.length===0&&o.push("idle")):r==="name-only"?(o.push(`${t.project} ${n.length}w`),o.push(tr(e,t)),o.push(tp)):o.push(dp(t.project,r)),e.staleness.stale&&o.push(cp(e)),o.join(" ")}function dp(e,t){return t==="unregistered"?`project unknown \u2014 ${e} is not registered on this host`:"project unknown \u2014 this directory resolved to no project"}function tr(e,t){let n=t.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===t.project).reduce((o,s)=>o+s.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return t.mode==="global"&&r!=null&&r>0?`${ge(n)}/${ge(r)}`:ge(n)}function cp(e){let t=e.staleness.age_ms;return t==null?"!unmeasured":`!stale ${Math.round(t/1e3)}s`}function up(e,t){let n=gi(e,t),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?ge(r):`${ge(r)}/${ge(e.budget.bytes)}`;return`${n} ${o}`}function pp(e,t){let n=[];for(let r of e){let o=mp(r.log.last_line);o!=null&&n.push(nr(` ${fp} ${gi(r,t)}: ${o}`,t.maxWidth))}return n}var fp="\u21B3";function mp(e){if(e==null)return null;let t=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return t===""?null:t}function gi(e,t){return t.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function gp(e){return`${e.project_label} ${e.worker_count}w ${ge(e.observed_rss_bytes)}`}function hp(e,t,n){return[e,...t].join(n)}function yp(e){return[...e].length}function nr(e,t){if(t<=0)return"";let n=[...e];return n.length<=t?e:t===1?"\u2026":`${n.slice(0,t-1).join("")}\u2026`}function ge(e){if(!Number.isFinite(e)||e<=0)return"0B";let t=["B","K","M","G","T"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n>=100||r===0?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")}${t[r]}`}import{randomUUID as hi}from"node:crypto";import{spawn as kp}from"node:child_process";import{closeSync as Rp,mkdirSync as wp,openSync as bp}from"node:fs";import{dirname as _p}from"node:path";var tt=class extends Error{constructor(t){super(t),this.name="RedskilledWorkerSpecError"}},$t=class extends Error{constructor(n,r){super(n);this.admission=r;this.name="RedskilledAdmissionError"}};function vp(e){if(e==null||e.trim()==="")return null;try{return wp(_p(e),{recursive:!0}),bp(e,"a")}catch{return null}}function Sp(e){try{Rp(e)}catch{}}function xp(e){let t=[["project_label",e.project_label],["workspace_path",e.workspace_path],["command",e.command]];for(let[n,r]of t)if(typeof r!="string"||r.trim()==="")throw new tt(`redskilled worker spec is missing ${n}`);if(e.args!=null&&!Array.isArray(e.args))throw new tt("redskilled worker spec args must be an array")}function Ep(e){if(e==null)throw new $t("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new $t(e.reason,e)}function ki(e){let{spec:t,admission:n}=e;Ep(n),xp(t);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(t.worker_id??e.workerId??hi()).trim()||hi(),i=e.probes??zs(r),l=e.openLog===!1?null:vp(t.log_path),a=Zs({workerId:s,projectLabel:t.project_label,workspacePath:t.workspace_path,command:t.command,args:t.args,budget:t.budget,target:t.placement,env:t.env,enabled:e.enabled??Qs(r),probes:i,pipeOutput:l!==null}),u=(e.spawnFn??kp)(a.command,a.args,{...a.cwd!=null?{cwd:a.cwd}:{},detached:!0,stdio:l===null?"ignore":["ignore",l,l],env:a.isolated?{...r}:{...r,...t.env??{}}});if(l!==null&&Sp(l),u.pid==null)throw u.once("error",()=>{}),new tt(`redskilled could not spawn ${JSON.stringify(a.command)} for worker ${s}`);let f=a.job!=null?jp(a,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(w,b)=>{try{f?.job?.close()}catch{}e.onExit?.(s,w,b)}),u.unref();let p=a.job!=null?f?.job!=null:a.isolated,h=[a.warning,f?.warning,a.budgetWarning].filter(w=>w!=null);return{worker:{worker_id:s,project_label:t.project_label,pid:u.pid,started_at:o(),workspace_path:t.workspace_path,...t.log_path!=null?{log_path:t.log_path}:{},isolated:p,...a.unit!=null?{unit:a.unit}:{},...t.budget!=null?{budget:t.budget}:{},warnings:h},admission:n,warnings:h,plan:a,child:u,...f?.job!=null?{job:f.job}:{}}}function jp(e,t,n){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(!t.jobObjects.available)return{warning:`Job Object placement unavailable: ${t.jobObjects.reason}. ${o}`};let s;try{s=t.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(i){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${yi(i)}. ${o}`}}try{s.assign(n)}catch(i){try{s.close()}catch{}return{warning:`Worker pid ${n} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${yi(i)}. ${o}`}}return{job:s}}function yi(e){return e instanceof Error?e.message:String(e)}import{open as Pp,stat as Op}from"node:fs/promises";var Dp=16*1024;async function Ri(e,t=Dp){let n;try{n=(await Op(e)).size}catch{return null}if(n<=0)return null;let r=Math.min(t,n),o;try{let s=await Pp(e,"r");try{let i=Buffer.alloc(r);await s.read(i,0,r,n-r),o=i.toString("utf8")}finally{await s.close()}}catch{return null}return Lp(o)}function Lp(e){let t=e.split(`
55
- `);for(let n=t.length-1;n>=0;n-=1){let r=t[n].replace(/\r$/,"");if(r.trim()!=="")return r}return null}import{spawn as Jp}from"node:child_process";import{existsSync as Kp,readdirSync as qp}from"node:fs";import{dirname as Gp,join as xi,resolve as zp}from"node:path";function U(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])}:null}function rr(e,t){let n=U(e),r=U(t);return!n||!r?0:n.major-r.major||n.minor-r.minor||n.patch-r.patch}var Dy=4*60*60*1e3;X();X();import{spawnSync as $p}from"node:child_process";import{mkdir as Ap,rm as Ip,writeFile as Tp}from"node:fs/promises";import{existsSync as Np}from"node:fs";import{homedir as Wp}from"node:os";import{dirname as Mp,join as or}from"node:path";var De="redskilled.service",sr="REDSKILLED_SUPERVISED",Cp="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function Up(e=process.env){let t=e.XDG_CONFIG_HOME?.trim()||or(e.HOME?.trim()||Wp(),".config");return or(t,"systemd","user")}function ir(e=process.env){return or(Up(e),De)}function wi(e,t={}){let n=t.env??process.env,r=_t(t.override??{},t.entryLookup??{}),o=[...r.args,...fe(e,t.idleMs==null?{}:{idleMs:t.idleMs})];return{unitName:De,unitPath:ir(n),command:r.command,args:o,text:Fp(r.command,o,e)}}function Fp(e,t,n){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${Cp}`,"","[Service]","Type=simple",`ExecStart=${[e,...t].map(Hp).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${sr}=1"`,`Environment="REDSKILLED_SESSION=${bi(n.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
56
- `)}function Hp(e){return/[\s"'\\$%]/.test(e)?`"${bi(e)}"`:e}function bi(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function _i(e,t={}){let n=t.writeFile??Vp,r=t.run??lr,o=[];return await n(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(At("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(At("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function vi(e={}){let t=e.removeFile??Bp,n=e.run??lr,r=ir(e.env??process.env),o=[At("disable",n,["systemctl","--user","disable","--now",De])];return await t(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(At("daemon-reload",n,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function Si(e={}){let t=e.exists??Np,n=e.run??lr,r=ir(e.env??process.env),o=t(r);return{unitName:De,unitPath:r,installed:o,enabled:o&&n(["systemctl","--user","is-enabled",De]).status===0,active:o&&n(["systemctl","--user","is-active",De]).status===0,floor:"auto-spawn"}}function At(e,t,n){let r=t(n),o=(r.stderr??r.stdout??"").trim();return{step:e,argv:n,ok:r.status===0,...o?{detail:o}:{}}}async function Vp(e,t){await Ap(Mp(e),{recursive:!0}),await Tp(e,t,{encoding:"utf8",mode:420})}async function Bp(e){await Ip(e,{force:!0})}function lr(e){let t=$p(e[0],[...e.slice(1)],{encoding:"utf8"});return t.error!=null?{status:null,stderr:t.error.message}:{status:t.status,stdout:t.stdout??"",stderr:t.stderr??""}}var Ei=75,Pi=9e5,ji="redskilled-replacement-entry-unresolved",Qp="REDSKILLED_NO_REGISTRY_PROBE",Oi="REDSKILLED_BORN_BY_REPLACEMENT";function Di(e=process.env){return e[Oi]==="1"}function Li(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function $i(e){let t=e.running.trim();if(nt(t))return null;let n=e.newest?.trim()??"",r=U(n),o=U(t);return r===null||o===null||r.major<=o.major?null:{version:n,running_major:o.major,held_major:r.major,reason:`redskilled ${n} is published and this daemon runs ${t}; 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:Yp(r.major,e.supervised)}}function Yp(e,t){let n=`install the ${e}.x bundle (update this machine's plugin pin), then `;return t?`${n}re-point the unit and restart it: redskilled unit install && systemctl --user restart redskilled.service`:`${n}stop this daemon \u2014 the next client start resolves the newly installed bundle`}function Ai(e){let t=e.running.trim();if(nt(t))return{act:"hold",reason:"local-build"};let n=e.published?.trim()??"";return!n||U(n)===null?{act:"hold",reason:"published-unknown"}:rr(n,t)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:n,via:e.supervised?"supervisor-exit":"self-spawn"}}function nt(e){let t=e.trim();return U(t)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(t)}function Ii(e=process.env){return e[sr]==="1"}var ar=class extends Error{code=ji;searched;constructor(t,n){super(`${ji}: the published redskilled bundle ${t} exists on no reachable path and the version-pinned dispatch is disabled
48
+ `).filter(Lc).map(Dc)}function os(e){let t=new Map;for(let n of e)n.event!=="daemon-stop"&&(n.event==="worker-birth"?t.set(n.worker_id,Pc(n)):t.delete(n.worker_id));return[...t.values()]}function Pc(e){let t={...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(t).length>0?{budget:t}:{},warnings:[]}}function Oc(e){return{...e}}function Lc(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 Dc(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:ee(e.project_label)??"",pid:Number(e.pid??0),workspace_path:ee(e.workspace_path)??"",log_path:ee(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:ee(e.unit),memory_high:ee(e.memory_high),memory_max:ee(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:ee(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:ee(e.signal),reason:ee(e.reason)}}function ee(e){return e==null||e===""?null:String(e)}function ss(e){let t=[...e.projects].sort((i,l)=>i.project_label.localeCompare(l.project_label)),n=e.backoffUntilMs??null,r=n!=null&&e.nowMs<n,o=[],s=[];for(let i of t){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(n).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 f=Math.max(0,Math.min(Math.max(0,i.target),c)-l);if(f===0){o.push({...u,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${c}, so it asks for none`});continue}o.push({...u,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${c}, so it asks for ${f} more`});for(let p=0;p<f;p+=1)(s[p]??(s[p]=[])).push({project_label:i.project_label,index:l+p,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function is(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function as(e){let t=e.workers.map($c),n=[...new Set([...t.map(o=>o.project_label),...e.projects??[]])].filter(o=>o!=="").sort(),r=t.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:t,projects:n},surviving:r,detail:Ic({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:t.length,projects:n.length,surviving:r.length})}}function ds(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 $c(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 Ac(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 Ic(e){let t=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Ac(e.reason)}`;return e.held===0?`${t}; it holds no Workers, so nothing survives the stop`:`${t}; it holds ${ls(e.held,"Worker")} across ${ls(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 ls(e,t){return`${e} ${t}${e===1?"":"s"}`}function Wn(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=t.holding;return t.version===1&&typeof t.running=="boolean"&&typeof t.stopped=="boolean"&&typeof t.reason=="string"&&typeof t.socket_path=="string"&&typeof t.detail=="string"&&(t.daemon_version===null||typeof t.daemon_version=="string")&&(t.pid===null||typeof t.pid=="number")&&n!=null&&Array.isArray(n.workers)&&Array.isArray(n.projects)&&Array.isArray(t.surviving)}import{chmod as Tc,mkdir as Nc,readFile as Wc,rm as Mc,writeFile as Cc}from"node:fs/promises";import{dirname as cs,join as ms}from"node:path";import{tmpdir as us}from"node:os";var Uc="redskilled.machine.claim.toon",Fc="REDSKILLED_MACHINE_DIR",Hc=8,le=class extends Error{constructor(n,r,o){super(Bc(n,r,o));this.claimPath=n;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},ps;function gs(){return ps??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},ps}function Vc(e={machineIdHash:"unknown"}){let t=e.env??process.env,n=t[Fc]?.trim();if(n)return n;let o=(e.platform??process.platform)==="win32"?t.PROGRAMDATA?.trim()||us():us();return ms(o,`redskilled-${e.machineIdHash}`)}function Et(e){return ms(Vc(e),Uc)}function jt(e,t,n={}){let r=n.clock??(()=>new Date().toISOString()),o=n.isPidAlive??N;async function s(){let a;try{a=await Wc(e,"utf8")}catch(u){if(u.code==="ENOENT"||Mn(u))return;throw u}let c=Kc(a);return qc(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:t.machineIdHash,session_key_hash:t.sessionKeyHash,socket_path:t.socketPath,acquired_at:c,renewed_at:c}}async function l(){try{return await Mc(e,{force:!0}),!0}catch(a){if(Mn(a))return!1;throw a}}return{claimPath:e,read:s,async claim(a){await Nc(cs(e),{recursive:!0,mode:1023})!=null&&await Tc(cs(e),1023).catch(()=>{});let u=!1;for(let f=0;f<Hc;f+=1){let p=i(a,r());try{return await Cc(e,Jc(p),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:u,claim:p}}catch(y){if(y.code!=="EEXIST"){if(Mn(y))return{claimed:!1,reason:"stale-claim-not-reapable"};throw y}}let h=await s();if(!h){if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable"};u=!0;continue}if(fs(h,a,t.socketPath))return{claimed:!0,reaped:u,claim:h};if(await o(h.pid))return{claimed:!1,reason:"held",claim:h};if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable",claim:h};u=!0}return{claimed:!1,reason:"contended"}},async release(a){let c=await s();return!c||!fs(c,a,t.socketPath)?!1:await l()}}}function hs(e,t,n){return{kind:"machine",claim_path:e,owner_uid:n.uid,machine_id_hash:t.machineIdHash,session_key_hash:t.sessionKeyHash,socket_path:t.socketPath}}function ys(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.kind==="machine"&&typeof t.claim_path=="string"&&typeof t.owner_uid=="number"&&typeof t.machine_id_hash=="string"&&typeof t.session_key_hash=="string"&&typeof t.socket_path=="string"}function Bc(e,t,n){let r=n==null?"":` \u2014 held by pid ${n.pid} (uid ${n.uid}) on socket ${JSON.stringify(n.socket_path)}`;return t==="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.`:t==="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 Mn(e){let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"}function fs(e,t,n){return e.pid===t.pid&&e.start_time===t.startTime&&e.socket_path===n}function Jc(e){return`${I(e,{keyedMapCollapse:!0})}
49
+ `}function Kc(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{try{return K(t)}catch{return null}}}function qc(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(t.version!==1||t.scope!=="machine"||!Number.isInteger(t.pid)||t.pid<=0||!Number.isInteger(t.uid))return!1;for(let n of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof t[n]!="string"||t[n].length===0)return!1;return!0}function Cn(e,t){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(t)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((n,r)=>{if(typeof n!="string"||n==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${r} of project ${JSON.stringify(t)} is not`);return n})}function Un(e,t){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(t)}, not ${JSON.stringify(e)}`);let n={};for(let[r,o]of Object.entries(e)){if(r==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(t)} 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(t)} is ${JSON.stringify(o)}`);n[r]=o}return n}var Gc=3e5,zc=.5,Hn=class extends Error{constructor(n){super(`redskilled already holds a registration for project ${JSON.stringify(n.project_label)}, registered at ${n.registered_at} for a target of ${n.target} and standing until ${n.renew_by}: a project contributes one registration, so a second one is refused rather than silently replacing the first`);this.held=n;this.name="RedskilledProjectRegisteredError"}};function ks(e,t){if(t.held!=null)throw new Hn(t.held);let n=Fn(e.project_label,"a project label"),r=Fn(e.selector,"a selector"),o=Cn(e.argv,n),s=Un(e.env,n),i=Fn(e.workspace_path,`a workspace path for project ${JSON.stringify(n)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(n)}, not ${JSON.stringify(e.target)}`);let l=e.renew_within_ms??Gc;if(!Number.isFinite(l)||l<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(n)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let a=Date.parse(t.now);if(!Number.isFinite(a))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(t.now)}`);return{version:1,project_label:n,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 Pt=class extends Error{constructor(n){super(`redskilled holds no registration for project ${JSON.stringify(n)} 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=n;this.name="RedskilledProjectUnregisteredError"}};function Rs(e,t){let n=Date.parse(t.now);if(!Number.isFinite(n))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(t.now)}`);let r=t.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(t.renew_within_ms)}`);let o=t.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:Cn(t.launch.argv,e.project_label),env:Un(t.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1};return{...e,...o,renew_within_ms:r,renewed_at:new Date(n).toISOString(),renew_by:new Date(n+r).toISOString(),renewals:e.renewals+1}}function ws(e,t){let n=Date.parse(t.now);if(!Number.isFinite(n))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(t.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,t.liveWorkers??0),s=t.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(n+e.renew_within_ms).toISOString(),sustained_at:new Date(n).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 Qc(e,t){let n=Date.parse(e.renew_by);return Number.isFinite(n)?t>=n:!1}function bs(e,t){let n=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&t-s<=e.renew_within_ms*zc;if(r(n))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return r(o)?"self-renewing":"running-on"}function _s(e,t){let n=[],r=[];for(let o of e)(Qc(o,t)?r:n).push(o);return{standing:n,lapsed:r}}function Vn(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&typeof t.project_label=="string"&&typeof t.selector=="string"&&Array.isArray(t.argv)&&t.argv.every(n=>typeof n=="string")&&typeof t.workspace_path=="string"&&Number.isInteger(t.target)&&typeof t.registered_at=="string"&&typeof t.renew_within_ms=="number"&&typeof t.renew_by=="string"&&(t.renewed_at===void 0||typeof t.renewed_at=="string")&&(t.renewals===void 0||Number.isInteger(t.renewals))&&(t.env===void 0||Yc(t.env))&&(t.launch_revision===void 0||Number.isInteger(t.launch_revision))&&(t.sustained_at===void 0||typeof t.sustained_at=="string")&&(t.sustains===void 0||Number.isInteger(t.sustains))&&(t.sustained_by===void 0||t.sustained_by==="open-work"||t.sustained_by==="live-worker")}function Yc(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function Fn(e,t){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${t} to register a project, not ${JSON.stringify(e)}`);return e}var Zc={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 vs(e){return`worker-${e}`}function Ss(e){let t=Zc[e.op]??"project-write",n=e.sessionProject??null,r=e.targetProject??null,o={version:1,op:e.op,reach:t,session_project:n,target_project:r};return t==="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`}:t==="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`}:n==null||n===""?{...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===n?{...o,permitted:!0,verdict:"permitted-own-project",reason:`redskilled permitted ${e.op}: the target belongs to project ${JSON.stringify(n)}, 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(n)}: ${r==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(r)}`}. A session reads the whole host and writes only its own project.`}}import{execFileSync as Xc}from"node:child_process";import{readFileSync as eu,readdirSync as tu}from"node:fs";import{join as nu}from"node:path";function Xe(e){let t=e.budget??{},n=[["MemoryMax",t.memory_max],["MemoryHigh",t.memory_high]];for(let[r,o]of n){if(o==null)continue;let s=je(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function xs(e){let t=[],n=[];for(let r of e.workers){let o=Xe(r);if(o==null){n.push({worker_id:r.worker_id,reason:(r.budget?.memory_max??r.budget?.memory_high)==null?"this Worker declared no memory budget, so the sampler has no ceiling to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let s=e.rss[r.worker_id];if(typeof s!="number"||!Number.isFinite(s)){n.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||t.push(ru(r,o,s))}return{terminations:t,unenforceable:n}}function ru(e,t,n){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:t.name,budget_declared:t.declared,budget_bytes:t.bytes,observed_rss_bytes:n,workspace_path:e.workspace_path,reason:`redskilled terminated ${r}: its tree RSS of ${n} bytes exceeded its ${t.name} budget of ${t.declared} (${t.bytes} bytes). This is a budget termination, not a stall, and the work in ${JSON.stringify(e.workspace_path)} is handed forward.`}}var ou=4096;function Es(e,t={}){let n=t.platform??process.platform,r={rss:{},cpu_seconds:{}};if(e.length===0)return r;let o=su(n,t);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,f=[a.pid],p=new Set;for(;f.length>0;){let h=f.pop();if(p.has(h))continue;p.add(h);let y=o.get(h);if(y){c+=y.rssBytes,u+=y.cpuSeconds;for(let w of s.get(h)??[])f.push(w)}}i[a.worker_id]=c,l[a.worker_id]=u}return{rss:i,cpu_seconds:l}}function su(e,t){return t.procRoot!=null||e==="linux"?uu(t.procRoot??"/proc"):t.psTable!=null||e==="darwin"?du(iu(t.psTable)):new Map}function iu(e){try{return(e??lu)()}catch{return""}}function lu(){return Xc("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var au=1024;function du(e){let t=new Map;for(let n of e.split(`
50
+ `)){let r=n.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=cu(r[3]);l!=null&&t.set(o,{pid:o,ppid:s,rssBytes:i*au,cpuSeconds:l})}return t}function cu(e){let t=e.indexOf("-"),n=t<0?0:Number(e.slice(0,t));if(!Number.isFinite(n)||n<0)return null;let r=e.slice(t+1).split(":"),o=n*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 uu(e){let t=new Map,n;try{n=tu(e)}catch{return t}for(let r of n){if(!/^\d+$/.test(r))continue;let o;try{o=eu(nu(e,r,"stat"),"utf8")}catch{continue}let s=fu(o);s&&t.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*ou,cpuSeconds:s.cpuTicks/pu})}return t}var pu=100;function fu(e){let t=e.lastIndexOf(")");if(t<0)return null;let n=Number(e.slice(0,e.indexOf(" "))),r=e.slice(t+1).trim().split(/\s+/),o=Number(r[1]),s=Number(r[11]),i=Number(r[12]),l=Number(r[21]);return!Number.isSafeInteger(n)||!Number.isSafeInteger(o)||!Number.isFinite(l)||!Number.isFinite(s)||!Number.isFinite(i)?null:{pid:n,ppid:o,rssPages:Math.max(0,l),cpuTicks:Math.max(0,s)+Math.max(0,i)}}var Bn=class extends Error{constructor(n,r,o){super(`redskilled polls every repository with one host token ${JSON.stringify(o)}, and project ${JSON.stringify(n)} 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=n;this.tokenRef=r;this.hostTokenRef=o;this.name="RedskilledSplitCredentialError"}};function Kn(e,t){for(let n of e)if(n.token_ref!=null&&n.token_ref!==t)throw new Bn(n.project_label,n.token_ref,t)}function mu(e,t={now:new Date(0).toISOString()}){yu(e);let n=t.closedWindowMs??6048e5,r=Date.parse(t.now);if(!Number.isFinite(r))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(t.now)}`);let o=new Date(r-Math.max(0,n)).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 f=JSON.stringify(u.owner),p=JSON.stringify(u.name),h=JSON.stringify(`repo:${u.owner}/${u.name} is:closed closed:>=${o}`);return[` ${a}: repository(owner: ${f}, name: ${p}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${c}: search(query: ${h}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
51
+ `),aliases:s,closed_since:o}}function gu(e,t,n){let r=Pe(t),o=Pe(r.data),s=Array.isArray(r.errors)?r.errors.map(Pe):[],i=ku(o.rateLimit,s),l=e.aliases.map(({alias:a,search_alias:c,project:u})=>{let f=u.owner+"/"+u.name,p=o[a],h=s.find(y=>js(y.path,a)||js(y.path,c));if(As(p)){let y=Ps(p.open_pull_requests),w=Ps(p.open_issues),b=Ru(o[c]);if(y!=null&&w!=null&&b!=null)return{project_label:u.project_label,repository:f,outcome:"counted",counts:{open_pull_requests:y,open_issues:w,recently_closed:b},detail:`counted ${f} for project ${JSON.stringify(u.project_label)}`}}return i.exhausted||$s(h)?{project_label:u.project_label,repository:f,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${f} 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:f,outcome:"unreachable",counts:null,detail:`${f} is not reachable with the host token: ${Jn(h?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:n.fetchedAt,request_count:1,project_count:l.length,rate_limit:i,projects:l}}function hu(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 Os(e){if(e.projects.length===0)return hu(e.now);Kn(e.projects,e.hostTokenRef);let t=mu(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let n=await e.transport(t.query);return gu(t,n,{fetchedAt:e.now})}catch(n){let r=n instanceof Error?n.message:String(n),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 Ls(e){let t=e.stalenessMs??12e4,n=e.activity;if(n==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:t,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(n.fetched_at),s=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,i=s==null||s>t;return{version:1,fetched_at:n.fetched_at,age_ms:s,threshold_ms:t,stale:n.projects.length>0&&i,request_count:n.request_count,rate_limit:n.rate_limit,projects:n.projects.map(l=>({...l,fetched_at:n.fetched_at,age_ms:s,stale:i})),reason:n.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 ${t}ms window`:`fetched ${s}ms ago, within the ${t}ms window`}}function Ds(e){let t=e.endpoint??"https://api.github.com/graphql",n=e.fetchImpl??fetch;return async r=>{let o=await n(t,{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 yu(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 t=new Set;for(let n of e){if(n.project_label===""||n.owner===""||n.name==="")throw new Error("redskilled activity fetch needs a project label and an owner/name for every registered project");if(t.has(n.project_label))throw new Error(`redskilled holds one repository per project, and ${JSON.stringify(n.project_label)} is registered twice`);t.add(n.project_label)}}function ku(e,t){let n=Pe(e),r=typeof n.remaining=="number"&&Number.isFinite(n.remaining)?n.remaining:null,o=typeof n.resetAt=="string"?n.resetAt:null,s=t.some($s);return{remaining:r,reset_at:o,exhausted:s||r===0}}function $s(e){if(e==null)return!1;let t=Jn(e.type),n=Jn(e.message);return t==="RATE_LIMITED"||/rate limit/i.test(n)}function js(e,t){return Array.isArray(e)&&e.includes(t)}function Ps(e){let t=Pe(e);return Number.isInteger(t.totalCount)?t.totalCount:null}function Ru(e){let t=Pe(e);return Number.isInteger(t.issueCount)?t.issueCount:null}function Pe(e){return As(e)?e:{}}function As(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jn(e){return typeof e=="string"?e:""}var wu=3e4;function Is(e){let t=e.stalenessMs??wu,n=qn(e.now),r=e.sampledAt==null?null:qn(e.sampledAt),o=n==null||r==null?null:Math.max(0,n-r),s=o!=null&&o<=t,i=new Set(e.reattachedWorkerIds??[]),l=e.hostState.workers.map(p=>bu(p,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:n,log:e.logLines?.[p.worker_id],state:i.has(p.worker_id)?"reattached":"running"})),a=l.filter(p=>p.vitals.rss_bytes==null).map(p=>p.worker_id).sort(),c=l.length-a.length,u=l.reduce((p,h)=>p+(h.vitals.rss_bytes??0),0),f=Nn(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:xu({sampledAt:e.sampledAt,ageMs:o,threshold:t,workerCount:l.length,measuredCount:c,unmeasured:a}),host:{worker_count:l.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:f,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:f.memory_bytes/e.ceiling.memory_bytes},projects:Su(l),known_projects:vu(e.hostState),registered_projects:(e.hostState.registrations??[]).map(p=>p.project_label).sort((p,h)=>p.localeCompare(h)),workers:l,repository_activity:Ls({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs})}}function bu(e,t){let n=t.rss[e.worker_id],r=typeof n=="number"&&Number.isFinite(n)?n:null,o=Xe(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=qn(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms:t.nowMs==null||i==null?null:Math.max(0,t.nowMs-i),state:t.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:r,sampled_at:r==null?null:t.sampledAt,age_ms:r==null?null:t.ageMs,fresh:r!=null&&t.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:_u(t.log)}}function _u(e){let t={last_line:null,published_at:null,source:null};return e==null||e.line.trim()===""?t:{last_line:e.line,published_at:e.published_at,source:e.source}}function vu(e){let t=new Set;for(let n of e.registrations??[])t.add(n.project_label);for(let n of e.projects)t.add(n.project_label);return[...t].sort((n,r)=>n.localeCompare(r))}function Su(e){let t=new Map;for(let n of e){let r=t.get(n.project_label)??{workers:0,declared:0,observed:0,measured:0};r.workers+=1,r.declared+=n.budget.bytes??0,r.observed+=n.vitals.rss_bytes??0,r.measured+=n.vitals.rss_bytes==null?0:1,t.set(n.project_label,r)}return[...t.entries()].map(([n,r])=>({project_label:n,worker_count:r.workers,declared_memory_bytes:r.declared,observed_rss_bytes:r.observed,measured_worker_count:r.measured})).sort((n,r)=>n.project_label.localeCompare(r.project_label))}function xu(e){let t={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?{...t,stale:!1,reason:"the host holds no Workers, so there is nothing to measure and nothing to age"}:e.sampledAt==null||e.ageMs==null?{...t,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?{...t,stale:!0,reason:`this answer is stale: its measurement is ${e.ageMs}ms old, past the ${e.threshold}ms staleness window`}:{...t,stale:!1,reason:`measured ${e.ageMs}ms ago, within the ${e.threshold}ms staleness window`}}function qn(e){let t=Date.parse(e);return Number.isFinite(t)?t:null}var Ot=1;async function et(e,t){return await Rt(e,t,"redskilled daemon")}function Ts(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&typeof t.line=="string"&&Array.isArray(t.lines)&&t.lines.every(n=>typeof n=="string")&&typeof t.verbose=="boolean"&&(t.mode==="local"||t.mode==="global")&&(t.project===null||typeof t.project=="string")&&typeof t.detail=="string"&&(t.project_match===void 0||typeof t.project_match=="string")&&typeof t.degraded=="boolean"&&typeof t.stale=="boolean"&&typeof t.generated_at=="string"}function Ns(e){let t=[...e.workers??[]],n=new Map;for(let r of t)n.set(r.project_label,(n.get(r.project_label)??0)+1);return{version:1,protocol_version:Ot,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:t,projects:[...n.entries()].map(([r,o])=>({project_label:r,worker_count:o})).sort((r,o)=>r.project_label.localeCompare(o.project_label)),registrations:ju(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:Qo(t),upgrade:Pu(e)}}function ju(e){let t=e.now==null?Number.NaN:Date.parse(e.now),n=Number.isFinite(t),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,...n?{renewal:bs(s,t)}:{},...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 Pu(e){let t=e.daemonVersion,n=e.published?.version??null,r=e.published?.majorHold??null;return{running_version:t,published_version:n,published_unknown:+(n===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 Ws(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&typeof t.protocol_version=="number"&&typeof t.daemon_version=="string"&&typeof t.machine_id_hash=="string"&&typeof t.session_key_hash=="string"&&Number.isInteger(t.pid)&&typeof t.started_at=="string"&&Array.isArray(t.workers)&&Array.isArray(t.projects)&&Yo(t.budget_accounting)&&(t.scope===void 0||ys(t.scope))&&(t.registrations===void 0||Array.isArray(t.registrations)&&t.registrations.every(Vn))&&(t.upgrade===void 0||Ou(t.upgrade))}function Ou(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.running_version=="string"&&(t.published_version===null||typeof t.published_version=="string")&&typeof t.published_unknown=="number"&&typeof t.newer_published=="number"&&(t.replacement==="none"||t.replacement==="pending"||t.replacement==="in-progress")&&(t.checked_at===null||typeof t.checked_at=="string")&&(t.newest_published_version===void 0||t.newest_published_version===null||typeof t.newest_published_version=="string")&&(t.major_held===void 0||typeof t.major_held=="number")&&(t.checks===void 0||typeof t.checks=="number")&&(t.hold_reason===void 0||t.hold_reason===null||typeof t.hold_reason=="string")&&(t.major_hold===void 0||t.major_hold===null||Lu(t.major_hold))}function Lu(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.version=="string"&&Number.isInteger(t.running_major)&&Number.isInteger(t.held_major)&&typeof t.reason=="string"&&typeof t.action=="string"&&t.action.trim()!==""}import{spawnSync as $t}from"node:child_process";import{existsSync as Zn}from"node:fs";import{delimiter as Cu,join as qs}from"node:path";import{join as Ms}from"node:path";import{existsSync as Du}from"node:fs";import{createRequire as $u}from"node:module";var Cs="redskilled-job-object.node",me=100;function Oe(e){return{available:!1,reason:e}}function Au(e,t,n){return[Ms(n,"prebuilds",`${e}-${t}`,Cs),Ms(n,"native","build","Release",Cs)]}function Us(e={}){let t=e.platform??process.platform,n=e.arch??process.arch;if(t!=="win32")return Oe(`Job Object placement is the Windows backend (platform=${t}), so there is no native reach to load here`);let r=e.packageRoot??Tu(),o=e.exists??Du,s=Au(t,n,r),i=s.find(c=>o(c));if(i==null)return Oe(`no Job Object addon was found for ${t}-${n} (looked in ${s.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let l=e.requireFn??$u(import.meta.url),a;try{a=l(i)}catch(c){return Oe(`the Job Object addon at ${i} could not be loaded: ${c instanceof Error?c.message:String(c)}`)}return Iu(a)?{available:!0,binding:a}:Oe(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function Iu(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Tu(){return new URL("..",import.meta.url).pathname}function Fs(e){let t=e??{},n=[],r=Nu(t);r==null&&(t.memory_max??t.memory_high)!=null&&n.push("the declared memory budget could not be reduced to bytes, so the job carries no memory ceiling");let o;return t.cpu_weight!=null&&(t.cpu_weight<me?o=Math.max(1,Math.min(100,Math.round(t.cpu_weight))):n.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${me}, 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,...n.length>0?{note:n.join("; ")}:{}}}function Nu(e){return Xe({budget:e})}var Lt=5,Hs=19;function Gn(e){return{available:!1,reason:e}}var Wu="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 Bs(e,t){let n=e??{},r=[],o;if(!t.canRenice)r.push("nice is not on this host, so no priority control was applied and the Worker competes with interactive work");else if(n.cpu_weight==null)o=Lt;else if(n.cpu_weight<me){let l=Math.round(Hs*(me-n.cpu_weight)/me);o=Math.min(Hs,Math.max(Lt,l))}else o=Lt,r.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${me}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Lt}`);let s=Vs(n.max_processes);s==null&&n.max_processes!=null&&r.push(`max_processes=${n.max_processes} is not a positive whole number, so no ulimit -u is set`);let i=Vs(n.cpu_seconds);return i==null&&n.cpu_seconds!=null&&r.push(`cpu_seconds=${n.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:Wu,...r.length>0?{note:r.join("; ")}:{}}}function Js(e){let{limits:t}=e,n=[];return t.max_processes!=null&&n.push(`ulimit -u ${t.max_processes}`),t.cpu_seconds!=null&&n.push(`ulimit -t ${t.cpu_seconds}`),n.push(t.nice!=null&&e.nice!=null?`exec ${Mu(e.nice)} -n ${t.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",n.join(`
52
+ `),e.command,...e.args]}function Ks(e){let t=[];return e.nice!=null?t.push(`the Worker runs at nice ${e.nice} so it yields to interactive work`):t.push("no priority control was applied"),e.max_processes!=null&&t.push(`its processes are capped at ${e.max_processes}`),e.cpu_seconds!=null&&t.push(`its CPU time is capped at ${e.cpu_seconds} seconds`),`macOS placement applied POSIX limits: ${t.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 zn(e){let t=e??{},n=[t.max_processes!=null?"max_processes":null,t.cpu_seconds!=null?"cpu_seconds":null].filter(r=>r!=null);return n.length===0?null:`${n.join(" and ")} ${n.length===1?"is a POSIX rlimit":"are POSIX rlimits"} honoured only by the macOS placement backend, so this placement carries no equivalent`}function Vs(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function Mu(e){return`'${e.replace(/'/g,"'\\''")}'`}var Gs="REDSKILLED_PLACEMENT",Dt="red-worker",Qn="/bin/sh";function zs(e=process.env,t=process.platform){let n=Gn(`POSIX rlimit and priority placement is the macOS backend (platform=${t})`);if(t==="win32")return{platform:t,systemdRun:null,userSession:!1,jobObjects:Us({platform:t}),posix:n};let r=Oe(`Job Object placement is the Windows backend (platform=${t}), so there is no native reach to load here`);if(t==="darwin")return{platform:t,systemdRun:null,userSession:!1,jobObjects:r,posix:Uu(e)};if(t!=="linux")return{platform:t,systemdRun:null,userSession:!1,jobObjects:r,posix:n};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Zn(qs(o,"systemd","private"));return{platform:t,systemdRun:Xs("systemd-run",e),userSession:s,jobObjects:r,posix:n}}function Uu(e){return Zn(Qn)?{available:!0,shell:Qn,nice:Xs("nice",e)}:Gn(`no POSIX shell was found at ${Qn}, so there is nothing to apply rlimits or priority in`)}function Qs(e=process.env){let t=(e[Gs]??"").trim().toLowerCase();return t===""?!0:!["off","false","0","no"].includes(t)}function Fu(e,t,n=Dt){return Ys(e,t,n).replace(/\.service$/,"")}function Ys(e,t,n=Dt){return`${Yn(n,"red-worker",24)}-${Yn(e,"project",32)}-${Yn(t,"worker",32)}.service`}function Zs(e){let t=[...e.args??[]],n=e.budget??{},r=n.memory_high!=null||n.memory_max!=null||n.cpu_weight!=null,o=e.target??{isolation:"transient-unit"},s=c=>({isolated:!1,backend:"none",command:e.command,args:t,cwd:e.workspacePath,warning:c,...r?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(o.isolation==="inherit")return s("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return s(`worker isolation disabled by ${Gs}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return Vu(e,t,r,s);if(e.probes.platform==="darwin")return Hu(e,t,s);if(e.probes.platform!=="linux")return s(`transient-unit placement is the Linux backend (platform=${e.probes.platform}): the Worker is charged to the daemon's own resource group`);if(!e.probes.systemdRun)return s("transient-unit placement unavailable: systemd-run is not on PATH; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");if(!e.probes.userSession)return s("transient-unit placement unavailable: no systemd --user session; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");let i=Ys(e.projectLabel,e.workerId,o.unit_prefix),l=["--user","--collect","--quiet","--wait",`--unit=${i}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&l.push("--pipe"),n.memory_high!=null&&l.push(`--property=MemoryHigh=${n.memory_high}`),n.memory_max!=null&&l.push(`--property=MemoryMax=${n.memory_max}`),n.cpu_weight!=null&&l.push(`--property=CPUWeight=${n.cpu_weight}`);for(let[c,u]of Object.entries(e.env??{}))l.push(`--setenv=${c}=${u}`);let a=zn(e.budget);return{isolated:!0,backend:"transient-unit",unit:i,command:e.probes.systemdRun,args:[...l,"--",e.command,...t],...a!=null?{budgetWarning:a}:{}}}function Hu(e,t,n){let r=e.probes.posix;if(!r.available)return n(`POSIX limit placement unavailable: ${r.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let o=Bs(e.budget,{canRenice:r.nice!=null}),s=e.budget??{},i=s.memory_high!=null||s.memory_max!=null;return{isolated:!1,backend:"posix-limits",command:r.shell,args:Js({limits:o,nice:r.nice,command:e.command,args:t}),cwd:e.workspacePath,posix:o,warning:Ks(o),...i?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+o.memory_ceiling_reason}:{}}}function Vu(e,t,n,r){let o=e.probes.jobObjects;if(!o.available)return r(`Job Object placement unavailable: ${o.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let s=Fs(e.budget),i=Fu(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...t],cwd:e.workspacePath,job:{name:i,limits:s},...Bu(n&&s.note!=null?`${s.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,zn(e.budget))}}function Bu(...e){let t=e.filter(n=>n!=null&&n!=="");return t.length>0?{budgetWarning:t.join("; ")}:{}}function Xs(e,t){for(let n of(t.PATH??"").split(Cu)){if(!n)continue;let r=qs(n,e);if(Zn(r))return r}return null}function Yn(e,t,n){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,n).replace(/-+$/g,"")||t}async function Xn(e,t){let n=[],r=[];for(let o of e){let s=!1;try{s=await t(o)===!0}catch{s=!1}(s?n:r).push(o)}return{alive:n,dead:r}}function ei(e){return e.unit!=null&&e.unit!==""?Ju(e.unit):N(e.pid)}function Ju(e){let t=$t("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return t.error!=null?!1:t.status===0}var Ku="REDSKILLED_UNIT_DISCOVERY",ti="(unowned)";function ni(e){let t=$t("systemctl",["--user","show","--property=MainPID","--value",e],{encoding:"utf8"});if(t.error!=null||t.status!==0)return null;let n=Number.parseInt((t.stdout??"").trim(),10);return Number.isInteger(n)&&n>0?n:null}function qu(e=process.env){let t=(e[Ku]??"").trim().toLowerCase();return t===""?!0:!["off","false","0","no"].includes(t)}function ri(e,t,n=process.env){return qu(n)&&e===t}function oi(e=Dt){let t=$t("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return t.error!=null||t.status!==0?[]:(t.stdout??"").split(`
53
+ `).map(n=>n.trim().split(/\s+/)[0]??"").filter(n=>n.startsWith(`${e}-`)&&n.endsWith(".service"))}function si(e){let t=new Set(e.held.map(o=>o.unit).filter(o=>o!=null&&o!=="")),n=new Set,r=[];for(let o of e.units)o===""||t.has(o)||n.has(o)||(n.add(o),r.push({worker_id:o.replace(/\.service$/,""),project_label:ti,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 ii(e){return e.project_label.trim()!==""?e:{...e,project_label:ti,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 li(e){if(e.unit!=null&&e.unit!==""){let t=$t("systemctl",["--user","stop",e.unit],{stdio:"ignore"});return t.error==null&&t.status===0}try{return process.kill(e.pid,"SIGTERM"),!0}catch{return!1}}function Gu(e,t=50){if(ui(e),!Number.isInteger(t)||t<=0)throw new Error(`redskilled queue discovery needs a whole, positive batch size, not ${JSON.stringify(t)}`);let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function zu(e,t={}){let n=t.batchSize??50;if(ui(e),e.length>n)throw new Error(`redskilled queue discovery spans at most ${n} 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(`
54
+ `),aliases:r}}function Qu(e,t){let n=tt(t),r=tt(n.data),o=Array.isArray(n.errors)?n.errors.map(tt):[],s=Zu(r.rateLimit,o);return{projects:e.aliases.map(({alias:l,project:a})=>{let c=ep(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(f=>Xu(f.path,l));return s.exhausted||pi(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: ${er(u?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function Yu(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 di(e,t,n){return{version:1,fetched_at:t,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: ${n}`}))}}async function ci(e){if(e.projects.length===0)return Yu(e.now);let t=e.batchSize??50,n=Gu(e.projects,t),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of n){let i=zu(s,{batchSize:t});try{let l=await e.transport(i.query),a=Qu(i,l);r.push(...a.projects),o=ai(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=ai(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:n.length,project_count:r.length,batch_size:t,rate_limit:o,projects:r}}function ui(e){if(e.length===0)throw new Error("redskilled queue discovery needs at least one registered project");let t=new Set;for(let n of e){if(typeof n.project_label!="string"||n.project_label==="")throw new Error("redskilled queue discovery needs a project label for every registered project");if(typeof n.selector!="string"||n.selector==="")throw new Error(`redskilled queue discovery needs a selector for project ${JSON.stringify(n.project_label)}: a project that names no work has no queue to discover`);if(t.has(n.project_label))throw new Error(`redskilled holds one selector per project, and ${JSON.stringify(n.project_label)} is registered twice`);t.add(n.project_label)}}function ai(e,t){return{remaining:t.remaining==null?e.remaining:e.remaining==null?t.remaining:Math.min(e.remaining,t.remaining),reset_at:t.reset_at??e.reset_at,exhausted:e.exhausted||t.exhausted}}function Zu(e,t){let n=tt(e),r=typeof n.remaining=="number"&&Number.isFinite(n.remaining)?n.remaining:null,o=typeof n.resetAt=="string"?n.resetAt:null;return{remaining:r,reset_at:o,exhausted:t.some(pi)||r===0}}function pi(e){return e==null?!1:er(e.type)==="RATE_LIMITED"||/rate limit/i.test(er(e.message))}function Xu(e,t){return Array.isArray(e)&&e.includes(t)}function ep(e){let t=tt(e);return Number.isInteger(t.issueCount)?t.issueCount:null}function tt(e){return tp(e)?e:{}}function tp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function er(e){return typeof e=="string"?e:""}var L={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function fi(e,t=L){let n=ap(e,t),r=ip(e,t),o=lp(e,t),s=dp(e,t,r,n),i=op(t,r,o),l={detail:"host",line:s};for(let f of i){let p=yp(s,sp(f,t,r,o),t.separator);if(l={detail:f,line:p},kp(p)<=t.maxWidth)break}let a=nr(l.line,t.maxWidth),c=t.verbose&&l.detail==="workers"?fp(r,t):[],u=r.length>0?"workers":"host";return{version:1,line:a,lines:[a,...c],verbose:t.verbose,mode:t.mode,project:t.project,project_match:n,detail:l.detail,degraded:l.detail!==u||a!==l.line,stale:e.staleness.stale,generated_at:e.generated_at}}function mi(e){let t=e.options??L,n=nr(rp,t.maxWidth);return{version:1,line:n,lines:[n],verbose:t.verbose,mode:t.mode,project:t.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}var np="!unregistered",rp="redskilled unreachable \u2014 Worker state unknown";function op(e,t,n){let r=[];return t.length>0&&t.length<=e.maxWorkers&&r.push("workers"),e.mode==="global"&&n.length>0&&n.length<=e.maxProjects&&r.push("projects"),r.push("host"),r}function sp(e,t,n,r){return e==="workers"?n.map(o=>pp(o,t)):e==="projects"?r.map(hp):[]}function ip(e,t){return t.mode==="global"?e.workers:t.project==null?[]:e.workers.filter(n=>n.project_label===t.project)}function lp(e,t){return t.mode==="global"?e.projects:e.projects.filter(n=>n.project_label===t.project)}function ap(e,t){return t.project==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(t.project)?e.registered_projects==null||e.registered_projects.includes(t.project)?"matched":"name-only":"unregistered"}function dp(e,t,n,r){let o=[];return t.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(tr(e,t))):r==="matched"?(o.push(`${t.project} ${n.length}w`),o.push(tr(e,t)),n.length===0&&o.push("idle")):r==="name-only"?(o.push(`${t.project} ${n.length}w`),o.push(tr(e,t)),o.push(np)):o.push(cp(t.project,r)),e.staleness.stale&&o.push(up(e)),o.join(" ")}function cp(e,t){return t==="unregistered"?`project unknown \u2014 ${e} is not registered on this host`:"project unknown \u2014 this directory resolved to no project"}function tr(e,t){let n=t.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===t.project).reduce((o,s)=>o+s.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return t.mode==="global"&&r!=null&&r>0?`${ge(n)}/${ge(r)}`:ge(n)}function up(e){let t=e.staleness.age_ms;return t==null?"!unmeasured":`!stale ${Math.round(t/1e3)}s`}function pp(e,t){let n=gi(e,t),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?ge(r):`${ge(r)}/${ge(e.budget.bytes)}`;return`${n} ${o}`}function fp(e,t){let n=[];for(let r of e){let o=gp(r.log.last_line);o!=null&&n.push(nr(` ${mp} ${gi(r,t)}: ${o}`,t.maxWidth))}return n}var mp="\u21B3";function gp(e){if(e==null)return null;let t=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return t===""?null:t}function gi(e,t){return t.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function hp(e){return`${e.project_label} ${e.worker_count}w ${ge(e.observed_rss_bytes)}`}function yp(e,t,n){return[e,...t].join(n)}function kp(e){return[...e].length}function nr(e,t){if(t<=0)return"";let n=[...e];return n.length<=t?e:t===1?"\u2026":`${n.slice(0,t-1).join("")}\u2026`}function ge(e){if(!Number.isFinite(e)||e<=0)return"0B";let t=["B","K","M","G","T"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n>=100||r===0?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")}${t[r]}`}import{randomUUID as hi}from"node:crypto";import{spawn as Rp}from"node:child_process";import{closeSync as wp,mkdirSync as bp,openSync as _p}from"node:fs";import{dirname as vp}from"node:path";var nt=class extends Error{constructor(t){super(t),this.name="RedskilledWorkerSpecError"}},At=class extends Error{constructor(n,r){super(n);this.admission=r;this.name="RedskilledAdmissionError"}};function Sp(e){if(e==null||e.trim()==="")return null;try{return bp(vp(e),{recursive:!0}),_p(e,"a")}catch{return null}}function xp(e){try{wp(e)}catch{}}function Ep(e){let t=[["project_label",e.project_label],["workspace_path",e.workspace_path],["command",e.command]];for(let[n,r]of t)if(typeof r!="string"||r.trim()==="")throw new nt(`redskilled worker spec is missing ${n}`);if(e.args!=null&&!Array.isArray(e.args))throw new nt("redskilled worker spec args must be an array")}function jp(e){if(e==null)throw new At("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new At(e.reason,e)}function ki(e){let{spec:t,admission:n}=e;jp(n),Ep(t);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(t.worker_id??e.workerId??hi()).trim()||hi(),i=e.probes??zs(r),l=e.openLog===!1?null:Sp(t.log_path),a=Zs({workerId:s,projectLabel:t.project_label,workspacePath:t.workspace_path,command:t.command,args:t.args,budget:t.budget,target:t.placement,env:t.env,enabled:e.enabled??Qs(r),probes:i,pipeOutput:l!==null}),u=(e.spawnFn??Rp)(a.command,a.args,{...a.cwd!=null?{cwd:a.cwd}:{},detached:!0,stdio:l===null?"ignore":["ignore",l,l],env:a.isolated?{...r}:{...r,...t.env??{}}});if(l!==null&&xp(l),u.pid==null)throw u.once("error",()=>{}),new nt(`redskilled could not spawn ${JSON.stringify(a.command)} for worker ${s}`);let f=a.job!=null?Pp(a,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(w,b)=>{try{f?.job?.close()}catch{}e.onExit?.(s,w,b)}),u.unref();let p=a.job!=null?f?.job!=null:a.isolated,h=[a.warning,f?.warning,a.budgetWarning].filter(w=>w!=null);return{worker:{worker_id:s,project_label:t.project_label,pid:u.pid,started_at:o(),workspace_path:t.workspace_path,...t.log_path!=null?{log_path:t.log_path}:{},isolated:p,...a.unit!=null?{unit:a.unit}:{},...t.budget!=null?{budget:t.budget}:{},warnings:h},admission:n,warnings:h,plan:a,child:u,...f?.job!=null?{job:f.job}:{}}}function Pp(e,t,n){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(!t.jobObjects.available)return{warning:`Job Object placement unavailable: ${t.jobObjects.reason}. ${o}`};let s;try{s=t.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(i){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${yi(i)}. ${o}`}}try{s.assign(n)}catch(i){try{s.close()}catch{}return{warning:`Worker pid ${n} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${yi(i)}. ${o}`}}return{job:s}}function yi(e){return e instanceof Error?e.message:String(e)}import{open as Op,stat as Lp}from"node:fs/promises";var Dp=16*1024;async function Ri(e,t=Dp){let n;try{n=(await Lp(e)).size}catch{return null}if(n<=0)return null;let r=Math.min(t,n),o;try{let s=await Op(e,"r");try{let i=Buffer.alloc(r);await s.read(i,0,r,n-r),o=i.toString("utf8")}finally{await s.close()}}catch{return null}return $p(o)}function $p(e){let t=e.split(`
55
+ `);for(let n=t.length-1;n>=0;n-=1){let r=t[n].replace(/\r$/,"");if(r.trim()!=="")return r}return null}import{spawn as Kp}from"node:child_process";import{existsSync as qp,readdirSync as Gp}from"node:fs";import{dirname as zp,join as xi,resolve as Qp}from"node:path";function U(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])}:null}function rr(e,t){let n=U(e),r=U(t);return!n||!r?0:n.major-r.major||n.minor-r.minor||n.patch-r.patch}var Dy=4*60*60*1e3;X();X();import{spawnSync as Ap}from"node:child_process";import{mkdir as Ip,rm as Tp,writeFile as Np}from"node:fs/promises";import{existsSync as Wp}from"node:fs";import{homedir as Mp}from"node:os";import{dirname as Cp,join as or}from"node:path";var Le="redskilled.service",sr="REDSKILLED_SUPERVISED",Up="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function Fp(e=process.env){let t=e.XDG_CONFIG_HOME?.trim()||or(e.HOME?.trim()||Mp(),".config");return or(t,"systemd","user")}function ir(e=process.env){return or(Fp(e),Le)}function wi(e,t={}){let n=t.env??process.env,r=vt(t.override??{},t.entryLookup??{}),o=[...r.args,...fe(e,t.idleMs==null?{}:{idleMs:t.idleMs})];return{unitName:Le,unitPath:ir(n),command:r.command,args:o,text:Hp(r.command,o,e)}}function Hp(e,t,n){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${Up}`,"","[Service]","Type=simple",`ExecStart=${[e,...t].map(Vp).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${sr}=1"`,`Environment="REDSKILLED_SESSION=${bi(n.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
56
+ `)}function Vp(e){return/[\s"'\\$%]/.test(e)?`"${bi(e)}"`:e}function bi(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function _i(e,t={}){let n=t.writeFile??Bp,r=t.run??lr,o=[];return await n(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(It("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(It("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function vi(e={}){let t=e.removeFile??Jp,n=e.run??lr,r=ir(e.env??process.env),o=[It("disable",n,["systemctl","--user","disable","--now",Le])];return await t(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(It("daemon-reload",n,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function Si(e={}){let t=e.exists??Wp,n=e.run??lr,r=ir(e.env??process.env),o=t(r);return{unitName:Le,unitPath:r,installed:o,enabled:o&&n(["systemctl","--user","is-enabled",Le]).status===0,active:o&&n(["systemctl","--user","is-active",Le]).status===0,floor:"auto-spawn"}}function It(e,t,n){let r=t(n),o=(r.stderr??r.stdout??"").trim();return{step:e,argv:n,ok:r.status===0,...o?{detail:o}:{}}}async function Bp(e,t){await Ip(Cp(e),{recursive:!0}),await Np(e,t,{encoding:"utf8",mode:420})}async function Jp(e){await Tp(e,{force:!0})}function lr(e){let t=Ap(e[0],[...e.slice(1)],{encoding:"utf8"});return t.error!=null?{status:null,stderr:t.error.message}:{status:t.status,stdout:t.stdout??"",stderr:t.stderr??""}}var Ei=75,Pi=9e5,ji="redskilled-replacement-entry-unresolved",Yp="REDSKILLED_NO_REGISTRY_PROBE",Oi="REDSKILLED_BORN_BY_REPLACEMENT";function Li(e=process.env){return e[Oi]==="1"}function Di(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function $i(e){let t=e.running.trim();if(rt(t))return null;let n=e.newest?.trim()??"",r=U(n),o=U(t);return r===null||o===null||r.major<=o.major?null:{version:n,running_major:o.major,held_major:r.major,reason:`redskilled ${n} is published and this daemon runs ${t}; 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:Zp(r.major,e.supervised)}}function Zp(e,t){let n=`install the ${e}.x bundle (update this machine's plugin pin), then `;return t?`${n}re-point the unit and restart it: redskilled unit install && systemctl --user restart redskilled.service`:`${n}stop this daemon \u2014 the next client start resolves the newly installed bundle`}function Ai(e){let t=e.running.trim();if(rt(t))return{act:"hold",reason:"local-build"};let n=e.published?.trim()??"";return!n||U(n)===null?{act:"hold",reason:"published-unknown"}:rr(n,t)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:n,via:e.supervised?"supervisor-exit":"self-spawn"}}function rt(e){let t=e.trim();return U(t)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(t)}function Ii(e=process.env){return e[sr]==="1"}var ar=class extends Error{code=ji;searched;constructor(t,n){super(`${ji}: the published redskilled bundle ${t} exists on no reachable path and the version-pinned dispatch is disabled
57
57
  searched:
58
58
  ${n.map(r=>` ${r}`).join(`
59
- `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...n]}};function Zp(e,t={}){let n=t.env??process.env,r=t.exists??Kp,o=t.execPath??process.execPath,s=t.callerEntry===void 0?process.argv[1]:t.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,l=[],a=[[xi(bt(n),i),"bundle-cache"]];s&&a.push([xi(Gp(zp(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(n.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new ar(e,l);return{command:n.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:l}}function Ti(e,t={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let n=t.resolveEntry??(r=>Zp(r,t.env==null?{}:{env:t.env}));return{via:e.via,to:e.to,entry:n(e.to)}}function Ni(e,t,n={}){let r=n.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??ef)(Ei),{...e,exitCode:Ei};let o=[...e.entry.args,...fe(t,n.idleMs==null?{}:{idleMs:n.idleMs})];return(r.spawnSuccessor??Xp(r.env))(e.entry,o),e}function Xp(e){return(t,n)=>{let r=Jp(t.command,[...n],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[Oi]:"1"}});r.on("error",()=>{}),r.unref()}}function ef(e){process.exitCode=e,process.exit(e)}async function Wi(e,t=process.env,n=tf){let r=Ci(t),o=Ui(e,t);if(t[Qp]==="1")return{version:o,newest:r};let s=U(e)===null?"0.0.0":e;try{let i=await Jo({fetchText:n},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function Mi(e,t=process.env,n){let r=n??dr;return{version:Ui(e,t,r),newest:Ci(t,r)}}function Ci(e=process.env,t=dr){return Hi(Fi(e,t))}function Ui(e,t=process.env,n=dr){let r=U(e.trim())?.major;return r===void 0?null:Hi(Fi(t,n).filter(o=>U(o)?.major===r))}function Fi(e,t){let n=[];for(let r of t(bt(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||U(o)===null||n.push(o)}return n}function Hi(e){let t=null;for(let n of e)(t===null||rr(n,t)>0)&&(t=n);return t}function dr(e){try{return qp(e)}catch{return[]}}async function tf(e){let t=await fetch(e,{headers:{accept:"application/json"}});if(!t.ok)throw new Error(`registry read failed with HTTP ${t.status}`);return await t.text()}import{mkdir as nf,readFile as rf,rename as of,rm as cr,writeFile as Vi}from"node:fs/promises";import{randomUUID as sf}from"node:crypto";import{dirname as lf}from"node:path";var It=class extends Error{constructor(t){super(`redskilled lease ${JSON.stringify(t)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function pr(e){let t;try{t=await rf(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let n=af(t);return df(n)?n:void 0}var Bi;function Ki(){return Bi??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Bi}function qi(e,t,n={}){let r=n.clock??(()=>new Date().toISOString()),o=n.isPidAlive??N;async function s(){return await pr(e)}async function i(a){let c=`${e}.${a.pid}.${sf()}.tmp`;await Vi(c,Ji(a),{encoding:"utf8",mode:384}),await of(c,e)}function l(a,c){return{version:1,pid:a.pid,start_time:a.startTime,session_key_hash:t.sessionKeyHash,machine_id_hash:t.machineIdHash,socket_path:t.socketPath,acquired_at:c,renewed_at:c}}return{read:s,async acquire(a){await nf(lf(e),{recursive:!0,mode:448});let c=!1;for(;;){let u=r(),f=l(a,u);try{return await Vi(e,Ji(f),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:c,lease:f}}catch(h){if(h.code!=="EEXIST")throw h}let p=await s();if(!p){await cr(e,{force:!0}),c=!0;continue}if(ur(p,a))return{acquired:!0,reaped:c,lease:p};if(await o(p.pid))return{acquired:!1,lease:p};await cr(e,{force:!0}),c=!0}},async renew(a){let c=await s();if(!c||!ur(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(!ur(c,a))throw new It(e);return await cr(e,{force:!0}),!0}}}function ur(e,t){return e.pid===t.pid&&e.start_time===t.startTime}function Ji(e){return`${I(e,{keyedMapCollapse:!0})}
60
- `}function af(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{try{return K(t)}catch{return null}}}function df(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(t.version!==1||!Number.isInteger(t.pid)||t.pid<=0)return!1;for(let n of["start_time","session_key_hash","machine_id_hash","socket_path","acquired_at","renewed_at"])if(typeof t[n]!="string"||t[n].length===0)return!1;return!0}var fr=3e5,yf=1e4,kf=6e4,Rf=15e3,Gi=16,Le=class extends Error{constructor(n,r){super(`a redskilled daemon already owns ${JSON.stringify(n)}`);this.socketPath=n;this.lease=r;this.name="RedskilledAlreadyRunningError"}},wf="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Qi(e){let{paths:t}=e,n=e.daemonVersion??"0.0.0-dev",r=e.idleMs??fr,o=e.clock??(()=>new Date().toISOString()),s=e.launch??ki,i=e.ceiling??es();e.repositoryActivity!=null&&Kn(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??Ki(),a=e.leaseStore??qi(t.leasePath,{sessionKeyHash:t.sessionKeyHash,machineIdHash:t.machineIdHash,socketPath:t.socketPath},{clock:o}),c=e.machineOwner??gs(),u={machineIdHash:t.machineIdHash,sessionKeyHash:t.sessionKeyHash,socketPath:t.socketPath},f=e.machineClaimStore??Et(t.machineClaimPath,u,{clock:o});await mf(hf(t.socketPath),{recursive:!0,mode:448});let p=await f.claim(c);if(!p.claimed)throw p.claim?.socket_path===t.socketPath?new Le(t.socketPath):new le(f.claimPath,p.reason,p.claim);let h=await a.acquire(l);if(!h.acquired)throw await f.release(c).catch(()=>{}),new Le(t.socketPath,h.lease);let y;try{y=await bf(t.socketPath)}catch(d){throw await a.release(l).catch(()=>{}),await f.release(c).catch(()=>{}),d}let w=o(),b=e.eventLane??rs(t.eventLanePath),_=e.liveness??ei,O=e.stopWorker??li,F=e.unitInventory??(()=>ri(t.machineClaimPath,xt({machineIdHash:t.machineIdHash}))?oi():[]),M=e.unitMainPid??ni,ae=e.treeSampler??Es,he=e.readLogTail??Ri,st=e.sampleMs??Rf,_r=e.publishedVersion??(d=>Wi(d)),vr=e.replaceCheckMs??Pi,Sr=e.publishedProbeTimeoutMs??yf,Ol=e.localPublishedEvidence??(d=>Mi(d,e.replacementIO?.env??process.env)),Dl=e.bornByReplacement??Di(),xr=e.replaceBootCheckMs??kf,Er=e.supervised??Ii(),jr=e.replacementIO??{},H=e.repositoryActivity,Pr=H?.intervalMs??6e4,Ie=e.queueDiscovery,Or=Ie?.transport??H?.transport,Ll=Ie?.unconfiguredReason??wf,Dr=Ie?.intervalMs??15e3,Lr=e.demandMs??15e3,$l=e.demandBackoffMs??3e4,x=new Map,re=new Set,ye=new Map,A=new Map,Wt=new Set,$r={},Mt=null,Ar=null,Ct=null,Ir=!1,Ut=0,Ft=null,Te="none",Ht=null,Tr=null,Vt=null,oe=null,it=null,Ne=[],We=null,Bt=!1,ke,Me,Ce,Ue,lt,Fe,He,Q=!1,Jt=!1,at=null,Nr,Kt=new Promise(d=>{Nr=d});function Ve(d){Wr(d);let m=Date.parse(d),g=_s(A.values(),m);for(let R of g.lapsed)A.delete(R.project_label),Al(R,m);return g.lapsed}function Al(d,m){let g=Number.isFinite(m)?new Date(m).toISOString():d.renew_by;Ne.push({project_label:d.project_label,at:g,renew_by:d.renew_by,renewals:d.renewals,sustains:d.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(d.project_label)}: it stood until ${d.renew_by} and nothing renewed it \u2014 no session spoke for it, and no poll found it work or a Worker to hold it up`}),Ne.length>Gi&&Ne.splice(0,Ne.length-Gi)}function Wr(d){if(A.size===0)return;let m=Date.parse(d);if(!Number.isFinite(m))return;let g={};for(let v of x.values())g[v.project_label]=(g[v.project_label]??0)+1;let R=new Map((oe?.projects??[]).map(v=>[v.project_label,v]));for(let v of[...A.values()]){let P=R.get(v.project_label),we=ws(v,{now:d,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:g[v.project_label]??0});we.registration!==v&&A.set(v.project_label,we.registration)}}function dt(){let d=o();return Ve(d),Ns({now:d,daemonVersion:n,machineIdHash:t.machineIdHash,sessionKeyHash:t.sessionKeyHash,pid:l.pid,startedAt:w,scope:hs(f.claimPath,u,c),workers:[...x.values()],registrations:[...A.values()],lapses:Ne,queue:oe,published:{version:Ar,checkedAt:Ct,newer:Ir,replacement:Te,newest:Ht,majorHold:Tr,checks:Ut,holdReason:Ft}})}function qt(){return Is({hostState:dt(),ceiling:i,rss:$r,sampledAt:Mt,logLines:Object.fromEntries(ye),now:o(),reattachedWorkerIds:[...re],repositoryActivity:Vt})}async function Gt(){return H==null||H.projects.length===0?null:(Vt=await Os({projects:H.projects,hostTokenRef:H.hostTokenRef,transport:H.transport,closedWindowMs:H.closedWindowMs,now:o()}),Vt)}async function Mr(){let d=o();Ve(d);let m=[...A.values()].map(g=>({project_label:g.project_label,selector:g.selector})).sort((g,R)=>g.project_label.localeCompare(R.project_label));return m.length===0?null:Or==null?(oe=di(m,d,Ll),oe):(oe=await ci({projects:m,transport:Or,now:d,...Ie?.batchSize==null?{}:{batchSize:Ie.batchSize}}),Wr(o()),oe)}async function Cr(){let d=o();if(Bt)return it??is(d);Bt=!0;try{let m={};for(let $ of x.values())m[$.project_label]=(m[$.project_label]??0)+1;let g={};for(let $ of oe?.projects??[])g[$.project_label]=$.depth;let R=Date.parse(d),v=ss({projects:[...A.values()].map($=>({project_label:$.project_label,selector:$.selector,argv:$.argv,workspace_path:$.workspace_path,target:$.target})),queue:g,live:m,nowMs:Number.isFinite(R)?R:0,backoffUntilMs:We}),P=[],we=null;for(let $ of v.births){let mt;try{mt=zt({project_label:$.project_label,workspace_path:$.workspace_path,command:$.argv[0],args:$.argv.slice(1)})}catch(Zt){we=Zt instanceof Error?Zt.message:String(Zt),We=(Number.isFinite(R)?R:Date.now())+$l;break}P.push({project_label:$.project_label,worker_id:mt.worker.worker_id,pid:mt.worker.pid,warnings:mt.warnings})}return we==null&&v.births.length>0&&(We=null),it={version:1,at:d,requested:v.births.length,granted:P,shortfall:v.births.length-P.length,refusal:we,retry_after:We==null?null:new Date(We).toISOString(),projects:v.intents},it}finally{Bt=!1}}function Il(d){return fi(qt(),{...D,mode:d?.mode??D.mode,project:d?.project??D.project,maxWorkers:d?.max_workers??D.maxWorkers,maxProjects:d?.max_projects??D.maxProjects,maxWidth:d?.max_width??D.maxWidth,verbose:d?.verbose??D.verbose})}function Re(d,m,g){return Ss({op:d,sessionProject:m??null,targetProject:g})}async function Tl(d){let m=x.get(d.worker_id),g=Re(vs(d.command),d.session_project,m?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(d.command!=="stop")throw new Error(`redskilled does not implement ${d.command}: it owns birth, death and limits, and ${d.command} is a work decision the project's own bundle makes on top of them`);let R=m!=null&&await Cl(m,d.detail??"stopped by its own project");return{version:1,command:d.command,worker_id:d.worker_id,applied:R,reach:g,detail:R?`redskilled stopped Worker ${JSON.stringify(d.worker_id)} of project ${JSON.stringify(m.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(d.worker_id)} to stop`}}function ct(d){x.delete(d),re.delete(d),ye.delete(d)}function Ur(d){let m=x.get(d.worker_id),g=Re("worker-heartbeat",d.session_project,m?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(typeof d.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(m==null)return{version:1,worker_id:d.worker_id,accepted:!1,reach:g,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(d.worker_id)} to publish a line for`};let R=o();return ye.set(d.worker_id,{line:d.last_log_line,published_at:R,source:"heartbeat"}),{version:1,worker_id:d.worker_id,accepted:!0,reach:g,published_at:R,detail:`redskilled stored a line for Worker ${JSON.stringify(d.worker_id)} without reading it`}}async function Nl(d,m,g){let R=`exit code=${m??"null"} signal=${g??"null"}`;if(d.unit!=null&&d.unit!==""&&await Wl(d)){Ml(d,`its launch client ended (${R}) 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}ct(d.worker_id),Y("worker-death",d,R,{exitCode:m,signal:g}),L()}async function Wl(d){try{return await _(d)===!0}catch{return!1}}function Ml(d,m){let g=d.unit==null?null:M(d.unit);x.set(d.worker_id,{...d,...g!=null&&g>0?{pid:g}:{},warnings:[...d.warnings,m]}),re.add(d.worker_id),L()}function Fr(d,m){let g=Re("project-register",m,d.project_label);if(!g.permitted)throw new Error(g.reason);let R=o();Ve(R);let v=ks(d,{now:R,held:A.get(d.project_label)});return A.set(v.project_label,v),L(),{version:1,registration:v,reach:g,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 Hr(d,m={}){let g=Re("project-renew",m.sessionProject,d);if(!g.permitted)throw new Error(g.reason);let R=o();Ve(R);let v=A.get(d);if(v==null)throw new jt(d);let P=Rs(v,{now:R,...m.renewWithinMs==null?{}:{renew_within_ms:m.renewWithinMs},...m.launch==null?{}:{launch:m.launch}});return A.set(P.project_label,P),L(),{version:1,registration:P,reach:g,detail:`redskilled renewed the registration for project ${JSON.stringify(P.project_label)}, which now stands until ${P.renew_by} after renewal ${P.renewals}`+(m.launch==null?"":`, carrying launch revision ${P.launch_revision} for its next Worker`)}}function Vr(d,m){let g=Re("project-deregister",m,d);if(!g.permitted)throw new Error(g.reason);let R=A.delete(d);return{version:1,project_label:d,released:R,reach:g,detail:R?`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 Cl(d,m){try{await O(d)}catch{}return ct(d.worker_id),Y("worker-death",d,m),L(),!0}function Br(d){return Xo({ceiling:i,workers:[...x.values()],budget:d.budget,projectLabel:d.project_label})}function zt(d){let m=s({spec:d,admission:Br(d),clock:o,onExit:(g,R,v)=>{let P=x.get(g);if(P==null){L();return}Nl(P,R,v).catch(()=>{})}});return x.set(m.worker.worker_id,m.worker),Y("worker-birth",m.worker,null),L(),m}function Y(d,m,g,R={}){Q||b.record({event:d,worker:m,ts:o(),detail:g,...R.exitCode!==void 0?{exitCode:R.exitCode}:{},...R.signal!==void 0?{signal:R.signal}:{}}).catch(()=>{})}async function Jr(){let d=[...re].map(g=>x.get(g)).filter(g=>g!=null);if(d.length===0)return[];let{dead:m}=await Xn(d,_);for(let g of m)ct(g.worker_id),Y("worker-death",g,"the host no longer confirms this Worker");return m.length>0&&L(),m}async function Kr(d,m){let g=x.get(d);if(!g)return!1;try{await O(g)}catch{}return ct(d),Y("worker-budget-kill",g,m),L(),!0}async function qr(){let d=[...x.values()];if(d.length===0)return[];let m;try{m=await ae(d)}catch{return[]}let g=m.rss;$r=g,Mt=o(),Ul(m.cpu_seconds,Mt);let{terminations:R}=xs({workers:d,rss:g}),v=[];for(let P of R)await Kr(P.worker_id,P.reason)&&v.push(P);return v}function Ul(d,m){for(let[g,R]of Object.entries(d)){if(typeof R!="number"||!Number.isFinite(R))continue;let v=x.get(g);v&&x.set(g,{...v,cpu:{cpu_seconds:R,sampled_at:m}})}}async function Fl(){try{return Sr<=0?await _r(n):await new Promise(d=>{let m=setTimeout(()=>d(Qt()),Sr);m.unref(),_r(n).then(g=>{clearTimeout(m),d(g)},()=>{clearTimeout(m),d(Qt())})})}catch{return Qt()}}function Qt(){try{return Ol(n)}catch{return null}}async function Gr(){if(nt(n))return Ut+=1,Ct=o(),Ft="local-build",{act:"hold",reason:"local-build"};let d=Li(await Fl()),m=d.version;Ar=m,Ht=d.newest??null,Ct=o(),Tr=$i({running:n,newest:Ht,supervised:Er});let g=Ai({running:n,published:m,supervised:Er});return Ir=g.act==="replace",Ut+=1,Ft=g.act==="hold"?g.reason:null,Te!=="in-progress"&&(Te=g.act==="replace"?"pending":"none"),g}async function ut(){let d=await Gr();if(d.act!=="replace"||Te==="in-progress")return d;let m=Ti(d,jr);return Te="in-progress",await b.flush().catch(()=>{}),await ft({reason:"replaced"}),Ni(m,t,{...r==null?{}:{idleMs:r},io:jr}),d}function Hl(){Q||Ue!=null||vr<=0||(!Dl&&xr>0&&(lt=setTimeout(()=>{ut().catch(()=>{})},xr),lt.unref()),Ue=setInterval(()=>{ut().catch(()=>{})},vr),Ue.unref())}function Vl(){Q||Me!=null||st<=0||(Me=setInterval(()=>{qr().catch(()=>{})},st),Me.unref())}function Bl(){Q||Fe!=null||H==null||H.projects.length===0||Pr<=0||(Gt().catch(()=>{}),Fe=setInterval(()=>{Gt().catch(()=>{})},Pr),Fe.unref())}function Jl(){Q||He!=null||Dr<=0||(He=setInterval(()=>{Mr().catch(()=>{})},Dr),He.unref())}function Kl(){Q||Ce!=null||Lr<=0||(Ce=setInterval(()=>{Cr().catch(()=>{})},Lr),Ce.unref())}function L(){Q||(ke&&clearTimeout(ke),ke=setTimeout(()=>{Jr().catch(()=>{}).then(()=>zr())},r),ke.unref())}function zr(){return x.size>0?(L(),"held-by-workers"):(Ve(o()),A.size>0?(L(),"held-by-registrations"):(ql(),"exited"))}async function ql(){if(!nt(n)){if((await ut().catch(()=>null))?.act==="replace"||Jt||Q)return;if(x.size>0||A.size>0){L();return}}await ft({reason:"idle"})}function pt(d){return as({reason:d,socketPath:t.socketPath,daemonVersion:n,pid:l.pid,workers:[...x.values()],projects:[...A.keys()]})}function Qr(d){if(at!=null)return at;let m=d.reason??"requested",g=d.note?.trim();return at=b.recordDaemonStop({ts:o(),pid:l.pid,socketPath:t.socketPath,reason:m,detail:g==null||g===""?pt(m).detail:`${pt(m).detail} \u2014 ${g}`,...d.signal==null?{}:{signal:d.signal}}).catch(()=>{}),at}async function ft(d={}){if(Jt)return await Kt;Jt=!0,await Qr(d),Q=!0,ke&&clearTimeout(ke),Me&&clearInterval(Me),Ue&&clearInterval(Ue),lt&&clearTimeout(lt),Fe&&clearInterval(Fe),He&&clearInterval(He),Ce&&clearInterval(Ce),await b.flush().catch(()=>{}),y.close();for(let m of Wt)m.destroy();return await new Promise(m=>y.once("close",()=>m())),await zi(t.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await f.release(c).catch(()=>{}),Nr(),await Kt}let Gl=os(await b.read().catch(()=>[])),Yt=await Xn(Gl,_);for(let d of Yt.alive){let m=ii(d),g=m.unit==null||N(m.pid)?null:M(m.unit);x.set(m.worker_id,g!=null&&g>0?{...m,pid:g}:m),re.add(m.worker_id)}for(let d of Yt.dead)Y("worker-death",d,"the Worker ended while no daemon was watching");let zl=si({units:await Promise.resolve(F()).catch(()=>[]),held:[...x.values()],mainPid:M,now:w});for(let d of zl)x.set(d.worker_id,d),re.add(d.worker_id),Y("worker-birth",d,"adopted from an active unit with no birth on this lane");for(let d of Yt.alive){if(d.log_path==null||ye.has(d.worker_id))continue;let m=await he(d.log_path).catch(()=>null);m==null||m.trim()===""||ye.set(d.worker_id,{line:m,published_at:o(),source:"rehydrated"})}y.on("connection",d=>{Wt.add(d),d.once("close",()=>Wt.delete(d)),L(),_f(d,async(m,g)=>{L();let R=await Ql(m);g(R),m.op==="shutdown"&&setImmediate(()=>void ft({reason:"requested"}))})});async function Ql(d){try{if(d.op==="ping")return{id:d.id,ok:!0,value:{pong:!0,protocol_version:Pt,daemon_version:n,pid:l.pid}};if(d.op==="host-state")return{id:d.id,ok:!0,value:dt()};if(d.op==="statusline-payload")return{id:d.id,ok:!0,value:qt()};if(d.op==="statusline-string")return{id:d.id,ok:!0,value:Il(d.render)};if(d.op==="worker-heartbeat")return{id:d.id,ok:!0,value:Ur(d.heartbeat)};if(d.op==="project-register")return{id:d.id,ok:!0,value:Fr(d.registration,d.session_project)};if(d.op==="project-renew")return{id:d.id,ok:!0,value:Hr(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:Vr(d.project_label,d.session_project)};if(d.op==="worker-command")return{id:d.id,ok:!0,value:await Tl(d.command)};if(d.op==="worker-start"){let g=Re("worker-start",d.session_project,d.spec.project_label);if(!g.permitted)return{id:d.id,ok:!1,error:g.reason};let R=zt(d.spec);return await b.flush().catch(()=>{}),{id:d.id,ok:!0,value:{worker:R.worker,admission:R.admission,warnings:R.warnings}}}if(d.op==="shutdown"){let g=pt("requested");return await Qr({reason:"requested",...d.detail==null?{}:{note:d.detail}}),{id:d.id,ok:!0,value:g}}let m=d;return{id:m.id??Tt(),ok:!1,error:`unsupported redskilled op: ${m.op??"unknown"}`}}catch(m){return{id:d.id??Tt(),ok:!1,error:m instanceof Error?m.message:String(m)}}}return L(),Vl(),Hl(),Bl(),Jl(),Kl(),{socketPath:t.socketPath,lease:h.lease,startedAt:w,closed:Kt,startWorker:zt,admit:Br,ceiling:()=>i,killWorkerOverBudget:Kr,sampleMemoryBudgets:qr,pollRepositoryActivity:Gt,pollQueueDiscovery:Mr,queueDiscovery:()=>oe,driveDemand:Cr,demand:()=>it,sweepReattached:Jr,publishWorkerHeartbeat:Ur,reattached:()=>[...re].map(d=>x.get(d)).filter(d=>d!=null),flushEvents:()=>b.flush(),trackWorker(d){x.set(d.worker_id,d),Y("worker-birth",d,null),L()},releaseWorker(d){let m=x.get(d),g=x.delete(d);return re.delete(d),ye.delete(d),m&&Y("worker-death",m,"released by the daemon"),L(),g},workerCount:()=>x.size,registerProject:Fr,renewProject:Hr,deregisterProject:Vr,registrations:()=>dt().registrations??[],hostState:dt,statuslinePayload:qt,evaluateIdle:zr,observePublishedVersion:Gr,checkForReplacement:ut,stopReport:pt,stop:ft}}async function bf(e){for(let t=0;t<2;t++){let n=gf();try{return await new Promise((r,o)=>{n.once("error",o),n.listen(e,()=>{n.off("error",o),r()})}),n}catch(r){if(n.close(),r.code!=="EADDRINUSE")throw r;if(await te(e))throw new Le(e);await zi(e,{force:!0})}}throw new Le(e)}async function te(e,t=250){try{return(await kt({socketPath:e,timeoutMs:t},{id:Tt(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function _f(e,t){Uo(e,(n,r)=>t(n,r),(n,r,o)=>{o({id:r?.id??Tt(),ok:!1,error:n instanceof Error?n.message:String(n)})})}X();var jf=1e4,$e=class extends Error{constructor(n,r){super(`redskilled daemon is unreachable on ${JSON.stringify(n)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}`);this.socketPath=n;this.cause=r;this.name="RedskilledUnreachableError"}};async function mr(e,t={}){try{return await Pf(e,t)}catch(n){throw n instanceof le||n instanceof $e?n:new $e(e.socketPath,n)}}async function Pf(e,t){if(await Sf(Ef(e.socketPath),{recursive:!0,mode:448}),await te(e.socketPath))return"already-running";await Of(e);let n=await Fo(e.lockPath);if(!n)return await Yi(e,t),"joined";try{if(await te(e.socketPath))return"already-running";let r=await $f(e,t);return await Yi(e,t,r),"spawned"}finally{await n.close(),await xf(e.lockPath,{force:!0})}}async function Of(e){let n=await Et(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(n!=null&&n.socket_path!==e.socketPath&&N(n.pid))throw new le(e.machineClaimPath,"held",n)}async function Xi(e,t,n={}){await mr(e,n);let r;try{r=await Xe({socketPath:e.socketPath,timeoutMs:n.requestTimeoutMs??2e3},{...t,id:Zi()})}catch(o){throw new $e(e.socketPath,o)}if(!r.ok)throw new Error(r.error);return r.value}async function el(e,t={},n={}){if(!await te(e.socketPath))return ds(e.socketPath);let r;try{r=await Xe({socketPath:e.socketPath,timeoutMs:n.requestTimeoutMs??2e3},{id:Zi(),op:"shutdown",...t.detail==null?{}:{detail:t.detail}})}catch(i){throw new $e(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!Wn(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await Df(e.socketPath,t.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 Df(e,t){let n=Date.now()+t;for(;;){if(!await te(e))return!0;if(Date.now()>=n)return!1;await new Promise(r=>setTimeout(r,25))}}async function tl(e,t={}){let n=await Xi(e,{op:"host-state"},t);if(!Ws(n))throw new Error("redskilled daemon returned a malformed host state");return n}async function nl(e,t=void 0,n={}){let r=await Xi(e,{op:"statusline-string",...n.sessionProject!=null?{session_project:n.sessionProject}:{},...t==null?{}:{render:Lf(t)}},n);if(!Ts(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function Lf(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 Yi(e,t,n){let r=Date.now()+(t.readyTimeoutMs??jf);for(;;){if(await te(e.socketPath))return;if(n?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(n.entry.entry??n.entry.command)} (resolved as ${n.entry.source}): ${n.failure.message}`);if(Date.now()>=r){let o=n?` from ${JSON.stringify(n.entry.entry??n.entry.command)} (resolved as ${n.entry.source})${n.exit?`, which ${n.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${o}`)}await new Promise(o=>setTimeout(o,25))}}async function $f(e,t){let n=t.serverCommand??(t.serverArgs!=null?process.execPath:void 0),r=await zo({...n!=null?{serverCommand:n}:{},serverArgs:t.serverArgs},t.entryLookup??{}),o={entry:r},s=[...r.args,...fe(e,t.idleMs==null?{}:{idleMs:t.idleMs})],i=vf(r.command,s,{detached:!0,stdio:"ignore",env:{...t.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}X();import{chmod as dl,mkdir as ul,readFile as pl,stat as Jf,writeFile as Kf}from"node:fs/promises";import{homedir as yr}from"node:os";import{dirname as qf,join as kr}from"node:path";import{join as Af}from"node:path";var If=[".red","redskilled"],z=448;function rt(e){return Af(e,...If)}import{join as Tf}from"node:path";var rl=["local","tmp","host"],Nf="local",ot="plugins.dev.workspace.target";var gr=class extends Error{constructor(t){super(t),this.name="WorkspaceConfigError"}};function sl(e){let t=xe(e,ot),n=Cf(t??"").trim();return n===""?void 0:n}function il(e){let t=(e??"").trim();if(t==="")return{kind:"preset",preset:Nf};let n=rl.find(r=>r===t.toLowerCase());if(n)return{kind:"preset",preset:n};if(t.startsWith("/")||t==="~"||t.startsWith("~/"))return{kind:"custom",parentDir:t};throw new gr(`${ot}: unknown workspace target ${JSON.stringify(t)}. Use one of the presets (${rl.join(", ")}) or an absolute parent directory for Workers.`)}function ll(e,t){return e.kind==="preset"?e.preset==="host":Mf(Wf(e.parentDir,t),rt(t))}function Wf(e,t){return e==="~"?ol(t):e.startsWith("~/")?Tf(t,e.slice(2)):ol(e)}function Mf(e,t){return e===t?!0:t==="/"?e.startsWith("/"):e.startsWith(`${t}/`)}function ol(e){let t=e.trim();return t.length>1?t.replace(/\/+$/,""):t}function Cf(e){let t=e.trim(),n=/^(["'])(.*)\1$/.exec(t);return n?n[2]:t}X();import{createHash as Uf}from"node:crypto";import{hostname as Ff}from"node:os";import{join as Nt}from"node:path";var Ae="redskilled.sock",Hf="REDSKILLED_SESSION";function Vf(e={}){let t=e.env??process.env,n=t[Hf]?.trim();if(n)return n;let r=t.XDG_RUNTIME_DIR?.trim();return r||`uid:${e.uid??(typeof process.getuid=="function"?process.getuid():"nouid")}`}function Bf(e={}){return al(e.host??Ff())}function ne(e={}){let t=Vf(e),n=e.runtimeDir??Rt({key:`redskilled:${t}`,socketFileName:Ae,env:e.env,uid:e.uid}),r=Bf(e);return{sessionKey:t,sessionKeyHash:al(t),machineIdHash:r,runtimeDir:n,socketPath:Nt(n,Ae),lockPath:Nt(n,"redskilled.spawn.lock"),leasePath:Nt(n,"redskilled.lease.toon"),eventLanePath:Nt(n,ns),machineClaimPath:e.machineClaimPath??xt({env:e.env,machineIdHash:r,platform:e.platform})}}function al(e){return Uf("sha256").update(e).digest("hex").slice(0,12)}var hr="run `/red-setup` (Section E3 \u2014 execution daemon), or `redskilled provision` directly";async function fl(e=yr()){let t=rt(e),n=await wr(t);return n===void 0?(await ul(t,{recursive:!0,mode:z}),await dl(t,z),{path:t,created:!0,tightened:!1,mode:z}):n===z?{path:t,created:!1,tightened:!1,mode:n}:(await dl(t,z),{path:t,created:!1,tightened:!0,mode:z})}var ml={needed:!1,declaredBy:`no ${ot} in view`};async function Rr(e={}){let t=e.homeDir??yr(),n=e.declaredTarget?.trim();if(n)return cl(n,t,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return ml;let o=kr(r,".red","config.yaml"),s=await pl(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=sl(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:cl(i,t,o)}function cl(e,t,n){let r=`${ot}: ${e} (${n})`;try{return{needed:ll(il(e),t),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function gl(e){let t=[Gf(e),zf(e),Qf(e),Yf(e)],n=t.filter(o=>o.verdict!=="ok");return{verdict:n.some(o=>o.verdict==="missing")?"missing":n.length>0?"degraded":"ok",rows:t,findings:n}}function Gf(e){let t=e.homeNeed??ml;if(!e.homePresent)return t.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${t.declaredBy}`,fix:hr}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${t.declaredBy}; the daemon never reads it`,fix:""};let n=e.homeMode??z;return n!==z?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${n.toString(8)}, not owner-only ${z.toString(8)}`,fix:`${hr} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${n.toString(8)})`,fix:""}}function zf(e){return G(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 Qf(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:`${hr} \u2014 it starts the daemon and waits for the socket`}}function Yf(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 hl(e={}){let t=e.env??process.env,n=e.homeDir??yr(),r=e.paths??ne({env:t}),o=rt(n),[s,i,l]=await Promise.all([wr(o),te(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Rr({homeDir:n,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:ie(e.entryOverride??{},{env:t,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await Xf(em(e,t,n),t)}}var Zf="redskilled.service";function yl(e){return kr(e,"systemd","user",Zf)}function kl(e){let t=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${t}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
61
- `)}async function Rl(e){let t=yl(e.configHome);return await wr(t)!==void 0?{path:t,status:"already-present"}:(await ul(qf(t),{recursive:!0}),await Kf(t,e.unit,"utf8"),{path:t,status:"installed"})}async function Xf(e,t){if(process.platform!=="linux")return"unsupported";try{return await pl(yl(e),"utf8"),"installed"}catch{return t.XDG_RUNTIME_DIR?"absent":"unsupported"}}function em(e,t,n){return e.configHome??t.XDG_CONFIG_HOME?.trim()??kr(n,".config")}async function wr(e){try{return(await Jf(e)).mode&511}catch{return}}import{readdir as bl,rm as tm,stat as nm}from"node:fs/promises";import{dirname as rm,join as br}from"node:path";var om=5*6e4,sm="redskilled.";function im(e={}){let t=e.env??process.env,n=i=>rm(Rt({key:"redskilled:reclaim-probe",socketFileName:Ae,env:i,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=t,s=[n(t),n(o)];return[...new Set(s)]}async function _l(e={}){let t=e.roots??im(e),n=e.graceMs??om,r=e.now??Date.now,o=e.isPidAlive??N,s=e.answers??cm,i=e.dryRun===!0,l=[];for(let a of t){let c;try{c=(await bl(a,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name)}catch{continue}for(let u of c.sort())l.push(await lm(br(a,u),{graceMs:n,now:r,pidAlive:o,answers:s,dryRun:i}))}return{roots:t,scanned:l.length,reclaimed:l.filter(a=>a.verdict==="reclaimed").length,dryRun:i,entries:l}}async function lm(e,t){let n;try{n=(await bl(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:vl(i),removed:[]}}let r=n.filter(i=>i.startsWith(sm));if(n.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await am(br(e,"redskilled.lease.toon"));if(o!==void 0)return await t.pidAlive(o.pid)?{dir:e,verdict:"live",reason:`lease pid ${o.pid} is alive`,removed:[]}:await wl(e,n,`lease pid ${o.pid} is dead`,t);if(n.includes(Ae)&&await t.answers(br(e,Ae)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await dm(e,t.now);return s!==void 0&&s<t.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(s/1e3)}s ago`,removed:[]}:await wl(e,n,n.length===0?"empty and stale":"no lease and stale",t)}async function wl(e,t,n,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${n} (dry run)`,removed:t};try{await tm(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:vl(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:n,removed:t}}async function am(e){try{return await pr(e)}catch{return}}async function dm(e,t){try{return Math.max(0,t()-(await nm(e)).mtimeMs)}catch{return}}async function cm(e){try{return(await Xe({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function vl(e){return e instanceof Error?e.message:String(e)}var um="plugins.dev.statusline",pm="dev.statusline";function fm(e){let t=[],n=l=>{for(let a of[um,pm]){let c=`${a}.${l}`,u=xe(e,c)?.trim();if(u!=null&&u!=="")return{key:c,value:u}}},r=n("mode"),o={};r!=null&&(r.value==="local"||r.value==="global"?o.mode=r.value:t.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=n(l.leaf);if(a==null)continue;let c=Number(a.value);Number.isInteger(c)&&c>=0?l.assign(c):t.push({...a,reason:"expected a whole number of zero or more"})}let i=n("verbose");return i!=null&&(i.value==="true"||i.value==="false"?o.verbose=i.value==="true":t.push({...i,reason:"expected `true` or `false`"})),{config:o,warnings:t}}var mm={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 Sl(e){let{values:t,positionals:n}=pe(e,mm),r=[],o={},s=t.mode??n.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`"})),t.project!=null&&(o.project=t.project),t.verbose!==void 0&&(o.verbose=t.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=t[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 xl(e={}){let t=e.configText==null?{config:{},warnings:[]}:fm(e.configText),n=e.flags??{};return{options:{...D,mode:n.mode??t.config.mode??D.mode,project:n.project!==void 0?n.project:e.project??D.project,maxWorkers:n.maxWorkers??t.config.maxWorkers??D.maxWorkers,maxProjects:n.maxProjects??t.config.maxProjects??D.maxProjects,maxWidth:n.maxWidth??t.config.maxWidth??D.maxWidth,verbose:n.verbose??t.config.verbose??D.verbose},warnings:t.warnings}}var ym=`Usage: redskilled <command> [options]
59
+ `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...n]}};function Xp(e,t={}){let n=t.env??process.env,r=t.exists??qp,o=t.execPath??process.execPath,s=t.callerEntry===void 0?process.argv[1]:t.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,l=[],a=[[xi(_t(n),i),"bundle-cache"]];s&&a.push([xi(zp(Qp(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(n.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new ar(e,l);return{command:n.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:l}}function Ti(e,t={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let n=t.resolveEntry??(r=>Xp(r,t.env==null?{}:{env:t.env}));return{via:e.via,to:e.to,entry:n(e.to)}}function Ni(e,t,n={}){let r=n.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??tf)(Ei),{...e,exitCode:Ei};let o=[...e.entry.args,...fe(t,n.idleMs==null?{}:{idleMs:n.idleMs})];return(r.spawnSuccessor??ef(r.env))(e.entry,o),e}function ef(e){return(t,n)=>{let r=Kp(t.command,[...n],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[Oi]:"1"}});r.on("error",()=>{}),r.unref()}}function tf(e){process.exitCode=e,process.exit(e)}async function Wi(e,t=process.env,n=nf){let r=Ci(t),o=Ui(e,t);if(t[Yp]==="1")return{version:o,newest:r};let s=U(e)===null?"0.0.0":e;try{let i=await Jo({fetchText:n},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function Mi(e,t=process.env,n){let r=n??dr;return{version:Ui(e,t,r),newest:Ci(t,r)}}function Ci(e=process.env,t=dr){return Hi(Fi(e,t))}function Ui(e,t=process.env,n=dr){let r=U(e.trim())?.major;return r===void 0?null:Hi(Fi(t,n).filter(o=>U(o)?.major===r))}function Fi(e,t){let n=[];for(let r of t(_t(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||U(o)===null||n.push(o)}return n}function Hi(e){let t=null;for(let n of e)(t===null||rr(n,t)>0)&&(t=n);return t}function dr(e){try{return Gp(e)}catch{return[]}}async function nf(e){let t=await fetch(e,{headers:{accept:"application/json"}});if(!t.ok)throw new Error(`registry read failed with HTTP ${t.status}`);return await t.text()}import{mkdir as rf,readFile as of,rename as sf,rm as cr,writeFile as Vi}from"node:fs/promises";import{randomUUID as lf}from"node:crypto";import{dirname as af}from"node:path";var Tt=class extends Error{constructor(t){super(`redskilled lease ${JSON.stringify(t)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function pr(e){let t;try{t=await of(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let n=df(t);return cf(n)?n:void 0}var Bi;function Ki(){return Bi??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Bi}function qi(e,t,n={}){let r=n.clock??(()=>new Date().toISOString()),o=n.isPidAlive??N;async function s(){return await pr(e)}async function i(a){let c=`${e}.${a.pid}.${lf()}.tmp`;await Vi(c,Ji(a),{encoding:"utf8",mode:384}),await sf(c,e)}function l(a,c){return{version:1,pid:a.pid,start_time:a.startTime,session_key_hash:t.sessionKeyHash,machine_id_hash:t.machineIdHash,socket_path:t.socketPath,acquired_at:c,renewed_at:c}}return{read:s,async acquire(a){await rf(af(e),{recursive:!0,mode:448});let c=!1;for(;;){let u=r(),f=l(a,u);try{return await Vi(e,Ji(f),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:c,lease:f}}catch(h){if(h.code!=="EEXIST")throw h}let p=await s();if(!p){await cr(e,{force:!0}),c=!0;continue}if(ur(p,a))return{acquired:!0,reaped:c,lease:p};if(await o(p.pid))return{acquired:!1,lease:p};await cr(e,{force:!0}),c=!0}},async renew(a){let c=await s();if(!c||!ur(c,a))throw new Tt(e);let u={...c,renewed_at:r()};return await i(u),u},async release(a){let c=await s();if(!c)return!1;if(!ur(c,a))throw new Tt(e);return await cr(e,{force:!0}),!0}}}function ur(e,t){return e.pid===t.pid&&e.start_time===t.startTime}function Ji(e){return`${I(e,{keyedMapCollapse:!0})}
60
+ `}function df(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{try{return K(t)}catch{return null}}}function cf(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(t.version!==1||!Number.isInteger(t.pid)||t.pid<=0)return!1;for(let n of["start_time","session_key_hash","machine_id_hash","socket_path","acquired_at","renewed_at"])if(typeof t[n]!="string"||t[n].length===0)return!1;return!0}var fr=3e5,kf=1e4,Rf=6e4,wf=15e3,Gi=16,De=class extends Error{constructor(n,r){super(`a redskilled daemon already owns ${JSON.stringify(n)}`);this.socketPath=n;this.lease=r;this.name="RedskilledAlreadyRunningError"}},bf="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Qi(e){let{paths:t}=e,n=e.daemonVersion??"0.0.0-dev",r=e.idleMs??fr,o=e.clock??(()=>new Date().toISOString()),s=e.launch??ki,i=e.ceiling??es();e.repositoryActivity!=null&&Kn(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??Ki(),a=e.leaseStore??qi(t.leasePath,{sessionKeyHash:t.sessionKeyHash,machineIdHash:t.machineIdHash,socketPath:t.socketPath},{clock:o}),c=e.machineOwner??gs(),u={machineIdHash:t.machineIdHash,sessionKeyHash:t.sessionKeyHash,socketPath:t.socketPath},f=e.machineClaimStore??jt(t.machineClaimPath,u,{clock:o});await gf(yf(t.socketPath),{recursive:!0,mode:448});let p=await f.claim(c);if(!p.claimed)throw p.claim?.socket_path===t.socketPath?new De(t.socketPath):new le(f.claimPath,p.reason,p.claim);let h=await a.acquire(l);if(!h.acquired)throw await f.release(c).catch(()=>{}),new De(t.socketPath,h.lease);let y;try{y=await _f(t.socketPath)}catch(d){throw await a.release(l).catch(()=>{}),await f.release(c).catch(()=>{}),d}let w=o(),b=e.eventLane??rs(t.eventLanePath),_=e.liveness??ei,O=e.stopWorker??li,F=e.unitInventory??(()=>ri(t.machineClaimPath,Et({machineIdHash:t.machineIdHash}))?oi():[]),M=e.unitMainPid??ni,ae=e.treeSampler??Es,he=e.readLogTail??Ri,it=e.sampleMs??wf,_r=e.publishedVersion??(d=>Wi(d)),vr=e.replaceCheckMs??Pi,Sr=e.publishedProbeTimeoutMs??kf,Ol=e.localPublishedEvidence??(d=>Mi(d,e.replacementIO?.env??process.env)),Ll=e.bornByReplacement??Li(),xr=e.replaceBootCheckMs??Rf,Er=e.supervised??Ii(),jr=e.replacementIO??{},H=e.repositoryActivity,Pr=H?.intervalMs??6e4,Ie=e.queueDiscovery,Or=Ie?.transport??H?.transport,Dl=Ie?.unconfiguredReason??bf,Lr=Ie?.intervalMs??15e3,Dr=e.demandMs??15e3,$l=e.demandBackoffMs??3e4,x=new Map,re=new Set,ye=new Map,A=new Map,Mt=new Set,$r={},Ct=null,Ar=null,Ut=null,Ir=!1,Ft=0,Ht=null,Te="none",Vt=null,Tr=null,Bt=null,oe=null,lt=null,Ne=[],We=null,Jt=!1,ke,Me,Ce,Ue,at,Fe,He,Q=!1,Kt=!1,dt=null,Nr,qt=new Promise(d=>{Nr=d});function Ve(d){Wr(d);let m=Date.parse(d),g=_s(A.values(),m);for(let R of g.lapsed)A.delete(R.project_label),Al(R,m);return g.lapsed}function Al(d,m){let g=Number.isFinite(m)?new Date(m).toISOString():d.renew_by;Ne.push({project_label:d.project_label,at:g,renew_by:d.renew_by,renewals:d.renewals,sustains:d.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(d.project_label)}: it stood until ${d.renew_by} and nothing renewed it \u2014 no session spoke for it, and no poll found it work or a Worker to hold it up`}),Ne.length>Gi&&Ne.splice(0,Ne.length-Gi)}function Wr(d){if(A.size===0)return;let m=Date.parse(d);if(!Number.isFinite(m))return;let g={};for(let v of x.values())g[v.project_label]=(g[v.project_label]??0)+1;let R=new Map((oe?.projects??[]).map(v=>[v.project_label,v]));for(let v of[...A.values()]){let P=R.get(v.project_label),we=ws(v,{now:d,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:g[v.project_label]??0});we.registration!==v&&A.set(v.project_label,we.registration)}}function ct(){let d=o();return Ve(d),Ns({now:d,daemonVersion:n,machineIdHash:t.machineIdHash,sessionKeyHash:t.sessionKeyHash,pid:l.pid,startedAt:w,scope:hs(f.claimPath,u,c),workers:[...x.values()],registrations:[...A.values()],lapses:Ne,queue:oe,published:{version:Ar,checkedAt:Ut,newer:Ir,replacement:Te,newest:Vt,majorHold:Tr,checks:Ft,holdReason:Ht}})}function Gt(){return Is({hostState:ct(),ceiling:i,rss:$r,sampledAt:Ct,logLines:Object.fromEntries(ye),now:o(),reattachedWorkerIds:[...re],repositoryActivity:Bt})}async function zt(){return H==null||H.projects.length===0?null:(Bt=await Os({projects:H.projects,hostTokenRef:H.hostTokenRef,transport:H.transport,closedWindowMs:H.closedWindowMs,now:o()}),Bt)}async function Mr(){let d=o();Ve(d);let m=[...A.values()].map(g=>({project_label:g.project_label,selector:g.selector})).sort((g,R)=>g.project_label.localeCompare(R.project_label));return m.length===0?null:Or==null?(oe=di(m,d,Dl),oe):(oe=await ci({projects:m,transport:Or,now:d,...Ie?.batchSize==null?{}:{batchSize:Ie.batchSize}}),Wr(o()),oe)}async function Cr(){let d=o();if(Jt)return lt??is(d);Jt=!0;try{let m={};for(let $ of x.values())m[$.project_label]=(m[$.project_label]??0)+1;let g={};for(let $ of oe?.projects??[])g[$.project_label]=$.depth;let R=Date.parse(d),v=ss({projects:[...A.values()].map($=>({project_label:$.project_label,selector:$.selector,argv:$.argv,workspace_path:$.workspace_path,target:$.target})),queue:g,live:m,nowMs:Number.isFinite(R)?R:0,backoffUntilMs:We}),P=[],we=null;for(let $ of v.births){let gt;try{gt=Qt({project_label:$.project_label,workspace_path:$.workspace_path,command:$.argv[0],args:$.argv.slice(1)})}catch(Xt){we=Xt instanceof Error?Xt.message:String(Xt),We=(Number.isFinite(R)?R:Date.now())+$l;break}P.push({project_label:$.project_label,worker_id:gt.worker.worker_id,pid:gt.worker.pid,warnings:gt.warnings})}return we==null&&v.births.length>0&&(We=null),lt={version:1,at:d,requested:v.births.length,granted:P,shortfall:v.births.length-P.length,refusal:we,retry_after:We==null?null:new Date(We).toISOString(),projects:v.intents},lt}finally{Jt=!1}}function Il(d){return fi(Gt(),{...L,mode:d?.mode??L.mode,project:d?.project??L.project,maxWorkers:d?.max_workers??L.maxWorkers,maxProjects:d?.max_projects??L.maxProjects,maxWidth:d?.max_width??L.maxWidth,verbose:d?.verbose??L.verbose})}function Re(d,m,g){return Ss({op:d,sessionProject:m??null,targetProject:g})}async function Tl(d){let m=x.get(d.worker_id),g=Re(vs(d.command),d.session_project,m?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(d.command!=="stop")throw new Error(`redskilled does not implement ${d.command}: it owns birth, death and limits, and ${d.command} is a work decision the project's own bundle makes on top of them`);let R=m!=null&&await Cl(m,d.detail??"stopped by its own project");return{version:1,command:d.command,worker_id:d.worker_id,applied:R,reach:g,detail:R?`redskilled stopped Worker ${JSON.stringify(d.worker_id)} of project ${JSON.stringify(m.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(d.worker_id)} to stop`}}function ut(d){x.delete(d),re.delete(d),ye.delete(d)}function Ur(d){let m=x.get(d.worker_id),g=Re("worker-heartbeat",d.session_project,m?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(typeof d.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(m==null)return{version:1,worker_id:d.worker_id,accepted:!1,reach:g,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(d.worker_id)} to publish a line for`};let R=o();return ye.set(d.worker_id,{line:d.last_log_line,published_at:R,source:"heartbeat"}),{version:1,worker_id:d.worker_id,accepted:!0,reach:g,published_at:R,detail:`redskilled stored a line for Worker ${JSON.stringify(d.worker_id)} without reading it`}}async function Nl(d,m,g){let R=`exit code=${m??"null"} signal=${g??"null"}`;if(d.unit!=null&&d.unit!==""&&await Wl(d)){Ml(d,`its launch client ended (${R}) 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}ut(d.worker_id),Y("worker-death",d,R,{exitCode:m,signal:g}),D()}async function Wl(d){try{return await _(d)===!0}catch{return!1}}function Ml(d,m){let g=d.unit==null?null:M(d.unit);x.set(d.worker_id,{...d,...g!=null&&g>0?{pid:g}:{},warnings:[...d.warnings,m]}),re.add(d.worker_id),D()}function Fr(d,m){let g=Re("project-register",m,d.project_label);if(!g.permitted)throw new Error(g.reason);let R=o();Ve(R);let v=ks(d,{now:R,held:A.get(d.project_label)});return A.set(v.project_label,v),D(),{version:1,registration:v,reach:g,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 Hr(d,m={}){let g=Re("project-renew",m.sessionProject,d);if(!g.permitted)throw new Error(g.reason);let R=o();Ve(R);let v=A.get(d);if(v==null)throw new Pt(d);let P=Rs(v,{now:R,...m.renewWithinMs==null?{}:{renew_within_ms:m.renewWithinMs},...m.launch==null?{}:{launch:m.launch}});return A.set(P.project_label,P),D(),{version:1,registration:P,reach:g,detail:`redskilled renewed the registration for project ${JSON.stringify(P.project_label)}, which now stands until ${P.renew_by} after renewal ${P.renewals}`+(m.launch==null?"":`, carrying launch revision ${P.launch_revision} for its next Worker`)}}function Vr(d,m){let g=Re("project-deregister",m,d);if(!g.permitted)throw new Error(g.reason);let R=A.delete(d);return{version:1,project_label:d,released:R,reach:g,detail:R?`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 Cl(d,m){try{await O(d)}catch{}return ut(d.worker_id),Y("worker-death",d,m),D(),!0}function Br(d){return Xo({ceiling:i,workers:[...x.values()],budget:d.budget,projectLabel:d.project_label})}function Qt(d){let m=s({spec:d,admission:Br(d),clock:o,onExit:(g,R,v)=>{let P=x.get(g);if(P==null){D();return}Nl(P,R,v).catch(()=>{})}});return x.set(m.worker.worker_id,m.worker),Y("worker-birth",m.worker,null),D(),m}function Y(d,m,g,R={}){Q||b.record({event:d,worker:m,ts:o(),detail:g,...R.exitCode!==void 0?{exitCode:R.exitCode}:{},...R.signal!==void 0?{signal:R.signal}:{}}).catch(()=>{})}async function Jr(){let d=[...re].map(g=>x.get(g)).filter(g=>g!=null);if(d.length===0)return[];let{dead:m}=await Xn(d,_);for(let g of m)ut(g.worker_id),Y("worker-death",g,"the host no longer confirms this Worker");return m.length>0&&D(),m}async function Kr(d,m){let g=x.get(d);if(!g)return!1;try{await O(g)}catch{}return ut(d),Y("worker-budget-kill",g,m),D(),!0}async function qr(){let d=[...x.values()];if(d.length===0)return[];let m;try{m=await ae(d)}catch{return[]}let g=m.rss;$r=g,Ct=o(),Ul(m.cpu_seconds,Ct);let{terminations:R}=xs({workers:d,rss:g}),v=[];for(let P of R)await Kr(P.worker_id,P.reason)&&v.push(P);return v}function Ul(d,m){for(let[g,R]of Object.entries(d)){if(typeof R!="number"||!Number.isFinite(R))continue;let v=x.get(g);v&&x.set(g,{...v,cpu:{cpu_seconds:R,sampled_at:m}})}}async function Fl(){try{return Sr<=0?await _r(n):await new Promise(d=>{let m=setTimeout(()=>d(Yt()),Sr);m.unref(),_r(n).then(g=>{clearTimeout(m),d(g)},()=>{clearTimeout(m),d(Yt())})})}catch{return Yt()}}function Yt(){try{return Ol(n)}catch{return null}}async function Gr(){if(rt(n))return Ft+=1,Ut=o(),Ht="local-build",{act:"hold",reason:"local-build"};let d=Di(await Fl()),m=d.version;Ar=m,Vt=d.newest??null,Ut=o(),Tr=$i({running:n,newest:Vt,supervised:Er});let g=Ai({running:n,published:m,supervised:Er});return Ir=g.act==="replace",Ft+=1,Ht=g.act==="hold"?g.reason:null,Te!=="in-progress"&&(Te=g.act==="replace"?"pending":"none"),g}async function pt(){let d=await Gr();if(d.act!=="replace"||Te==="in-progress")return d;let m=Ti(d,jr);return Te="in-progress",await b.flush().catch(()=>{}),await mt({reason:"replaced"}),Ni(m,t,{...r==null?{}:{idleMs:r},io:jr}),d}function Hl(){Q||Ue!=null||vr<=0||(!Ll&&xr>0&&(at=setTimeout(()=>{pt().catch(()=>{})},xr),at.unref()),Ue=setInterval(()=>{pt().catch(()=>{})},vr),Ue.unref())}function Vl(){Q||Me!=null||it<=0||(Me=setInterval(()=>{qr().catch(()=>{})},it),Me.unref())}function Bl(){Q||Fe!=null||H==null||H.projects.length===0||Pr<=0||(zt().catch(()=>{}),Fe=setInterval(()=>{zt().catch(()=>{})},Pr),Fe.unref())}function Jl(){Q||He!=null||Lr<=0||(He=setInterval(()=>{Mr().catch(()=>{})},Lr),He.unref())}function Kl(){Q||Ce!=null||Dr<=0||(Ce=setInterval(()=>{Cr().catch(()=>{})},Dr),Ce.unref())}function D(){Q||(ke&&clearTimeout(ke),ke=setTimeout(()=>{Jr().catch(()=>{}).then(()=>zr())},r),ke.unref())}function zr(){return x.size>0?(D(),"held-by-workers"):(Ve(o()),A.size>0?(D(),"held-by-registrations"):(ql(),"exited"))}async function ql(){if(!rt(n)){if((await pt().catch(()=>null))?.act==="replace"||Kt||Q)return;if(x.size>0||A.size>0){D();return}}await mt({reason:"idle"})}function ft(d){return as({reason:d,socketPath:t.socketPath,daemonVersion:n,pid:l.pid,workers:[...x.values()],projects:[...A.keys()]})}function Qr(d){if(dt!=null)return dt;let m=d.reason??"requested",g=d.note?.trim();return dt=b.recordDaemonStop({ts:o(),pid:l.pid,socketPath:t.socketPath,reason:m,detail:g==null||g===""?ft(m).detail:`${ft(m).detail} \u2014 ${g}`,...d.signal==null?{}:{signal:d.signal}}).catch(()=>{}),dt}async function mt(d={}){if(Kt)return await qt;Kt=!0,await Qr(d),Q=!0,ke&&clearTimeout(ke),Me&&clearInterval(Me),Ue&&clearInterval(Ue),at&&clearTimeout(at),Fe&&clearInterval(Fe),He&&clearInterval(He),Ce&&clearInterval(Ce),await b.flush().catch(()=>{}),y.close();for(let m of Mt)m.destroy();return await new Promise(m=>y.once("close",()=>m())),await zi(t.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await f.release(c).catch(()=>{}),Nr(),await qt}let Gl=os(await b.read().catch(()=>[])),Zt=await Xn(Gl,_);for(let d of Zt.alive){let m=ii(d),g=m.unit==null||N(m.pid)?null:M(m.unit);x.set(m.worker_id,g!=null&&g>0?{...m,pid:g}:m),re.add(m.worker_id)}for(let d of Zt.dead)Y("worker-death",d,"the Worker ended while no daemon was watching");let zl=si({units:await Promise.resolve(F()).catch(()=>[]),held:[...x.values()],mainPid:M,now:w});for(let d of zl)x.set(d.worker_id,d),re.add(d.worker_id),Y("worker-birth",d,"adopted from an active unit with no birth on this lane");for(let d of Zt.alive){if(d.log_path==null||ye.has(d.worker_id))continue;let m=await he(d.log_path).catch(()=>null);m==null||m.trim()===""||ye.set(d.worker_id,{line:m,published_at:o(),source:"rehydrated"})}y.on("connection",d=>{Mt.add(d),d.once("close",()=>Mt.delete(d)),D(),vf(d,async(m,g)=>{D();let R=await Ql(m);g(R),m.op==="shutdown"&&setImmediate(()=>void mt({reason:"requested"}))})});async function Ql(d){try{if(d.op==="ping")return{id:d.id,ok:!0,value:{pong:!0,protocol_version:Ot,daemon_version:n,pid:l.pid}};if(d.op==="host-state")return{id:d.id,ok:!0,value:ct()};if(d.op==="statusline-payload")return{id:d.id,ok:!0,value:Gt()};if(d.op==="statusline-string")return{id:d.id,ok:!0,value:Il(d.render)};if(d.op==="worker-heartbeat")return{id:d.id,ok:!0,value:Ur(d.heartbeat)};if(d.op==="project-register")return{id:d.id,ok:!0,value:Fr(d.registration,d.session_project)};if(d.op==="project-renew")return{id:d.id,ok:!0,value:Hr(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:Vr(d.project_label,d.session_project)};if(d.op==="worker-command")return{id:d.id,ok:!0,value:await Tl(d.command)};if(d.op==="worker-start"){let g=Re("worker-start",d.session_project,d.spec.project_label);if(!g.permitted)return{id:d.id,ok:!1,error:g.reason};let R=Qt(d.spec);return await b.flush().catch(()=>{}),{id:d.id,ok:!0,value:{worker:R.worker,admission:R.admission,warnings:R.warnings}}}if(d.op==="shutdown"){let g=ft("requested");return await Qr({reason:"requested",...d.detail==null?{}:{note:d.detail}}),{id:d.id,ok:!0,value:g}}let m=d;return{id:m.id??Nt(),ok:!1,error:`unsupported redskilled op: ${m.op??"unknown"}`}}catch(m){return{id:d.id??Nt(),ok:!1,error:m instanceof Error?m.message:String(m)}}}return D(),Vl(),Hl(),Bl(),Jl(),Kl(),{socketPath:t.socketPath,lease:h.lease,startedAt:w,closed:qt,startWorker:Qt,admit:Br,ceiling:()=>i,killWorkerOverBudget:Kr,sampleMemoryBudgets:qr,pollRepositoryActivity:zt,pollQueueDiscovery:Mr,queueDiscovery:()=>oe,driveDemand:Cr,demand:()=>lt,sweepReattached:Jr,publishWorkerHeartbeat:Ur,reattached:()=>[...re].map(d=>x.get(d)).filter(d=>d!=null),flushEvents:()=>b.flush(),trackWorker(d){x.set(d.worker_id,d),Y("worker-birth",d,null),D()},releaseWorker(d){let m=x.get(d),g=x.delete(d);return re.delete(d),ye.delete(d),m&&Y("worker-death",m,"released by the daemon"),D(),g},workerCount:()=>x.size,registerProject:Fr,renewProject:Hr,deregisterProject:Vr,registrations:()=>ct().registrations??[],hostState:ct,statuslinePayload:Gt,evaluateIdle:zr,observePublishedVersion:Gr,checkForReplacement:pt,stopReport:ft,stop:mt}}async function _f(e){for(let t=0;t<2;t++){let n=hf();try{return await new Promise((r,o)=>{n.once("error",o),n.listen(e,()=>{n.off("error",o),r()})}),n}catch(r){if(n.close(),r.code!=="EADDRINUSE")throw r;if(await te(e))throw new De(e);await zi(e,{force:!0})}}throw new De(e)}async function te(e,t=250){try{return(await Rt({socketPath:e,timeoutMs:t},{id:Nt(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function vf(e,t){Uo(e,(n,r)=>t(n,r),(n,r,o)=>{o({id:r?.id??Nt(),ok:!1,error:n instanceof Error?n.message:String(n)})})}X();var Pf=1e4,$e=class extends Error{constructor(n,r){super(`redskilled daemon is unreachable on ${JSON.stringify(n)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}`);this.socketPath=n;this.cause=r;this.name="RedskilledUnreachableError"}};async function mr(e,t={}){try{return await Of(e,t)}catch(n){throw n instanceof le||n instanceof $e?n:new $e(e.socketPath,n)}}async function Of(e,t){if(await xf(jf(e.socketPath),{recursive:!0,mode:448}),await te(e.socketPath))return"already-running";await Lf(e);let n=await Fo(e.lockPath);if(!n)return await Yi(e,t),"joined";try{if(await te(e.socketPath))return"already-running";let r=await Af(e,t);return await Yi(e,t,r),"spawned"}finally{await n.close(),await Ef(e.lockPath,{force:!0})}}async function Lf(e){let n=await jt(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(n!=null&&n.socket_path!==e.socketPath&&N(n.pid))throw new le(e.machineClaimPath,"held",n)}async function Xi(e,t,n={}){await mr(e,n);let r;try{r=await et({socketPath:e.socketPath,timeoutMs:n.requestTimeoutMs??2e3},{...t,id:Zi()})}catch(o){throw new $e(e.socketPath,o)}if(!r.ok)throw new Error(r.error);return r.value}async function el(e,t={},n={}){if(!await te(e.socketPath))return ds(e.socketPath);let r;try{r=await et({socketPath:e.socketPath,timeoutMs:n.requestTimeoutMs??2e3},{id:Zi(),op:"shutdown",...t.detail==null?{}:{detail:t.detail}})}catch(i){throw new $e(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!Wn(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await Df(e.socketPath,t.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 Df(e,t){let n=Date.now()+t;for(;;){if(!await te(e))return!0;if(Date.now()>=n)return!1;await new Promise(r=>setTimeout(r,25))}}async function tl(e,t={}){let n=await Xi(e,{op:"host-state"},t);if(!Ws(n))throw new Error("redskilled daemon returned a malformed host state");return n}async function nl(e,t=void 0,n={}){let r=await Xi(e,{op:"statusline-string",...n.sessionProject!=null?{session_project:n.sessionProject}:{},...t==null?{}:{render:$f(t)}},n);if(!Ts(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function $f(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 Yi(e,t,n){let r=Date.now()+(t.readyTimeoutMs??Pf);for(;;){if(await te(e.socketPath))return;if(n?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(n.entry.entry??n.entry.command)} (resolved as ${n.entry.source}): ${n.failure.message}`);if(Date.now()>=r){let o=n?` from ${JSON.stringify(n.entry.entry??n.entry.command)} (resolved as ${n.entry.source})${n.exit?`, which ${n.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${o}`)}await new Promise(o=>setTimeout(o,25))}}async function Af(e,t){let n=t.serverCommand??(t.serverArgs!=null?process.execPath:void 0),r=await zo({...n!=null?{serverCommand:n}:{},serverArgs:t.serverArgs},t.entryLookup??{}),o={entry:r},s=[...r.args,...fe(e,t.idleMs==null?{}:{idleMs:t.idleMs})],i=Sf(r.command,s,{detached:!0,stdio:"ignore",env:{...t.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}X();import{chmod as dl,mkdir as ul,readFile as pl,stat as Kf,writeFile as qf}from"node:fs/promises";import{homedir as yr}from"node:os";import{dirname as Gf,join as kr}from"node:path";import{join as If}from"node:path";var Tf=[".red","redskilled"],z=448;function ot(e){return If(e,...Tf)}import{join as Nf}from"node:path";var rl=["local","tmp","host"],Wf="local",st="plugins.dev.workspace.target";var gr=class extends Error{constructor(t){super(t),this.name="WorkspaceConfigError"}};function sl(e){let t=xe(e,st),n=Uf(t??"").trim();return n===""?void 0:n}function il(e){let t=(e??"").trim();if(t==="")return{kind:"preset",preset:Wf};let n=rl.find(r=>r===t.toLowerCase());if(n)return{kind:"preset",preset:n};if(t.startsWith("/")||t==="~"||t.startsWith("~/"))return{kind:"custom",parentDir:t};throw new gr(`${st}: unknown workspace target ${JSON.stringify(t)}. Use one of the presets (${rl.join(", ")}) or an absolute parent directory for Workers.`)}function ll(e,t){return e.kind==="preset"?e.preset==="host":Cf(Mf(e.parentDir,t),ot(t))}function Mf(e,t){return e==="~"?ol(t):e.startsWith("~/")?Nf(t,e.slice(2)):ol(e)}function Cf(e,t){return e===t?!0:t==="/"?e.startsWith("/"):e.startsWith(`${t}/`)}function ol(e){let t=e.trim();return t.length>1?t.replace(/\/+$/,""):t}function Uf(e){let t=e.trim(),n=/^(["'])(.*)\1$/.exec(t);return n?n[2]:t}X();import{createHash as Ff}from"node:crypto";import{hostname as Hf}from"node:os";import{join as Wt}from"node:path";var Ae="redskilled.sock",Vf="REDSKILLED_SESSION";function Bf(e={}){let t=e.env??process.env,n=t[Vf]?.trim();if(n)return n;let r=t.XDG_RUNTIME_DIR?.trim();return r||`uid:${e.uid??(typeof process.getuid=="function"?process.getuid():"nouid")}`}function Jf(e={}){return al(e.host??Hf())}function ne(e={}){let t=Bf(e),n=e.runtimeDir??wt({key:`redskilled:${t}`,socketFileName:Ae,env:e.env,uid:e.uid}),r=Jf(e);return{sessionKey:t,sessionKeyHash:al(t),machineIdHash:r,runtimeDir:n,socketPath:Wt(n,Ae),lockPath:Wt(n,"redskilled.spawn.lock"),leasePath:Wt(n,"redskilled.lease.toon"),eventLanePath:Wt(n,ns),machineClaimPath:e.machineClaimPath??Et({env:e.env,machineIdHash:r,platform:e.platform})}}function al(e){return Ff("sha256").update(e).digest("hex").slice(0,12)}var hr="run `/red-setup` (Section E3 \u2014 execution daemon), or `redskilled provision` directly";async function fl(e=yr()){let t=ot(e),n=await wr(t);return n===void 0?(await ul(t,{recursive:!0,mode:z}),await dl(t,z),{path:t,created:!0,tightened:!1,mode:z}):n===z?{path:t,created:!1,tightened:!1,mode:n}:(await dl(t,z),{path:t,created:!1,tightened:!0,mode:z})}var ml={needed:!1,declaredBy:`no ${st} in view`};async function Rr(e={}){let t=e.homeDir??yr(),n=e.declaredTarget?.trim();if(n)return cl(n,t,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return ml;let o=kr(r,".red","config.yaml"),s=await pl(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=sl(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:cl(i,t,o)}function cl(e,t,n){let r=`${st}: ${e} (${n})`;try{return{needed:ll(il(e),t),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function gl(e){let t=[zf(e),Qf(e),Yf(e),Zf(e)],n=t.filter(o=>o.verdict!=="ok");return{verdict:n.some(o=>o.verdict==="missing")?"missing":n.length>0?"degraded":"ok",rows:t,findings:n}}function zf(e){let t=e.homeNeed??ml;if(!e.homePresent)return t.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${t.declaredBy}`,fix:hr}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${t.declaredBy}; the daemon never reads it`,fix:""};let n=e.homeMode??z;return n!==z?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${n.toString(8)}, not owner-only ${z.toString(8)}`,fix:`${hr} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${n.toString(8)})`,fix:""}}function Qf(e){return G(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 Yf(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:`${hr} \u2014 it starts the daemon and waits for the socket`}}function Zf(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 hl(e={}){let t=e.env??process.env,n=e.homeDir??yr(),r=e.paths??ne({env:t}),o=ot(n),[s,i,l]=await Promise.all([wr(o),te(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Rr({homeDir:n,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:ie(e.entryOverride??{},{env:t,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await em(tm(e,t,n),t)}}var Xf="redskilled.service";function yl(e){return kr(e,"systemd","user",Xf)}function kl(e){let t=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${t}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
61
+ `)}async function Rl(e){let t=yl(e.configHome);return await wr(t)!==void 0?{path:t,status:"already-present"}:(await ul(Gf(t),{recursive:!0}),await qf(t,e.unit,"utf8"),{path:t,status:"installed"})}async function em(e,t){if(process.platform!=="linux")return"unsupported";try{return await pl(yl(e),"utf8"),"installed"}catch{return t.XDG_RUNTIME_DIR?"absent":"unsupported"}}function tm(e,t,n){return e.configHome??t.XDG_CONFIG_HOME?.trim()??kr(n,".config")}async function wr(e){try{return(await Kf(e)).mode&511}catch{return}}import{readdir as bl,rm as nm,stat as rm}from"node:fs/promises";import{dirname as om,join as br}from"node:path";var sm=5*6e4,im="redskilled.";function lm(e={}){let t=e.env??process.env,n=i=>om(wt({key:"redskilled:reclaim-probe",socketFileName:Ae,env:i,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=t,s=[n(t),n(o)];return[...new Set(s)]}async function _l(e={}){let t=e.roots??lm(e),n=e.graceMs??sm,r=e.now??Date.now,o=e.isPidAlive??N,s=e.answers??um,i=e.dryRun===!0,l=[];for(let a of t){let c;try{c=(await bl(a,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name)}catch{continue}for(let u of c.sort())l.push(await am(br(a,u),{graceMs:n,now:r,pidAlive:o,answers:s,dryRun:i}))}return{roots:t,scanned:l.length,reclaimed:l.filter(a=>a.verdict==="reclaimed").length,dryRun:i,entries:l}}async function am(e,t){let n;try{n=(await bl(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:vl(i),removed:[]}}let r=n.filter(i=>i.startsWith(im));if(n.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await dm(br(e,"redskilled.lease.toon"));if(o!==void 0)return await t.pidAlive(o.pid)?{dir:e,verdict:"live",reason:`lease pid ${o.pid} is alive`,removed:[]}:await wl(e,n,`lease pid ${o.pid} is dead`,t);if(n.includes(Ae)&&await t.answers(br(e,Ae)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await cm(e,t.now);return s!==void 0&&s<t.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(s/1e3)}s ago`,removed:[]}:await wl(e,n,n.length===0?"empty and stale":"no lease and stale",t)}async function wl(e,t,n,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${n} (dry run)`,removed:t};try{await nm(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:vl(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:n,removed:t}}async function dm(e){try{return await pr(e)}catch{return}}async function cm(e,t){try{return Math.max(0,t()-(await rm(e)).mtimeMs)}catch{return}}async function um(e){try{return(await et({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function vl(e){return e instanceof Error?e.message:String(e)}var pm="plugins.dev.statusline",fm="dev.statusline";function mm(e){let t=[],n=l=>{for(let a of[pm,fm]){let c=`${a}.${l}`,u=xe(e,c)?.trim();if(u!=null&&u!=="")return{key:c,value:u}}},r=n("mode"),o={};r!=null&&(r.value==="local"||r.value==="global"?o.mode=r.value:t.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=n(l.leaf);if(a==null)continue;let c=Number(a.value);Number.isInteger(c)&&c>=0?l.assign(c):t.push({...a,reason:"expected a whole number of zero or more"})}let i=n("verbose");return i!=null&&(i.value==="true"||i.value==="false"?o.verbose=i.value==="true":t.push({...i,reason:"expected `true` or `false`"})),{config:o,warnings:t}}var gm={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 Sl(e){let{values:t,positionals:n}=pe(e,gm),r=[],o={},s=t.mode??n.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`"})),t.project!=null&&(o.project=t.project),t.verbose!==void 0&&(o.verbose=t.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=t[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 xl(e={}){let t=e.configText==null?{config:{},warnings:[]}:mm(e.configText),n=e.flags??{};return{options:{...L,mode:n.mode??t.config.mode??L.mode,project:n.project!==void 0?n.project:e.project??L.project,maxWorkers:n.maxWorkers??t.config.maxWorkers??L.maxWorkers,maxProjects:n.maxProjects??t.config.maxProjects??L.maxProjects,maxWidth:n.maxWidth??t.config.maxWidth??L.maxWidth,verbose:n.verbose??t.config.verbose??L.verbose},warnings:t.warnings}}var km=`Usage: redskilled <command> [options]
62
62
 
63
63
  Commands:
64
64
  host-state (default) print the host's state as JSON
@@ -70,7 +70,7 @@ Commands:
70
70
 
71
71
  Run \`redskilled <command> --help\` for a command's own usage.
72
72
  \`--version\` (\`-v\`) prints the build stamp; both answer offline.
73
- `,km={serve:`Usage: redskilled serve [options]
73
+ `,Rm={serve:`Usage: redskilled serve [options]
74
74
 
75
75
  Runs the daemon in this process. Every path is a flag and none is derived
76
76
  (ADR 0130 rule 3); what is absent falls back to the session derivation.
@@ -134,18 +134,18 @@ Reports every session runtime dir it looked at and why it kept or removed it.
134
134
 
135
135
  --dry-run the same report with nothing removed
136
136
  --grace-ms <n> how long a dir must be idle before it is reclaimed
137
- `};function Rm(e){return e==="--help"||e==="-h"||e==="help"}var wm={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)}},jl="REDSKILLED_HOST_TOKEN";function Pl(){try{let t=gm("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return t===""?null:t}catch{return null}}function bm(e=process.env,t=Pl){let n=(e[jl]??e.GITHUB_TOKEN??e.GH_TOKEN??"").trim();if(n!=="")return{token:n,source:"env"};let r=(t()??"").trim();return r!==""?{token:r,source:"tracker-cli"}:null}function _m(e,t=process.env,n=Pl){let r=e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},o=bm(t,n);if(o==null)return{...r,unconfiguredReason:`no credential names a tracker for this host: ${jl}, GITHUB_TOKEN and GH_TOKEN are all unset in the daemon's environment and \`gh auth token\` returned nothing \u2014 so no queue depth is asked for, and no depth is invented either`};let s=e["queue-endpoint"]??t.GITHUB_GRAPHQL_URL;return{...r,transport:Ls({token:o.token,...s?{endpoint:s}:{}})}}async function vm(e){if(e[0]==="--version"||e[0]==="-v"){let o=gn("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
137
+ `};function wm(e){return e==="--help"||e==="-h"||e==="help"}var bm={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)}},jl="REDSKILLED_HOST_TOKEN";function Pl(){try{let t=hm("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return t===""?null:t}catch{return null}}function _m(e=process.env,t=Pl){let n=(e[jl]??e.GITHUB_TOKEN??e.GH_TOKEN??"").trim();if(n!=="")return{token:n,source:"env"};let r=(t()??"").trim();return r!==""?{token:r,source:"tracker-cli"}:null}function vm(e,t=process.env,n=Pl){let r=e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},o=_m(t,n);if(o==null)return{...r,unconfiguredReason:`no credential names a tracker for this host: ${jl}, GITHUB_TOKEN and GH_TOKEN are all unset in the daemon's environment and \`gh auth token\` returned nothing \u2014 so no queue depth is asked for, and no depth is invented either`};let s=e["queue-endpoint"]??t.GITHUB_GRAPHQL_URL;return{...r,transport:Ds({token:o.token,...s?{endpoint:s}:{}})}}async function Sm(e){if(e[0]==="--version"||e[0]==="-v"){let o=hn("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
138
138
  `:`${Ro(o)}
139
- `),0}if(Rm(e[0]))return process.stdout.write(ym),0;let{command:t,args:n}=vo(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(n.some(o=>o==="--help"||o==="-h"))return process.stdout.write(km[t]),0;if(t==="serve"){let{values:o}=pe(n,wm),s=_m(o),i=await Qi({paths:Im(o),idleMs:o["idle-ms"]??fr,daemonVersion:o["daemon-version"]??gn("redskilled").version,queueDiscovery:s,...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let l of["SIGTERM","SIGINT"])process.once(l,()=>void i.stop({reason:"signal",signal:l}).catch(()=>{}));return await i.closed,0}if(t==="stop")return await xm(n);if(t==="statusline")return await jm(n);if(t==="unit")return await Em(n);if(t==="provision")return await Om(n);if(t==="reclaim")return await Lm(n);let r=await tl(ne());return process.stdout.write(`${JSON.stringify(r,null,2)}
140
- `),0}var Sm={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function xm(e,t={}){let n=t.write??(s=>process.stdout.write(s)),{values:r}=pe(e,Sm),o=await el(t.paths??ne(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},t.client??{});return n(`${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})}
141
- `),o.running&&!o.stopped?1:0}async function Em(e,t={}){let n=t.write??(s=>process.stdout.write(s)),r=t.paths??ne(),o=e[0]??"status";if(o==="status")return n(`${JSON.stringify(Si(t.unitIO??{}),null,2)}
139
+ `),0}if(wm(e[0]))return process.stdout.write(km),0;let{command:t,args:n}=vo(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(n.some(o=>o==="--help"||o==="-h"))return process.stdout.write(Rm[t]),0;if(t==="serve"){let{values:o}=pe(n,bm),s=vm(o),i=await Qi({paths:Tm(o),idleMs:o["idle-ms"]??fr,daemonVersion:o["daemon-version"]??hn("redskilled").version,queueDiscovery:s,...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let l of["SIGTERM","SIGINT"])process.once(l,()=>void i.stop({reason:"signal",signal:l}).catch(()=>{}));return await i.closed,0}if(t==="stop")return await Em(n);if(t==="statusline")return await Pm(n);if(t==="unit")return await jm(n);if(t==="provision")return await Lm(n);if(t==="reclaim")return await $m(n);let r=await tl(ne());return process.stdout.write(`${JSON.stringify(r,null,2)}
140
+ `),0}var xm={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function Em(e,t={}){let n=t.write??(s=>process.stdout.write(s)),{values:r}=pe(e,xm),o=await el(t.paths??ne(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},t.client??{});return n(`${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})}
141
+ `),o.running&&!o.stopped?1:0}async function jm(e,t={}){let n=t.write??(s=>process.stdout.write(s)),r=t.paths??ne(),o=e[0]??"status";if(o==="status")return n(`${JSON.stringify(Si(t.unitIO??{}),null,2)}
142
142
  `),0;if(o==="install"){let s=await _i(wi(r),t.unitIO??{});return n(`${JSON.stringify(s,null,2)}
143
143
  `),s.installed?0:1}if(o==="uninstall")return n(`${JSON.stringify(await vi(t.unitIO??{}),null,2)}
144
- `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function jm(e,t={}){let n=t.write??(a=>process.stdout.write(a)),r=t.warn??(a=>process.stderr.write(a)),o=Sl(e),s=Am(t.cwd??process.cwd()),i=xl({...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}
144
+ `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function Pm(e,t={}){let n=t.write??(a=>process.stdout.write(a)),r=t.warn??(a=>process.stderr.write(a)),o=Sl(e),s=Im(t.cwd??process.cwd()),i=xl({...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}
145
145
  `);let l;try{l=await nl(t.paths??ne(),i.options,{...t.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(a){r(`redskilled statusline: ${a instanceof Error?a.message:String(a)}
146
146
  `),l=mi({options:i.options,generated_at:(t.now??(()=>new Date().toISOString()))()})}return n(`${l.lines.join(`
147
147
  `)}
148
- `),0}var Pm={"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 Om(e,t={}){let n=t.write??(p=>process.stdout.write(p)),{values:r}=pe(e,Pm),o=t.paths??ne(),s=t.homeDir??El(),i=await Rr({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??t.projectRoot??process.cwd()}),l=r.check||!i.needed?void 0:await fl(s),a;if(!r.check&&!r["no-start"])try{await mr(o,t.client??{})}catch(p){a=p instanceof Error?p.message:String(p)}let c=await hl({paths:o,homeNeed:i,...t.homeDir==null?{}:{homeDir:t.homeDir},...t.configHome==null?{}:{configHome:t.configHome},...t.client?.serverCommand==null?{}:{entryOverride:{serverCommand:t.client.serverCommand,serverArgs:t.client.serverArgs}}}),u=r["install-unit"]&&G(c.entry)?await Rl({configHome:t.configHome??$m(),unit:kl({command:[c.entry.command,...c.entry.args].join(" "),socketPath:o.socketPath})}):void 0,f=gl(c);return n(`${I({verdict:f.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:f.rows.map(p=>({check:p.check,verdict:p.verdict,evidence:p.evidence})),fixes:f.findings.map(p=>({check:p.check,fix:p.fix}))})}
149
- `),f.verdict==="ok"?0:1}var Dm={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function Lm(e,t={}){let n=t.write??(s=>process.stdout.write(s)),{values:r}=pe(e,Dm),o=await _l({...t.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return n(`${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]}))})}
150
- `),o.entries.some(s=>s.verdict==="failed")?1:0}function $m(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:hm(El(),".config")}function Am(e){let t=bn(e);return t.configText==null?{label:null}:{configText:t.configText,label:Lo(e)}}function Im(e){let t=ne();return{...t,socketPath:e.socket??t.socketPath,leasePath:e.lease??t.leasePath,eventLanePath:e.events??t.eventLanePath,sessionKeyHash:e["session-key-hash"]??t.sessionKeyHash,machineIdHash:e["machine-id-hash"]??t.machineIdHash,machineClaimPath:e["machine-claim"]??t.machineClaimPath}}var Tm=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;Tm&&vm(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
151
- `),process.exitCode=1});export{jl as REDSKILLED_HOST_TOKEN_ENV,ym as REDSKILLED_USAGE,bm as resolveRedskilledHostToken,_m as resolveServeQueueDiscovery,Om as runProvision,Lm as runReclaim,vm as runRedskilledCli,jm as runStatusline,xm as runStop,Em as runUnit};
148
+ `),0}var Om={"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 Lm(e,t={}){let n=t.write??(p=>process.stdout.write(p)),{values:r}=pe(e,Om),o=t.paths??ne(),s=t.homeDir??El(),i=await Rr({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??t.projectRoot??process.cwd()}),l=r.check||!i.needed?void 0:await fl(s),a;if(!r.check&&!r["no-start"])try{await mr(o,t.client??{})}catch(p){a=p instanceof Error?p.message:String(p)}let c=await hl({paths:o,homeNeed:i,...t.homeDir==null?{}:{homeDir:t.homeDir},...t.configHome==null?{}:{configHome:t.configHome},...t.client?.serverCommand==null?{}:{entryOverride:{serverCommand:t.client.serverCommand,serverArgs:t.client.serverArgs}}}),u=r["install-unit"]&&G(c.entry)?await Rl({configHome:t.configHome??Am(),unit:kl({command:[c.entry.command,...c.entry.args].join(" "),socketPath:o.socketPath})}):void 0,f=gl(c);return n(`${I({verdict:f.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:f.rows.map(p=>({check:p.check,verdict:p.verdict,evidence:p.evidence})),fixes:f.findings.map(p=>({check:p.check,fix:p.fix}))})}
149
+ `),f.verdict==="ok"?0:1}var Dm={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function $m(e,t={}){let n=t.write??(s=>process.stdout.write(s)),{values:r}=pe(e,Dm),o=await _l({...t.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return n(`${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]}))})}
150
+ `),o.entries.some(s=>s.verdict==="failed")?1:0}function Am(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:ym(El(),".config")}function Im(e){let t=_n(e);return t.configText==null?{label:null}:{configText:t.configText,label:Do(e)}}function Tm(e){let t=ne();return{...t,socketPath:e.socket??t.socketPath,leasePath:e.lease??t.leasePath,eventLanePath:e.events??t.eventLanePath,sessionKeyHash:e["session-key-hash"]??t.sessionKeyHash,machineIdHash:e["machine-id-hash"]??t.machineIdHash,machineClaimPath:e["machine-claim"]??t.machineClaimPath}}var Nm=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;Nm&&Sm(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
151
+ `),process.exitCode=1});export{jl as REDSKILLED_HOST_TOKEN_ENV,km as REDSKILLED_USAGE,_m as resolveRedskilledHostToken,vm as resolveServeQueueDiscovery,Lm as runProvision,$m as runReclaim,Sm as runRedskilledCli,Pm as runStatusline,Em as runStop,jm as runUnit};