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