@reddb-io/red-skills 3.0.4 → 3.1.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,67 +1,151 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- import{readFileSync as Fc}from"node:fs";import{homedir as bi}from"node:os";import{join as Vc}from"node:path";var je=class extends Error{constructor(t,n){super(t===0?n:`line ${t}: ${n}`),this.name="ToonError",this.line=t,this.reason=n}},ee=class extends Error{constructor(t,n){super(t===0?n:`line ${t}: ${n}`),this.name="ToonlError",this.line=t,this.reason=n}};function g(e,t){return new je(e,t)}function v(e,t){return new ee(e,t)}function ue(e){return e instanceof ee?e:e instanceof je?new ee(e.line,e.reason):new ee(0,String(e&&e.message?e.message:e))}var S=",";function He(e){let t=e.split(`
4
- `);return t.length>0&&t[t.length-1]===""&&t.pop(),t.map(n=>n.endsWith("\r")?n.slice(0,-1):n)}function D(e){return g(e,"invalid quoted string")}function W(e,t){if(e==="")return"";if(e.startsWith('"'))return Mn(e,t);if(e.includes('"'))throw D(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:Ci(e)?Number(e):e}function H(e,t){let n=e.trim();if(n.startsWith('"'))return[Mn(n,t),!0];if(n.includes('"')||/\s/.test(n))throw g(t,"expected non-empty field name");return[n,!1]}function Mn(e,t){if(e[0]!=='"')throw D(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 D(t)}if(o==="\\"){let i=e[r];switch(r+=1,i){case'"':n+='"';break;case"\\":n+="\\";break;case"n":n+=`
5
- `;break;case"r":n+="\r";break;case"t":n+=" ";break;case"u":{let s=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw D(t);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw D(t);n+=String.fromCharCode(a),r+=4;break}default:throw D(t)}continue}if(o<" "&&o!==" ")throw D(t);n+=o}throw D(t)}function te(e,t,n){if(e==="")return[];let r=[],o=0,i=!1,s=!1;for(let a=0;a<e.length;a+=1){let l=e[a];if(s){s=!1;continue}l==="\\"&&i?s=!0:l==='"'?i=!i:l===t&&!i&&(r.push(e.slice(o,a).trim()),o=a+1)}if(i||s)throw D(n);return r.push(e.slice(o).trim()),r}function O(e,t,n){let r=!1,o=!1;for(let i=0;i<e.length;i+=1){let s=e[i];if(o){o=!1;continue}if(s==="\\"&&r)o=!0;else if(s==='"')r=!r;else if(s===t&&!r)return i}if(r||o)throw D(n);return-1}function Ci(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Di(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Wi(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw g(0,"number is not representable in TOON");return String(e)}function Oe(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function M(e,t){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Wi(e);if(typeof e=="string")return Ui(e,t);throw g(0,"not a primitive")}function Mi(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function T(e){return Mi(e)?e:Un(e)}function Ui(e,t){return Fi(e,t)?Un(e):e}function Fi(e,t){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Di(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")}function Un(e){let t='"';for(let n of e)switch(n){case'"':t+='\\"';break;case"\\":t+="\\\\";break;case`
6
- `: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 fe(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}var St=2;function Vi(e={}){return{indent:Math.max(1,e.indent??St),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function Hi(e,t){let n=[],r=!1;return He(e).forEach((o,i)=>{let s=i+1;if(o.trim()===""){r=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw g(s,"invalid indentation");if(t.strict&&a%t.indent!==0)throw g(s,"invalid indentation");n.push({number:s,depth:Math.floor(a/t.indent),content:o.slice(a),blankBefore:r}),r=!1}),n}function K(e,t){let n=Vi(t),r=Hi(e,n),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw g(o.number,"invalid indentation");let i=r.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){let d;try{d=jt(o.content,O(o.content,":",o.number))}catch(c){if(n.strict)throw vt(c,o.number);d=void 0}if(d!==void 0)return Ki(d,r,n)}if(i&&O(o.content,":",o.number)===-1)return W(o.content.trim(),o.number);let s={index:0},a=Et(r,s,0,n),l=r[s.index];if(l!==void 0)throw g(l.number,"expected end of document");return a}function Et(e,t,n,r){let o={};for(;t.index<e.length;){let i=e[t.index];if(i.depth<n)break;if(i.depth>n)throw g(i.number,"invalid indentation");let{key:s,quoted:a,value:l}=Ji(e,t,n,r);Hn(o,s,a,l,r,i.number)}return o}function Ji(e,t,n,r){let o=e[t.index],i=o.content,s=O(i,":",o.number);if(s===-1)throw g(o.number,"expected `key: value`");let a=i.slice(0,s),l=i.slice(s+1),d=O(a,"[",o.number),c=O(a,"{",o.number);if(c!==-1&&(d===-1||c<d)){let h;try{h=Yi(a)}catch(b){if(r.strict)throw vt(b,o.number);t.index+=1;let w=Rt(e,t,n,l,o.number,r);return{key:a.trim(),quoted:!1,value:w}}if(l.trim()!=="")throw g(o.number,"expected keyed map rows");let R=Bi(h,e,t,n+1,r);return{key:h.key,quoted:h.keyQuoted,value:R}}if(d!==-1){let h;try{h=jt(a,s)}catch(b){if(r.strict)throw vt(b,o.number);t.index+=1;let w=Rt(e,t,n,l,o.number,r);return{key:a.trim(),quoted:!1,value:w}}if(h.key===""&&!h.keyQuoted)throw g(o.number,"expected non-empty field name");let R=Pt(h,l,e,t,n,r);return{key:h.key,quoted:h.keyQuoted,value:R}}let[f,p]=H(a,o.number);if(f===""&&!p)throw g(o.number,"expected non-empty field name");t.index+=1;let m=Rt(e,t,n,l,o.number,r);return{key:f,quoted:p,value:m}}function Rt(e,t,n,r,o,i){let s=r.trim();if(s==="[]")return[];if(s!=="")return W(s,o);let a=e[t.index];return a!==void 0&&a.depth>n?Et(e,t,n+1,i):{}}function Bi(e,t,n,r,o){let i={};for(n.index+=1;n.index<t.length;){let s=t[n.index];if(s.depth<r)break;if(s.depth>r)throw g(s.number,"invalid indentation");if(s.blankBefore&&o.strict)throw g(s.number,"blank line inside keyed map");let a=O(s.content,":",s.number);if(a===-1)throw g(s.number,"expected `key: value`");let[l,d]=H(s.content.slice(0,a),s.number);if(l===""&&!d)throw g(s.number,"expected non-empty field name");let c=te(s.content.slice(a+1).trim(),e.delimiter,s.number);if(c.length!==e.fields.length)throw g(s.number,"keyed map row length mismatch");let f={};e.fields.forEach((p,m)=>{$e(f,p,W(c[m],s.number),o,s.number)}),Hn(i,l,d,f,o,s.number),n.index+=1}return i}function Ki(e,t,n){let r=t[0],o=O(r.content,":",r.number);if(o===-1)throw g(r.number,"expected `key: value`");let i=r.content.slice(o+1),s={index:0},a=Pt(e,i,t,s,0,n),l=t[s.index];if(l!==void 0)throw g(l.number,"expected end of document");return a}function Pt(e,t,n,r,o,i){let s=n[r.index].number,a=t.trim();if(r.index+=1,e.fields!==void 0){if(a!=="")throw g(s,"expected tabular rows");return qi(e,e.fields,n,r,o+1,i)}if(a!==""){let l=te(a,e.delimiter,s).map(d=>W(d,s));if(l.length!==e.len)throw g(s,"array length mismatch");return l}return zi(e,n,r,o+1,i)}function qi(e,t,n,r,o,i){let s=[];for(;s.length<e.len;){let l=n[r.index];if(l===void 0)throw wt(n,r.index);if(l.depth<o)break;if(l.depth>o)throw g(l.number,"invalid indentation");if(l.blankBefore&&i.strict)throw g(l.number,"blank line inside array");if(!Fn(l.content,e.delimiter,l.number))break;let d=te(l.content,e.delimiter,l.number);if(d.length!==t.length)throw g(l.number,"array row length mismatch");let c={};t.forEach((f,p)=>{$e(c,f,W(d[p],l.number),i,l.number)}),s.push(c),r.index+=1}if(s.length!==e.len)throw wt(n,r.index);let a=n[r.index];if(a!==void 0&&a.depth>=o&&Fn(a.content,e.delimiter,a.number))throw g(a.number,"array length mismatch");return s}function Fn(e,t,n){let r=O(e,":",n);if(r===-1)return!0;let o=O(e,t,n);return o===-1?!1:o<r}function zi(e,t,n,r,o){let i=[];for(;i.length<e.len;){let a=t[n.index];if(a===void 0||a.depth<r)throw wt(t,n.index);if(a.depth>r)throw g(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw g(a.number,"blank line inside array");i.push(Gi(t,n,r,o))}let s=t[n.index];if(s!==void 0&&s.depth>=r)throw g(s.number,"array length mismatch");return i}function Gi(e,t,n,r){let o=e[t.index];if(!o.content.startsWith("-"))throw g(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return t.index+=1,{};if(i.startsWith("[")){let s=O(i,":",o.number),a;try{a=jt(i,s)}catch{a=void 0}if(a!==void 0){let l=i.slice(s+1);return Pt(a,l,e,t,n,r)}}if(O(i,":",o.number)!==-1){let s=[{number:o.number,depth:n+1,content:i,blankBefore:!1}];for(t.index+=1;t.index<e.length;){let a=e[t.index];if(a.depth<=n)break;s.push(a),t.index+=1}return Et(s,{index:0},n+1,r)}return t.index+=1,W(i,o.number)}function wt(e,t){let n=e[t]??e[e.length-1];return g(n===void 0?1:n.number,"array length mismatch")}function jt(e,t){if(t===-1)throw g(0,"array header missing colon");let n=e.slice(0,t),r=O(n,"[",0);if(r===-1)throw g(0,"invalid array header");let o,i;try{[o,i]=H(n.slice(0,r),0)}catch{throw g(0,"invalid array header")}let s=n.slice(r+1),a=s.indexOf("]");if(a===-1)throw g(0,"invalid array header");let l=s.slice(0,a),d=/^[0-9]*/.exec(l)[0];if(d===""||d.length>1&&d.startsWith("0"))throw g(0,"invalid array header");let c=Number.parseInt(d,10),f;switch(l.slice(d.length)){case"":f=",";break;case" ":f=" ";break;case"|":f="|";break;default:throw g(0,"invalid array header")}let p=s.slice(a+1),m;if(p==="")m=void 0;else if(p.startsWith("{")&&p.endsWith("}")&&p.length>=2)try{m=Vn(p.slice(1,-1),f)}catch(h){throw g(0,h.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw g(0,"invalid array header");return{key:o,keyQuoted:i,len:c,delimiter:f,fields:m}}function Yi(e){let t=O(e,"{",0);if(t===-1||!e.endsWith("}"))throw g(0,"invalid keyed map header");let n,r;try{[n,r]=H(e.slice(0,t),0)}catch{throw g(0,"invalid keyed map header")}if(n===""&&!r)throw g(0,"expected non-empty field name");let o;try{o=Vn(e.slice(t+1,-1),S)}catch(i){throw g(0,i.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:n,keyQuoted:r,delimiter:S,fields:o}}function Vn(e,t){let n=[],r=0;function o(a,l){let d=0;for(;r<e.length&&!(l&&e[r]==="}");){if(e[r]===t||e[r]==="}")throw g(0,"invalid array header");let c=r;for(;r<e.length;){let p=e[r];if(p==='"'){i();continue}if(p===t||p==="{"||p==="}")break;r+=1}let[f]=H(e.slice(c,r),0);if(f==="")throw g(0,"invalid array header");if(d+=1,e[r]==="{"){r+=1;let p=n.length;if(o([...a,f],!0),e[r]!=="}"||n.length===p)throw g(0,"invalid array header");r+=1}else n.push([...a,f]);if(e[r]===t){if(r+=1,r>=e.length||e[r]==="}")throw g(0,"invalid array header");continue}if(l?e[r]==="}":r===e.length)break;throw g(0,"invalid array header")}if(d===0)throw g(0,"invalid array header")}function i(){for(r+=1;r<e.length;){let a=e[r];if(r+=1,a==="\\")r+=1;else if(a==='"')return}}if(o([],!1),r!==e.length)throw g(0,"invalid array header");let s=new Set;for(let a=0;a<n.length;a+=1)for(let l=a+1;l<n.length;l+=1)if(Zi(n[a],n[l])||_t(n[a],n[l])||_t(n[l],n[a]))throw g(0,"duplicate key");for(let a of n){let l=a.join("\0");if(s.has(l))throw g(0,"duplicate key");s.add(l)}return n}function Zi(e,t){return e.length===t.length&&_t(e,t)}function _t(e,t){return t.every((n,r)=>e[r]===n)}function vt(e,t){return g(t,e.reason??String(e.message))}function Hn(e,t,n,r,o,i){if(o.expandPaths&&!n&&t.includes(".")){let s=t.split(".");if(s.every(Xi)){$e(e,s,r,o,i);return}}$e(e,[t],r,o,i)}function $e(e,t,n,r,o){let i=t[0],s=Object.prototype.hasOwnProperty.call(e,i);if(t.length===1){if(s&&r.strict)throw g(o,"duplicate key");fe(e,i,n);return}if(s&&!pe(e[i])){if(r.strict)throw g(o,"path expansion conflict");fe(e,i,{})}else s||fe(e,i,{});$e(e[i],t.slice(1),n,r,o)}function Xi(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function pe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function L(e,t={}){let n={nestedTabularHeaders:t.nestedTabularHeaders===!0,keyedMapCollapse:t.keyedMapCollapse===!0},r=[];return Array.isArray(e)?Ot(r,void 0,e,0,!1,n):pe(e)?Jn(r,e,0,n):r.push(M(e,S)),r.join("")}function Le(e,t){e.push(" ".repeat(t*St))}function Jn(e,t,n,r){for(let[o,i]of Object.entries(t))Le(e,n),xt(e,o,i,n,r)}function xt(e,t,n,r,o){if(Array.isArray(n)){Ot(e,t,n,r,!1,o);return}if(pe(n)){let i=o.keyedMapCollapse?es(n,o):void 0;if(i!==void 0){e.push(T(t),"{",i.fields.map($t).join(S),`}:
7
- `);for(let[s,a]of Object.entries(n))Le(e,r+1),e.push(T(s),": ",i.paths.map(l=>M(zn(a,l),S)).join(S),`
8
- `);return}e.push(T(t),`:
9
- `),Jn(e,n,r+1,o);return}e.push(T(t),": ",M(n,S),`
10
- `)}function Ot(e,t,n,r,o,i){if(n.length===0){t!==void 0?e.push(T(t),`: []
3
+ var Ea=Object.defineProperty;var ja=(e,t)=>()=>(e&&(t=e(e=0)),t);var Pa=(e,t)=>{for(var n in t)Ea(e,n,{get:t[n],enumerable:!0})};var Lo={};Pa(Lo,{REDSKILLED_BIN_ENV:()=>_n,REDSKILLED_BUNDLE_ASSET:()=>q,REDSKILLED_ENTRY_UNRESOLVED:()=>Ke,RedskilledDaemonEntryError:()=>qe,isRedskilledEntryPath:()=>xn,isResolvedRedskilledEntry:()=>G,redskilledBundleCacheRoot:()=>ht,redskilledServeArgv:()=>pe,requireRedskilledEntry:()=>yt,resolveRedskilledEntry:()=>se});import{existsSync as sd,readdirSync as id}from"node:fs";import{homedir as ad}from"node:os";import{basename as bn,dirname as wn,join as W,resolve as gt}from"node:path";function G(e){return"command"in e}function pe(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 ht(e=process.env){return Do(e)}function se(e={},t={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let n=t.env??process.env,r=t.exists??sd,o=t.execPath??process.execPath,s=t.execArgv??[],i=t.callerEntry===void 0?process.argv[1]:t.callerEntry,a=(u,f)=>({command:o,args:[...s,u],source:f,entry:u}),l=n[_n];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(i&&xn(i))return a(gt(i),"caller-entry");let d=[];for(let[u,f]of ud(i,t.rootDir,n,t.listDir??md))if(d.push(u),r(u))return a(u,f);return{diagnostic:Ke,searched:d,...i?{callerEntry:gt(i)}:{}}}function yt(e={},t={}){let n=se(e,t);if(G(n))return n;throw new qe(n)}function xn(e){let t=bn(e);return t===q||vn.test(t)||t==="red-skills-redskilled"||t==="red-skills-redskilled.mjs"?!0:t!=="cli.js"&&t!=="cli.mjs"&&t!=="cli.ts"?!1:cd(gt(e))}function cd(e){let t=wn(e);for(let n=0;n<4;n++){if(bn(t)==="redskilled")return!0;let r=wn(t);if(r===t)return!1;t=r}return!1}function*ud(e,t,n,r){if(e){let s=wn(gt(e));yield[W(s,q),"caller-sibling-bundle"];let i=ld.exec(bn(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 dd){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=Do(n);yield[W(o,q),"bundle-cache"];for(let s of pd(o,r))yield[W(o,s),"bundle-cache"]}function Do(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 pd(e,t){return t(e).filter(n=>vn.test(n)).sort((n,r)=>fd(Oo(r),Oo(n)))}function Oo(e){return vn.exec(e)?.[1]??""}function fd(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,a]=[r[s],o[s]];if(Number.isNaN(i)||i===void 0)return Number.isNaN(a)||a===void 0?e.localeCompare(t):-1;if(Number.isNaN(a)||a===void 0)return 1;if(i!==a)return i-a}return 0}function md(e){try{return id(e)}catch{return[]}}var q,Ke,_n,qe,ld,vn,dd,Z=ja(()=>{"use strict";q="redskilled.bundle.min.mjs",Ke="redskilled-daemon-entry-unresolved",_n="REDSKILLED_BIN";qe=class extends Error{code=Ke;searched;callerEntry;constructor(t){super(`${Ke}: no published ${q} found to spawn the redskilled daemon from${t.callerEntry?` (caller entry: ${t.callerEntry}, which is NOT used as a fallback)`:""}
4
+ searched:
5
+ ${t.searched.map(n=>` ${n}`).join(`
6
+ `)}`),this.name="RedskilledDaemonEntryError",this.searched=t.searched,t.callerEntry!=null&&(this.callerEntry=t.callerEntry)}};ld=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,vn=/^redskilled-(.+)\.bundle\.min\.mjs$/,dd=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{homedir as la}from"node:os";import{join as Hf}from"node:path";var Fe=class extends Error{constructor(t,n){super(t===0?n:`line ${t}: ${n}`),this.name="ToonError",this.line=t,this.reason=n}},le=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 Fe(e,t)}function v(e,t){return new le(e,t)}function Re(e){return e instanceof le?e:e instanceof Fe?new le(e.line,e.reason):new le(0,String(e&&e.message?e.message:e))}var E=",";function ct(e){let t=e.split(`
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 J(e,t){if(e==="")return"";if(e.startsWith('"'))return Cr(e,t);if(e.includes('"'))throw V(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:Oa(e)?Number(e):e}function Y(e,t){let n=e.trim();if(n.startsWith('"'))return[Cr(n,t),!0];if(n.includes('"')||/\s/.test(n))throw k(t,"expected non-empty field name");return[n,!1]}function Cr(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
+ `;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 a=Number.parseInt(i,16);if(a>=55296&&a<=57343)throw V(t);n+=String.fromCharCode(a),r+=4;break}default:throw V(t)}continue}if(o<" "&&o!==" ")throw V(t);n+=o}throw V(t)}function de(e,t,n){if(e==="")return[];let r=[],o=0,s=!1,i=!1;for(let a=0;a<e.length;a+=1){let l=e[a];if(i){i=!1;continue}l==="\\"&&s?i=!0:l==='"'?s=!s:l===t&&!s&&(r.push(e.slice(o,a).trim()),o=a+1)}if(s||i)throw V(n);return r.push(e.slice(o).trim()),r}function I(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 Oa(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Da(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function La(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 He(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function B(e,t){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return La(e);if(typeof e=="string")return Aa(e,t);throw k(0,"not a primitive")}function $a(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function C(e){return $a(e)?e:Ur(e)}function Aa(e,t){return Ia(e,t)?Ur(e):e}function Ia(e,t){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Da(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")}function Ur(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 we(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}var Yt=2;function Na(e={}){return{indent:Math.max(1,e.indent??Yt),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function Ta(e,t){let n=[],r=!1;return ct(e).forEach((o,s)=>{let i=s+1;if(o.trim()===""){r=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw k(i,"invalid indentation");if(t.strict&&a%t.indent!==0)throw k(i,"invalid indentation");n.push({number:i,depth:Math.floor(a/t.indent),content:o.slice(a),blankBefore:r}),r=!1}),n}function K(e,t){let n=Na(t),r=Ta(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 d;try{d=en(o.content,I(o.content,":",o.number))}catch(u){if(n.strict)throw zt(u,o.number);d=void 0}if(d!==void 0)return Ca(d,r,n)}if(s&&I(o.content,":",o.number)===-1)return J(o.content.trim(),o.number);let i={index:0},a=Zt(r,i,0,n),l=r[i.index];if(l!==void 0)throw k(l.number,"expected end of document");return a}function Zt(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:a,value:l}=Wa(e,t,n,r);Vr(o,i,a,l,r,s.number)}return o}function Wa(e,t,n,r){let o=e[t.index],s=o.content,i=I(s,":",o.number);if(i===-1)throw k(o.number,"expected `key: value`");let a=s.slice(0,i),l=s.slice(i+1),d=I(a,"[",o.number),u=I(a,"{",o.number);if(u!==-1&&(d===-1||u<d)){let y;try{y=Va(a)}catch(w){if(r.strict)throw zt(w,o.number);t.index+=1;let _=Bt(e,t,n,l,o.number,r);return{key:a.trim(),quoted:!1,value:_}}if(l.trim()!=="")throw k(o.number,"expected keyed map rows");let R=Ma(y,e,t,n+1,r);return{key:y.key,quoted:y.keyQuoted,value:R}}if(d!==-1){let y;try{y=en(a,i)}catch(w){if(r.strict)throw zt(w,o.number);t.index+=1;let _=Bt(e,t,n,l,o.number,r);return{key:a.trim(),quoted:!1,value:_}}if(y.key===""&&!y.keyQuoted)throw k(o.number,"expected non-empty field name");let R=Xt(y,l,e,t,n,r);return{key:y.key,quoted:y.keyQuoted,value:R}}let[f,p]=Y(a,o.number);if(f===""&&!p)throw k(o.number,"expected non-empty field name");t.index+=1;let h=Bt(e,t,n,l,o.number,r);return{key:f,quoted:p,value:h}}function Bt(e,t,n,r,o,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return J(i,o);let a=e[t.index];return a!==void 0&&a.depth>n?Zt(e,t,n+1,s):{}}function Ma(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 a=I(i.content,":",i.number);if(a===-1)throw k(i.number,"expected `key: value`");let[l,d]=Y(i.content.slice(0,a),i.number);if(l===""&&!d)throw k(i.number,"expected non-empty field name");let u=de(i.content.slice(a+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)=>{Ve(f,p,J(u[h],i.number),o,i.number)}),Vr(s,l,d,f,o,i.number),n.index+=1}return s}function Ca(e,t,n){let r=t[0],o=I(r.content,":",r.number);if(o===-1)throw k(r.number,"expected `key: value`");let s=r.content.slice(o+1),i={index:0},a=Xt(e,s,t,i,0,n),l=t[i.index];if(l!==void 0)throw k(l.number,"expected end of document");return a}function Xt(e,t,n,r,o,s){let i=n[r.index].number,a=t.trim();if(r.index+=1,e.fields!==void 0){if(a!=="")throw k(i,"expected tabular rows");return Ua(e,e.fields,n,r,o+1,s)}if(a!==""){let l=de(a,e.delimiter,i).map(d=>J(d,i));if(l.length!==e.len)throw k(i,"array length mismatch");return l}return Fa(e,n,r,o+1,s)}function Ua(e,t,n,r,o,s){let i=[];for(;i.length<e.len;){let l=n[r.index];if(l===void 0)throw qt(n,r.index);if(l.depth<o)break;if(l.depth>o)throw k(l.number,"invalid indentation");if(l.blankBefore&&s.strict)throw k(l.number,"blank line inside array");if(!Fr(l.content,e.delimiter,l.number))break;let d=de(l.content,e.delimiter,l.number);if(d.length!==t.length)throw k(l.number,"array row length mismatch");let u={};t.forEach((f,p)=>{Ve(u,f,J(d[p],l.number),s,l.number)}),i.push(u),r.index+=1}if(i.length!==e.len)throw qt(n,r.index);let a=n[r.index];if(a!==void 0&&a.depth>=o&&Fr(a.content,e.delimiter,a.number))throw k(a.number,"array length mismatch");return i}function Fr(e,t,n){let r=I(e,":",n);if(r===-1)return!0;let o=I(e,t,n);return o===-1?!1:o<r}function Fa(e,t,n,r,o){let s=[];for(;s.length<e.len;){let a=t[n.index];if(a===void 0||a.depth<r)throw qt(t,n.index);if(a.depth>r)throw k(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw k(a.number,"blank line inside array");s.push(Ha(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 Ha(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=I(s,":",o.number),a;try{a=en(s,i)}catch{a=void 0}if(a!==void 0){let l=s.slice(i+1);return Xt(a,l,e,t,n,r)}}if(I(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 a=e[t.index];if(a.depth<=n)break;i.push(a),t.index+=1}return Zt(i,{index:0},n+1,r)}return t.index+=1,J(s,o.number)}function qt(e,t){let n=e[t]??e[e.length-1];return k(n===void 0?1:n.number,"array length mismatch")}function en(e,t){if(t===-1)throw k(0,"array header missing colon");let n=e.slice(0,t),r=I(n,"[",0);if(r===-1)throw k(0,"invalid array header");let o,s;try{[o,s]=Y(n.slice(0,r),0)}catch{throw k(0,"invalid array header")}let i=n.slice(r+1),a=i.indexOf("]");if(a===-1)throw k(0,"invalid array header");let l=i.slice(0,a),d=/^[0-9]*/.exec(l)[0];if(d===""||d.length>1&&d.startsWith("0"))throw k(0,"invalid array header");let u=Number.parseInt(d,10),f;switch(l.slice(d.length)){case"":f=",";break;case" ":f=" ";break;case"|":f="|";break;default:throw k(0,"invalid array header")}let p=i.slice(a+1),h;if(p==="")h=void 0;else if(p.startsWith("{")&&p.endsWith("}")&&p.length>=2)try{h=Hr(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 Va(e){let t=I(e,"{",0);if(t===-1||!e.endsWith("}"))throw k(0,"invalid keyed map header");let n,r;try{[n,r]=Y(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=Hr(e.slice(t+1,-1),E)}catch(s){throw k(0,s.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:n,keyQuoted:r,delimiter:E,fields:o}}function Hr(e,t){let n=[],r=0;function o(a,l){let d=0;for(;r<e.length&&!(l&&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]=Y(e.slice(u,r),0);if(f==="")throw k(0,"invalid array header");if(d+=1,e[r]==="{"){r+=1;let p=n.length;if(o([...a,f],!0),e[r]!=="}"||n.length===p)throw k(0,"invalid array header");r+=1}else n.push([...a,f]);if(e[r]===t){if(r+=1,r>=e.length||e[r]==="}")throw k(0,"invalid array header");continue}if(l?e[r]==="}":r===e.length)break;throw k(0,"invalid array header")}if(d===0)throw k(0,"invalid array header")}function s(){for(r+=1;r<e.length;){let a=e[r];if(r+=1,a==="\\")r+=1;else if(a==='"')return}}if(o([],!1),r!==e.length)throw k(0,"invalid array header");let i=new Set;for(let a=0;a<n.length;a+=1)for(let l=a+1;l<n.length;l+=1)if(Ja(n[a],n[l])||Gt(n[a],n[l])||Gt(n[l],n[a]))throw k(0,"duplicate key");for(let a of n){let l=a.join("\0");if(i.has(l))throw k(0,"duplicate key");i.add(l)}return n}function Ja(e,t){return e.length===t.length&&Gt(e,t)}function Gt(e,t){return t.every((n,r)=>e[r]===n)}function zt(e,t){return k(t,e.reason??String(e.message))}function Vr(e,t,n,r,o,s){if(o.expandPaths&&!n&&t.includes(".")){let i=t.split(".");if(i.every(Ba)){Ve(e,i,r,o,s);return}}Ve(e,[t],r,o,s)}function Ve(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");we(e,s,n);return}if(i&&!be(e[s])){if(r.strict)throw k(o,"path expansion conflict");we(e,s,{})}else i||we(e,s,{});Ve(e[s],t.slice(1),n,r,o)}function Ba(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function A(e,t={}){let n={nestedTabularHeaders:t.nestedTabularHeaders===!0,keyedMapCollapse:t.keyedMapCollapse===!0},r=[];return Array.isArray(e)?tn(r,void 0,e,0,!1,n):be(e)?Jr(r,e,0,n):r.push(B(e,E)),r.join("")}function Je(e,t){e.push(" ".repeat(t*Yt))}function Jr(e,t,n,r){for(let[o,s]of Object.entries(t))Je(e,n),Qt(e,o,s,n,r)}function Qt(e,t,n,r,o){if(Array.isArray(n)){tn(e,t,n,r,!1,o);return}if(be(n)){let s=o.keyedMapCollapse?qa(n,o):void 0;if(s!==void 0){e.push(C(t),"{",s.fields.map(nn).join(E),`}:
10
+ `);for(let[i,a]of Object.entries(n))Je(e,r+1),e.push(C(i),": ",s.paths.map(l=>B(Gr(a,l),E)).join(E),`
11
+ `);return}e.push(C(t),`:
12
+ `),Jr(e,n,r+1,o);return}e.push(C(t),": ",B(n,E),`
13
+ `)}function tn(e,t,n,r,o,s){if(n.length===0){t!==void 0?e.push(C(t),`: []
11
14
  `):o?e.push(`[0]:
12
15
  `):e.push(`[]
13
- `);return}if(n.every(Oe)){bt(e,t,n.length,void 0),e.push(" "),e.push(n.map(a=>M(a,S)).join(S)),e.push(`
14
- `);return}let s=o?void 0:Bn(n,i);if(s!==void 0){bt(e,t,n.length,s.fields),e.push(`
15
- `);for(let a of n)Le(e,r+1),e.push(s.paths.map(l=>M(zn(a,l),S)).join(S)),e.push(`
16
- `);return}bt(e,t,n.length,void 0),e.push(`
17
- `);for(let a of n)Le(e,r+1),Qi(e,a,r+1,i)}function Qi(e,t,n,r){if(Array.isArray(t)){e.push("- "),Ot(e,void 0,t,n,!0,r);return}if(pe(t)){let o=Object.entries(t);if(o.length===0){e.push(`-
18
- `);return}e.push("- "),xt(e,o[0][0],o[0][1],n+1,r);for(let[i,s]of o.slice(1))Le(e,n+1),xt(e,i,s,n+1,r);return}e.push("- ",M(t,S),`
19
- `)}function bt(e,t,n,r){t!==void 0&&e.push(T(t)),e.push("[",String(n),"]"),r!==void 0&&e.push("{",r.map($t).join(S),"}"),e.push(":")}function Bn(e,t){let n=Kn(e.map(r=>({value:r})),t);return n===void 0?void 0:{fields:n,paths:qn(n)}}function es(e,t){let n=Object.values(e);if(!(n.length<2))return Bn(n,t)}function Kn(e,t){let n=e[0]?.value;if(!pe(n))return;let r=Object.keys(n).map(o=>({key:o}));if(r.length!==0){for(let{value:o}of e)if(!pe(o)||Object.keys(o).length!==r.length||r.some(s=>!Object.prototype.hasOwnProperty.call(o,s.key)))return;for(let o of r){let i=e.map(({value:a})=>({value:a[o.key]}));if(i.every(({value:a})=>Oe(a)))continue;if(!t.nestedTabularHeaders)return;let s=Kn(i,t);if(s===void 0)return;o.children=s}return r}}function qn(e,t=[]){return e.flatMap(n=>{let r=[...t,n.key];return n.children===void 0?[r]:qn(n.children,r)})}function zn(e,t){let n=e;for(let r of t)n=n[r];return n}function $t(e){return e.children===void 0?T(e.key):`${T(e.key)}{${e.children.map($t).join(S)}}`}var nr=[S,"|"," "];var rr=8,or=/^[A-Za-z0-9_-]+$/,fu=new TextEncoder,pu=new TextDecoder;function ns(e,t){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let n=e.slice(2,-1);if(!/^[0-9]+$/.test(n))throw v(t,"invalid trailer count");return Number.parseInt(n,10)}function ir(e,t){if(!or.test(e))throw v(t,"invalid tag")}function rs(e,t){let n=e.indexOf(":");if(n<=0)return null;let r=e.slice(0,n);if(!or.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw v(t,"invalid tag");return null}return{tag:r,cellsText:e.slice(n+1)}}function os(e,t){if(!e.startsWith("["))return null;let n=e.slice(1),r=n.indexOf("]");if(r===-1)throw v(t,"invalid header");let o=n.slice(0,r),i=o.startsWith("~"),s=i?o.slice(1):o;if(!i&&s.startsWith("="))return null;if(!nr.includes(s)&&s!=="")throw v(t,"invalid header delimiter");let a=s===""?S:s,l=n.slice(r+1),d=null;if(!i&&l.startsWith("<")){let p=l.indexOf(">");if(p===-1)throw v(t,"invalid tag");if(d=l.slice(1,p),ir(d,t),s!=="")throw v(t,"invalid header delimiter");l=l.slice(p+1)}if(!l.startsWith("{")||!l.endsWith("}:"))throw v(t,"invalid header");let c=l.slice(1,-2),f;try{f=te(c,a,t).map(p=>H(p,t)[0])}catch(p){throw ue(p)}if(f.length===0||f.some(p=>p===""))throw v(t,"invalid header fields");return{delimiter:a,fields:f,fieldText:c,continuation:i,tag:d}}function is(e,t,n){if(e===null||e.delimiter===void 0)throw v(n,"continuation header before header");if(e.delimiter!==t.delimiter||e.fieldText!==t.fieldText)throw v(n,"continuation header mismatch")}function Gn(e,t,n,r){let o;try{o=te(e,t,r)}catch(i){throw ue(i)}if(o.length!==n)throw v(r,"row arity mismatch");for(let i of o)try{W(i,r)}catch(s){throw ue(s)}return o}function ss(e,t,n){let r={};return e.forEach((o,i)=>{try{fe(r,o,W(t[i],n))}catch(s){throw ue(s)}}),r}function as(e,t,n){if(e.startsWith("- "))throw v(t,"reserved line prefix");let r=ns(e,t);if(r!==null){if(n===null||n.delimiter===void 0)throw v(t,"trailer without header");if(n.rowCount!==r)throw v(t,"trailer count mismatch");return{kind:"trailer"}}let o=os(e,t);if(o!==null)return o.continuation?(is(n,o,t),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let i=rs(e,t);if(i!==null){let s=n?.taggedLanes?.get(i.tag);if(s===void 0)throw v(t,"unknown tag");return{kind:"tagged-row",tag:i.tag,cells:Gn(i.cellsText,s.delimiter,s.fields.length,t)}}if(n===null||n.delimiter===void 0)throw v(t,"row before header");return{kind:"row",cells:Gn(e,n.delimiter,n.fields.length,t)}}function ls(e,t={}){let n=[],r=new Map,o=[],i=[],s=null,a=!1,l=!1;function d(m,h){let R=i.at(-1);if(R!==void 0&&R.lane===m.lane&&R.delimiter===m.delimiter&&R.fieldText===m.fieldText){R.rows.push(h);return}i.push({lane:m.lane,delimiter:m.delimiter,fields:m.fields,fieldText:m.fieldText,rows:[h]})}function c(){s!==null&&o.push({delimiter:s.delimiter,fields:s.fields,fieldText:s.fieldText,lane:s.lane,rows:s.rows})}function f(m,h,R){let b=r.get(m);if(b===void 0){if(r.size>=rr)throw v(R,"too many tagged lanes");b={segments:[],current:null},r.set(m,b),n.push(m)}else b.current!==null&&b.segments.push(b.current);b.current={lane:m,delimiter:h.delimiter,fields:h.fields,fieldText:h.fieldText,rows:[]},b.delimiter=h.delimiter,b.fields=h.fields,b.fieldText=h.fieldText}if(He(e).forEach((m,h)=>{let R=h+1;if(m==="")return;let b=s===null?{taggedLanes:r}:{delimiter:s.delimiter,fields:s.fields,fieldText:s.fieldText,rowCount:s.rows.length,taggedLanes:r},w=as(m,R,b);if(w.kind==="trailer"){c(),s=null;return}if(w.kind!=="continuation"){if(w.kind==="tag-header"){l=!0,f(w.header.tag,w.header,R);return}if(w.kind==="header"){c(),a||(n.push(null),a=!0),s={lane:null,delimiter:w.header.delimiter,fields:w.header.fields,fieldText:w.header.fieldText,rows:[]};return}if(w.kind==="tagged-row"){l=!0;let P=r.get(w.tag).current;P.rows.push(w.cells),d(P,w.cells);return}if(s===null)throw v(R,"row before header");s.rows.push(w.cells),d(s,w.cells)}}),!l)return c(),t.preserveInterleaving===!0,o;let p=[];c();for(let m of n){if(m===null){p.push(...o);continue}let h=r.get(m);p.push(...h.segments),h.current!==null&&p.push(h.current)}return t.preserveInterleaving===!0?i:p}function At(e){return ls(e).flatMap(t=>t.rows.map(n=>ss(t.fields,n,0)))}function ds(e){if(!nr.includes(e))throw v(0,"invalid header delimiter")}function Yn(e,t,n=!1){return`[${`${n?"~":""}${e===S?"":e}`}]{${t}}:
20
- `}function Zn(e,t){return`[]<${e}>{${t}}:
21
- `}function Lt(e,t){return t.map(T).join(e)}function cs(e){if(!Array.isArray(e)||e.length===0)throw v(0,"TOONL header requires fields");return e.map(t=>{let n;try{[n]=H(String(t),0)}catch(r){throw ue(r)}if(n==="")throw v(0,"TOONL header requires fields");return n})}function Xn(e,t){return e!==null&&e.length===t.length&&e.every((n,r)=>n===t[r])}function Qn(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw v(0,"TOONL continuation cadence must be positive")}function us(e,t,n){return e.continuationEveryRows!==void 0&&t>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&n>=e.continuationEveryBytes}function er(e){if(e===null||typeof e!="object"||Array.isArray(e))throw v(0,"TOONL output requires object rows");let t=Object.keys(e);if(t.length===0)throw v(0,"TOONL output requires object rows");if(t.some(n=>!Oe(e[n])))throw v(0,"TOONL rows must be flat objects");return t}function fs(e){return JSON.stringify([...e].sort())}function tr(e,t){let n=fs(e),r=t.get(n);return r!==void 0?r:(t.set(n,e),e)}function It({delimiter:e=S,trailer:t=!0,continuationEveryRows:n,continuationEveryBytes:r}={}){ds(e),Qn(n),Qn(r);let o=null,i="",s=new Map,a=0,l=0,d=0,c=new Map,f=!1,p={continuationEveryRows:n,continuationEveryBytes:r},m=()=>o===null||!t?"":`[=${a}]
22
- `,h=()=>us(p,l,d)?(l=0,d=0,Yn(e,i,!0)):"",R=b=>{ir(b,0);let w=c.get(b);if(w===void 0){if(c.size>=rr)throw v(0,"too many tagged lanes");w={fields:null,fieldsByShape:new Map},c.set(b,w)}return w};return{push(b){if(f)throw v(0,"TOONL encoder is closed");let w=tr(er(b),s),P="";(o===null||o.length!==w.length||o.some((Z,ae)=>Z!==w[ae]))&&(P+=m(),o=w,i=Lt(e,o),a=0,l=0,d=0,P+=Yn(e,i));let C=o.map(Z=>M(b[Z],e));P+=h();let N=`${C.join(e)}
23
- `;return P+=N,a+=1,l+=1,d+=N.length,P},declareLane(b,w){if(f)throw v(0,"TOONL encoder is closed");let P=cs(w),C=Lt(S,P),N=R(b);return Xn(N.fields,P)?"":(N.fields=P,Zn(b,C))},pushTagged(b,w){if(f)throw v(0,"TOONL encoder is closed");let P=R(b),C=tr(er(w),P.fieldsByShape),N=Lt(S,C),Z=C.map(We=>M(w[We],S)),ae="";return Xn(P.fields,C)||(P.fields=C,ae+=Zn(b,N)),`${ae}${b}:${Z.join(S)}
24
- `},end(){return f?"":(f=!0,m())}}}function Nt(e){let t={app:e,version:ps(me("__RED_BUILD_VERSION__",()=>"3.0.4")??"0.0.0-dev"),gitSha:me("__RED_BUILD_GIT_SHA__",()=>"93051f3eda65f6e0cd40c92339034c3e119295e4")??"unknown",buildTime:me("__RED_BUILD_TIME__",()=>"2026-07-31T00:19:51-03:00")??"unknown",bundleAsset:me("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},n=me("__REDDB_SDK_VERSION__",()=>""),r=me("__REDDB_BINARY_TAG__",()=>"");return n&&(t.reddbSdkVersion=n),r&&(t.reddbBinaryTag=r),t}function ps(e){return e.startsWith("v")?e.slice(1):e}function sr(e){return`${e.app} ${e.version} ${e.gitSha}`}function me(e,t){try{let n=t();return typeof n=="string"&&n.length>0?n:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var ar={"=":"data",":=":{to:"data",typed:!0},":":"meta"},ms=/^[a-z][a-z0-9+.-]*:\/\//i;function ys(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 hs(e=ar){return Object.entries(e).map(([t,n])=>ys(t,n)).sort((t,n)=>n.separator.length-t.separator.length)}function gs(e){return/^-\d+(\.\d+)?$/.test(e)}function Ae(e){return!(!e||e.startsWith("-")&&!gs(e))}function Je(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 lr(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=>lr(n.trim())):e}function ne(e,t){switch(t){case"boolean":return ks(e);case"number":return Rs(e);case"array":return e.split(",").map(n=>Je(n.trim()));case"string":default:return e}}function ks(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function Rs(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 q(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function bs(e,t={}){return e.map(n=>{let r=t[n.type];return r?r(n.value):n.value}).join("")}function x(e,t){return{type:e,value:t}}function ws(e){let t=[],n=vs(e);if(t.push(x("section-header","Usage:"),x("text"," "),x("usage-text",n),x("newline",`
16
+ `);return}if(n.every(He)){Kt(e,t,n.length,void 0),e.push(" "),e.push(n.map(a=>B(a,E)).join(E)),e.push(`
17
+ `);return}let i=o?void 0:Br(n,s);if(i!==void 0){Kt(e,t,n.length,i.fields),e.push(`
18
+ `);for(let a of n)Je(e,r+1),e.push(i.paths.map(l=>B(Gr(a,l),E)).join(E)),e.push(`
19
+ `);return}Kt(e,t,n.length,void 0),e.push(`
20
+ `);for(let a of n)Je(e,r+1),Ka(e,a,r+1,s)}function Ka(e,t,n,r){if(Array.isArray(t)){e.push("- "),tn(e,void 0,t,n,!0,r);return}if(be(t)){let o=Object.entries(t);if(o.length===0){e.push(`-
21
+ `);return}e.push("- "),Qt(e,o[0][0],o[0][1],n+1,r);for(let[s,i]of o.slice(1))Je(e,n+1),Qt(e,s,i,n+1,r);return}e.push("- ",B(t,E),`
22
+ `)}function Kt(e,t,n,r){t!==void 0&&e.push(C(t)),e.push("[",String(n),"]"),r!==void 0&&e.push("{",r.map(nn).join(E),"}"),e.push(":")}function Br(e,t){let n=Kr(e.map(r=>({value:r})),t);return n===void 0?void 0:{fields:n,paths:qr(n)}}function qa(e,t){let n=Object.values(e);if(!(n.length<2))return Br(n,t)}function Kr(e,t){let n=e[0]?.value;if(!be(n))return;let r=Object.keys(n).map(o=>({key:o}));if(r.length!==0){for(let{value:o}of e)if(!be(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:a})=>({value:a[o.key]}));if(s.every(({value:a})=>He(a)))continue;if(!t.nestedTabularHeaders)return;let i=Kr(s,t);if(i===void 0)return;o.children=i}return r}}function qr(e,t=[]){return e.flatMap(n=>{let r=[...t,n.key];return n.children===void 0?[r]:qr(n.children,r)})}function Gr(e,t){let n=e;for(let r of t)n=n[r];return n}function nn(e){return e.children===void 0?C(e.key):`${C(e.key)}{${e.children.map(nn).join(E)}}`}var no=[E,"|"," "];var ro=8,oo=/^[A-Za-z0-9_-]+$/,wm=new TextEncoder,bm=new TextDecoder;function za(e,t){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let n=e.slice(2,-1);if(!/^[0-9]+$/.test(n))throw v(t,"invalid trailer count");return Number.parseInt(n,10)}function so(e,t){if(!oo.test(e))throw v(t,"invalid tag")}function Qa(e,t){let n=e.indexOf(":");if(n<=0)return null;let r=e.slice(0,n);if(!oo.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw v(t,"invalid tag");return null}return{tag:r,cellsText:e.slice(n+1)}}function Ya(e,t){if(!e.startsWith("["))return null;let n=e.slice(1),r=n.indexOf("]");if(r===-1)throw v(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(!no.includes(i)&&i!=="")throw v(t,"invalid header delimiter");let a=i===""?E:i,l=n.slice(r+1),d=null;if(!s&&l.startsWith("<")){let p=l.indexOf(">");if(p===-1)throw v(t,"invalid tag");if(d=l.slice(1,p),so(d,t),i!=="")throw v(t,"invalid header delimiter");l=l.slice(p+1)}if(!l.startsWith("{")||!l.endsWith("}:"))throw v(t,"invalid header");let u=l.slice(1,-2),f;try{f=de(u,a,t).map(p=>Y(p,t)[0])}catch(p){throw Re(p)}if(f.length===0||f.some(p=>p===""))throw v(t,"invalid header fields");return{delimiter:a,fields:f,fieldText:u,continuation:s,tag:d}}function Za(e,t,n){if(e===null||e.delimiter===void 0)throw v(n,"continuation header before header");if(e.delimiter!==t.delimiter||e.fieldText!==t.fieldText)throw v(n,"continuation header mismatch")}function zr(e,t,n,r){let o;try{o=de(e,t,r)}catch(s){throw Re(s)}if(o.length!==n)throw v(r,"row arity mismatch");for(let s of o)try{J(s,r)}catch(i){throw Re(i)}return o}function Xa(e,t,n){let r={};return e.forEach((o,s)=>{try{we(r,o,J(t[s],n))}catch(i){throw Re(i)}}),r}function el(e,t,n){if(e.startsWith("- "))throw v(t,"reserved line prefix");let r=za(e,t);if(r!==null){if(n===null||n.delimiter===void 0)throw v(t,"trailer without header");if(n.rowCount!==r)throw v(t,"trailer count mismatch");return{kind:"trailer"}}let o=Ya(e,t);if(o!==null)return o.continuation?(Za(n,o,t),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=Qa(e,t);if(s!==null){let i=n?.taggedLanes?.get(s.tag);if(i===void 0)throw v(t,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:zr(s.cellsText,i.delimiter,i.fields.length,t)}}if(n===null||n.delimiter===void 0)throw v(t,"row before header");return{kind:"row",cells:zr(e,n.delimiter,n.fields.length,t)}}function tl(e,t={}){let n=[],r=new Map,o=[],s=[],i=null,a=!1,l=!1;function d(h,y){let R=s.at(-1);if(R!==void 0&&R.lane===h.lane&&R.delimiter===h.delimiter&&R.fieldText===h.fieldText){R.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,R){let w=r.get(h);if(w===void 0){if(r.size>=ro)throw v(R,"too many tagged lanes");w={segments:[],current:null},r.set(h,w),n.push(h)}else w.current!==null&&w.segments.push(w.current);w.current={lane:h,delimiter:y.delimiter,fields:y.fields,fieldText:y.fieldText,rows:[]},w.delimiter=y.delimiter,w.fields=y.fields,w.fieldText=y.fieldText}if(ct(e).forEach((h,y)=>{let R=y+1;if(h==="")return;let w=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},_=el(h,R,w);if(_.kind==="trailer"){u(),i=null;return}if(_.kind!=="continuation"){if(_.kind==="tag-header"){l=!0,f(_.header.tag,_.header,R);return}if(_.kind==="header"){u(),a||(n.push(null),a=!0),i={lane:null,delimiter:_.header.delimiter,fields:_.header.fields,fieldText:_.header.fieldText,rows:[]};return}if(_.kind==="tagged-row"){l=!0;let P=r.get(_.tag).current;P.rows.push(_.cells),d(P,_.cells);return}if(i===null)throw v(R,"row before header");i.rows.push(_.cells),d(i,_.cells)}}),!l)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 on(e){return tl(e).flatMap(t=>t.rows.map(n=>Xa(t.fields,n,0)))}function nl(e){if(!no.includes(e))throw v(0,"invalid header delimiter")}function Qr(e,t,n=!1){return`[${`${n?"~":""}${e===E?"":e}`}]{${t}}:
23
+ `}function Yr(e,t){return`[]<${e}>{${t}}:
24
+ `}function rn(e,t){return t.map(C).join(e)}function rl(e){if(!Array.isArray(e)||e.length===0)throw v(0,"TOONL header requires fields");return e.map(t=>{let n;try{[n]=Y(String(t),0)}catch(r){throw Re(r)}if(n==="")throw v(0,"TOONL header requires fields");return n})}function Zr(e,t){return e!==null&&e.length===t.length&&e.every((n,r)=>n===t[r])}function Xr(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw v(0,"TOONL continuation cadence must be positive")}function ol(e,t,n){return e.continuationEveryRows!==void 0&&t>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&n>=e.continuationEveryBytes}function eo(e){if(e===null||typeof e!="object"||Array.isArray(e))throw v(0,"TOONL output requires object rows");let t=Object.keys(e);if(t.length===0)throw v(0,"TOONL output requires object rows");if(t.some(n=>!He(e[n])))throw v(0,"TOONL rows must be flat objects");return t}function sl(e){return JSON.stringify([...e].sort())}function to(e,t){let n=sl(e),r=t.get(n);return r!==void 0?r:(t.set(n,e),e)}function sn({delimiter:e=E,trailer:t=!0,continuationEveryRows:n,continuationEveryBytes:r}={}){nl(e),Xr(n),Xr(r);let o=null,s="",i=new Map,a=0,l=0,d=0,u=new Map,f=!1,p={continuationEveryRows:n,continuationEveryBytes:r},h=()=>o===null||!t?"":`[=${a}]
25
+ `,y=()=>ol(p,l,d)?(l=0,d=0,Qr(e,s,!0)):"",R=w=>{so(w,0);let _=u.get(w);if(_===void 0){if(u.size>=ro)throw v(0,"too many tagged lanes");_={fields:null,fieldsByShape:new Map},u.set(w,_)}return _};return{push(w){if(f)throw v(0,"TOONL encoder is closed");let _=to(eo(w),i),P="";(o===null||o.length!==_.length||o.some((ae,ge)=>ae!==_[ge]))&&(P+=h(),o=_,s=rn(e,o),a=0,l=0,d=0,P+=Qr(e,s));let F=o.map(ae=>B(w[ae],e));P+=y();let M=`${F.join(e)}
26
+ `;return P+=M,a+=1,l+=1,d+=M.length,P},declareLane(w,_){if(f)throw v(0,"TOONL encoder is closed");let P=rl(_),F=rn(E,P),M=R(w);return Zr(M.fields,P)?"":(M.fields=P,Yr(w,F))},pushTagged(w,_){if(f)throw v(0,"TOONL encoder is closed");let P=R(w),F=to(eo(_),P.fieldsByShape),M=rn(E,F),ae=F.map(tt=>B(_[tt],E)),ge="";return Zr(P.fields,F)||(P.fields=F,ge+=Yr(w,M)),`${ge}${w}:${ae.join(E)}
27
+ `},end(){return f?"":(f=!0,h())}}}function an(e){let t={app:e,version:il(_e("__RED_BUILD_VERSION__",()=>"3.1.0")??"0.0.0-dev"),gitSha:_e("__RED_BUILD_GIT_SHA__",()=>"540d78ae57d6bb7186540d12ab175eea62ec82a4")??"unknown",buildTime:_e("__RED_BUILD_TIME__",()=>"2026-07-31T20:29:52Z")??"unknown",bundleAsset:_e("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},n=_e("__REDDB_SDK_VERSION__",()=>""),r=_e("__REDDB_BINARY_TAG__",()=>"");return n&&(t.reddbSdkVersion=n),r&&(t.reddbBinaryTag=r),t}function il(e){return e.startsWith("v")?e.slice(1):e}function io(e){return`${e.app} ${e.version} ${e.gitSha}`}function _e(e,t){try{let n=t();return typeof n=="string"&&n.length>0?n:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var ao={"=":"data",":=":{to:"data",typed:!0},":":"meta"},al=/^[a-z][a-z0-9+.-]*:\/\//i;function ll(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 dl(e=ao){return Object.entries(e).map(([t,n])=>ll(t,n)).sort((t,n)=>n.separator.length-t.separator.length)}function cl(e){return/^-\d+(\.\d+)?$/.test(e)}function Be(e){return!(!e||e.startsWith("-")&&!cl(e))}function ut(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 lo(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=>lo(n.trim())):e}function ce(e,t){switch(t){case"boolean":return ul(e);case"number":return pl(e);case"array":return e.split(",").map(n=>ut(n.trim()));case"string":default:return e}}function ul(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function pl(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 oe(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function fl(e,t={}){return e.map(n=>{let r=t[n.type];return r?r(n.value):n.value}).join("")}function x(e,t){return{type:e,value:t}}function ml(e){let t=[],n=hl(e);if(t.push(x("section-header","Usage:"),x("text"," "),x("usage-text",n),x("newline",`
25
28
  `),x("newline",`
26
29
  `)),e.positional&&e.positional.length>0){t.push(x("section-header","Arguments:"),x("newline",`
27
30
  `));for(let r of e.positional)if(r.description){let o=r.variadic?`${r.name}...`:r.name;t.push(x("indent"," "),x("positional-name",`<${o}>`)),r.required||t.push(x("positional-optional"," (optional)")),t.push(x("newline",`
28
31
  `),x("indent"," "),x("option-description",r.description),x("newline",`
29
32
  `))}t.push(x("newline",`
30
33
  `))}if(e.options&&Object.keys(e.options).length>0){t.push(x("section-header","Options:"),x("newline",`
31
- `));let r=xs(e.options);t.push(...r)}return t}function _s(e,t){let n=ws(e);return bs(n,t)}function vs(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 xs(e,t=!1){let n=[],r=[],o=t?"global-option-flag":"option-flag",i=t?"global-option-type":"option-type",s=t?"global-option-default":"option-default",a=t?"global-option-description":"option-description";for(let[d,c]of Object.entries(e)){if(c.hidden)continue;let f=[],p=R=>{f.includes(R)||f.push(R)};c.short&&p(`-${c.short}`),p(`--${d}`);for(let R of c.aliases??[])R.length===1?p(`-${R}`):p(`--${R}`);let m=f.join(", "),h=c.type&&c.type!=="boolean"?`<${c.type}>`:void 0;r.push({flags:m,type:h,desc:c.description??"",default:c.default!==void 0?String(c.default):void 0})}let l=Math.max(...r.map(d=>d.flags.length+(d.type?d.type.length+1:0)),20);for(let d of r){let c=d.flags.length+(d.type?d.type.length+1:0),f=" ".repeat(l-c+2);n.push(x("indent"," ")),n.push(x(o,d.flags)),d.type&&(n.push(x("text"," ")),n.push(x(i,d.type))),n.push(x("text",f)),n.push(x(a,d.desc)),d.default!==void 0&&(n.push(x("text"," ")),n.push(x(s,`(default: ${d.default})`))),n.push(x("newline",`
32
- `))}return n}function dr(e){let t=Ls(e.options??{},e.autoShort??!1),n=hs(e.separators??ar);return{schema:e,parse(r){return Ss(r,e,t,n)},help(){return _s(e,e.formatter)}}}function Ss(e,t,n,r){let o={positional:{},options:{},errors:[],rest:[]},i=new Set(r.map(c=>c.to));for(let c of i)o[c]={};let s=0,a=t.positional??[],l=0,d=!1;for(;l<e.length;){let c=e[l];if(t.stopEarly&&s>0){o.rest=e.slice(l);break}if(c==="--"&&!d){d=!0,l++;continue}if(d){if(s<a.length){let p=a[s];if(p.variadic){let m=[];for(;l<e.length;){let h=e[l];m.push(p.type?ne(h,p.type):h),l++}o.positional[p.name]=m,s++}else{let m=p.type?ne(c,p.type):c;o.positional[p.name]=m,s++,l++}}else t.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(c)),l++;continue}if(c.startsWith("--")){l=Os(c,l,e,o,n,t);continue}if(c.startsWith("-")&&c.length>1&&!Cs(c)){l=$s(c,l,e,o,n,t);continue}let f=Es(c,r);if(f){let{key:p,value:m,config:h}=f,R=o,b=R[h.to]??(R[h.to]={});b[p]=h.typed?lr(m):q(m),l++;continue}if(s<a.length){let p=a[s];if(p.variadic){let h=[];for(;l<e.length&&!e[l].startsWith("-");){let R=e[l];h.push(p.type?ne(R,p.type):R),l++}o.positional[p.name]=h,s++;continue}let m=p.type?ne(c,p.type):c;o.positional[p.name]=m,s++}else t.allowUnknown!==!1?o.rest.push(c):o.errors.push(`Unexpected positional argument: ${c}`);l++}return Is(o,t,n),Ns(o,t,a),Ts(o,t,n),o}function Es(e,t){if(ms.test(e))return null;for(let n of t){if(n.prefix&&e.startsWith(n.separator)){let o=e.slice(n.separator.length),i=o.indexOf(":");if(i>0){let s=o.slice(0,i),a=o.slice(i+1);if(Ps(s))return{key:s,value:a,config:n}}continue}let r=e.indexOf(n.separator);if(r>0){let o=e.slice(0,r),i=e.slice(r+n.separator.length);if(js(o,i,n))return{key:o,value:i,config:n}}}return null}function Ps(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function js(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 Os(e,t,n,r,o,i){let s=e.slice(2);if(s.startsWith("no-")){let l=s.slice(3),d=o.get(l);if(d?.negatable!==!1&&d?.type==="boolean")return r.options[d.name]=!1,t+1}if(s.includes("=")){let l=s.indexOf("="),d=s.slice(0,l),c=s.slice(l+1);return Be(d,c,t+1,r,o,i)}let a=o.get(s);if(a){if(a.type!=="boolean"){let l=n[t+1];return Ae(l)?Be(a.name,l,t+2,r,o,i):(r.errors.push(`Option --${s} requires a value`),t+1)}return r.options[a.name]=!0,t+1}return i.strict?r.errors.push(`Unknown option: --${s}`):i.allowUnknown!==!1&&(r.options[s]=!0),t+1}function $s(e,t,n,r,o,i){let s=e.slice(1);if(s.includes("=")){let a=s.indexOf("="),l=s.slice(0,a),d=s.slice(a+1),c=Tt(l,o);return c?Be(c.name,d,t+1,r,o,i):(i.strict?r.errors.push(`Unknown option: -${l}`):i.allowUnknown!==!1&&(r.options[l]=Je(q(d))),t+1)}if(s.length===1){let a=Tt(s,o);if(a){if(a.type!=="boolean"){let l=n[t+1];return Ae(l)?Be(a.name,l,t+2,r,o,i):(r.errors.push(`Option -${s} requires a value`),t+1)}return r.options[a.name]=!0,t+1}if(i.strict)r.errors.push(`Unknown option: -${s}`);else if(i.allowUnknown!==!1){let l=n[t+1];if(Ae(l))return r.options[s]=Je(q(l)),t+2;r.options[s]=!0}return t+1}for(let a of s){let l=Tt(a,o);l?l.type==="boolean"?r.options[l.name]=!0:r.errors.push(`Option -${a} requires a value`):i.strict?r.errors.push(`Unknown option: -${a}`):i.allowUnknown!==!1&&(r.options[a]=!0)}return t+1}function Be(e,t,n,r,o,i){let s=o.get(e);if(s){if(s.choices){let l=s.type?ne(q(t),s.type):q(t);if(!s.choices.includes(l))return r.errors.push(`Invalid value for '${e}': '${t}'. Allowed: ${s.choices.join(", ")}`),n}let a=s.type?ne(q(t),s.type):q(t);if(s.type==="array"){let l=r.options[e];Array.isArray(l)?l.push(...a):r.options[e]=a}else r.options[e]=a}else i.strict?r.errors.push(`Unknown option: --${e}`):i.allowUnknown!==!1&&(r.options[e]=Je(q(t)));return n}function Ls(e,t=!1){let n=new Map,r=Object.entries(e).sort(([i],[s])=>i.localeCompare(s)),o=new Set;for(let[,i]of r)i.short&&o.add(i.short);for(let[i,s]of r){let a=s.short??"";t&&!a&&(a=As(i,o),a&&o.add(a));let l={name:i,short:a,aliases:s.aliases??[],type:s.type??"string",description:s.description??"",required:s.required??!1,hidden:s.hidden??!1,negatable:s.negatable??!0,default:s.default,choices:s.choices,env:s.env,validate:s.validate};n.set(i,l);for(let d of l.aliases)n.set(d,l)}return n}function As(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 Tt(e,t){for(let n of t.values())if(n.short===e||n.aliases.includes(e))return n}function Is(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?ne(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 Ns(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 Ts(e,t,n){for(let r of n.values()){let o=e.options[r.name];if(r.validate&&o!==void 0){let i=r.validate(o);i!==!0&&e.errors.push(i)}}for(let r of t.positional??[]){let o=e.positional[r.name];if(r.validate&&o!==void 0){let i=r.validate(o);i!==!0&&e.errors.push(i)}}}function Cs(e){return/^-\d+(\.\d+)?$/.test(e)}var Ct=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 Ds(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 Ws(e,t){let n=new Map;for(let[o,i]of Object.entries(t))if(!(i.kind!=="value"||i.type!=="array")){n.set(o,o);for(let s of i.aliases??[])n.set(s,o)}let r=new Map;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="--")break;let s=i.match(/^--([^=]+)(?:=(.*))?$/)??i.match(/^-([^=])(?:=(.*))?$/);if(s===null)continue;let a=n.get(s[1]);if(a===void 0)continue;let l=s[2];if(l===void 0&&Ae(e[o+1])&&(l=e[o+1],o+=1),l===void 0)continue;let d=r.get(a)??[];d.push(l),r.set(a,d)}return r}function ye(e,t,n={}){let o=dr({options:Ds(t),separators:{},allowUnknown:!0}).parse([...e]),i={},s=Ws(e,t),a=o.errors.find(l=>/^Option --?\S+ requires a value$/.test(l));if(a!==void 0)throw new Error(a.replace(/^Option /,""));if(o.errors.length>0)throw new Error(o.errors[0]);if(n.unknownFlags==="error"){let l=new Set(Object.keys(t));for(let d of Object.keys(o.options))if(!l.has(d))throw new Ct(d.length===1?`-${d}`:`--${d}`,Object.keys(t).map(c=>c.length===1?`-${c}`:`--${c}`))}for(let[l,d]of Object.entries(t)){let c=o.options[l];c!==void 0&&(d.kind==="boolean"?i[l]=c:d.type==="array"?i[l]=(s.get(l)??[]).map(f=>d.coerce(f)):i[l]=d.coerce(String(c)))}return{values:i,positionals:o.rest}}var Dt=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 cr(e,t){let[n,...r]=e;if(n!==void 0){for(let[i,s]of Object.entries(t.commands))if(n===i||(s.aliases??[]).includes(n))return{command:i,args:r};if(t.errorOnUnknownCommand&&!n.startsWith("-"))throw new Dt(n,Object.keys(t.commands))}let o=t.keepArgvOnDefault??!0;return{command:t.default,args:o?[...e]:r}}import{existsSync as Ms,readFileSync as Ju}from"node:fs";import{dirname as Us,join as Fs}from"node:path";function ur(e,t){let n=e;for(let r=0;r<16;r++){let o=Fs(n,t);if(Ms(o))return o;let i=Us(n);if(i===n)break;n=i}return null}function Vs(e){let t=e.indexOf(" #");return(t>=0?e.slice(0,t):e).trim()}function Ke(e,t){let n=[];for(let r of e.split(`
33
- `)){let o=r.replace(/\r$/,""),i=o.trim();if(!i||i.startsWith("#"))continue;let s=o.indexOf(":");if(s<0)continue;let a=o.length-o.trimStart().length,l=o.slice(0,s).trim();if(!l)continue;let d=o.slice(s+1).trim();for(;n.length&&n[n.length-1].indent>=a;)n.pop();if(n.push({indent:a,key:l}),d&&n.map(f=>f.key).join(".")===t)return Vs(d)}}var Hs="project.name";function fr(e){let t=Ke(e,Hs)?.trim();return t===void 0||t===""?void 0:t}import{randomUUID as Qd}from"node:crypto";import{spawn as ec}from"node:child_process";import{mkdir as tc,rm as nc}from"node:fs/promises";import{dirname as rc}from"node:path";import{createHash as Js}from"node:crypto";import{constants as Wt}from"node:fs";import{mkdir as Bs,open as Ks}from"node:fs/promises";import{createConnection as qs}from"node:net";import{tmpdir as zs}from"node:os";import{dirname as Gs,join as Mt}from"node:path";var Ys=108;async function qe(e,t,n="resident server"){let r=e.timeoutMs??1e3;return await new Promise((o,i)=>{let s=qs(e.socketPath),a=!1,l="",d=setTimeout(()=>{c(()=>i(new Error(`${n} timed out`))),s.destroy()},r);function c(f){a||(a=!0,clearTimeout(d),f())}s.on("connect",()=>{s.write(`${JSON.stringify(t)}
34
- `)}),s.on("data",f=>{l+=f.toString("utf8");let p=l.indexOf(`
35
- `);if(p<0)return;let m=l.slice(0,p);c(()=>{try{o(JSON.parse(m))}catch(h){i(h)}}),s.end()}),s.on("error",f=>c(()=>i(f))),s.on("close",()=>{a||c(()=>i(new Error(`${n} closed without response`)))})})}async function pr(e){await Bs(Gs(e),{recursive:!0,mode:448});try{return await Ks(e,Wt.O_CREAT|Wt.O_EXCL|Wt.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function A(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function ze(e){let t=e.env??process.env,n=Js("sha256").update(e.key).digest("hex").slice(0,20),r=t.XDG_RUNTIME_DIR;if(r){let i=Mt(r,"red-skills",n);if(Mt(i,e.socketFileName).length<Ys)return i}let o=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid");return Mt(zs(),`red-skills-${o}`,n)}import{existsSync as Zs,readdirSync as Xs}from"node:fs";import{homedir as Qs}from"node:os";import{basename as Ft,dirname as Ut,join as I,resolve as Ge}from"node:path";var J="redskilled.bundle.min.mjs",Ye="redskilled-daemon-entry-unresolved",yr="REDSKILLED_BIN";function he(e){return"command"in e}var Ze=class extends Error{code=Ye;searched;callerEntry;constructor(t){super(`${Ye}: no published ${J} found to spawn the redskilled daemon from${t.callerEntry?` (caller entry: ${t.callerEntry}, which is NOT used as a fallback)`:""}
36
- searched:
37
- ${t.searched.map(n=>` ${n}`).join(`
38
- `)}`),this.name="RedskilledDaemonEntryError",this.searched=t.searched,t.callerEntry!=null&&(this.callerEntry=t.callerEntry)}};function ge(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 Vt(e=process.env){return gr(e)}var ea=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Ht=/^redskilled-(.+)\.bundle\.min\.mjs$/,ta=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"];function Xe(e={},t={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let n=t.env??process.env,r=t.exists??Zs,o=t.execPath??process.execPath,i=t.execArgv??[],s=t.callerEntry===void 0?process.argv[1]:t.callerEntry,a=(c,f)=>({command:o,args:[...i,c],source:f,entry:c}),l=n[yr];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(s&&hr(s))return a(Ge(s),"caller-entry");let d=[];for(let[c,f]of ra(s,t.rootDir,n,t.listDir??sa))if(d.push(c),r(c))return a(c,f);return{diagnostic:Ye,searched:d,...s?{callerEntry:Ge(s)}:{}}}function Ie(e={},t={}){let n=Xe(e,t);if(he(n))return n;throw new Ze(n)}function hr(e){let t=Ft(e);return t===J||Ht.test(t)||t==="red-skills-redskilled"||t==="red-skills-redskilled.mjs"?!0:t!=="cli.js"&&t!=="cli.mjs"&&t!=="cli.ts"?!1:na(Ge(e))}function na(e){let t=Ut(e);for(let n=0;n<4;n++){if(Ft(t)==="redskilled")return!0;let r=Ut(t);if(r===t)return!1;t=r}return!1}function*ra(e,t,n,r){if(e){let i=Ut(Ge(e));yield[I(i,J),"caller-sibling-bundle"];let s=ea.exec(Ft(e));s&&(yield[I(i,`redskilled-${s[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[I(i,"..","dist",J),"caller-sibling-bundle"]}for(let i of ta){let s=n[i];s&&(yield[I(s,"dist",J),"plugin-root-bundle"],yield[I(s,"..","..","dist",J),"plugin-root-bundle"])}t&&(yield[I(t,"dist",J),"repo-bundle"],yield[I(t,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[I(t,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=gr(n);yield[I(o,J),"bundle-cache"];for(let i of oa(o,r))yield[I(o,i),"bundle-cache"]}function gr(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let t=e.XDG_CACHE_HOME||I(e.HOME||Qs(),".cache");return I(t,"red-skills","bundles")}function oa(e,t){return t(e).filter(n=>Ht.test(n)).sort((n,r)=>ia(mr(r),mr(n)))}function mr(e){return Ht.exec(e)?.[1]??""}function ia(e,t){let n=i=>i.split(".").map(s=>Number.parseInt(s,10)),[r,o]=[n(e),n(t)];for(let i=0;i<Math.max(r.length,o.length);i++){let[s,a]=[r[i],o[i]];if(Number.isNaN(s)||s===void 0)return Number.isNaN(a)||a===void 0?e.localeCompare(t):-1;if(Number.isNaN(a)||a===void 0)return 1;if(s!==a)return s-a}return 0}function sa(e){try{return Xs(e)}catch{return[]}}import{randomUUID as dt}from"node:crypto";import{mkdir as qd,rm as Yo}from"node:fs/promises";import{createServer as zd}from"node:net";import{dirname as Gd}from"node:path";import{totalmem as aa}from"node:os";function kr(e){let t=0,n=0,r=0,o=[],i=[];for(let s of e){let a=s.budget??{},l=!1;for(let[d,c]of[[a.memory_high,f=>t+=f],[a.memory_max,f=>n+=f]]){if(d==null)continue;let f=ke(d);f==null?l=!0:c(f)}a.cpu_weight!=null&&(r+=a.cpu_weight),l&&o.push(s.worker_id),s.isolated||i.push(s.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:i.sort()}}function ke(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 Rr(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 la="REDSKILLED_MEMORY_CEILING",da="REDSKILLED_WORKER_CEILING",ca=.7;function br(e){let t=e?.memory_max??e?.memory_high;if(t!=null)return ke(t)}function Jt(e){let t=0,n=[];for(let r of e){let o=br(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 wr(e){let{ceiling:t}=e,n=Jt(e.workers),r=br(e.budget),o=r===void 0?null:r,i=n.memory_bytes+(r??0),s=n.worker_count+1,a=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",l=`the host is already holding ${n.memory_bytes} bytes across ${n.worker_count} Worker(s)`,d=(c,f)=>({version:1,admitted:!1,verdict:c,reason:f,ceiling:t,consumption:n,requested_memory_bytes:o,projected_worker_count:s,projected_memory_bytes:i});return t.worker_count!=null&&s>t.worker_count?d("refused-over-worker-ceiling",`redskilled refused this Worker${a}: it would be Worker ${s} past a host ceiling of ${t.worker_count} Worker(s), and ${l}`):t.memory_bytes!=null&&r===null?d("refused-unaccountable-budget",`redskilled refused this Worker${a}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${t.memory_bytes} bytes, and ${l}`):t.memory_bytes!=null&&i>t.memory_bytes?d("refused-over-memory-ceiling",`redskilled refused this Worker${a}: it would take the host to ${i} bytes of declared Worker memory, past the host ceiling of ${t.memory_bytes} bytes, and ${l}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${a}: ${i} bytes of declared Worker memory against a host ceiling of ${t.memory_bytes??"unbounded"} bytes, and ${l}`,ceiling:t,consumption:n,requested_memory_bytes:o,projected_worker_count:s,projected_memory_bytes:i}}function _r(e=process.env,t=aa()){let n=(e[la]??"").trim(),r=(e[da]??"").trim(),o=fa(r);if(n!==""){let i=ua(n,t);if(i!==void 0)return{memory_bytes:i,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(t*ca),worker_count:o,source:r!==""?"declared":"host-fraction"}}function ua(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)):ke(e)??void 0}function fa(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 pa,mkdir as ma,open as ya,readFile as ha,stat as ga,truncate as vr}from"node:fs/promises";import{dirname as ka}from"node:path";var xr="redskilled.events.toonl";function Ra(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}}function Sr(e){let t=It({trailer:!1}),n=Promise.resolve();return{path:e,async record(r){let o=Ra(r),i=n.then(async()=>{await ma(ka(e),{recursive:!0,mode:448}),await ba(e),await pa(e,t.push(xa(o)),{encoding:"utf8",mode:384})});return n=i.catch(()=>{}),await i,o},read:()=>wa(e),flush:async()=>{await n}}}async function ba(e){let t;try{t=(await ga(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(t===0)return;let n=64*1024,r=await ya(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,t-1),o[0]===10)return;for(let i=t;i>0;i-=n){let s=Math.min(n,i),a=Buffer.alloc(s);await r.read(a,0,s,i-s);let l=a.lastIndexOf(10);if(l>=0){await vr(e,i-s+l+1);return}}await vr(e,0)}finally{await r.close()}}async function wa(e){let t;try{t=await ha(e,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return _a(t)}function _a(e){let t=e.split(`
39
- `);return t.pop(),t.length===0?[]:At(`${t.join(`
34
+ `));let r=yl(e.options);t.push(...r)}return t}function gl(e,t){let n=ml(e);return fl(n,t)}function hl(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 yl(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",a=t?"global-option-description":"option-description";for(let[d,u]of Object.entries(e)){if(u.hidden)continue;let f=[],p=R=>{f.includes(R)||f.push(R)};u.short&&p(`-${u.short}`),p(`--${d}`);for(let R of u.aliases??[])R.length===1?p(`-${R}`):p(`--${R}`);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 l=Math.max(...r.map(d=>d.flags.length+(d.type?d.type.length+1:0)),20);for(let d of r){let u=d.flags.length+(d.type?d.type.length+1:0),f=" ".repeat(l-u+2);n.push(x("indent"," ")),n.push(x(o,d.flags)),d.type&&(n.push(x("text"," ")),n.push(x(s,d.type))),n.push(x("text",f)),n.push(x(a,d.desc)),d.default!==void 0&&(n.push(x("text"," ")),n.push(x(i,`(default: ${d.default})`))),n.push(x("newline",`
35
+ `))}return n}function co(e){let t=xl(e.options??{},e.autoShort??!1),n=dl(e.separators??ao);return{schema:e,parse(r){return kl(r,e,t,n)},help(){return gl(e,e.formatter)}}}function kl(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,a=t.positional??[],l=0,d=!1;for(;l<e.length;){let u=e[l];if(t.stopEarly&&i>0){o.rest=e.slice(l);break}if(u==="--"&&!d){d=!0,l++;continue}if(d){if(i<a.length){let p=a[i];if(p.variadic){let h=[];for(;l<e.length;){let y=e[l];h.push(p.type?ce(y,p.type):y),l++}o.positional[p.name]=h,i++}else{let h=p.type?ce(u,p.type):u;o.positional[p.name]=h,i++,l++}}else t.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(u)),l++;continue}if(u.startsWith("--")){l=_l(u,l,e,o,n,t);continue}if(u.startsWith("-")&&u.length>1&&!Ol(u)){l=vl(u,l,e,o,n,t);continue}let f=Rl(u,r);if(f){let{key:p,value:h,config:y}=f,R=o,w=R[y.to]??(R[y.to]={});w[p]=y.typed?lo(h):oe(h),l++;continue}if(i<a.length){let p=a[i];if(p.variadic){let y=[];for(;l<e.length&&!e[l].startsWith("-");){let R=e[l];y.push(p.type?ce(R,p.type):R),l++}o.positional[p.name]=y,i++;continue}let h=p.type?ce(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}`);l++}return El(o,t,n),jl(o,t,a),Pl(o,t,n),o}function Rl(e,t){if(al.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),a=o.slice(s+1);if(wl(i))return{key:i,value:a,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(bl(o,s,n))return{key:o,value:s,config:n}}}return null}function wl(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function bl(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 _l(e,t,n,r,o,s){let i=e.slice(2);if(i.startsWith("no-")){let l=i.slice(3),d=o.get(l);if(d?.negatable!==!1&&d?.type==="boolean")return r.options[d.name]=!1,t+1}if(i.includes("=")){let l=i.indexOf("="),d=i.slice(0,l),u=i.slice(l+1);return pt(d,u,t+1,r,o,s)}let a=o.get(i);if(a){if(a.type!=="boolean"){let l=n[t+1];return Be(l)?pt(a.name,l,t+2,r,o,s):(r.errors.push(`Option --${i} requires a value`),t+1)}return r.options[a.name]=!0,t+1}return s.strict?r.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(r.options[i]=!0),t+1}function vl(e,t,n,r,o,s){let i=e.slice(1);if(i.includes("=")){let a=i.indexOf("="),l=i.slice(0,a),d=i.slice(a+1),u=ln(l,o);return u?pt(u.name,d,t+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${l}`):s.allowUnknown!==!1&&(r.options[l]=ut(oe(d))),t+1)}if(i.length===1){let a=ln(i,o);if(a){if(a.type!=="boolean"){let l=n[t+1];return Be(l)?pt(a.name,l,t+2,r,o,s):(r.errors.push(`Option -${i} requires a value`),t+1)}return r.options[a.name]=!0,t+1}if(s.strict)r.errors.push(`Unknown option: -${i}`);else if(s.allowUnknown!==!1){let l=n[t+1];if(Be(l))return r.options[i]=ut(oe(l)),t+2;r.options[i]=!0}return t+1}for(let a of i){let l=ln(a,o);l?l.type==="boolean"?r.options[l.name]=!0:r.errors.push(`Option -${a} requires a value`):s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=!0)}return t+1}function pt(e,t,n,r,o,s){let i=o.get(e);if(i){if(i.choices){let l=i.type?ce(oe(t),i.type):oe(t);if(!i.choices.includes(l))return r.errors.push(`Invalid value for '${e}': '${t}'. Allowed: ${i.choices.join(", ")}`),n}let a=i.type?ce(oe(t),i.type):oe(t);if(i.type==="array"){let l=r.options[e];Array.isArray(l)?l.push(...a):r.options[e]=a}else r.options[e]=a}else s.strict?r.errors.push(`Unknown option: --${e}`):s.allowUnknown!==!1&&(r.options[e]=ut(oe(t)));return n}function xl(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 a=i.short??"";t&&!a&&(a=Sl(s,o),a&&o.add(a));let l={name:s,short:a,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,l);for(let d of l.aliases)n.set(d,l)}return n}function Sl(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 ln(e,t){for(let n of t.values())if(n.short===e||n.aliases.includes(e))return n}function El(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?ce(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 jl(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 Pl(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 Ol(e){return/^-\d+(\.\d+)?$/.test(e)}var dn=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 Dl(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 Ll(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 a=n.get(i[1]);if(a===void 0)continue;let l=i[2];if(l===void 0&&Be(e[o+1])&&(l=e[o+1],o+=1),l===void 0)continue;let d=r.get(a)??[];d.push(l),r.set(a,d)}return r}function ue(e,t,n={}){let o=co({options:Dl(t),separators:{},allowUnknown:!0}).parse([...e]),s={},i=Ll(e,t),a=o.errors.find(l=>/^Option --?\S+ requires a value$/.test(l));if(a!==void 0)throw new Error(a.replace(/^Option /,""));if(o.errors.length>0)throw new Error(o.errors[0]);if(n.unknownFlags==="error"){let l=new Set(Object.keys(t));for(let d of Object.keys(o.options))if(!l.has(d))throw new dn(d.length===1?`-${d}`:`--${d}`,Object.keys(t).map(u=>u.length===1?`-${u}`:`--${u}`))}for(let[l,d]of Object.entries(t)){let u=o.options[l];u!==void 0&&(d.kind==="boolean"?s[l]=u:d.type==="array"?s[l]=(i.get(l)??[]).map(f=>d.coerce(f)):s[l]=d.coerce(String(u)))}return{values:s,positionals:o.rest}}var cn=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 uo(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 cn(n,Object.keys(t.commands))}let o=t.keepArgvOnDefault??!0;return{command:t.default,args:o?[...e]:r}}import{execFileSync as Bl}from"node:child_process";import{readFileSync as Kl}from"node:fs";import{dirname as yo,join as ql}from"node:path";import{existsSync as $l,readFileSync as Zm}from"node:fs";import{dirname as Al,join as Il}from"node:path";function po(e,t){let n=e;for(let r=0;r<16;r++){let o=Il(n,t);if($l(o))return o;let s=Al(n);if(s===n)break;n=s}return null}function Nl(e){let t=e.indexOf(" #");return(t>=0?e.slice(0,t):e).trim()}function ve(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 a=o.length-o.trimStart().length,l=o.slice(0,i).trim();if(!l)continue;let d=o.slice(i+1).trim();for(;n.length&&n[n.length-1].indent>=a;)n.pop();if(n.push({indent:a,key:l}),d&&n.map(f=>f.key).join(".")===t)return Nl(d)}}import{createHash as Tl}from"node:crypto";var Wl="project.name";function mo(e){let t=ve(e,Wl)?.trim();return t===void 0||t===""?void 0:t}var Ml=8,go="project";function ho(e){let t=Vl(e.gitCommonDir),n=(e.declaredName??"").trim(),r=n!==""?{name:n,source:"declared"}:Cl(e.remoteUrl)??{name:Ul(e.checkoutPath,t),source:"basename"},o=Hl(t??un(e.checkoutPath));return{name:r.name,slug:`${Fl(r.name)}-${o}`,hash:o,source:r.source}}function Cl(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(a=>a.trim()).filter(a=>a!=="");return s.length===0?void 0:{name:s.slice(-2).join("/"),source:"remote"}}function Ul(e,t){let n=t===void 0?"":fo(Jl(t));if(n!=="")return n;let r=fo(un(e));return r===""?go:r}function Fl(e){let n=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return n===""?go:n}function Hl(e){return Tl("sha256").update(e).digest("hex").slice(0,Ml)}function Vl(e){let t=un(e??"");return t===""?void 0:t}function un(e){let t=e.trim().replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t}function fo(e){let t=e.split("/").filter(n=>n!=="");return t[t.length-1]??""}function Jl(e){return e.split("/").filter(n=>n!=="").slice(0,-1).join("/")}var Gl=2e3;function ko(e){return zl(e).name}function zl(e){let t=fn(e),n=pn(e,["rev-parse","--absolute-git-dir"])??pn(e,["rev-parse","--git-common-dir"]),r=pn(e,["remote","get-url","origin"]);return ho({checkoutPath:t.root??e,...n!==void 0?{gitCommonDir:n}:{},...r!==void 0?{remoteUrl:r}:{},...t.name!==void 0?{declaredName:t.name}:{}})}function fn(e){let t=po(e,ql(".red","config.yaml"));if(t==null)return{};let n;try{n=Kl(t,"utf8")}catch{return{}}let r=mo(n),o=yo(yo(t));return{...r===void 0?{}:{name:r},configText:n,root:o}}function pn(e,t){try{let n=Bl("git",[...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Gl}).trim();return n===""?void 0:n}catch{return}}import{randomUUID as Ii}from"node:crypto";import{spawn as zp}from"node:child_process";import{mkdir as Qp,rm as Yp}from"node:fs/promises";import{dirname as Zp}from"node:path";import{createHash as Zl}from"node:crypto";import{constants as kn}from"node:fs";import{mkdir as Xl,open as ed}from"node:fs/promises";import{createConnection as td}from"node:net";import{tmpdir as nd}from"node:os";import{dirname as rd,join as Rn}from"node:path";var Ql="toon";function bo(e){return e.trimStart().startsWith("{")?"json":"toon"}function gn(e){let t=0;for(;e[t]===`
37
+ `||e[t]==="\r";)t+=1;let n=e.slice(t);if(n==="")return null;let r=bo(n);if(r==="json"){let s=n.indexOf(`
38
+ `);return s<0?null:{frame:n.slice(0,s),dialect:r,rest:n.slice(s+1)}}let o=n.indexOf(`
39
+
40
+ `);return o<0?null:{frame:n.slice(0,o+1),dialect:r,rest:n.slice(o+2)}}function hn(e){let t=bo(e)==="json"?mn:Ro,n=t===mn?Ro:mn;try{return t(e)}catch(r){try{return n(e)}catch{throw r}}}function mn(e){return JSON.parse(e)}function Ro(e){return K(e)}function yn(e,t){if(t==="toon"){let n=Yl(e);if(n!==null)return n.endsWith(`
41
+ `)?`${n}
42
+ `:`${n}
43
+
44
+ `}return`${JSON.stringify(e)}
45
+ `}function Yl(e){try{let t=JSON.stringify(e);if(t===void 0)return null;let n=A(JSON.parse(t));return n.trim()===""?null:n}catch{return null}}function _o(e,t){return!wo(e)||!wo(t)||t.ok!==!1?!1:typeof e.id=="string"&&typeof t.id=="string"&&t.id!==e.id}function wo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var vo=new Set;function xo(e){return vo.has(e)?"json":Ql}function So(e){vo.add(e)}var od=108;async function ft(e,t,n="resident server"){let r=e.wire,o=r??xo(e.socketPath),s=await Eo(e,t,n,o);return r||o==="json"||!_o(t,s)?s:(So(e.socketPath),await Eo(e,t,n,"json"))}async function Eo(e,t,n,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let a=td(e.socketPath),l=!1,d="",u=setTimeout(()=>{f(()=>i(new Error(`${n} timed out`))),a.destroy()},o);function f(p){l||(l=!0,clearTimeout(u),p())}a.on("connect",()=>{a.write(yn(t,r))}),a.on("data",p=>{d+=p.toString("utf8");let h=gn(d);h&&(d=h.rest,f(()=>{try{s(hn(h.frame))}catch(y){i(y)}}),a.end())}),a.on("error",p=>f(()=>i(p))),a.on("close",()=>{l||f(()=>i(new Error(`${n} closed without response`)))})})}function jo(e,t,n){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=gn(r);if(!s)return;r=s.rest,e.pause();let i=a=>{if(!(e.destroyed||!e.writable))try{e.write(yn(a,s.dialect))}catch{}};(async()=>{let a;try{a=hn(s.frame),await t(a,i)}catch(l){n(l,a,i)}finally{e.end()}})()})}async function Po(e){await Xl(rd(e),{recursive:!0,mode:448});try{return await ed(e,kn.O_CREAT|kn.O_EXCL|kn.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function T(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function mt(e){let t=e.env??process.env,n=Zl("sha256").update(e.key).digest("hex").slice(0,20),r=t.XDG_RUNTIME_DIR;if(r){let s=Rn(r,"red-skills",n);if(Rn(s,e.socketFileName).length<od)return s}let o=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid");return Rn(nd(),`red-skills-${o}`,n)}Z();import{homedir as jd}from"node:os";import{join as jn}from"node:path";import{spawnSync as Pd}from"node:child_process";import{createHash as Od}from"node:crypto";import{existsSync as Dd}from"node:fs";import{mkdir as No,readFile as Ld,writeFile as $d}from"node:fs/promises";import{dirname as Ad}from"node:path";var Ge="@reddb-io/red-skills",gd="https://registry.npmjs.org",hd="canary",xe=class extends Error{kind;cause;constructor(t,n,r){super(n),this.name="BundleFetchError",this.kind=t,this.cause=r}};function yd(e,t,n="stable"){return`${e}-${n==="canary"?"canary":t}.bundle.min.mjs`}function kt(e){let{plugin:t,version:n,cacheDir:r,channel:o}=e;return Rt(r,yd(t,n,o))}function kd(e){return e==="dev"?["rsp"]:[]}function Rd(e){return`${e}.bundle.min.mjs`}function wd(e){return Rt("dist",Rd(e))}function bd(e,t="stable"){return`${Ge}@${t==="canary"?hd:e}`}function _d(e=Ge){return`${gd}/${e.replace("/","%2F")}`}async function En(e,t){let{plugin:n,version:r,cacheDir:o,channel:s="stable"}=t,i=kt({plugin:n,version:r,cacheDir:o,channel:s}),a=kd(n),l=a.map(p=>kt({plugin:p,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await vd(e,l))return i;let d=bd(r,s),u=Rt(o,`.staging-${n}-${s==="canary"?"canary":r}`),f;try{f=await e.materialize(d,u)}catch(p){throw Io(p,d)}for(let p of[n,...a]){let h=wd(p),y=Rt(f,h);if(!await e.exists(y))throw new xe("bundle-missing",`npm package ${d} has no ${h}`);let R=p===n?i:kt({plugin:p,version:r,cacheDir:o,channel:s});await e.writeFile(R,await e.readFile(y))}return i}async function vd(e,t){for(let n of t)if(!await e.exists(n))return!1;return!0}async function $o(e,t,n=Ge){let r;try{r=await e.fetchText(_d(n))}catch(s){throw Io(s,n)}let o=xd(r);return{sameMajor:Sd(o,t),newest:Ed(o)}}function xd(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 Sd(e,t){let n=Sn(t);if(n===null)return null;let r=null;for(let o of e)Sn(o)===n&&(r===null||Ao(o,r)>0)&&(r=o);return r}function Ed(e){let t=null;for(let n of e){let r=String(n).trim();Sn(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(t===null||Ao(r,t)>0)&&(t=r)}return t}function Sn(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?Number(t[1]):null}function Ao(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 Io(e,t){let n=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(n)?new xe("npm-unavailable",`npm is unavailable while resolving ${t}: ${n}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(n)?new xe("package-missing",`npm could not resolve ${t}: ${n}`,e):new xe("network",`failed to resolve ${t}: ${n}`,e)}function Rt(e,t){return e.endsWith("/")?`${e}${t}`:`${e}/${t}`}Z();var Id={async materialize(e,t){await No(t,{recursive:!0});let n=Pd("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 jn(t,"node_modules",...Ge.split("/"))},async readFile(e){return new Uint8Array(await Ld(e))},async writeFile(e,t){await No(Ad(e),{recursive:!0}),await $d(e,t)},async exists(e){return Dd(e)},sha256(e){return Od("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()}},Nd="redskilled";function Td(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let t=e.XDG_CACHE_HOME||jn(e.HOME||jd(),".cache");return jn(t,"red-skills","bundles")}async function Wd(e={},t={},n={}){let r=se(e,t);if(G(r))return r;let o=n.env??t.env??process.env;try{await En(n.bundleIO??Id,{plugin:Nd,version:n.version??"",cacheDir:Td(o)})}catch{return r}return se(e,t)}async function To(e={},t={},n={}){let r=await Wd(e,t,n);if(G(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(Z(),Lo));throw new o(r)}import{randomUUID as Dt}from"node:crypto";import{mkdir as Vp,rm as Li}from"node:fs/promises";import{createServer as Jp}from"node:net";import{dirname as Bp}from"node:path";import{totalmem as Md}from"node:os";function Wo(e){let t=0,n=0,r=0,o=[],s=[];for(let i of e){let a=i.budget??{},l=!1;for(let[d,u]of[[a.memory_high,f=>t+=f],[a.memory_max,f=>n+=f]]){if(d==null)continue;let f=Se(d);f==null?l=!0:u(f)}a.cpu_weight!=null&&(r+=a.cpu_weight),l&&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 Se(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 Mo(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 Cd="REDSKILLED_MEMORY_CEILING",Ud="REDSKILLED_WORKER_CEILING",Fd=.7;function Co(e){let t=e?.memory_max??e?.memory_high;if(t!=null)return Se(t)}function Pn(e){let t=0,n=[];for(let r of e){let o=Co(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 Uo(e){let{ceiling:t}=e,n=Pn(e.workers),r=Co(e.budget),o=r===void 0?null:r,s=n.memory_bytes+(r??0),i=n.worker_count+1,a=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",l=`the host is already holding ${n.memory_bytes} bytes across ${n.worker_count} Worker(s)`,d=(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?d("refused-over-worker-ceiling",`redskilled refused this Worker${a}: it would be Worker ${i} past a host ceiling of ${t.worker_count} Worker(s), and ${l}`):t.memory_bytes!=null&&r===null?d("refused-unaccountable-budget",`redskilled refused this Worker${a}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${t.memory_bytes} bytes, and ${l}`):t.memory_bytes!=null&&s>t.memory_bytes?d("refused-over-memory-ceiling",`redskilled refused this Worker${a}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${t.memory_bytes} bytes, and ${l}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${a}: ${s} bytes of declared Worker memory against a host ceiling of ${t.memory_bytes??"unbounded"} bytes, and ${l}`,ceiling:t,consumption:n,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function Fo(e=process.env,t=Md()){let n=(e[Cd]??"").trim(),r=(e[Ud]??"").trim(),o=Vd(r);if(n!==""){let s=Hd(n,t);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(t*Fd),worker_count:o,source:r!==""?"declared":"host-fraction"}}function Hd(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)):Se(e)??void 0}function Vd(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 Jd,mkdir as Bd,open as Kd,readFile as qd,stat as Gd,truncate as Ho}from"node:fs/promises";import{dirname as zd}from"node:path";var Vo="redskilled.events.toonl";function Qd(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 Yd="daemon:";function Zd(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${Yd}${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 Jo(e){let t=sn({trailer:!1}),n=Promise.resolve();async function r(o){let s=n.then(async()=>{await Bd(zd(e),{recursive:!0,mode:448}),await Xd(e),await Jd(e,t.push(rc(o)),{encoding:"utf8",mode:384})});return n=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(Qd(o)),recordDaemonStop:o=>r(Zd(o)),read:()=>ec(e),flush:async()=>{await n}}}async function Xd(e){let t;try{t=(await Gd(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(t===0)return;let n=64*1024,r=await Kd(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),a=Buffer.alloc(i);await r.read(a,0,i,s-i);let l=a.lastIndexOf(10);if(l>=0){await Ho(e,s-i+l+1);return}}await Ho(e,0)}finally{await r.close()}}async function ec(e){let t;try{t=await qd(e,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return tc(t)}function tc(e){let t=e.split(`
46
+ `);return t.pop(),t.length===0?[]:on(`${t.join(`
40
47
  `)}
41
- `).filter(Sa).map(Ea)}function Er(e){let t=new Map;for(let n of e)n.event==="worker-birth"?t.set(n.worker_id,va(n)):t.delete(n.worker_id);return[...t.values()]}function va(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 xa(e){return{...e}}function Sa(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")}function Ea(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:z(e.project_label)??"",pid:Number(e.pid??0),workspace_path:z(e.workspace_path)??"",log_path:z(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:z(e.unit),memory_high:z(e.memory_high),memory_max:z(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:z(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:z(e.signal)}}function z(e){return e==null||e===""?null:String(e)}import{chmod as Pa,mkdir as ja,readFile as Oa,rm as $a,writeFile as La}from"node:fs/promises";import{dirname as Pr,join as Lr}from"node:path";import{tmpdir as jr}from"node:os";var Aa="redskilled.machine.claim.toon",Ia="REDSKILLED_MACHINE_DIR",Na=8,G=class extends Error{constructor(n,r,o){super(Ca(n,r,o));this.claimPath=n;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},Or;function Ar(){return Or??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},Or}function Ta(e={machineIdHash:"unknown"}){let t=e.env??process.env,n=t[Ia]?.trim();if(n)return n;let o=(e.platform??process.platform)==="win32"?t.PROGRAMDATA?.trim()||jr():jr();return Lr(o,`redskilled-${e.machineIdHash}`)}function Qe(e){return Lr(Ta(e),Aa)}function et(e,t,n={}){let r=n.clock??(()=>new Date().toISOString()),o=n.isPidAlive??A;async function i(){let l;try{l=await Oa(e,"utf8")}catch(c){if(c.code==="ENOENT"||Bt(c))return;throw c}let d=Wa(l);return Ma(d)?d:void 0}function s(l,d){return{version:1,scope:"machine",pid:l.pid,start_time:l.startTime,uid:l.uid,machine_id_hash:t.machineIdHash,session_key_hash:t.sessionKeyHash,socket_path:t.socketPath,acquired_at:d,renewed_at:d}}async function a(){try{return await $a(e,{force:!0}),!0}catch(l){if(Bt(l))return!1;throw l}}return{claimPath:e,read:i,async claim(l){await ja(Pr(e),{recursive:!0,mode:1023})!=null&&await Pa(Pr(e),1023).catch(()=>{});let c=!1;for(let f=0;f<Na;f+=1){let p=s(l,r());try{return await La(e,Da(p),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:c,claim:p}}catch(h){if(h.code!=="EEXIST"){if(Bt(h))return{claimed:!1,reason:"stale-claim-not-reapable"};throw h}}let m=await i();if(!m){if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable"};c=!0;continue}if($r(m,l,t.socketPath))return{claimed:!0,reaped:c,claim:m};if(await o(m.pid))return{claimed:!1,reason:"held",claim:m};if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable",claim:m};c=!0}return{claimed:!1,reason:"contended"}},async release(l){let d=await i();return!d||!$r(d,l,t.socketPath)?!1:await a()}}}function Ir(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 Nr(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 Ca(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 Bt(e){let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"}function $r(e,t,n){return e.pid===t.pid&&e.start_time===t.startTime&&e.socket_path===n}function Da(e){return`${L(e,{keyedMapCollapse:!0})}
42
- `}function Wa(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{try{return K(t)}catch{return null}}}function Ma(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}var Kt=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 Cr(e,t){if(t.held!=null)throw new Kt(t.held);let n=Tr(e.project_label,"a project label"),r=Tr(e.selector,"a selector");if(!Array.isArray(e.argv)||e.argv.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(n)}: a registration with nothing to run is a project the host could never start a Worker for`);let o=e.argv.map((a,l)=>{if(typeof a!="string"||a==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${l} of project ${JSON.stringify(n)} is not`);return a});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 i=e.renew_within_ms??3e5;if(!Number.isFinite(i)||i<=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 s=Date.parse(t.now);if(!Number.isFinite(s))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,target:e.target,registered_at:new Date(s).toISOString(),renew_within_ms:i,renew_by:new Date(s+i).toISOString()}}function qt(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")&&Number.isInteger(t.target)&&typeof t.registered_at=="string"&&typeof t.renew_within_ms=="number"&&typeof t.renew_by=="string"}function Tr(e,t){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${t} to register a project, not ${JSON.stringify(e)}`);return e}var Ua={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"};function Dr(e){return`worker-${e}`}function Wr(e){let t=Ua[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 Fa}from"node:child_process";import{readFileSync as Va,readdirSync as Ha}from"node:fs";import{join as Ja}from"node:path";function Ne(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 i=ke(o);return i==null?null:{name:r,declared:o,bytes:i}}return null}function Mr(e){let t=[],n=[];for(let r of e.workers){let o=Ne(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 i=e.rss[r.worker_id];if(typeof i!="number"||!Number.isFinite(i)){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}i<=o.bytes||t.push(Ba(r,o,i))}return{terminations:t,unenforceable:n}}function Ba(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 Ka=4096;function Ur(e,t={}){let n=t.platform??process.platform,r={rss:{},cpu_seconds:{}};if(e.length===0)return r;let o=qa(n,t);if(o.size===0)return r;let i=new Map;for(let l of o.values()){let d=i.get(l.ppid);d?d.push(l.pid):i.set(l.ppid,[l.pid])}let s={},a={};for(let l of e){if(!o.has(l.pid))continue;let d=0,c=0,f=[l.pid],p=new Set;for(;f.length>0;){let m=f.pop();if(p.has(m))continue;p.add(m);let h=o.get(m);if(h){d+=h.rssBytes,c+=h.cpuSeconds;for(let R of i.get(m)??[])f.push(R)}}s[l.worker_id]=d,a[l.worker_id]=c}return{rss:s,cpu_seconds:a}}function qa(e,t){return t.procRoot!=null||e==="linux"?Qa(t.procRoot??"/proc"):t.psTable!=null||e==="darwin"?Za(za(t.psTable)):new Map}function za(e){try{return(e??Ga)()}catch{return""}}function Ga(){return Fa("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Ya=1024;function Za(e){let t=new Map;for(let n of e.split(`
43
- `)){let r=n.trim().split(/\s+/);if(r.length!==4)continue;let[o,i,s]=r.slice(0,3).map(Number);if(![o,i,s].every(l=>l!=null&&Number.isSafeInteger(l)&&l>=0))continue;let a=Xa(r[3]);a!=null&&t.set(o,{pid:o,ppid:i,rssBytes:s*Ya,cpuSeconds:a})}return t}function Xa(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,i=1;for(let s=r.length-1;s>=0;s--){let a=Number(r[s]);if(!Number.isFinite(a)||a<0||r[s]==="")return null;o+=a*i,i*=60}return o}function Qa(e){let t=new Map,n;try{n=Ha(e)}catch{return t}for(let r of n){if(!/^\d+$/.test(r))continue;let o;try{o=Va(Ja(e,r,"stat"),"utf8")}catch{continue}let i=tl(o);i&&t.set(i.pid,{pid:i.pid,ppid:i.ppid,rssBytes:i.rssPages*Ka,cpuSeconds:i.cpuTicks/el})}return t}var el=100;function tl(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]),i=Number(r[11]),s=Number(r[12]),a=Number(r[21]);return!Number.isSafeInteger(n)||!Number.isSafeInteger(o)||!Number.isFinite(a)||!Number.isFinite(i)||!Number.isFinite(s)?null:{pid:n,ppid:o,rssPages:Math.max(0,a),cpuTicks:Math.max(0,i)+Math.max(0,s)}}var zt=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 Yt(e,t){for(let n of e)if(n.token_ref!=null&&n.token_ref!==t)throw new zt(n.project_label,n.token_ref,t)}function nl(e,t={now:new Date(0).toISOString()}){il(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(),i=e.map((l,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:l}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { remaining resetAt }",...i.flatMap(({alias:l,search_alias:d,project:c})=>{let f=JSON.stringify(c.owner),p=JSON.stringify(c.name),m=JSON.stringify(`repo:${c.owner}/${c.name} is:closed closed:>=${o}`);return[` ${l}: repository(owner: ${f}, name: ${p}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${d}: search(query: ${m}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
44
- `),aliases:i,closed_since:o}}function rl(e,t,n){let r=Re(t),o=Re(r.data),i=Array.isArray(r.errors)?r.errors.map(Re):[],s=sl(o.rateLimit,i),a=e.aliases.map(({alias:l,search_alias:d,project:c})=>{let f=c.owner+"/"+c.name,p=o[l],m=i.find(h=>Fr(h.path,l)||Fr(h.path,d));if(Kr(p)){let h=Vr(p.open_pull_requests),R=Vr(p.open_issues),b=al(o[d]);if(h!=null&&R!=null&&b!=null)return{project_label:c.project_label,repository:f,outcome:"counted",counts:{open_pull_requests:h,open_issues:R,recently_closed:b},detail:`counted ${f} for project ${JSON.stringify(c.project_label)}`}}return s.exhausted||Br(m)?{project_label:c.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${s.reset_at==null?"":`; the quota resets at ${s.reset_at}`}`}:{project_label:c.project_label,repository:f,outcome:"unreachable",counts:null,detail:`${f} is not reachable with the host token: ${Gt(m?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:n.fetchedAt,request_count:1,project_count:a.length,rate_limit:s,projects:a}}function ol(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 Hr(e){if(e.projects.length===0)return ol(e.now);Yt(e.projects,e.hostTokenRef);let t=nl(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let n=await e.transport(t.query);return rl(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(i=>({project_label:i.project_label,repository:`${i.owner}/${i.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${i.owner}/${i.name} answered: ${r}`}))}}}function Jr(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),i=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,s=i==null||i>t;return{version:1,fetched_at:n.fetched_at,age_ms:i,threshold_ms:t,stale:n.projects.length>0&&s,request_count:n.request_count,rate_limit:n.rate_limit,projects:n.projects.map(a=>({...a,fetched_at:n.fetched_at,age_ms:i,stale:s})),reason:n.projects.length===0?"the daemon polls no repository, so there are no counts to age":i==null?"these counts carry no readable instant, so they cannot be presented as current":s?`these counts are ${i}ms old, past the ${t}ms window`:`fetched ${i}ms ago, within the ${t}ms window`}}function il(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 sl(e,t){let n=Re(e),r=typeof n.remaining=="number"&&Number.isFinite(n.remaining)?n.remaining:null,o=typeof n.resetAt=="string"?n.resetAt:null,i=t.some(Br);return{remaining:r,reset_at:o,exhausted:i||r===0}}function Br(e){if(e==null)return!1;let t=Gt(e.type),n=Gt(e.message);return t==="RATE_LIMITED"||/rate limit/i.test(n)}function Fr(e,t){return Array.isArray(e)&&e.includes(t)}function Vr(e){let t=Re(e);return Number.isInteger(t.totalCount)?t.totalCount:null}function al(e){let t=Re(e);return Number.isInteger(t.issueCount)?t.issueCount:null}function Re(e){return Kr(e)?e:{}}function Kr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gt(e){return typeof e=="string"?e:""}var ll=3e4;function qr(e){let t=e.stalenessMs??ll,n=Zt(e.now),r=e.sampledAt==null?null:Zt(e.sampledAt),o=n==null||r==null?null:Math.max(0,n-r),i=o!=null&&o<=t,s=new Set(e.reattachedWorkerIds??[]),a=e.hostState.workers.map(p=>dl(p,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:i,nowMs:n,log:e.logLines?.[p.worker_id],state:s.has(p.worker_id)?"reattached":"running"})),l=a.filter(p=>p.vitals.rss_bytes==null).map(p=>p.worker_id).sort(),d=a.length-l.length,c=a.reduce((p,m)=>p+(m.vitals.rss_bytes??0),0),f=Jt(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:fl({sampledAt:e.sampledAt,ageMs:o,threshold:t,workerCount:a.length,measuredCount:d,unmeasured:l}),host:{worker_count:a.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:f,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:c,measured_worker_count:d,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:f.memory_bytes/e.ceiling.memory_bytes},projects:ul(a),workers:a,repository_activity:Jr({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs})}}function dl(e,t){let n=t.rss[e.worker_id],r=typeof n=="number"&&Number.isFinite(n)?n:null,o=Ne(e),i=e.budget?.memory_max??e.budget?.memory_high??null,s=Zt(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||s==null?null:Math.max(0,t.nowMs-s),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??i,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:cl(t.log)}}function cl(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 ul(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 fl(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 Zt(e){let t=Date.parse(e);return Number.isFinite(t)?t:null}var tt=1;async function nt(e,t){return await qe(e,t,"redskilled daemon")}function zr(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"&&typeof t.degraded=="boolean"&&typeof t.stale=="boolean"&&typeof t.generated_at=="string"}function Gr(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:tt,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:[...e.registrations??[]].sort((r,o)=>r.project_label.localeCompare(o.project_label)),budget_accounting:kr(t),upgrade:ml(e)}}function ml(e){let t=e.daemonVersion,n=e.published?.version??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}}function Yr(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)&&Rr(t.budget_accounting)&&(t.scope===void 0||Nr(t.scope))&&(t.registrations===void 0||Array.isArray(t.registrations)&&t.registrations.every(qt))&&(t.upgrade===void 0||yl(t.upgrade))}function yl(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")}import{spawnSync as it}from"node:child_process";import{existsSync as nn}from"node:fs";import{delimiter as xl,join as so}from"node:path";import{join as Zr}from"node:path";import{existsSync as hl}from"node:fs";import{createRequire as gl}from"node:module";var Xr="redskilled-job-object.node",re=100;function be(e){return{available:!1,reason:e}}function kl(e,t,n){return[Zr(n,"prebuilds",`${e}-${t}`,Xr),Zr(n,"native","build","Release",Xr)]}function Qr(e={}){let t=e.platform??process.platform,n=e.arch??process.arch;if(t!=="win32")return be(`Job Object placement is the Windows backend (platform=${t}), so there is no native reach to load here`);let r=e.packageRoot??bl(),o=e.exists??hl,i=kl(t,n,r),s=i.find(d=>o(d));if(s==null)return be(`no Job Object addon was found for ${t}-${n} (looked in ${i.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let a=e.requireFn??gl(import.meta.url),l;try{l=a(s)}catch(d){return be(`the Job Object addon at ${s} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return Rl(l)?{available:!0,binding:l}:be(`the Job Object addon at ${s} does not export createJobObject, so it cannot be the native reach`)}function Rl(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function bl(){return new URL("..",import.meta.url).pathname}function eo(e){let t=e??{},n=[],r=wl(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<re?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 ${re}, 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 wl(e){return Ne({budget:e})}var rt=5,to=19;function Xt(e){return{available:!1,reason:e}}var _l="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 ro(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=rt;else if(n.cpu_weight<re){let a=Math.round(to*(re-n.cpu_weight)/re);o=Math.min(to,Math.max(rt,a))}else o=rt,r.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${re}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${rt}`);let i=no(n.max_processes);i==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 s=no(n.cpu_seconds);return s==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}:{},...i!=null?{max_processes:i}:{},...s!=null?{cpu_seconds:s}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:_l,...r.length>0?{note:r.join("; ")}:{}}}function oo(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 ${vl(e.nice)} -n ${t.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",n.join(`
45
- `),e.command,...e.args]}function io(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 Qt(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 no(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function vl(e){return`'${e.replace(/'/g,"'\\''")}'`}var ao="REDSKILLED_PLACEMENT",ot="red-worker",en="/bin/sh";function lo(e=process.env,t=process.platform){let n=Xt(`POSIX rlimit and priority placement is the macOS backend (platform=${t})`);if(t==="win32")return{platform:t,systemdRun:null,userSession:!1,jobObjects:Qr({platform:t}),posix:n};let r=be(`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:Sl(e)};if(t!=="linux")return{platform:t,systemdRun:null,userSession:!1,jobObjects:r,posix:n};let o=(e.XDG_RUNTIME_DIR??"").trim(),i=o!==""&&nn(so(o,"systemd","private"));return{platform:t,systemdRun:po("systemd-run",e),userSession:i,jobObjects:r,posix:n}}function Sl(e){return nn(en)?{available:!0,shell:en,nice:po("nice",e)}:Xt(`no POSIX shell was found at ${en}, so there is nothing to apply rlimits or priority in`)}function co(e=process.env){let t=(e[ao]??"").trim().toLowerCase();return t===""?!0:!["off","false","0","no"].includes(t)}function El(e,t,n=ot){return uo(e,t,n).replace(/\.service$/,"")}function uo(e,t,n=ot){return`${tn(n,"red-worker",24)}-${tn(e,"project",32)}-${tn(t,"worker",32)}.service`}function fo(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"},i=d=>({isolated:!1,backend:"none",command:e.command,args:t,cwd:e.workspacePath,warning:d,...r?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(o.isolation==="inherit")return i("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return i(`worker isolation disabled by ${ao}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return jl(e,t,r,i);if(e.probes.platform==="darwin")return Pl(e,t,i);if(e.probes.platform!=="linux")return i(`transient-unit placement is the Linux backend (platform=${e.probes.platform}): the Worker is charged to the daemon's own resource group`);if(!e.probes.systemdRun)return i("transient-unit placement unavailable: systemd-run is not on PATH; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");if(!e.probes.userSession)return i("transient-unit placement unavailable: no systemd --user session; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");let s=uo(e.projectLabel,e.workerId,o.unit_prefix),a=["--user","--collect","--quiet","--wait",`--unit=${s}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&a.push("--pipe"),n.memory_high!=null&&a.push(`--property=MemoryHigh=${n.memory_high}`),n.memory_max!=null&&a.push(`--property=MemoryMax=${n.memory_max}`),n.cpu_weight!=null&&a.push(`--property=CPUWeight=${n.cpu_weight}`);for(let[d,c]of Object.entries(e.env??{}))a.push(`--setenv=${d}=${c}`);let l=Qt(e.budget);return{isolated:!0,backend:"transient-unit",unit:s,command:e.probes.systemdRun,args:[...a,"--",e.command,...t],...l!=null?{budgetWarning:l}:{}}}function Pl(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=ro(e.budget,{canRenice:r.nice!=null}),i=e.budget??{},s=i.memory_high!=null||i.memory_max!=null;return{isolated:!1,backend:"posix-limits",command:r.shell,args:oo({limits:o,nice:r.nice,command:e.command,args:t}),cwd:e.workspacePath,posix:o,warning:io(o),...s?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+o.memory_ceiling_reason}:{}}}function jl(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 i=eo(e.budget),s=El(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...t],cwd:e.workspacePath,job:{name:s,limits:i},...Ol(n&&i.note!=null?`${i.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,Qt(e.budget))}}function Ol(...e){let t=e.filter(n=>n!=null&&n!=="");return t.length>0?{budgetWarning:t.join("; ")}:{}}function po(e,t){for(let n of(t.PATH??"").split(xl)){if(!n)continue;let r=so(n,e);if(nn(r))return r}return null}function tn(e,t,n){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,n).replace(/-+$/g,"")||t}async function rn(e,t){let n=[],r=[];for(let o of e){let i=!1;try{i=await t(o)===!0}catch{i=!1}(i?n:r).push(o)}return{alive:n,dead:r}}function mo(e){return e.unit!=null&&e.unit!==""?$l(e.unit):A(e.pid)}function $l(e){let t=it("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return t.error!=null?!1:t.status===0}var Ll="REDSKILLED_UNIT_DISCOVERY",yo="(unowned)";function ho(e){let t=it("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 Al(e=process.env){let t=(e[Ll]??"").trim().toLowerCase();return t===""?!0:!["off","false","0","no"].includes(t)}function go(e,t,n=process.env){return Al(n)&&e===t}function ko(e=ot){let t=it("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(`
46
- `).map(n=>n.trim().split(/\s+/)[0]??"").filter(n=>n.startsWith(`${e}-`)&&n.endsWith(".service"))}function Ro(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:yo,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 bo(e){return e.project_label.trim()!==""?e:{...e,project_label:yo,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 wo(e){if(e.unit!=null&&e.unit!==""){let t=it("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}}var j={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function _o(e,t=j){let n=Tl(e,t),r=Cl(e,t),o=Dl(e,t,n),i=Il(t,n,r),s={detail:"host",line:o};for(let c of i){let f=Bl(o,Nl(c,t,n,r),t.separator);if(s={detail:c,line:f},Kl(f)<=t.maxWidth)break}let a=xo(s.line,t.maxWidth),l=t.verbose&&s.detail==="workers"?Fl(n,t):[],d=n.length>0?"workers":"host";return{version:1,line:a,lines:[a,...l],verbose:t.verbose,mode:t.mode,project:t.project,detail:s.detail,degraded:s.detail!==d||a!==s.line,stale:e.staleness.stale,generated_at:e.generated_at}}function Il(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 Nl(e,t,n,r){return e==="workers"?n.map(o=>Ul(o,t)):e==="projects"?r.map(Jl):[]}function Tl(e,t){return t.mode==="global"?e.workers:t.project==null?[]:e.workers.filter(n=>n.project_label===t.project)}function Cl(e,t){return t.mode==="global"?e.projects:e.projects.filter(n=>n.project_label===t.project)}function Dl(e,t,n){let r=[];return t.mode==="global"?r.push(`host ${e.host.worker_count}w/${e.host.project_count}p`):r.push(`${t.project??"project unknown"} ${n.length}w`),r.push(Wl(e,t)),t.mode==="local"&&n.length===0&&r.push("idle"),e.staleness.stale&&r.push(Ml(e)),r.join(" ")}function Wl(e,t){let n=t.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===t.project).reduce((o,i)=>o+i.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return t.mode==="global"&&r!=null&&r>0?`${oe(n)}/${oe(r)}`:oe(n)}function Ml(e){let t=e.staleness.age_ms;return t==null?"!unmeasured":`!stale ${Math.round(t/1e3)}s`}function Ul(e,t){let n=vo(e,t),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?oe(r):`${oe(r)}/${oe(e.budget.bytes)}`;return`${n} ${o}`}function Fl(e,t){let n=[];for(let r of e){let o=Hl(r.log.last_line);o!=null&&n.push(xo(` ${Vl} ${vo(r,t)}: ${o}`,t.maxWidth))}return n}var Vl="\u21B3";function Hl(e){if(e==null)return null;let t=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return t===""?null:t}function vo(e,t){return t.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Jl(e){return`${e.project_label} ${e.worker_count}w ${oe(e.observed_rss_bytes)}`}function Bl(e,t,n){return[e,...t].join(n)}function Kl(e){return[...e].length}function xo(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 oe(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 So}from"node:crypto";import{spawn as ql}from"node:child_process";import{closeSync as zl,mkdirSync as Gl,openSync as Yl}from"node:fs";import{dirname as Zl}from"node:path";var Te=class extends Error{constructor(t){super(t),this.name="RedskilledWorkerSpecError"}},st=class extends Error{constructor(n,r){super(n);this.admission=r;this.name="RedskilledAdmissionError"}};function Xl(e){if(e==null||e.trim()==="")return null;try{return Gl(Zl(e),{recursive:!0}),Yl(e,"a")}catch{return null}}function Ql(e){try{zl(e)}catch{}}function ed(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 Te(`redskilled worker spec is missing ${n}`);if(e.args!=null&&!Array.isArray(e.args))throw new Te("redskilled worker spec args must be an array")}function td(e){if(e==null)throw new st("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new st(e.reason,e)}function Po(e){let{spec:t,admission:n}=e;td(n),ed(t);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),i=(t.worker_id??e.workerId??So()).trim()||So(),s=e.probes??lo(r),a=e.openLog===!1?null:Xl(t.log_path),l=fo({workerId:i,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??co(r),probes:s,pipeOutput:a!==null}),c=(e.spawnFn??ql)(l.command,l.args,{...l.cwd!=null?{cwd:l.cwd}:{},detached:!0,stdio:a===null?"ignore":["ignore",a,a],env:l.isolated?{...r}:{...r,...t.env??{}}});if(a!==null&&Ql(a),c.pid==null)throw c.once("error",()=>{}),new Te(`redskilled could not spawn ${JSON.stringify(l.command)} for worker ${i}`);let f=l.job!=null?nd(l,s,c.pid):null;c.once("error",()=>{}),c.once("exit",(R,b)=>{try{f?.job?.close()}catch{}e.onExit?.(i,R,b)}),c.unref();let p=l.job!=null?f?.job!=null:l.isolated,m=[l.warning,f?.warning,l.budgetWarning].filter(R=>R!=null);return{worker:{worker_id:i,project_label:t.project_label,pid:c.pid,started_at:o(),workspace_path:t.workspace_path,...t.log_path!=null?{log_path:t.log_path}:{},isolated:p,...l.unit!=null?{unit:l.unit}:{},...t.budget!=null?{budget:t.budget}:{},warnings:m},admission:n,warnings:m,plan:l,child:c,...f?.job!=null?{job:f.job}:{}}}function nd(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 i;try{i=t.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(s){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${Eo(s)}. ${o}`}}try{i.assign(n)}catch(s){try{i.close()}catch{}return{warning:`Worker pid ${n} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${Eo(s)}. ${o}`}}return{job:i}}function Eo(e){return e instanceof Error?e.message:String(e)}import{open as rd,stat as od}from"node:fs/promises";var id=16*1024;async function jo(e,t=id){let n;try{n=(await od(e)).size}catch{return null}if(n<=0)return null;let r=Math.min(t,n),o;try{let i=await rd(e,"r");try{let s=Buffer.alloc(r);await i.read(s,0,r,n-r),o=s.toString("utf8")}finally{await i.close()}}catch{return null}return sd(o)}function sd(e){let t=e.split(`
47
- `);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 Ed}from"node:child_process";import{existsSync as Pd,readdirSync as jd}from"node:fs";import{dirname as Od,join as Co,resolve as $d}from"node:path";var $o="@reddb-io/red-skills",ad="https://registry.npmjs.org";var Ce=class extends Error{kind;cause;constructor(t,n,r){super(n),this.name="BundleFetchError",this.kind=t,this.cause=r}};function ld(e=$o){return`${ad}/${e.replace("/","%2F")}`}async function on(e,t,n=$o){let r;try{r=await e.fetchText(ld(n))}catch(o){throw fd(o,n)}return cd(dd(r),t)}function dd(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 cd(e,t){let n=Oo(t);if(n===null)return null;let r=null;for(let o of e)Oo(o)===n&&(r===null||ud(o,r)>0)&&(r=o);return r}function Oo(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?Number(t[1]):null}function ud(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 fd(e,t){let n=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(n)?new Ce("npm-unavailable",`npm is unavailable while resolving ${t}: ${n}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(n)?new Ce("package-missing",`npm could not resolve ${t}: ${n}`,e):new Ce("network",`failed to resolve ${t}: ${n}`,e)}function ie(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 sn(e,t){let n=ie(e),r=ie(t);return!n||!r?0:n.major-r.major||n.minor-r.minor||n.patch-r.patch}var Sp=4*60*60*1e3;import{spawnSync as pd}from"node:child_process";import{mkdir as md,rm as yd,writeFile as hd}from"node:fs/promises";import{existsSync as gd}from"node:fs";import{homedir as kd}from"node:os";import{dirname as Rd,join as an}from"node:path";var we="redskilled.service",ln="REDSKILLED_SUPERVISED",bd="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function wd(e=process.env){let t=e.XDG_CONFIG_HOME?.trim()||an(e.HOME?.trim()||kd(),".config");return an(t,"systemd","user")}function dn(e=process.env){return an(wd(e),we)}function Lo(e,t={}){let n=t.env??process.env,r=Ie(t.override??{},t.entryLookup??{}),o=[...r.args,...ge(e,t.idleMs==null?{}:{idleMs:t.idleMs})];return{unitName:we,unitPath:dn(n),command:r.command,args:o,text:_d(r.command,o,e)}}function _d(e,t,n){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${bd}`,"","[Service]","Type=simple",`ExecStart=${[e,...t].map(vd).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${ln}=1"`,`Environment="REDSKILLED_SESSION=${Ao(n.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
48
- `)}function vd(e){return/[\s"'\\$%]/.test(e)?`"${Ao(e)}"`:e}function Ao(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function Io(e,t={}){let n=t.writeFile??xd,r=t.run??cn,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(i=>i.ok),steps:o}}async function No(e={}){let t=e.removeFile??Sd,n=e.run??cn,r=dn(e.env??process.env),o=[at("disable",n,["systemctl","--user","disable","--now",we])];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 To(e={}){let t=e.exists??gd,n=e.run??cn,r=dn(e.env??process.env),o=t(r);return{unitName:we,unitPath:r,installed:o,enabled:o&&n(["systemctl","--user","is-enabled",we]).status===0,active:o&&n(["systemctl","--user","is-active",we]).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 xd(e,t){await md(Rd(e),{recursive:!0}),await hd(e,t,{encoding:"utf8",mode:420})}async function Sd(e){await yd(e,{force:!0})}function cn(e){let t=pd(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 Do=75,Mo=9e5,Wo="redskilled-replacement-entry-unresolved",Ld="REDSKILLED_NO_REGISTRY_PROBE";function Uo(e){let t=e.running.trim();if(Ad(t))return{act:"hold",reason:"local-build"};let n=e.published?.trim()??"";return!n||ie(n)===null?{act:"hold",reason:"published-unknown"}:sn(n,t)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:n,via:e.supervised?"supervisor-exit":"self-spawn"}}function Ad(e){let t=e.trim();return ie(t)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(t)}function Fo(e=process.env){return e[ln]==="1"}var un=class extends Error{code=Wo;searched;constructor(t,n){super(`${Wo}: the published redskilled bundle ${t} exists on no reachable path and the version-pinned dispatch is disabled
48
+ `).filter(oc).map(sc)}function Bo(e){let t=new Map;for(let n of e)n.event!=="daemon-stop"&&(n.event==="worker-birth"?t.set(n.worker_id,nc(n)):t.delete(n.worker_id));return[...t.values()]}function nc(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 rc(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 sc(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:X(e.project_label)??"",pid:Number(e.pid??0),workspace_path:X(e.workspace_path)??"",log_path:X(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:X(e.unit),memory_high:X(e.memory_high),memory_max:X(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:X(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:X(e.signal),reason:X(e.reason)}}function X(e){return e==null||e===""?null:String(e)}function Ko(e){let t=[...e.projects].sort((i,a)=>i.project_label.localeCompare(a.project_label)),n=e.backoffUntilMs??null,r=n!=null&&e.nowMs<n,o=[],s=[];for(let i of t){let a=Math.max(0,e.live[i.project_label]??0),l=Object.prototype.hasOwnProperty.call(e.queue,i.project_label),d=l?e.queue[i.project_label]??null:null,u={project_label:i.project_label,queue_depth:d,target:i.target,live:a};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(d==null){o.push({...u,outcome:"queue-unknown",wanted:0,detail:l?`the last poll produced no depth for project ${JSON.stringify(i.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(i.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...u,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(i.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,i.target),d)-a);if(f===0){o.push({...u,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(i.project_label)} holds ${a} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for none`});continue}o.push({...u,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(i.project_label)} holds ${a} Worker(s) against a target of ${i.target} and a queue of ${d}, 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:a+p,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function qo(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function zo(e){let t=e.workers.map(ic),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:lc({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:t.length,projects:n.length,surviving:r.length})}}function Qo(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 ic(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 lc(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 ${Go(e.held,"Worker")} across ${Go(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 Go(e,t){return`${e} ${t}${e===1?"":"s"}`}function On(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 dc,mkdir as cc,readFile as uc,rm as pc,writeFile as fc}from"node:fs/promises";import{dirname as Yo,join as ts}from"node:path";import{tmpdir as Zo}from"node:os";var mc="redskilled.machine.claim.toon",gc="REDSKILLED_MACHINE_DIR",hc=8,ie=class extends Error{constructor(n,r,o){super(kc(n,r,o));this.claimPath=n;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},Xo;function ns(){return Xo??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},Xo}function yc(e={machineIdHash:"unknown"}){let t=e.env??process.env,n=t[gc]?.trim();if(n)return n;let o=(e.platform??process.platform)==="win32"?t.PROGRAMDATA?.trim()||Zo():Zo();return ts(o,`redskilled-${e.machineIdHash}`)}function wt(e){return ts(yc(e),mc)}function bt(e,t,n={}){let r=n.clock??(()=>new Date().toISOString()),o=n.isPidAlive??T;async function s(){let l;try{l=await uc(e,"utf8")}catch(u){if(u.code==="ENOENT"||Dn(u))return;throw u}let d=wc(l);return bc(d)?d:void 0}function i(l,d){return{version:1,scope:"machine",pid:l.pid,start_time:l.startTime,uid:l.uid,machine_id_hash:t.machineIdHash,session_key_hash:t.sessionKeyHash,socket_path:t.socketPath,acquired_at:d,renewed_at:d}}async function a(){try{return await pc(e,{force:!0}),!0}catch(l){if(Dn(l))return!1;throw l}}return{claimPath:e,read:s,async claim(l){await cc(Yo(e),{recursive:!0,mode:1023})!=null&&await dc(Yo(e),1023).catch(()=>{});let u=!1;for(let f=0;f<hc;f+=1){let p=i(l,r());try{return await fc(e,Rc(p),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:u,claim:p}}catch(y){if(y.code!=="EEXIST"){if(Dn(y))return{claimed:!1,reason:"stale-claim-not-reapable"};throw y}}let h=await s();if(!h){if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable"};u=!0;continue}if(es(h,l,t.socketPath))return{claimed:!0,reaped:u,claim:h};if(await o(h.pid))return{claimed:!1,reason:"held",claim:h};if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable",claim:h};u=!0}return{claimed:!1,reason:"contended"}},async release(l){let d=await s();return!d||!es(d,l,t.socketPath)?!1:await a()}}}function rs(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 os(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 kc(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 Dn(e){let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"}function es(e,t,n){return e.pid===t.pid&&e.start_time===t.startTime&&e.socket_path===n}function Rc(e){return`${A(e,{keyedMapCollapse:!0})}
49
+ `}function wc(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{try{return K(t)}catch{return null}}}function bc(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 Ln(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 $n(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 _c=3e5,vc=.5,In=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 ss(e,t){if(t.held!=null)throw new In(t.held);let n=An(e.project_label,"a project label"),r=An(e.selector,"a selector"),o=Ln(e.argv,n),s=$n(e.env,n),i=An(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 a=e.renew_within_ms??_c;if(!Number.isFinite(a)||a<=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 l=Date.parse(t.now);if(!Number.isFinite(l))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(l).toISOString(),renew_within_ms:a,renew_by:new Date(l+a).toISOString(),renewed_at:new Date(l).toISOString(),renewals:0,launch_revision:0}}var _t=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 is(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:Ln(t.launch.argv,e.project_label),env:$n(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 xc(e,t){let n=Date.parse(e.renew_by);return Number.isFinite(n)?t>=n:!1}function as(e,t){let n=Date.parse(e.renewed_at??e.registered_at);return Number.isFinite(n)&&t-n<=e.renew_within_ms*vc?"renewing":"running-on"}function ls(e,t){let n=[],r=[];for(let o of e)(xc(o,t)?r:n).push(o);return{standing:n,lapsed:r}}function Nn(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||Sc(t.env))&&(t.launch_revision===void 0||Number.isInteger(t.launch_revision))}function Sc(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function An(e,t){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${t} to register a project, not ${JSON.stringify(e)}`);return e}var Ec={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 ds(e){return`worker-${e}`}function cs(e){let t=Ec[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 jc}from"node:child_process";import{readFileSync as Pc,readdirSync as Oc}from"node:fs";import{join as Dc}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=Se(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function us(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(Lc(r,o,s))}return{terminations:t,unenforceable:n}}function Lc(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 $c=4096;function ps(e,t={}){let n=t.platform??process.platform,r={rss:{},cpu_seconds:{}};if(e.length===0)return r;let o=Ac(n,t);if(o.size===0)return r;let s=new Map;for(let l of o.values()){let d=s.get(l.ppid);d?d.push(l.pid):s.set(l.ppid,[l.pid])}let i={},a={};for(let l of e){if(!o.has(l.pid))continue;let d=0,u=0,f=[l.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){d+=y.rssBytes,u+=y.cpuSeconds;for(let R of s.get(h)??[])f.push(R)}}i[l.worker_id]=d,a[l.worker_id]=u}return{rss:i,cpu_seconds:a}}function Ac(e,t){return t.procRoot!=null||e==="linux"?Cc(t.procRoot??"/proc"):t.psTable!=null||e==="darwin"?Wc(Ic(t.psTable)):new Map}function Ic(e){try{return(e??Nc)()}catch{return""}}function Nc(){return jc("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Tc=1024;function Wc(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(l=>l!=null&&Number.isSafeInteger(l)&&l>=0))continue;let a=Mc(r[3]);a!=null&&t.set(o,{pid:o,ppid:s,rssBytes:i*Tc,cpuSeconds:a})}return t}function Mc(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 a=Number(r[i]);if(!Number.isFinite(a)||a<0||r[i]==="")return null;o+=a*s,s*=60}return o}function Cc(e){let t=new Map,n;try{n=Oc(e)}catch{return t}for(let r of n){if(!/^\d+$/.test(r))continue;let o;try{o=Pc(Dc(e,r,"stat"),"utf8")}catch{continue}let s=Fc(o);s&&t.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*$c,cpuSeconds:s.cpuTicks/Uc})}return t}var Uc=100;function Fc(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]),a=Number(r[21]);return!Number.isSafeInteger(n)||!Number.isSafeInteger(o)||!Number.isFinite(a)||!Number.isFinite(s)||!Number.isFinite(i)?null:{pid:n,ppid:o,rssPages:Math.max(0,a),cpuTicks:Math.max(0,s)+Math.max(0,i)}}var Tn=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 Mn(e,t){for(let n of e)if(n.token_ref!=null&&n.token_ref!==t)throw new Tn(n.project_label,n.token_ref,t)}function Hc(e,t={now:new Date(0).toISOString()}){Bc(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((l,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:l}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { remaining resetAt }",...s.flatMap(({alias:l,search_alias:d,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[` ${l}: repository(owner: ${f}, name: ${p}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${d}: search(query: ${h}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
51
+ `),aliases:s,closed_since:o}}function Vc(e,t,n){let r=Ee(t),o=Ee(r.data),s=Array.isArray(r.errors)?r.errors.map(Ee):[],i=Kc(o.rateLimit,s),a=e.aliases.map(({alias:l,search_alias:d,project:u})=>{let f=u.owner+"/"+u.name,p=o[l],h=s.find(y=>fs(y.path,l)||fs(y.path,d));if(Rs(p)){let y=ms(p.open_pull_requests),R=ms(p.open_issues),w=qc(o[d]);if(y!=null&&R!=null&&w!=null)return{project_label:u.project_label,repository:f,outcome:"counted",counts:{open_pull_requests:y,open_issues:R,recently_closed:w},detail:`counted ${f} for project ${JSON.stringify(u.project_label)}`}}return i.exhausted||ks(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: ${Wn(h?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:n.fetchedAt,request_count:1,project_count:a.length,rate_limit:i,projects:a}}function Jc(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 gs(e){if(e.projects.length===0)return Jc(e.now);Mn(e.projects,e.hostTokenRef);let t=Hc(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let n=await e.transport(t.query);return Vc(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 hs(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(a=>({...a,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 ys(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 Bc(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 Kc(e,t){let n=Ee(e),r=typeof n.remaining=="number"&&Number.isFinite(n.remaining)?n.remaining:null,o=typeof n.resetAt=="string"?n.resetAt:null,s=t.some(ks);return{remaining:r,reset_at:o,exhausted:s||r===0}}function ks(e){if(e==null)return!1;let t=Wn(e.type),n=Wn(e.message);return t==="RATE_LIMITED"||/rate limit/i.test(n)}function fs(e,t){return Array.isArray(e)&&e.includes(t)}function ms(e){let t=Ee(e);return Number.isInteger(t.totalCount)?t.totalCount:null}function qc(e){let t=Ee(e);return Number.isInteger(t.issueCount)?t.issueCount:null}function Ee(e){return Rs(e)?e:{}}function Rs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wn(e){return typeof e=="string"?e:""}var Gc=3e4;function ws(e){let t=e.stalenessMs??Gc,n=Cn(e.now),r=e.sampledAt==null?null:Cn(e.sampledAt),o=n==null||r==null?null:Math.max(0,n-r),s=o!=null&&o<=t,i=new Set(e.reattachedWorkerIds??[]),a=e.hostState.workers.map(p=>zc(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"})),l=a.filter(p=>p.vitals.rss_bytes==null).map(p=>p.worker_id).sort(),d=a.length-l.length,u=a.reduce((p,h)=>p+(h.vitals.rss_bytes??0),0),f=Pn(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:Xc({sampledAt:e.sampledAt,ageMs:o,threshold:t,workerCount:a.length,measuredCount:d,unmeasured:l}),host:{worker_count:a.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:d,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:f.memory_bytes/e.ceiling.memory_bytes},projects:Zc(a),known_projects:Yc(e.hostState),workers:a,repository_activity:hs({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs})}}function zc(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=Cn(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms: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:Qc(t.log)}}function Qc(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 Yc(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 Zc(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 Xc(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 Cn(e){let t=Date.parse(e);return Number.isFinite(t)?t:null}var vt=1;async function Qe(e,t){return await ft(e,t,"redskilled daemon")}function bs(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 _s(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:vt,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:tu(e),budget_accounting:Wo(t),upgrade:nu(e)}}function tu(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:as(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 nu(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,newest_published_version:e.published?.newest??null,major_held:+(r!==null),major_hold:r}}function vs(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)&&Mo(t.budget_accounting)&&(t.scope===void 0||os(t.scope))&&(t.registrations===void 0||Array.isArray(t.registrations)&&t.registrations.every(Nn))&&(t.upgrade===void 0||ru(t.upgrade))}function ru(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.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 Et}from"node:child_process";import{existsSync as Jn}from"node:fs";import{delimiter as fu,join as As}from"node:path";import{join as xs}from"node:path";import{existsSync as su}from"node:fs";import{createRequire as iu}from"node:module";var Ss="redskilled-job-object.node",fe=100;function je(e){return{available:!1,reason:e}}function au(e,t,n){return[xs(n,"prebuilds",`${e}-${t}`,Ss),xs(n,"native","build","Release",Ss)]}function Es(e={}){let t=e.platform??process.platform,n=e.arch??process.arch;if(t!=="win32")return je(`Job Object placement is the Windows backend (platform=${t}), so there is no native reach to load here`);let r=e.packageRoot??du(),o=e.exists??su,s=au(t,n,r),i=s.find(d=>o(d));if(i==null)return je(`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 a=e.requireFn??iu(import.meta.url),l;try{l=a(i)}catch(d){return je(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return lu(l)?{available:!0,binding:l}:je(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function lu(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function du(){return new URL("..",import.meta.url).pathname}function js(e){let t=e??{},n=[],r=cu(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<fe?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 ${fe}, and Windows CPU rate control is an absolute cap rather than a share, so no rate limit is set`)),{...r!=null?{memory_limit_bytes:r.bytes,memory_budget_name:r.name,memory_budget_declared:r.declared}:{},...o!=null?{cpu_rate_percent:o}:{},kill_on_close:!0,...n.length>0?{note:n.join("; ")}:{}}}function cu(e){return ze({budget:e})}var xt=5,Ps=19;function Un(e){return{available:!1,reason:e}}var uu="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 Ds(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=xt;else if(n.cpu_weight<fe){let a=Math.round(Ps*(fe-n.cpu_weight)/fe);o=Math.min(Ps,Math.max(xt,a))}else o=xt,r.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${fe}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${xt}`);let s=Os(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=Os(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:uu,...r.length>0?{note:r.join("; ")}:{}}}function Ls(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 ${pu(e.nice)} -n ${t.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",n.join(`
52
+ `),e.command,...e.args]}function $s(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 Fn(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 Os(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function pu(e){return`'${e.replace(/'/g,"'\\''")}'`}var Is="REDSKILLED_PLACEMENT",St="red-worker",Hn="/bin/sh";function Ns(e=process.env,t=process.platform){let n=Un(`POSIX rlimit and priority placement is the macOS backend (platform=${t})`);if(t==="win32")return{platform:t,systemdRun:null,userSession:!1,jobObjects:Es({platform:t}),posix:n};let r=je(`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:mu(e)};if(t!=="linux")return{platform:t,systemdRun:null,userSession:!1,jobObjects:r,posix:n};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Jn(As(o,"systemd","private"));return{platform:t,systemdRun:Cs("systemd-run",e),userSession:s,jobObjects:r,posix:n}}function mu(e){return Jn(Hn)?{available:!0,shell:Hn,nice:Cs("nice",e)}:Un(`no POSIX shell was found at ${Hn}, so there is nothing to apply rlimits or priority in`)}function Ts(e=process.env){let t=(e[Is]??"").trim().toLowerCase();return t===""?!0:!["off","false","0","no"].includes(t)}function gu(e,t,n=St){return Ws(e,t,n).replace(/\.service$/,"")}function Ws(e,t,n=St){return`${Vn(n,"red-worker",24)}-${Vn(e,"project",32)}-${Vn(t,"worker",32)}.service`}function Ms(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=d=>({isolated:!1,backend:"none",command:e.command,args:t,cwd:e.workspacePath,warning:d,...r?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(o.isolation==="inherit")return s("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return s(`worker isolation disabled by ${Is}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return yu(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=Ws(e.projectLabel,e.workerId,o.unit_prefix),a=["--user","--collect","--quiet","--wait",`--unit=${i}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&a.push("--pipe"),n.memory_high!=null&&a.push(`--property=MemoryHigh=${n.memory_high}`),n.memory_max!=null&&a.push(`--property=MemoryMax=${n.memory_max}`),n.cpu_weight!=null&&a.push(`--property=CPUWeight=${n.cpu_weight}`);for(let[d,u]of Object.entries(e.env??{}))a.push(`--setenv=${d}=${u}`);let l=Fn(e.budget);return{isolated:!0,backend:"transient-unit",unit:i,command:e.probes.systemdRun,args:[...a,"--",e.command,...t],...l!=null?{budgetWarning:l}:{}}}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=Ds(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:Ls({limits:o,nice:r.nice,command:e.command,args:t}),cwd:e.workspacePath,posix:o,warning:$s(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 yu(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=js(e.budget),i=gu(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},...ku(n&&s.note!=null?`${s.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,Fn(e.budget))}}function ku(...e){let t=e.filter(n=>n!=null&&n!=="");return t.length>0?{budgetWarning:t.join("; ")}:{}}function Cs(e,t){for(let n of(t.PATH??"").split(fu)){if(!n)continue;let r=As(n,e);if(Jn(r))return r}return null}function Vn(e,t,n){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,n).replace(/-+$/g,"")||t}async function Bn(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 Us(e){return e.unit!=null&&e.unit!==""?Ru(e.unit):T(e.pid)}function Ru(e){let t=Et("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return t.error!=null?!1:t.status===0}var wu="REDSKILLED_UNIT_DISCOVERY",Fs="(unowned)";function Hs(e){let t=Et("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 bu(e=process.env){let t=(e[wu]??"").trim().toLowerCase();return t===""?!0:!["off","false","0","no"].includes(t)}function Vs(e,t,n=process.env){return bu(n)&&e===t}function Js(e=St){let t=Et("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 Bs(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:Fs,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 Ks(e){return e.project_label.trim()!==""?e:{...e,project_label:Fs,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 qs(e){if(e.unit!=null&&e.unit!==""){let t=Et("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 _u(e,t=50){if(Qs(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 vu(e,t={}){let n=t.batchSize??50;if(Qs(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,a)=>({alias:`q${a}`,project:i}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...r.map(({alias:i,project:a})=>` ${i}: search(query: ${JSON.stringify(a.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
54
+ `),aliases:r}}function xu(e,t){let n=Ye(t),r=Ye(n.data),o=Array.isArray(n.errors)?n.errors.map(Ye):[],s=Eu(r.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=Pu(r[a]);if(d!=null)return{project_label:l.project_label,outcome:"counted",depth:d,detail:`project ${JSON.stringify(l.project_label)} has ${d} item(s) matching its selector`};let u=o.find(f=>ju(f.path,a));return s.exhausted||Ys(u)?{project_label:l.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(l.project_label)} answered, so this queue has no depth rather than a depth of zero`+(s.reset_at==null?"":`; the quota resets at ${s.reset_at}`)}:{project_label:l.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(l.project_label)} could not be counted with the host token: ${Kn(u?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function Su(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:[]}}async function zs(e){if(e.projects.length===0)return Su(e.now);let t=e.batchSize??50,n=_u(e.projects,t),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of n){let i=vu(s,{batchSize:t});try{let a=await e.transport(i.query),l=xu(i,a);r.push(...l.projects),o=Gs(o,l.rate_limit)}catch(a){let l=a instanceof Error?a.message:String(a),d=/rate limit|secondary rate|429/i.test(l);o=Gs(o,{remaining:null,reset_at:null,exhausted:d});for(let u of s)r.push({project_label:u.project_label,outcome:d?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(u.project_label)} answered: ${l}`})}}return{version:1,fetched_at:e.now,request_count:n.length,project_count:r.length,batch_size:t,rate_limit:o,projects:r}}function Qs(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 Gs(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 Eu(e,t){let n=Ye(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(Ys)||r===0}}function Ys(e){return e==null?!1:Kn(e.type)==="RATE_LIMITED"||/rate limit/i.test(Kn(e.message))}function ju(e,t){return Array.isArray(e)&&e.includes(t)}function Pu(e){let t=Ye(e);return Number.isInteger(t.issueCount)?t.issueCount:null}function Ye(e){return Ou(e)?e:{}}function Ou(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kn(e){return typeof e=="string"?e:""}var D={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Xs(e,t=D){let n=Nu(e,t),r=Au(e,t),o=Iu(e,t),s=Tu(e,t,r,n),i=Lu(t,r,o),a={detail:"host",line:s};for(let f of i){let p=Ju(s,$u(f,t,r,o),t.separator);if(a={detail:f,line:p},Bu(p)<=t.maxWidth)break}let l=qn(a.line,t.maxWidth),d=t.verbose&&a.detail==="workers"?Uu(r,t):[],u=r.length>0?"workers":"host";return{version:1,line:l,lines:[l,...d],verbose:t.verbose,mode:t.mode,project:t.project,project_match:n,detail:a.detail,degraded:a.detail!==u||l!==a.line,stale:e.staleness.stale,generated_at:e.generated_at}}function ei(e){let t=e.options??D,n=qn(Du,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 Du="redskilled unreachable \u2014 Worker state unknown";function Lu(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 $u(e,t,n,r){return e==="workers"?n.map(o=>Cu(o,t)):e==="projects"?r.map(Vu):[]}function Au(e,t){return t.mode==="global"?e.workers:t.project==null?[]:e.workers.filter(n=>n.project_label===t.project)}function Iu(e,t){return t.mode==="global"?e.projects:e.projects.filter(n=>n.project_label===t.project)}function Nu(e,t){return t.project==null?"unresolved":e.known_projects==null||e.known_projects.includes(t.project)?"matched":"unregistered"}function Tu(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(Zs(e,t))):r==="matched"?(o.push(`${t.project} ${n.length}w`),o.push(Zs(e,t)),n.length===0&&o.push("idle")):o.push(Wu(t.project,r)),e.staleness.stale&&o.push(Mu(e)),o.join(" ")}function Wu(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 Zs(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?`${me(n)}/${me(r)}`:me(n)}function Mu(e){let t=e.staleness.age_ms;return t==null?"!unmeasured":`!stale ${Math.round(t/1e3)}s`}function Cu(e,t){let n=ti(e,t),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?me(r):`${me(r)}/${me(e.budget.bytes)}`;return`${n} ${o}`}function Uu(e,t){let n=[];for(let r of e){let o=Hu(r.log.last_line);o!=null&&n.push(qn(` ${Fu} ${ti(r,t)}: ${o}`,t.maxWidth))}return n}var Fu="\u21B3";function Hu(e){if(e==null)return null;let t=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return t===""?null:t}function ti(e,t){return t.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Vu(e){return`${e.project_label} ${e.worker_count}w ${me(e.observed_rss_bytes)}`}function Ju(e,t,n){return[e,...t].join(n)}function Bu(e){return[...e].length}function qn(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 me(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 ni}from"node:crypto";import{spawn as Ku}from"node:child_process";import{closeSync as qu,mkdirSync as Gu,openSync as zu}from"node:fs";import{dirname as Qu}from"node:path";var Ze=class extends Error{constructor(t){super(t),this.name="RedskilledWorkerSpecError"}},jt=class extends Error{constructor(n,r){super(n);this.admission=r;this.name="RedskilledAdmissionError"}};function Yu(e){if(e==null||e.trim()==="")return null;try{return Gu(Qu(e),{recursive:!0}),zu(e,"a")}catch{return null}}function Zu(e){try{qu(e)}catch{}}function Xu(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 Ze(`redskilled worker spec is missing ${n}`);if(e.args!=null&&!Array.isArray(e.args))throw new Ze("redskilled worker spec args must be an array")}function ep(e){if(e==null)throw new jt("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new jt(e.reason,e)}function oi(e){let{spec:t,admission:n}=e;ep(n),Xu(t);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(t.worker_id??e.workerId??ni()).trim()||ni(),i=e.probes??Ns(r),a=e.openLog===!1?null:Yu(t.log_path),l=Ms({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??Ts(r),probes:i,pipeOutput:a!==null}),u=(e.spawnFn??Ku)(l.command,l.args,{...l.cwd!=null?{cwd:l.cwd}:{},detached:!0,stdio:a===null?"ignore":["ignore",a,a],env:l.isolated?{...r}:{...r,...t.env??{}}});if(a!==null&&Zu(a),u.pid==null)throw u.once("error",()=>{}),new Ze(`redskilled could not spawn ${JSON.stringify(l.command)} for worker ${s}`);let f=l.job!=null?tp(l,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(R,w)=>{try{f?.job?.close()}catch{}e.onExit?.(s,R,w)}),u.unref();let p=l.job!=null?f?.job!=null:l.isolated,h=[l.warning,f?.warning,l.budgetWarning].filter(R=>R!=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,...l.unit!=null?{unit:l.unit}:{},...t.budget!=null?{budget:t.budget}:{},warnings:h},admission:n,warnings:h,plan:l,child:u,...f?.job!=null?{job:f.job}:{}}}function tp(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: ${ri(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)}: ${ri(i)}. ${o}`}}return{job:s}}function ri(e){return e instanceof Error?e.message:String(e)}import{open as np,stat as rp}from"node:fs/promises";var op=16*1024;async function si(e,t=op){let n;try{n=(await rp(e)).size}catch{return null}if(n<=0)return null;let r=Math.min(t,n),o;try{let s=await np(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 sp(o)}function sp(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 Rp}from"node:child_process";import{existsSync as wp,readdirSync as bp}from"node:fs";import{dirname as _p,join as ui,resolve as vp}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 Gn(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 ny=4*60*60*1e3;Z();Z();import{spawnSync as ip}from"node:child_process";import{mkdir as ap,rm as lp,writeFile as dp}from"node:fs/promises";import{existsSync as cp}from"node:fs";import{homedir as up}from"node:os";import{dirname as pp,join as zn}from"node:path";var Pe="redskilled.service",Qn="REDSKILLED_SUPERVISED",fp="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function mp(e=process.env){let t=e.XDG_CONFIG_HOME?.trim()||zn(e.HOME?.trim()||up(),".config");return zn(t,"systemd","user")}function Yn(e=process.env){return zn(mp(e),Pe)}function ii(e,t={}){let n=t.env??process.env,r=yt(t.override??{},t.entryLookup??{}),o=[...r.args,...pe(e,t.idleMs==null?{}:{idleMs:t.idleMs})];return{unitName:Pe,unitPath:Yn(n),command:r.command,args:o,text:gp(r.command,o,e)}}function gp(e,t,n){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${fp}`,"","[Service]","Type=simple",`ExecStart=${[e,...t].map(hp).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Qn}=1"`,`Environment="REDSKILLED_SESSION=${ai(n.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
56
+ `)}function hp(e){return/[\s"'\\$%]/.test(e)?`"${ai(e)}"`:e}function ai(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function li(e,t={}){let n=t.writeFile??yp,r=t.run??Zn,o=[];return await n(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(Pt("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(Pt("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function di(e={}){let t=e.removeFile??kp,n=e.run??Zn,r=Yn(e.env??process.env),o=[Pt("disable",n,["systemctl","--user","disable","--now",Pe])];return await t(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(Pt("daemon-reload",n,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function ci(e={}){let t=e.exists??cp,n=e.run??Zn,r=Yn(e.env??process.env),o=t(r);return{unitName:Pe,unitPath:r,installed:o,enabled:o&&n(["systemctl","--user","is-enabled",Pe]).status===0,active:o&&n(["systemctl","--user","is-active",Pe]).status===0,floor:"auto-spawn"}}function Pt(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 yp(e,t){await ap(pp(e),{recursive:!0}),await dp(e,t,{encoding:"utf8",mode:420})}async function kp(e){await lp(e,{force:!0})}function Zn(e){let t=ip(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 pi=75,mi=9e5,fi="redskilled-replacement-entry-unresolved",xp="REDSKILLED_NO_REGISTRY_PROBE";function gi(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function hi(e){let t=e.running.trim();if(ki(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:Sp(r.major,e.supervised)}}function Sp(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 yi(e){let t=e.running.trim();if(ki(t))return{act:"hold",reason:"local-build"};let n=e.published?.trim()??"";return!n||U(n)===null?{act:"hold",reason:"published-unknown"}:Gn(n,t)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:n,via:e.supervised?"supervisor-exit":"self-spawn"}}function ki(e){let t=e.trim();return U(t)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(t)}function Ri(e=process.env){return e[Qn]==="1"}var Xn=class extends Error{code=fi;searched;constructor(t,n){super(`${fi}: the published redskilled bundle ${t} exists on no reachable path and the version-pinned dispatch is disabled
49
57
  searched:
50
58
  ${n.map(r=>` ${r}`).join(`
51
- `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...n]}};function Id(e,t={}){let n=t.env??process.env,r=t.exists??Pd,o=t.execPath??process.execPath,i=t.callerEntry===void 0?process.argv[1]:t.callerEntry,s=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[Co(Vt(n),s),"bundle-cache"]];i&&l.push([Co(Od($d(i)),s),"caller-sibling-bundle"]);for(let[d,c]of l)if(a.push(d),r(d))return{command:o,args:[d],version:e,source:c,searched:a};if(n.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new un(e,a);return{command:n.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:a}}function Vo(e,t={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let n=t.resolveEntry??(r=>Id(r,t.env==null?{}:{env:t.env}));return{via:e.via,to:e.to,entry:n(e.to)}}function Ho(e,t,n={}){let r=n.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??Td)(Do),{...e,exitCode:Do};let o=[...e.entry.args,...ge(t,n.idleMs==null?{}:{idleMs:n.idleMs})];return(r.spawnSuccessor??Nd(r.env))(e.entry,o),e}function Nd(e){return(t,n)=>{let r=Ed(t.command,[...n],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1"}});r.on("error",()=>{}),r.unref()}}function Td(e){process.exitCode=e,process.exit(e)}async function Jo(e,t=process.env,n=Wd){let r=Cd(t);if(t[Ld]==="1")return r;let o=ie(e)===null?"0.0.0":e;try{return await on({fetchText:n},o)??r}catch{return r}}function Cd(e=process.env,t=Dd){let n=null;for(let r of t(Vt(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||ie(o)===null||(n===null||sn(o,n)>0)&&(n=o)}return n}function Dd(e){try{return jd(e)}catch{return[]}}async function Wd(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 Md,readFile as Ud,rename as Fd,rm as fn,writeFile as Bo}from"node:fs/promises";import{randomUUID as Vd}from"node:crypto";import{dirname as Hd}from"node:path";var lt=class extends Error{constructor(t){super(`redskilled lease ${JSON.stringify(t)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function mn(e){let t;try{t=await Ud(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let n=Jd(t);return Bd(n)?n:void 0}var Ko;function zo(){return Ko??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Ko}function Go(e,t,n={}){let r=n.clock??(()=>new Date().toISOString()),o=n.isPidAlive??A;async function i(){return await mn(e)}async function s(l){let d=`${e}.${l.pid}.${Vd()}.tmp`;await Bo(d,qo(l),{encoding:"utf8",mode:384}),await Fd(d,e)}function a(l,d){return{version:1,pid:l.pid,start_time:l.startTime,session_key_hash:t.sessionKeyHash,machine_id_hash:t.machineIdHash,socket_path:t.socketPath,acquired_at:d,renewed_at:d}}return{read:i,async acquire(l){await Md(Hd(e),{recursive:!0,mode:448});let d=!1;for(;;){let c=r(),f=a(l,c);try{return await Bo(e,qo(f),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:f}}catch(m){if(m.code!=="EEXIST")throw m}let p=await i();if(!p){await fn(e,{force:!0}),d=!0;continue}if(pn(p,l))return{acquired:!0,reaped:d,lease:p};if(await o(p.pid))return{acquired:!1,lease:p};await fn(e,{force:!0}),d=!0}},async renew(l){let d=await i();if(!d||!pn(d,l))throw new lt(e);let c={...d,renewed_at:r()};return await s(c),c},async release(l){let d=await i();if(!d)return!1;if(!pn(d,l))throw new lt(e);return await fn(e,{force:!0}),!0}}}function pn(e,t){return e.pid===t.pid&&e.start_time===t.startTime}function qo(e){return`${L(e,{keyedMapCollapse:!0})}
52
- `}function Jd(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{try{return K(t)}catch{return null}}}function Bd(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 yn=3e5,Yd=15e3,_e=class extends Error{constructor(n,r){super(`a redskilled daemon already owns ${JSON.stringify(n)}`);this.socketPath=n;this.lease=r;this.name="RedskilledAlreadyRunningError"}};async function Zo(e){let{paths:t}=e,n=e.daemonVersion??"0.0.0-dev",r=e.idleMs??yn,o=e.clock??(()=>new Date().toISOString()),i=e.launch??Po,s=e.ceiling??_r();e.repositoryActivity!=null&&Yt(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??zo(),l=e.leaseStore??Go(t.leasePath,{sessionKeyHash:t.sessionKeyHash,machineIdHash:t.machineIdHash,socketPath:t.socketPath},{clock:o}),d=e.machineOwner??Ar(),c={machineIdHash:t.machineIdHash,sessionKeyHash:t.sessionKeyHash,socketPath:t.socketPath},f=e.machineClaimStore??et(t.machineClaimPath,c,{clock:o});await qd(Gd(t.socketPath),{recursive:!0,mode:448});let p=await f.claim(d);if(!p.claimed)throw p.claim?.socket_path===t.socketPath?new _e(t.socketPath):new G(f.claimPath,p.reason,p.claim);let m=await l.acquire(a);if(!m.acquired)throw await f.release(d).catch(()=>{}),new _e(t.socketPath,m.lease);let h;try{h=await Zd(t.socketPath)}catch(u){throw await l.release(a).catch(()=>{}),await f.release(d).catch(()=>{}),u}let R=o(),b=e.eventLane??Sr(t.eventLanePath),w=e.liveness??mo,P=e.stopWorker??wo,C=e.unitInventory??(()=>go(t.machineClaimPath,Qe({machineIdHash:t.machineIdHash}))?ko():[]),N=e.unitMainPid??ho,Z=e.treeSampler??Ur,ae=e.readLogTail??jo,We=e.sampleMs??Yd,wi=e.publishedVersion??(u=>Jo(u)),wn=e.replaceCheckMs??Mo,_i=e.supervised??Fo(),_n=e.replacementIO??{},F=e.repositoryActivity,vn=F?.intervalMs??6e4,E=new Map,B=new Set,le=new Map,ut=new Map,ft=new Set,xn={},pt=null,Sn=null,En=null,Pn=!1,xe="none",mt=null,de,Se,Ee,Pe,X=!1,jn,yt=new Promise(u=>{jn=u});function Me(){return Gr({daemonVersion:n,machineIdHash:t.machineIdHash,sessionKeyHash:t.sessionKeyHash,pid:a.pid,startedAt:R,scope:Ir(f.claimPath,c,d),workers:[...E.values()],registrations:[...ut.values()],published:{version:Sn,checkedAt:En,newer:Pn,replacement:xe}})}function ht(){return qr({hostState:Me(),ceiling:s,rss:xn,sampledAt:pt,logLines:Object.fromEntries(le),now:o(),reattachedWorkerIds:[...B],repositoryActivity:mt})}async function gt(){return F==null||F.projects.length===0?null:(mt=await Hr({projects:F.projects,hostTokenRef:F.hostTokenRef,transport:F.transport,closedWindowMs:F.closedWindowMs,now:o()}),mt)}function vi(u){return _o(ht(),{...j,mode:u?.mode??j.mode,project:u?.project??j.project,maxWorkers:u?.max_workers??j.maxWorkers,maxProjects:u?.max_projects??j.maxProjects,maxWidth:u?.max_width??j.maxWidth,verbose:u?.verbose??j.verbose})}function Ue(u,y,k){return Wr({op:u,sessionProject:y??null,targetProject:k})}async function xi(u){let y=E.get(u.worker_id),k=Ue(Dr(u.command),u.session_project,y?.project_label??null);if(!k.permitted)throw new Error(k.reason);if(u.command!=="stop")throw new Error(`redskilled does not implement ${u.command}: it owns birth, death and limits, and ${u.command} is a work decision the project's own bundle makes on top of them`);let _=y!=null&&await ji(y,u.detail??"stopped by its own project");return{version:1,command:u.command,worker_id:u.worker_id,applied:_,reach:k,detail:_?`redskilled stopped Worker ${JSON.stringify(u.worker_id)} of project ${JSON.stringify(y.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(u.worker_id)} to stop`}}function Fe(u){E.delete(u),B.delete(u),le.delete(u)}function On(u){let y=E.get(u.worker_id),k=Ue("worker-heartbeat",u.session_project,y?.project_label??null);if(!k.permitted)throw new Error(k.reason);if(typeof u.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(y==null)return{version:1,worker_id:u.worker_id,accepted:!1,reach:k,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(u.worker_id)} to publish a line for`};let _=o();return le.set(u.worker_id,{line:u.last_log_line,published_at:_,source:"heartbeat"}),{version:1,worker_id:u.worker_id,accepted:!0,reach:k,published_at:_,detail:`redskilled stored a line for Worker ${JSON.stringify(u.worker_id)} without reading it`}}async function Si(u,y,k){let _=`exit code=${y??"null"} signal=${k??"null"}`;if(u.unit!=null&&u.unit!==""&&await Ei(u)){Pi(u,`its launch client ended (${_}) while unit ${JSON.stringify(u.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}Fe(u.worker_id),V("worker-death",u,_,{exitCode:y,signal:k}),$()}async function Ei(u){try{return await w(u)===!0}catch{return!1}}function Pi(u,y){let k=u.unit==null?null:N(u.unit);E.set(u.worker_id,{...u,...k!=null&&k>0?{pid:k}:{},warnings:[...u.warnings,y]}),B.add(u.worker_id),$()}function $n(u,y){let k=Ue("project-register",y,u.project_label);if(!k.permitted)throw new Error(k.reason);let _=Cr(u,{now:o(),held:ut.get(u.project_label)});return ut.set(_.project_label,_),{version:1,registration:_,reach:k,detail:`redskilled holds a registration for project ${JSON.stringify(_.project_label)} at a target of ${_.target} until ${_.renew_by}, and has read neither its selector nor its argv`}}async function ji(u,y){try{await P(u)}catch{}return Fe(u.worker_id),V("worker-death",u,y),$(),!0}function Ln(u){return wr({ceiling:s,workers:[...E.values()],budget:u.budget,projectLabel:u.project_label})}function An(u){let y=i({spec:u,admission:Ln(u),clock:o,onExit:(k,_,Q)=>{let ce=E.get(k);if(ce==null){$();return}Si(ce,_,Q).catch(()=>{})}});return E.set(y.worker.worker_id,y.worker),V("worker-birth",y.worker,null),$(),y}function V(u,y,k,_={}){X||b.record({event:u,worker:y,ts:o(),detail:k,..._.exitCode!==void 0?{exitCode:_.exitCode}:{},..._.signal!==void 0?{signal:_.signal}:{}}).catch(()=>{})}async function In(){let u=[...B].map(k=>E.get(k)).filter(k=>k!=null);if(u.length===0)return[];let{dead:y}=await rn(u,w);for(let k of y)Fe(k.worker_id),V("worker-death",k,"the host no longer confirms this Worker");return y.length>0&&$(),y}async function Nn(u,y){let k=E.get(u);if(!k)return!1;try{await P(k)}catch{}return Fe(u),V("worker-budget-kill",k,y),$(),!0}async function Tn(){let u=[...E.values()];if(u.length===0)return[];let y;try{y=await Z(u)}catch{return[]}let k=y.rss;xn=k,pt=o(),Oi(y.cpu_seconds,pt);let{terminations:_}=Mr({workers:u,rss:k}),Q=[];for(let ce of _)await Nn(ce.worker_id,ce.reason)&&Q.push(ce);return Q}function Oi(u,y){for(let[k,_]of Object.entries(u)){if(typeof _!="number"||!Number.isFinite(_))continue;let Q=E.get(k);Q&&E.set(k,{...Q,cpu:{cpu_seconds:_,sampled_at:y}})}}async function Cn(){let u;try{u=await wi(n)}catch{u=null}Sn=u,En=o();let y=Uo({running:n,published:u,supervised:_i});return Pn=y.act==="replace",xe!=="in-progress"&&(xe=y.act==="replace"?"pending":"none"),y}async function Dn(){let u=await Cn();if(u.act!=="replace"||xe==="in-progress")return u;let y=Vo(u,_n);return xe="in-progress",await b.flush().catch(()=>{}),await Ve(),Ho(y,t,{...r==null?{}:{idleMs:r},io:_n}),u}function $i(){X||Ee!=null||wn<=0||(Ee=setInterval(()=>{Dn().catch(()=>{})},wn),Ee.unref())}function Li(){X||Se!=null||We<=0||(Se=setInterval(()=>{Tn().catch(()=>{})},We),Se.unref())}function Ai(){X||Pe!=null||F==null||F.projects.length===0||vn<=0||(gt().catch(()=>{}),Pe=setInterval(()=>{gt().catch(()=>{})},vn),Pe.unref())}function $(){X||(de&&clearTimeout(de),de=setTimeout(()=>{In().catch(()=>{}).then(()=>Wn())},r),de.unref())}function Wn(){return E.size>0?($(),"held-by-workers"):(Ve(),"exited")}async function Ve(){if(X)return await yt;X=!0,de&&clearTimeout(de),Se&&clearInterval(Se),Ee&&clearInterval(Ee),Pe&&clearInterval(Pe),await b.flush().catch(()=>{}),h.close();for(let u of ft)u.destroy();return await new Promise(u=>h.once("close",()=>u())),await Yo(t.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await f.release(d).catch(()=>{}),jn(),await yt}let Ii=Er(await b.read().catch(()=>[])),kt=await rn(Ii,w);for(let u of kt.alive){let y=bo(u),k=y.unit==null||A(y.pid)?null:N(y.unit);E.set(y.worker_id,k!=null&&k>0?{...y,pid:k}:y),B.add(y.worker_id)}for(let u of kt.dead)V("worker-death",u,"the Worker ended while no daemon was watching");let Ni=Ro({units:await Promise.resolve(C()).catch(()=>[]),held:[...E.values()],mainPid:N,now:R});for(let u of Ni)E.set(u.worker_id,u),B.add(u.worker_id),V("worker-birth",u,"adopted from an active unit with no birth on this lane");for(let u of kt.alive){if(u.log_path==null||le.has(u.worker_id))continue;let y=await ae(u.log_path).catch(()=>null);y==null||y.trim()===""||le.set(u.worker_id,{line:y,published_at:o(),source:"rehydrated"})}h.on("connection",u=>{ft.add(u),u.once("close",()=>ft.delete(u)),$(),Xd(u,async y=>{$();let k=await Ti(y);Xo(u,k),y.op==="shutdown"&&setImmediate(()=>void Ve())})});async function Ti(u){try{if(u.op==="ping")return{id:u.id,ok:!0,value:{pong:!0,protocol_version:tt,daemon_version:n,pid:a.pid}};if(u.op==="host-state")return{id:u.id,ok:!0,value:Me()};if(u.op==="statusline-payload")return{id:u.id,ok:!0,value:ht()};if(u.op==="statusline-string")return{id:u.id,ok:!0,value:vi(u.render)};if(u.op==="worker-heartbeat")return{id:u.id,ok:!0,value:On(u.heartbeat)};if(u.op==="project-register")return{id:u.id,ok:!0,value:$n(u.registration,u.session_project)};if(u.op==="worker-command")return{id:u.id,ok:!0,value:await xi(u.command)};if(u.op==="worker-start"){let k=Ue("worker-start",u.session_project,u.spec.project_label);if(!k.permitted)return{id:u.id,ok:!1,error:k.reason};let _=An(u.spec);return await b.flush().catch(()=>{}),{id:u.id,ok:!0,value:{worker:_.worker,admission:_.admission,warnings:_.warnings}}}if(u.op==="shutdown")return{id:u.id,ok:!0,value:{stopping:!0}};let y=u;return{id:y.id??dt(),ok:!1,error:`unsupported redskilled op: ${y.op??"unknown"}`}}catch(y){return{id:u.id??dt(),ok:!1,error:y instanceof Error?y.message:String(y)}}}return $(),Li(),$i(),Ai(),{socketPath:t.socketPath,lease:m.lease,startedAt:R,closed:yt,startWorker:An,admit:Ln,ceiling:()=>s,killWorkerOverBudget:Nn,sampleMemoryBudgets:Tn,pollRepositoryActivity:gt,sweepReattached:In,publishWorkerHeartbeat:On,reattached:()=>[...B].map(u=>E.get(u)).filter(u=>u!=null),flushEvents:()=>b.flush(),trackWorker(u){E.set(u.worker_id,u),V("worker-birth",u,null),$()},releaseWorker(u){let y=E.get(u),k=E.delete(u);return B.delete(u),le.delete(u),y&&V("worker-death",y,"released by the daemon"),$(),k},workerCount:()=>E.size,registerProject:$n,registrations:()=>Me().registrations??[],hostState:Me,statuslinePayload:ht,evaluateIdle:Wn,observePublishedVersion:Cn,checkForReplacement:Dn,stop:Ve}}async function Zd(e){for(let t=0;t<2;t++){let n=zd();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 se(e))throw new _e(e);await Yo(e,{force:!0})}}throw new _e(e)}async function se(e,t=250){try{return(await qe({socketPath:e,timeoutMs:t},{id:dt(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function Xd(e,t){let n="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",r=>{n+=r;let o=n.indexOf(`
53
- `);if(o<0)return;let i=n.slice(0,o);e.pause(),(async()=>{let s;try{s=JSON.parse(i),await t(s)}catch(a){Xo(e,{id:s?.id??dt(),ok:!1,error:a instanceof Error?a.message:String(a)})}finally{e.end()}})()})}function Xo(e,t){if(!(e.destroyed||!e.writable))try{e.write(`${JSON.stringify(t)}
54
- `)}catch{}}var oc=1e4,De=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 hn(e,t={}){try{return await ic(e,t)}catch(n){throw n instanceof G||n instanceof De?n:new De(e.socketPath,n)}}async function ic(e,t){if(await tc(rc(e.socketPath),{recursive:!0,mode:448}),await se(e.socketPath))return"already-running";await sc(e);let n=await pr(e.lockPath);if(!n)return await Qo(e,t),"joined";try{if(await se(e.socketPath))return"already-running";let r=lc(e,t);return await Qo(e,t,r),"spawned"}finally{await n.close(),await nc(e.lockPath,{force:!0})}}async function sc(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&&A(n.pid))throw new G(e.machineClaimPath,"held",n)}async function ei(e,t,n={}){await hn(e,n);let r;try{r=await nt({socketPath:e.socketPath,timeoutMs:n.requestTimeoutMs??2e3},{...t,id:Qd()})}catch(o){throw new De(e.socketPath,o)}if(!r.ok)throw new Error(r.error);return r.value}async function ti(e,t={}){let n=await ei(e,{op:"host-state"},t);if(!Yr(n))throw new Error("redskilled daemon returned a malformed host state");return n}async function ni(e,t=void 0,n={}){let r=await ei(e,{op:"statusline-string",...n.sessionProject!=null?{session_project:n.sessionProject}:{},...t==null?{}:{render:ac(t)}},n);if(!zr(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function ac(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 Qo(e,t,n){let r=Date.now()+(t.readyTimeoutMs??oc);for(;;){if(await se(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))}}function lc(e,t){let n=t.serverCommand??(t.serverArgs!=null?process.execPath:void 0),r=Ie({...n!=null?{serverCommand:n}:{},serverArgs:t.serverArgs},t.entryLookup??{}),o={entry:r},i=[...r.args,...ge(e,t.idleMs==null?{}:{idleMs:t.idleMs})],s=ec(r.command,i,{detached:!0,stdio:"ignore",env:{...t.env??process.env,REDSKILLED_DAEMON:"1"}});return s.on("error",a=>{o.failure=a}),s.on("exit",(a,l)=>{o.exit=l?`died on ${l}`:`exited with code ${a??-1}`}),s.unref(),o}import{chmod as oi,mkdir as ii,readFile as hc,stat as gc,writeFile as kc}from"node:fs/promises";import{homedir as si}from"node:os";import{dirname as Rc,join as ai}from"node:path";import{join as dc}from"node:path";var cc=[".red","redskilled"],U=448;function gn(e){return dc(e,...cc)}import{createHash as uc}from"node:crypto";import{hostname as fc}from"node:os";import{join as ct}from"node:path";var ve="redskilled.sock",pc="REDSKILLED_SESSION";function mc(e={}){let t=e.env??process.env,n=t[pc]?.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 yc(e={}){return ri(e.host??fc())}function Y(e={}){let t=mc(e),n=e.runtimeDir??ze({key:`redskilled:${t}`,socketFileName:ve,env:e.env,uid:e.uid}),r=yc(e);return{sessionKey:t,sessionKeyHash:ri(t),machineIdHash:r,runtimeDir:n,socketPath:ct(n,ve),lockPath:ct(n,"redskilled.spawn.lock"),leasePath:ct(n,"redskilled.lease.toon"),eventLanePath:ct(n,xr),machineClaimPath:e.machineClaimPath??Qe({env:e.env,machineIdHash:r,platform:e.platform})}}function ri(e){return uc("sha256").update(e).digest("hex").slice(0,12)}var kn="run `/red-setup` (Section E3 \u2014 execution daemon), or `redskilled provision` directly";async function li(e=si()){let t=gn(e),n=await Rn(t);return n===void 0?(await ii(t,{recursive:!0,mode:U}),await oi(t,U),{path:t,created:!0,tightened:!1,mode:U}):n===U?{path:t,created:!1,tightened:!1,mode:n}:(await oi(t,U),{path:t,created:!1,tightened:!0,mode:U})}function di(e){let t=[bc(e),wc(e),_c(e),vc(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 bc(e){if(!e.homePresent)return{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist`,fix:kn};let t=e.homeMode??U;return t!==U?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${U.toString(8)}`,fix:`${kn} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function wc(e){return he(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 _c(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:`${kn} \u2014 it starts the daemon and waits for the socket`}}function vc(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 ci(e={}){let t=e.env??process.env,n=e.homeDir??si(),r=e.paths??Y({env:t}),o=gn(n),[i,s]=await Promise.all([Rn(o),se(r.socketPath)]);return{homePath:o,homePresent:i!==void 0,homeMode:i,entry:Xe(e.entryOverride??{},{env:t,...e.entryLookup}),socketPath:r.socketPath,reachable:s,supervisorUnit:await Sc(Ec(e,t,n),t)}}var xc="redskilled.service";function ui(e){return ai(e,"systemd","user",xc)}function fi(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(`
55
- `)}async function pi(e){let t=ui(e.configHome);return await Rn(t)!==void 0?{path:t,status:"already-present"}:(await ii(Rc(t),{recursive:!0}),await kc(t,e.unit,"utf8"),{path:t,status:"installed"})}async function Sc(e,t){if(process.platform!=="linux")return"unsupported";try{return await hc(ui(e),"utf8"),"installed"}catch{return t.XDG_RUNTIME_DIR?"absent":"unsupported"}}function Ec(e,t,n){return e.configHome??t.XDG_CONFIG_HOME?.trim()??ai(n,".config")}async function Rn(e){try{return(await gc(e)).mode&511}catch{return}}import{readdir as yi,rm as Pc,stat as jc}from"node:fs/promises";import{dirname as Oc,join as bn}from"node:path";var $c=5*6e4,Lc="redskilled.";function Ac(e={}){let t=e.env??process.env,n=s=>Oc(ze({key:"redskilled:reclaim-probe",socketFileName:ve,env:s,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=t,i=[n(t),n(o)];return[...new Set(i)]}async function hi(e={}){let t=e.roots??Ac(e),n=e.graceMs??$c,r=e.now??Date.now,o=e.isPidAlive??A,i=e.answers??Cc,s=e.dryRun===!0,a=[];for(let l of t){let d;try{d=(await yi(l,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name)}catch{continue}for(let c of d.sort())a.push(await Ic(bn(l,c),{graceMs:n,now:r,pidAlive:o,answers:i,dryRun:s}))}return{roots:t,scanned:a.length,reclaimed:a.filter(l=>l.verdict==="reclaimed").length,dryRun:s,entries:a}}async function Ic(e,t){let n;try{n=(await yi(e)).sort()}catch(s){return{dir:e,verdict:"failed",reason:gi(s),removed:[]}}let r=n.filter(s=>s.startsWith(Lc));if(n.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await Nc(bn(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 mi(e,n,`lease pid ${o.pid} is dead`,t);if(n.includes(ve)&&await t.answers(bn(e,ve)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let i=await Tc(e,t.now);return i!==void 0&&i<t.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(i/1e3)}s ago`,removed:[]}:await mi(e,n,n.length===0?"empty and stale":"no lease and stale",t)}async function mi(e,t,n,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${n} (dry run)`,removed:t};try{await Pc(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:gi(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:n,removed:t}}async function Nc(e){try{return await mn(e)}catch{return}}async function Tc(e,t){try{return Math.max(0,t()-(await jc(e)).mtimeMs)}catch{return}}async function Cc(e){try{return(await nt({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function gi(e){return e instanceof Error?e.message:String(e)}var Dc="plugins.dev.statusline",Wc="dev.statusline";function Mc(e){let t=[],n=a=>{for(let l of[Dc,Wc]){let d=`${l}.${a}`,c=Ke(e,d)?.trim();if(c!=null&&c!=="")return{key:d,value:c}}},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 i=[{leaf:"max_workers",assign:a=>{o.maxWorkers=a}},{leaf:"max_projects",assign:a=>{o.maxProjects=a}},{leaf:"max_width",assign:a=>{o.maxWidth=a}}];for(let a of i){let l=n(a.leaf);if(l==null)continue;let d=Number(l.value);Number.isInteger(d)&&d>=0?a.assign(d):t.push({...l,reason:"expected a whole number of zero or more"})}let s=n("verbose");return s!=null&&(s.value==="true"||s.value==="false"?o.verbose=s.value==="true":t.push({...s,reason:"expected `true` or `false`"})),{config:o,warnings:t}}var Uc={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 ki(e){let{values:t,positionals:n}=ye(e,Uc),r=[],o={},i=t.mode??n.find(a=>a==="global"||a==="local");i!=null&&(i==="local"||i==="global"?o.mode=i:r.push({key:"--mode",value:i,reason:"expected `local` or `global`"})),t.project!=null&&(o.project=t.project),t.verbose!==void 0&&(o.verbose=t.verbose===!0);let s=[{flag:"max-workers",assign:a=>{o.maxWorkers=a}},{flag:"max-projects",assign:a=>{o.maxProjects=a}},{flag:"max-width",assign:a=>{o.maxWidth=a}}];for(let a of s){let l=t[a.flag];if(l==null)continue;let d=Number(l);Number.isInteger(d)&&d>=0?a.assign(d):r.push({key:`--${a.flag}`,value:l,reason:"expected a whole number of zero or more"})}return{flags:o,warnings:r}}function Ri(e={}){let t=e.configText==null?{config:{},warnings:[]}:Mc(e.configText),n=e.flags??{};return{options:{...j,mode:n.mode??t.config.mode??j.mode,project:n.project!==void 0?n.project:e.project??j.project,maxWorkers:n.maxWorkers??t.config.maxWorkers??j.maxWorkers,maxProjects:n.maxProjects??t.config.maxProjects??j.maxProjects,maxWidth:n.maxWidth??t.config.maxWidth??j.maxWidth,verbose:n.verbose??t.config.verbose??j.verbose},warnings:t.warnings}}var Hc={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}};async function Jc(e){if(e[0]==="--version"||e[0]==="-v"){let o=Nt("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
56
- `:`${sr(o)}
57
- `),0}let{command:t,args:n}=cr(e,{commands:{serve:{},"host-state":{},statusline:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t==="serve"){let{values:o}=ye(n,Hc),i=await Zo({paths:Qc(o),idleMs:o["idle-ms"]??yn,daemonVersion:o["daemon-version"]??Nt("redskilled").version});for(let s of["SIGTERM","SIGINT"])process.once(s,()=>void i.stop().catch(()=>{}));return await i.closed,0}if(t==="statusline")return await Kc(n);if(t==="unit")return await Bc(n);if(t==="provision")return await zc(n);if(t==="reclaim")return await Yc(n);let r=await ti(Y());return process.stdout.write(`${JSON.stringify(r,null,2)}
58
- `),0}async function Bc(e,t={}){let n=t.write??(i=>process.stdout.write(i)),r=t.paths??Y(),o=e[0]??"status";if(o==="status")return n(`${JSON.stringify(To(t.unitIO??{}),null,2)}
59
- `),0;if(o==="install"){let i=await Io(Lo(r),t.unitIO??{});return n(`${JSON.stringify(i,null,2)}
60
- `),i.installed?0:1}if(o==="uninstall")return n(`${JSON.stringify(await No(t.unitIO??{}),null,2)}
61
- `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function Kc(e,t={}){let n=t.write??(l=>process.stdout.write(l)),r=t.warn??(l=>process.stderr.write(l)),o=ki(e),i=Xc(t.cwd??process.cwd()),s=Ri({configText:i.configText,project:i.name,flags:o.flags});for(let l of[...s.warnings,...o.warnings])r(`redskilled statusline: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
62
- `);let a=await ni(t.paths??Y(),s.options,{...s.options.project==null?{}:{sessionProject:s.options.project}});return n(`${a.lines.join(`
59
+ `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...n]}};function Ep(e,t={}){let n=t.env??process.env,r=t.exists??wp,o=t.execPath??process.execPath,s=t.callerEntry===void 0?process.argv[1]:t.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[ui(ht(n),i),"bundle-cache"]];s&&l.push([ui(_p(vp(s)),i),"caller-sibling-bundle"]);for(let[d,u]of l)if(a.push(d),r(d))return{command:o,args:[d],version:e,source:u,searched:a};if(n.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new Xn(e,a);return{command:n.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:a}}function wi(e,t={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let n=t.resolveEntry??(r=>Ep(r,t.env==null?{}:{env:t.env}));return{via:e.via,to:e.to,entry:n(e.to)}}function bi(e,t,n={}){let r=n.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??Pp)(pi),{...e,exitCode:pi};let o=[...e.entry.args,...pe(t,n.idleMs==null?{}:{idleMs:n.idleMs})];return(r.spawnSuccessor??jp(r.env))(e.entry,o),e}function jp(e){return(t,n)=>{let r=Rp(t.command,[...n],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1"}});r.on("error",()=>{}),r.unref()}}function Pp(e){process.exitCode=e,process.exit(e)}async function _i(e,t=process.env,n=Lp){let r=Op(t),o=Dp(e,t);if(t[xp]==="1")return{version:o,newest:r};let s=U(e)===null?"0.0.0":e;try{let i=await $o({fetchText:n},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function Op(e=process.env,t=Si){return xi(vi(e,t))}function Dp(e,t=process.env,n=Si){let r=U(e.trim())?.major;return r===void 0?null:xi(vi(t,n).filter(o=>U(o)?.major===r))}function vi(e,t){let n=[];for(let r of t(ht(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||U(o)===null||n.push(o)}return n}function xi(e){let t=null;for(let n of e)(t===null||Gn(n,t)>0)&&(t=n);return t}function Si(e){try{return bp(e)}catch{return[]}}async function Lp(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 $p,readFile as Ap,rename as Ip,rm as er,writeFile as Ei}from"node:fs/promises";import{randomUUID as Np}from"node:crypto";import{dirname as Tp}from"node:path";var Ot=class extends Error{constructor(t){super(`redskilled lease ${JSON.stringify(t)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function nr(e){let t;try{t=await Ap(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let n=Wp(t);return Mp(n)?n:void 0}var ji;function Oi(){return ji??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},ji}function Di(e,t,n={}){let r=n.clock??(()=>new Date().toISOString()),o=n.isPidAlive??T;async function s(){return await nr(e)}async function i(l){let d=`${e}.${l.pid}.${Np()}.tmp`;await Ei(d,Pi(l),{encoding:"utf8",mode:384}),await Ip(d,e)}function a(l,d){return{version:1,pid:l.pid,start_time:l.startTime,session_key_hash:t.sessionKeyHash,machine_id_hash:t.machineIdHash,socket_path:t.socketPath,acquired_at:d,renewed_at:d}}return{read:s,async acquire(l){await $p(Tp(e),{recursive:!0,mode:448});let d=!1;for(;;){let u=r(),f=a(l,u);try{return await Ei(e,Pi(f),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:f}}catch(h){if(h.code!=="EEXIST")throw h}let p=await s();if(!p){await er(e,{force:!0}),d=!0;continue}if(tr(p,l))return{acquired:!0,reaped:d,lease:p};if(await o(p.pid))return{acquired:!1,lease:p};await er(e,{force:!0}),d=!0}},async renew(l){let d=await s();if(!d||!tr(d,l))throw new Ot(e);let u={...d,renewed_at:r()};return await i(u),u},async release(l){let d=await s();if(!d)return!1;if(!tr(d,l))throw new Ot(e);return await er(e,{force:!0}),!0}}}function tr(e,t){return e.pid===t.pid&&e.start_time===t.startTime}function Pi(e){return`${A(e,{keyedMapCollapse:!0})}
60
+ `}function Wp(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{try{return K(t)}catch{return null}}}function Mp(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 rr=3e5,Kp=15e3,Oe=class extends Error{constructor(n,r){super(`a redskilled daemon already owns ${JSON.stringify(n)}`);this.socketPath=n;this.lease=r;this.name="RedskilledAlreadyRunningError"}};async function $i(e){let{paths:t}=e,n=e.daemonVersion??"0.0.0-dev",r=e.idleMs??rr,o=e.clock??(()=>new Date().toISOString()),s=e.launch??oi,i=e.ceiling??Fo();e.repositoryActivity!=null&&Mn(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??Oi(),l=e.leaseStore??Di(t.leasePath,{sessionKeyHash:t.sessionKeyHash,machineIdHash:t.machineIdHash,socketPath:t.socketPath},{clock:o}),d=e.machineOwner??ns(),u={machineIdHash:t.machineIdHash,sessionKeyHash:t.sessionKeyHash,socketPath:t.socketPath},f=e.machineClaimStore??bt(t.machineClaimPath,u,{clock:o});await Vp(Bp(t.socketPath),{recursive:!0,mode:448});let p=await f.claim(d);if(!p.claimed)throw p.claim?.socket_path===t.socketPath?new Oe(t.socketPath):new ie(f.claimPath,p.reason,p.claim);let h=await l.acquire(a);if(!h.acquired)throw await f.release(d).catch(()=>{}),new Oe(t.socketPath,h.lease);let y;try{y=await qp(t.socketPath)}catch(c){throw await l.release(a).catch(()=>{}),await f.release(d).catch(()=>{}),c}let R=o(),w=e.eventLane??Jo(t.eventLanePath),_=e.liveness??Us,P=e.stopWorker??qs,F=e.unitInventory??(()=>Vs(t.machineClaimPath,wt({machineIdHash:t.machineIdHash}))?Js():[]),M=e.unitMainPid??Hs,ae=e.treeSampler??ps,ge=e.readLogTail??si,tt=e.sampleMs??Kp,da=e.publishedVersion??(c=>_i(c)),pr=e.replaceCheckMs??mi,fr=e.supervised??Ri(),mr=e.replacementIO??{},H=e.repositoryActivity,gr=H?.intervalMs??6e4,nt=e.queueDiscovery,$t=nt?.transport??H?.transport,hr=nt?.intervalMs??15e3,yr=e.demandMs??15e3,ca=e.demandBackoffMs??3e4,S=new Map,ne=new Set,he=new Map,N=new Map,At=new Set,kr={},It=null,Rr=null,wr=null,br=!1,$e="none",Nt=null,_r=null,Tt=null,Ae=null,rt=null,Ie=null,Wt=!1,ye,Ne,Te,We,Me,Ce,re=!1,vr=!1,ot=null,xr,Mt=new Promise(c=>{xr=c});function Ue(c){let m=ls(N.values(),c);for(let g of m.lapsed)N.delete(g.project_label);return m.lapsed}function st(){let c=o();return Ue(Date.parse(c)),_s({now:c,daemonVersion:n,machineIdHash:t.machineIdHash,sessionKeyHash:t.sessionKeyHash,pid:a.pid,startedAt:R,scope:rs(f.claimPath,u,d),workers:[...S.values()],registrations:[...N.values()],queue:Ae,published:{version:Rr,checkedAt:wr,newer:br,replacement:$e,newest:Nt,majorHold:_r}})}function Ct(){return ws({hostState:st(),ceiling:i,rss:kr,sampledAt:It,logLines:Object.fromEntries(he),now:o(),reattachedWorkerIds:[...ne],repositoryActivity:Tt})}async function Ut(){return H==null||H.projects.length===0?null:(Tt=await gs({projects:H.projects,hostTokenRef:H.hostTokenRef,transport:H.transport,closedWindowMs:H.closedWindowMs,now:o()}),Tt)}async function Sr(){if($t==null)return null;let c=o();Ue(Date.parse(c));let m=[...N.values()].map(g=>({project_label:g.project_label,selector:g.selector})).sort((g,b)=>g.project_label.localeCompare(b.project_label));return m.length===0?null:(Ae=await zs({projects:m,transport:$t,now:c,...nt?.batchSize==null?{}:{batchSize:nt.batchSize}}),Ae)}async function Er(){let c=o();if(Wt)return rt??qo(c);Wt=!0;try{let m={};for(let L of S.values())m[L.project_label]=(m[L.project_label]??0)+1;let g={};for(let L of Ae?.projects??[])g[L.project_label]=L.depth;let b=Date.parse(c),j=Ko({projects:[...N.values()].map(L=>({project_label:L.project_label,selector:L.selector,argv:L.argv,workspace_path:L.workspace_path,target:L.target})),queue:g,live:m,nowMs:Number.isFinite(b)?b:0,backoffUntilMs:Ie}),O=[],Vt=null;for(let L of j.births){let dt;try{dt=Ft({project_label:L.project_label,workspace_path:L.workspace_path,command:L.argv[0],args:L.argv.slice(1)})}catch(Jt){Vt=Jt instanceof Error?Jt.message:String(Jt),Ie=(Number.isFinite(b)?b:Date.now())+ca;break}O.push({project_label:L.project_label,worker_id:dt.worker.worker_id,pid:dt.worker.pid,warnings:dt.warnings})}return Vt==null&&j.births.length>0&&(Ie=null),rt={version:1,at:c,requested:j.births.length,granted:O,shortfall:j.births.length-O.length,refusal:Vt,retry_after:Ie==null?null:new Date(Ie).toISOString(),projects:j.intents},rt}finally{Wt=!1}}function ua(c){return Xs(Ct(),{...D,mode:c?.mode??D.mode,project:c?.project??D.project,maxWorkers:c?.max_workers??D.maxWorkers,maxProjects:c?.max_projects??D.maxProjects,maxWidth:c?.max_width??D.maxWidth,verbose:c?.verbose??D.verbose})}function ke(c,m,g){return cs({op:c,sessionProject:m??null,targetProject:g})}async function pa(c){let m=S.get(c.worker_id),g=ke(ds(c.command),c.session_project,m?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(c.command!=="stop")throw new Error(`redskilled does not implement ${c.command}: it owns birth, death and limits, and ${c.command} is a work decision the project's own bundle makes on top of them`);let b=m!=null&&await ha(m,c.detail??"stopped by its own project");return{version:1,command:c.command,worker_id:c.worker_id,applied:b,reach:g,detail:b?`redskilled stopped Worker ${JSON.stringify(c.worker_id)} of project ${JSON.stringify(m.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function it(c){S.delete(c),ne.delete(c),he.delete(c)}function jr(c){let m=S.get(c.worker_id),g=ke("worker-heartbeat",c.session_project,m?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(typeof c.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(m==null)return{version:1,worker_id:c.worker_id,accepted:!1,reach:g,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to publish a line for`};let b=o();return he.set(c.worker_id,{line:c.last_log_line,published_at:b,source:"heartbeat"}),{version:1,worker_id:c.worker_id,accepted:!0,reach:g,published_at:b,detail:`redskilled stored a line for Worker ${JSON.stringify(c.worker_id)} without reading it`}}async function fa(c,m,g){let b=`exit code=${m??"null"} signal=${g??"null"}`;if(c.unit!=null&&c.unit!==""&&await ma(c)){ga(c,`its launch client ended (${b}) while unit ${JSON.stringify(c.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}it(c.worker_id),Q("worker-death",c,b,{exitCode:m,signal:g}),$()}async function ma(c){try{return await _(c)===!0}catch{return!1}}function ga(c,m){let g=c.unit==null?null:M(c.unit);S.set(c.worker_id,{...c,...g!=null&&g>0?{pid:g}:{},warnings:[...c.warnings,m]}),ne.add(c.worker_id),$()}function Pr(c,m){let g=ke("project-register",m,c.project_label);if(!g.permitted)throw new Error(g.reason);let b=o();Ue(Date.parse(b));let j=ss(c,{now:b,held:N.get(c.project_label)});return N.set(j.project_label,j),$(),{version:1,registration:j,reach:g,detail:`redskilled holds a registration for project ${JSON.stringify(j.project_label)} at a target of ${j.target} until ${j.renew_by}, and has read neither its selector nor its argv`}}function Or(c,m={}){let g=ke("project-renew",m.sessionProject,c);if(!g.permitted)throw new Error(g.reason);let b=o();Ue(Date.parse(b));let j=N.get(c);if(j==null)throw new _t(c);let O=is(j,{now:b,...m.renewWithinMs==null?{}:{renew_within_ms:m.renewWithinMs},...m.launch==null?{}:{launch:m.launch}});return N.set(O.project_label,O),$(),{version:1,registration:O,reach:g,detail:`redskilled renewed the registration for project ${JSON.stringify(O.project_label)}, which now stands until ${O.renew_by} after renewal ${O.renewals}`+(m.launch==null?"":`, carrying launch revision ${O.launch_revision} for its next Worker`)}}function Dr(c,m){let g=ke("project-deregister",m,c);if(!g.permitted)throw new Error(g.reason);let b=N.delete(c);return{version:1,project_label:c,released:b,reach:g,detail:b?`redskilled released the registration for project ${JSON.stringify(c)}`:`redskilled held no registration for project ${JSON.stringify(c)}, so there was nothing to release`}}async function ha(c,m){try{await P(c)}catch{}return it(c.worker_id),Q("worker-death",c,m),$(),!0}function Lr(c){return Uo({ceiling:i,workers:[...S.values()],budget:c.budget,projectLabel:c.project_label})}function Ft(c){let m=s({spec:c,admission:Lr(c),clock:o,onExit:(g,b,j)=>{let O=S.get(g);if(O==null){$();return}fa(O,b,j).catch(()=>{})}});return S.set(m.worker.worker_id,m.worker),Q("worker-birth",m.worker,null),$(),m}function Q(c,m,g,b={}){re||w.record({event:c,worker:m,ts:o(),detail:g,...b.exitCode!==void 0?{exitCode:b.exitCode}:{},...b.signal!==void 0?{signal:b.signal}:{}}).catch(()=>{})}async function $r(){let c=[...ne].map(g=>S.get(g)).filter(g=>g!=null);if(c.length===0)return[];let{dead:m}=await Bn(c,_);for(let g of m)it(g.worker_id),Q("worker-death",g,"the host no longer confirms this Worker");return m.length>0&&$(),m}async function Ar(c,m){let g=S.get(c);if(!g)return!1;try{await P(g)}catch{}return it(c),Q("worker-budget-kill",g,m),$(),!0}async function Ir(){let c=[...S.values()];if(c.length===0)return[];let m;try{m=await ae(c)}catch{return[]}let g=m.rss;kr=g,It=o(),ya(m.cpu_seconds,It);let{terminations:b}=us({workers:c,rss:g}),j=[];for(let O of b)await Ar(O.worker_id,O.reason)&&j.push(O);return j}function ya(c,m){for(let[g,b]of Object.entries(c)){if(typeof b!="number"||!Number.isFinite(b))continue;let j=S.get(g);j&&S.set(g,{...j,cpu:{cpu_seconds:b,sampled_at:m}})}}async function Nr(){let c;try{c=gi(await da(n))}catch{c={version:null,newest:null}}let m=c.version;Rr=m,Nt=c.newest??null,wr=o(),_r=hi({running:n,newest:Nt,supervised:fr});let g=yi({running:n,published:m,supervised:fr});return br=g.act==="replace",$e!=="in-progress"&&($e=g.act==="replace"?"pending":"none"),g}async function Tr(){let c=await Nr();if(c.act!=="replace"||$e==="in-progress")return c;let m=wi(c,mr);return $e="in-progress",await w.flush().catch(()=>{}),await lt({reason:"replaced"}),bi(m,t,{...r==null?{}:{idleMs:r},io:mr}),c}function ka(){re||We!=null||pr<=0||(We=setInterval(()=>{Tr().catch(()=>{})},pr),We.unref())}function Ra(){re||Ne!=null||tt<=0||(Ne=setInterval(()=>{Ir().catch(()=>{})},tt),Ne.unref())}function wa(){re||Me!=null||H==null||H.projects.length===0||gr<=0||(Ut().catch(()=>{}),Me=setInterval(()=>{Ut().catch(()=>{})},gr),Me.unref())}function ba(){re||Ce!=null||$t==null||hr<=0||(Ce=setInterval(()=>{Sr().catch(()=>{})},hr),Ce.unref())}function _a(){re||Te!=null||yr<=0||(Te=setInterval(()=>{Er().catch(()=>{})},yr),Te.unref())}function $(){re||(ye&&clearTimeout(ye),ye=setTimeout(()=>{$r().catch(()=>{}).then(()=>Wr())},r),ye.unref())}function Wr(){return S.size>0?($(),"held-by-workers"):(Ue(Date.parse(o())),N.size>0?($(),"held-by-registrations"):(lt({reason:"idle"}),"exited"))}function at(c){return zo({reason:c,socketPath:t.socketPath,daemonVersion:n,pid:a.pid,workers:[...S.values()],projects:[...N.keys()]})}function Mr(c){if(ot!=null)return ot;let m=c.reason??"requested",g=c.note?.trim();return ot=w.recordDaemonStop({ts:o(),pid:a.pid,socketPath:t.socketPath,reason:m,detail:g==null||g===""?at(m).detail:`${at(m).detail} \u2014 ${g}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),ot}async function lt(c={}){if(vr)return await Mt;vr=!0,await Mr(c),re=!0,ye&&clearTimeout(ye),Ne&&clearInterval(Ne),We&&clearInterval(We),Me&&clearInterval(Me),Ce&&clearInterval(Ce),Te&&clearInterval(Te),await w.flush().catch(()=>{}),y.close();for(let m of At)m.destroy();return await new Promise(m=>y.once("close",()=>m())),await Li(t.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await f.release(d).catch(()=>{}),xr(),await Mt}let va=Bo(await w.read().catch(()=>[])),Ht=await Bn(va,_);for(let c of Ht.alive){let m=Ks(c),g=m.unit==null||T(m.pid)?null:M(m.unit);S.set(m.worker_id,g!=null&&g>0?{...m,pid:g}:m),ne.add(m.worker_id)}for(let c of Ht.dead)Q("worker-death",c,"the Worker ended while no daemon was watching");let xa=Bs({units:await Promise.resolve(F()).catch(()=>[]),held:[...S.values()],mainPid:M,now:R});for(let c of xa)S.set(c.worker_id,c),ne.add(c.worker_id),Q("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of Ht.alive){if(c.log_path==null||he.has(c.worker_id))continue;let m=await ge(c.log_path).catch(()=>null);m==null||m.trim()===""||he.set(c.worker_id,{line:m,published_at:o(),source:"rehydrated"})}y.on("connection",c=>{At.add(c),c.once("close",()=>At.delete(c)),$(),Gp(c,async(m,g)=>{$();let b=await Sa(m);g(b),m.op==="shutdown"&&setImmediate(()=>void lt({reason:"requested"}))})});async function Sa(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:vt,daemon_version:n,pid:a.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:st()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:Ct()};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:ua(c.render)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:jr(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:Pr(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:Or(c.project_label,{...c.session_project==null?{}:{sessionProject:c.session_project},...c.renew_within_ms==null?{}:{renewWithinMs:c.renew_within_ms},...c.launch==null?{}:{launch:c.launch}})};if(c.op==="project-deregister")return{id:c.id,ok:!0,value:Dr(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await pa(c.command)};if(c.op==="worker-start"){let g=ke("worker-start",c.session_project,c.spec.project_label);if(!g.permitted)return{id:c.id,ok:!1,error:g.reason};let b=Ft(c.spec);return await w.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:b.worker,admission:b.admission,warnings:b.warnings}}}if(c.op==="shutdown"){let g=at("requested");return await Mr({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:g}}let m=c;return{id:m.id??Dt(),ok:!1,error:`unsupported redskilled op: ${m.op??"unknown"}`}}catch(m){return{id:c.id??Dt(),ok:!1,error:m instanceof Error?m.message:String(m)}}}return $(),Ra(),ka(),wa(),ba(),_a(),{socketPath:t.socketPath,lease:h.lease,startedAt:R,closed:Mt,startWorker:Ft,admit:Lr,ceiling:()=>i,killWorkerOverBudget:Ar,sampleMemoryBudgets:Ir,pollRepositoryActivity:Ut,pollQueueDiscovery:Sr,queueDiscovery:()=>Ae,driveDemand:Er,demand:()=>rt,sweepReattached:$r,publishWorkerHeartbeat:jr,reattached:()=>[...ne].map(c=>S.get(c)).filter(c=>c!=null),flushEvents:()=>w.flush(),trackWorker(c){S.set(c.worker_id,c),Q("worker-birth",c,null),$()},releaseWorker(c){let m=S.get(c),g=S.delete(c);return ne.delete(c),he.delete(c),m&&Q("worker-death",m,"released by the daemon"),$(),g},workerCount:()=>S.size,registerProject:Pr,renewProject:Or,deregisterProject:Dr,registrations:()=>st().registrations??[],hostState:st,statuslinePayload:Ct,evaluateIdle:Wr,observePublishedVersion:Nr,checkForReplacement:Tr,stopReport:at,stop:lt}}async function qp(e){for(let t=0;t<2;t++){let n=Jp();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 ee(e))throw new Oe(e);await Li(e,{force:!0})}}throw new Oe(e)}async function ee(e,t=250){try{return(await ft({socketPath:e,timeoutMs:t},{id:Dt(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function Gp(e,t){jo(e,(n,r)=>t(n,r),(n,r,o)=>{o({id:r?.id??Dt(),ok:!1,error:n instanceof Error?n.message:String(n)})})}Z();var Xp=1e4,De=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 or(e,t={}){try{return await ef(e,t)}catch(n){throw n instanceof ie||n instanceof De?n:new De(e.socketPath,n)}}async function ef(e,t){if(await Qp(Zp(e.socketPath),{recursive:!0,mode:448}),await ee(e.socketPath))return"already-running";await tf(e);let n=await Po(e.lockPath);if(!n)return await Ai(e,t),"joined";try{if(await ee(e.socketPath))return"already-running";let r=await of(e,t);return await Ai(e,t,r),"spawned"}finally{await n.close(),await Yp(e.lockPath,{force:!0})}}async function tf(e){let n=await bt(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(n!=null&&n.socket_path!==e.socketPath&&T(n.pid))throw new ie(e.machineClaimPath,"held",n)}async function Ni(e,t,n={}){await or(e,n);let r;try{r=await Qe({socketPath:e.socketPath,timeoutMs:n.requestTimeoutMs??2e3},{...t,id:Ii()})}catch(o){throw new De(e.socketPath,o)}if(!r.ok)throw new Error(r.error);return r.value}async function Ti(e,t={},n={}){if(!await ee(e.socketPath))return Qo(e.socketPath);let r;try{r=await Qe({socketPath:e.socketPath,timeoutMs:n.requestTimeoutMs??2e3},{id:Ii(),op:"shutdown",...t.detail==null?{}:{detail:t.detail}})}catch(i){throw new De(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!On(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await nf(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 nf(e,t){let n=Date.now()+t;for(;;){if(!await ee(e))return!0;if(Date.now()>=n)return!1;await new Promise(r=>setTimeout(r,25))}}async function Wi(e,t={}){let n=await Ni(e,{op:"host-state"},t);if(!vs(n))throw new Error("redskilled daemon returned a malformed host state");return n}async function Mi(e,t=void 0,n={}){let r=await Ni(e,{op:"statusline-string",...n.sessionProject!=null?{session_project:n.sessionProject}:{},...t==null?{}:{render:rf(t)}},n);if(!bs(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function rf(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 Ai(e,t,n){let r=Date.now()+(t.readyTimeoutMs??Xp);for(;;){if(await ee(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 of(e,t){let n=t.serverCommand??(t.serverArgs!=null?process.execPath:void 0),r=await To({...n!=null?{serverCommand:n}:{},serverArgs:t.serverArgs},t.entryLookup??{}),o={entry:r},s=[...r.args,...pe(e,t.idleMs==null?{}:{idleMs:t.idleMs})],i=zp(r.command,s,{detached:!0,stdio:"ignore",env:{...t.env??process.env,REDSKILLED_DAEMON:"1"}});return i.on("error",a=>{o.failure=a}),i.on("exit",(a,l)=>{o.exit=l?`died on ${l}`:`exited with code ${a??-1}`}),i.unref(),o}Z();import{chmod as Bi,mkdir as qi,readFile as Gi,stat as kf,writeFile as Rf}from"node:fs/promises";import{homedir as ar}from"node:os";import{dirname as wf,join as lr}from"node:path";import{join as sf}from"node:path";var af=[".red","redskilled"],z=448;function Xe(e){return sf(e,...af)}import{join as lf}from"node:path";var Ci=["local","tmp","host"],df="local",et="plugins.dev.workspace.target";var sr=class extends Error{constructor(t){super(t),this.name="WorkspaceConfigError"}};function Fi(e){let t=ve(e,et),n=pf(t??"").trim();return n===""?void 0:n}function Hi(e){let t=(e??"").trim();if(t==="")return{kind:"preset",preset:df};let n=Ci.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 sr(`${et}: unknown workspace target ${JSON.stringify(t)}. Use one of the presets (${Ci.join(", ")}) or an absolute parent directory for Workers.`)}function Vi(e,t){return e.kind==="preset"?e.preset==="host":uf(cf(e.parentDir,t),Xe(t))}function cf(e,t){return e==="~"?Ui(t):e.startsWith("~/")?lf(t,e.slice(2)):Ui(e)}function uf(e,t){return e===t?!0:t==="/"?e.startsWith("/"):e.startsWith(`${t}/`)}function Ui(e){let t=e.trim();return t.length>1?t.replace(/\/+$/,""):t}function pf(e){let t=e.trim(),n=/^(["'])(.*)\1$/.exec(t);return n?n[2]:t}Z();import{createHash as ff}from"node:crypto";import{hostname as mf}from"node:os";import{join as Lt}from"node:path";var Le="redskilled.sock",gf="REDSKILLED_SESSION";function hf(e={}){let t=e.env??process.env,n=t[gf]?.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 yf(e={}){return Ji(e.host??mf())}function te(e={}){let t=hf(e),n=e.runtimeDir??mt({key:`redskilled:${t}`,socketFileName:Le,env:e.env,uid:e.uid}),r=yf(e);return{sessionKey:t,sessionKeyHash:Ji(t),machineIdHash:r,runtimeDir:n,socketPath:Lt(n,Le),lockPath:Lt(n,"redskilled.spawn.lock"),leasePath:Lt(n,"redskilled.lease.toon"),eventLanePath:Lt(n,Vo),machineClaimPath:e.machineClaimPath??wt({env:e.env,machineIdHash:r,platform:e.platform})}}function Ji(e){return ff("sha256").update(e).digest("hex").slice(0,12)}var ir="run `/red-setup` (Section E3 \u2014 execution daemon), or `redskilled provision` directly";async function zi(e=ar()){let t=Xe(e),n=await cr(t);return n===void 0?(await qi(t,{recursive:!0,mode:z}),await Bi(t,z),{path:t,created:!0,tightened:!1,mode:z}):n===z?{path:t,created:!1,tightened:!1,mode:n}:(await Bi(t,z),{path:t,created:!1,tightened:!0,mode:z})}var Qi={needed:!1,declaredBy:`no ${et} in view`};async function dr(e={}){let t=e.homeDir??ar(),n=e.declaredTarget?.trim();if(n)return Ki(n,t,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return Qi;let o=lr(r,".red","config.yaml"),s=await Gi(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=Fi(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Ki(i,t,o)}function Ki(e,t,n){let r=`${et}: ${e} (${n})`;try{return{needed:Vi(Hi(e),t),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function Yi(e){let t=[bf(e),_f(e),vf(e),xf(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 bf(e){let t=e.homeNeed??Qi;if(!e.homePresent)return t.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${t.declaredBy}`,fix:ir}:{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:`${ir} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${n.toString(8)})`,fix:""}}function _f(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 vf(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:`${ir} \u2014 it starts the daemon and waits for the socket`}}function xf(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 Zi(e={}){let t=e.env??process.env,n=e.homeDir??ar(),r=e.paths??te({env:t}),o=Xe(n),[s,i,a]=await Promise.all([cr(o),ee(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):dr({homeDir:n,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:a,entry:se(e.entryOverride??{},{env:t,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await Ef(jf(e,t,n),t)}}var Sf="redskilled.service";function Xi(e){return lr(e,"systemd","user",Sf)}function ea(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 ta(e){let t=Xi(e.configHome);return await cr(t)!==void 0?{path:t,status:"already-present"}:(await qi(wf(t),{recursive:!0}),await Rf(t,e.unit,"utf8"),{path:t,status:"installed"})}async function Ef(e,t){if(process.platform!=="linux")return"unsupported";try{return await Gi(Xi(e),"utf8"),"installed"}catch{return t.XDG_RUNTIME_DIR?"absent":"unsupported"}}function jf(e,t,n){return e.configHome??t.XDG_CONFIG_HOME?.trim()??lr(n,".config")}async function cr(e){try{return(await kf(e)).mode&511}catch{return}}import{readdir as ra,rm as Pf,stat as Of}from"node:fs/promises";import{dirname as Df,join as ur}from"node:path";var Lf=5*6e4,$f="redskilled.";function Af(e={}){let t=e.env??process.env,n=i=>Df(mt({key:"redskilled:reclaim-probe",socketFileName:Le,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 oa(e={}){let t=e.roots??Af(e),n=e.graceMs??Lf,r=e.now??Date.now,o=e.isPidAlive??T,s=e.answers??Wf,i=e.dryRun===!0,a=[];for(let l of t){let d;try{d=(await ra(l,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name)}catch{continue}for(let u of d.sort())a.push(await If(ur(l,u),{graceMs:n,now:r,pidAlive:o,answers:s,dryRun:i}))}return{roots:t,scanned:a.length,reclaimed:a.filter(l=>l.verdict==="reclaimed").length,dryRun:i,entries:a}}async function If(e,t){let n;try{n=(await ra(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:sa(i),removed:[]}}let r=n.filter(i=>i.startsWith($f));if(n.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await Nf(ur(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 na(e,n,`lease pid ${o.pid} is dead`,t);if(n.includes(Le)&&await t.answers(ur(e,Le)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await Tf(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 na(e,n,n.length===0?"empty and stale":"no lease and stale",t)}async function na(e,t,n,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${n} (dry run)`,removed:t};try{await Pf(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:sa(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:n,removed:t}}async function Nf(e){try{return await nr(e)}catch{return}}async function Tf(e,t){try{return Math.max(0,t()-(await Of(e)).mtimeMs)}catch{return}}async function Wf(e){try{return(await Qe({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function sa(e){return e instanceof Error?e.message:String(e)}var Mf="plugins.dev.statusline",Cf="dev.statusline";function Uf(e){let t=[],n=a=>{for(let l of[Mf,Cf]){let d=`${l}.${a}`,u=ve(e,d)?.trim();if(u!=null&&u!=="")return{key:d,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:a=>{o.maxWorkers=a}},{leaf:"max_projects",assign:a=>{o.maxProjects=a}},{leaf:"max_width",assign:a=>{o.maxWidth=a}}];for(let a of s){let l=n(a.leaf);if(l==null)continue;let d=Number(l.value);Number.isInteger(d)&&d>=0?a.assign(d):t.push({...l,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 Ff={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 ia(e){let{values:t,positionals:n}=ue(e,Ff),r=[],o={},s=t.mode??n.find(a=>a==="global"||a==="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:a=>{o.maxWorkers=a}},{flag:"max-projects",assign:a=>{o.maxProjects=a}},{flag:"max-width",assign:a=>{o.maxWidth=a}}];for(let a of i){let l=t[a.flag];if(l==null)continue;let d=Number(l);Number.isInteger(d)&&d>=0?a.assign(d):r.push({key:`--${a.flag}`,value:l,reason:"expected a whole number of zero or more"})}return{flags:o,warnings:r}}function aa(e={}){let t=e.configText==null?{config:{},warnings:[]}:Uf(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 Vf=`Usage: redskilled <command> [options]
62
+
63
+ Commands:
64
+ host-state (default) print the host's state as JSON
65
+ serve run the daemon in this process
66
+ statusline [global] render one agent-host status line
67
+ unit install | uninstall | status \u2014 the optional supervisor
68
+ provision make this machine ready; --check is the read-only half
69
+ reclaim clear runtime dirs left by dead sessions
70
+
71
+ Run \`redskilled <command> --help\` for a command's own usage.
72
+ \`--version\` (\`-v\`) prints the build stamp; both answer offline.
73
+ `,Jf={serve:`Usage: redskilled serve [options]
74
+
75
+ Runs the daemon in this process. Every path is a flag and none is derived
76
+ (ADR 0130 rule 3); what is absent falls back to the session derivation.
77
+
78
+ --socket <path> the unix socket to listen on
79
+ --lease <path> the singleton lease record
80
+ --events <path> the append-only host event lane
81
+ --session-key-hash <hex> publishable session identity
82
+ --machine-id-hash <hex> publishable host label
83
+ --machine-claim <path> the machine-wide claim record
84
+ --idle-ms <n> exit after this long with no work
85
+ --daemon-version <v> the version this daemon reports as
86
+ --queue-endpoint <url> where the queue poll asks; GitHub's when absent
87
+ --queue-ms <n> window between queue polls
88
+ --demand-ms <n> window between demand ticks
89
+
90
+ The poller is armed by a token in REDSKILLED_HOST_TOKEN (GITHUB_TOKEN or
91
+ GH_TOKEN when it is unset). With none, the daemon holds registrations and counts
92
+ no queue \u2014 an honest unknown, never a drained one.
93
+ `,"host-state":`Usage: redskilled host-state
94
+
95
+ Prints the host's state as JSON. Contacts the running daemon; the default
96
+ command when none is named.
97
+ `,statusline:`Usage: redskilled statusline [global] [--verbose] [flags]
98
+
99
+ Renders the status line the agent host prints verbatim. Config is read on this
100
+ side and only decided values cross the socket (ADR 0130 rule 10).
101
+
102
+ global render the host-wide line instead of this project's
103
+ --verbose add one line per Worker
104
+ `,unit:`Usage: redskilled unit [install|uninstall|status]
105
+
106
+ Manages the OPTIONAL user supervisor unit \u2014 auto-spawn is the floor, and a host
107
+ with no unit is a supported configuration (ADR 0130 rule 7). Defaults to status.
108
+ `,provision:`Usage: redskilled provision [--check] [--no-start] [--install-unit]
109
+ [--workspace <target>] [--project <dir>]
110
+
111
+ Makes a machine with no prior state ready, and prints the audit. Idempotent: a
112
+ second run creates nothing and reports the same verdicts.
113
+
114
+ The host-scoped home is created only when a declared workspace target reads it
115
+ (the \`host\` preset, or a custom parent under the home). The daemon never reads
116
+ the home, so the default \`local\` preset needs none \u2014 and never gets an empty one.
117
+
118
+ --check read-only; creates and starts nothing
119
+ --no-start make the host ready without starting the daemon
120
+ --install-unit also install the user supervisor unit
121
+ --workspace <t> state the workspace target outright, instead of reading a config
122
+ --project <dir> the repository whose config declares the target (default: cwd)
123
+ `,stop:`Usage: redskilled stop [--detail <why>]
124
+
125
+ Asks the daemon to shut down and reports what it was holding. Every Worker
126
+ survives: they are init-system units, so a stop is a restart and not an
127
+ evacuation. A socket nobody answers on is a success with a stated reason.
128
+
129
+ --detail <why> the operator's own words, recorded on the event lane so a
130
+ successor can tell a planned handover from a crash
131
+ `,reclaim:`Usage: redskilled reclaim [--dry-run] [--grace-ms <n>]
132
+
133
+ Reports every session runtime dir it looked at and why it kept or removed it.
134
+
135
+ --dry-run the same report with nothing removed
136
+ --grace-ms <n> how long a dir must be idle before it is reclaimed
137
+ `};function Bf(e){return e==="--help"||e==="-h"||e==="help"}var Kf={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)}},qf="REDSKILLED_HOST_TOKEN";function Gf(e,t=process.env){let n=(t[qf]??t.GITHUB_TOKEN??t.GH_TOKEN??"").trim();if(n==="")return;let r=e["queue-endpoint"]??t.GITHUB_GRAPHQL_URL;return{transport:ys({token:n,...r?{endpoint:r}:{}}),...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]}}}async function zf(e){if(e[0]==="--version"||e[0]==="-v"){let o=an("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
138
+ `:`${io(o)}
139
+ `),0}if(Bf(e[0]))return process.stdout.write(Vf),0;let{command:t,args:n}=uo(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(Jf[t]),0;if(t==="serve"){let{values:o}=ue(n,Kf),s=Gf(o),i=await $i({paths:im(o),idleMs:o["idle-ms"]??rr,daemonVersion:o["daemon-version"]??an("redskilled").version,...s==null?{}:{queueDiscovery:s},...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let a of["SIGTERM","SIGINT"])process.once(a,()=>void i.stop({reason:"signal",signal:a}).catch(()=>{}));return await i.closed,0}if(t==="stop")return await Yf(n);if(t==="statusline")return await Xf(n);if(t==="unit")return await Zf(n);if(t==="provision")return await tm(n);if(t==="reclaim")return await rm(n);let r=await Wi(te());return process.stdout.write(`${JSON.stringify(r,null,2)}
140
+ `),0}var Qf={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function Yf(e,t={}){let n=t.write??(s=>process.stdout.write(s)),{values:r}=ue(e,Qf),o=await Ti(t.paths??te(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},t.client??{});return n(`${A({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 Zf(e,t={}){let n=t.write??(s=>process.stdout.write(s)),r=t.paths??te(),o=e[0]??"status";if(o==="status")return n(`${JSON.stringify(ci(t.unitIO??{}),null,2)}
142
+ `),0;if(o==="install"){let s=await li(ii(r),t.unitIO??{});return n(`${JSON.stringify(s,null,2)}
143
+ `),s.installed?0:1}if(o==="uninstall")return n(`${JSON.stringify(await di(t.unitIO??{}),null,2)}
144
+ `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function Xf(e,t={}){let n=t.write??(l=>process.stdout.write(l)),r=t.warn??(l=>process.stderr.write(l)),o=ia(e),s=sm(t.cwd??process.cwd()),i=aa({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let l of[...i.warnings,...o.warnings])r(`redskilled statusline: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
145
+ `);let a;try{a=await Mi(t.paths??te(),i.options,{...t.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(l){r(`redskilled statusline: ${l instanceof Error?l.message:String(l)}
146
+ `),a=ei({options:i.options,generated_at:(t.now??(()=>new Date().toISOString()))()})}return n(`${a.lines.join(`
63
147
  `)}
64
- `),0}var qc={"no-start":{kind:"boolean"},"install-unit":{kind:"boolean"},check:{kind:"boolean"}};async function zc(e,t={}){let n=t.write??(c=>process.stdout.write(c)),{values:r}=ye(e,qc),o=t.paths??Y(),i=r.check?void 0:await li(t.homeDir??bi()),s;if(!r.check&&!r["no-start"])try{await hn(o,t.client??{})}catch(c){s=c instanceof Error?c.message:String(c)}let a=await ci({paths:o,...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}}}),l=r["install-unit"]&&he(a.entry)?await pi({configHome:t.configHome??Zc(),unit:fi({command:[a.entry.command,...a.entry.args].join(" "),socketPath:o.socketPath})}):void 0,d=di(a);return n(`${L({verdict:d.verdict,home:i==null?{path:a.homePath,created:!1,tightened:!1}:{path:i.path,created:i.created,tightened:i.tightened},socket:a.socketPath,...s==null?{}:{start_error:s},...l==null?{}:{unit:{path:l.path,status:l.status}},checks:d.rows.map(c=>({check:c.check,verdict:c.verdict,evidence:c.evidence})),fixes:d.findings.map(c=>({check:c.check,fix:c.fix}))})}
65
- `),d.verdict==="ok"?0:1}var Gc={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function Yc(e,t={}){let n=t.write??(i=>process.stdout.write(i)),{values:r}=ye(e,Gc),o=await hi({...t.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return n(`${L({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(i=>({dir:i.dir,verdict:i.verdict,reason:i.reason,removed:[...i.removed]}))})}
66
- `),o.entries.some(i=>i.verdict==="failed")?1:0}function Zc(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:Vc(bi(),".config")}function Xc(e){let t=ur(e,".red/config.yaml");if(t==null)return{name:null};let n;try{n=Fc(t,"utf8")}catch{return{name:null}}return{configText:n,name:fr(n)??null}}function Qc(e){let t=Y();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 eu=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;eu&&Jc(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
67
- `),process.exitCode=1});export{zc as runProvision,Yc as runReclaim,Jc as runRedskilledCli,Kc as runStatusline,Bc as runUnit};
148
+ `),0}var em={"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 tm(e,t={}){let n=t.write??(p=>process.stdout.write(p)),{values:r}=ue(e,em),o=t.paths??te(),s=t.homeDir??la(),i=await dr({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??t.projectRoot??process.cwd()}),a=r.check||!i.needed?void 0:await zi(s),l;if(!r.check&&!r["no-start"])try{await or(o,t.client??{})}catch(p){l=p instanceof Error?p.message:String(p)}let d=await Zi({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(d.entry)?await ta({configHome:t.configHome??om(),unit:ea({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,f=Yi(d);return n(`${A({verdict:f.verdict,home:{path:a?.path??d.homePath,created:a?.created??!1,tightened:a?.tightened??!1,needed:i.needed,needed_by:i.declaredBy},socket:d.socketPath,...l==null?{}:{start_error:l},...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 nm={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function rm(e,t={}){let n=t.write??(s=>process.stdout.write(s)),{values:r}=ue(e,nm),o=await oa({...t.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return n(`${A({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 om(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:Hf(la(),".config")}function sm(e){let t=fn(e);return t.configText==null?{label:null}:{configText:t.configText,label:ko(e)}}function im(e){let t=te();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 am=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;am&&zf(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{qf as REDSKILLED_HOST_TOKEN_ENV,Vf as REDSKILLED_USAGE,Gf as resolveServeQueueDiscovery,tm as runProvision,rm as runReclaim,zf as runRedskilledCli,Xf as runStatusline,Yf as runStop,Zf as runUnit};