@reddb-io/red-skills 3.3.3 → 3.3.6
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.
- package/dist/brain.bundle.min.mjs +1 -1
- package/dist/castle-mcp.bundle.min.mjs +349 -349
- package/dist/code-nav.bundle.min.mjs +1 -1
- package/dist/dev.bundle.min.mjs +583 -582
- package/dist/memory.bundle.min.mjs +1 -1
- package/dist/redskilled.bundle.min.mjs +61 -61
- package/dist/rsp.bundle.min.mjs +1 -1
- package/package.json +1 -1
|
@@ -1,72 +1,72 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
3
|
-
var
|
|
3
|
+
var td=Object.defineProperty;var rd=(e,n)=>()=>(e&&(n=e(e=0)),n);var od=(e,n)=>{for(var t in n)td(e,t,{get:n[t],enumerable:!0})};var Bs={};od(Bs,{REDSKILLED_BIN_ENV:()=>ir,REDSKILLED_BUNDLE_ASSET:()=>Q,REDSKILLED_ENTRY_UNRESOLVED:()=>ln,RedskilledDaemonEntryError:()=>an,isRedskilledEntryPath:()=>ar,isResolvedRedskilledEntry:()=>Y,redskilledBundleCacheRoot:()=>Fn,redskilledServeArgv:()=>be,requireRedskilledEntry:()=>Hn,resolveRedskilledEntry:()=>ue});import{existsSync as Ou,readdirSync as $u}from"node:fs";import{homedir as Au}from"node:os";import{basename as sr,dirname as or,join as C,resolve as Mn}from"node:path";function Y(e){return"command"in e}function be(e,n={}){let t=["serve","--socket",e.socketPath,"--lease",e.leasePath,"--events",e.eventLanePath,"--session-key-hash",e.sessionKeyHash,"--machine-id-hash",e.machineIdHash,"--machine-claim",e.machineClaimPath];return n.idleMs!=null&&t.push("--idle-ms",String(n.idleMs)),n.daemonVersion!=null&&t.push("--daemon-version",n.daemonVersion),t}function Fn(e=process.env){return Us(e)}function ue(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??Ou,o=n.execPath??process.execPath,s=n.execArgv??[],i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,l=(u,p)=>({command:o,args:[...s,u],source:p,entry:u}),a=t[ir];if(a)return{command:a,args:[],source:"env-redskilled-bin",entry:a};if(i&&ar(i))return l(Mn(i),"caller-entry");let c=[];for(let[u,p]of Nu(i,n.rootDir,t,n.listDir??Mu))if(c.push(u),r(u))return l(u,p);return{diagnostic:ln,searched:c,...i?{callerEntry:Mn(i)}:{}}}function Hn(e={},n={}){let t=ue(e,n);if(Y(t))return t;throw new an(t)}function ar(e){let n=sr(e);return n===Q||lr.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:Tu(Mn(e))}function Tu(e){let n=or(e);for(let t=0;t<4;t++){if(sr(n)==="redskilled")return!0;let r=or(n);if(r===n)return!1;n=r}return!1}function*Nu(e,n,t,r){if(e){let s=or(Mn(e));yield[C(s,Q),"caller-sibling-bundle"];let i=Lu.exec(sr(e));i&&(yield[C(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[C(s,"..","dist",Q),"caller-sibling-bundle"]}for(let s of Iu){let i=t[s];i&&(yield[C(i,"dist",Q),"plugin-root-bundle"],yield[C(i,"..","..","dist",Q),"plugin-root-bundle"])}n&&(yield[C(n,"dist",Q),"repo-bundle"],yield[C(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[C(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=Us(t);yield[C(o,Q),"bundle-cache"];for(let s of Wu(o,r))yield[C(o,s),"bundle-cache"]}function Us(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||C(e.HOME||Au(),".cache");return C(n,"red-skills","bundles")}function Wu(e,n){return n(e).filter(t=>lr.test(t)).sort((t,r)=>Cu(Hs(r),Hs(t)))}function Hs(e){return lr.exec(e)?.[1]??""}function Cu(e,n){let t=s=>s.split(".").map(i=>Number.parseInt(i,10)),[r,o]=[t(e),t(n)];for(let s=0;s<Math.max(r.length,o.length);s++){let[i,l]=[r[s],o[s]];if(Number.isNaN(i)||i===void 0)return Number.isNaN(l)||l===void 0?e.localeCompare(n):-1;if(Number.isNaN(l)||l===void 0)return 1;if(i!==l)return i-l}return 0}function Mu(e){try{return $u(e)}catch{return[]}}var Q,ln,ir,an,Lu,lr,Iu,re=rd(()=>{"use strict";Q="redskilled.bundle.min.mjs",ln="redskilled-daemon-entry-unresolved",ir="REDSKILLED_BIN";an=class extends Error{code=ln;searched;callerEntry;constructor(n){super(`${ln}: no published ${Q} found to spawn the redskilled daemon from${n.callerEntry?` (caller entry: ${n.callerEntry}, which is NOT used as a fallback)`:""}
|
|
4
4
|
searched:
|
|
5
5
|
${n.searched.map(t=>` ${t}`).join(`
|
|
6
|
-
`)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};
|
|
7
|
-
`);return n.length>0&&n[n.length-1]===""&&n.pop(),n.map(t=>t.endsWith("\r")?t.slice(0,-1):t)}function
|
|
8
|
-
`;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let i=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(i))throw
|
|
9
|
-
`:n+="\\n";break;case"\r":n+="\\r";break;case" ":n+="\\t";break;default:t<" "?n+=`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`:n+=t}return`${n}"`}function Pe(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}var
|
|
10
|
-
`);for(let[i,l]of Object.entries(t))en(e,r+1),e.push(F(i),": ",s.paths.map(a=>q(
|
|
6
|
+
`)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};Lu=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,lr=/^redskilled-(.+)\.bundle\.min\.mjs$/,Iu=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as Ch}from"node:child_process";import{homedir as Xr}from"node:os";import{join as Oa}from"node:path";var Ye=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},me=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonlError",this.line=n,this.reason=t}};function R(e,n){return new Ye(e,n)}function x(e,n){return new me(e,n)}function Ee(e){return e instanceof me?e:e instanceof Ye?new me(e.line,e.reason):new me(0,String(e&&e.message?e.message:e))}var P=",";function On(e){let n=e.split(`
|
|
7
|
+
`);return n.length>0&&n[n.length-1]===""&&n.pop(),n.map(t=>t.endsWith("\r")?t.slice(0,-1):t)}function K(e){return R(e,"invalid quoted string")}function J(e,n){if(e==="")return"";if(e.startsWith('"'))return Oo(e,n);if(e.includes('"'))throw K(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:sd(e)?Number(e):e}function ne(e,n){let t=e.trim();if(t.startsWith('"'))return[Oo(t,n),!0];if(t.includes('"')||/\s/.test(t))throw R(n,"expected non-empty field name");return[t,!1]}function Oo(e,n){if(e[0]!=='"')throw K(n);let t="",r=1;for(;r<e.length;){let o=e[r];if(r+=1,o==='"'){if(e.slice(r).trim()==="")return t;throw K(n)}if(o==="\\"){let s=e[r];switch(r+=1,s){case'"':t+='"';break;case"\\":t+="\\";break;case"n":t+=`
|
|
8
|
+
`;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let i=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(i))throw K(n);let l=Number.parseInt(i,16);if(l>=55296&&l<=57343)throw K(n);t+=String.fromCharCode(l),r+=4;break}default:throw K(n)}continue}if(o<" "&&o!==" ")throw K(n);t+=o}throw K(n)}function ge(e,n,t){if(e==="")return[];let r=[],o=0,s=!1,i=!1;for(let l=0;l<e.length;l+=1){let a=e[l];if(i){i=!1;continue}a==="\\"&&s?i=!0:a==='"'?s=!s:a===n&&!s&&(r.push(e.slice(o,l).trim()),o=l+1)}if(s||i)throw K(t);return r.push(e.slice(o).trim()),r}function T(e,n,t){let r=!1,o=!1;for(let s=0;s<e.length;s+=1){let i=e[s];if(o){o=!1;continue}if(i==="\\"&&r)o=!0;else if(i==='"')r=!r;else if(i===n&&!r)return s}if(r||o)throw K(t);return-1}function sd(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function id(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function ld(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw R(0,"number is not representable in TOON");return String(e)}function Ze(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function q(e,n){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return ld(e);if(typeof e=="string")return dd(e,n);throw R(0,"not a primitive")}function ad(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function F(e){return ad(e)?e:$o(e)}function dd(e,n){return cd(e,n)?$o(e):e}function cd(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||id(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}function $o(e){let n='"';for(let t of e)switch(t){case'"':n+='\\"';break;case"\\":n+="\\\\";break;case`
|
|
9
|
+
`:n+="\\n";break;case"\r":n+="\\r";break;case" ":n+="\\t";break;default:t<" "?n+=`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`:n+=t}return`${n}"`}function Pe(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}var Et=2;function ud(e={}){return{indent:Math.max(1,e.indent??Et),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function pd(e,n){let t=[],r=!1;return On(e).forEach((o,s)=>{let i=s+1;if(o.trim()===""){r=!0;return}let l=o.length-o.replace(/^ +/,"").length;if(o[l]===" ")throw R(i,"invalid indentation");if(n.strict&&l%n.indent!==0)throw R(i,"invalid indentation");t.push({number:i,depth:Math.floor(l/n.indent),content:o.slice(l),blankBefore:r}),r=!1}),t}function G(e,n){let t=ud(n),r=pd(e,t),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw R(o.number,"invalid indentation");let s=r.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){let c;try{c=Dt(o.content,T(o.content,":",o.number))}catch(u){if(t.strict)throw xt(u,o.number);c=void 0}if(c!==void 0)return gd(c,r,t)}if(s&&T(o.content,":",o.number)===-1)return J(o.content.trim(),o.number);let i={index:0},l=Pt(r,i,0,t),a=r[i.index];if(a!==void 0)throw R(a.number,"expected end of document");return l}function Pt(e,n,t,r){let o={};for(;n.index<e.length;){let s=e[n.index];if(s.depth<t)break;if(s.depth>t)throw R(s.number,"invalid indentation");let{key:i,quoted:l,value:a}=fd(e,n,t,r);Io(o,i,l,a,r,s.number)}return o}function fd(e,n,t,r){let o=e[n.index],s=o.content,i=T(s,":",o.number);if(i===-1)throw R(o.number,"expected `key: value`");let l=s.slice(0,i),a=s.slice(i+1),c=T(l,"[",o.number),u=T(l,"{",o.number);if(u!==-1&&(c===-1||u<c)){let k;try{k=Rd(l)}catch(y){if(r.strict)throw xt(y,o.number);n.index+=1;let _=bt(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:_}}if(a.trim()!=="")throw R(o.number,"expected keyed map rows");let b=md(k,e,n,t+1,r);return{key:k.key,quoted:k.keyQuoted,value:b}}if(c!==-1){let k;try{k=Dt(l,i)}catch(y){if(r.strict)throw xt(y,o.number);n.index+=1;let _=bt(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:_}}if(k.key===""&&!k.keyQuoted)throw R(o.number,"expected non-empty field name");let b=jt(k,a,e,n,t,r);return{key:k.key,quoted:k.keyQuoted,value:b}}let[p,f]=ne(l,o.number);if(p===""&&!f)throw R(o.number,"expected non-empty field name");n.index+=1;let h=bt(e,n,t,a,o.number,r);return{key:p,quoted:f,value:h}}function bt(e,n,t,r,o,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return J(i,o);let l=e[n.index];return l!==void 0&&l.depth>t?Pt(e,n,t+1,s):{}}function md(e,n,t,r,o){let s={};for(t.index+=1;t.index<n.length;){let i=n[t.index];if(i.depth<r)break;if(i.depth>r)throw R(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw R(i.number,"blank line inside keyed map");let l=T(i.content,":",i.number);if(l===-1)throw R(i.number,"expected `key: value`");let[a,c]=ne(i.content.slice(0,l),i.number);if(a===""&&!c)throw R(i.number,"expected non-empty field name");let u=ge(i.content.slice(l+1).trim(),e.delimiter,i.number);if(u.length!==e.fields.length)throw R(i.number,"keyed map row length mismatch");let p={};e.fields.forEach((f,h)=>{Xe(p,f,J(u[h],i.number),o,i.number)}),Io(s,a,c,p,o,i.number),t.index+=1}return s}function gd(e,n,t){let r=n[0],o=T(r.content,":",r.number);if(o===-1)throw R(r.number,"expected `key: value`");let s=r.content.slice(o+1),i={index:0},l=jt(e,s,n,i,0,t),a=n[i.index];if(a!==void 0)throw R(a.number,"expected end of document");return l}function jt(e,n,t,r,o,s){let i=t[r.index].number,l=n.trim();if(r.index+=1,e.fields!==void 0){if(l!=="")throw R(i,"expected tabular rows");return hd(e,e.fields,t,r,o+1,s)}if(l!==""){let a=ge(l,e.delimiter,i).map(c=>J(c,i));if(a.length!==e.len)throw R(i,"array length mismatch");return a}return yd(e,t,r,o+1,s)}function hd(e,n,t,r,o,s){let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0)throw _t(t,r.index);if(a.depth<o)break;if(a.depth>o)throw R(a.number,"invalid indentation");if(a.blankBefore&&s.strict)throw R(a.number,"blank line inside array");if(!Ao(a.content,e.delimiter,a.number))break;let c=ge(a.content,e.delimiter,a.number);if(c.length!==n.length)throw R(a.number,"array row length mismatch");let u={};n.forEach((p,f)=>{Xe(u,p,J(c[f],a.number),s,a.number)}),i.push(u),r.index+=1}if(i.length!==e.len)throw _t(t,r.index);let l=t[r.index];if(l!==void 0&&l.depth>=o&&Ao(l.content,e.delimiter,l.number))throw R(l.number,"array length mismatch");return i}function Ao(e,n,t){let r=T(e,":",t);if(r===-1)return!0;let o=T(e,n,t);return o===-1?!1:o<r}function yd(e,n,t,r,o){let s=[];for(;s.length<e.len;){let l=n[t.index];if(l===void 0||l.depth<r)throw _t(n,t.index);if(l.depth>r)throw R(l.number,"invalid indentation");if(l.blankBefore&&o.strict)throw R(l.number,"blank line inside array");s.push(kd(n,t,r,o))}let i=n[t.index];if(i!==void 0&&i.depth>=r)throw R(i.number,"array length mismatch");return s}function kd(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw R(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return n.index+=1,{};if(s.startsWith("[")){let i=T(s,":",o.number),l;try{l=Dt(s,i)}catch{l=void 0}if(l!==void 0){let a=s.slice(i+1);return jt(l,a,e,n,t,r)}}if(T(s,":",o.number)!==-1){let i=[{number:o.number,depth:t+1,content:s,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let l=e[n.index];if(l.depth<=t)break;i.push(l),n.index+=1}return Pt(i,{index:0},t+1,r)}return n.index+=1,J(s,o.number)}function _t(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function Dt(e,n){if(n===-1)throw R(0,"array header missing colon");let t=e.slice(0,n),r=T(t,"[",0);if(r===-1)throw R(0,"invalid array header");let o,s;try{[o,s]=ne(t.slice(0,r),0)}catch{throw R(0,"invalid array header")}let i=t.slice(r+1),l=i.indexOf("]");if(l===-1)throw R(0,"invalid array header");let a=i.slice(0,l),c=/^[0-9]*/.exec(a)[0];if(c===""||c.length>1&&c.startsWith("0"))throw R(0,"invalid array header");let u=Number.parseInt(c,10),p;switch(a.slice(c.length)){case"":p=",";break;case" ":p=" ";break;case"|":p="|";break;default:throw R(0,"invalid array header")}let f=i.slice(l+1),h;if(f==="")h=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{h=Lo(f.slice(1,-1),p)}catch(k){throw R(0,k.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw R(0,"invalid array header");return{key:o,keyQuoted:s,len:u,delimiter:p,fields:h}}function Rd(e){let n=T(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=ne(e.slice(0,n),0)}catch{throw R(0,"invalid keyed map header")}if(t===""&&!r)throw R(0,"expected non-empty field name");let o;try{o=Lo(e.slice(n+1,-1),P)}catch(s){throw R(0,s.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:P,fields:o}}function Lo(e,n){let t=[],r=0;function o(l,a){let c=0;for(;r<e.length&&!(a&&e[r]==="}");){if(e[r]===n||e[r]==="}")throw R(0,"invalid array header");let u=r;for(;r<e.length;){let f=e[r];if(f==='"'){s();continue}if(f===n||f==="{"||f==="}")break;r+=1}let[p]=ne(e.slice(u,r),0);if(p==="")throw R(0,"invalid array header");if(c+=1,e[r]==="{"){r+=1;let f=t.length;if(o([...l,p],!0),e[r]!=="}"||t.length===f)throw R(0,"invalid array header");r+=1}else t.push([...l,p]);if(e[r]===n){if(r+=1,r>=e.length||e[r]==="}")throw R(0,"invalid array header");continue}if(a?e[r]==="}":r===e.length)break;throw R(0,"invalid array header")}if(c===0)throw R(0,"invalid array header")}function s(){for(r+=1;r<e.length;){let l=e[r];if(r+=1,l==="\\")r+=1;else if(l==='"')return}}if(o([],!1),r!==e.length)throw R(0,"invalid array header");let i=new Set;for(let l=0;l<t.length;l+=1)for(let a=l+1;a<t.length;a+=1)if(bd(t[l],t[a])||vt(t[l],t[a])||vt(t[a],t[l]))throw R(0,"duplicate key");for(let l of t){let a=l.join("\0");if(i.has(a))throw R(0,"duplicate key");i.add(a)}return t}function bd(e,n){return e.length===n.length&&vt(e,n)}function vt(e,n){return n.every((t,r)=>e[r]===t)}function xt(e,n){return R(n,e.reason??String(e.message))}function Io(e,n,t,r,o,s){if(o.expandPaths&&!t&&n.includes(".")){let i=n.split(".");if(i.every(wd)){Xe(e,i,r,o,s);return}}Xe(e,[n],r,o,s)}function Xe(e,n,t,r,o){let s=n[0],i=Object.prototype.hasOwnProperty.call(e,s);if(n.length===1){if(i&&r.strict)throw R(o,"duplicate key");Pe(e,s,t);return}if(i&&!je(e[s])){if(r.strict)throw R(o,"path expansion conflict");Pe(e,s,{})}else i||Pe(e,s,{});Xe(e[s],n.slice(1),t,r,o)}function wd(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function I(e,n={}){let t={nestedTabularHeaders:n.nestedTabularHeaders===!0,keyedMapCollapse:n.keyedMapCollapse===!0},r=[];return Array.isArray(e)?Ot(r,void 0,e,0,!1,t):je(e)?To(r,e,0,t):r.push(q(e,P)),r.join("")}function en(e,n){e.push(" ".repeat(n*Et))}function To(e,n,t,r){for(let[o,s]of Object.entries(n))en(e,t),St(e,o,s,t,r)}function St(e,n,t,r,o){if(Array.isArray(t)){Ot(e,n,t,r,!1,o);return}if(je(t)){let s=o.keyedMapCollapse?vd(t,o):void 0;if(s!==void 0){e.push(F(n),"{",s.fields.map($t).join(P),`}:
|
|
10
|
+
`);for(let[i,l]of Object.entries(t))en(e,r+1),e.push(F(i),": ",s.paths.map(a=>q(Mo(l,a),P)).join(P),`
|
|
11
11
|
`);return}e.push(F(n),`:
|
|
12
|
-
`),
|
|
13
|
-
`)}function
|
|
12
|
+
`),To(e,t,r+1,o);return}e.push(F(n),": ",q(t,P),`
|
|
13
|
+
`)}function Ot(e,n,t,r,o,s){if(t.length===0){n!==void 0?e.push(F(n),`: []
|
|
14
14
|
`):o?e.push(`[0]:
|
|
15
15
|
`):e.push(`[]
|
|
16
|
-
`);return}if(t.every(Ze)){
|
|
17
|
-
`);return}let i=o?void 0:
|
|
18
|
-
`);for(let l of t)en(e,r+1),e.push(i.paths.map(a=>q(
|
|
19
|
-
`);return}
|
|
20
|
-
`);for(let l of t)en(e,r+1),
|
|
21
|
-
`);return}e.push("- "),
|
|
22
|
-
`)}function
|
|
23
|
-
`}function
|
|
24
|
-
`}function
|
|
25
|
-
`,k=()=>
|
|
26
|
-
`;return D+=M,l+=1,a+=1,
|
|
27
|
-
`},end(){return p?"":(p=!0,
|
|
16
|
+
`);return}if(t.every(Ze)){wt(e,n,t.length,void 0),e.push(" "),e.push(t.map(l=>q(l,P)).join(P)),e.push(`
|
|
17
|
+
`);return}let i=o?void 0:No(t,s);if(i!==void 0){wt(e,n,t.length,i.fields),e.push(`
|
|
18
|
+
`);for(let l of t)en(e,r+1),e.push(i.paths.map(a=>q(Mo(l,a),P)).join(P)),e.push(`
|
|
19
|
+
`);return}wt(e,n,t.length,void 0),e.push(`
|
|
20
|
+
`);for(let l of t)en(e,r+1),_d(e,l,r+1,s)}function _d(e,n,t,r){if(Array.isArray(n)){e.push("- "),Ot(e,void 0,n,t,!0,r);return}if(je(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
|
|
21
|
+
`);return}e.push("- "),St(e,o[0][0],o[0][1],t+1,r);for(let[s,i]of o.slice(1))en(e,t+1),St(e,s,i,t+1,r);return}e.push("- ",q(n,P),`
|
|
22
|
+
`)}function wt(e,n,t,r){n!==void 0&&e.push(F(n)),e.push("[",String(t),"]"),r!==void 0&&e.push("{",r.map($t).join(P),"}"),e.push(":")}function No(e,n){let t=Wo(e.map(r=>({value:r})),n);return t===void 0?void 0:{fields:t,paths:Co(t)}}function vd(e,n){let t=Object.values(e);if(!(t.length<2))return No(t,n)}function Wo(e,n){let t=e[0]?.value;if(!je(t))return;let r=Object.keys(t).map(o=>({key:o}));if(r.length!==0){for(let{value:o}of e)if(!je(o)||Object.keys(o).length!==r.length||r.some(i=>!Object.prototype.hasOwnProperty.call(o,i.key)))return;for(let o of r){let s=e.map(({value:l})=>({value:l[o.key]}));if(s.every(({value:l})=>Ze(l)))continue;if(!n.nestedTabularHeaders)return;let i=Wo(s,n);if(i===void 0)return;o.children=i}return r}}function Co(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children===void 0?[r]:Co(t.children,r)})}function Mo(e,n){let t=e;for(let r of n)t=t[r];return t}function $t(e){return e.children===void 0?F(e.key):`${F(e.key)}{${e.children.map($t).join(P)}}`}var qo=[P,"|"," "];var Go=8,zo=/^[A-Za-z0-9_-]+$/,hy=new TextEncoder,yy=new TextDecoder;function Sd(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw x(n,"invalid trailer count");return Number.parseInt(t,10)}function Qo(e,n){if(!zo.test(e))throw x(n,"invalid tag")}function Ed(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!zo.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw x(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function Pd(e,n){if(!e.startsWith("["))return null;let t=e.slice(1),r=t.indexOf("]");if(r===-1)throw x(n,"invalid header");let o=t.slice(0,r),s=o.startsWith("~"),i=s?o.slice(1):o;if(!s&&i.startsWith("="))return null;if(!qo.includes(i)&&i!=="")throw x(n,"invalid header delimiter");let l=i===""?P:i,a=t.slice(r+1),c=null;if(!s&&a.startsWith("<")){let f=a.indexOf(">");if(f===-1)throw x(n,"invalid tag");if(c=a.slice(1,f),Qo(c,n),i!=="")throw x(n,"invalid header delimiter");a=a.slice(f+1)}if(!a.startsWith("{")||!a.endsWith("}:"))throw x(n,"invalid header");let u=a.slice(1,-2),p;try{p=ge(u,l,n).map(f=>ne(f,n)[0])}catch(f){throw Ee(f)}if(p.length===0||p.some(f=>f===""))throw x(n,"invalid header fields");return{delimiter:l,fields:p,fieldText:u,continuation:s,tag:c}}function jd(e,n,t){if(e===null||e.delimiter===void 0)throw x(t,"continuation header before header");if(e.delimiter!==n.delimiter||e.fieldText!==n.fieldText)throw x(t,"continuation header mismatch")}function Fo(e,n,t,r){let o;try{o=ge(e,n,r)}catch(s){throw Ee(s)}if(o.length!==t)throw x(r,"row arity mismatch");for(let s of o)try{J(s,r)}catch(i){throw Ee(i)}return o}function Dd(e,n,t){let r={};return e.forEach((o,s)=>{try{Pe(r,o,J(n[s],t))}catch(i){throw Ee(i)}}),r}function Od(e,n,t){if(e.startsWith("- "))throw x(n,"reserved line prefix");let r=Sd(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw x(n,"trailer without header");if(t.rowCount!==r)throw x(n,"trailer count mismatch");return{kind:"trailer"}}let o=Pd(e,n);if(o!==null)return o.continuation?(jd(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=Ed(e,n);if(s!==null){let i=t?.taggedLanes?.get(s.tag);if(i===void 0)throw x(n,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:Fo(s.cellsText,i.delimiter,i.fields.length,n)}}if(t===null||t.delimiter===void 0)throw x(n,"row before header");return{kind:"row",cells:Fo(e,t.delimiter,t.fields.length,n)}}function $d(e,n={}){let t=[],r=new Map,o=[],s=[],i=null,l=!1,a=!1;function c(h,k){let b=s.at(-1);if(b!==void 0&&b.lane===h.lane&&b.delimiter===h.delimiter&&b.fieldText===h.fieldText){b.rows.push(k);return}s.push({lane:h.lane,delimiter:h.delimiter,fields:h.fields,fieldText:h.fieldText,rows:[k]})}function u(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function p(h,k,b){let y=r.get(h);if(y===void 0){if(r.size>=Go)throw x(b,"too many tagged lanes");y={segments:[],current:null},r.set(h,y),t.push(h)}else y.current!==null&&y.segments.push(y.current);y.current={lane:h,delimiter:k.delimiter,fields:k.fields,fieldText:k.fieldText,rows:[]},y.delimiter=k.delimiter,y.fields=k.fields,y.fieldText=k.fieldText}if(On(e).forEach((h,k)=>{let b=k+1;if(h==="")return;let y=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},_=Od(h,b,y);if(_.kind==="trailer"){u(),i=null;return}if(_.kind!=="continuation"){if(_.kind==="tag-header"){a=!0,p(_.header.tag,_.header,b);return}if(_.kind==="header"){u(),l||(t.push(null),l=!0),i={lane:null,delimiter:_.header.delimiter,fields:_.header.fields,fieldText:_.header.fieldText,rows:[]};return}if(_.kind==="tagged-row"){a=!0;let D=r.get(_.tag).current;D.rows.push(_.cells),c(D,_.cells);return}if(i===null)throw x(b,"row before header");i.rows.push(_.cells),c(i,_.cells)}}),!a)return u(),n.preserveInterleaving===!0,o;let f=[];u();for(let h of t){if(h===null){f.push(...o);continue}let k=r.get(h);f.push(...k.segments),k.current!==null&&f.push(k.current)}return n.preserveInterleaving===!0?s:f}function de(e){return $d(e).flatMap(n=>n.rows.map(t=>Dd(n.fields,t,0)))}function Ad(e){if(!qo.includes(e))throw x(0,"invalid header delimiter")}function Ho(e,n,t=!1){return`[${`${t?"~":""}${e===P?"":e}`}]{${n}}:
|
|
23
|
+
`}function Uo(e,n){return`[]<${e}>{${n}}:
|
|
24
|
+
`}function At(e,n){return n.map(F).join(e)}function Ld(e){if(!Array.isArray(e)||e.length===0)throw x(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=ne(String(n),0)}catch(r){throw Ee(r)}if(t==="")throw x(0,"TOONL header requires fields");return t})}function Bo(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function Vo(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw x(0,"TOONL continuation cadence must be positive")}function Id(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function Ko(e){if(e===null||typeof e!="object"||Array.isArray(e))throw x(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw x(0,"TOONL output requires object rows");if(n.some(t=>!Ze(e[t])))throw x(0,"TOONL rows must be flat objects");return n}function Td(e){return JSON.stringify([...e].sort())}function Jo(e,n){let t=Td(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function te({delimiter:e=P,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){Ad(e),Vo(t),Vo(r);let o=null,s="",i=new Map,l=0,a=0,c=0,u=new Map,p=!1,f={continuationEveryRows:t,continuationEveryBytes:r},h=()=>o===null||!n?"":`[=${l}]
|
|
25
|
+
`,k=()=>Id(f,a,c)?(a=0,c=0,Ho(e,s,!0)):"",b=y=>{Qo(y,0);let _=u.get(y);if(_===void 0){if(u.size>=Go)throw x(0,"too many tagged lanes");_={fields:null,fieldsByShape:new Map},u.set(y,_)}return _};return{push(y){if(p)throw x(0,"TOONL encoder is closed");let _=Jo(Ko(y),i),D="";(o===null||o.length!==_.length||o.some((fe,_e)=>fe!==_[_e]))&&(D+=h(),o=_,s=At(e,o),l=0,a=0,c=0,D+=Ho(e,s));let B=o.map(fe=>q(y[fe],e));D+=k();let M=`${B.join(e)}
|
|
26
|
+
`;return D+=M,l+=1,a+=1,c+=M.length,D},declareLane(y,_){if(p)throw x(0,"TOONL encoder is closed");let D=Ld(_),B=At(P,D),M=b(y);return Bo(M.fields,D)?"":(M.fields=D,Uo(y,B))},pushTagged(y,_){if(p)throw x(0,"TOONL encoder is closed");let D=b(y),B=Jo(Ko(_),D.fieldsByShape),M=At(P,B),fe=B.map(kn=>q(_[kn],P)),_e="";return Bo(D.fields,B)||(D.fields=B,_e+=Uo(y,M)),`${_e}${y}:${fe.join(P)}
|
|
27
|
+
`},end(){return p?"":(p=!0,h())}}}function Lt(e){let n={app:e,version:Nd(De("__RED_BUILD_VERSION__",()=>"3.3.6")??"0.0.0-dev"),gitSha:De("__RED_BUILD_GIT_SHA__",()=>"ac326ac6f408e3f05f6326a1e12f9d9e9b1b5c6c")??"unknown",buildTime:De("__RED_BUILD_TIME__",()=>"2026-08-02T02:34:56Z")??"unknown",bundleAsset:De("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=De("__REDDB_SDK_VERSION__",()=>""),r=De("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function Nd(e){return e.startsWith("v")?e.slice(1):e}function Yo(e){return`${e.app} ${e.version} ${e.gitSha}`}function De(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var Zo={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Wd=/^[a-z][a-z0-9+.-]*:\/\//i;function Cd(e,n){return typeof n=="string"?{separator:e,to:n,typed:!1,prefix:!1}:{separator:e,to:n.to,typed:n.typed??!1,prefix:n.prefix??!1}}function Md(e=Zo){return Object.entries(e).map(([n,t])=>Cd(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function Fd(e){return/^-\d+(\.\d+)?$/.test(e)}function nn(e){return!(!e||e.startsWith("-")&&!Fd(e))}function $n(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e}function Xo(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e.includes(",")?e.split(",").map(t=>Xo(t.trim())):e}function he(e,n){switch(n){case"boolean":return Hd(e);case"number":return Ud(e);case"array":return e.split(",").map(t=>$n(t.trim()));case"string":default:return e}}function Hd(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function Ud(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let n=Number(e);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${e}" to number`);return n}function ce(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Bd(e,n={}){return e.map(t=>{let r=n[t.type];return r?r(t.value):t.value}).join("")}function E(e,n){return{type:e,value:n}}function Vd(e){let n=[],t=Jd(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
|
|
28
28
|
`),E("newline",`
|
|
29
29
|
`)),e.positional&&e.positional.length>0){n.push(E("section-header","Arguments:"),E("newline",`
|
|
30
30
|
`));for(let r of e.positional)if(r.description){let o=r.variadic?`${r.name}...`:r.name;n.push(E("indent"," "),E("positional-name",`<${o}>`)),r.required||n.push(E("positional-optional"," (optional)")),n.push(E("newline",`
|
|
31
31
|
`),E("indent"," "),E("option-description",r.description),E("newline",`
|
|
32
32
|
`))}n.push(E("newline",`
|
|
33
33
|
`))}if(e.options&&Object.keys(e.options).length>0){n.push(E("section-header","Options:"),E("newline",`
|
|
34
|
-
`));let r=
|
|
35
|
-
`))}return t}function
|
|
36
|
-
`),o=r.find(i=>i.startsWith("0::"));if(o)return o.slice(3)||null;let s=r[0]?.split(":").slice(2).join(":");return s===void 0||s===""?null:s}function
|
|
37
|
-
`)}catch{return!0}},append(e,n){
|
|
38
|
-
`),t.append(e,r),n}function
|
|
34
|
+
`));let r=qd(e.options);n.push(...r)}return n}function Kd(e,n){let t=Vd(e);return Bd(t,n)}function Jd(e){let n=["[options]"];if(e.positional)for(let t of e.positional)t.variadic?n.push(t.required?`<${t.name}...>`:`[${t.name}...]`):n.push(t.required?`<${t.name}>`:`[${t.name}]`);return n.join(" ")}function qd(e,n=!1){let t=[],r=[],o=n?"global-option-flag":"option-flag",s=n?"global-option-type":"option-type",i=n?"global-option-default":"option-default",l=n?"global-option-description":"option-description";for(let[c,u]of Object.entries(e)){if(u.hidden)continue;let p=[],f=b=>{p.includes(b)||p.push(b)};u.short&&f(`-${u.short}`),f(`--${c}`);for(let b of u.aliases??[])b.length===1?f(`-${b}`):f(`--${b}`);let h=p.join(", "),k=u.type&&u.type!=="boolean"?`<${u.type}>`:void 0;r.push({flags:h,type:k,desc:u.description??"",default:u.default!==void 0?String(u.default):void 0})}let a=Math.max(...r.map(c=>c.flags.length+(c.type?c.type.length+1:0)),20);for(let c of r){let u=c.flags.length+(c.type?c.type.length+1:0),p=" ".repeat(a-u+2);t.push(E("indent"," ")),t.push(E(o,c.flags)),c.type&&(t.push(E("text"," ")),t.push(E(s,c.type))),t.push(E("text",p)),t.push(E(l,c.desc)),c.default!==void 0&&(t.push(E("text"," ")),t.push(E(i,`(default: ${c.default})`))),t.push(E("newline",`
|
|
35
|
+
`))}return t}function es(e){let n=ec(e.options??{},e.autoShort??!1),t=Md(e.separators??Zo);return{schema:e,parse(r){return Gd(r,e,n,t)},help(){return Kd(e,e.formatter)}}}function Gd(e,n,t,r){let o={positional:{},options:{},errors:[],rest:[]},s=new Set(r.map(u=>u.to));for(let u of s)o[u]={};let i=0,l=n.positional??[],a=0,c=!1;for(;a<e.length;){let u=e[a];if(n.stopEarly&&i>0){o.rest=e.slice(a);break}if(u==="--"&&!c){c=!0,a++;continue}if(c){if(i<l.length){let f=l[i];if(f.variadic){let h=[];for(;a<e.length;){let k=e[a];h.push(f.type?he(k,f.type):k),a++}o.positional[f.name]=h,i++}else{let h=f.type?he(u,f.type):u;o.positional[f.name]=h,i++,a++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(u)),a++;continue}if(u.startsWith("--")){a=Zd(u,a,e,o,t,n);continue}if(u.startsWith("-")&&u.length>1&&!sc(u)){a=Xd(u,a,e,o,t,n);continue}let p=zd(u,r);if(p){let{key:f,value:h,config:k}=p,b=o,y=b[k.to]??(b[k.to]={});y[f]=k.typed?Xo(h):ce(h),a++;continue}if(i<l.length){let f=l[i];if(f.variadic){let k=[];for(;a<e.length&&!e[a].startsWith("-");){let b=e[a];k.push(f.type?he(b,f.type):b),a++}o.positional[f.name]=k,i++;continue}let h=f.type?he(u,f.type):u;o.positional[f.name]=h,i++}else n.allowUnknown!==!1?o.rest.push(u):o.errors.push(`Unexpected positional argument: ${u}`);a++}return tc(o,n,t),rc(o,n,l),oc(o,n,t),o}function zd(e,n){if(Wd.test(e))return null;for(let t of n){if(t.prefix&&e.startsWith(t.separator)){let o=e.slice(t.separator.length),s=o.indexOf(":");if(s>0){let i=o.slice(0,s),l=o.slice(s+1);if(Qd(i))return{key:i,value:l,config:t}}continue}let r=e.indexOf(t.separator);if(r>0){let o=e.slice(0,r),s=e.slice(r+t.separator.length);if(Yd(o,s,t))return{key:o,value:s,config:t}}}return null}function Qd(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function Yd(e,n,t){return e?t.separator===":"?e.includes("/")||e.includes(".")||/^\d+$/.test(n)?!1:/^[A-Z][a-zA-Z0-9-]*$/.test(e):!((t.separator==="="||t.separator===":=")&&e.includes("/")):!1}function Zd(e,n,t,r,o,s){let i=e.slice(2);if(i.startsWith("no-")){let a=i.slice(3),c=o.get(a);if(c?.negatable!==!1&&c?.type==="boolean")return r.options[c.name]=!1,n+1}if(i.includes("=")){let a=i.indexOf("="),c=i.slice(0,a),u=i.slice(a+1);return An(c,u,n+1,r,o,s)}let l=o.get(i);if(l){if(l.type!=="boolean"){let a=t[n+1];return nn(a)?An(l.name,a,n+2,r,o,s):(r.errors.push(`Option --${i} requires a value`),n+1)}return r.options[l.name]=!0,n+1}return s.strict?r.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(r.options[i]=!0),n+1}function Xd(e,n,t,r,o,s){let i=e.slice(1);if(i.includes("=")){let l=i.indexOf("="),a=i.slice(0,l),c=i.slice(l+1),u=It(a,o);return u?An(u.name,c,n+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=$n(ce(c))),n+1)}if(i.length===1){let l=It(i,o);if(l){if(l.type!=="boolean"){let a=t[n+1];return nn(a)?An(l.name,a,n+2,r,o,s):(r.errors.push(`Option -${i} requires a value`),n+1)}return r.options[l.name]=!0,n+1}if(s.strict)r.errors.push(`Unknown option: -${i}`);else if(s.allowUnknown!==!1){let a=t[n+1];if(nn(a))return r.options[i]=$n(ce(a)),n+2;r.options[i]=!0}return n+1}for(let l of i){let a=It(l,o);a?a.type==="boolean"?r.options[a.name]=!0:r.errors.push(`Option -${l} requires a value`):s.strict?r.errors.push(`Unknown option: -${l}`):s.allowUnknown!==!1&&(r.options[l]=!0)}return n+1}function An(e,n,t,r,o,s){let i=o.get(e);if(i){if(i.choices){let a=i.type?he(ce(n),i.type):ce(n);if(!i.choices.includes(a))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${i.choices.join(", ")}`),t}let l=i.type?he(ce(n),i.type):ce(n);if(i.type==="array"){let a=r.options[e];Array.isArray(a)?a.push(...l):r.options[e]=l}else r.options[e]=l}else s.strict?r.errors.push(`Unknown option: --${e}`):s.allowUnknown!==!1&&(r.options[e]=$n(ce(n)));return t}function ec(e,n=!1){let t=new Map,r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i)),o=new Set;for(let[,s]of r)s.short&&o.add(s.short);for(let[s,i]of r){let l=i.short??"";n&&!l&&(l=nc(s,o),l&&o.add(l));let a={name:s,short:l,aliases:i.aliases??[],type:i.type??"string",description:i.description??"",required:i.required??!1,hidden:i.hidden??!1,negatable:i.negatable??!0,default:i.default,choices:i.choices,env:i.env,validate:i.validate};t.set(s,a);for(let c of a.aliases)t.set(c,a)}return t}function nc(e,n){for(let t of e){if(!/[a-zA-Z]/.test(t))continue;let r=t.toLowerCase();if(!n.has(r))return r;let o=t.toUpperCase();if(!n.has(o))return o}return""}function It(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function tc(e,n,t){for(let r of t.values())if(e.options[r.name]===void 0)if(r.env&&process.env[r.env]!==void 0){let o=process.env[r.env];e.options[r.name]=r.type?he(o,r.type):o}else r.default!==void 0&&(e.options[r.name]=r.default);for(let r of n.positional??[])e.positional[r.name]===void 0&&r.default!==void 0&&(e.positional[r.name]=r.default)}function rc(e,n,t){if(n.options)for(let[r,o]of Object.entries(n.options))o.required&&e.options[r]===void 0&&e.errors.push(`Missing required option: --${r}`);for(let r of t)r.required&&e.positional[r.name]===void 0&&e.errors.push(`Missing required argument: <${r.name}>`)}function oc(e,n,t){for(let r of t.values()){let o=e.options[r.name];if(r.validate&&o!==void 0){let s=r.validate(o);s!==!0&&e.errors.push(s)}}for(let r of n.positional??[]){let o=e.positional[r.name];if(r.validate&&o!==void 0){let s=r.validate(o);s!==!0&&e.errors.push(s)}}}function sc(e){return/^-\d+(\.\d+)?$/.test(e)}var Tt=class extends Error{flag;known;constructor(n,t){super(`unknown flag '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownFlagError",this.flag=n,this.known=t}};function ic(e){let n={};for(let[t,r]of Object.entries(e))n[t]={type:r.kind==="boolean"?"boolean":"string",...t.length===1?{short:t}:{},...r.aliases===void 0?{}:{aliases:r.aliases}};return n}function lc(e,n){let t=new Map;for(let[o,s]of Object.entries(n))if(!(s.kind!=="value"||s.type!=="array")){t.set(o,o);for(let i of s.aliases??[])t.set(i,o)}let r=new Map;for(let o=0;o<e.length;o+=1){let s=e[o];if(s==="--")break;let i=s.match(/^--([^=]+)(?:=(.*))?$/)??s.match(/^-([^=])(?:=(.*))?$/);if(i===null)continue;let l=t.get(i[1]);if(l===void 0)continue;let a=i[2];if(a===void 0&&nn(e[o+1])&&(a=e[o+1],o+=1),a===void 0)continue;let c=r.get(l)??[];c.push(a),r.set(l,c)}return r}function ye(e,n,t={}){let o=es({options:ic(n),separators:{},allowUnknown:!0}).parse([...e]),s={},i=lc(e,n),l=o.errors.find(a=>/^Option --?\S+ requires a value$/.test(a));if(l!==void 0)throw new Error(l.replace(/^Option /,""));if(o.errors.length>0)throw new Error(o.errors[0]);if(t.unknownFlags==="error"){let a=new Set(Object.keys(n));for(let c of Object.keys(o.options))if(!a.has(c))throw new Tt(c.length===1?`-${c}`:`--${c}`,Object.keys(n).map(u=>u.length===1?`-${u}`:`--${u}`))}for(let[a,c]of Object.entries(n)){let u=o.options[a];u!==void 0&&(c.kind==="boolean"?s[a]=u:c.type==="array"?s[a]=(i.get(a)??[]).map(p=>c.coerce(p)):s[a]=c.coerce(String(u)))}return{values:s,positionals:o.rest}}var Nt=class extends Error{token;known;constructor(n,t){super(`unknown command '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownCommandError",this.token=n,this.known=t}};function ns(e,n){let[t,...r]=e;if(t!==void 0){for(let[s,i]of Object.entries(n.commands))if(t===s||(i.aliases??[]).includes(t))return{command:s,args:r};if(n.errorOnUnknownCommand&&!t.startsWith("-"))throw new Nt(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as kc,mkdirSync as Rc,readFileSync as us,statSync as bc}from"node:fs";import{dirname as fs,join as wc}from"node:path";var ts="RED_WORKER_SCOPE",rs="RED_WORKER_MEMORY_CEILING",os="RED_WORKER_SCOPE_DEGRADATION",Ct={scope:null,memory_ceiling:null,scope_degradation:null};function Mt(e){return{scope:Wt(e[ts]),memory_ceiling:Wt(e[rs]),scope_degradation:Wt(e[os])}}function tn(e){let n={};return e.scope!=null&&e.scope!==""&&(n[ts]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[rs]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[os]=e.scope_degradation),n}function Wt(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as cc,readdirSync as uc,readFileSync as as,rmSync as pc,writeFileSync as fc}from"node:fs";import{basename as mc,join as Oe}from"node:path";import{isAbsolute as zy,join as Ln,resolve as Qy}from"node:path";function ac(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var ss="deaths",is="deaths.toonl";function In(e){return Ln(ac(e),ss)}function rn(e){return Ln(In(e),is)}var on="live",ls="attributions.toonl";function Tn(e){return Ln(In(e),on)}function Ft(e){return Ln(In(e),ls)}var Ut=Oe("sys","kernel","random","boot_id"),ds=1;function Bt(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:ds,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:cs(Oe(t,Ut)),cgroup:gc(t,r),last_phase:e.last_phase}}function cs(e){try{let n=as(e,"utf8").trim();return n===""?null:n}catch{return null}}function gc(e,n){let t=cs(Oe(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
|
|
36
|
+
`),o=r.find(i=>i.startsWith("0::"));if(o)return o.slice(3)||null;let s=r[0]?.split(":").slice(2).join(":");return s===void 0||s===""?null:s}function Vt(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function Kt(e,n){let t=Oe(e,Vt(n));try{return cc(e,{recursive:!0,mode:448}),fc(t,te({trailer:!1}).push(yc(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function ke(e,n){try{pc(Oe(e,Vt(n)),{force:!0})}catch{}}function Jt(e,n){let t;try{t=uc(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=Oe(e,o);try{let l=de(as(s,"utf8"))[0];if(l===void 0)throw new Error("anchor holds no record");r.push(hc(l))}catch(i){n?.(mc(s),i instanceof Error?i.message:String(i))}}return r}function hc(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:Ht(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:Ht(e.pid),ppid:Ht(e.ppid),boot_id:e.boot_id==null?null:String(e.boot_id),cgroup:e.cgroup==null?null:String(e.cgroup),last_phase:String(e.last_phase)}}function Ht(e){return typeof e=="number"?e:Number(e)}function yc(e){return{...e}}var _c=1,vc=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function xc(e){return typeof e=="string"&&vc.has(e)}var Sc="startup";function Ec(e,n){return{...e.scope??Ct,version:_c,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,exit_path:e.exit_path,signal:e.signal??null,exit_code:e.exit_code??null,last_phase:e.last_phase,detail:e.detail??null,...n}}function Pc(e){let n=e.resourceUsage();return{uptime_s:Math.round(e.uptime()),rss_kb:Math.round(e.memoryUsage().rss/1024),max_rss_kb:n.maxRSS,user_cpu_us:n.userCPUTime,system_cpu_us:n.systemCPUTime,minor_page_faults:n.minorPageFault,major_page_faults:n.majorPageFault,voluntary_ctx_switches:n.voluntaryContextSwitches,involuntary_ctx_switches:n.involuntaryContextSwitches}}var Gt={mkdir(e){Rc(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=bc(e).size}catch{return!0}if(n===0)return!0;try{return us(e,"utf8").endsWith(`
|
|
37
|
+
`)}catch{return!0}},append(e,n){kc(e,n,{encoding:"utf8",mode:384})},read(e){return us(e,"utf8")}};function jc(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function Dc(e,n,t=Gt){let r=te({trailer:!1}).push(jc(n));return t.mkdir(fs(e)),t.endsClean(e)||t.append(e,`
|
|
38
|
+
`),t.append(e,r),n}function ms(e){let n=e.endsWith(`
|
|
39
39
|
`)?e:e.slice(0,e.lastIndexOf(`
|
|
40
|
-
`)+1);return n===""?[]:
|
|
41
|
-
`).filter(p=>p.trim()!=="");l.push(...u),r.push({source:a,result:u.length===0?"empty":"read",detail:`${u.length} lines`})}catch(
|
|
40
|
+
`)+1);return n===""?[]:de(n).map(Oc)}function Oc(e){let n=e.exit_path;if(!xc(n))throw new Error(`death record has unknown exit_path ${JSON.stringify(n)}`);let t=e.kind;if(t!=="launcher"&&t!=="worker"&&t!=="daemon")throw new Error(`death record has unknown kind ${JSON.stringify(t)}`);return{version:N(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:N(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:N(e.exit_code),last_phase:String(e.last_phase),detail:e.detail==null?null:String(e.detail),scope:e.scope==null?null:String(e.scope),memory_ceiling:e.memory_ceiling==null?null:String(e.memory_ceiling),scope_degradation:e.scope_degradation==null?null:String(e.scope_degradation),uptime_s:N(e.uptime_s),rss_kb:N(e.rss_kb),max_rss_kb:N(e.max_rss_kb),user_cpu_us:N(e.user_cpu_us),system_cpu_us:N(e.system_cpu_us),minor_page_faults:N(e.minor_page_faults),major_page_faults:N(e.major_page_faults),voluntary_ctx_switches:N(e.voluntary_ctx_switches),involuntary_ctx_switches:N(e.involuntary_ctx_switches)}}function N(e){return typeof e=="number"?e:Number(e)}function gs(e,n=Gt){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return ms(t)}var $c=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],qt=null;function hs(e){let n=e.host??process,t=e.io??Gt,r=e.clock??(()=>new Date().toISOString()),o=n.pid,s=e.scope??Mt(process.env),i=e.phase??Sc,l=null,a=e.presenceDir===void 0?wc(fs(e.lanePath),on):e.presenceDir,c=null,u=()=>{a!==null&&(c=Bt({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),Kt(a,c))},p=y=>{if(!l){try{l=Dc(e.lanePath,Ec({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...y},Pc(n)),t)}catch{}a!==null&&c!==null&&ke(a,c)}},f={signal(y){p({exit_path:"signal",signal:y})},exit(y){p({exit_path:"exit",exit_code:y})},uncaughtException(y){p({exit_path:"uncaught-exception",detail:ps(y)})},unhandledRejection(y){p({exit_path:"unhandled-rejection",detail:ps(y)})}},k=[...(e.signals??$c).map(y=>{let _=()=>{if(f.signal(y),!(n.listenerCount?.(y)!==1||!n.kill)){n.off(y,_);try{n.kill(o,y)}catch{}}};return[y,_]}),["uncaughtException",(...y)=>f.uncaughtException(y[0])],["unhandledRejection",(...y)=>f.unhandledRejection(y[0])],["exit",(...y)=>f.exit(typeof y[0]=="number"?y[0]:null)]];for(let[y,_]of k)n.on(y,_);let b={lanePath:e.lanePath,phase(y){i=y,l||u()},currentPhase:()=>i,written:()=>l,uninstall(){for(let[y,_]of k)n.off(y,_);a!==null&&c!==null&&ke(a,c),qt===b&&(qt=null)},handlers:f};return e.setActive!==!1&&(qt=b),u(),b}function ps(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Ac,readdirSync as Lc,readFileSync as Nn,statSync as Ic,writeFileSync as Tc}from"node:fs";import{join as bs}from"node:path";var Nc=1,Wc=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],Cc=512*1024;function Mc(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??Wc,r=[],o=bs(n,Ut),s=null;try{let a=Nn(o,"utf8").trim();s=a===""?null:a,r.push({source:o,result:s?"read":"empty",detail:s})}catch(a){r.push({source:o,result:zt(a),detail:null})}let i=new Set;try{for(let a of Lc(n))/^\d+$/.test(a)&&i.add(Number(a));r.push({source:n,result:"read",detail:`${i.size} live pids`})}catch(a){r.push({source:n,result:zt(a),detail:null})}let l=[];for(let a of t)try{let u=Fc(a,e.tailBytes??Cc).split(`
|
|
41
|
+
`).filter(p=>p.trim()!=="");l.push(...u),r.push({source:a,result:u.length===0?"empty":"read",detail:`${u.length} lines`})}catch(c){r.push({source:a,result:zt(c),detail:null})}return{boot_id:s,live_pids:i,journal:l,probes:r}}function zt(e){return e.code==="ENOENT"?"absent":"unreadable"}function Fc(e,n){let t=Ic(e).size,r=Nn(e,"utf8");return t<=n?r:r.slice(r.length-n)}var Hc=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,Uc=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,Bc=/Killed (\/\S*) due to memory pressure/,Vc=/\bopid=(\d+)\b/,ys=/\bsig=(\d+)\b/,Kc=/\buid=(\d+)\b/,Jc=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,qc={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function Gc(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,s=[...n.probes.map(p=>`${p.source}: ${p.result}${p.detail?` (${p.detail})`:""}`),`boot id: anchored under ${e.boot_id??"unknown"}, host now ${n.boot_id??"unknown"} (${o?"changed":"same"})`,`parent account: ppid ${e.ppid}`,`cgroup: ${e.cgroup??"unknown"}`],i=(p,f,h,k)=>({version:Nc,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:p,confidence:f,signal:h,host_boot_changed:o,evidence:k,checked:s}),l=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],a=n.journal.find(p=>ks(p,e.pid,Hc)||ks(p,e.pid,Uc));if(a!==void 0)return i("oomd",o?"medium":"high","SIGKILL",[a,...l]);if(e.cgroup!==null)for(let p of n.journal){let f=Bc.exec(p)?.[1];if(f!==void 0){if(f===e.cgroup)return i("oomd",o?"medium":"high","SIGKILL",[p,...l]);if(e.cgroup.startsWith(`${f}/`))return i("oomd","medium","SIGKILL",[p,`the killed scope ${f} is an ancestor of this process's ${e.cgroup}`,...l])}}let c=n.journal.find(p=>Number(Vc.exec(p)?.[1])===e.pid&&ys.test(p));if(c!==void 0){let p=Number(ys.exec(c)?.[1]),f=Kc.exec(c)?.[1];return i("user-signal",o?"medium":"high",qc[p]??null,[c,...f===void 0?[]:[`sent by uid ${f}`],...l])}let u=t.find(p=>p.pid===e.ppid);if(u!==void 0&&!n.live_pids.has(e.ppid))return i("parent-death","medium",null,[`parent pid ${e.ppid} (${u.kind} ${u.id}) recorded its own death at ${u.ts} via ${u.exit_path}${u.signal?` ${u.signal}`:""}`]);if(o){let p=n.journal.find(f=>Jc.test(f));return p!==void 0?i("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,p]):i("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,"no shutdown record on any journal read: the host stopped without announcing it (a freeze or a power loss, not an orderly teardown)"])}return i("unknown","none",null,[])}function ks(e,n,t){return Number(t.exec(e)?.[1])===n}var zc=" | ";function Rs(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(zc)}function Qc(e){return{version:e.version,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.last_seen,last_phase:e.last_phase,sender_class:e.sender_class,confidence:e.confidence,signal:e.signal,host_boot_changed:e.host_boot_changed,evidence:Rs(e.evidence),checked:Rs(e.checked)}}function Yc(e){let n=te({trailer:!1});return e.map(t=>n.push(Qc(t))).join("")}function ws(e){let n=Tn(e.stateRoot),t=Ft(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??Mc({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=Jt(n,p=>s.push(p)),l=gs(rn(e.stateRoot)),a=[],c=[],u=[];for(let p of i){if(o.live_pids.has(p.pid)){c.push(p);continue}if(l.find(h=>h.pid===p.pid&&h.id===p.id)!==void 0){u.push(p),ke(n,p);continue}a.push(Gc(p,o,l,r())),ke(n,p)}return a.length>0&&Zc(t,a),{attributions:a,alive:c,self_recorded:u,skipped:s,laneText:()=>{try{return Nn(t,"utf8")}catch{return""}}}}function _s(e){let n=e.skipped.length===0?"":` | unreadable anchors=${e.skipped.join(",")}`;if(e.attributions.length===0)return`death reaper: no un-recorded deaths (live=${e.alive.length} self-recorded=${e.self_recorded.length})${n}`;let t=e.attributions.map(r=>` | ${r.kind} ${r.id} pid=${r.pid} ${r.sender_class}/${r.confidence} phase=${r.last_phase}`+(r.evidence[0]?` evidence="${r.evidence[0]}"`:"")).join("");return`death reaper: attributed ${e.attributions.length}${t}${n}`}function Zc(e,n){try{Ac(bs(e,".."),{recursive:!0,mode:448});let t=Xc(e),r=t===""||t.endsWith(`
|
|
42
42
|
`)?"":`
|
|
43
|
-
`;
|
|
44
|
-
`)){let o=r.replace(/\r$/,""),s=o.trim();if(!s||s.startsWith("#"))continue;let i=o.indexOf(":");if(i<0)continue;let l=o.length-o.trimStart().length,a=o.slice(0,i).trim();if(!a)continue;let
|
|
45
|
-
`||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=
|
|
43
|
+
`;Tc(e,`${t}${r}${Yc(n)}`,{encoding:"utf8",mode:384})}catch{}}function Xc(e){try{return Nn(e,"utf8")}catch{return""}}import{join as eu}from"node:path";var nu=[".red","redskilled"],z=448;function Re(e){return eu(e,...nu)}import{execFileSync as gu}from"node:child_process";import{readFileSync as hu}from"node:fs";import{dirname as Ds,join as yu}from"node:path";import{existsSync as tu,readFileSync as Pk}from"node:fs";import{dirname as ru,join as ou}from"node:path";function vs(e,n){let t=e;for(let r=0;r<16;r++){let o=ou(t,n);if(tu(o))return o;let s=ru(t);if(s===t)break;t=s}return null}function su(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function $e(e,n){let t=[];for(let r of e.split(`
|
|
44
|
+
`)){let o=r.replace(/\r$/,""),s=o.trim();if(!s||s.startsWith("#"))continue;let i=o.indexOf(":");if(i<0)continue;let l=o.length-o.trimStart().length,a=o.slice(0,i).trim();if(!a)continue;let c=o.slice(i+1).trim();for(;t.length&&t[t.length-1].indent>=l;)t.pop();if(t.push({indent:l,key:a}),c&&t.map(p=>p.key).join(".")===n)return su(c)}}import{createHash as iu}from"node:crypto";var lu="project.name";function Ss(e){let n=$e(e,lu)?.trim();return n===void 0||n===""?void 0:n}var au=8,Es="project";function Ps(e){let n=fu(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:du(e.remoteUrl)??{name:cu(e.checkoutPath,n),source:"basename"},o=pu(n??Qt(e.checkoutPath));return{name:r.name,slug:`${uu(r.name)}-${o}`,hash:o,source:r.source}}function js(e){let n=(e??"").trim();if(n==="")return;let t=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),r=/^[^/]*?:(?!\d)(.+)$/.exec(t),s=(r?r[1]:t.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(i=>i.trim()).filter(i=>i!=="");if(s.length!==0)return s.slice(-2).join("/")}function du(e){let n=js(e);return n===void 0?void 0:{name:n,source:"remote"}}function cu(e,n){let t=n===void 0?"":xs(mu(n));if(t!=="")return t;let r=xs(Qt(e));return r===""?Es:r}function uu(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?Es:t}function pu(e){return iu("sha256").update(e).digest("hex").slice(0,au)}function fu(e){let n=Qt(e??"");return n===""?void 0:n}function Qt(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function xs(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function mu(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var ku=2e3;function Os(e){return Ru(e).name}function Ru(e){let n=Zt(e),t=Yt(e,["rev-parse","--absolute-git-dir"])??Yt(e,["rev-parse","--git-common-dir"]),r=Yt(e,["remote","get-url","origin"]);return Ps({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function Zt(e){let n=vs(e,yu(".red","config.yaml"));if(n==null)return{};let t;try{t=hu(n,"utf8")}catch{return{}}let r=Ss(t),o=Ds(Ds(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function Yt(e,n){try{let t=gu("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:ku}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as ta}from"node:crypto";import{spawn as Gg}from"node:child_process";import{mkdir as zg,rm as Qg}from"node:fs/promises";import{dirname as Yg}from"node:path";import{createHash as _u}from"node:crypto";import{constants as rr}from"node:fs";import{mkdir as vu,open as xu}from"node:fs/promises";import{createConnection as Su}from"node:net";import{tmpdir as Eu}from"node:os";import{dirname as Pu,join as sn}from"node:path";var bu="toon";function Ls(e){return e.trimStart().startsWith("{")?"json":"toon"}function er(e){let n=0;for(;e[n]===`
|
|
45
|
+
`||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=Ls(t);if(r==="json"){let s=t.indexOf(`
|
|
46
46
|
`);return s<0?null:{frame:t.slice(0,s),dialect:r,rest:t.slice(s+1)}}let o=t.indexOf(`
|
|
47
47
|
|
|
48
|
-
`);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function
|
|
48
|
+
`);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function nr(e){let n=Ls(e)==="json"?Xt:$s,t=n===Xt?$s:Xt;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function Xt(e){return JSON.parse(e)}function $s(e){return G(e)}function tr(e,n){if(n==="toon"){let t=wu(e);if(t!==null)return t.endsWith(`
|
|
49
49
|
`)?`${t}
|
|
50
50
|
`:`${t}
|
|
51
51
|
|
|
52
52
|
`}return`${JSON.stringify(e)}
|
|
53
|
-
`}function uu(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=I(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function Ss(e,n){return!vs(e)||!vs(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function vs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Es=new Set;function Ps(e){return Es.has(e)?"json":cu}function js(e){Es.add(e)}var ku=108;async function In(e,n,t="resident server"){let r=e.wire,o=r??Ps(e.socketPath),s=await Ds(e,n,t,o);return r||o==="json"||!Ss(n,s)?s:(js(e.socketPath),await Ds(e,n,t,"json"))}async function Ds(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=hu(e.socketPath),a=!1,d="",u=setTimeout(()=>{p(()=>i(new Error(`${t} timed out`))),l.destroy()},o);function p(f){a||(a=!0,clearTimeout(u),f())}l.on("connect",()=>{l.write(Gt(n,r))}),l.on("data",f=>{d+=f.toString("utf8");let g=Kt(d);g&&(d=g.rest,p(()=>{try{s(qt(g.frame))}catch(k){i(k)}}),l.end())}),l.on("error",f=>p(()=>i(f))),l.on("close",()=>{a||p(()=>i(new Error(`${t} closed without response`)))})})}function Os(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=Kt(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(Gt(l,s.dialect))}catch{}};(async()=>{let l;try{l=qt(s.frame),await n(l,i)}catch(a){t(a,l,i)}finally{e.end()}})()})}async function Ls(e){await fu(yu(e),{recursive:!0,mode:448});try{return await mu(e,zt.O_CREAT|zt.O_EXCL|zt.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}function W(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var Ru="/tmp";function Tn(e){let n=e.env??process.env,t=pu("sha256").update(e.key).digest("hex").slice(0,20),r=a=>on(a,e.socketFileName).length<ku,o=n.XDG_RUNTIME_DIR;if(o){let a=on(o,"red-skills",t);if(r(a))return a}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=on(`red-skills-${s}`,t),l=on(gu(),i);return r(l)||process.platform==="win32"?l:on(Ru,i)}te();import{homedir as Hu}from"node:os";import{join as rr}from"node:path";import{spawnSync as Vu}from"node:child_process";import{createHash as Bu}from"node:crypto";import{existsSync as Ju}from"node:fs";import{mkdir as Cs,readFile as Ku,writeFile as qu}from"node:fs/promises";import{dirname as Gu}from"node:path";var an="@reddb-io/red-skills",Ou="https://registry.npmjs.org",Lu="canary",$e=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function $u(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function Mn(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return Fn(r,$u(n,t,o))}function Au(e){return e==="dev"?["rsp"]:[]}function Iu(e){return`${e}.bundle.min.mjs`}function Tu(e){return Fn("dist",Iu(e))}function Nu(e,n="stable"){return`${an}@${n==="canary"?Lu:e}`}function Wu(e=an){return`${Ou}/${e.replace("/","%2F")}`}async function tr(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=Mn({plugin:t,version:r,cacheDir:o,channel:s}),l=Au(t),a=l.map(f=>Mn({plugin:f,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await Cu(e,a))return i;let d=Nu(r,s),u=Fn(o,`.staging-${t}-${s==="canary"?"canary":r}`),p;try{p=await e.materialize(d,u)}catch(f){throw Ws(f,d)}for(let f of[t,...l]){let g=Tu(f),k=Fn(p,g);if(!await e.exists(k))throw new $e("bundle-missing",`npm package ${d} has no ${g}`);let y=f===t?i:Mn({plugin:f,version:r,cacheDir:o,channel:s});await e.writeFile(y,await e.readFile(k))}return i}async function Cu(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function Ts(e,n,t=an){let r;try{r=await e.fetchText(Wu(t))}catch(s){throw Ws(s,t)}let o=Mu(r);return{sameMajor:Fu(o,n),newest:Uu(o)}}function Mu(e){let n;try{n=JSON.parse(e)}catch{return[]}if(typeof n!="object"||n===null)return[];let t=n.versions;return typeof t!="object"||t===null?[]:Object.keys(t)}function Fu(e,n){let t=nr(n);if(t===null)return null;let r=null;for(let o of e)nr(o)===t&&(r===null||Ns(o,r)>0)&&(r=o);return r}function Uu(e){let n=null;for(let t of e){let r=String(t).trim();nr(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||Ns(r,n)>0)&&(n=r)}return n}function nr(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function Ns(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n.trim());return!t||!r?0:Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function Ws(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new $e("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new $e("package-missing",`npm could not resolve ${n}: ${t}`,e):new $e("network",`failed to resolve ${n}: ${t}`,e)}function Fn(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}te();var zu={async materialize(e,n){await Cs(n,{recursive:!0});let t=Vu("npm",["install",e,"--prefix",n,"--no-save","--no-audit","--no-fund","--ignore-scripts","--loglevel=error"],{stdio:["ignore","ignore","pipe"],encoding:"utf8"});if(t.error)throw t.error;if(t.status!==0)throw new Error(`npm install ${e} -> ${t.status}: ${(t.stderr||"").trim()}`);return rr(n,"node_modules",...an.split("/"))},async readFile(e){return new Uint8Array(await Ku(e))},async writeFile(e,n){await Cs(Gu(e),{recursive:!0}),await qu(e,n)},async exists(e){return Ju(e)},sha256(e){return Bu("sha256").update(e).digest("hex")},async fetchText(e){let n=await fetch(e,{redirect:"follow"});if(!n.ok)throw new Error(`GET ${e} -> ${n.status}`);return await n.text()}},Qu="redskilled";function Yu(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||rr(e.HOME||Hu(),".cache");return rr(n,"red-skills","bundles")}async function Zu(e={},n={},t={}){let r=ce(e,n);if(Y(r))return r;let o=t.env??n.env??process.env;try{await tr(t.bundleIO??zu,{plugin:Qu,version:t.version??"",cacheDir:Yu(o)})}catch{return r}return ce(e,n)}async function Ms(e={},n={},t={}){let r=await Zu(e,n,t);if(Y(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(te(),Is));throw new o(r)}import{randomUUID as Zn}from"node:crypto";import{mkdir as vh,rm as Vl}from"node:fs/promises";import{createServer as xh}from"node:net";import{dirname as Sh}from"node:path";import{totalmem as Xu}from"node:os";function Fs(e){let n=0,t=0,r=0,o=[],s=[];for(let i of e){let l=i.budget??{},a=!1;for(let[d,u]of[[l.memory_high,p=>n+=p],[l.memory_max,p=>t+=p]]){if(d==null)continue;let p=Ae(d);p==null?a=!0:u(p)}l.cpu_weight!=null&&(r+=l.cpu_weight),a&&o.push(i.worker_id),i.isolated||s.push(i.worker_id)}return{version:1,worker_count:e.length,memory_high_bytes:n,memory_max_bytes:t,cpu_weight_total:r,unaccounted_workers:o.sort(),unisolated_workers:s.sort()}}function Ae(e){let n=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!n)return null;let t={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[n[2].toLowerCase()];return Math.round(Number(n[1])*t)}function Us(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&Number.isInteger(n.worker_count)&&typeof n.memory_high_bytes=="number"&&typeof n.memory_max_bytes=="number"&&typeof n.cpu_weight_total=="number"&&Array.isArray(n.unaccounted_workers)&&Array.isArray(n.unisolated_workers)}var ep="REDSKILLED_MEMORY_CEILING",np="REDSKILLED_WORKER_CEILING",tp=.7;function Hs(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return Ae(n)}function or(e){let n=0,t=[];for(let r of e){let o=Hs(r.budget);o===null?t.push(r.worker_id):o!==void 0&&(n+=o)}return{worker_count:e.length,memory_bytes:n,unaccounted_workers:t.sort()}}function Vs(e){let{ceiling:n}=e,t=or(e.workers),r=Hs(e.budget),o=r===void 0?null:r,s=t.memory_bytes+(r??0),i=t.worker_count+1,l=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",a=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,d=(u,p)=>({version:1,admitted:!1,verdict:u,reason:p,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s});return n.worker_count!=null&&i>n.worker_count?d("refused-over-worker-ceiling",`redskilled refused this Worker${l}: it would be Worker ${i} past a host ceiling of ${n.worker_count} Worker(s), and ${a}`):n.memory_bytes!=null&&r===null?d("refused-unaccountable-budget",`redskilled refused this Worker${l}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${n.memory_bytes} bytes, and ${a}`):n.memory_bytes!=null&&s>n.memory_bytes?d("refused-over-memory-ceiling",`redskilled refused this Worker${l}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${n.memory_bytes} bytes, and ${a}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${l}: ${s} bytes of declared Worker memory against a host ceiling of ${n.memory_bytes??"unbounded"} bytes, and ${a}`,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function Bs(e=process.env,n=Xu()){let t=(e[ep]??"").trim(),r=(e[np]??"").trim(),o=op(r);if(t!==""){let s=rp(t,n);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(n*tp),worker_count:o,source:r!==""?"declared":"host-fraction"}}function rp(e,n){let t=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(t))return null;let r=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return r?Math.floor(n*(Number(r[1])/100)):Ae(e)??void 0}function op(e){if(e===""||["infinity","none","off","unbounded"].includes(e.toLowerCase()))return null;let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:null}import{appendFile as sp,mkdir as ip,open as lp,readFile as ap,stat as dp,truncate as Js}from"node:fs/promises";import{dirname as cp}from"node:path";var Ks="redskilled.events.toonl";function up(e){let n=e.worker.budget??{};return{version:1,ts:e.ts,event:e.event,worker_id:e.worker.worker_id,project_label:e.worker.project_label,pid:e.worker.pid,workspace_path:e.worker.workspace_path,log_path:e.worker.log_path??null,isolated:e.worker.isolated,unit:e.worker.unit??null,memory_high:n.memory_high??null,memory_max:n.memory_max??null,cpu_weight:n.cpu_weight??null,detail:e.detail??null,exit_code:e.exitCode??null,signal:e.signal??null,reason:e.reason??null}}var pp="daemon:";function fp(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${pp}${e.pid}`,project_label:"",pid:e.pid,workspace_path:e.socketPath,log_path:null,isolated:!1,unit:null,memory_high:null,memory_max:null,cpu_weight:null,detail:e.detail,exit_code:null,signal:e.signal??null,reason:e.reason}}function qs(e){let n=ne({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await ip(cp(e),{recursive:!0,mode:448}),await mp(e),await sp(e,n.push(kp(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(up(o)),recordDaemonStop:o=>r(fp(o)),read:()=>hp(e),flush:async()=>{await t}}}async function mp(e){let n;try{n=(await dp(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await lp(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let s=n;s>0;s-=t){let i=Math.min(t,s),l=Buffer.alloc(i);await r.read(l,0,i,s-i);let a=l.lastIndexOf(10);if(a>=0){await Js(e,s-i+a+1);return}}await Js(e,0)}finally{await r.close()}}async function hp(e){let n;try{n=await ap(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return gp(n)}function gp(e){let n=e.split(`
|
|
54
|
-
`);return n.pop(),n.length===0?[]:
|
|
53
|
+
`}function wu(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=I(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function Is(e,n){return!As(e)||!As(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function As(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ts=new Set;function Ns(e){return Ts.has(e)?"json":bu}function Ws(e){Ts.add(e)}var ju=108;async function Wn(e,n,t="resident server"){let r=e.wire,o=r??Ns(e.socketPath),s=await Cs(e,n,t,o);return r||o==="json"||!Is(n,s)?s:(Ws(e.socketPath),await Cs(e,n,t,"json"))}async function Cs(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=Su(e.socketPath),a=!1,c="",u=setTimeout(()=>{p(()=>i(new Error(`${t} timed out`))),l.destroy()},o);function p(f){a||(a=!0,clearTimeout(u),f())}l.on("connect",()=>{l.write(tr(n,r))}),l.on("data",f=>{c+=f.toString("utf8");let h=er(c);h&&(c=h.rest,p(()=>{try{s(nr(h.frame))}catch(k){i(k)}}),l.end())}),l.on("error",f=>p(()=>i(f))),l.on("close",()=>{a||p(()=>i(new Error(`${t} closed without response`)))})})}function Ms(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=er(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(tr(l,s.dialect))}catch{}};(async()=>{let l;try{l=nr(s.frame),await n(l,i)}catch(a){t(a,l,i)}finally{e.end()}})()})}async function Fs(e){await vu(Pu(e),{recursive:!0,mode:448});try{return await xu(e,rr.O_CREAT|rr.O_EXCL|rr.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}function W(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var Du="/tmp";function Cn(e){let n=e.env??process.env,t=_u("sha256").update(e.key).digest("hex").slice(0,20),r=a=>sn(a,e.socketFileName).length<ju,o=n.XDG_RUNTIME_DIR;if(o){let a=sn(o,"red-skills",t);if(r(a))return a}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=sn(`red-skills-${s}`,t),l=sn(Eu(),i);return r(l)||process.platform==="win32"?l:sn(Du,i)}re();import{homedir as Zu}from"node:os";import{join as ur}from"node:path";import{spawnSync as Xu}from"node:child_process";import{createHash as ep}from"node:crypto";import{existsSync as np}from"node:fs";import{mkdir as qs,readFile as tp,writeFile as rp}from"node:fs/promises";import{dirname as op}from"node:path";var dn="@reddb-io/red-skills",Fu="https://registry.npmjs.org",Hu="canary",Ae=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function Uu(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function Un(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return Bn(r,Uu(n,t,o))}function Bu(e){return e==="dev"?["rsp"]:[]}function Vu(e){return`${e}.bundle.min.mjs`}function Ku(e){return Bn("dist",Vu(e))}function Ju(e,n="stable"){return`${dn}@${n==="canary"?Hu:e}`}function qu(e=dn){return`${Fu}/${e.replace("/","%2F")}`}async function cr(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=Un({plugin:t,version:r,cacheDir:o,channel:s}),l=Bu(t),a=l.map(f=>Un({plugin:f,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await Gu(e,a))return i;let c=Ju(r,s),u=Bn(o,`.staging-${t}-${s==="canary"?"canary":r}`),p;try{p=await e.materialize(c,u)}catch(f){throw Js(f,c)}for(let f of[t,...l]){let h=Ku(f),k=Bn(p,h);if(!await e.exists(k))throw new Ae("bundle-missing",`npm package ${c} has no ${h}`);let b=f===t?i:Un({plugin:f,version:r,cacheDir:o,channel:s});await e.writeFile(b,await e.readFile(k))}return i}async function Gu(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function Vs(e,n,t=dn){let r;try{r=await e.fetchText(qu(t))}catch(s){throw Js(s,t)}let o=zu(r);return{sameMajor:Qu(o,n),newest:Yu(o)}}function zu(e){let n;try{n=JSON.parse(e)}catch{return[]}if(typeof n!="object"||n===null)return[];let t=n.versions;return typeof t!="object"||t===null?[]:Object.keys(t)}function Qu(e,n){let t=dr(n);if(t===null)return null;let r=null;for(let o of e)dr(o)===t&&(r===null||Ks(o,r)>0)&&(r=o);return r}function Yu(e){let n=null;for(let t of e){let r=String(t).trim();dr(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||Ks(r,n)>0)&&(n=r)}return n}function dr(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function Ks(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n.trim());return!t||!r?0:Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function Js(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Ae("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Ae("package-missing",`npm could not resolve ${n}: ${t}`,e):new Ae("network",`failed to resolve ${n}: ${t}`,e)}function Bn(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}re();var sp={async materialize(e,n){await qs(n,{recursive:!0});let t=Xu("npm",["install",e,"--prefix",n,"--no-save","--no-audit","--no-fund","--ignore-scripts","--loglevel=error"],{stdio:["ignore","ignore","pipe"],encoding:"utf8"});if(t.error)throw t.error;if(t.status!==0)throw new Error(`npm install ${e} -> ${t.status}: ${(t.stderr||"").trim()}`);return ur(n,"node_modules",...dn.split("/"))},async readFile(e){return new Uint8Array(await tp(e))},async writeFile(e,n){await qs(op(e),{recursive:!0}),await rp(e,n)},async exists(e){return np(e)},sha256(e){return ep("sha256").update(e).digest("hex")},async fetchText(e){let n=await fetch(e,{redirect:"follow"});if(!n.ok)throw new Error(`GET ${e} -> ${n.status}`);return await n.text()}},ip="redskilled";function lp(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||ur(e.HOME||Zu(),".cache");return ur(n,"red-skills","bundles")}async function ap(e={},n={},t={}){let r=ue(e,n);if(Y(r))return r;let o=t.env??n.env??process.env;try{await cr(t.bundleIO??sp,{plugin:ip,version:t.version??"",cacheDir:lp(o)})}catch{return r}return ue(e,n)}async function Gs(e={},n={},t={}){let r=await ap(e,n,t);if(Y(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(re(),Bs));throw new o(r)}import{randomUUID as rt}from"node:crypto";import{mkdir as Mg,rm as Xl}from"node:fs/promises";import{createServer as Fg}from"node:net";import{dirname as Hg}from"node:path";import{totalmem as dp}from"node:os";function zs(e){let n=0,t=0,r=0,o=[],s=[];for(let i of e){let l=i.budget??{},a=!1;for(let[c,u]of[[l.memory_high,p=>n+=p],[l.memory_max,p=>t+=p]]){if(c==null)continue;let p=Le(c);p==null?a=!0:u(p)}l.cpu_weight!=null&&(r+=l.cpu_weight),a&&o.push(i.worker_id),i.isolated||s.push(i.worker_id)}return{version:1,worker_count:e.length,memory_high_bytes:n,memory_max_bytes:t,cpu_weight_total:r,unaccounted_workers:o.sort(),unisolated_workers:s.sort()}}function Le(e){let n=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!n)return null;let t={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[n[2].toLowerCase()];return Math.round(Number(n[1])*t)}function Qs(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&Number.isInteger(n.worker_count)&&typeof n.memory_high_bytes=="number"&&typeof n.memory_max_bytes=="number"&&typeof n.cpu_weight_total=="number"&&Array.isArray(n.unaccounted_workers)&&Array.isArray(n.unisolated_workers)}var cp="REDSKILLED_MEMORY_CEILING",up="REDSKILLED_WORKER_CEILING",pp=.7;function Ys(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return Le(n)}function Vn(e){let n=0,t=[];for(let r of e){let o=Ys(r.budget);o===null?t.push(r.worker_id):o!==void 0&&(n+=o)}return{worker_count:e.length,memory_bytes:n,unaccounted_workers:t.sort()}}function Zs(e){let{ceiling:n}=e,t=Vn(e.workers),r=Ys(e.budget),o=r===void 0?null:r,s=t.memory_bytes+(r??0),i=t.worker_count+1,l=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",a=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,c=(u,p)=>({version:1,admitted:!1,verdict:u,reason:p,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s});return n.worker_count!=null&&i>n.worker_count?c("refused-over-worker-ceiling",`redskilled refused this Worker${l}: it would be Worker ${i} past a host ceiling of ${n.worker_count} Worker(s), and ${a}`):n.memory_bytes!=null&&r===null?c("refused-unaccountable-budget",`redskilled refused this Worker${l}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${n.memory_bytes} bytes, and ${a}`):n.memory_bytes!=null&&s>n.memory_bytes?c("refused-over-memory-ceiling",`redskilled refused this Worker${l}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${n.memory_bytes} bytes, and ${a}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${l}: ${s} bytes of declared Worker memory against a host ceiling of ${n.memory_bytes??"unbounded"} bytes, and ${a}`,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function Xs(e){let n=e.budget?.memory_max??e.budget?.memory_high;if(n!=null)return{memory_max:n,reason:`the client declared this Worker's memory ceiling (${n}), so the host derived none`};if(e.ceiling.memory_bytes==null)return{memory_max:null,reason:"this host admits Workers against no memory ceiling, so there is no accounting to derive a per-Worker ceiling from; the daemon's RSS sampling floor is the only remaining ceiling"};let t=Vn(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,s=o==null?r:Math.floor(e.ceiling.memory_bytes/o),i=Math.min(r,s);if(i<=0)return{memory_max:null,reason:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes is already fully committed to ${t.worker_count} Worker(s), so no positive per-Worker ceiling can be derived; the daemon's RSS sampling floor is the only remaining ceiling`};let l=o==null?`the headroom under this host's memory ceiling of ${e.ceiling.memory_bytes} bytes`:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes shared across its ${o} Worker slot(s)`;return{memory_max:String(i),reason:`derived from ${l} (ceiling source: ${e.ceiling.source})`}}function ei(e=process.env,n=dp()){let t=(e[cp]??"").trim(),r=(e[up]??"").trim(),o=mp(r);if(t!==""){let s=fp(t,n);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(n*pp),worker_count:o,source:r!==""?"declared":"host-fraction"}}function fp(e,n){let t=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(t))return null;let r=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return r?Math.floor(n*(Number(r[1])/100)):Le(e)??void 0}function mp(e){if(e===""||["infinity","none","off","unbounded"].includes(e.toLowerCase()))return null;let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:null}import{appendFile as gp,mkdir as hp,open as yp,readFile as kp,stat as Rp,truncate as ni}from"node:fs/promises";import{dirname as bp}from"node:path";var ti="redskilled.events.toonl";function wp(e){let n=e.worker.budget??{};return{version:1,ts:e.ts,event:e.event,worker_id:e.worker.worker_id,project_label:e.worker.project_label,pid:e.worker.pid,workspace_path:e.worker.workspace_path,log_path:e.worker.log_path??null,isolated:e.worker.isolated,unit:e.worker.unit??null,memory_high:n.memory_high??null,memory_max:n.memory_max??null,cpu_weight:n.cpu_weight??null,detail:e.detail??null,exit_code:e.exitCode??null,signal:e.signal??null,reason:e.reason??null}}var _p="daemon:";function vp(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${_p}${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 ri(e){let n=te({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await hp(bp(e),{recursive:!0,mode:448}),await xp(e),await gp(e,n.push(jp(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(wp(o)),recordDaemonStop:o=>r(vp(o)),read:()=>Sp(e),flush:async()=>{await t}}}async function xp(e){let n;try{n=(await Rp(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await yp(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let s=n;s>0;s-=t){let i=Math.min(t,s),l=Buffer.alloc(i);await r.read(l,0,i,s-i);let a=l.lastIndexOf(10);if(a>=0){await ni(e,s-i+a+1);return}}await ni(e,0)}finally{await r.close()}}async function Sp(e){let n;try{n=await kp(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return Ep(n)}function Ep(e){let n=e.split(`
|
|
54
|
+
`);return n.pop(),n.length===0?[]:de(`${n.join(`
|
|
55
55
|
`)}
|
|
56
|
-
`).filter(
|
|
57
|
-
`}function Tp(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return G(n)}catch{return null}}}function Np(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||n.scope!=="machine"||!Number.isInteger(n.pid)||n.pid<=0||!Number.isInteger(n.uid))return!1;for(let t of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}function lr(e,n){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(n)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((t,r)=>{if(typeof t!="string"||t==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${r} of project ${JSON.stringify(n)} is not`);return t})}function ar(e,n){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error(`redskilled needs a launch env to be a map of strings to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}`);let t={};for(let[r,o]of Object.entries(e)){if(r==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(n)} to be named`);if(typeof o!="string")throw new Error(`redskilled needs every launch env value to be a string, and ${JSON.stringify(r)} of project ${JSON.stringify(n)} is ${JSON.stringify(o)}`);t[r]=o}return t}var Wp=3e5,Cp=.5,cr=class extends Error{constructor(t){super(`redskilled already holds a registration for project ${JSON.stringify(t.project_label)}, registered at ${t.registered_at} for a target of ${t.target} and standing until ${t.renew_by}: a project contributes one registration, so a second one is refused rather than silently replacing the first`);this.held=t;this.name="RedskilledProjectRegisteredError"}};function ai(e,n){if(n.held!=null)throw new cr(n.held);let t=dr(e.project_label,"a project label"),r=dr(e.selector,"a selector"),o=lr(e.argv,t),s=ar(e.env,t),i=dr(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.target)}`);let l=e.renew_within_ms??Wp;if(!Number.isFinite(l)||l<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let a=Date.parse(n.now);if(!Number.isFinite(a))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(n.now)}`);return{version:1,project_label:t,selector:r,argv:o,workspace_path:i,env:s,target:e.target,registered_at:new Date(a).toISOString(),renew_within_ms:l,renew_by:new Date(a+l).toISOString(),renewed_at:new Date(a).toISOString(),renewals:0,launch_revision:0}}var Vn=class extends Error{constructor(t){super(`redskilled holds no registration for project ${JSON.stringify(t)} to renew: it lapsed or was never held, and a renewal never mints a record \u2014 register again, stating the selector, the argv and the target`);this.projectLabel=t;this.name="RedskilledProjectUnregisteredError"}};function di(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(n.now)}`);let r=n.renew_within_ms??e.renew_within_ms;if(!Number.isFinite(r)||r<=0)throw new Error(`redskilled needs a positive renewal window to renew project ${JSON.stringify(e.project_label)}, not ${JSON.stringify(n.renew_within_ms)}`);let o=n.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:lr(n.launch.argv,e.project_label),env:ar(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1};return{...e,...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1}}function ci(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(n.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,n.liveWorkers??0),s=n.queue,i=s!=null&&s.outcome==="counted"?s.depth:null,l=i!=null&&i>0?"open-work":o>0?"live-worker":null;if(l==null){let a=i===0?"drained":"uncounted";return{registration:e,verdict:a,detail:a==="drained"?`project ${r} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${r}, and an uncounted queue never sustains a registration \u2014 it stands on its own deadline of ${e.renew_by}`}}return{registration:{...e,renew_by:new Date(t+e.renew_within_ms).toISOString(),sustained_at:new Date(t).toISOString(),sustains:(e.sustains??0)+1,sustained_by:l},verdict:l,detail:l==="open-work"?`project ${r} has ${i} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function Mp(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function ui(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*Cp;if(r(t))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return r(o)?"self-renewing":"running-on"}function pi(e,n){let t=[],r=[];for(let o of e)(Mp(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function ur(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.project_label=="string"&&typeof n.selector=="string"&&Array.isArray(n.argv)&&n.argv.every(t=>typeof t=="string")&&typeof n.workspace_path=="string"&&Number.isInteger(n.target)&&typeof n.registered_at=="string"&&typeof n.renew_within_ms=="number"&&typeof n.renew_by=="string"&&(n.renewed_at===void 0||typeof n.renewed_at=="string")&&(n.renewals===void 0||Number.isInteger(n.renewals))&&(n.env===void 0||Fp(n.env))&&(n.launch_revision===void 0||Number.isInteger(n.launch_revision))&&(n.sustained_at===void 0||typeof n.sustained_at=="string")&&(n.sustains===void 0||Number.isInteger(n.sustains))&&(n.sustained_by===void 0||n.sustained_by==="open-work"||n.sustained_by==="live-worker")}function Fp(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function dr(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var Up={ping:"host-read","host-state":"host-read","statusline-payload":"host-read",shutdown:"daemon-life","worker-start":"project-write","worker-stop":"project-write","worker-recycle":"project-write","worker-steer":"project-write","worker-heartbeat":"project-write","project-register":"project-write","project-renew":"project-write","project-deregister":"project-write"};function fi(e){return`worker-${e}`}function mi(e){let n=Up[e.op]??"project-write",t=e.sessionProject??null,r=e.targetProject??null,o={version:1,op:e.op,reach:n,session_project:t,target_project:r};return n==="host-read"?{...o,permitted:!0,verdict:"permitted-host-read",reason:`redskilled permitted ${e.op}: a session reads the whole host, whichever project it was started in`}:n==="daemon-life"?{...o,permitted:!0,verdict:"permitted-daemon-life",reason:`redskilled permitted ${e.op}: it acts on the daemon's own process, not on any project's Workers`}:t==null||t===""?{...o,permitted:!0,verdict:"permitted-unattributed",reason:`redskilled permitted ${e.op}: the session named no project of its own, so there is nothing to refuse it against`}:r!=null&&r===t?{...o,permitted:!0,verdict:"permitted-own-project",reason:`redskilled permitted ${e.op}: the target belongs to project ${JSON.stringify(t)}, which is this session's own`}:{...o,permitted:!1,verdict:"refused-cross-project",reason:`redskilled refused ${e.op} from a session in project ${JSON.stringify(t)}: ${r==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(r)}`}. A session reads the whole host and writes only its own project.`}}import{execFileSync as Hp}from"node:child_process";import{readFileSync as Vp,readdirSync as Bp}from"node:fs";import{join as Jp}from"node:path";function dn(e){let n=e.budget??{},t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let s=Ae(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function hi(e){let n=[],t=[];for(let r of e.workers){let o=dn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(r.budget?.memory_max??r.budget?.memory_high)==null?"this Worker declared no memory budget, so the sampler has no ceiling to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let s=e.rss[r.worker_id];if(typeof s!="number"||!Number.isFinite(s)){t.push({worker_id:r.worker_id,reason:"the host produced no RSS reading for this Worker on this tick, and an unmeasured Worker is never killed on suspicion"});continue}s<=o.bytes||n.push(Kp(r,o,s))}return{terminations:n,unenforceable:t}}function Kp(e,n,t){let r=`Worker ${JSON.stringify(e.worker_id)} of project ${JSON.stringify(e.project_label)}`;return{version:1,worker_id:e.worker_id,project_label:e.project_label,outcome:"terminated-over-memory-budget",classification:"budget-exceeded",stall:!1,budget_name:n.name,budget_declared:n.declared,budget_bytes:n.bytes,observed_rss_bytes:t,workspace_path:e.workspace_path,reason:`redskilled terminated ${r}: its tree RSS of ${t} bytes exceeded its ${n.name} budget of ${n.declared} (${n.bytes} bytes). This is a budget termination, not a stall, and the work in ${JSON.stringify(e.workspace_path)} is handed forward.`}}var qp=4096;function gi(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{}};if(e.length===0)return r;let o=Gp(t,n);if(o.size===0)return r;let s=new Map;for(let a of o.values()){let d=s.get(a.ppid);d?d.push(a.pid):s.set(a.ppid,[a.pid])}let i={},l={};for(let a of e){if(!o.has(a.pid))continue;let d=0,u=0,p=[a.pid],f=new Set;for(;p.length>0;){let g=p.pop();if(f.has(g))continue;f.add(g);let k=o.get(g);if(k){d+=k.rssBytes,u+=k.cpuSeconds;for(let y of s.get(g)??[])p.push(y)}}i[a.worker_id]=d,l[a.worker_id]=u}return{rss:i,cpu_seconds:l}}function Gp(e,n){return n.procRoot!=null||e==="linux"?ef(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?Zp(zp(n.psTable)):new Map}function zp(e){try{return(e??Qp)()}catch{return""}}function Qp(){return Hp("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Yp=1024;function Zp(e){let n=new Map;for(let t of e.split(`
|
|
58
|
-
`)){let r=t.trim().split(/\s+/);if(r.length!==4)continue;let[o,s,i]=r.slice(0,3).map(Number);if(![o,s,i].every(a=>a!=null&&Number.isSafeInteger(a)&&a>=0))continue;let l=
|
|
59
|
-
`),aliases:s,closed_since:o}}function of(e,n,t){let r=Ie(n),o=Ie(r.data),s=Array.isArray(r.errors)?r.errors.map(Ie):[],i=af(o.rateLimit,s),l=e.aliases.map(({alias:a,search_alias:d,project:u})=>{let p=u.owner+"/"+u.name,f=o[a],g=s.find(k=>yi(k.path,a)||yi(k.path,d));if(vi(f)){let k=ki(f.open_pull_requests),y=ki(f.open_issues),b=df(o[d]);if(k!=null&&y!=null&&b!=null)return{project_label:u.project_label,repository:p,outcome:"counted",counts:{open_pull_requests:k,open_issues:y,recently_closed:b},detail:`counted ${p} for project ${JSON.stringify(u.project_label)}`}}return i.exhausted||_i(g)?{project_label:u.project_label,repository:p,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${p} answered, so this project has no counts rather than zero counts${i.reset_at==null?"":`; the quota resets at ${i.reset_at}`}`}:{project_label:u.project_label,repository:p,outcome:"unreachable",counts:null,detail:`${p} is not reachable with the host token: ${fr(g?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:l.length,rate_limit:i,projects:l}}function sf(e){return{version:1,fetched_at:e,request_count:0,project_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}async function Ri(e){if(e.projects.length===0)return sf(e.now);mr(e.projects,e.hostTokenRef);let n=rf(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return of(n,t,{fetchedAt:e.now})}catch(t){let r=t instanceof Error?t.message:String(t),o=/rate limit|secondary rate|429/i.test(r);return{version:1,fetched_at:e.now,request_count:1,project_count:e.projects.length,rate_limit:{remaining:null,reset_at:null,exhausted:o},projects:e.projects.map(s=>({project_label:s.project_label,repository:`${s.owner}/${s.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${s.owner}/${s.name} answered: ${r}`}))}}}function bi(e){let n=e.stalenessMs??12e4,t=e.activity;if(t==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:n,stale:!1,request_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[],reason:"the daemon polls no repository, so there are no counts to age"};let r=Date.parse(e.now),o=Date.parse(t.fetched_at),s=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,i=s==null||s>n;return{version:1,fetched_at:t.fetched_at,age_ms:s,threshold_ms:n,stale:t.projects.length>0&&i,request_count:t.request_count,rate_limit:t.rate_limit,projects:t.projects.map(l=>({...l,fetched_at:t.fetched_at,age_ms:s,stale:i})),reason:t.projects.length===0?"the daemon polls no repository, so there are no counts to age":s==null?"these counts carry no readable instant, so they cannot be presented as current":i?`these counts are ${s}ms old, past the ${n}ms window`:`fetched ${s}ms ago, within the ${n}ms window`}}function wi(e){let n=e.endpoint??"https://api.github.com/graphql",t=e.fetchImpl??fetch;return async r=>{let o=await t(n,{method:"POST",headers:{authorization:`bearer ${e.token}`,"content-type":"application/json",accept:"application/vnd.github+json"},body:JSON.stringify({query:r})});if(!o.ok){let s=o.headers.get("x-ratelimit-remaining"),i=o.status===429||s==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(i?": the host token's rate limit is spent":""))}return await o.json()}}function lf(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>100)throw new Error("redskilled activity fetch spans at most 100 repositories in one query");let n=new Set;for(let t of e){if(t.project_label===""||t.owner===""||t.name==="")throw new Error("redskilled activity fetch needs a project label and an owner/name for every registered project");if(n.has(t.project_label))throw new Error(`redskilled holds one repository per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function af(e,n){let t=Ie(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(_i);return{remaining:r,reset_at:o,exhausted:s||r===0}}function _i(e){if(e==null)return!1;let n=fr(e.type),t=fr(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function yi(e,n){return Array.isArray(e)&&e.includes(n)}function ki(e){let n=Ie(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function df(e){let n=Ie(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Ie(e){return vi(e)?e:{}}function vi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fr(e){return typeof e=="string"?e:""}var cf=3e4;function xi(e){let n=e.stalenessMs??cf,t=hr(e.now),r=e.sampledAt==null?null:hr(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),s=o!=null&&o<=n,i=new Set(e.reattachedWorkerIds??[]),l=e.hostState.workers.map(f=>uf(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:i.has(f.worker_id)?"reattached":"running"})),a=l.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=l.length-a.length,u=l.reduce((f,g)=>f+(g.vitals.rss_bytes??0),0),p=or(e.hostState.workers);return{version:1,generated_at:e.now,daemon:{pid:e.hostState.pid,daemon_version:e.hostState.daemon_version,protocol_version:e.hostState.protocol_version,started_at:e.hostState.started_at,machine_id_hash:e.hostState.machine_id_hash,session_key_hash:e.hostState.session_key_hash},staleness:hf({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:l.length,measuredCount:d,unmeasured:a}),host:{worker_count:l.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:p,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:u,measured_worker_count:d,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:p.memory_bytes/e.ceiling.memory_bytes},projects:mf(l),known_projects:ff(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,g)=>f.localeCompare(g)),workers:l,repository_activity:bi({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs})}}function uf(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=dn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=hr(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms:n.nowMs==null||i==null?null:Math.max(0,n.nowMs-i),state:n.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:r,sampled_at:r==null?null:n.sampledAt,age_ms:r==null?null:n.ageMs,fresh:r!=null&&n.sampleFresh},budget:{name:o?.name??null,declared:o?.declared??s,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:pf(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function pf(e){let n={last_line:null,published_at:null,source:null};return e==null||e.line.trim()===""?n:{last_line:e.line,published_at:e.published_at,source:e.source}}function ff(e){let n=new Set;for(let t of e.registrations??[])n.add(t.project_label);for(let t of e.projects)n.add(t.project_label);return[...n].sort((t,r)=>t.localeCompare(r))}function mf(e){let n=new Map;for(let t of e){let r=n.get(t.project_label)??{workers:0,declared:0,observed:0,measured:0};r.workers+=1,r.declared+=t.budget.bytes??0,r.observed+=t.vitals.rss_bytes??0,r.measured+=t.vitals.rss_bytes==null?0:1,n.set(t.project_label,r)}return[...n.entries()].map(([t,r])=>({project_label:t,worker_count:r.workers,declared_memory_bytes:r.declared,observed_rss_bytes:r.observed,measured_worker_count:r.measured})).sort((t,r)=>t.project_label.localeCompare(r.project_label))}function hf(e){let n={sampled_at:e.sampledAt,age_ms:e.ageMs,threshold_ms:e.threshold,measured_worker_count:e.measuredCount,unmeasured_workers:e.unmeasured};return e.workerCount===0?{...n,stale:!1,reason:"the host holds no Workers, so there is nothing to measure and nothing to age"}:e.sampledAt==null||e.ageMs==null?{...n,stale:!0,reason:`this answer is stale: the daemon has taken no measurement of its ${e.workerCount} live Worker(s) yet`}:e.ageMs>e.threshold?{...n,stale:!0,reason:`this answer is stale: its measurement is ${e.ageMs}ms old, past the ${e.threshold}ms staleness window`}:{...n,stale:!1,reason:`measured ${e.ageMs}ms ago, within the ${e.threshold}ms staleness window`}}function hr(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}var O={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Si(e,n=O){let t=_f(e,n),r=bf(e,n),o=wf(e,n),s=vf(e,n,r,t),i=kf(n,r,o),l={detail:"host",line:s};for(let p of i){let f=Lf(s,Rf(p,n,r,o),n.separator);if(l={detail:p,line:f},$f(f)<=n.maxWidth)break}let a=kr(l.line,n.maxWidth),d=n.verbose&&l.detail==="workers"?Pf(r,n):[],u=r.length>0?"workers":"host";return{version:1,line:a,lines:[a,...d],verbose:n.verbose,mode:n.mode,project:n.project,project_match:t,detail:l.detail,degraded:l.detail!==u||a!==l.line,stale:e.staleness.stale,generated_at:e.generated_at}}function Ei(e){let n=e.options??O,t=kr(yf,n.maxWidth);return{version:1,line:t,lines:[t],verbose:n.verbose,mode:n.mode,project:n.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}var gf="!unregistered",yf="redskilled unreachable \u2014 Worker state unknown";function kf(e,n,t){let r=[];return n.length>0&&n.length<=e.maxWorkers&&r.push("workers"),e.mode==="global"&&t.length>0&&t.length<=e.maxProjects&&r.push("projects"),r.push("host"),r}function Rf(e,n,t,r){return e==="workers"?t.map(o=>Ef(o,n)):e==="projects"?r.map(Of):[]}function bf(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function wf(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function _f(e,n){return yr(e,n.project)}function yr(e,n){return n==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(n)?e.registered_projects==null||e.registered_projects.includes(n)?"matched":"name-only":"unregistered"}function vf(e,n,t,r){let o=[];return n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(gr(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(gr(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(gr(e,n)),o.push(gf)):o.push(xf(n.project,r)),e.staleness.stale&&o.push(Sf(e)),o.join(" ")}function xf(e,n){return n==="unregistered"?`project unknown \u2014 ${e} is not registered on this host`:"project unknown \u2014 this directory resolved to no project"}function gr(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,s)=>o+s.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${U(t)}/${U(r)}`:U(t)}function Sf(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function Ef(e,n){let t=Pi(e,n),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?U(r):`${U(r)}/${U(e.budget.bytes)}`;return`${t} ${o}`}function Pf(e,n){let t=[];for(let r of e){let o=Df(r.log.last_line);o!=null&&t.push(kr(` ${jf} ${Pi(r,n)}: ${o}`,n.maxWidth))}return t}var jf="\u21B3";function Df(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}function Pi(e,n){return n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Of(e){return`${e.project_label} ${e.worker_count}w ${U(e.observed_rss_bytes)}`}function Lf(e,n,t){return[e,...n].join(t)}function $f(e){return[...e].length}function kr(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}function U(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}var Rr={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},Af=["runner","model","effort","origin","issue","phase","step","heartbeat"],If=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function ji(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...Rr};for(let r of Af){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of If){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}var Bn=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],Te={mode:"local",project:null,maxWidth:200,maxRows:16};var Tf=" ",Di="\u2588",Nf="\u25B6",Wf="\u2717",Cf="\u2591";function Oi(e,n=Te){let t=yr(e,n.project),r=Mf(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(p=>Ff(p,n)),i=Gf(s),l=o.map((p,f)=>({worker_id:p.worker_id,project_label:p.project_label,mine:n.project!=null&&p.project_label===n.project,cells:s[f],line:br(zf(s[f],i),n.maxWidth)})),a=Hf(e,n,r,t),d=r.length-o.length,u=[a.line,...l.map(p=>p.line)];return d>0&&u.push(br(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Bn,header:a,rows:l,lines:u,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Mf(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Ff(e,n){let t=e.display??Rr,r=[t.runner,t.model,t.effort].filter(o=>!!o).join(" ");return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:r===""?"":`run=${r}`,org:t.origin==null?"":`org=${t.origin}`,iss:t.issue==null?"":`iss=${t.issue}`,bar:Uf(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:qf(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:Jf(t.added,t.removed),tks:t.tokens==null?"":`tks=${Kf(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function Uf(e){let n=e.phase_total,t=e.phase_index;if(n==null||n<=0||t==null||t<0)return"";let r=Math.min(Math.floor(t),Math.floor(n));if(r>=n)return Di.repeat(Math.floor(n));let o=e.failed?Wf:Nf;return`${Di.repeat(r)}${o}${Cf.repeat(Math.floor(n)-r-1)}`}function Hf(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(u=>u.project_label===n.project),s={open_pull_requests:o?.counts?.open_pull_requests??null,recently_closed:o?.counts?.recently_closed??null,open_issues:o?.counts?.open_issues??null,stale:o?.stale===!0},i={memory_used_fraction:e.host.ceiling_used_fraction,memory_used_bytes:e.host.consumption.memory_bytes,memory_ceiling_bytes:e.host.ceiling.memory_bytes,worker_count:e.host.worker_count,worker_ceiling:e.host.ceiling.worker_count},l=Bf(t),a=o?.repository??n.project,d=[`\xBB ${a??"host"} v${e.daemon.daemon_version}`];if(r==="unregistered"&&d.push("!unregistered"),r==="name-only"&&d.push("!lapsed"),l!=null&&d.push(l),d.push(`wrk=${t.length}/${e.host.worker_count}`),d.push(i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`),d.push(Vf(i)),s.open_pull_requests!=null&&d.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&d.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&d.push(`iss=${s.open_issues}`),s.stale&&d.push("!counts stale"),e.staleness.stale){let u=e.staleness.age_ms;d.push(u==null?"!unmeasured":`!stale ${Math.round(u/1e3)}s`)}return{repo:a,project:n.project,project_match:r,version:e.daemon.daemon_version,model:l,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:br(d.join(" \xB7 "),n.maxWidth)}}function Vf(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${U(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${U(e.memory_used_bytes)}/${U(e.memory_ceiling_bytes)}${n}`}function Bf(e){for(let n of e){let t=n.display;if(t==null)continue;let r=[t.runner,t.model,t.effort].filter(o=>!!o);if(r.length>0)return r.join("\xB7")}return null}function Jf(e,n){if(e==null&&n==null)return"";let t=[];return e!=null&&e>0&&t.push(`+${e}`),n!=null&&n>0&&t.push(`-${n}`),`loc=${t.length>0?t.join(" "):"0"}`}function Kf(e){if(!Number.isFinite(e)||e<=0)return"0";let n=(t,r)=>{let o=(Math.round(t*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${r}`};return e>=1e9?n(e/1e9,"B"):e>=1e6?n(e/1e6,"M"):e>=1e3?n(e/1e3,"k"):String(Math.round(e))}function qf(e){if(e==null||!Number.isFinite(e)||e<0)return"\u2014";let n=Math.floor(e/1e3);if(n<60)return`${n}s`;let t=Math.floor(n/60);if(t<60)return`${t}m${n%60}s`;let r=Math.floor(t/60);return r<24?`${r}h${t%60}m`:`${Math.floor(r/24)}d${r%24}h`}function Gf(e){let n=Object.fromEntries(Bn.map(t=>[t,0]));for(let t of e)for(let r of Bn)n[r]=Math.max(n[r],Li(t[r]));return n}function zf(e,n){return Bn.filter(r=>n[r]>0).map(r=>Qf(e[r],n[r])).join(Tf).replace(/\s+$/,"")}function Qf(e,n){return e+" ".repeat(Math.max(0,n-Li(e)))}function Li(e){return[...e].length}function br(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}var Jn=1;async function cn(e,n){return await In(e,n,"redskilled daemon")}function $i(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.line=="string"&&Array.isArray(n.lines)&&n.lines.every(t=>typeof t=="string")&&typeof n.verbose=="boolean"&&(n.mode==="local"||n.mode==="global")&&(n.project===null||typeof n.project=="string")&&typeof n.detail=="string"&&(n.project_match===void 0||typeof n.project_match=="string")&&typeof n.degraded=="boolean"&&typeof n.stale=="boolean"&&typeof n.generated_at=="string"}function Ai(e){let n=[...e.workers??[]],t=new Map;for(let r of n)t.set(r.project_label,(t.get(r.project_label)??0)+1);return{version:1,protocol_version:Jn,daemon_version:e.daemonVersion,machine_id_hash:e.machineIdHash,session_key_hash:e.sessionKeyHash,pid:e.pid,started_at:e.startedAt,...e.scope==null?{}:{scope:e.scope},workers:n,projects:[...t.entries()].map(([r,o])=>({project_label:r,worker_count:o})).sort((r,o)=>r.project_label.localeCompare(o.project_label)),registrations:Xf(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:Fs(n),upgrade:em(e)}}function Xf(e){let n=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(n),r=e.queue??null,o=new Map(r==null?[]:r.projects.map(s=>[s.project_label,s]));return[...e.registrations??[]].map(s=>{let i=o.get(s.project_label);return{...s,...t?{renewal:ui(s,n)}:{},...r==null||i==null?{}:{last_poll:{at:r.fetched_at,outcome:i.outcome,depth:i.depth,request_count:r.request_count,detail:i.detail}}}}).sort((s,i)=>s.project_label.localeCompare(i.project_label))}function em(e){let n=e.daemonVersion,t=e.published?.version??null,r=e.published?.majorHold??null;return{running_version:n,published_version:t,published_unknown:+(t===null),newer_published:+(e.published?.newer===!0),replacement:e.published?.replacement??"none",checked_at:e.published?.checkedAt??null,checks:e.published?.checks??0,hold_reason:e.published?.holdReason??null,newest_published_version:e.published?.newest??null,major_held:+(r!==null),major_hold:r}}function Ii(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.protocol_version=="number"&&typeof n.daemon_version=="string"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&Number.isInteger(n.pid)&&typeof n.started_at=="string"&&Array.isArray(n.workers)&&Array.isArray(n.projects)&&Us(n.budget_accounting)&&(n.scope===void 0||li(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(ur))&&(n.upgrade===void 0||nm(n.upgrade))}function nm(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")&&typeof n.published_unknown=="number"&&typeof n.newer_published=="number"&&(n.replacement==="none"||n.replacement==="pending"||n.replacement==="in-progress")&&(n.checked_at===null||typeof n.checked_at=="string")&&(n.newest_published_version===void 0||n.newest_published_version===null||typeof n.newest_published_version=="string")&&(n.major_held===void 0||typeof n.major_held=="number")&&(n.checks===void 0||typeof n.checks=="number")&&(n.hold_reason===void 0||n.hold_reason===null||typeof n.hold_reason=="string")&&(n.major_hold===void 0||n.major_hold===null||tm(n.major_hold))}function tm(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.version=="string"&&Number.isInteger(n.running_major)&&Number.isInteger(n.held_major)&&typeof n.reason=="string"&&typeof n.action=="string"&&n.action.trim()!==""}import{spawnSync as Gn}from"node:child_process";import{existsSync as Sr}from"node:fs";import{delimiter as um,join as Bi}from"node:path";import{join as Ti}from"node:path";import{existsSync as rm}from"node:fs";import{createRequire as om}from"node:module";var Ni="redskilled-job-object.node",be=100;function Ne(e){return{available:!1,reason:e}}function sm(e,n,t){return[Ti(t,"prebuilds",`${e}-${n}`,Ni),Ti(t,"native","build","Release",Ni)]}function Wi(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return Ne(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??lm(),o=e.exists??rm,s=sm(n,t,r),i=s.find(d=>o(d));if(i==null)return Ne(`no Job Object addon was found for ${n}-${t} (looked in ${s.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let l=e.requireFn??om(import.meta.url),a;try{a=l(i)}catch(d){return Ne(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return im(a)?{available:!0,binding:a}:Ne(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function im(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function lm(){return new URL("..",import.meta.url).pathname}function Ci(e){let n=e??{},t=[],r=am(n);r==null&&(n.memory_max??n.memory_high)!=null&&t.push("the declared memory budget could not be reduced to bytes, so the job carries no memory ceiling");let o;return n.cpu_weight!=null&&(n.cpu_weight<be?o=Math.max(1,Math.min(100,Math.round(n.cpu_weight))):t.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${be}, and Windows CPU rate control is an absolute cap rather than a share, so no rate limit is set`)),{...r!=null?{memory_limit_bytes:r.bytes,memory_budget_name:r.name,memory_budget_declared:r.declared}:{},...o!=null?{cpu_rate_percent:o}:{},kill_on_close:!0,...t.length>0?{note:t.join("; ")}:{}}}function am(e){return dn({budget:e})}var Kn=5,Mi=19;function wr(e){return{available:!1,reason:e}}var dm="an address-space rlimit is not a resident-memory ceiling: a runtime that reserves address space it never faults in would die under a limit it never used, so no memory rlimit is set and the daemon's RSS sampling floor is the ceiling that actually holds";function Ui(e,n){let t=e??{},r=[],o;if(!n.canRenice)r.push("nice is not on this host, so no priority control was applied and the Worker competes with interactive work");else if(t.cpu_weight==null)o=Kn;else if(t.cpu_weight<be){let l=Math.round(Mi*(be-t.cpu_weight)/be);o=Math.min(Mi,Math.max(Kn,l))}else o=Kn,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${be}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Kn}`);let s=Fi(t.max_processes);s==null&&t.max_processes!=null&&r.push(`max_processes=${t.max_processes} is not a positive whole number, so no ulimit -u is set`);let i=Fi(t.cpu_seconds);return i==null&&t.cpu_seconds!=null&&r.push(`cpu_seconds=${t.cpu_seconds} is not a positive whole number, so no ulimit -t is set`),{...o!=null?{nice:o}:{},...s!=null?{max_processes:s}:{},...i!=null?{cpu_seconds:i}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:dm,...r.length>0?{note:r.join("; ")}:{}}}function Hi(e){let{limits:n}=e,t=[];return n.max_processes!=null&&t.push(`ulimit -u ${n.max_processes}`),n.cpu_seconds!=null&&t.push(`ulimit -t ${n.cpu_seconds}`),t.push(n.nice!=null&&e.nice!=null?`exec ${cm(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
|
|
60
|
-
`),e.command,...e.args]}function
|
|
61
|
-
`).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function
|
|
62
|
-
`),aliases:r}}function
|
|
63
|
-
`);for(let t=n.length-1;t>=0;t-=1){let r=n[t].replace(/\r$/,"");if(r.trim()!=="")return r}return null}import{spawn as
|
|
64
|
-
`)}function
|
|
56
|
+
`).filter(Dp).map(Op)}function oi(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,Pp(t)):n.delete(t.worker_id));return[...n.values()]}function Pp(e){let n={...e.memory_high!=null?{memory_high:e.memory_high}:{},...e.memory_max!=null?{memory_max:e.memory_max}:{},...e.cpu_weight!=null?{cpu_weight:e.cpu_weight}:{}};return{worker_id:e.worker_id,project_label:e.project_label,pid:e.pid,started_at:e.ts,workspace_path:e.workspace_path,...e.log_path!=null?{log_path:e.log_path}:{},isolated:e.isolated,...e.unit!=null?{unit:e.unit}:{},...Object.keys(n).length>0?{budget:n}:{},warnings:[]}}function jp(e){return{...e}}function Dp(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 Op(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:oe(e.project_label)??"",pid:Number(e.pid??0),workspace_path:oe(e.workspace_path)??"",log_path:oe(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:oe(e.unit),memory_high:oe(e.memory_high),memory_max:oe(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:oe(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:oe(e.signal),reason:oe(e.reason)}}function oe(e){return e==null||e===""?null:String(e)}function si(e){let n=[...e.projects].sort((i,l)=>i.project_label.localeCompare(l.project_label)),t=e.backoffUntilMs??null,r=t!=null&&e.nowMs<t,o=[],s=[];for(let i of n){let l=Math.max(0,e.live[i.project_label]??0),a=Object.prototype.hasOwnProperty.call(e.queue,i.project_label),c=a?e.queue[i.project_label]??null:null,u={project_label:i.project_label,queue_depth:c,target:i.target,live:l};if(r){o.push({...u,outcome:"backing-off",wanted:0,detail:`the host refused a Worker, so no project is asked for one again before ${new Date(t).toISOString()}`});continue}if(c==null){o.push({...u,outcome:"queue-unknown",wanted:0,detail:a?`the last poll produced no depth for project ${JSON.stringify(i.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(i.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(c===0){o.push({...u,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(i.project_label)} has nothing queued, so it is asked for no Worker`});continue}let p=Math.max(0,Math.min(Math.max(0,i.target),c)-l);if(p===0){o.push({...u,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${c}, so it asks for none`});continue}o.push({...u,outcome:"asking",wanted:p,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${c}, so it asks for ${p} more`});for(let f=0;f<p;f+=1)(s[f]??(s[f]=[])).push({project_label:i.project_label,index:l+f,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function ii(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function ai(e){let n=e.workers.map($p),t=[...new Set([...n.map(o=>o.project_label),...e.projects??[]])].filter(o=>o!=="").sort(),r=n.filter(o=>o.survives).map(o=>o.worker_id);return{version:1,running:!0,stopped:!0,reason:e.reason,socket_path:e.socketPath,daemon_version:e.daemonVersion,pid:e.pid,holding:{workers:n,projects:t},surviving:r,detail:Lp({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function di(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 $p(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 Ap(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 Lp(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Ap(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${li(e.held,"Worker")} across ${li(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 li(e,n){return`${e} ${n}${e===1?"":"s"}`}function pr(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.holding;return n.version===1&&typeof n.running=="boolean"&&typeof n.stopped=="boolean"&&typeof n.reason=="string"&&typeof n.socket_path=="string"&&typeof n.detail=="string"&&(n.daemon_version===null||typeof n.daemon_version=="string")&&(n.pid===null||typeof n.pid=="number")&&t!=null&&Array.isArray(t.workers)&&Array.isArray(t.projects)&&Array.isArray(n.surviving)}import{chmod as Ip,mkdir as Tp,readFile as Np,rm as Wp,writeFile as Cp}from"node:fs/promises";import{dirname as ci,join as mi}from"node:path";import{tmpdir as ui}from"node:os";var Mp="redskilled.machine.claim.toon",Fp="REDSKILLED_MACHINE_DIR",Hp=8,pe=class extends Error{constructor(t,r,o){super(Bp(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},pi;function gi(){return pi??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},pi}function Up(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[Fp]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||ui():ui();return mi(o,`redskilled-${e.machineIdHash}`)}function Kn(e){return mi(Up(e),Mp)}function Jn(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??W;async function s(){let a;try{a=await Np(e,"utf8")}catch(u){if(u.code==="ENOENT"||fr(u))return;throw u}let c=Kp(a);return Jp(c)?c:void 0}function i(a,c){return{version:1,scope:"machine",pid:a.pid,start_time:a.startTime,uid:a.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath,acquired_at:c,renewed_at:c}}async function l(){try{return await Wp(e,{force:!0}),!0}catch(a){if(fr(a))return!1;throw a}}return{claimPath:e,read:s,async claim(a){await Tp(ci(e),{recursive:!0,mode:1023})!=null&&await Ip(ci(e),1023).catch(()=>{});let u=!1;for(let p=0;p<Hp;p+=1){let f=i(a,r());try{return await Cp(e,Vp(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:u,claim:f}}catch(k){if(k.code!=="EEXIST"){if(fr(k))return{claimed:!1,reason:"stale-claim-not-reapable"};throw k}}let h=await s();if(!h){if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable"};u=!0;continue}if(fi(h,a,n.socketPath))return{claimed:!0,reaped:u,claim:h};if(await o(h.pid))return{claimed:!1,reason:"held",claim:h};if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable",claim:h};u=!0}return{claimed:!1,reason:"contended"}},async release(a){let c=await s();return!c||!fi(c,a,n.socketPath)?!1:await l()}}}function hi(e,n,t){return{kind:"machine",claim_path:e,owner_uid:t.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath}}function yi(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.kind==="machine"&&typeof n.claim_path=="string"&&typeof n.owner_uid=="number"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&typeof n.socket_path=="string"}function Bp(e,n,t){let r=t==null?"":` \u2014 held by pid ${t.pid} (uid ${t.uid}) on socket ${JSON.stringify(t.socket_path)}`;return n==="held"?`this machine already has a redskilled daemon${r}; a second one would void the host budget, so none was started. Reach that daemon, or stop it before starting another.`:n==="stale-claim-not-reapable"?`the redskilled machine claim ${JSON.stringify(e)} is stale and cannot be removed by this user${r}; remove it as its owner, then start again. No second daemon was started.`:`the redskilled machine claim ${JSON.stringify(e)} changed hands repeatedly; no daemon was started.`}function fr(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function fi(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function Vp(e){return`${I(e,{keyedMapCollapse:!0})}
|
|
57
|
+
`}function Kp(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return G(n)}catch{return null}}}function Jp(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||n.scope!=="machine"||!Number.isInteger(n.pid)||n.pid<=0||!Number.isInteger(n.uid))return!1;for(let t of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}function mr(e,n){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(n)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((t,r)=>{if(typeof t!="string"||t==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${r} of project ${JSON.stringify(n)} is not`);return t})}function gr(e,n){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error(`redskilled needs a launch env to be a map of strings to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}`);let t={};for(let[r,o]of Object.entries(e)){if(r==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(n)} to be named`);if(typeof o!="string")throw new Error(`redskilled needs every launch env value to be a string, and ${JSON.stringify(r)} of project ${JSON.stringify(n)} is ${JSON.stringify(o)}`);t[r]=o}return t}var qp=3e5,Gp=.5,yr=class extends Error{constructor(t){super(`redskilled already holds a registration for project ${JSON.stringify(t.project_label)}, registered at ${t.registered_at} for a target of ${t.target} and standing until ${t.renew_by}: a project contributes one registration, so a second one is refused rather than silently replacing the first`);this.held=t;this.name="RedskilledProjectRegisteredError"}};function ki(e,n){if(n.held!=null)throw new yr(n.held);let t=hr(e.project_label,"a project label"),r=hr(e.selector,"a selector"),o=mr(e.argv,t),s=gr(e.env,t),i=hr(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.target)}`);let l=e.renew_within_ms??qp;if(!Number.isFinite(l)||l<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let a=Date.parse(n.now);if(!Number.isFinite(a))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(n.now)}`);return{version:1,project_label:t,selector:r,argv:o,workspace_path:i,env:s,target:e.target,registered_at:new Date(a).toISOString(),renew_within_ms:l,renew_by:new Date(a+l).toISOString(),renewed_at:new Date(a).toISOString(),renewals:0,launch_revision:0}}var qn=class extends Error{constructor(t){super(`redskilled holds no registration for project ${JSON.stringify(t)} to renew: it lapsed or was never held, and a renewal never mints a record \u2014 register again, stating the selector, the argv and the target`);this.projectLabel=t;this.name="RedskilledProjectUnregisteredError"}};function Ri(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(n.now)}`);let r=n.renew_within_ms??e.renew_within_ms;if(!Number.isFinite(r)||r<=0)throw new Error(`redskilled needs a positive renewal window to renew project ${JSON.stringify(e.project_label)}, not ${JSON.stringify(n.renew_within_ms)}`);let o=n.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:mr(n.launch.argv,e.project_label),env:gr(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1};return{...e,...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1}}function bi(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(n.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,n.liveWorkers??0),s=n.queue,i=s!=null&&s.outcome==="counted"?s.depth:null,l=i!=null&&i>0?"open-work":o>0?"live-worker":null;if(l==null){let a=i===0?"drained":"uncounted";return{registration:e,verdict:a,detail:a==="drained"?`project ${r} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${r}, and an uncounted queue never sustains a registration \u2014 it stands on its own deadline of ${e.renew_by}`}}return{registration:{...e,renew_by:new Date(t+e.renew_within_ms).toISOString(),sustained_at:new Date(t).toISOString(),sustains:(e.sustains??0)+1,sustained_by:l},verdict:l,detail:l==="open-work"?`project ${r} has ${i} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function zp(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function wi(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*Gp;if(r(t))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return r(o)?"self-renewing":"running-on"}function _i(e,n){let t=[],r=[];for(let o of e)(zp(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function kr(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.project_label=="string"&&typeof n.selector=="string"&&Array.isArray(n.argv)&&n.argv.every(t=>typeof t=="string")&&typeof n.workspace_path=="string"&&Number.isInteger(n.target)&&typeof n.registered_at=="string"&&typeof n.renew_within_ms=="number"&&typeof n.renew_by=="string"&&(n.renewed_at===void 0||typeof n.renewed_at=="string")&&(n.renewals===void 0||Number.isInteger(n.renewals))&&(n.env===void 0||Qp(n.env))&&(n.launch_revision===void 0||Number.isInteger(n.launch_revision))&&(n.sustained_at===void 0||typeof n.sustained_at=="string")&&(n.sustains===void 0||Number.isInteger(n.sustains))&&(n.sustained_by===void 0||n.sustained_by==="open-work"||n.sustained_by==="live-worker")}function Qp(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function hr(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var Yp={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 vi(e){return`worker-${e}`}function xi(e){let n=Yp[e.op]??"project-write",t=e.sessionProject??null,r=e.targetProject??null,o={version:1,op:e.op,reach:n,session_project:t,target_project:r};return n==="host-read"?{...o,permitted:!0,verdict:"permitted-host-read",reason:`redskilled permitted ${e.op}: a session reads the whole host, whichever project it was started in`}:n==="daemon-life"?{...o,permitted:!0,verdict:"permitted-daemon-life",reason:`redskilled permitted ${e.op}: it acts on the daemon's own process, not on any project's Workers`}:t==null||t===""?{...o,permitted:!0,verdict:"permitted-unattributed",reason:`redskilled permitted ${e.op}: the session named no project of its own, so there is nothing to refuse it against`}:r!=null&&r===t?{...o,permitted:!0,verdict:"permitted-own-project",reason:`redskilled permitted ${e.op}: the target belongs to project ${JSON.stringify(t)}, which is this session's own`}:{...o,permitted:!1,verdict:"refused-cross-project",reason:`redskilled refused ${e.op} from a session in project ${JSON.stringify(t)}: ${r==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(r)}`}. A session reads the whole host and writes only its own project.`}}import{execFileSync as Zp}from"node:child_process";import{readFileSync as Xp,readdirSync as ef}from"node:fs";import{join as nf}from"node:path";function cn(e){let n=e.budget??{},t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high],["MemoryMax",e.memory_ceiling]];for(let[r,o]of t){if(o==null)continue;let s=Le(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function Si(e){let n=[],t=[];for(let r of e.workers){let o=cn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(r.budget?.memory_max??r.budget?.memory_high??r.memory_ceiling)==null?"this Worker declared no memory budget and the host derived no ceiling for it, so the sampler has none to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let s=e.rss[r.worker_id];if(typeof s!="number"||!Number.isFinite(s)){t.push({worker_id:r.worker_id,reason:"the host produced no RSS reading for this Worker on this tick, and an unmeasured Worker is never killed on suspicion"});continue}s<=o.bytes||n.push(tf(r,o,s))}return{terminations:n,unenforceable:t}}function tf(e,n,t){let r=`Worker ${JSON.stringify(e.worker_id)} of project ${JSON.stringify(e.project_label)}`;return{version:1,worker_id:e.worker_id,project_label:e.project_label,outcome:"terminated-over-memory-budget",classification:"budget-exceeded",stall:!1,budget_name:n.name,budget_declared:n.declared,budget_bytes:n.bytes,observed_rss_bytes:t,workspace_path:e.workspace_path,reason:`redskilled terminated ${r}: its tree RSS of ${t} bytes exceeded its ${n.name} budget of ${n.declared} (${n.bytes} bytes). This is a budget termination, not a stall, and the work in ${JSON.stringify(e.workspace_path)} is handed forward.`}}var rf=4096;function Ei(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{}};if(e.length===0)return r;let o=of(t,n);if(o.size===0)return r;let s=new Map;for(let a of o.values()){let c=s.get(a.ppid);c?c.push(a.pid):s.set(a.ppid,[a.pid])}let i={},l={};for(let a of e){if(!o.has(a.pid))continue;let c=0,u=0,p=[a.pid],f=new Set;for(;p.length>0;){let h=p.pop();if(f.has(h))continue;f.add(h);let k=o.get(h);if(k){c+=k.rssBytes,u+=k.cpuSeconds;for(let b of s.get(h)??[])p.push(b)}}i[a.worker_id]=c,l[a.worker_id]=u}return{rss:i,cpu_seconds:l}}function of(e,n){return n.procRoot!=null||e==="linux"?uf(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?df(sf(n.psTable)):new Map}function sf(e){try{return(e??lf)()}catch{return""}}function lf(){return Zp("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var af=1024;function df(e){let n=new Map;for(let t of e.split(`
|
|
58
|
+
`)){let r=t.trim().split(/\s+/);if(r.length!==4)continue;let[o,s,i]=r.slice(0,3).map(Number);if(![o,s,i].every(a=>a!=null&&Number.isSafeInteger(a)&&a>=0))continue;let l=cf(r[3]);l!=null&&n.set(o,{pid:o,ppid:s,rssBytes:i*af,cpuSeconds:l})}return n}function cf(e){let n=e.indexOf("-"),t=n<0?0:Number(e.slice(0,n));if(!Number.isFinite(t)||t<0)return null;let r=e.slice(n+1).split(":"),o=t*86400,s=1;for(let i=r.length-1;i>=0;i--){let l=Number(r[i]);if(!Number.isFinite(l)||l<0||r[i]==="")return null;o+=l*s,s*=60}return o}function uf(e){let n=new Map,t;try{t=ef(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=Xp(nf(e,r,"stat"),"utf8")}catch{continue}let s=ff(o);s&&n.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*rf,cpuSeconds:s.cpuTicks/pf})}return n}var pf=100;function ff(e){let n=e.lastIndexOf(")");if(n<0)return null;let t=Number(e.slice(0,e.indexOf(" "))),r=e.slice(n+1).trim().split(/\s+/),o=Number(r[1]),s=Number(r[11]),i=Number(r[12]),l=Number(r[21]);return!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||!Number.isFinite(l)||!Number.isFinite(s)||!Number.isFinite(i)?null:{pid:t,ppid:o,rssPages:Math.max(0,l),cpuTicks:Math.max(0,s)+Math.max(0,i)}}var Rr=class extends Error{constructor(t,r,o){super(`redskilled polls every repository with one host token ${JSON.stringify(o)}, and project ${JSON.stringify(t)} declares its own credential ${JSON.stringify(r)}: a project needing its own credential invalidates the host-scoped poller (ADR 0130 Amendment 1) rather than bending it, so the poller returns to the projects instead of reaching this repository under the wrong identity`);this.projectLabel=t;this.tokenRef=r;this.hostTokenRef=o;this.name="RedskilledSplitCredentialError"}};function wr(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new Rr(t.project_label,t.token_ref,n)}function mf(e,n={now:new Date(0).toISOString()}){yf(e);let t=n.closedWindowMs??6048e5,r=Date.parse(n.now);if(!Number.isFinite(r))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(n.now)}`);let o=new Date(r-Math.max(0,t)).toISOString(),s=e.map((a,c)=>({alias:`r${c}`,search_alias:`c${c}`,project:a}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { remaining resetAt }",...s.flatMap(({alias:a,search_alias:c,project:u})=>{let p=JSON.stringify(u.owner),f=JSON.stringify(u.name),h=JSON.stringify(`repo:${u.owner}/${u.name} is:closed closed:>=${o}`);return[` ${a}: repository(owner: ${p}, name: ${f}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${c}: search(query: ${h}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
|
|
59
|
+
`),aliases:s,closed_since:o}}function gf(e,n,t){let r=Ie(n),o=Ie(r.data),s=Array.isArray(r.errors)?r.errors.map(Ie):[],i=kf(o.rateLimit,s),l=e.aliases.map(({alias:a,search_alias:c,project:u})=>{let p=u.owner+"/"+u.name,f=o[a],h=s.find(k=>Pi(k.path,a)||Pi(k.path,c));if(Li(f)){let k=ji(f.open_pull_requests),b=ji(f.open_issues),y=Rf(o[c]);if(k!=null&&b!=null&&y!=null)return{project_label:u.project_label,repository:p,outcome:"counted",counts:{open_pull_requests:k,open_issues:b,recently_closed:y},detail:`counted ${p} for project ${JSON.stringify(u.project_label)}`}}return i.exhausted||Ai(h)?{project_label:u.project_label,repository:p,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${p} answered, so this project has no counts rather than zero counts${i.reset_at==null?"":`; the quota resets at ${i.reset_at}`}`}:{project_label:u.project_label,repository:p,outcome:"unreachable",counts:null,detail:`${p} is not reachable with the host token: ${br(h?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:l.length,rate_limit:i,projects:l}}function hf(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 Di(e){if(e.projects.length===0)return hf(e.now);wr(e.projects,e.hostTokenRef);let n=mf(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return gf(n,t,{fetchedAt:e.now})}catch(t){let r=t instanceof Error?t.message:String(t),o=/rate limit|secondary rate|429/i.test(r);return{version:1,fetched_at:e.now,request_count:1,project_count:e.projects.length,rate_limit:{remaining:null,reset_at:null,exhausted:o},projects:e.projects.map(s=>({project_label:s.project_label,repository:`${s.owner}/${s.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${s.owner}/${s.name} answered: ${r}`}))}}}function Oi(e){let n=e.stalenessMs??12e4,t=e.activity;if(t==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:n,stale:!1,request_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[],reason:"the daemon polls no repository, so there are no counts to age"};let r=Date.parse(e.now),o=Date.parse(t.fetched_at),s=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,i=s==null||s>n;return{version:1,fetched_at:t.fetched_at,age_ms:s,threshold_ms:n,stale:t.projects.length>0&&i,request_count:t.request_count,rate_limit:t.rate_limit,projects:t.projects.map(l=>({...l,fetched_at:t.fetched_at,age_ms:s,stale:i})),reason:t.projects.length===0?"the daemon polls no repository, so there are no counts to age":s==null?"these counts carry no readable instant, so they cannot be presented as current":i?`these counts are ${s}ms old, past the ${n}ms window`:`fetched ${s}ms ago, within the ${n}ms window`}}function $i(e){let n=e.endpoint??"https://api.github.com/graphql",t=e.fetchImpl??fetch;return async r=>{let o=await t(n,{method:"POST",headers:{authorization:`bearer ${e.token}`,"content-type":"application/json",accept:"application/vnd.github+json"},body:JSON.stringify({query:r})});if(!o.ok){let s=o.headers.get("x-ratelimit-remaining"),i=o.status===429||s==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(i?": the host token's rate limit is spent":""))}return await o.json()}}function yf(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>100)throw new Error("redskilled activity fetch spans at most 100 repositories in one query");let n=new Set;for(let t of e){if(t.project_label===""||t.owner===""||t.name==="")throw new Error("redskilled activity fetch needs a project label and an owner/name for every registered project");if(n.has(t.project_label))throw new Error(`redskilled holds one repository per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function kf(e,n){let t=Ie(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(Ai);return{remaining:r,reset_at:o,exhausted:s||r===0}}function Ai(e){if(e==null)return!1;let n=br(e.type),t=br(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function Pi(e,n){return Array.isArray(e)&&e.includes(n)}function ji(e){let n=Ie(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function Rf(e){let n=Ie(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Ie(e){return Li(e)?e:{}}function Li(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function br(e){return typeof e=="string"?e:""}var bf=3e4,wf=4;function Ii(e){let n=e.stalenessMs??bf,t=un(e.now),r=e.sampledAt==null?null:un(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),s=o!=null&&o<=n,i=new Set(e.reattachedWorkerIds??[]),l=e.hostState.workers.map(f=>xf(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:i.has(f.worker_id)?"reattached":"running"})),a=l.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),c=l.length-a.length,u=l.reduce((f,h)=>f+(h.vitals.rss_bytes??0),0),p=Vn(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:jf({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:l.length,measuredCount:c,unmeasured:a}),host:{worker_count:l.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:p,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:u,measured_worker_count:c,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:p.memory_bytes/e.ceiling.memory_bytes},projects:Pf(l),known_projects:Ef(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,h)=>f.localeCompare(h)),workers:l,repository_activity:Oi({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:_f(e.deaths,e.recentDeathLimit??wf)},engine:vf(e.hostState)}}function _f(e,n){let t=[...e].sort((o,s)=>(un(s.ts)??0)-(un(o.ts)??0)),r=t.slice(0,Math.max(0,Math.floor(n))).map(o=>({kind:o.kind,id:o.id,pid:o.pid,ts:o.ts,last_seen:o.last_seen,last_phase:o.last_phase,sender_class:o.sender_class,confidence:o.confidence,signal:o.signal,evidence:o.evidence[0]??null}));return{count:t.length,recent:r,latest:r[0]??null,reaped_at:r[0]?.ts??null}}function vf(e){let n=e.upgrade,t=n?.running_version??e.daemon_version,r=n?.published_version??null,o=n?.newest_published_version??null,s=(n?.newer_published??0)>0,i=(n?.major_held??0)>0;return{running_version:t,published_version:r,newer_published:s,major_held:i,current:r==null&&o==null?null:!s&&!i}}function xf(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=cn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=un(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms:n.nowMs==null||i==null?null:Math.max(0,n.nowMs-i),state:n.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:r,sampled_at:r==null?null:n.sampledAt,age_ms:r==null?null:n.ageMs,fresh:r!=null&&n.sampleFresh},budget:{name:o?.name??null,declared:o?.declared??s,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:Sf(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function Sf(e){let n={last_line:null,published_at:null,source:null};return e==null||e.line.trim()===""?n:{last_line:e.line,published_at:e.published_at,source:e.source}}function Ef(e){let n=new Set;for(let t of e.registrations??[])n.add(t.project_label);for(let t of e.projects)n.add(t.project_label);return[...n].sort((t,r)=>t.localeCompare(r))}function Pf(e){let n=new Map;for(let t of e){let r=n.get(t.project_label)??{workers:0,declared:0,observed:0,measured:0};r.workers+=1,r.declared+=t.budget.bytes??0,r.observed+=t.vitals.rss_bytes??0,r.measured+=t.vitals.rss_bytes==null?0:1,n.set(t.project_label,r)}return[...n.entries()].map(([t,r])=>({project_label:t,worker_count:r.workers,declared_memory_bytes:r.declared,observed_rss_bytes:r.observed,measured_worker_count:r.measured})).sort((t,r)=>t.project_label.localeCompare(r.project_label))}function jf(e){let n={sampled_at:e.sampledAt,age_ms:e.ageMs,threshold_ms:e.threshold,measured_worker_count:e.measuredCount,unmeasured_workers:e.unmeasured};return e.workerCount===0?{...n,stale:!1,reason:"the host holds no Workers, so there is nothing to measure and nothing to age"}:e.sampledAt==null||e.ageMs==null?{...n,stale:!0,reason:`this answer is stale: the daemon has taken no measurement of its ${e.workerCount} live Worker(s) yet`}:e.ageMs>e.threshold?{...n,stale:!0,reason:`this answer is stale: its measurement is ${e.ageMs}ms old, past the ${e.threshold}ms staleness window`}:{...n,stale:!1,reason:`measured ${e.ageMs}ms ago, within the ${e.threshold}ms staleness window`}}function un(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}var O={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Ti(e,n=O){let t=Tf(e,n),r=Lf(e,n),o=If(e,n),s=Nf(e,n,r,t),i=$f(n,r,o),l={detail:"host",line:s};for(let p of i){let f=Jf(s,Af(p,n,r,o),n.separator);if(l={detail:p,line:f},qf(f)<=n.maxWidth)break}let a=Sr(l.line,n.maxWidth),c=n.verbose&&l.detail==="workers"?Uf(r,n):[],u=r.length>0?"workers":"host";return{version:1,line:a,lines:[a,...c],verbose:n.verbose,mode:n.mode,project:n.project,project_match:t,detail:l.detail,degraded:l.detail!==u||a!==l.line,stale:e.staleness.stale,generated_at:e.generated_at}}function Ni(e){let n=e.options??O,t=Sr(Of,n.maxWidth);return{version:1,line:t,lines:[t],verbose:n.verbose,mode:n.mode,project:n.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}var Df="!unregistered",vr="\u21E1",Gn="\u2020",Of="redskilled unreachable \u2014 Worker state unknown";function $f(e,n,t){let r=[];return n.length>0&&n.length<=e.maxWorkers&&r.push("workers"),e.mode==="global"&&t.length>0&&t.length<=e.maxProjects&&r.push("projects"),r.push("host"),r}function Af(e,n,t,r){return e==="workers"?t.map(o=>Hf(o,n)):e==="projects"?r.map(Kf):[]}function Lf(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function If(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function Tf(e,n){return xr(e,n.project)}function xr(e,n){return n==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(n)?e.registered_projects==null||e.registered_projects.includes(n)?"matched":"name-only":"unregistered"}function Nf(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(_r(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(_r(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(_r(e,n)),o.push(Df)):o.push(Mf(n.project,r)),o.push(Wf(e));let s=Cf(e);return s!=null&&o.push(s),e.staleness.stale&&o.push(Ff(e)),o.join(" ")}function Wf(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${vr}`}function Cf(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Gn}${n.count} ${n.latest.sender_class}`}function Mf(e,n){return n==="unregistered"?`project unknown \u2014 ${e} is not registered on this host`:"project unknown \u2014 this directory resolved to no project"}function _r(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,s)=>o+s.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${H(t)}/${H(r)}`:H(t)}function Ff(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function Hf(e,n){let t=Wi(e,n),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?H(r):`${H(r)}/${H(e.budget.bytes)}`;return`${t} ${o}`}function Uf(e,n){let t=[];for(let r of e){let o=Vf(r.log.last_line);o!=null&&t.push(Sr(` ${Bf} ${Wi(r,n)}: ${o}`,n.maxWidth))}return t}var Bf="\u21B3";function Vf(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}function Wi(e,n){return n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Kf(e){return`${e.project_label} ${e.worker_count}w ${H(e.observed_rss_bytes)}`}function Jf(e,n,t){return[e,...n].join(t)}function qf(e){return[...e].length}function Sr(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}function H(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}var Er={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},Gf=["runner","model","effort","origin","issue","phase","step","heartbeat"],zf=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function Ci(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...Er};for(let r of Gf){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of zf){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}var zn=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],Te={mode:"local",project:null,maxWidth:200,maxRows:16};var Qf=" ",Mi="\u2588",Yf="\u25B6",Zf="\u2717",Xf="\u2591";function Fi(e,n=Te){let t=xr(e,n.project),r=em(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(p=>nm(p,n)),i=cm(s),l=o.map((p,f)=>({worker_id:p.worker_id,project_label:p.project_label,mine:n.project!=null&&p.project_label===n.project,cells:s[f],line:pn(um(s[f],i),n.maxWidth)})),a=rm(e,n,r,t),c=r.length-o.length,u=[a.line,...l.map(p=>p.line)];return c>0&&u.push(pn(`\u2026 ${c} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),u.push(...om(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:zn,header:a,rows:l,lines:u,hidden_row_count:Math.max(0,c),stale:e.staleness.stale}}function em(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function nm(e,n){let t=e.display??Er,r=[t.runner,t.model,t.effort].filter(o=>!!o).join(" ");return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:r===""?"":`run=${r}`,org:t.origin==null?"":`org=${t.origin}`,iss:t.issue==null?"":`iss=${t.issue}`,bar:tm(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:dm(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:lm(t.added,t.removed),tks:t.tokens==null?"":`tks=${am(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function tm(e){let n=e.phase_total,t=e.phase_index;if(n==null||n<=0||t==null||t<0)return"";let r=Math.min(Math.floor(t),Math.floor(n));if(r>=n)return Mi.repeat(Math.floor(n));let o=e.failed?Zf:Yf;return`${Mi.repeat(r)}${o}${Xf.repeat(Math.floor(n)-r-1)}`}function rm(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(h=>h.project_label===n.project),s={open_pull_requests:o?.counts?.open_pull_requests??null,recently_closed:o?.counts?.recently_closed??null,open_issues:o?.counts?.open_issues??null,stale:o?.stale===!0},i={memory_used_fraction:e.host.ceiling_used_fraction,memory_used_bytes:e.host.consumption.memory_bytes,memory_ceiling_bytes:e.host.ceiling.memory_bytes,worker_count:e.host.worker_count,worker_ceiling:e.host.ceiling.worker_count},l=im(t),a=o?.repository??n.project,c=e.engine??null,u=c?.running_version??e.daemon.daemon_version,p=e.deaths??null,f=[`\xBB ${a??"host"} v${u}${c!=null&&c.current===!1?vr:""}`];if(r==="unregistered"&&f.push("!unregistered"),r==="name-only"&&f.push("!lapsed"),l!=null&&f.push(l),f.push(`wrk=${t.length}/${e.host.worker_count}`),f.push(i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`),f.push(sm(i)),s.open_pull_requests!=null&&f.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&f.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&f.push(`iss=${s.open_issues}`),s.stale&&f.push("!counts stale"),p!=null&&p.count>0&&p.latest!=null&&f.push(`${Gn}${p.count} ${p.latest.sender_class}`),e.staleness.stale){let h=e.staleness.age_ms;f.push(h==null?"!unmeasured":`!stale ${Math.round(h/1e3)}s`)}return{repo:a,project:n.project,project_match:r,version:u,engine:c,deaths:p,model:l,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:pn(f.join(" \xB7 "),n.maxWidth)}}function om(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(s=>pn(`${Gn} ${s.kind} ${s.id} pid=${s.pid} ${s.sender_class}/${s.confidence} phase=${s.last_phase}`+(s.signal==null?"":` signal=${s.signal}`)+(s.evidence==null?"":` \u2014 ${s.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(pn(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function sm(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${H(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${H(e.memory_used_bytes)}/${H(e.memory_ceiling_bytes)}${n}`}function im(e){for(let n of e){let t=n.display;if(t==null)continue;let r=[t.runner,t.model,t.effort].filter(o=>!!o);if(r.length>0)return r.join("\xB7")}return null}function lm(e,n){if(e==null&&n==null)return"";let t=[];return e!=null&&e>0&&t.push(`+${e}`),n!=null&&n>0&&t.push(`-${n}`),`loc=${t.length>0?t.join(" "):"0"}`}function am(e){if(!Number.isFinite(e)||e<=0)return"0";let n=(t,r)=>{let o=(Math.round(t*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${r}`};return e>=1e9?n(e/1e9,"B"):e>=1e6?n(e/1e6,"M"):e>=1e3?n(e/1e3,"k"):String(Math.round(e))}function dm(e){if(e==null||!Number.isFinite(e)||e<0)return"\u2014";let n=Math.floor(e/1e3);if(n<60)return`${n}s`;let t=Math.floor(n/60);if(t<60)return`${t}m${n%60}s`;let r=Math.floor(t/60);return r<24?`${r}h${t%60}m`:`${Math.floor(r/24)}d${r%24}h`}function cm(e){let n=Object.fromEntries(zn.map(t=>[t,0]));for(let t of e)for(let r of zn)n[r]=Math.max(n[r],Hi(t[r]));return n}function um(e,n){return zn.filter(r=>n[r]>0).map(r=>pm(e[r],n[r])).join(Qf).replace(/\s+$/,"")}function pm(e,n){return e+" ".repeat(Math.max(0,n-Hi(e)))}function Hi(e){return[...e].length}function pn(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}var Qn=1;async function fn(e,n){return await Wn(e,n,"redskilled daemon")}function Ui(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.line=="string"&&Array.isArray(n.lines)&&n.lines.every(t=>typeof t=="string")&&typeof n.verbose=="boolean"&&(n.mode==="local"||n.mode==="global")&&(n.project===null||typeof n.project=="string")&&typeof n.detail=="string"&&(n.project_match===void 0||typeof n.project_match=="string")&&typeof n.degraded=="boolean"&&typeof n.stale=="boolean"&&typeof n.generated_at=="string"}function Bi(e){let n=[...e.workers??[]],t=new Map;for(let r of n)t.set(r.project_label,(t.get(r.project_label)??0)+1);return{version:1,protocol_version:Qn,daemon_version:e.daemonVersion,machine_id_hash:e.machineIdHash,session_key_hash:e.sessionKeyHash,pid:e.pid,started_at:e.startedAt,...e.scope==null?{}:{scope:e.scope},workers:n,projects:[...t.entries()].map(([r,o])=>({project_label:r,worker_count:o})).sort((r,o)=>r.project_label.localeCompare(o.project_label)),registrations:gm(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:zs(n),upgrade:hm(e)}}function gm(e){let n=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(n),r=e.queue??null,o=new Map(r==null?[]:r.projects.map(s=>[s.project_label,s]));return[...e.registrations??[]].map(s=>{let i=o.get(s.project_label);return{...s,...t?{renewal:wi(s,n)}:{},...r==null||i==null?{}:{last_poll:{at:r.fetched_at,outcome:i.outcome,depth:i.depth,request_count:r.request_count,detail:i.detail}}}}).sort((s,i)=>s.project_label.localeCompare(i.project_label))}function hm(e){let n=e.daemonVersion,t=e.published?.version??null,r=e.published?.majorHold??null;return{running_version:n,published_version:t,published_unknown:+(t===null),newer_published:+(e.published?.newer===!0),replacement:e.published?.replacement??"none",checked_at:e.published?.checkedAt??null,checks:e.published?.checks??0,hold_reason:e.published?.holdReason??null,newest_published_version:e.published?.newest??null,major_held:+(r!==null),major_hold:r}}function Vi(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.protocol_version=="number"&&typeof n.daemon_version=="string"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&Number.isInteger(n.pid)&&typeof n.started_at=="string"&&Array.isArray(n.workers)&&Array.isArray(n.projects)&&Qs(n.budget_accounting)&&(n.scope===void 0||yi(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(kr))&&(n.upgrade===void 0||ym(n.upgrade))}function ym(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")&&typeof n.published_unknown=="number"&&typeof n.newer_published=="number"&&(n.replacement==="none"||n.replacement==="pending"||n.replacement==="in-progress")&&(n.checked_at===null||typeof n.checked_at=="string")&&(n.newest_published_version===void 0||n.newest_published_version===null||typeof n.newest_published_version=="string")&&(n.major_held===void 0||typeof n.major_held=="number")&&(n.checks===void 0||typeof n.checks=="number")&&(n.hold_reason===void 0||n.hold_reason===null||typeof n.hold_reason=="string")&&(n.major_hold===void 0||n.major_hold===null||km(n.major_hold))}function km(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.version=="string"&&Number.isInteger(n.running_major)&&Number.isInteger(n.held_major)&&typeof n.reason=="string"&&typeof n.action=="string"&&n.action.trim()!==""}import{spawnSync as Xn}from"node:child_process";import{existsSync as $r}from"node:fs";import{delimiter as Pm,join as el}from"node:path";import{join as Ki}from"node:path";import{existsSync as Rm}from"node:fs";import{createRequire as bm}from"node:module";var Ji="redskilled-job-object.node",we=100;function Ne(e){return{available:!1,reason:e}}function wm(e,n,t){return[Ki(t,"prebuilds",`${e}-${n}`,Ji),Ki(t,"native","build","Release",Ji)]}function qi(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return Ne(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??vm(),o=e.exists??Rm,s=wm(n,t,r),i=s.find(c=>o(c));if(i==null)return Ne(`no Job Object addon was found for ${n}-${t} (looked in ${s.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let l=e.requireFn??bm(import.meta.url),a;try{a=l(i)}catch(c){return Ne(`the Job Object addon at ${i} could not be loaded: ${c instanceof Error?c.message:String(c)}`)}return _m(a)?{available:!0,binding:a}:Ne(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function _m(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function vm(){return new URL("..",import.meta.url).pathname}function Gi(e){let n=e??{},t=[],r=xm(n);r==null&&(n.memory_max??n.memory_high)!=null&&t.push("the declared memory budget could not be reduced to bytes, so the job carries no memory ceiling");let o;return n.cpu_weight!=null&&(n.cpu_weight<we?o=Math.max(1,Math.min(100,Math.round(n.cpu_weight))):t.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${we}, and Windows CPU rate control is an absolute cap rather than a share, so no rate limit is set`)),{...r!=null?{memory_limit_bytes:r.bytes,memory_budget_name:r.name,memory_budget_declared:r.declared}:{},...o!=null?{cpu_rate_percent:o}:{},kill_on_close:!0,...t.length>0?{note:t.join("; ")}:{}}}function xm(e){return cn({budget:e})}var Yn=5,zi=19;function Pr(e){return{available:!1,reason:e}}var Sm="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 Yi(e,n){let t=e??{},r=[],o;if(!n.canRenice)r.push("nice is not on this host, so no priority control was applied and the Worker competes with interactive work");else if(t.cpu_weight==null)o=Yn;else if(t.cpu_weight<we){let l=Math.round(zi*(we-t.cpu_weight)/we);o=Math.min(zi,Math.max(Yn,l))}else o=Yn,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${we}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Yn}`);let s=Qi(t.max_processes);s==null&&t.max_processes!=null&&r.push(`max_processes=${t.max_processes} is not a positive whole number, so no ulimit -u is set`);let i=Qi(t.cpu_seconds);return i==null&&t.cpu_seconds!=null&&r.push(`cpu_seconds=${t.cpu_seconds} is not a positive whole number, so no ulimit -t is set`),{...o!=null?{nice:o}:{},...s!=null?{max_processes:s}:{},...i!=null?{cpu_seconds:i}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:Sm,...r.length>0?{note:r.join("; ")}:{}}}function Zi(e){let{limits:n}=e,t=[];return n.max_processes!=null&&t.push(`ulimit -u ${n.max_processes}`),n.cpu_seconds!=null&&t.push(`ulimit -t ${n.cpu_seconds}`),t.push(n.nice!=null&&e.nice!=null?`exec ${Em(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
|
|
60
|
+
`),e.command,...e.args]}function Xi(e){let n=[];return e.nice!=null?n.push(`the Worker runs at nice ${e.nice} so it yields to interactive work`):n.push("no priority control was applied"),e.max_processes!=null&&n.push(`its processes are capped at ${e.max_processes}`),e.cpu_seconds!=null&&n.push(`its CPU time is capped at ${e.cpu_seconds} seconds`),`macOS placement applied POSIX limits: ${n.join(", ")}. macOS has no resource-group equivalent, so the Worker is charged to the daemon's own resource group, and ${e.memory_ceiling_reason}`+(e.note!=null?` (${e.note})`:"")}function jr(e){let n=e??{},t=[n.max_processes!=null?"max_processes":null,n.cpu_seconds!=null?"cpu_seconds":null].filter(r=>r!=null);return t.length===0?null:`${t.join(" and ")} ${t.length===1?"is a POSIX rlimit":"are POSIX rlimits"} honoured only by the macOS placement backend, so this placement carries no equivalent`}function Qi(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function Em(e){return`'${e.replace(/'/g,"'\\''")}'`}var nl="REDSKILLED_PLACEMENT",Zn="red-worker",Dr="/bin/sh";function tl(e=process.env,n=process.platform){let t=Pr(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:qi({platform:n}),posix:t};let r=Ne(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);if(n==="darwin")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:jm(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&$r(el(o,"systemd","private"));return{platform:n,systemdRun:il("systemd-run",e),userSession:s,jobObjects:r,posix:t}}function jm(e){return $r(Dr)?{available:!0,shell:Dr,nice:il("nice",e)}:Pr(`no POSIX shell was found at ${Dr}, so there is nothing to apply rlimits or priority in`)}function rl(e=process.env){let n=(e[nl]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Dm(e,n,t=Zn){return ol(e,n,t).replace(/\.service$/,"")}function ol(e,n,t=Zn){return`${Or(t,"red-worker",24)}-${Or(e,"project",32)}-${Or(n,"worker",32)}.service`}function sl(e){let n=[...e.args??[]],t={...e.budget??{},...e.budget?.memory_max==null&&e.memoryCeiling?.memory_max!=null?{memory_max:e.memoryCeiling.memory_max}:{}},r=t.memory_max??t.memory_high??null,o=t.memory_high!=null||t.memory_max!=null||t.cpu_weight!=null,s=e.target??{isolation:"transient-unit"},i=p=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:p,...r!=null?{memoryCeiling:r}:{},environment:tn({scope:null,memory_ceiling:r,scope_degradation:p}),...o?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(s.isolation==="inherit")return i("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return i(`worker isolation disabled by ${nl}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return $m(e,n,t,r,o,i);if(e.probes.platform==="darwin")return Om(e,n,t,r,i);if(e.probes.platform!=="linux")return i(`transient-unit placement is the Linux backend (platform=${e.probes.platform}): the Worker is charged to the daemon's own resource group`);if(!e.probes.systemdRun)return i("transient-unit placement unavailable: systemd-run is not on PATH; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");if(!e.probes.userSession)return i("transient-unit placement unavailable: no systemd --user session; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");let l=ol(e.projectLabel,e.workerId,s.unit_prefix),a=["--user","--collect","--quiet","--wait",`--unit=${l}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&a.push("--pipe"),t.memory_high!=null&&a.push(`--property=MemoryHigh=${t.memory_high}`),t.memory_max!=null&&a.push(`--property=MemoryMax=${t.memory_max}`),t.cpu_weight!=null&&a.push(`--property=CPUWeight=${t.cpu_weight}`);let c=tn({scope:l,memory_ceiling:r,scope_degradation:null});for(let[p,f]of Object.entries({...e.env??{},...c}))a.push(`--setenv=${p}=${f}`);let u=jr(e.budget);return{isolated:!0,backend:"transient-unit",unit:l,command:e.probes.systemdRun,args:[...a,"--",e.command,...n],...r!=null?{memoryCeiling:r}:{},environment:c,...u!=null?{budgetWarning:u}:{}}}function Om(e,n,t,r,o){let s=e.probes.posix;if(!s.available)return o(`POSIX limit placement unavailable: ${s.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let i=Yi(t,{canRenice:s.nice!=null}),l=t.memory_high!=null||t.memory_max!=null,a=Xi(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:Zi({limits:i,nice:s.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:i,warning:a,...r!=null?{memoryCeiling:r}:{},environment:tn({scope:null,memory_ceiling:r,scope_degradation:a}),...l?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+i.memory_ceiling_reason}:{}}}function $m(e,n,t,r,o,s){let i=e.probes.jobObjects;if(!i.available)return s(`Job Object placement unavailable: ${i.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let l=Gi(t),a=Dm(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...n],cwd:e.workspacePath,job:{name:a,limits:l},...r!=null?{memoryCeiling:r}:{},environment:tn({scope:a,memory_ceiling:r,scope_degradation:null}),...Am(o&&l.note!=null?`${l.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,jr(e.budget))}}function Am(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function il(e,n){for(let t of(n.PATH??"").split(Pm)){if(!t)continue;let r=el(t,e);if($r(r))return r}return null}function Or(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function Ar(e,n){let t=[],r=[];for(let o of e){let s=!1;try{s=await n(o)===!0}catch{s=!1}(s?t:r).push(o)}return{alive:t,dead:r}}function ll(e){return e.unit!=null&&e.unit!==""?Lm(e.unit):W(e.pid)}function Lm(e){let n=Xn("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var Im="REDSKILLED_UNIT_DISCOVERY",al="(unowned)";function dl(e){let n=Xn("systemctl",["--user","show","--property=MainPID","--value",e],{encoding:"utf8"});if(n.error!=null||n.status!==0)return null;let t=Number.parseInt((n.stdout??"").trim(),10);return Number.isInteger(t)&&t>0?t:null}function Tm(e=process.env){let n=(e[Im]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function cl(e,n,t=process.env){return Tm(t)&&e===n}function ul(e=Zn){let n=Xn("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return n.error!=null||n.status!==0?[]:(n.stdout??"").split(`
|
|
61
|
+
`).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function pl(e){let n=new Set(e.held.map(o=>o.unit).filter(o=>o!=null&&o!=="")),t=new Set,r=[];for(let o of e.units)o===""||n.has(o)||t.has(o)||(t.add(o),r.push({worker_id:o.replace(/\.service$/,""),project_label:al,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 fl(e){return e.project_label.trim()!==""?e:{...e,project_label:al,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 ml(e){if(e.unit!=null&&e.unit!==""){let n=Xn("systemctl",["--user","stop",e.unit],{stdio:"ignore"});return n.error==null&&n.status===0}try{return process.kill(e.pid,"SIGTERM"),!0}catch{return!1}}function Nm(e,n=50){if(kl(e),!Number.isInteger(n)||n<=0)throw new Error(`redskilled queue discovery needs a whole, positive batch size, not ${JSON.stringify(n)}`);let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}function Wm(e,n={}){let t=n.batchSize??50;if(kl(e),e.length>t)throw new Error(`redskilled queue discovery spans at most ${t} selectors in one query, and this batch holds ${e.length}: split it with planQueueDiscoveryBatches rather than dropping the remainder`);let r=e.map((i,l)=>({alias:`q${l}`,project:i}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...r.map(({alias:i,project:l})=>` ${i}: search(query: ${JSON.stringify(l.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
|
|
62
|
+
`),aliases:r}}function Cm(e,n){let t=mn(n),r=mn(t.data),o=Array.isArray(t.errors)?t.errors.map(mn):[],s=Fm(r.rateLimit,o);return{projects:e.aliases.map(({alias:l,project:a})=>{let c=Um(r[l]);if(c!=null)return{project_label:a.project_label,outcome:"counted",depth:c,detail:`project ${JSON.stringify(a.project_label)} has ${c} item(s) matching its selector`};let u=o.find(p=>Hm(p.path,l));return s.exhausted||Rl(u)?{project_label:a.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(a.project_label)} answered, so this queue has no depth rather than a depth of zero`+(s.reset_at==null?"":`; the quota resets at ${s.reset_at}`)}:{project_label:a.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(a.project_label)} could not be counted with the host token: ${Lr(u?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function Mm(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function hl(e,n,t){return{version:1,fetched_at:n,request_count:0,project_count:e.length,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:e.map(r=>({project_label:r.project_label,outcome:"unconfigured",depth:null,detail:`project ${JSON.stringify(r.project_label)} was not counted because this host polls no tracker: ${t}`}))}}async function yl(e){if(e.projects.length===0)return Mm(e.now);let n=e.batchSize??50,t=Nm(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=Wm(s,{batchSize:n});try{let l=await e.transport(i.query),a=Cm(i,l);r.push(...a.projects),o=gl(o,a.rate_limit)}catch(l){let a=l instanceof Error?l.message:String(l),c=/rate limit|secondary rate|429/i.test(a);o=gl(o,{remaining:null,reset_at:null,exhausted:c});for(let u of s)r.push({project_label:u.project_label,outcome:c?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(u.project_label)} answered: ${a}`})}}return{version:1,fetched_at:e.now,request_count:t.length,project_count:r.length,batch_size:n,rate_limit:o,projects:r}}function kl(e){if(e.length===0)throw new Error("redskilled queue discovery needs at least one registered project");let n=new Set;for(let t of e){if(typeof t.project_label!="string"||t.project_label==="")throw new Error("redskilled queue discovery needs a project label for every registered project");if(typeof t.selector!="string"||t.selector==="")throw new Error(`redskilled queue discovery needs a selector for project ${JSON.stringify(t.project_label)}: a project that names no work has no queue to discover`);if(n.has(t.project_label))throw new Error(`redskilled holds one selector per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function gl(e,n){return{remaining:n.remaining==null?e.remaining:e.remaining==null?n.remaining:Math.min(e.remaining,n.remaining),reset_at:n.reset_at??e.reset_at,exhausted:e.exhausted||n.exhausted}}function Fm(e,n){let t=mn(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null;return{remaining:r,reset_at:o,exhausted:n.some(Rl)||r===0}}function Rl(e){return e==null?!1:Lr(e.type)==="RATE_LIMITED"||/rate limit/i.test(Lr(e.message))}function Hm(e,n){return Array.isArray(e)&&e.includes(n)}function Um(e){let n=mn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function mn(e){return Bm(e)?e:{}}function Bm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lr(e){return typeof e=="string"?e:""}import{randomUUID as bl}from"node:crypto";import{spawn as Vm}from"node:child_process";import{closeSync as Km,mkdirSync as Jm,openSync as qm}from"node:fs";import{dirname as Gm}from"node:path";var gn=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},et=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function zm(e){if(e==null||e.trim()==="")return null;try{return Jm(Gm(e),{recursive:!0}),qm(e,"a")}catch{return null}}function Qm(e){try{Km(e)}catch{}}function Ym(e){let n=[["project_label",e.project_label],["workspace_path",e.workspace_path],["command",e.command]];for(let[t,r]of n)if(typeof r!="string"||r.trim()==="")throw new gn(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new gn("redskilled worker spec args must be an array")}function Zm(e){if(e==null)throw new et("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new et(e.reason,e)}function _l(e){let{spec:n,admission:t}=e;Zm(t),Ym(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(n.worker_id??e.workerId??bl()).trim()||bl(),i=e.probes??tl(r),l=e.openLog===!1?null:zm(n.log_path),a=sl({workerId:s,projectLabel:n.project_label,workspacePath:n.workspace_path,command:n.command,args:n.args,budget:n.budget,...e.memoryCeiling!=null?{memoryCeiling:e.memoryCeiling}:{},target:n.placement,env:n.env,enabled:e.enabled??rl(r),probes:i,pipeOutput:l!==null}),u=(e.spawnFn??Vm)(a.command,a.args,{...a.cwd!=null?{cwd:a.cwd}:{},detached:!0,stdio:l===null?"ignore":["ignore",l,l],env:a.backend==="transient-unit"?{...r}:{...r,...n.env??{},...a.environment}});if(l!==null&&Qm(l),u.pid==null)throw u.once("error",()=>{}),new gn(`redskilled could not spawn ${JSON.stringify(a.command)} for worker ${s}`);let p=a.job!=null?Xm(a,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(b,y)=>{try{p?.job?.close()}catch{}e.onExit?.(s,b,y)}),u.unref();let f=a.job!=null?p?.job!=null:a.isolated,h=[a.warning,p?.warning,a.budgetWarning].filter(b=>b!=null);return{worker:{worker_id:s,project_label:n.project_label,pid:u.pid,started_at:o(),workspace_path:n.workspace_path,...n.log_path!=null?{log_path:n.log_path}:{},isolated:f,...a.unit!=null?{unit:a.unit}:{},...n.budget!=null?{budget:n.budget}:{},...a.memoryCeiling!=null?{memory_ceiling:a.memoryCeiling,memory_ceiling_reason:e.memoryCeiling?.reason??"this Worker's ceiling is the budget its client declared"}:{},warnings:h},admission:t,warnings:h,plan:a,child:u,...p?.job!=null?{job:p.job}:{}}}function Xm(e,n,t){let r=e.job;if(r==null)return{};let o="the Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling";if(!n.jobObjects.available)return{warning:`Job Object placement unavailable: ${n.jobObjects.reason}. ${o}`};let s;try{s=n.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(i){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${wl(i)}. ${o}`}}try{s.assign(t)}catch(i){try{s.close()}catch{}return{warning:`Worker pid ${t} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${wl(i)}. ${o}`}}return{job:s}}function wl(e){return e instanceof Error?e.message:String(e)}import{open as eg,stat as ng}from"node:fs/promises";var tg=16*1024;async function vl(e,n=tg){let t;try{t=(await ng(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let s=await eg(e,"r");try{let i=Buffer.alloc(r);await s.read(i,0,r,t-r),o=i.toString("utf8")}finally{await s.close()}}catch{return null}return rg(o)}function rg(e){let n=e.split(`
|
|
63
|
+
`);for(let t=n.length-1;t>=0;t-=1){let r=n[t].replace(/\r$/,"");if(r.trim()!=="")return r}return null}import{spawn as yg}from"node:child_process";import{existsSync as kg,readdirSync as Rg}from"node:fs";import{dirname as bg,join as Dl,resolve as wg}from"node:path";function U(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?{major:Number(n[1]),minor:Number(n[2]),patch:Number(n[3])}:null}function Ir(e,n){let t=U(e),r=U(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var Wb=4*60*60*1e3;re();re();import{spawnSync as og}from"node:child_process";import{mkdir as sg,rm as ig,writeFile as lg}from"node:fs/promises";import{existsSync as ag}from"node:fs";import{homedir as dg}from"node:os";import{dirname as cg,join as Tr}from"node:path";var We="redskilled.service",Nr="REDSKILLED_SUPERVISED",ug="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function pg(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||Tr(e.HOME?.trim()||dg(),".config");return Tr(n,"systemd","user")}function Wr(e=process.env){return Tr(pg(e),We)}function xl(e,n={}){let t=n.env??process.env,r=Hn(n.override??{},n.entryLookup??{}),o=[...r.args,...be(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:We,unitPath:Wr(t),command:r.command,args:o,text:fg(r.command,o,e)}}function fg(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${ug}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(mg).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Nr}=1"`,`Environment="REDSKILLED_SESSION=${Sl(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
|
|
64
|
+
`)}function mg(e){return/[\s"'\\$%]/.test(e)?`"${Sl(e)}"`:e}function Sl(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function El(e,n={}){let t=n.writeFile??gg,r=n.run??Cr,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(nt("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(nt("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function Pl(e={}){let n=e.removeFile??hg,t=e.run??Cr,r=Wr(e.env??process.env),o=[nt("disable",t,["systemctl","--user","disable","--now",We])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(nt("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function jl(e={}){let n=e.exists??ag,t=e.run??Cr,r=Wr(e.env??process.env),o=n(r);return{unitName:We,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",We]).status===0,active:o&&t(["systemctl","--user","is-active",We]).status===0,floor:"auto-spawn"}}function nt(e,n,t){let r=n(t),o=(r.stderr??r.stdout??"").trim();return{step:e,argv:t,ok:r.status===0,...o?{detail:o}:{}}}async function gg(e,n){await sg(cg(e),{recursive:!0}),await lg(e,n,{encoding:"utf8",mode:420})}async function hg(e){await ig(e,{force:!0})}function Cr(e){let n=og(e[0],[...e.slice(1)],{encoding:"utf8"});return n.error!=null?{status:null,stderr:n.error.message}:{status:n.status,stdout:n.stdout??"",stderr:n.stderr??""}}var Ol=75,Al=9e5,$l="redskilled-replacement-entry-unresolved",_g="REDSKILLED_NO_REGISTRY_PROBE",Ll="REDSKILLED_BORN_BY_REPLACEMENT";function Il(e=process.env){return e[Ll]==="1"}function Tl(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function Nl(e){let n=e.running.trim();if(hn(n))return null;let t=e.newest?.trim()??"",r=U(t),o=U(n);return r===null||o===null||r.major<=o.major?null:{version:t,running_major:o.major,held_major:r.major,reason:`redskilled ${t} is published and this daemon runs ${n}; a major version is deliberately never adopted by the background check, because a breaking change must not arrive on a machine that is holding Workers`,action:vg(r.major,e.supervised)}}function vg(e,n){let t=`install the ${e}.x bundle (update this machine's plugin pin), then `;return n?`${t}re-point the unit and restart it: redskilled unit install && systemctl --user restart redskilled.service`:`${t}stop this daemon \u2014 the next client start resolves the newly installed bundle`}function Wl(e){let n=e.running.trim();if(hn(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||U(t)===null?{act:"hold",reason:"published-unknown"}:Ir(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function hn(e){let n=e.trim();return U(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function Cl(e=process.env){return e[Nr]==="1"}var Mr=class extends Error{code=$l;searched;constructor(n,t){super(`${$l}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
|
|
65
65
|
searched:
|
|
66
66
|
${t.map(r=>` ${r}`).join(`
|
|
67
|
-
`)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function
|
|
68
|
-
`}function yh(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return G(n)}catch{return null}}}function kh(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||!Number.isInteger(n.pid)||n.pid<=0)return!1;for(let t of["start_time","session_key_hash","machine_id_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var Cr=3e5,Eh=1e4,Ph=6e4,jh=15e3,Hl=16,Ce=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},Dh="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Bl(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??Cr,o=e.clock??(()=>new Date().toISOString()),s=e.launch??pl,i=e.ceiling??Bs();e.repositoryActivity!=null&&mr(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??Fl(),a=e.leaseStore??Ul(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??si(),u={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},p=e.machineClaimStore??Hn(n.machineClaimPath,u,{clock:o});await vh(Sh(n.socketPath),{recursive:!0,mode:448});let f=await p.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new Ce(n.socketPath):new ue(p.claimPath,f.reason,f.claim);let g=await a.acquire(l);if(!g.acquired)throw await p.release(d).catch(()=>{}),new Ce(n.socketPath,g.lease);let k;try{k=await Oh(n.socketPath)}catch(c){throw await a.release(l).catch(()=>{}),await p.release(d).catch(()=>{}),c}let y=o(),b=e.eventLane??qs(n.eventLanePath),v=e.liveness??Yi,D=e.stopWorker??ol,V=e.unitInventory??(()=>el(n.machineClaimPath,Un({machineIdHash:n.machineIdHash}))?nl():[]),M=e.unitMainPid??Xi,pe=e.treeSampler??gi,we=e.readLogTail??fl,hn=e.sampleMs??jh,Gr=e.publishedVersion??(c=>Ll(c)),zr=e.replaceCheckMs??_l,Qr=e.publishedProbeTimeoutMs??Eh,va=e.localPublishedEvidence??(c=>$l(c,e.replacementIO?.env??process.env)),xa=e.bornByReplacement??xl(),Yr=e.replaceBootCheckMs??Ph,Zr=e.supervised??jl(),Xr=e.replacementIO??{},B=e.repositoryActivity,eo=B?.intervalMs??6e4,Ue=e.queueDiscovery,no=Ue?.transport??B?.transport,Sa=Ue?.unconfiguredReason??Dh,to=Ue?.intervalMs??15e3,ro=e.demandMs??15e3,Ea=e.demandBackoffMs??3e4,S=new Map,ie=new Set,_e=new Map,gn=new Map,A=new Map,et=new Set,oo={},nt=null,so=null,tt=null,io=!1,rt=0,ot=null,He="none",st=null,lo=null,it=null,le=null,yn=null,Ve=[],Be=null,lt=!1,ve,Je,Ke,qe,kn,Ge,ze,Z=!1,at=!1,Rn=null,ao,dt=new Promise(c=>{ao=c});function Qe(c){co(c);let m=Date.parse(c),h=pi(A.values(),m);for(let w of h.lapsed)A.delete(w.project_label),Pa(w,m);return h.lapsed}function Pa(c,m){let h=Number.isFinite(m)?new Date(m).toISOString():c.renew_by;Ve.push({project_label:c.project_label,at:h,renew_by:c.renew_by,renewals:c.renewals,sustains:c.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(c.project_label)}: it stood until ${c.renew_by} and nothing renewed it \u2014 no session spoke for it, and no poll found it work or a Worker to hold it up`}),Ve.length>Hl&&Ve.splice(0,Ve.length-Hl)}function co(c){if(A.size===0)return;let m=Date.parse(c);if(!Number.isFinite(m))return;let h={};for(let _ of S.values())h[_.project_label]=(h[_.project_label]??0)+1;let w=new Map((le?.projects??[]).map(_=>[_.project_label,_]));for(let _ of[...A.values()]){let j=w.get(_.project_label),Se=ci(_,{now:c,...j==null?{}:{queue:{outcome:j.outcome,depth:j.depth}},liveWorkers:h[_.project_label]??0});Se.registration!==_&&A.set(_.project_label,Se.registration)}}function bn(){let c=o();return Qe(c),Ai({now:c,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:l.pid,startedAt:y,scope:ii(p.claimPath,u,d),workers:[...S.values()],registrations:[...A.values()],lapses:Ve,queue:le,published:{version:so,checkedAt:tt,newer:io,replacement:He,newest:st,majorHold:lo,checks:rt,holdReason:ot}})}function wn(){return xi({hostState:bn(),ceiling:i,rss:oo,sampledAt:nt,logLines:Object.fromEntries(_e),displays:Object.fromEntries(gn),now:o(),reattachedWorkerIds:[...ie],repositoryActivity:it})}async function ct(){return B==null||B.projects.length===0?null:(it=await Ri({projects:B.projects,hostTokenRef:B.hostTokenRef,transport:B.transport,closedWindowMs:B.closedWindowMs,now:o()}),it)}async function uo(){let c=o();Qe(c);let m=[...A.values()].map(h=>({project_label:h.project_label,selector:h.selector})).sort((h,w)=>h.project_label.localeCompare(w.project_label));return m.length===0?null:no==null?(le=il(m,c,Sa),le):(le=await ll({projects:m,transport:no,now:c,...Ue?.batchSize==null?{}:{batchSize:Ue.batchSize}}),co(o()),le)}async function po(){let c=o();if(lt)return yn??Qs(c);lt=!0;try{let m={};for(let $ of S.values())m[$.project_label]=(m[$.project_label]??0)+1;let h={};for(let $ of le?.projects??[])h[$.project_label]=$.depth;let w=Date.parse(c),_=zs({projects:[...A.values()].map($=>({project_label:$.project_label,selector:$.selector,argv:$.argv,workspace_path:$.workspace_path,target:$.target})),queue:h,live:m,nowMs:Number.isFinite(w)?w:0,backoffUntilMs:Be}),j=[],Se=null;for(let $ of _.births){let En;try{En=ut({project_label:$.project_label,workspace_path:$.workspace_path,command:$.argv[0],args:$.argv.slice(1)})}catch(mt){Se=mt instanceof Error?mt.message:String(mt),Be=(Number.isFinite(w)?w:Date.now())+Ea;break}j.push({project_label:$.project_label,worker_id:En.worker.worker_id,pid:En.worker.pid,warnings:En.warnings})}return Se==null&&_.births.length>0&&(Be=null),yn={version:1,at:c,requested:_.births.length,granted:j,shortfall:_.births.length-j.length,refusal:Se,retry_after:Be==null?null:new Date(Be).toISOString(),projects:_.intents},yn}finally{lt=!1}}function ja(c){return Si(wn(),{...O,mode:c?.mode??O.mode,project:c?.project??O.project,maxWorkers:c?.max_workers??O.maxWorkers,maxProjects:c?.max_projects??O.maxProjects,maxWidth:c?.max_width??O.maxWidth,verbose:c?.verbose??O.verbose})}function Da(c){return Oi(wn(),{mode:c?.mode??Te.mode,project:c?.project??Te.project,maxWidth:c?.max_width??Te.maxWidth,maxRows:c?.max_rows??Te.maxRows})}function xe(c,m,h){return mi({op:c,sessionProject:m??null,targetProject:h})}async function Oa(c){let m=S.get(c.worker_id),h=xe(fi(c.command),c.session_project,m?.project_label??null);if(!h.permitted)throw new Error(h.reason);if(c.command!=="stop")throw new Error(`redskilled does not implement ${c.command}: it owns birth, death and limits, and ${c.command} is a work decision the project's own bundle makes on top of them`);let w=m!=null&&await Ia(m,c.detail??"stopped by its own project");return{version:1,command:c.command,worker_id:c.worker_id,applied:w,reach:h,detail:w?`redskilled stopped Worker ${JSON.stringify(c.worker_id)} of project ${JSON.stringify(m.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function _n(c){S.delete(c),ie.delete(c),_e.delete(c),gn.delete(c)}function fo(c){let m=S.get(c.worker_id),h=xe("worker-heartbeat",c.session_project,m?.project_label??null);if(!h.permitted)throw new Error(h.reason);if(typeof c.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(m==null)return{version:1,worker_id:c.worker_id,accepted:!1,reach:h,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to publish a line for`};let w=o();_e.set(c.worker_id,{line:c.last_log_line,published_at:w,source:"heartbeat"});let _=c.display===void 0?null:ji(c.display);return _!=null&&gn.set(c.worker_id,{display:_,published_at:w}),{version:1,worker_id:c.worker_id,accepted:!0,reach:h,published_at:w,detail:`redskilled stored a line for Worker ${JSON.stringify(c.worker_id)} without reading it`}}async function La(c,m,h){let w=`exit code=${m??"null"} signal=${h??"null"}`;if(c.unit!=null&&c.unit!==""&&await $a(c)){Aa(c,`its launch client ended (${w}) while unit ${JSON.stringify(c.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}_n(c.worker_id),X("worker-death",c,w,{exitCode:m,signal:h}),L()}async function $a(c){try{return await v(c)===!0}catch{return!1}}function Aa(c,m){let h=c.unit==null?null:M(c.unit);S.set(c.worker_id,{...c,...h!=null&&h>0?{pid:h}:{},warnings:[...c.warnings,m]}),ie.add(c.worker_id),L()}function mo(c,m){let h=xe("project-register",m,c.project_label);if(!h.permitted)throw new Error(h.reason);let w=o();Qe(w);let _=ai(c,{now:w,held:A.get(c.project_label)});return A.set(_.project_label,_),L(),{version:1,registration:_,reach:h,detail:`redskilled holds a registration for project ${JSON.stringify(_.project_label)} at a target of ${_.target} until ${_.renew_by}, and has read neither its selector nor its argv`}}function ho(c,m={}){let h=xe("project-renew",m.sessionProject,c);if(!h.permitted)throw new Error(h.reason);let w=o();Qe(w);let _=A.get(c);if(_==null)throw new Vn(c);let j=di(_,{now:w,...m.renewWithinMs==null?{}:{renew_within_ms:m.renewWithinMs},...m.launch==null?{}:{launch:m.launch}});return A.set(j.project_label,j),L(),{version:1,registration:j,reach:h,detail:`redskilled renewed the registration for project ${JSON.stringify(j.project_label)}, which now stands until ${j.renew_by} after renewal ${j.renewals}`+(m.launch==null?"":`, carrying launch revision ${j.launch_revision} for its next Worker`)}}function go(c,m){let h=xe("project-deregister",m,c);if(!h.permitted)throw new Error(h.reason);let w=A.delete(c);return{version:1,project_label:c,released:w,reach:h,detail:w?`redskilled released the registration for project ${JSON.stringify(c)}`:`redskilled held no registration for project ${JSON.stringify(c)}, so there was nothing to release`}}async function Ia(c,m){try{await D(c)}catch{}return _n(c.worker_id),X("worker-death",c,m),L(),!0}function yo(c){return Vs({ceiling:i,workers:[...S.values()],budget:c.budget,projectLabel:c.project_label})}function ut(c){let m=s({spec:c,admission:yo(c),clock:o,onExit:(h,w,_)=>{let j=S.get(h);if(j==null){L();return}La(j,w,_).catch(()=>{})}});return S.set(m.worker.worker_id,m.worker),X("worker-birth",m.worker,null),L(),m}function X(c,m,h,w={}){Z||b.record({event:c,worker:m,ts:o(),detail:h,...w.exitCode!==void 0?{exitCode:w.exitCode}:{},...w.signal!==void 0?{signal:w.signal}:{}}).catch(()=>{})}async function ko(){let c=[...ie].map(h=>S.get(h)).filter(h=>h!=null);if(c.length===0)return[];let{dead:m}=await Er(c,v);for(let h of m)_n(h.worker_id),X("worker-death",h,"the host no longer confirms this Worker");return m.length>0&&L(),m}async function Ro(c,m){let h=S.get(c);if(!h)return!1;try{await D(h)}catch{}return _n(c),X("worker-budget-kill",h,m),L(),!0}async function bo(){let c=[...S.values()];if(c.length===0)return[];let m;try{m=await pe(c)}catch{return[]}let h=m.rss;oo=h,nt=o(),Ta(m.cpu_seconds,nt);let{terminations:w}=hi({workers:c,rss:h}),_=[];for(let j of w)await Ro(j.worker_id,j.reason)&&_.push(j);return _}function Ta(c,m){for(let[h,w]of Object.entries(c)){if(typeof w!="number"||!Number.isFinite(w))continue;let _=S.get(h);_&&S.set(h,{..._,cpu:{cpu_seconds:w,sampled_at:m}})}}async function Na(){try{return Qr<=0?await Gr(t):await new Promise(c=>{let m=setTimeout(()=>c(pt()),Qr);m.unref(),Gr(t).then(h=>{clearTimeout(m),c(h)},()=>{clearTimeout(m),c(pt())})})}catch{return pt()}}function pt(){try{return va(t)}catch{return null}}async function wo(){if(fn(t))return rt+=1,tt=o(),ot="local-build",{act:"hold",reason:"local-build"};let c=Sl(await Na()),m=c.version;so=m,st=c.newest??null,tt=o(),lo=El({running:t,newest:st,supervised:Zr});let h=Pl({running:t,published:m,supervised:Zr});return io=h.act==="replace",rt+=1,ot=h.act==="hold"?h.reason:null,He!=="in-progress"&&(He=h.act==="replace"?"pending":"none"),h}async function vn(){let c=await wo();if(c.act!=="replace"||He==="in-progress")return c;let m=Dl(c,Xr);return He="in-progress",await b.flush().catch(()=>{}),await Sn({reason:"replaced"}),Ol(m,n,{...r==null?{}:{idleMs:r},io:Xr}),c}function Wa(){Z||qe!=null||zr<=0||(!xa&&Yr>0&&(kn=setTimeout(()=>{vn().catch(()=>{})},Yr),kn.unref()),qe=setInterval(()=>{vn().catch(()=>{})},zr),qe.unref())}function Ca(){Z||Je!=null||hn<=0||(Je=setInterval(()=>{bo().catch(()=>{})},hn),Je.unref())}function Ma(){Z||Ge!=null||B==null||B.projects.length===0||eo<=0||(ct().catch(()=>{}),Ge=setInterval(()=>{ct().catch(()=>{})},eo),Ge.unref())}function Fa(){Z||ze!=null||to<=0||(ze=setInterval(()=>{uo().catch(()=>{})},to),ze.unref())}function Ua(){Z||Ke!=null||ro<=0||(Ke=setInterval(()=>{po().catch(()=>{})},ro),Ke.unref())}function L(){Z||(ve&&clearTimeout(ve),ve=setTimeout(()=>{ko().catch(()=>{}).then(()=>_o())},r),ve.unref())}function _o(){return S.size>0?(L(),"held-by-workers"):(Qe(o()),A.size>0?(L(),"held-by-registrations"):(Ha(),"exited"))}async function Ha(){if(!fn(t)){if((await vn().catch(()=>null))?.act==="replace"||at||Z)return;if(S.size>0||A.size>0){L();return}}await Sn({reason:"idle"})}function xn(c){return Zs({reason:c,socketPath:n.socketPath,daemonVersion:t,pid:l.pid,workers:[...S.values()],projects:[...A.keys()]})}function vo(c){if(Rn!=null)return Rn;let m=c.reason??"requested",h=c.note?.trim();return Rn=b.recordDaemonStop({ts:o(),pid:l.pid,socketPath:n.socketPath,reason:m,detail:h==null||h===""?xn(m).detail:`${xn(m).detail} \u2014 ${h}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),Rn}async function Sn(c={}){if(at)return await dt;at=!0,await vo(c),Z=!0,ve&&clearTimeout(ve),Je&&clearInterval(Je),qe&&clearInterval(qe),kn&&clearTimeout(kn),Ge&&clearInterval(Ge),ze&&clearInterval(ze),Ke&&clearInterval(Ke),await b.flush().catch(()=>{}),k.close();for(let m of et)m.destroy();return await new Promise(m=>k.once("close",()=>m())),await Vl(n.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await p.release(d).catch(()=>{}),ao(),await dt}let Va=Gs(await b.read().catch(()=>[])),ft=await Er(Va,v);for(let c of ft.alive){let m=rl(c),h=m.unit==null||W(m.pid)?null:M(m.unit);S.set(m.worker_id,h!=null&&h>0?{...m,pid:h}:m),ie.add(m.worker_id)}for(let c of ft.dead)X("worker-death",c,"the Worker ended while no daemon was watching");let Ba=tl({units:await Promise.resolve(V()).catch(()=>[]),held:[...S.values()],mainPid:M,now:y});for(let c of Ba)S.set(c.worker_id,c),ie.add(c.worker_id),X("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of ft.alive){if(c.log_path==null||_e.has(c.worker_id))continue;let m=await we(c.log_path).catch(()=>null);m==null||m.trim()===""||_e.set(c.worker_id,{line:m,published_at:o(),source:"rehydrated"})}k.on("connection",c=>{et.add(c),c.once("close",()=>et.delete(c)),L(),Lh(c,async(m,h)=>{L();let w=await Ja(m);h(w),m.op==="shutdown"&&setImmediate(()=>void Sn({reason:"requested"}))})});async function Ja(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:Jn,daemon_version:t,pid:l.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:bn()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:wn()};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:ja(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:Da(c.dashboard)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:fo(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:mo(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:ho(c.project_label,{...c.session_project==null?{}:{sessionProject:c.session_project},...c.renew_within_ms==null?{}:{renewWithinMs:c.renew_within_ms},...c.launch==null?{}:{launch:c.launch}})};if(c.op==="project-deregister")return{id:c.id,ok:!0,value:go(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await Oa(c.command)};if(c.op==="worker-start"){let h=xe("worker-start",c.session_project,c.spec.project_label);if(!h.permitted)return{id:c.id,ok:!1,error:h.reason};let w=ut(c.spec);return await b.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:w.worker,admission:w.admission,warnings:w.warnings}}}if(c.op==="shutdown"){let h=xn("requested");return await vo({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:h}}let m=c;return{id:m.id??Zn(),ok:!1,error:`unsupported redskilled op: ${m.op??"unknown"}`}}catch(m){return{id:c.id??Zn(),ok:!1,error:m instanceof Error?m.message:String(m)}}}return L(),Ca(),Wa(),Ma(),Fa(),Ua(),{socketPath:n.socketPath,lease:g.lease,startedAt:y,closed:dt,startWorker:ut,admit:yo,ceiling:()=>i,killWorkerOverBudget:Ro,sampleMemoryBudgets:bo,pollRepositoryActivity:ct,pollQueueDiscovery:uo,queueDiscovery:()=>le,driveDemand:po,demand:()=>yn,sweepReattached:ko,publishWorkerHeartbeat:fo,reattached:()=>[...ie].map(c=>S.get(c)).filter(c=>c!=null),flushEvents:()=>b.flush(),trackWorker(c){S.set(c.worker_id,c),X("worker-birth",c,null),L()},releaseWorker(c){let m=S.get(c),h=S.delete(c);return ie.delete(c),_e.delete(c),gn.delete(c),m&&X("worker-death",m,"released by the daemon"),L(),h},workerCount:()=>S.size,registerProject:mo,renewProject:ho,deregisterProject:go,registrations:()=>bn().registrations??[],hostState:bn,statuslinePayload:wn,evaluateIdle:_o,observePublishedVersion:wo,checkForReplacement:vn,stopReport:xn,stop:Sn}}async function Oh(e){for(let n=0;n<2;n++){let t=xh();try{return await new Promise((r,o)=>{t.once("error",o),t.listen(e,()=>{t.off("error",o),r()})}),t}catch(r){if(t.close(),r.code!=="EADDRINUSE")throw r;if(await oe(e))throw new Ce(e);await Vl(e,{force:!0})}}throw new Ce(e)}async function oe(e,n=250){try{return(await In({socketPath:e,timeoutMs:n},{id:Zn(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function Lh(e,n){Os(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??Zn(),ok:!1,error:t instanceof Error?t.message:String(t)})})}te();var Nh=1e4,Me=class extends Error{constructor(t,r){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}`);this.socketPath=t;this.cause=r;this.name="RedskilledUnreachableError"}};async function Mr(e,n={}){try{return await Wh(e,n)}catch(t){throw t instanceof ue||t instanceof Me?t:new Me(e.socketPath,t)}}async function Wh(e,n){if(await Ah(Th(e.socketPath),{recursive:!0,mode:448}),await oe(e.socketPath))return"already-running";await Ch(e);let t=await Ls(e.lockPath);if(!t)return await Jl(e,n),"joined";try{if(await oe(e.socketPath))return"already-running";let r=await Uh(e,n);return await Jl(e,n,r),"spawned"}finally{await t.close(),await Ih(e.lockPath,{force:!0})}}async function Ch(e){let t=await Hn(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&W(t.pid))throw new ue(e.machineClaimPath,"held",t)}async function ql(e,n,t={}){await Mr(e,t);let r;try{r=await cn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:Kl()})}catch(o){throw new Me(e.socketPath,o)}if(!r.ok)throw new Error(r.error);return r.value}async function Gl(e,n={},t={}){if(!await oe(e.socketPath))return Xs(e.socketPath);let r;try{r=await cn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Kl(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new Me(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!sr(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await Mh(e.socketPath,n.settleTimeoutMs??5e3)?o:{...o,stopped:!1,detail:`${o.detail}; the daemon accepted the stop and is still answering on ${JSON.stringify(e.socketPath)}`}}async function Mh(e,n){let t=Date.now()+n;for(;;){if(!await oe(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function zl(e,n={}){let t=await ql(e,{op:"host-state"},n);if(!Ii(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Ql(e,n=void 0,t={}){let r=await ql(e,{op:"statusline-string",...t.sessionProject!=null?{session_project:t.sessionProject}:{},...n==null?{}:{render:Fh(n)}},t);if(!$i(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function Fh(e){return{mode:e.mode,project:e.project,max_workers:e.maxWorkers,max_projects:e.maxProjects,max_width:e.maxWidth,verbose:e.verbose}}async function Jl(e,n,t){let r=Date.now()+(n.readyTimeoutMs??Nh);for(;;){if(await oe(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=r){let o=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${o}`)}await new Promise(o=>setTimeout(o,25))}}async function Uh(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await Ms({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,...Re(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=$h(r.command,s,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return i.on("error",l=>{o.failure=l}),i.on("exit",(l,a)=>{o.exit=a?`died on ${a}`:`exited with code ${l??-1}`}),i.unref(),o}te();import{chmod as ra,mkdir as sa,readFile as ia,stat as Zh,writeFile as Xh}from"node:fs/promises";import{homedir as Hr}from"node:os";import{dirname as eg,join as Vr}from"node:path";import{join as Hh}from"node:path";var Yl=["local","tmp","host"],Vh="local",mn="plugins.dev.workspace.target";var Fr=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function Xl(e){let n=Le(e,mn),t=Kh(n??"").trim();return t===""?void 0:t}function ea(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:Vh};let t=Yl.find(r=>r===n.toLowerCase());if(t)return{kind:"preset",preset:t};if(n.startsWith("/")||n==="~"||n.startsWith("~/"))return{kind:"custom",parentDir:n};throw new Fr(`${mn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${Yl.join(", ")}) or an absolute parent directory for Workers.`)}function na(e,n){return e.kind==="preset"?e.preset==="host":Jh(Bh(e.parentDir,n),ke(n))}function Bh(e,n){return e==="~"?Zl(n):e.startsWith("~/")?Hh(n,e.slice(2)):Zl(e)}function Jh(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Zl(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function Kh(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}te();import{createHash as qh}from"node:crypto";import{hostname as Gh}from"node:os";import{join as Xn}from"node:path";var Fe="redskilled.sock",zh="REDSKILLED_SESSION";function Qh(e={}){let n=e.env??process.env,t=n[zh]?.trim();if(t)return t;let r=n.XDG_RUNTIME_DIR?.trim();return r||`uid:${e.uid??(typeof process.getuid=="function"?process.getuid():"nouid")}`}function Yh(e={}){return ta(e.host??Gh())}function se(e={}){let n=Qh(e),t=e.runtimeDir??Tn({key:`redskilled:${n}`,socketFileName:Fe,env:e.env,uid:e.uid}),r=Yh(e);return{sessionKey:n,sessionKeyHash:ta(n),machineIdHash:r,runtimeDir:t,socketPath:Xn(t,Fe),lockPath:Xn(t,"redskilled.spawn.lock"),leasePath:Xn(t,"redskilled.lease.toon"),eventLanePath:Xn(t,Ks),machineClaimPath:e.machineClaimPath??Un({env:e.env,machineIdHash:r,platform:e.platform})}}function ta(e){return qh("sha256").update(e).digest("hex").slice(0,12)}var Ur="run `/red-setup` (Section E3 \u2014 execution daemon), or `redskilled provision` directly";async function la(e=Hr()){let n=ke(e),t=await Jr(n);return t===void 0?(await sa(n,{recursive:!0,mode:z}),await ra(n,z),{path:n,created:!0,tightened:!1,mode:z}):t===z?{path:n,created:!1,tightened:!1,mode:t}:(await ra(n,z),{path:n,created:!1,tightened:!0,mode:z})}var aa={needed:!1,declaredBy:`no ${mn} in view`};async function Br(e={}){let n=e.homeDir??Hr(),t=e.declaredTarget?.trim();if(t)return oa(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return aa;let o=Vr(r,".red","config.yaml"),s=await ia(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=Xl(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:oa(i,n,o)}function oa(e,n,t){let r=`${mn}: ${e} (${t})`;try{return{needed:na(ea(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function da(e){let n=[ng(e),tg(e),rg(e),og(e)],t=n.filter(o=>o.verdict!=="ok");return{verdict:t.some(o=>o.verdict==="missing")?"missing":t.length>0?"degraded":"ok",rows:n,findings:t}}function ng(e){let n=e.homeNeed??aa;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:Ur}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??z;return t!==z?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${z.toString(8)}`,fix:`${Ur} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function tg(e){return Y(e.entry)?{check:"daemon-entry",verdict:"ok",evidence:`${e.entry.entry??e.entry.command} (resolved as ${e.entry.source})`,fix:""}:{check:"daemon-entry",verdict:"missing",evidence:`no published redskilled bundle; probed ${e.entry.searched.join(", ")||"nothing"}`,fix:"install or warm the RedSkills bundle for this host, then re-run `redskilled provision`"}}function rg(e){return e.reachable?{check:"reach",verdict:"ok",evidence:`daemon answered on ${e.socketPath}`,fix:""}:{check:"reach",verdict:"missing",evidence:`no daemon answered on ${e.socketPath}`,fix:`${Ur} \u2014 it starts the daemon and waits for the socket`}}function og(e){return{check:"supervisor-unit",verdict:"ok",evidence:e.supervisorUnit==="installed"?"redskilled.service is installed (optional supervision, Restart=on-failure)":e.supervisorUnit==="unsupported"?"optional: this host has no systemd --user session; auto-spawn is the only start path":"optional: not installed; auto-spawn already starts the daemon on first use",fix:""}}async function ca(e={}){let n=e.env??process.env,t=e.homeDir??Hr(),r=e.paths??se({env:n}),o=ke(t),[s,i,l]=await Promise.all([Jr(o),oe(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Br({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:ce(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await ig(lg(e,n,t),n)}}var sg="redskilled.service";function ua(e){return Vr(e,"systemd","user",sg)}function pa(e){let n=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${n}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
|
|
69
|
-
`)}async function
|
|
67
|
+
`)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function xg(e,n={}){let t=n.env??process.env,r=n.exists??kg,o=n.execPath??process.execPath,s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,l=[],a=[[Dl(Fn(t),i),"bundle-cache"]];s&&a.push([Dl(bg(wg(s)),i),"caller-sibling-bundle"]);for(let[c,u]of a)if(l.push(c),r(c))return{command:o,args:[c],version:e,source:u,searched:l};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new Mr(e,l);return{command:t.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:l}}function Ml(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>xg(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function Fl(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??Eg)(Ol),{...e,exitCode:Ol};let o=[...e.entry.args,...be(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??Sg(r.env))(e.entry,o),e}function Sg(e){return(n,t)=>{let r=yg(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[Ll]:"1"}});r.on("error",()=>{}),r.unref()}}function Eg(e){process.exitCode=e,process.exit(e)}async function Hl(e,n=process.env,t=Pg){let r=Bl(n),o=Vl(e,n);if(n[_g]==="1")return{version:o,newest:r};let s=U(e)===null?"0.0.0":e;try{let i=await Vs({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function Ul(e,n=process.env,t){let r=t??Fr;return{version:Vl(e,n,r),newest:Bl(n,r)}}function Bl(e=process.env,n=Fr){return Jl(Kl(e,n))}function Vl(e,n=process.env,t=Fr){let r=U(e.trim())?.major;return r===void 0?null:Jl(Kl(n,t).filter(o=>U(o)?.major===r))}function Kl(e,n){let t=[];for(let r of n(Fn(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||U(o)===null||t.push(o)}return t}function Jl(e){let n=null;for(let t of e)(n===null||Ir(t,n)>0)&&(n=t);return n}function Fr(e){try{return Rg(e)}catch{return[]}}async function Pg(e){let n=await fetch(e,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`registry read failed with HTTP ${n.status}`);return await n.text()}import{mkdir as jg,readFile as Dg,rename as Og,rm as Hr,writeFile as ql}from"node:fs/promises";import{randomUUID as $g}from"node:crypto";import{dirname as Ag}from"node:path";var tt=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function Br(e){let n;try{n=await Dg(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=Lg(n);return Ig(t)?t:void 0}var Gl;function Ql(){return Gl??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Gl}function Yl(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??W;async function s(){return await Br(e)}async function i(a){let c=`${e}.${a.pid}.${$g()}.tmp`;await ql(c,zl(a),{encoding:"utf8",mode:384}),await Og(c,e)}function l(a,c){return{version:1,pid:a.pid,start_time:a.startTime,session_key_hash:n.sessionKeyHash,machine_id_hash:n.machineIdHash,socket_path:n.socketPath,acquired_at:c,renewed_at:c}}return{read:s,async acquire(a){await jg(Ag(e),{recursive:!0,mode:448});let c=!1;for(;;){let u=r(),p=l(a,u);try{return await ql(e,zl(p),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:c,lease:p}}catch(h){if(h.code!=="EEXIST")throw h}let f=await s();if(!f){await Hr(e,{force:!0}),c=!0;continue}if(Ur(f,a))return{acquired:!0,reaped:c,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await Hr(e,{force:!0}),c=!0}},async renew(a){let c=await s();if(!c||!Ur(c,a))throw new tt(e);let u={...c,renewed_at:r()};return await i(u),u},async release(a){let c=await s();if(!c)return!1;if(!Ur(c,a))throw new tt(e);return await Hr(e,{force:!0}),!0}}}function Ur(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function zl(e){return`${I(e,{keyedMapCollapse:!0})}
|
|
68
|
+
`}function Lg(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return G(n)}catch{return null}}}function Ig(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||!Number.isInteger(n.pid)||n.pid<=0)return!1;for(let t of["start_time","session_key_hash","machine_id_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var Vr=3e5,Ug=1e4,Bg=6e4,Vg=15e3,Zl=16,Ce=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},Kg="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function ea(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??Vr,o=e.clock??(()=>new Date().toISOString()),s=e.launch??_l,i=e.ceiling??ei();e.repositoryActivity!=null&&wr(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??Ql(),a=e.leaseStore??Yl(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),c=e.machineOwner??gi(),u={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},p=e.machineClaimStore??Jn(n.machineClaimPath,u,{clock:o});await Mg(Hg(n.socketPath),{recursive:!0,mode:448});let f=await p.claim(c);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new Ce(n.socketPath):new pe(p.claimPath,f.reason,f.claim);let h=await a.acquire(l);if(!h.acquired)throw await p.release(c).catch(()=>{}),new Ce(n.socketPath,h.lease);let k;try{k=await Jg(n.socketPath)}catch(d){throw await a.release(l).catch(()=>{}),await p.release(c).catch(()=>{}),d}let b=o(),y=e.eventLane??ri(n.eventLanePath),_=e.liveness??ll,D=e.stopWorker??ml,B=e.unitInventory??(()=>cl(n.machineClaimPath,Kn({machineIdHash:n.machineIdHash}))?ul():[]),M=e.unitMainPid??dl,fe=e.treeSampler??Ei,_e=e.readLogTail??vl,kn=e.sampleMs??Vg,eo=e.publishedVersion??(d=>Hl(d)),no=e.replaceCheckMs??Al,to=e.publishedProbeTimeoutMs??Ug,La=e.localPublishedEvidence??(d=>Ul(d,e.replacementIO?.env??process.env)),Ia=e.bornByReplacement??Il(),ro=e.replaceBootCheckMs??Bg,oo=e.supervised??Cl(),so=e.replacementIO??{},V=e.repositoryActivity,io=V?.intervalMs??6e4,He=e.queueDiscovery,lo=He?.transport??V?.transport,Ta=He?.unconfiguredReason??Kg,ao=He?.intervalMs??15e3,co=e.demandMs??15e3,Na=e.demandBackoffMs??3e4,S=new Map,le=new Set,ve=new Map,Rn=new Map,L=new Map,st=new Set,uo={},it=null,po=null,lt=null,fo=!1,at=0,dt=null,Ue="none",ct=null,mo=null,ut=null,ae=null,bn=null,Be=[],Ve=null,pt=!1,xe,Ke,Je,qe,wn,Ge,ze,Z=!1,ft=!1,_n=null,go,mt=new Promise(d=>{go=d});function Qe(d){ho(d);let m=Date.parse(d),g=_i(L.values(),m);for(let w of g.lapsed)L.delete(w.project_label),Wa(w,m);return g.lapsed}function Wa(d,m){let g=Number.isFinite(m)?new Date(m).toISOString():d.renew_by;Be.push({project_label:d.project_label,at:g,renew_by:d.renew_by,renewals:d.renewals,sustains:d.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(d.project_label)}: it stood until ${d.renew_by} and nothing renewed it \u2014 no session spoke for it, and no poll found it work or a Worker to hold it up`}),Be.length>Zl&&Be.splice(0,Be.length-Zl)}function ho(d){if(L.size===0)return;let m=Date.parse(d);if(!Number.isFinite(m))return;let g={};for(let v of S.values())g[v.project_label]=(g[v.project_label]??0)+1;let w=new Map((ae?.projects??[]).map(v=>[v.project_label,v]));for(let v of[...L.values()]){let j=w.get(v.project_label),ee=bi(v,{now:d,...j==null?{}:{queue:{outcome:j.outcome,depth:j.depth}},liveWorkers:g[v.project_label]??0});ee.registration!==v&&L.set(v.project_label,ee.registration)}}function vn(){let d=o();return Qe(d),Bi({now:d,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:l.pid,startedAt:b,scope:hi(p.claimPath,u,c),workers:[...S.values()],registrations:[...L.values()],lapses:Be,queue:ae,published:{version:po,checkedAt:lt,newer:fo,replacement:Ue,newest:ct,majorHold:mo,checks:at,holdReason:dt}})}function xn(){return Ii({hostState:vn(),ceiling:i,rss:uo,sampledAt:it,logLines:Object.fromEntries(ve),displays:Object.fromEntries(Rn),now:o(),reattachedWorkerIds:[...le],repositoryActivity:ut,...e.deaths===void 0?{}:{deaths:e.deaths}})}async function gt(){return V==null||V.projects.length===0?null:(ut=await Di({projects:V.projects,hostTokenRef:V.hostTokenRef,transport:V.transport,closedWindowMs:V.closedWindowMs,now:o()}),ut)}async function yo(){let d=o();Qe(d);let m=[...L.values()].map(g=>({project_label:g.project_label,selector:g.selector})).sort((g,w)=>g.project_label.localeCompare(w.project_label));return m.length===0?null:lo==null?(ae=hl(m,d,Ta),ae):(ae=await yl({projects:m,transport:lo,now:d,...He?.batchSize==null?{}:{batchSize:He.batchSize}}),ho(o()),ae)}async function ko(){let d=o();if(pt)return bn??ii(d);pt=!0;try{let m={};for(let A of S.values())m[A.project_label]=(m[A.project_label]??0)+1;let g={};for(let A of ae?.projects??[])g[A.project_label]=A.depth;let w=Date.parse(d),v=si({projects:[...L.values()].map(A=>({project_label:A.project_label,selector:A.selector,argv:A.argv,workspace_path:A.workspace_path,target:A.target})),queue:g,live:m,nowMs:Number.isFinite(w)?w:0,backoffUntilMs:Ve}),j=[],ee=null;for(let A of v.births){let Dn;try{Dn=ht({project_label:A.project_label,workspace_path:A.workspace_path,command:A.argv[0],args:A.argv.slice(1)})}catch(Rt){ee=Rt instanceof Error?Rt.message:String(Rt),Ve=(Number.isFinite(w)?w:Date.now())+Na;break}j.push({project_label:A.project_label,worker_id:Dn.worker.worker_id,pid:Dn.worker.pid,warnings:Dn.warnings})}return ee==null&&v.births.length>0&&(Ve=null),bn={version:1,at:d,requested:v.births.length,granted:j,shortfall:v.births.length-j.length,refusal:ee,retry_after:Ve==null?null:new Date(Ve).toISOString(),projects:v.intents},bn}finally{pt=!1}}function Ca(d){return Ti(xn(),{...O,mode:d?.mode??O.mode,project:d?.project??O.project,maxWorkers:d?.max_workers??O.maxWorkers,maxProjects:d?.max_projects??O.maxProjects,maxWidth:d?.max_width??O.maxWidth,verbose:d?.verbose??O.verbose})}function Ma(d){return Fi(xn(),{mode:d?.mode??Te.mode,project:d?.project??Te.project,maxWidth:d?.max_width??Te.maxWidth,maxRows:d?.max_rows??Te.maxRows})}function Se(d,m,g){return xi({op:d,sessionProject:m??null,targetProject:g})}async function Fa(d){let m=S.get(d.worker_id),g=Se(vi(d.command),d.session_project,m?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(d.command!=="stop")throw new Error(`redskilled does not implement ${d.command}: it owns birth, death and limits, and ${d.command} is a work decision the project's own bundle makes on top of them`);let w=m!=null&&await Va(m,d.detail??"stopped by its own project");return{version:1,command:d.command,worker_id:d.worker_id,applied:w,reach:g,detail:w?`redskilled stopped Worker ${JSON.stringify(d.worker_id)} of project ${JSON.stringify(m.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(d.worker_id)} to stop`}}function Sn(d){S.delete(d),le.delete(d),ve.delete(d),Rn.delete(d)}function Ro(d){let m=S.get(d.worker_id),g=Se("worker-heartbeat",d.session_project,m?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(typeof d.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(m==null)return{version:1,worker_id:d.worker_id,accepted:!1,reach:g,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(d.worker_id)} to publish a line for`};let w=o();ve.set(d.worker_id,{line:d.last_log_line,published_at:w,source:"heartbeat"});let v=d.display===void 0?null:Ci(d.display);return v!=null&&Rn.set(d.worker_id,{display:v,published_at:w}),{version:1,worker_id:d.worker_id,accepted:!0,reach:g,published_at:w,detail:`redskilled stored a line for Worker ${JSON.stringify(d.worker_id)} without reading it`}}async function Ha(d,m,g){let w=`exit code=${m??"null"} signal=${g??"null"}`;if(d.unit!=null&&d.unit!==""&&await Ua(d)){Ba(d,`its launch client ended (${w}) while unit ${JSON.stringify(d.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}Sn(d.worker_id),X("worker-death",d,w,{exitCode:m,signal:g}),$()}async function Ua(d){try{return await _(d)===!0}catch{return!1}}function Ba(d,m){let g=d.unit==null?null:M(d.unit);S.set(d.worker_id,{...d,...g!=null&&g>0?{pid:g}:{},warnings:[...d.warnings,m]}),le.add(d.worker_id),$()}function bo(d,m){let g=Se("project-register",m,d.project_label);if(!g.permitted)throw new Error(g.reason);let w=o();Qe(w);let v=ki(d,{now:w,held:L.get(d.project_label)});return L.set(v.project_label,v),$(),{version:1,registration:v,reach:g,detail:`redskilled holds a registration for project ${JSON.stringify(v.project_label)} at a target of ${v.target} until ${v.renew_by}, and has read neither its selector nor its argv`}}function wo(d,m={}){let g=Se("project-renew",m.sessionProject,d);if(!g.permitted)throw new Error(g.reason);let w=o();Qe(w);let v=L.get(d);if(v==null)throw new qn(d);let j=Ri(v,{now:w,...m.renewWithinMs==null?{}:{renew_within_ms:m.renewWithinMs},...m.launch==null?{}:{launch:m.launch}});return L.set(j.project_label,j),$(),{version:1,registration:j,reach:g,detail:`redskilled renewed the registration for project ${JSON.stringify(j.project_label)}, which now stands until ${j.renew_by} after renewal ${j.renewals}`+(m.launch==null?"":`, carrying launch revision ${j.launch_revision} for its next Worker`)}}function _o(d,m){let g=Se("project-deregister",m,d);if(!g.permitted)throw new Error(g.reason);let w=L.delete(d);return{version:1,project_label:d,released:w,reach:g,detail:w?`redskilled released the registration for project ${JSON.stringify(d)}`:`redskilled held no registration for project ${JSON.stringify(d)}, so there was nothing to release`}}async function Va(d,m){try{await D(d)}catch{}return Sn(d.worker_id),X("worker-death",d,m),$(),!0}function vo(d){return Zs({ceiling:i,workers:[...S.values()],budget:d.budget,projectLabel:d.project_label})}function ht(d){let m=Xs({ceiling:i,workers:[...S.values()],budget:d.budget}),g=s({spec:d,admission:vo(d),memoryCeiling:m,clock:o,onExit:(w,v,j)=>{let ee=S.get(w);if(ee==null){$();return}Ha(ee,v,j).catch(()=>{})}});return S.set(g.worker.worker_id,g.worker),X("worker-birth",g.worker,null),$(),g}function X(d,m,g,w={}){Z||y.record({event:d,worker:m,ts:o(),detail:g,...w.exitCode!==void 0?{exitCode:w.exitCode}:{},...w.signal!==void 0?{signal:w.signal}:{}}).catch(()=>{})}async function xo(){let d=[...le].map(g=>S.get(g)).filter(g=>g!=null);if(d.length===0)return[];let{dead:m}=await Ar(d,_);for(let g of m)Sn(g.worker_id),X("worker-death",g,"the host no longer confirms this Worker");return m.length>0&&$(),m}async function So(d,m){let g=S.get(d);if(!g)return!1;try{await D(g)}catch{}return Sn(d),X("worker-budget-kill",g,m),$(),!0}async function Eo(){let d=[...S.values()];if(d.length===0)return[];let m;try{m=await fe(d)}catch{return[]}let g=m.rss;uo=g,it=o(),Ka(m.cpu_seconds,it);let{terminations:w}=Si({workers:d,rss:g}),v=[];for(let j of w)await So(j.worker_id,j.reason)&&v.push(j);return v}function Ka(d,m){for(let[g,w]of Object.entries(d)){if(typeof w!="number"||!Number.isFinite(w))continue;let v=S.get(g);v&&S.set(g,{...v,cpu:{cpu_seconds:w,sampled_at:m}})}}async function Ja(){try{return to<=0?await eo(t):await new Promise(d=>{let m=setTimeout(()=>d(yt()),to);m.unref(),eo(t).then(g=>{clearTimeout(m),d(g)},()=>{clearTimeout(m),d(yt())})})}catch{return yt()}}function yt(){try{return La(t)}catch{return null}}async function Po(){if(hn(t))return at+=1,lt=o(),dt="local-build",{act:"hold",reason:"local-build"};let d=Tl(await Ja()),m=d.version;po=m,ct=d.newest??null,lt=o(),mo=Nl({running:t,newest:ct,supervised:oo});let g=Wl({running:t,published:m,supervised:oo});return fo=g.act==="replace",at+=1,dt=g.act==="hold"?g.reason:null,Ue!=="in-progress"&&(Ue=g.act==="replace"?"pending":"none"),g}async function En(){let d=await Po();if(d.act!=="replace"||Ue==="in-progress")return d;let m=Ml(d,so);return Ue="in-progress",await y.flush().catch(()=>{}),await jn({reason:"replaced"}),Fl(m,n,{...r==null?{}:{idleMs:r},io:so}),d}function qa(){Z||qe!=null||no<=0||(!Ia&&ro>0&&(wn=setTimeout(()=>{En().catch(()=>{})},ro),wn.unref()),qe=setInterval(()=>{En().catch(()=>{})},no),qe.unref())}function Ga(){Z||Ke!=null||kn<=0||(Ke=setInterval(()=>{Eo().catch(()=>{})},kn),Ke.unref())}function za(){Z||Ge!=null||V==null||V.projects.length===0||io<=0||(gt().catch(()=>{}),Ge=setInterval(()=>{gt().catch(()=>{})},io),Ge.unref())}function Qa(){Z||ze!=null||ao<=0||(ze=setInterval(()=>{yo().catch(()=>{})},ao),ze.unref())}function Ya(){Z||Je!=null||co<=0||(Je=setInterval(()=>{ko().catch(()=>{})},co),Je.unref())}function $(){Z||(xe&&clearTimeout(xe),xe=setTimeout(()=>{xo().catch(()=>{}).then(()=>jo())},r),xe.unref())}function jo(){return S.size>0?($(),"held-by-workers"):(Qe(o()),L.size>0?($(),"held-by-registrations"):(Za(),"exited"))}async function Za(){if(!hn(t)){if((await En().catch(()=>null))?.act==="replace"||ft||Z)return;if(S.size>0||L.size>0){$();return}}await jn({reason:"idle"})}function Pn(d){return ai({reason:d,socketPath:n.socketPath,daemonVersion:t,pid:l.pid,workers:[...S.values()],projects:[...L.keys()]})}function Do(d){if(_n!=null)return _n;let m=d.reason??"requested",g=d.note?.trim();return _n=y.recordDaemonStop({ts:o(),pid:l.pid,socketPath:n.socketPath,reason:m,detail:g==null||g===""?Pn(m).detail:`${Pn(m).detail} \u2014 ${g}`,...d.signal==null?{}:{signal:d.signal}}).catch(()=>{}),_n}async function jn(d={}){if(ft)return await mt;ft=!0,await Do(d),Z=!0,xe&&clearTimeout(xe),Ke&&clearInterval(Ke),qe&&clearInterval(qe),wn&&clearTimeout(wn),Ge&&clearInterval(Ge),ze&&clearInterval(ze),Je&&clearInterval(Je),await y.flush().catch(()=>{}),k.close();for(let m of st)m.destroy();return await new Promise(m=>k.once("close",()=>m())),await Xl(n.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await p.release(c).catch(()=>{}),go(),await mt}let Xa=oi(await y.read().catch(()=>[])),kt=await Ar(Xa,_);for(let d of kt.alive){let m=fl(d),g=m.unit==null||W(m.pid)?null:M(m.unit);S.set(m.worker_id,g!=null&&g>0?{...m,pid:g}:m),le.add(m.worker_id)}for(let d of kt.dead)X("worker-death",d,"the Worker ended while no daemon was watching");let ed=pl({units:await Promise.resolve(B()).catch(()=>[]),held:[...S.values()],mainPid:M,now:b});for(let d of ed)S.set(d.worker_id,d),le.add(d.worker_id),X("worker-birth",d,"adopted from an active unit with no birth on this lane");for(let d of kt.alive){if(d.log_path==null||ve.has(d.worker_id))continue;let m=await _e(d.log_path).catch(()=>null);m==null||m.trim()===""||ve.set(d.worker_id,{line:m,published_at:o(),source:"rehydrated"})}k.on("connection",d=>{st.add(d),d.once("close",()=>st.delete(d)),$(),qg(d,async(m,g)=>{$();let w=await nd(m);g(w),m.op==="shutdown"&&setImmediate(()=>void jn({reason:"requested"}))})});async function nd(d){try{if(d.op==="ping")return{id:d.id,ok:!0,value:{pong:!0,protocol_version:Qn,daemon_version:t,pid:l.pid}};if(d.op==="host-state")return{id:d.id,ok:!0,value:vn()};if(d.op==="statusline-payload")return{id:d.id,ok:!0,value:xn()};if(d.op==="statusline-string")return{id:d.id,ok:!0,value:Ca(d.render)};if(d.op==="statusline-dashboard")return{id:d.id,ok:!0,value:Ma(d.dashboard)};if(d.op==="worker-heartbeat")return{id:d.id,ok:!0,value:Ro(d.heartbeat)};if(d.op==="project-register")return{id:d.id,ok:!0,value:bo(d.registration,d.session_project)};if(d.op==="project-renew")return{id:d.id,ok:!0,value:wo(d.project_label,{...d.session_project==null?{}:{sessionProject:d.session_project},...d.renew_within_ms==null?{}:{renewWithinMs:d.renew_within_ms},...d.launch==null?{}:{launch:d.launch}})};if(d.op==="project-deregister")return{id:d.id,ok:!0,value:_o(d.project_label,d.session_project)};if(d.op==="worker-command")return{id:d.id,ok:!0,value:await Fa(d.command)};if(d.op==="worker-start"){let g=Se("worker-start",d.session_project,d.spec.project_label);if(!g.permitted)return{id:d.id,ok:!1,error:g.reason};let w=ht(d.spec);return await y.flush().catch(()=>{}),{id:d.id,ok:!0,value:{worker:w.worker,admission:w.admission,warnings:w.warnings}}}if(d.op==="shutdown"){let g=Pn("requested");return await Do({reason:"requested",...d.detail==null?{}:{note:d.detail}}),{id:d.id,ok:!0,value:g}}let m=d;return{id:m.id??rt(),ok:!1,error:`unsupported redskilled op: ${m.op??"unknown"}`}}catch(m){return{id:d.id??rt(),ok:!1,error:m instanceof Error?m.message:String(m)}}}return $(),Ga(),qa(),za(),Qa(),Ya(),{socketPath:n.socketPath,lease:h.lease,startedAt:b,closed:mt,startWorker:ht,admit:vo,ceiling:()=>i,killWorkerOverBudget:So,sampleMemoryBudgets:Eo,pollRepositoryActivity:gt,pollQueueDiscovery:yo,queueDiscovery:()=>ae,driveDemand:ko,demand:()=>bn,sweepReattached:xo,publishWorkerHeartbeat:Ro,reattached:()=>[...le].map(d=>S.get(d)).filter(d=>d!=null),flushEvents:()=>y.flush(),trackWorker(d){S.set(d.worker_id,d),X("worker-birth",d,null),$()},releaseWorker(d){let m=S.get(d),g=S.delete(d);return le.delete(d),ve.delete(d),Rn.delete(d),m&&X("worker-death",m,"released by the daemon"),$(),g},workerCount:()=>S.size,registerProject:bo,renewProject:wo,deregisterProject:_o,registrations:()=>vn().registrations??[],hostState:vn,statuslinePayload:xn,evaluateIdle:jo,observePublishedVersion:Po,checkForReplacement:En,stopReport:Pn,stop:jn}}async function Jg(e){for(let n=0;n<2;n++){let t=Fg();try{return await new Promise((r,o)=>{t.once("error",o),t.listen(e,()=>{t.off("error",o),r()})}),t}catch(r){if(t.close(),r.code!=="EADDRINUSE")throw r;if(await se(e))throw new Ce(e);await Xl(e,{force:!0})}}throw new Ce(e)}async function se(e,n=250){try{return(await Wn({socketPath:e,timeoutMs:n},{id:rt(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function qg(e,n){Ms(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??rt(),ok:!1,error:t instanceof Error?t.message:String(t)})})}re();var Zg=1e4,Me=class extends Error{constructor(t,r){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}`);this.socketPath=t;this.cause=r;this.name="RedskilledUnreachableError"}};async function Kr(e,n={}){try{return await Xg(e,n)}catch(t){throw t instanceof pe||t instanceof Me?t:new Me(e.socketPath,t)}}async function Xg(e,n){if(await zg(Yg(e.socketPath),{recursive:!0,mode:448}),await se(e.socketPath))return"already-running";await eh(e);let t=await Fs(e.lockPath);if(!t)return await na(e,n),"joined";try{if(await se(e.socketPath))return"already-running";let r=await rh(e,n);return await na(e,n,r),"spawned"}finally{await t.close(),await Qg(e.lockPath,{force:!0})}}async function eh(e){let t=await Jn(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&W(t.pid))throw new pe(e.machineClaimPath,"held",t)}async function ra(e,n,t={}){await Kr(e,t);let r;try{r=await fn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:ta()})}catch(o){throw new Me(e.socketPath,o)}if(!r.ok)throw new Error(r.error);return r.value}async function oa(e,n={},t={}){if(!await se(e.socketPath))return di(e.socketPath);let r;try{r=await fn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:ta(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new Me(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!pr(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await nh(e.socketPath,n.settleTimeoutMs??5e3)?o:{...o,stopped:!1,detail:`${o.detail}; the daemon accepted the stop and is still answering on ${JSON.stringify(e.socketPath)}`}}async function nh(e,n){let t=Date.now()+n;for(;;){if(!await se(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function sa(e,n={}){let t=await ra(e,{op:"host-state"},n);if(!Vi(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function ia(e,n=void 0,t={}){let r=await ra(e,{op:"statusline-string",...t.sessionProject!=null?{session_project:t.sessionProject}:{},...n==null?{}:{render:th(n)}},t);if(!Ui(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function th(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 na(e,n,t){let r=Date.now()+(n.readyTimeoutMs??Zg);for(;;){if(await se(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=r){let o=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${o}`)}await new Promise(o=>setTimeout(o,25))}}async function rh(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await Gs({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,...be(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=Gg(r.command,s,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return i.on("error",l=>{o.failure=l}),i.on("exit",(l,a)=>{o.exit=a?`died on ${a}`:`exited with code ${l??-1}`}),i.unref(),o}re();import{chmod as fa,mkdir as ga,readFile as ha,stat as mh,writeFile as gh}from"node:fs/promises";import{homedir as Gr}from"node:os";import{dirname as hh,join as zr}from"node:path";import{join as oh}from"node:path";var la=["local","tmp","host"],sh="local",yn="plugins.dev.workspace.target";var Jr=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function da(e){let n=$e(e,yn),t=ah(n??"").trim();return t===""?void 0:t}function ca(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:sh};let t=la.find(r=>r===n.toLowerCase());if(t)return{kind:"preset",preset:t};if(n.startsWith("/")||n==="~"||n.startsWith("~/"))return{kind:"custom",parentDir:n};throw new Jr(`${yn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${la.join(", ")}) or an absolute parent directory for Workers.`)}function ua(e,n){return e.kind==="preset"?e.preset==="host":lh(ih(e.parentDir,n),Re(n))}function ih(e,n){return e==="~"?aa(n):e.startsWith("~/")?oh(n,e.slice(2)):aa(e)}function lh(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function aa(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function ah(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}re();import{createHash as dh}from"node:crypto";import{hostname as ch}from"node:os";import{join as ot}from"node:path";var Fe="redskilled.sock",uh="REDSKILLED_SESSION";function ph(e={}){let n=e.env??process.env,t=n[uh]?.trim();if(t)return t;let r=n.XDG_RUNTIME_DIR?.trim();return r||`uid:${e.uid??(typeof process.getuid=="function"?process.getuid():"nouid")}`}function fh(e={}){return pa(e.host??ch())}function ie(e={}){let n=ph(e),t=e.runtimeDir??Cn({key:`redskilled:${n}`,socketFileName:Fe,env:e.env,uid:e.uid}),r=fh(e);return{sessionKey:n,sessionKeyHash:pa(n),machineIdHash:r,runtimeDir:t,socketPath:ot(t,Fe),lockPath:ot(t,"redskilled.spawn.lock"),leasePath:ot(t,"redskilled.lease.toon"),eventLanePath:ot(t,ti),machineClaimPath:e.machineClaimPath??Kn({env:e.env,machineIdHash:r,platform:e.platform})}}function pa(e){return dh("sha256").update(e).digest("hex").slice(0,12)}var qr="run `/red-setup` (Section E3 \u2014 execution daemon), or `redskilled provision` directly";async function ya(e=Gr()){let n=Re(e),t=await Yr(n);return t===void 0?(await ga(n,{recursive:!0,mode:z}),await fa(n,z),{path:n,created:!0,tightened:!1,mode:z}):t===z?{path:n,created:!1,tightened:!1,mode:t}:(await fa(n,z),{path:n,created:!1,tightened:!0,mode:z})}var ka={needed:!1,declaredBy:`no ${yn} in view`};async function Qr(e={}){let n=e.homeDir??Gr(),t=e.declaredTarget?.trim();if(t)return ma(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return ka;let o=zr(r,".red","config.yaml"),s=await ha(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=da(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:ma(i,n,o)}function ma(e,n,t){let r=`${yn}: ${e} (${t})`;try{return{needed:ua(ca(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function Ra(e){let n=[yh(e),kh(e),Rh(e),bh(e)],t=n.filter(o=>o.verdict!=="ok");return{verdict:t.some(o=>o.verdict==="missing")?"missing":t.length>0?"degraded":"ok",rows:n,findings:t}}function yh(e){let n=e.homeNeed??ka;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:qr}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??z;return t!==z?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${z.toString(8)}`,fix:`${qr} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function kh(e){return Y(e.entry)?{check:"daemon-entry",verdict:"ok",evidence:`${e.entry.entry??e.entry.command} (resolved as ${e.entry.source})`,fix:""}:{check:"daemon-entry",verdict:"missing",evidence:`no published redskilled bundle; probed ${e.entry.searched.join(", ")||"nothing"}`,fix:"install or warm the RedSkills bundle for this host, then re-run `redskilled provision`"}}function Rh(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:`${qr} \u2014 it starts the daemon and waits for the socket`}}function bh(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 ba(e={}){let n=e.env??process.env,t=e.homeDir??Gr(),r=e.paths??ie({env:n}),o=Re(t),[s,i,l]=await Promise.all([Yr(o),se(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Qr({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:ue(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await _h(vh(e,n,t),n)}}var wh="redskilled.service";function wa(e){return zr(e,"systemd","user",wh)}function _a(e){let n=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${n}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
|
|
69
|
+
`)}async function va(e){let n=wa(e.configHome);return await Yr(n)!==void 0?{path:n,status:"already-present"}:(await ga(hh(n),{recursive:!0}),await gh(n,e.unit,"utf8"),{path:n,status:"installed"})}async function _h(e,n){if(process.platform!=="linux")return"unsupported";try{return await ha(wa(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function vh(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??zr(t,".config")}async function Yr(e){try{return(await mh(e)).mode&511}catch{return}}import{readdir as Sa,rm as xh,stat as Sh}from"node:fs/promises";import{dirname as Eh,join as Zr}from"node:path";var Ph=5*6e4,jh="redskilled.";function Dh(e={}){let n=e.env??process.env,t=i=>Eh(Cn({key:"redskilled:reclaim-probe",socketFileName:Fe,env:i,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=n,s=[t(n),t(o)];return[...new Set(s)]}async function Ea(e={}){let n=e.roots??Dh(e),t=e.graceMs??Ph,r=e.now??Date.now,o=e.isPidAlive??W,s=e.answers??Lh,i=e.dryRun===!0,l=[];for(let a of n){let c;try{c=(await Sa(a,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name)}catch{continue}for(let u of c.sort())l.push(await Oh(Zr(a,u),{graceMs:t,now:r,pidAlive:o,answers:s,dryRun:i}))}return{roots:n,scanned:l.length,reclaimed:l.filter(a=>a.verdict==="reclaimed").length,dryRun:i,entries:l}}async function Oh(e,n){let t;try{t=(await Sa(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:Pa(i),removed:[]}}let r=t.filter(i=>i.startsWith(jh));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await $h(Zr(e,"redskilled.lease.toon"));if(o!==void 0)return await n.pidAlive(o.pid)?{dir:e,verdict:"live",reason:`lease pid ${o.pid} is alive`,removed:[]}:await xa(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(Fe)&&await n.answers(Zr(e,Fe)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await Ah(e,n.now);return s!==void 0&&s<n.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(s/1e3)}s ago`,removed:[]}:await xa(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function xa(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await xh(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:Pa(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function $h(e){try{return await Br(e)}catch{return}}async function Ah(e,n){try{return Math.max(0,n()-(await Sh(e)).mtimeMs)}catch{return}}async function Lh(e){try{return(await fn({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function Pa(e){return e instanceof Error?e.message:String(e)}var Ih="plugins.dev.statusline",Th="dev.statusline";function Nh(e){let n=[],t=l=>{for(let a of[Ih,Th]){let c=`${a}.${l}`,u=$e(e,c)?.trim();if(u!=null&&u!=="")return{key:c,value:u}}},r=t("mode"),o={};r!=null&&(r.value==="local"||r.value==="global"?o.mode=r.value:n.push({...r,reason:"expected `local` or `global`"}));let s=[{leaf:"max_workers",assign:l=>{o.maxWorkers=l}},{leaf:"max_projects",assign:l=>{o.maxProjects=l}},{leaf:"max_width",assign:l=>{o.maxWidth=l}}];for(let l of s){let a=t(l.leaf);if(a==null)continue;let c=Number(a.value);Number.isInteger(c)&&c>=0?l.assign(c):n.push({...a,reason:"expected a whole number of zero or more"})}let i=t("verbose");return i!=null&&(i.value==="true"||i.value==="false"?o.verbose=i.value==="true":n.push({...i,reason:"expected `true` or `false`"})),{config:o,warnings:n}}var Wh={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 ja(e){let{values:n,positionals:t}=ye(e,Wh),r=[],o={},s=n.mode??t.find(l=>l==="global"||l==="local");s!=null&&(s==="local"||s==="global"?o.mode=s:r.push({key:"--mode",value:s,reason:"expected `local` or `global`"})),n.project!=null&&(o.project=n.project),n.verbose!==void 0&&(o.verbose=n.verbose===!0);let i=[{flag:"max-workers",assign:l=>{o.maxWorkers=l}},{flag:"max-projects",assign:l=>{o.maxProjects=l}},{flag:"max-width",assign:l=>{o.maxWidth=l}}];for(let l of i){let a=n[l.flag];if(a==null)continue;let c=Number(a);Number.isInteger(c)&&c>=0?l.assign(c):r.push({key:`--${l.flag}`,value:a,reason:"expected a whole number of zero or more"})}return{flags:o,warnings:r}}function Da(e={}){let n=e.configText==null?{config:{},warnings:[]}:Nh(e.configText),t=e.flags??{};return{options:{...O,mode:t.mode??n.config.mode??O.mode,project:t.project!==void 0?t.project:e.project??O.project,maxWorkers:t.maxWorkers??n.config.maxWorkers??O.maxWorkers,maxProjects:t.maxProjects??n.config.maxProjects??O.maxProjects,maxWidth:t.maxWidth??n.config.maxWidth??O.maxWidth,verbose:t.verbose??n.config.verbose??O.verbose},warnings:n.warnings}}var Mh=`Usage: redskilled <command> [options]
|
|
70
70
|
|
|
71
71
|
Commands:
|
|
72
72
|
host-state (default) print the host's state as JSON
|
|
@@ -78,7 +78,7 @@ Commands:
|
|
|
78
78
|
|
|
79
79
|
Run \`redskilled <command> --help\` for a command's own usage.
|
|
80
80
|
\`--version\` (\`-v\`) prints the build stamp; both answer offline.
|
|
81
|
-
`,
|
|
81
|
+
`,Fh={serve:`Usage: redskilled serve [options]
|
|
82
82
|
|
|
83
83
|
Runs the daemon in this process. Every path is a flag and none is derived
|
|
84
84
|
(ADR 0130 rule 3); what is absent falls back to the session derivation.
|
|
@@ -142,19 +142,19 @@ Reports every session runtime dir it looked at and why it kept or removed it.
|
|
|
142
142
|
|
|
143
143
|
--dry-run the same report with nothing removed
|
|
144
144
|
--grace-ms <n> how long a dir must be idle before it is reclaimed
|
|
145
|
-
`};function
|
|
146
|
-
`:`${
|
|
147
|
-
`),0}if(
|
|
148
|
-
`);let
|
|
149
|
-
`),0}var
|
|
150
|
-
`),o.running&&!o.stopped?1:0}async function
|
|
151
|
-
`),0;if(o==="install"){let s=await
|
|
152
|
-
`),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await
|
|
153
|
-
`),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function
|
|
154
|
-
`);let l;try{l=await
|
|
155
|
-
`),l=
|
|
145
|
+
`};function Hh(e){return e==="--help"||e==="-h"||e==="help"}var Uh={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)}},$a="REDSKILLED_HOST_TOKEN";function Aa(){try{let n=Ch("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function Bh(e=process.env,n=Aa){let t=(e[$a]??e.GITHUB_TOKEN??e.GH_TOKEN??"").trim();if(t!=="")return{token:t,source:"env"};let r=(n()??"").trim();return r!==""?{token:r,source:"tracker-cli"}:null}function Vh(e,n=process.env,t=Aa){let r=e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},o=Bh(n,t);if(o==null)return{...r,unconfiguredReason:`no credential names a tracker for this host: ${$a}, GITHUB_TOKEN and GH_TOKEN are all unset in the daemon's environment and \`gh auth token\` returned nothing \u2014 so no queue depth is asked for, and no depth is invented either`};let s=e["queue-endpoint"]??n.GITHUB_GRAPHQL_URL;return{...r,transport:$i({token:o.token,...s?{endpoint:s}:{}})}}async function Kh(e){if(e[0]==="--version"||e[0]==="-v"){let o=Lt("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
|
|
146
|
+
`:`${Yo(o)}
|
|
147
|
+
`),0}if(Hh(e[0]))return process.stdout.write(Mh),0;let{command:n,args:t}=ns(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(Fh[n]),0;if(n==="serve"){let{values:o}=ye(t,Uh),s=Vh(o),i=Oa(Re(Xr()),"state"),l=ws({stateRoot:i});process.stderr.write(`${_s(l)}
|
|
148
|
+
`);let a=hs({lanePath:rn(i),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),c=await ea({paths:ty(o),idleMs:o["idle-ms"]??Vr,daemonVersion:o["daemon-version"]??Lt("redskilled").version,deaths:l.attributions,queueDiscovery:s,...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let u of["SIGTERM","SIGINT"])process.once(u,()=>void c.stop({reason:"signal",signal:u}).catch(()=>{}));return await c.closed,a.phase("closed"),0}if(n==="stop")return await qh(t);if(n==="statusline")return await zh(t);if(n==="unit")return await Gh(t);if(n==="provision")return await Yh(t);if(n==="reclaim")return await Xh(t);let r=await sa(ie());return process.stdout.write(`${JSON.stringify(r,null,2)}
|
|
149
|
+
`),0}var Jh={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function qh(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=ye(e,Jh),o=await oa(n.paths??ie(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${I({running:o.running,stopped:o.stopped,reason:o.reason,socket:o.socket_path,daemon_version:o.daemon_version,pid:o.pid,holding:{workers:o.holding.workers.length,projects:[...o.holding.projects]},surviving:[...o.surviving],workers:o.holding.workers.map(s=>({worker_id:s.worker_id,project_label:s.project_label,pid:s.pid,unit:s.unit,isolated:s.isolated,survives:s.survives})),detail:o.detail})}
|
|
150
|
+
`),o.running&&!o.stopped?1:0}async function Gh(e,n={}){let t=n.write??(s=>process.stdout.write(s)),r=n.paths??ie(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(jl(n.unitIO??{}),null,2)}
|
|
151
|
+
`),0;if(o==="install"){let s=await El(xl(r),n.unitIO??{});return t(`${JSON.stringify(s,null,2)}
|
|
152
|
+
`),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await Pl(n.unitIO??{}),null,2)}
|
|
153
|
+
`),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function zh(e,n={}){let t=n.write??(a=>process.stdout.write(a)),r=n.warn??(a=>process.stderr.write(a)),o=ja(e),s=ny(n.cwd??process.cwd()),i=Da({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let a of[...i.warnings,...o.warnings])r(`redskilled statusline: ignoring ${a.key}=${a.value} \u2014 ${a.reason}
|
|
154
|
+
`);let l;try{l=await ia(n.paths??ie(),i.options,{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(a){r(`redskilled statusline: ${a instanceof Error?a.message:String(a)}
|
|
155
|
+
`),l=Ni({options:i.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${l.lines.join(`
|
|
156
156
|
`)}
|
|
157
|
-
`),0}var
|
|
158
|
-
`),p.verdict==="ok"?0:1}var
|
|
159
|
-
`),o.entries.some(s=>s.verdict==="failed")?1:0}function
|
|
160
|
-
`),process.exitCode=1});export{
|
|
157
|
+
`),0}var Qh={"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 Yh(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=ye(e,Qh),o=n.paths??ie(),s=n.homeDir??Xr(),i=await Qr({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),l=r.check||!i.needed?void 0:await ya(s),a;if(!r.check&&!r["no-start"])try{await Kr(o,n.client??{})}catch(f){a=f instanceof Error?f.message:String(f)}let c=await ba({paths:o,homeNeed:i,...n.homeDir==null?{}:{homeDir:n.homeDir},...n.configHome==null?{}:{configHome:n.configHome},...n.client?.serverCommand==null?{}:{entryOverride:{serverCommand:n.client.serverCommand,serverArgs:n.client.serverArgs}}}),u=r["install-unit"]&&Y(c.entry)?await va({configHome:n.configHome??ey(),unit:_a({command:[c.entry.command,...c.entry.args].join(" "),socketPath:o.socketPath})}):void 0,p=Ra(c);return t(`${I({verdict:p.verdict,home:{path:l?.path??c.homePath,created:l?.created??!1,tightened:l?.tightened??!1,needed:i.needed,needed_by:i.declaredBy},socket:c.socketPath,...a==null?{}:{start_error:a},...u==null?{}:{unit:{path:u.path,status:u.status}},checks:p.rows.map(f=>({check:f.check,verdict:f.verdict,evidence:f.evidence})),fixes:p.findings.map(f=>({check:f.check,fix:f.fix}))})}
|
|
158
|
+
`),p.verdict==="ok"?0:1}var Zh={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function Xh(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=ye(e,Zh),o=await Ea({...n.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return t(`${I({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(s=>({dir:s.dir,verdict:s.verdict,reason:s.reason,removed:[...s.removed]}))})}
|
|
159
|
+
`),o.entries.some(s=>s.verdict==="failed")?1:0}function ey(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:Oa(Xr(),".config")}function ny(e){let n=Zt(e);return n.configText==null?{label:null}:{configText:n.configText,label:Os(e)}}function ty(e){let n=ie();return{...n,socketPath:e.socket??n.socketPath,leasePath:e.lease??n.leasePath,eventLanePath:e.events??n.eventLanePath,sessionKeyHash:e["session-key-hash"]??n.sessionKeyHash,machineIdHash:e["machine-id-hash"]??n.machineIdHash,machineClaimPath:e["machine-claim"]??n.machineClaimPath}}var ry=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;ry&&Kh(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
|
|
160
|
+
`),process.exitCode=1});export{$a as REDSKILLED_HOST_TOKEN_ENV,Mh as REDSKILLED_USAGE,Bh as resolveRedskilledHostToken,Vh as resolveServeQueueDiscovery,Yh as runProvision,Xh as runReclaim,Kh as runRedskilledCli,zh as runStatusline,qh as runStop,Gh as runUnit};
|