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