@reddb-io/red-skills 3.3.12 → 3.3.13
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 +334 -334
- package/dist/code-nav.bundle.min.mjs +1 -1
- package/dist/dev.bundle.min.mjs +551 -551
- package/dist/memory.bundle.min.mjs +1 -1
- package/dist/redskilled.bundle.min.mjs +71 -70
- package/dist/rsp.bundle.min.mjs +1 -1
- package/package.json +1 -1
|
@@ -1,81 +1,82 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
3
|
-
var
|
|
3
|
+
var Cu=Object.defineProperty;var Mu=(e,n)=>()=>(e&&(n=e(e=0)),n);var Wu=(e,n)=>{for(var t in n)Cu(e,t,{get:n[t],enumerable:!0})};var Ul={};Wu(Ul,{REDSKILLED_BIN_ENV:()=>ko,REDSKILLED_BUNDLE_ASSET:()=>ae,REDSKILLED_ENTRY_UNRESOLVED:()=>$n,RedskilledDaemonEntryError:()=>In,isRedskilledEntryPath:()=>bo,isResolvedRedskilledEntry:()=>de,redskilledBundleCacheRoot:()=>Dt,redskilledServeArgv:()=>Te,requireRedskilledEntry:()=>Ot,resolveRedskilledEntry:()=>_e});import{existsSync as Cm,readdirSync as Mm}from"node:fs";import{homedir as Wm}from"node:os";import{basename as go,dirname as yo,join as Q,resolve as jt}from"node:path";function de(e){return"command"in e}function Te(e,n={}){let t=["serve","--socket",e.socketPath,"--lease",e.leasePath,"--events",e.eventLanePath,"--session-key-hash",e.sessionKeyHash,"--machine-id-hash",e.machineIdHash,"--machine-claim",e.machineClaimPath];return n.idleMs!=null&&t.push("--idle-ms",String(n.idleMs)),n.daemonVersion!=null&&t.push("--daemon-version",n.daemonVersion),t}function Dt(e=process.env){return Fl(e)}function _e(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??Cm,o=n.execPath??process.execPath,s=n.execArgv??[],i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,a=(p,u)=>({command:o,args:[...s,p],source:u,entry:p}),l=t[ko];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(i&&bo(i))return a(jt(i),"caller-entry");let d=[];for(let[p,u]of Hm(i,n.rootDir,t,n.listDir??Vm))if(d.push(p),r(p))return a(p,u);return{diagnostic:$n,searched:d,...i?{callerEntry:jt(i)}:{}}}function Ot(e={},n={}){let t=_e(e,n);if(de(t))return t;throw new In(t)}function bo(e){let n=go(e);return n===ae||Ro.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:Um(jt(e))}function Um(e){let n=yo(e);for(let t=0;t<4;t++){if(go(n)==="redskilled")return!0;let r=yo(n);if(r===n)return!1;n=r}return!1}function*Hm(e,n,t,r){if(e){let s=yo(jt(e));yield[Q(s,ae),"caller-sibling-bundle"];let i=Bm.exec(go(e));i&&(yield[Q(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[Q(s,"..","dist",ae),"caller-sibling-bundle"]}for(let s of Fm){let i=t[s];i&&(yield[Q(i,"dist",ae),"plugin-root-bundle"],yield[Q(i,"..","..","dist",ae),"plugin-root-bundle"])}n&&(yield[Q(n,"dist",ae),"repo-bundle"],yield[Q(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[Q(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=Fl(t);yield[Q(o,ae),"bundle-cache"];for(let s of Gm(o,r))yield[Q(o,s),"bundle-cache"]}function Fl(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Q(e.HOME||Wm(),".cache");return Q(n,"red-skills","bundles")}function Gm(e,n){return n(e).filter(t=>Ro.test(t)).sort((t,r)=>Km(Bl(r),Bl(t)))}function Bl(e){return Ro.exec(e)?.[1]??""}function Km(e,n){let t=s=>s.split(".").map(i=>Number.parseInt(i,10)),[r,o]=[t(e),t(n)];for(let s=0;s<Math.max(r.length,o.length);s++){let[i,a]=[r[s],o[s]];if(Number.isNaN(i)||i===void 0)return Number.isNaN(a)||a===void 0?e.localeCompare(n):-1;if(Number.isNaN(a)||a===void 0)return 1;if(i!==a)return i-a}return 0}function Vm(e){try{return Mm(e)}catch{return[]}}var ae,$n,ko,In,Bm,Ro,Fm,fe=Mu(()=>{"use strict";ae="redskilled.bundle.min.mjs",$n="redskilled-daemon-entry-unresolved",ko="REDSKILLED_BIN";In=class extends Error{code=$n;searched;callerEntry;constructor(n){super(`${$n}: no published ${ae} found to spawn the redskilled daemon from${n.callerEntry?` (caller entry: ${n.callerEntry}, which is NOT used as a fallback)`:""}
|
|
4
4
|
searched:
|
|
5
5
|
${n.searched.map(t=>` ${t}`).join(`
|
|
6
|
-
`)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};
|
|
7
|
-
`);return n.length>0&&n[n.length-1]===""&&n.pop(),n.map(t=>t.endsWith("\r")?t.slice(0,-1):t)}function
|
|
8
|
-
`;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let
|
|
9
|
-
`),e.push(" order: ",
|
|
10
|
-
`),e.push(" discriminator: ",
|
|
6
|
+
`)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};Bm=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Ro=/^redskilled-(.+)\.bundle\.min\.mjs$/,Fm=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as ub}from"node:child_process";import{homedir as Ts}from"node:os";import{join as ou}from"node:path";var qe=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},Pe=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonlError",this.line=n,this.reason=t}};function R(e,n){return new qe(e,n)}function S(e,n){return new Pe(e,n)}function Je(e){return e instanceof Pe?e:e instanceof qe?new Pe(e.line,e.reason):new Pe(0,String(e&&e.message?e.message:e))}var fi=["type","kind","event"],je="|",mi=new Set(["order","discriminator","rows","common"]);var O=",";function ft(e){let n=e.split(`
|
|
7
|
+
`);return n.length>0&&n[n.length-1]===""&&n.pop(),n.map(t=>t.endsWith("\r")?t.slice(0,-1):t)}function oe(e){return R(e,"invalid quoted string")}function V(e,n){if(e==="")return"";if(e.startsWith('"'))return gi(e,n);if(e.includes('"'))throw oe(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:Bu(e)?Number(e):e}function Y(e,n){let t=e.trim();if(t.startsWith('"'))return[gi(t,n),!0];if(t.includes('"')||/\s/.test(t))throw R(n,"expected non-empty field name");return[t,!1]}var hi=/["\\\u0000-\u0008\u000a-\u001f]/g;function gi(e,n){if(e.charCodeAt(0)!==34)throw oe(n);let t="",r=1;for(;r<e.length;){hi.lastIndex=r;let o=hi.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(r,o.index);throw oe(n)}if(o[0]!=="\\")throw oe(n);t+=e.slice(r,o.index);let s=e[o.index+1];switch(r=o.index+2,s){case'"':t+='"';break;case"\\":t+="\\";break;case"n":t+=`
|
|
8
|
+
`;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let i=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(i))throw oe(n);let a=Number.parseInt(i,16);if(a>=55296&&a<=57343)throw oe(n);t+=String.fromCharCode(a),r+=4;break}default:throw oe(n)}}throw oe(n)}function ki(e,n,t){for(;;){let r=e.indexOf('"',n),o=e.indexOf("\\",n);if(o!==-1&&(r===-1||o<r)){if(o===e.length-1)throw oe(t);n=o+2;continue}if(r===-1)throw oe(t);return r+1}}function X(e,n,t){if(e==="")return[];let r=[],o=0,s=0;for(;s<e.length;){let i=e.indexOf('"',s),a=e.indexOf(n,s);if(a!==-1&&(i===-1||a<i))r.push(e.slice(o,a).trim()),o=a+1,s=a+1;else if(i!==-1)s=ki(e,i+1,t);else break}return r.push(e.slice(o).trim()),r}function W(e,n,t){let r=0;for(;r<e.length;){let o=e.indexOf('"',r),s=e.indexOf(n,r);if(s!==-1&&(o===-1||s<o))return s;if(o===-1)return-1;r=ki(e,o+1,t)}return-1}function Bu(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Fu(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Uu(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw R(0,"number is not representable in TOON");return String(e)}function se(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function B(e,n){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Uu(e);if(typeof e=="string")return Gu(e,n);throw R(0,"not a primitive")}function Hu(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function N(e){return Hu(e)?e:mt(e)}function Gu(e,n){return vr(e,n)?mt(e):e}function vr(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Fu(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}var yi=/["\\\u0000-\u001f]/g;function mt(e){let n='"',t=0;yi.lastIndex=0;let r;for(;(r=yi.exec(e))!==null;){let o=e.charCodeAt(r.index),s;o===34?s='\\"':o===92?s="\\\\":o===10?s="\\n":o===13?s="\\r":o===9?s="\\t":s=`\\u${o.toString(16).padStart(4,"0")}`,n+=e.slice(t,r.index)+s,t=r.index+1}return`${n}${e.slice(t)}"`}function Z(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ri(e={}){let n=e.maxDepth??1e3,t=n===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(n));return{indent:Math.max(1,e.indent??2),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0,cyclicDiscriminatedArrays:e.cyclicDiscriminatedArrays!==!1,maxDepth:t}}function bi(e,n){let t=[],r=!1;return ft(e).forEach((o,s)=>{let i=s+1;if(o.trim()===""){r=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw R(i,"invalid indentation");if(n.strict&&a%n.indent!==0)throw R(i,"invalid indentation");let l=Math.floor(a/n.indent);ie(l,i,n),t.push({number:i,depth:l,content:o.slice(a),blankBefore:r}),r=!1}),t}function ie(e,n,t){if(t.maxDepth!==0&&e>t.maxDepth)throw R(n,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function Pn(e,n,t){if(t.maxDepth===0)return;let r=0,o=!1,s=!1;for(let i of e){if(s){s=!1;continue}if(o&&i==="\\"){s=!0;continue}if(i==='"'){o=!o;continue}o||(i==="{"?(r+=1,ie(r,n,t)):i==="}"&&(r=Math.max(0,r-1)))}}function xi(e){if(!L(e)||Object.keys(e).length===0)return e;let n={};for(let[t,r]of Object.entries(e)){let o=Ku(r,1);if(o===void 0)return e;Z(n,t,o)}return n}function Ku(e,n){if(!L(e)||!Vu(e))return;let{order:t,discriminator:r,rows:o}=e;if(typeof t!="string"||typeof r!="string"||!Number.isSafeInteger(o)||o<0)throw C(n);let s=qu(t,o,n),i=e.common,a=i===void 0?Array.from({length:o},()=>({})):i;if(!Array.isArray(a)||a.length!==o||!a.every(L))throw Si(n);let l=new Map;for(let[u,f]of Object.entries(e))if(!mi.has(u)){if(!Array.isArray(f)||!f.every(L))throw C(n);l.set(u,f)}if(l.size===0)throw C(n);let d=new Map,p=s.map((u,f)=>{let m=l.get(u);if(m===void 0)throw Er(n);let h=d.get(u)??0,b=m[h];if(b===void 0)throw Er(n);return d.set(u,h+1),Ju(r,u,a[f],b,n)});for(let[u,f]of l)if((d.get(u)??0)!==f.length)throw Er(n);return p}function Vu(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function qu(e,n,t){if(!e.startsWith("cycle("))throw C(t);let r=e.slice(6),o=r.indexOf(")*");if(o===-1)throw C(t);let s=r.slice(0,o),i=r.slice(o+2);if(s===""||i.includes("+tail("))throw C(t);let a=s.split(",").map(p=>Xu(p,t));if(a.some(p=>p===""))throw C(t);let l=Yu(i,t),d=a.length*l;if(!Number.isSafeInteger(d))throw C(t);if(d!==n)throw Si(t);return Array.from({length:d},(p,u)=>a[u%a.length])}function Ju(e,n,t,r,o){let s={};Z(s,e,n);for(let[i,a]of Object.entries(t??{})){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw C(o);Z(s,i,a)}for(let[i,a]of Object.entries(Qu(r,o))){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw C(o);Z(s,i,a)}return s}function Qu(e,n){let t={};for(let[r,o]of Object.entries(e))zu(t,r.split("."),o,n);return ht(t,n)}function zu(e,n,t,r){if(n.some(s=>s===""))throw C(r);let o=e;for(let s=0;s<n.length;s+=1){let i=n[s];if(s===n.length-1){o[i]=t;return}if(o[i]??={},o=o[i],!L(o))throw C(r)}}function ht(e,n){return Array.isArray(e)?e.map(t=>ht(t,n)):L(e)?Number.isSafeInteger(e.length)&&e.length>=0?Array.from({length:e.length},(t,r)=>{if(!Object.prototype.hasOwnProperty.call(e,String(r)))throw C(n);return ht(e[String(r)],n)}):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,ht(r,n)])):e}function Yu(e,n){if(e===""||e.length>1&&e.startsWith("0")||!/^[0-9]+$/.test(e))throw C(n);let t=Number(e);if(!Number.isSafeInteger(t))throw C(n);return t}function Xu(e,n){try{return decodeURIComponent(e)}catch{throw C(n)}}function _i(e){return encodeURIComponent(e)}function C(e){return R(e,"invalid cyclic array wire")}function Si(e){return R(e,"cyclic array length mismatch")}function Er(e){return R(e,"cyclic array group length mismatch")}function vi(e){if(!L(e))return;let n=Object.entries(e);if(n.length===0)return;let t=[];for(let[o,s]of n){let i=Zu(s);if(i===void 0)return;t.push([o,i])}let r=[];for(let[o,s]of t)rp(r,o,s);return r.join("")}function Zu(e){if(!Array.isArray(e)||e.length===0||!e.every(L))return;let n=ep(e);if(n===void 0)return;let t=e.map(a=>a[n]),r=np(t);if(r===void 0)return;let o=tp(e,n),s=new Map;for(let a of e){let l=a[n];s.has(l)||s.set(l,[]);let d={};for(let[p,u]of Object.entries(a))if(p!==n&&!o.includes(p)&&!Pr(u,p,d))return;s.get(l).push(d)}let i=[];for(let a of r.cycle){let l=s.get(a),d=sp(l);if(d===void 0||d.length===0)return;i.push({fields:d,label:a,rows:l})}return{common:o,commonRows:e.map(a=>Object.fromEntries(o.map(l=>[l,a[l]]))),discriminator:n,groups:i,order:r,rows:e}}function ep(e){return fi.find(n=>e.every(t=>typeof t[n]=="string"))}function np(e){if(!(e.length<12))for(let n=2;n<=Math.min(8,Math.floor(e.length/3));n+=1){if(e.length%n!==0)continue;let t=e.slice(0,n);if(new Set(t).size<2||!e.every((i,a)=>i===t[a%n]))continue;let r=e.length/n;if(r<3)continue;let o=e.map(_i).join(","),s=`cycle(${t.map(_i).join(",")})*${r}`;if(s.length<=o.length*.4)return{cycle:t,encoded:s,repeats:r}}}function tp(e,n){let t=[],r=Object.keys(e[0]),o=r.indexOf(n)+1;for(let s of r.slice(o).filter(i=>i!==n)){if(!op(s)||!e.every(i=>Object.prototype.hasOwnProperty.call(i,s))||!e.every(i=>se(i[s])))break;t.push(s)}return t}function rp(e,n,t){e.push(N(n),`:
|
|
9
|
+
`),e.push(" order: ",B(t.order.encoded,je),`
|
|
10
|
+
`),e.push(" discriminator: ",B(t.discriminator,je),`
|
|
11
11
|
`),e.push(" rows: ",String(t.rows.length),`
|
|
12
|
-
`),t.common.length>0&&
|
|
13
|
-
`);for(let o of r)e.push(" ",t.map(
|
|
14
|
-
`)}function Mu(e){return e!==""&&mr(e)}function fr(e,n,t,r=new Set){if(!mr(n))return!1;if(oe(e))return t[n]=e,!0;if(Array.isArray(e)){if(r.has(e))return!1;r.add(e),t[`${n}.length`]=e.length;let o=e.every((i,s)=>fr(i,`${n}.${s}`,t,r));return r.delete(e),o}if(A(e)){if(r.has(e))return!1;r.add(e);let o=Object.entries(e).every(([i,s])=>!i.includes(".")&&fr(s,`${n}.${i}`,t,r));return r.delete(e),o}return!1}function Wu(e){let n=Object.keys(e[0]??{});if(e.every(t=>Fu(Object.keys(t),n)))return n.every(mr)?n:void 0}function Fu(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function mr(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function Ge(e,n){let t=e[n]??e[e.length-1];return b(t===void 0?1:t.number,"array length mismatch")}function st(e,n){if(n===-1)throw b(0,"array header missing colon");let t=e.slice(0,n),r=W(t,"[",0);if(r===-1)throw b(0,"invalid array header");let o,i;try{[o,i]=J(t.slice(0,r),0)}catch{throw b(0,"invalid array header")}let s=t.slice(r+1),a=s.indexOf("]");if(a===-1)throw b(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 b(0,"invalid array header");let p=Number.parseInt(d,10),u;switch(l.slice(d.length)){case"":u=",";break;case" ":u=" ";break;case"|":u="|";break;default:throw b(0,"invalid array header")}let f=s.slice(a+1),m,h;if(f==="")m=void 0,h=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{h=Hu(f.slice(1,-1),u),m=gr(h)}catch(R){throw b(0,R.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw b(0,"invalid array header");return{key:o,keyQuoted:i,len:p,delimiter:u,fields:m,fieldTree:h}}function as(e){let n=W(e,"{",0);if(n===-1||!e.endsWith("}"))throw b(0,"invalid keyed map header");let t,r;try{[t,r]=J(e.slice(0,n),0)}catch{throw b(0,"invalid keyed map header")}if(t===""&&!r)throw b(0,"expected non-empty field name");let o=e.slice(n+1,-1),i=D;(o.startsWith("|")||o.startsWith(" "))&&(i=o[0],o=o.slice(1));let s;try{s=Bu(o,i,i)}catch(a){throw b(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:i,fields:s}}function Bu(e,n,t){let r=[],o=0;function i(l,d){let p=0;for(;o<e.length&&!(d&&e[o]==="}");){if(e[o]===n||e[o]==="}")throw b(0,"invalid array header");let u=o;for(;o<e.length;){let h=e[o];if(h==='"'){s();continue}if(h===n||h==="{"||h==="}"||h==="[")break;o+=1}let[f,m]=J(e.slice(u,o),0);if(f===""&&!m)throw b(0,"invalid array header");if(p+=1,e[o]==="["){o+=1;let h=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw b(0,"invalid array header");let R=e.slice(h,o);if(!ds(R,t))throw b(0,"invalid array header");o+=1,r.push({path:[...l,f],listDelimiter:R})}else if(e[o]==="{"){o+=1;let h=r.length;if(i([...l,f],!0),e[o]!=="}"||r.length===h)throw b(0,"invalid array header");o+=1}else r.push({path:[...l,f],listDelimiter:void 0});if(e[o]===n){if(o+=1,o>=e.length||e[o]==="}")throw b(0,"invalid array header");continue}if(d?e[o]==="}":o===e.length)break;throw b(0,"invalid array header")}if(p===0)throw b(0,"invalid array header")}function s(){for(o+=1;o<e.length;){let l=e[o];if(o+=1,l==="\\")o+=1;else if(l==='"')return}}if(i([],!1),o!==e.length)throw b(0,"invalid array header");let a=new Set;for(let l=0;l<r.length;l+=1)for(let d=l+1;d<r.length;d+=1)if(cs(r[l].path,r[d].path)||wn(r[l].path,r[d].path)||wn(r[d].path,r[l].path))throw b(0,"duplicate key");for(let l of r){let p=l.path.join("\0");if(a.has(p))throw b(0,"duplicate key");a.add(p)}return r}function Hu(e,n){if(n!==D&&e.includes(D)&&(e.includes("[")||e.includes("{")))return hr(e,D,n);try{return hr(e,n,n)}catch(t){if(n!==D&&t.reason!=="duplicate key")return hr(e,D,n);throw t}}function hr(e,n,t){let r=0;function o(l){let d=[];for(;r<e.length&&!(l&&e[r]==="}");){if(e[r]===n||e[r]==="}")throw b(0,"invalid array header");let p=r;for(;r<e.length;){let h=e[r];if(h==='"'){i();continue}if(h===n||h==="{"||h==="}"||h==="[")break;r+=1}let[u,f]=J(e.slice(p,r),0);if(u===""&&!f)throw b(0,"invalid array header");let m={key:u};if(e[r]==="["){r+=1;let h=r;for(;r<e.length&&e[r]!=="]";)r+=1;if(r>=e.length)throw b(0,"invalid array header");let R=e.slice(h,r);r+=1;let k=Uu(R);if(k!==void 0){if(k.delimiter!==t)throw b(0,"invalid array header");m.fixedLength=k.len,m.fixedDelimiter=k.delimiter}else if(ds(R,t))m.listDelimiter=R;else throw b(0,"invalid array header")}else if(e[r]==="{"){if(r+=1,m.children=o(!0),e[r]!=="}"||m.children.length===0)throw b(0,"invalid array header");r+=1}if(d.push(m),e[r]===n){if(r+=1,r>=e.length||e[r]==="}")throw b(0,"invalid array header");continue}if(l?e[r]==="}":r===e.length)break;throw b(0,"invalid array header")}if(d.length===0)throw b(0,"invalid array header");return d}function i(){for(r+=1;r<e.length;){let l=e[r];if(r+=1,l==="\\")r+=1;else if(l==='"')return}}let s=o(!1);if(r!==e.length)throw b(0,"invalid array header");let a=gr(s);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(cs(a[l].path,a[d].path)||wn(a[l].path,a[d].path)||wn(a[d].path,a[l].path))throw b(0,"duplicate key");return s}function Uu(e){let n=/^[0-9]+/.exec(e)?.[0];if(n===void 0||n.length>1&&n.startsWith("0"))return;let t=e.slice(n.length),r;switch(t){case"":r=D;break;case" ":r=" ";break;case"|":r="|";break;default:return}return{len:Number.parseInt(n,10),delimiter:r}}function gr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?gr(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function lt(e,n,t){return e.listDelimiter===void 0?G(n,t):Q(n,e.listDelimiter,t).map(r=>G(r,t))}function ds(e,n){return e.length===1&&e!==n&&!/[ \t\r\n"[\]{}:]/.test(e)}function cs(e,n){return e.length===n.length&&wn(e,n)}function wn(e,n){return n.every((t,r)=>e[r]===t)}function at(e,n){return b(n,e.reason??String(e.message))}function Y(e,n){let t=ns(n),r=ts(e,t),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw b(o.number,"invalid indentation");let i=r.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){_n(o.content,o.number,t);let d;try{d=st(o.content,W(o.content,":",o.number))}catch(p){if(t.strict)throw at(p,o.number);d=void 0}if(d!==void 0)return Vu(d,r,t)}if(i&&W(o.content,":",o.number)===-1)return G(o.content.trim(),o.number);let s={index:0},a=kr(r,s,0,t),l=r[s.index];if(l!==void 0)throw b(l.number,"expected end of document");return t.cyclicDiscriminatedArrays?is(a):a}function kr(e,n,t,r){let o={};for(;n.index<e.length;){let i=e[n.index];if(i.depth<t)break;if(i.depth>t)throw b(i.number,"invalid indentation");let{key:s,quoted:a,value:l}=Gu(e,n,t,r);ys(o,s,a,l,r,i.number)}return o}function Gu(e,n,t,r){let o=e[n.index],i=o.content,s=W(i,":",o.number);if(s===-1)throw b(o.number,"expected `key: value`");let a=i.slice(0,s),l=i.slice(s+1),d=W(a,"[",o.number),p=W(a,"{",o.number);if(p!==-1&&(d===-1||p<d)){_n(a,o.number,r);let h;try{h=as(a)}catch(k){if(r.strict)throw at(k,o.number);n.index+=1;let _=yr(e,n,t,l,o.number,r);return{key:a.trim(),quoted:!1,value:_}}if(l.trim()!=="")throw b(o.number,"expected keyed map rows");let R=Ku(h,e,n,t+1,r);return{key:h.key,quoted:h.keyQuoted,value:R}}if(d!==-1){_n(a,o.number,r);let h;try{h=st(a,s)}catch(k){if(r.strict)throw at(k,o.number);n.index+=1;let _=yr(e,n,t,l,o.number,r);return{key:a.trim(),quoted:!1,value:_}}if(h.key===""&&!h.keyQuoted)throw b(o.number,"expected non-empty field name");let R=br(h,l,e,n,t,r);return{key:h.key,quoted:h.keyQuoted,value:R}}let[u,f]=J(a,o.number);if(u===""&&!f)throw b(o.number,"expected non-empty field name");n.index+=1;let m=yr(e,n,t,l,o.number,r);return{key:u,quoted:f,value:m}}function yr(e,n,t,r,o,i){let s=r.trim();if(s==="[]")return[];if(s!=="")return G(s,o);let a=e[n.index];return a!==void 0&&a.depth>t?kr(e,n,t+1,i):{}}function Ku(e,n,t,r,o){let i={};for(t.index+=1;t.index<n.length;){let s=n[t.index];if(s.depth<r)break;if(s.depth>r)throw b(s.number,"invalid indentation");if(s.blankBefore&&o.strict)throw b(s.number,"blank line inside keyed map");let a=W(s.content,":",s.number);if(a===-1)throw b(s.number,"expected `key: value`");let[l,d]=J(s.content.slice(0,a),s.number);if(l===""&&!d)throw b(s.number,"expected non-empty field name");let p=Q(s.content.slice(a+1).trim(),e.delimiter,s.number);if(p.length!==e.fields.length)throw b(s.number,"keyed map row length mismatch");let u={};e.fields.forEach((f,m)=>{Ve(u,f.path,lt(f,p[m],s.number),o,s.number)}),ys(i,l,d,u,o,s.number),t.index+=1}return i}function Vu(e,n,t){let r=n[0],o=W(r.content,":",r.number);if(o===-1)throw b(r.number,"expected `key: value`");let i=r.content.slice(o+1),s={index:0},a=br(e,i,n,s,0,t),l=n[s.index];if(l!==void 0)throw b(l.number,"expected end of document");return a}function br(e,n,t,r,o,i){let s=t[r.index].number,a=n.trim();if(r.index+=1,e.fields!==void 0){if(a!=="")throw b(s,"expected tabular rows");return qu(e,e.fields,t,r,o+1,i)}if(a!==""){let l=Q(a,e.delimiter,s).map(d=>G(d,s));if(l.length!==e.len)throw b(s,"array length mismatch");return l}return ep(e,t,r,o+1,i)}function qu(e,n,t,r,o,i){if(e.fieldTree!==void 0&&Xu(e.fieldTree))return Ju(e,t,r,o,i);let s=[];for(;s.length<e.len;){let l=t[r.index];if(l===void 0)throw Ge(t,r.index);if(l.depth<o)break;if(l.depth>o)throw b(l.number,"invalid indentation");if(l.blankBefore&&i.strict)throw b(l.number,"blank line inside array");if(!Ke(l.content,e.delimiter,l.number))break;let d=Q(l.content,e.delimiter,l.number);if(d.length!==n.length)throw b(l.number,"array row length mismatch");let p={};n.forEach((u,f)=>{Ve(p,u.path,lt(u,d[f],l.number),i,l.number)}),s.push(p),r.index+=1}if(s.length!==e.len)throw Ge(t,r.index);let a=t[r.index];if(a!==void 0&&a.depth>=o&&Ke(a.content,e.delimiter,a.number))throw b(a.number,"array length mismatch");return s}function Ju(e,n,t,r,o){return us(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function us(e,n,t,r,o,i,s,a){let l=[],d=fs(e,n,t,r,o.index,i,s);for(;l.length<e;){let u=r[o.index];if(u===void 0)throw Ge(r,o.index);if(u.depth<i)break;if(u.depth>i)throw b(u.number,"invalid indentation");if(u.blankBefore&&s.strict)throw b(u.number,"blank line inside array");if(!Ke(u.content,t,u.number))break;let f=Q(u.content,t,u.number),m={cellIndex:0,nextIndex:o.index+1,flatWidth:dt(n),childTableFields:d},h=ps(n,f,u.number,r,m,i+1,t,s);if(m.cellIndex!==f.length)throw b(u.number,"array row length mismatch");l.push(Yu(n,h,a)),o.index=m.nextIndex}if(l.length!==e)throw Ge(r,o.index);let p=r[o.index];if(p!==void 0&&p.depth>=i&&Ke(p.content,t,p.number))throw b(p.number,"array length mismatch");return l}function ps(e,n,t,r,o,i,s,a){let l={};return e.forEach((d,p)=>{let u=e.slice(p+1),f=Qu(d,u,n,t,r,o,i,s,a);Ve(l,[d.key],f,a,t)}),l}function Qu(e,n,t,r,o,i,s,a,l){if(e.fixedLength!==void 0){if(i.cellIndex+e.fixedLength>t.length)throw b(r,"array row length mismatch");let p=t.slice(i.cellIndex,i.cellIndex+e.fixedLength).map(u=>G(u,r));return i.cellIndex+=e.fixedLength,p}if(e.children!==void 0){let p=dt(e.children),u=t[i.cellIndex],f=hs(u),m=t.length-i.cellIndex-1,h=o[i.nextIndex],R=h!==void 0&&h.depth===s,k=i.childTableFields===void 0?void 0:i.childTableFields.has(e);if(k===void 0?f!==void 0&&(R||t.length!==i.flatWidth&&m<p+Zu(n)):k){if(f===void 0)throw b(r,"array row length mismatch");return i.cellIndex+=1,us(f,e.children,a,o,{get index(){return i.nextIndex},set index(j){i.nextIndex=j}},s,l,!1)}return ps(e.children,t,r,o,i,s,a,l)}let d=t[i.cellIndex];if(d===void 0)throw b(r,"array row length mismatch");return i.cellIndex+=1,lt(e,d,r)}function fs(e,n,t,r,o,i,s){let a=n.filter(p=>p.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let l,d=1<<a.length;for(let p=0;p<d;p+=1){let u=new Set;a.forEach((m,h)=>{p&1<<h&&u.add(m)});let f=ms(e,n,u,t,r,o,i,s);f!==void 0&&(l===void 0||f.consumedChildRows>l.consumedChildRows||f.consumedChildRows===l.consumedChildRows&&u.size<l.childTableFields.size)&&(l={childTableFields:u,consumedChildRows:f.consumedChildRows})}return l?.childTableFields}function ms(e,n,t,r,o,i,s,a){let l=i,d=0;try{for(let u=0;u<e;u+=1){let f=o[l];if(f===void 0||f.depth!==s||f.blankBefore&&a.strict||!Ke(f.content,r,f.number))return;let m=Q(f.content,r,f.number),h=zu(n,t,m,r,o,l+1,s+1,a);if(h===void 0||o[h.nextIndex]?.depth>s)return;d+=h.consumedChildRows,l=h.nextIndex}let p=o[l];if(p!==void 0&&p.depth>=s&&Ke(p.content,r,p.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function zu(e,n,t,r,o,i,s,a){let l=0,d=i,p=0;for(let u of e){if(u.fixedLength!==void 0)l+=u.fixedLength;else if(u.children!==void 0)if(n.has(u)){let f=hs(t[l]);if(f===void 0)return;l+=1;let m=fs(f,u.children,r,o,d,s,a);if(m===void 0)return;let h=ms(f,u.children,m,r,o,d,s,a);if(h===void 0)return;d=h.nextIndex,p+=f+h.consumedChildRows}else l+=dt(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:p}}function Yu(e,n,t){return t&&e.length===1&&e[0].fixedLength!==void 0?n[e[0].key]:n}function hs(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function Xu(e){return e.some(n=>n.fixedLength!==void 0||n.children!==void 0)}function dt(e){return e.reduce((n,t)=>n+gs(t),0)}function gs(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?dt(e.children):1}function Zu(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+gs(t),0)}function Ke(e,n,t){let r=W(e,":",t);if(r===-1)return!0;let o=W(e,n,t);return o===-1?!1:o<r}function ep(e,n,t,r,o){let i=[];for(;i.length<e.len;){let a=n[t.index];if(a===void 0||a.depth<r)throw Ge(n,t.index);if(a.depth>r)throw b(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw b(a.number,"blank line inside array");i.push(np(n,t,r,o))}let s=n[t.index];if(s!==void 0&&s.depth>=r)throw b(s.number,"array length mismatch");return i}function np(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw b(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return n.index+=1,{};if(i.startsWith("[")){let s=W(i,":",o.number);_n(i,o.number,r);let a;try{a=st(i,s)}catch{a=void 0}if(a!==void 0){let l=i.slice(s+1);return br(a,l,e,n,t,r)}}if(W(i,":",o.number)!==-1){let s=[{number:o.number,depth:t+1,content:i,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let a=e[n.index];if(a.depth<=t)break;s.push(a),n.index+=1}return kr(s,{index:0},t+1,r)}return n.index+=1,G(i,o.number)}function ys(e,n,t,r,o,i){if(o.expandPaths&&!t&&n.includes(".")){let s=n.split(".");if(s.every(tp)){Ve(e,s,r,o,i);return}}Ve(e,[n],r,o,i)}function Ve(e,n,t,r,o){ie(n.length-1,o,r);let i=n[0],s=Object.prototype.hasOwnProperty.call(e,i);if(n.length===1){if(s&&r.strict)throw b(o,"duplicate key");z(e,i,t);return}if(s&&!A(e[i])){if(r.strict)throw b(o,"path expansion conflict");z(e,i,{})}else s||z(e,i,{});Ve(e[i],n.slice(1),t,r,o)}function tp(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function M(e,n={}){let t=n.maxDepth??1e3,r=n.delimiter??D;if(![D,"|"," "].includes(r))throw b(0,"invalid array header");let o={nestedTabularHeaders:n.nestedTabularHeaders===!0,keyedMapCollapse:n.keyedMapCollapse===!0,primitiveArrayColumns:n.primitiveArrayColumns===!0,objectArrayColumns:n.objectArrayColumns===!0,cyclicDiscriminatedArrays:n.cyclicDiscriminatedArrays===!0,delimiter:r,maxDepth:t===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(t))};if(o.cyclicDiscriminatedArrays){let s=ls(e);if(s!==void 0)return s}let i=[];return Array.isArray(e)?xr(i,void 0,e,0,!1,o):A(e)?ks(i,e,0,o):i.push(F(e,r)),i.join("")}function qe(e,n){e.push(" ".repeat(n*2))}function ks(e,n,t,r){ie(t,0,r);for(let[o,i]of Object.entries(n))qe(e,t),_r(e,o,i,t,r)}function _r(e,n,t,r,o){if(ie(r,0,o),Array.isArray(t)){xr(e,n,t,r,!1,o);return}if(A(t)){let i=o.keyedMapCollapse?op(t,o,r+1):void 0;if(i!==void 0){e.push(N(n),"{",Sr(o.delimiter),i.fields.map(s=>Pr(s,o.delimiter)).join(o.delimiter),`}:
|
|
15
|
-
`);for(let[
|
|
12
|
+
`),t.common.length>0&&wi(e,"common",t.common,t.commonRows);for(let r of t.groups)wi(e,r.label,r.fields,r.rows)}function wi(e,n,t,r){e.push(" ",N(n),"[",String(r.length),je,"]{",t.map(N).join(je),`}:
|
|
13
|
+
`);for(let o of r)e.push(" ",t.map(s=>B(o[s],je)).join(je),`
|
|
14
|
+
`)}function op(e){return e!==""&&jr(e)}function Pr(e,n,t,r=new Set){if(!jr(n))return!1;if(se(e))return t[n]=e,!0;if(Array.isArray(e)){if(r.has(e))return!1;r.add(e),t[`${n}.length`]=e.length;let o=e.every((s,i)=>Pr(s,`${n}.${i}`,t,r));return r.delete(e),o}if(L(e)){if(r.has(e))return!1;r.add(e);let o=Object.entries(e).every(([s,i])=>!s.includes(".")&&Pr(i,`${n}.${s}`,t,r));return r.delete(e),o}return!1}function sp(e){let n=Object.keys(e[0]??{});if(e.every(t=>ip(Object.keys(t),n)))return n.every(jr)?n:void 0}function ip(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function jr(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function Qe(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function yt(e,n){if(n===-1)throw R(0,"array header missing colon");let t=e.slice(0,n),r=W(t,"[",0);if(r===-1)throw R(0,"invalid array header");let o,s;try{[o,s]=Y(t.slice(0,r),0)}catch{throw R(0,"invalid array header")}let i=t.slice(r+1),a=i.indexOf("]");if(a===-1)throw R(0,"invalid array header");let l=i.slice(0,a),d=/^[0-9]*/.exec(l)[0];if(d===""||d.length>1&&d.startsWith("0"))throw R(0,"invalid array header");let p=Number.parseInt(d,10),u;switch(l.slice(d.length)){case"":u=",";break;case" ":u=" ";break;case"|":u="|";break;default:throw R(0,"invalid array header")}let f=i.slice(a+1),m,h;if(f==="")m=void 0,h=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{h=ap(f.slice(1,-1),u),m=Or(h)}catch(b){throw R(0,b.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw R(0,"invalid array header");return{key:o,keyQuoted:s,len:p,delimiter:u,fields:m,fieldTree:h}}function Ei(e){let n=W(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=Y(e.slice(0,n),0)}catch{throw R(0,"invalid keyed map header")}if(t===""&&!r)throw R(0,"expected non-empty field name");let o=e.slice(n+1,-1),s=O;(o.startsWith("|")||o.startsWith(" "))&&(s=o[0],o=o.slice(1));let i;try{i=lp(o,s,s)}catch(a){throw R(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:s,fields:i}}function lp(e,n,t){let r=[],o=0;function s(l,d){let p=0;for(;o<e.length&&!(d&&e[o]==="}");){if(e[o]===n||e[o]==="}")throw R(0,"invalid array header");let u=o;for(;o<e.length;){let h=e[o];if(h==='"'){i();continue}if(h===n||h==="{"||h==="}"||h==="[")break;o+=1}let[f,m]=Y(e.slice(u,o),0);if(f===""&&!m)throw R(0,"invalid array header");if(p+=1,e[o]==="["){o+=1;let h=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw R(0,"invalid array header");let b=e.slice(h,o);if(!Pi(b,t))throw R(0,"invalid array header");o+=1,r.push({path:[...l,f],listDelimiter:b})}else if(e[o]==="{"){o+=1;let h=r.length;if(s([...l,f],!0),e[o]!=="}"||r.length===h)throw R(0,"invalid array header");o+=1}else r.push({path:[...l,f],listDelimiter:void 0});if(e[o]===n){if(o+=1,o>=e.length||e[o]==="}")throw R(0,"invalid array header");continue}if(d?e[o]==="}":o===e.length)break;throw R(0,"invalid array header")}if(p===0)throw R(0,"invalid array header")}function i(){for(o+=1;o<e.length;){let l=e[o];if(o+=1,l==="\\")o+=1;else if(l==='"')return}}if(s([],!1),o!==e.length)throw R(0,"invalid array header");let a=new Set;for(let l=0;l<r.length;l+=1)for(let d=l+1;d<r.length;d+=1)if(ji(r[l].path,r[d].path)||jn(r[l].path,r[d].path)||jn(r[d].path,r[l].path))throw R(0,"duplicate key");for(let l of r){let p=l.path.join("\0");if(a.has(p))throw R(0,"duplicate key");a.add(p)}return r}function ap(e,n){if(n!==O&&e.includes(O)&&(e.includes("[")||e.includes("{")))return Dr(e,O,n);try{return Dr(e,n,n)}catch(t){if(n!==O&&t.reason!=="duplicate key")return Dr(e,O,n);throw t}}function Dr(e,n,t){let r=0;function o(l){let d=[];for(;r<e.length&&!(l&&e[r]==="}");){if(e[r]===n||e[r]==="}")throw R(0,"invalid array header");let p=r;for(;r<e.length;){let h=e[r];if(h==='"'){s();continue}if(h===n||h==="{"||h==="}"||h==="[")break;r+=1}let[u,f]=Y(e.slice(p,r),0);if(u===""&&!f)throw R(0,"invalid array header");let m={key:u};if(e[r]==="["){r+=1;let h=r;for(;r<e.length&&e[r]!=="]";)r+=1;if(r>=e.length)throw R(0,"invalid array header");let b=e.slice(h,r);r+=1;let k=dp(b);if(k!==void 0){if(k.delimiter!==t)throw R(0,"invalid array header");m.fixedLength=k.len,m.fixedDelimiter=k.delimiter}else if(Pi(b,t))m.listDelimiter=b;else throw R(0,"invalid array header")}else if(e[r]==="{"){if(r+=1,m.children=o(!0),e[r]!=="}"||m.children.length===0)throw R(0,"invalid array header");r+=1}if(d.push(m),e[r]===n){if(r+=1,r>=e.length||e[r]==="}")throw R(0,"invalid array header");continue}if(l?e[r]==="}":r===e.length)break;throw R(0,"invalid array header")}if(d.length===0)throw R(0,"invalid array header");return d}function s(){for(r+=1;r<e.length;){let l=e[r];if(r+=1,l==="\\")r+=1;else if(l==='"')return}}let i=o(!1);if(r!==e.length)throw R(0,"invalid array header");let a=Or(i);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(ji(a[l].path,a[d].path)||jn(a[l].path,a[d].path)||jn(a[d].path,a[l].path))throw R(0,"duplicate key");return i}function dp(e){let n=/^[0-9]+/.exec(e)?.[0];if(n===void 0||n.length>1&&n.startsWith("0"))return;let t=e.slice(n.length),r;switch(t){case"":r=O;break;case" ":r=" ";break;case"|":r="|";break;default:return}return{len:Number.parseInt(n,10),delimiter:r}}function Or(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?Or(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function gt(e,n,t){return e.listDelimiter===void 0?V(n,t):X(n,e.listDelimiter,t).map(r=>V(r,t))}function Pi(e,n){return e.length===1&&e!==n&&!/[ \t\r\n"[\]{}:]/.test(e)}function ji(e,n){return e.length===n.length&&jn(e,n)}function jn(e,n){return n.every((t,r)=>e[r]===t)}function kt(e,n){return R(n,e.reason??String(e.message))}function q(e,n){let t=Ri(n),r=bi(e,t),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw R(o.number,"invalid indentation");let s=r.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){Pn(o.content,o.number,t);let d;try{d=yt(o.content,W(o.content,":",o.number))}catch(p){if(t.strict)throw kt(p,o.number);d=void 0}if(d!==void 0)return pp(d,r,t)}if(s&&W(o.content,":",o.number)===-1)return V(o.content.trim(),o.number);let i={index:0},a=Lr(r,i,0,t),l=r[i.index];if(l!==void 0)throw R(l.number,"expected end of document");return t.cyclicDiscriminatedArrays?xi(a):a}function Lr(e,n,t,r){let o={};for(;n.index<e.length;){let s=e[n.index];if(s.depth<t)break;if(s.depth>t)throw R(s.number,"invalid indentation");let{key:i,quoted:a,value:l}=cp(e,n,t,r);Ii(o,i,a,l,r,s.number)}return o}function cp(e,n,t,r){let o=e[n.index],s=o.content,i=W(s,":",o.number);if(i===-1)throw R(o.number,"expected `key: value`");let a=s.slice(0,i),l=s.slice(i+1),d=W(a,"[",o.number),p=W(a,"{",o.number);if(p!==-1&&(d===-1||p<d)){Pn(a,o.number,r);let h;try{h=Ei(a)}catch(k){if(r.strict)throw kt(k,o.number);n.index+=1;let _=Ar(e,n,t,l,o.number,r);return{key:a.trim(),quoted:!1,value:_}}if(l.trim()!=="")throw R(o.number,"expected keyed map rows");let b=up(h,e,n,t+1,r);return{key:h.key,quoted:h.keyQuoted,value:b}}if(d!==-1){Pn(a,o.number,r);let h;try{h=yt(a,i)}catch(k){if(r.strict)throw kt(k,o.number);n.index+=1;let _=Ar(e,n,t,l,o.number,r);return{key:a.trim(),quoted:!1,value:_}}if(h.key===""&&!h.keyQuoted)throw R(o.number,"expected non-empty field name");let b=Tr(h,l,e,n,t,r);return{key:h.key,quoted:h.keyQuoted,value:b}}let[u,f]=Y(a,o.number);if(u===""&&!f)throw R(o.number,"expected non-empty field name");n.index+=1;let m=Ar(e,n,t,l,o.number,r);return{key:u,quoted:f,value:m}}function Ar(e,n,t,r,o,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return V(i,o);let a=e[n.index];return a!==void 0&&a.depth>t?Lr(e,n,t+1,s):{}}function up(e,n,t,r,o){let s={};for(t.index+=1;t.index<n.length;){let i=n[t.index];if(i.depth<r)break;if(i.depth>r)throw R(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw R(i.number,"blank line inside keyed map");let a=W(i.content,":",i.number);if(a===-1)throw R(i.number,"expected `key: value`");let[l,d]=Y(i.content.slice(0,a),i.number);if(l===""&&!d)throw R(i.number,"expected non-empty field name");let p=X(i.content.slice(a+1).trim(),e.delimiter,i.number);if(p.length!==e.fields.length)throw R(i.number,"keyed map row length mismatch");let u={};e.fields.forEach((f,m)=>{Ye(u,f.path,gt(f,p[m],i.number),o,i.number)}),Ii(s,l,d,u,o,i.number),t.index+=1}return s}function pp(e,n,t){let r=n[0],o=W(r.content,":",r.number);if(o===-1)throw R(r.number,"expected `key: value`");let s=r.content.slice(o+1),i={index:0},a=Tr(e,s,n,i,0,t),l=n[i.index];if(l!==void 0)throw R(l.number,"expected end of document");return a}function Tr(e,n,t,r,o,s){let i=t[r.index].number,a=n.trim();if(r.index+=1,e.fields!==void 0){if(a!=="")throw R(i,"expected tabular rows");return fp(e,e.fields,t,r,o+1,s)}if(a!==""){let l=X(a,e.delimiter,i).map(d=>V(d,i));if(l.length!==e.len)throw R(i,"array length mismatch");return l}return bp(e,t,r,o+1,s)}function fp(e,n,t,r,o,s){if(e.fieldTree!==void 0&&kp(e.fieldTree))return mp(e,t,r,o,s);let i=[];for(;i.length<e.len;){let l=t[r.index];if(l===void 0)throw Qe(t,r.index);if(l.depth<o)break;if(l.depth>o)throw R(l.number,"invalid indentation");if(l.blankBefore&&s.strict)throw R(l.number,"blank line inside array");if(!ze(l.content,e.delimiter,l.number))break;let d=X(l.content,e.delimiter,l.number);if(d.length!==n.length)throw R(l.number,"array row length mismatch");let p={};n.forEach((u,f)=>{Ye(p,u.path,gt(u,d[f],l.number),s,l.number)}),i.push(p),r.index+=1}if(i.length!==e.len)throw Qe(t,r.index);let a=t[r.index];if(a!==void 0&&a.depth>=o&&ze(a.content,e.delimiter,a.number))throw R(a.number,"array length mismatch");return i}function mp(e,n,t,r,o){return Di(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function Di(e,n,t,r,o,s,i,a){let l=[],d=Ai(e,n,t,r,o.index,s,i);for(;l.length<e;){let u=r[o.index];if(u===void 0)throw Qe(r,o.index);if(u.depth<s)break;if(u.depth>s)throw R(u.number,"invalid indentation");if(u.blankBefore&&i.strict)throw R(u.number,"blank line inside array");if(!ze(u.content,t,u.number))break;let f=X(u.content,t,u.number),m={cellIndex:0,nextIndex:o.index+1,flatWidth:Rt(n),childTableFields:d},h=Oi(n,f,u.number,r,m,s+1,t,i);if(m.cellIndex!==f.length)throw R(u.number,"array row length mismatch");l.push(gp(n,h,a)),o.index=m.nextIndex}if(l.length!==e)throw Qe(r,o.index);let p=r[o.index];if(p!==void 0&&p.depth>=s&&ze(p.content,t,p.number))throw R(p.number,"array length mismatch");return l}function Oi(e,n,t,r,o,s,i,a){let l={};return e.forEach((d,p)=>{let u=e.slice(p+1),f=hp(d,u,n,t,r,o,s,i,a);Ye(l,[d.key],f,a,t)}),l}function hp(e,n,t,r,o,s,i,a,l){if(e.fixedLength!==void 0){if(s.cellIndex+e.fixedLength>t.length)throw R(r,"array row length mismatch");let p=t.slice(s.cellIndex,s.cellIndex+e.fixedLength).map(u=>V(u,r));return s.cellIndex+=e.fixedLength,p}if(e.children!==void 0){let p=Rt(e.children),u=t[s.cellIndex],f=Ti(u),m=t.length-s.cellIndex-1,h=o[s.nextIndex],b=h!==void 0&&h.depth===i,k=s.childTableFields===void 0?void 0:s.childTableFields.has(e);if(k===void 0?f!==void 0&&(b||t.length!==s.flatWidth&&m<p+Rp(n)):k){if(f===void 0)throw R(r,"array row length mismatch");return s.cellIndex+=1,Di(f,e.children,a,o,{get index(){return s.nextIndex},set index(j){s.nextIndex=j}},i,l,!1)}return Oi(e.children,t,r,o,s,i,a,l)}let d=t[s.cellIndex];if(d===void 0)throw R(r,"array row length mismatch");return s.cellIndex+=1,gt(e,d,r)}function Ai(e,n,t,r,o,s,i){let a=n.filter(p=>p.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let l,d=1<<a.length;for(let p=0;p<d;p+=1){let u=new Set;a.forEach((m,h)=>{p&1<<h&&u.add(m)});let f=Li(e,n,u,t,r,o,s,i);f!==void 0&&(l===void 0||f.consumedChildRows>l.consumedChildRows||f.consumedChildRows===l.consumedChildRows&&u.size<l.childTableFields.size)&&(l={childTableFields:u,consumedChildRows:f.consumedChildRows})}return l?.childTableFields}function Li(e,n,t,r,o,s,i,a){let l=s,d=0;try{for(let u=0;u<e;u+=1){let f=o[l];if(f===void 0||f.depth!==i||f.blankBefore&&a.strict||!ze(f.content,r,f.number))return;let m=X(f.content,r,f.number),h=yp(n,t,m,r,o,l+1,i+1,a);if(h===void 0||o[h.nextIndex]?.depth>i)return;d+=h.consumedChildRows,l=h.nextIndex}let p=o[l];if(p!==void 0&&p.depth>=i&&ze(p.content,r,p.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function yp(e,n,t,r,o,s,i,a){let l=0,d=s,p=0;for(let u of e){if(u.fixedLength!==void 0)l+=u.fixedLength;else if(u.children!==void 0)if(n.has(u)){let f=Ti(t[l]);if(f===void 0)return;l+=1;let m=Ai(f,u.children,r,o,d,i,a);if(m===void 0)return;let h=Li(f,u.children,m,r,o,d,i,a);if(h===void 0)return;d=h.nextIndex,p+=f+h.consumedChildRows}else l+=Rt(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:p}}function gp(e,n,t){return t&&e.length===1&&e[0].fixedLength!==void 0?n[e[0].key]:n}function Ti(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function kp(e){return e.some(n=>n.fixedLength!==void 0||n.children!==void 0)}function Rt(e){return e.reduce((n,t)=>n+$i(t),0)}function $i(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?Rt(e.children):1}function Rp(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+$i(t),0)}function ze(e,n,t){let r=W(e,":",t);if(r===-1)return!0;let o=W(e,n,t);return o===-1?!1:o<r}function bp(e,n,t,r,o){let s=[];for(;s.length<e.len;){let a=n[t.index];if(a===void 0||a.depth<r)throw Qe(n,t.index);if(a.depth>r)throw R(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw R(a.number,"blank line inside array");s.push(_p(n,t,r,o))}let i=n[t.index];if(i!==void 0&&i.depth>=r)throw R(i.number,"array length mismatch");return s}function _p(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw R(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return n.index+=1,{};if(s.startsWith("[")){let i=W(s,":",o.number);Pn(s,o.number,r);let a;try{a=yt(s,i)}catch{a=void 0}if(a!==void 0){let l=s.slice(i+1);return Tr(a,l,e,n,t,r)}}if(W(s,":",o.number)!==-1){let i=[{number:o.number,depth:t+1,content:s,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let a=e[n.index];if(a.depth<=t)break;i.push(a),n.index+=1}return Lr(i,{index:0},t+1,r)}return n.index+=1,V(s,o.number)}function Ii(e,n,t,r,o,s){if(o.expandPaths&&!t&&n.includes(".")){let i=n.split(".");if(i.every(wp)){Ye(e,i,r,o,s);return}}Ye(e,[n],r,o,s)}function Ye(e,n,t,r,o){ie(n.length-1,o,r);let s=n[0],i=Object.prototype.hasOwnProperty.call(e,s);if(n.length===1){if(i&&r.strict)throw R(o,"duplicate key");Z(e,s,t);return}if(i&&!L(e[s])){if(r.strict)throw R(o,"path expansion conflict");Z(e,s,{})}else i||Z(e,s,{});Ye(e[s],n.slice(1),t,r,o)}function wp(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function M(e,n={}){let t=n.maxDepth??1e3,r=n.delimiter??O;if(![O,"|"," "].includes(r))throw R(0,"invalid array header");let o={nestedTabularHeaders:n.nestedTabularHeaders===!0,keyedMapCollapse:n.keyedMapCollapse===!0,primitiveArrayColumns:n.primitiveArrayColumns===!0,objectArrayColumns:n.objectArrayColumns===!0,cyclicDiscriminatedArrays:n.cyclicDiscriminatedArrays===!0,delimiter:r,maxDepth:t===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(t))};if(o.cyclicDiscriminatedArrays){let i=vi(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?Cr(s,void 0,e,0,!1,o):L(e)?Ni(s,e,0,o):s.push(B(e,r)),s.join("")}function Xe(e,n){e.push(" ".repeat(n*2))}function Ni(e,n,t,r){ie(t,0,r);for(let[o,s]of Object.entries(n))Xe(e,t),Ir(e,o,s,t,r)}function Ir(e,n,t,r,o){if(ie(r,0,o),Array.isArray(t)){Cr(e,n,t,r,!1,o);return}if(L(t)){let s=o.keyedMapCollapse?Sp(t,o,r+1):void 0;if(s!==void 0){e.push(N(n),"{",Mr(o.delimiter),s.fields.map(i=>Fr(i,o.delimiter)).join(o.delimiter),`}:
|
|
15
|
+
`);for(let[i,a]of Object.entries(t)){Xe(e,r+1);let l=[];e.push(N(i),": ",s.paths.map(d=>Ur(Br(a,d.path),d,o.delimiter,o,l,r+2)).join(o.delimiter),`
|
|
16
16
|
`),e.push(...l)}return}e.push(N(n),`:
|
|
17
|
-
`),
|
|
18
|
-
`)}function
|
|
17
|
+
`),Ni(e,t,r+1,o);return}e.push(N(n),": ",B(t,o.delimiter),`
|
|
18
|
+
`)}function Cr(e,n,t,r,o,s){if(ie(r,0,s),t.length===0){n!==void 0?e.push(N(n),`: []
|
|
19
19
|
`):o?e.push(`[0]:
|
|
20
20
|
`):e.push(`[]
|
|
21
|
-
`);return}if(t.every(
|
|
22
|
-
`);return}let
|
|
23
|
-
`);for(let a of t){
|
|
24
|
-
`),e.push(...l)}return}
|
|
25
|
-
`);for(let a of t)
|
|
26
|
-
`);return}e.push("- "),
|
|
27
|
-
`)}function
|
|
28
|
-
`),e.push(...
|
|
29
|
-
`}function
|
|
30
|
-
`}function
|
|
31
|
-
`,h=()=>
|
|
32
|
-
`;return j+=
|
|
33
|
-
`},end(){return u?"":(u=!0,m())}}}function
|
|
21
|
+
`);return}if(t.every(se)){$r(e,n,t.length,void 0,s.delimiter),e.push(" "),e.push(t.map(a=>B(a,s.delimiter)).join(s.delimiter)),e.push(`
|
|
22
|
+
`);return}let i=o?void 0:Ci(t,s,r+1);if(i!==void 0){$r(e,n,t.length,i.fields,s.delimiter),e.push(`
|
|
23
|
+
`);for(let a of t){Xe(e,r+1);let l=[];e.push(i.paths.map(d=>Ur(Br(a,d.path),d,s.delimiter,s,l,r+2)).join(s.delimiter)),e.push(`
|
|
24
|
+
`),e.push(...l)}return}$r(e,n,t.length,void 0,s.delimiter),e.push(`
|
|
25
|
+
`);for(let a of t)Xe(e,r+1),xp(e,a,r+1,s)}function xp(e,n,t,r){if(ie(t,0,r),Array.isArray(n)){e.push("- "),Cr(e,void 0,n,t,!0,r);return}if(L(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
|
|
26
|
+
`);return}e.push("- "),Ir(e,o[0][0],o[0][1],t+1,r);for(let[s,i]of o.slice(1))Xe(e,t+1),Ir(e,s,i,t+1,r);return}e.push("- ",B(n,r.delimiter),`
|
|
27
|
+
`)}function $r(e,n,t,r,o){n!==void 0&&e.push(N(n)),e.push("[",String(t),Mr(o),"]"),r!==void 0&&e.push("{",r.map(s=>Fr(s,o)).join(o),"}"),e.push(":")}function Mr(e){return e===O?"":e}function Ci(e,n,t){let r=vp(e,n);if(r!==void 0)return r;let o=Nr(e.map(s=>({value:s})),n,t);return o===void 0?void 0:{fields:o,paths:Wr(o)}}function Sp(e,n,t){let r=Object.values(e);if(!(r.length<2))return Ci(r,n,t)}function Nr(e,n,t){ie(t,0,n);let r=e[0]?.value;if(!L(r))return;let o=Object.keys(r).map(s=>({key:s}));if(o.length!==0){for(let{value:s}of e)if(!L(s)||Object.keys(s).length!==o.length||o.some(a=>!Object.prototype.hasOwnProperty.call(s,a.key)))return;for(let s of o){let i=e.map(({value:l})=>({value:l[s.key]}));if(i.every(({value:l})=>se(l)))continue;if(n.primitiveArrayColumns&&i.every(({value:l})=>Array.isArray(l)&&l.every(se))){s.listDelimiter=";";continue}if(n.objectArrayColumns&&i.every(({value:l})=>Array.isArray(l))){let l=Mi(i.map(({value:p})=>p));if(l!==void 0){s.fixedLength=l.fixedLength,s.fixedDelimiter=n.delimiter;continue}let d=Nr(i.flatMap(({value:p})=>p.map(u=>({value:u}))),n,t+1);if(d!==void 0){s.children=d,s.childTable=!0;continue}}if(!n.nestedTabularHeaders)return;let a=Nr(i,n,t+1);if(a===void 0)return;s.children=a}return o}}function vp(e,n){if(!n.objectArrayColumns)return;let t=Mi(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:n.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function Mi(e){let n=e[0]?.length;if(!(!Number.isInteger(n)||n===0)&&e.every(t=>Array.isArray(t)&&t.length===n&&t.every(se)))return{fixedLength:n}}function Wr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.childTable===!0?[{path:r,childFields:t.children}]:t.fixedLength!==void 0?[{path:r,fixedLength:t.fixedLength}]:t.children===void 0?[{path:r,listDelimiter:t.listDelimiter}]:Wr(t.children,r)})}function Br(e,n){let t=e;for(let r of n)t=t[r];return t}function Fr(e,n){return e.listDelimiter!==void 0?`${N(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${N(e.key)}[${e.fixedLength}${Mr(n)}]`:e.children===void 0?N(e.key):`${N(e.key)}{${e.children.map(t=>Fr(t,n)).join(n)}}`}function Ur(e,n,t,r,o,s){return n.childFields!==void 0?(Ep(o,e,n.childFields,r,s),String(e.length)):n.fixedLength!==void 0?e.map(i=>B(i,t)).join(t):n.listDelimiter===void 0?B(e,t):e.map(i=>Pp(i,t,n.listDelimiter)).join(n.listDelimiter)}function Ep(e,n,t,r,o){for(let s of n){Xe(e,o);let i=[];e.push(Wr(t).map(a=>Ur(Br(s,a.path),a,r.delimiter,r,i,o+1)).join(r.delimiter)),e.push(`
|
|
28
|
+
`),e.push(...i)}}function Pp(e,n,t){return typeof e!="string"?B(e,n):vr(e,n)||e.includes(t)?mt(e):e}var Vi=[O,"|"," "];var qi=8,Ji=/^[A-Za-z0-9_-]+$/,j_=new TextEncoder,D_=new TextDecoder;function Ap(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw S(n,"invalid trailer count");return Number.parseInt(t,10)}function Qi(e,n){if(!Ji.test(e))throw S(n,"invalid tag")}function Lp(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!Ji.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw S(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function Tp(e,n){if(!e.startsWith("["))return null;let t=e.slice(1),r=t.indexOf("]");if(r===-1)throw S(n,"invalid header");let o=t.slice(0,r),s=o.startsWith("~"),i=s?o.slice(1):o;if(!s&&i.startsWith("="))return null;if(!Vi.includes(i)&&i!=="")throw S(n,"invalid header delimiter");let a=i===""?O:i,l=t.slice(r+1),d=null;if(!s&&l.startsWith("<")){let f=l.indexOf(">");if(f===-1)throw S(n,"invalid tag");if(d=l.slice(1,f),Qi(d,n),i!=="")throw S(n,"invalid header delimiter");l=l.slice(f+1)}if(!l.startsWith("{")||!l.endsWith("}:"))throw S(n,"invalid header");let p=l.slice(1,-2),u;try{u=X(p,a,n).map(f=>Y(f,n)[0])}catch(f){throw Je(f)}if(u.length===0||u.some(f=>f===""))throw S(n,"invalid header fields");return{delimiter:a,fields:u,fieldText:p,continuation:s,tag:d}}function $p(e,n,t){if(e===null||e.delimiter===void 0)throw S(t,"continuation header before header");if(e.delimiter!==n.delimiter||e.fieldText!==n.fieldText)throw S(t,"continuation header mismatch")}function Wi(e,n,t,r){let o;try{o=X(e,n,r)}catch(s){throw Je(s)}if(o.length!==t)throw S(r,"row arity mismatch");for(let s of o)try{V(s,r)}catch(i){throw Je(i)}return o}function Ip(e,n,t){let r={};return e.forEach((o,s)=>{try{Z(r,o,V(n[s],t))}catch(i){throw Je(i)}}),r}function Np(e,n,t){if(e.startsWith("- "))throw S(n,"reserved line prefix");let r=Ap(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw S(n,"trailer without header");if(t.rowCount!==r)throw S(n,"trailer count mismatch");return{kind:"trailer"}}let o=Tp(e,n);if(o!==null)return o.continuation?($p(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=Lp(e,n);if(s!==null){let i=t?.taggedLanes?.get(s.tag);if(i===void 0)throw S(n,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:Wi(s.cellsText,i.delimiter,i.fields.length,n)}}if(t===null||t.delimiter===void 0)throw S(n,"row before header");return{kind:"row",cells:Wi(e,t.delimiter,t.fields.length,n)}}function Cp(e,n={}){let t=[],r=new Map,o=[],s=[],i=null,a=!1,l=!1;function d(m,h){let b=s.at(-1);if(b!==void 0&&b.lane===m.lane&&b.delimiter===m.delimiter&&b.fieldText===m.fieldText){b.rows.push(h);return}s.push({lane:m.lane,delimiter:m.delimiter,fields:m.fields,fieldText:m.fieldText,rows:[h]})}function p(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function u(m,h,b){let k=r.get(m);if(k===void 0){if(r.size>=qi)throw S(b,"too many tagged lanes");k={segments:[],current:null},r.set(m,k),t.push(m)}else k.current!==null&&k.segments.push(k.current);k.current={lane:m,delimiter:h.delimiter,fields:h.fields,fieldText:h.fieldText,rows:[]},k.delimiter=h.delimiter,k.fields=h.fields,k.fieldText=h.fieldText}if(ft(e).forEach((m,h)=>{let b=h+1;if(m==="")return;let k=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},_=Np(m,b,k);if(_.kind==="trailer"){p(),i=null;return}if(_.kind!=="continuation"){if(_.kind==="tag-header"){l=!0,u(_.header.tag,_.header,b);return}if(_.kind==="header"){p(),a||(t.push(null),a=!0),i={lane:null,delimiter:_.header.delimiter,fields:_.header.fields,fieldText:_.header.fieldText,rows:[]};return}if(_.kind==="tagged-row"){l=!0;let j=r.get(_.tag).current;j.rows.push(_.cells),d(j,_.cells);return}if(i===null)throw S(b,"row before header");i.rows.push(_.cells),d(i,_.cells)}}),!l)return p(),n.preserveInterleaving===!0,o;let f=[];p();for(let m of t){if(m===null){f.push(...o);continue}let h=r.get(m);f.push(...h.segments),h.current!==null&&f.push(h.current)}return n.preserveInterleaving===!0?s:f}function Re(e){return Cp(e).flatMap(n=>n.rows.map(t=>Ip(n.fields,t,0)))}function Mp(e){if(!Vi.includes(e))throw S(0,"invalid header delimiter")}function Bi(e,n,t=!1){return`[${`${t?"~":""}${e===O?"":e}`}]{${n}}:
|
|
29
|
+
`}function Fi(e,n){return`[]<${e}>{${n}}:
|
|
30
|
+
`}function Hr(e,n){return n.map(N).join(e)}function Wp(e){if(!Array.isArray(e)||e.length===0)throw S(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=Y(String(n),0)}catch(r){throw Je(r)}if(t==="")throw S(0,"TOONL header requires fields");return t})}function Ui(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function Hi(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw S(0,"TOONL continuation cadence must be positive")}function Bp(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function Gi(e){if(e===null||typeof e!="object"||Array.isArray(e))throw S(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw S(0,"TOONL output requires object rows");if(n.some(t=>!se(e[t])))throw S(0,"TOONL rows must be flat objects");return n}function Fp(e){return JSON.stringify([...e].sort())}function Ki(e,n){let t=Fp(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function pe({delimiter:e=O,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){Mp(e),Hi(t),Hi(r);let o=null,s="",i=new Map,a=0,l=0,d=0,p=new Map,u=!1,f={continuationEveryRows:t,continuationEveryBytes:r},m=()=>o===null||!n?"":`[=${a}]
|
|
31
|
+
`,h=()=>Bp(f,l,d)?(l=0,d=0,Bi(e,s,!0)):"",b=k=>{Qi(k,0);let _=p.get(k);if(_===void 0){if(p.size>=qi)throw S(0,"too many tagged lanes");_={fields:null,fieldsByShape:new Map},p.set(k,_)}return _};return{push(k){if(u)throw S(0,"TOONL encoder is closed");let _=Ki(Gi(k),i),j="";(o===null||o.length!==_.length||o.some((ve,Fe)=>ve!==_[Fe]))&&(j+=m(),o=_,s=Hr(e,o),a=0,l=0,d=0,j+=Bi(e,s));let te=o.map(ve=>B(k[ve],e));j+=h();let z=`${te.join(e)}
|
|
32
|
+
`;return j+=z,a+=1,l+=1,d+=z.length,j},declareLane(k,_){if(u)throw S(0,"TOONL encoder is closed");let j=Wp(_),te=Hr(O,j),z=b(k);return Ui(z.fields,j)?"":(z.fields=j,Fi(k,te))},pushTagged(k,_){if(u)throw S(0,"TOONL encoder is closed");let j=b(k),te=Ki(Gi(_),j.fieldsByShape),z=Hr(O,te),ve=te.map(Yn=>B(_[Yn],O)),Fe="";return Ui(j.fields,te)||(j.fields=te,Fe+=Fi(k,z)),`${Fe}${k}:${ve.join(O)}
|
|
33
|
+
`},end(){return u?"":(u=!0,m())}}}function Gr(e){let n={app:e,version:Up(Ze("__RED_BUILD_VERSION__",()=>"3.3.13")??"0.0.0-dev"),gitSha:Ze("__RED_BUILD_GIT_SHA__",()=>"832f145c84843c71cf5379685dc5a58bdabcaf38")??"unknown",buildTime:Ze("__RED_BUILD_TIME__",()=>"2026-08-03T02:28:27-03:00")??"unknown",bundleAsset:Ze("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=Ze("__REDDB_SDK_VERSION__",()=>""),r=Ze("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function Up(e){return e.startsWith("v")?e.slice(1):e}function zi(e){return`${e.app} ${e.version} ${e.gitSha}`}function Ze(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var Yi={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Hp=/^[a-z][a-z0-9+.-]*:\/\//i;function Gp(e,n){return typeof n=="string"?{separator:e,to:n,typed:!1,prefix:!1}:{separator:e,to:n.to,typed:n.typed??!1,prefix:n.prefix??!1}}function Kp(e=Yi){return Object.entries(e).map(([n,t])=>Gp(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function Vp(e){return/^-\d+(\.\d+)?$/.test(e)}function Dn(e){return!(!e||e.startsWith("-")&&!Vp(e))}function bt(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e}function Xi(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e.includes(",")?e.split(",").map(t=>Xi(t.trim())):e}function De(e,n){switch(n){case"boolean":return qp(e);case"number":return Jp(e);case"array":return e.split(",").map(t=>bt(t.trim()));case"string":default:return e}}function qp(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function Jp(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let n=Number(e);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${e}" to number`);return n}function be(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Qp(e,n={}){return e.map(t=>{let r=n[t.type];return r?r(t.value):t.value}).join("")}function E(e,n){return{type:e,value:n}}function zp(e){let n=[],t=Xp(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
|
|
34
34
|
`),E("newline",`
|
|
35
35
|
`)),e.positional&&e.positional.length>0){n.push(E("section-header","Arguments:"),E("newline",`
|
|
36
36
|
`));for(let r of e.positional)if(r.description){let o=r.variadic?`${r.name}...`:r.name;n.push(E("indent"," "),E("positional-name",`<${o}>`)),r.required||n.push(E("positional-optional"," (optional)")),n.push(E("newline",`
|
|
37
37
|
`),E("indent"," "),E("option-description",r.description),E("newline",`
|
|
38
38
|
`))}n.push(E("newline",`
|
|
39
39
|
`))}if(e.options&&Object.keys(e.options).length>0){n.push(E("section-header","Options:"),E("newline",`
|
|
40
|
-
`));let r
|
|
41
|
-
`))}return t}function
|
|
42
|
-
`),o=r.find(
|
|
43
|
-
`)}catch{return!0}},append(e,n){
|
|
44
|
-
`),t.append(e,r),n}function
|
|
40
|
+
`));let r=Zp(e.options);n.push(...r)}return n}function Yp(e,n){let t=zp(e);return Qp(t,n)}function Xp(e){let n=["[options]"];if(e.positional)for(let t of e.positional)t.variadic?n.push(t.required?`<${t.name}...>`:`[${t.name}...]`):n.push(t.required?`<${t.name}>`:`[${t.name}]`);return n.join(" ")}function Zp(e,n=!1){let t=[],r=[],o=n?"global-option-flag":"option-flag",s=n?"global-option-type":"option-type",i=n?"global-option-default":"option-default",a=n?"global-option-description":"option-description";for(let[d,p]of Object.entries(e)){if(p.hidden)continue;let u=[],f=b=>{u.includes(b)||u.push(b)};p.short&&f(`-${p.short}`),f(`--${d}`);for(let b of p.aliases??[])b.length===1?f(`-${b}`):f(`--${b}`);let m=u.join(", "),h=p.type&&p.type!=="boolean"?`<${p.type}>`:void 0;r.push({flags:m,type:h,desc:p.description??"",default:p.default!==void 0?String(p.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 p=d.flags.length+(d.type?d.type.length+1:0),u=" ".repeat(l-p+2);t.push(E("indent"," ")),t.push(E(o,d.flags)),d.type&&(t.push(E("text"," ")),t.push(E(s,d.type))),t.push(E("text",u)),t.push(E(a,d.desc)),d.default!==void 0&&(t.push(E("text"," ")),t.push(E(i,`(default: ${d.default})`))),t.push(E("newline",`
|
|
41
|
+
`))}return t}function Zi(e){let n=lf(e.options??{},e.autoShort??!1),t=Kp(e.separators??Yi);return{schema:e,parse(r){return ef(r,e,n,t)},help(){return Yp(e,e.formatter)}}}function ef(e,n,t,r){let o={positional:{},options:{},errors:[],rest:[]},s=new Set(r.map(p=>p.to));for(let p of s)o[p]={};let i=0,a=n.positional??[],l=0,d=!1;for(;l<e.length;){let p=e[l];if(n.stopEarly&&i>0){o.rest=e.slice(l);break}if(p==="--"&&!d){d=!0,l++;continue}if(d){if(i<a.length){let f=a[i];if(f.variadic){let m=[];for(;l<e.length;){let h=e[l];m.push(f.type?De(h,f.type):h),l++}o.positional[f.name]=m,i++}else{let m=f.type?De(p,f.type):p;o.positional[f.name]=m,i++,l++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(p)),l++;continue}if(p.startsWith("--")){l=of(p,l,e,o,t,n);continue}if(p.startsWith("-")&&p.length>1&&!pf(p)){l=sf(p,l,e,o,t,n);continue}let u=nf(p,r);if(u){let{key:f,value:m,config:h}=u,b=o,k=b[h.to]??(b[h.to]={});k[f]=h.typed?Xi(m):be(m),l++;continue}if(i<a.length){let f=a[i];if(f.variadic){let h=[];for(;l<e.length&&!e[l].startsWith("-");){let b=e[l];h.push(f.type?De(b,f.type):b),l++}o.positional[f.name]=h,i++;continue}let m=f.type?De(p,f.type):p;o.positional[f.name]=m,i++}else n.allowUnknown!==!1?o.rest.push(p):o.errors.push(`Unexpected positional argument: ${p}`);l++}return df(o,n,t),cf(o,n,a),uf(o,n,t),o}function nf(e,n){if(Hp.test(e))return null;for(let t of n){if(t.prefix&&e.startsWith(t.separator)){let o=e.slice(t.separator.length),s=o.indexOf(":");if(s>0){let i=o.slice(0,s),a=o.slice(s+1);if(tf(i))return{key:i,value:a,config:t}}continue}let r=e.indexOf(t.separator);if(r>0){let o=e.slice(0,r),s=e.slice(r+t.separator.length);if(rf(o,s,t))return{key:o,value:s,config:t}}}return null}function tf(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function rf(e,n,t){return e?t.separator===":"?e.includes("/")||e.includes(".")||/^\d+$/.test(n)?!1:/^[A-Z][a-zA-Z0-9-]*$/.test(e):!((t.separator==="="||t.separator===":=")&&e.includes("/")):!1}function of(e,n,t,r,o,s){let i=e.slice(2);if(i.startsWith("no-")){let l=i.slice(3),d=o.get(l);if(d?.negatable!==!1&&d?.type==="boolean")return r.options[d.name]=!1,n+1}if(i.includes("=")){let l=i.indexOf("="),d=i.slice(0,l),p=i.slice(l+1);return _t(d,p,n+1,r,o,s)}let a=o.get(i);if(a){if(a.type!=="boolean"){let l=t[n+1];return Dn(l)?_t(a.name,l,n+2,r,o,s):(r.errors.push(`Option --${i} requires a value`),n+1)}return r.options[a.name]=!0,n+1}return s.strict?r.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(r.options[i]=!0),n+1}function sf(e,n,t,r,o,s){let i=e.slice(1);if(i.includes("=")){let a=i.indexOf("="),l=i.slice(0,a),d=i.slice(a+1),p=Kr(l,o);return p?_t(p.name,d,n+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${l}`):s.allowUnknown!==!1&&(r.options[l]=bt(be(d))),n+1)}if(i.length===1){let a=Kr(i,o);if(a){if(a.type!=="boolean"){let l=t[n+1];return Dn(l)?_t(a.name,l,n+2,r,o,s):(r.errors.push(`Option -${i} requires a value`),n+1)}return r.options[a.name]=!0,n+1}if(s.strict)r.errors.push(`Unknown option: -${i}`);else if(s.allowUnknown!==!1){let l=t[n+1];if(Dn(l))return r.options[i]=bt(be(l)),n+2;r.options[i]=!0}return n+1}for(let a of i){let l=Kr(a,o);l?l.type==="boolean"?r.options[l.name]=!0:r.errors.push(`Option -${a} requires a value`):s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=!0)}return n+1}function _t(e,n,t,r,o,s){let i=o.get(e);if(i){if(i.choices){let l=i.type?De(be(n),i.type):be(n);if(!i.choices.includes(l))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${i.choices.join(", ")}`),t}let a=i.type?De(be(n),i.type):be(n);if(i.type==="array"){let l=r.options[e];Array.isArray(l)?l.push(...a):r.options[e]=a}else r.options[e]=a}else s.strict?r.errors.push(`Unknown option: --${e}`):s.allowUnknown!==!1&&(r.options[e]=bt(be(n)));return t}function lf(e,n=!1){let t=new Map,r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i)),o=new Set;for(let[,s]of r)s.short&&o.add(s.short);for(let[s,i]of r){let a=i.short??"";n&&!a&&(a=af(s,o),a&&o.add(a));let l={name:s,short:a,aliases:i.aliases??[],type:i.type??"string",description:i.description??"",required:i.required??!1,hidden:i.hidden??!1,negatable:i.negatable??!0,default:i.default,choices:i.choices,env:i.env,validate:i.validate};t.set(s,l);for(let d of l.aliases)t.set(d,l)}return t}function af(e,n){for(let t of e){if(!/[a-zA-Z]/.test(t))continue;let r=t.toLowerCase();if(!n.has(r))return r;let o=t.toUpperCase();if(!n.has(o))return o}return""}function Kr(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function df(e,n,t){for(let r of t.values())if(e.options[r.name]===void 0)if(r.env&&process.env[r.env]!==void 0){let o=process.env[r.env];e.options[r.name]=r.type?De(o,r.type):o}else r.default!==void 0&&(e.options[r.name]=r.default);for(let r of n.positional??[])e.positional[r.name]===void 0&&r.default!==void 0&&(e.positional[r.name]=r.default)}function cf(e,n,t){if(n.options)for(let[r,o]of Object.entries(n.options))o.required&&e.options[r]===void 0&&e.errors.push(`Missing required option: --${r}`);for(let r of t)r.required&&e.positional[r.name]===void 0&&e.errors.push(`Missing required argument: <${r.name}>`)}function uf(e,n,t){for(let r of t.values()){let o=e.options[r.name];if(r.validate&&o!==void 0){let s=r.validate(o);s!==!0&&e.errors.push(s)}}for(let r of n.positional??[]){let o=e.positional[r.name];if(r.validate&&o!==void 0){let s=r.validate(o);s!==!0&&e.errors.push(s)}}}function pf(e){return/^-\d+(\.\d+)?$/.test(e)}var Vr=class extends Error{flag;known;constructor(n,t){super(`unknown flag '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownFlagError",this.flag=n,this.known=t}};function ff(e){let n={};for(let[t,r]of Object.entries(e))n[t]={type:r.kind==="boolean"?"boolean":"string",...t.length===1?{short:t}:{},...r.aliases===void 0?{}:{aliases:r.aliases}};return n}function mf(e,n){let t=new Map;for(let[o,s]of Object.entries(n))if(!(s.kind!=="value"||s.type!=="array")){t.set(o,o);for(let i of s.aliases??[])t.set(i,o)}let r=new Map;for(let o=0;o<e.length;o+=1){let s=e[o];if(s==="--")break;let i=s.match(/^--([^=]+)(?:=(.*))?$/)??s.match(/^-([^=])(?:=(.*))?$/);if(i===null)continue;let a=t.get(i[1]);if(a===void 0)continue;let l=i[2];if(l===void 0&&Dn(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 Oe(e,n,t={}){let o=Zi({options:ff(n),separators:{},allowUnknown:!0}).parse([...e]),s={},i=mf(e,n),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(t.unknownFlags==="error"){let l=new Set(Object.keys(n));for(let d of Object.keys(o.options))if(!l.has(d))throw new Vr(d.length===1?`-${d}`:`--${d}`,Object.keys(n).map(p=>p.length===1?`-${p}`:`--${p}`))}for(let[l,d]of Object.entries(n)){let p=o.options[l];p!==void 0&&(d.kind==="boolean"?s[l]=p:d.type==="array"?s[l]=(i.get(l)??[]).map(u=>d.coerce(u)):s[l]=d.coerce(String(p)))}return{values:s,positionals:o.rest}}var qr=class extends Error{token;known;constructor(n,t){super(`unknown command '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownCommandError",this.token=n,this.known=t}};function el(e,n){let[t,...r]=e;if(t!==void 0){for(let[s,i]of Object.entries(n.commands))if(t===s||(i.aliases??[]).includes(t))return{command:s,args:r};if(n.errorOnUnknownCommand&&!t.startsWith("-"))throw new qr(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as vf,mkdirSync as Ef,readFileSync as cl,statSync as Pf}from"node:fs";import{dirname as pl,join as jf}from"node:path";var nl="RED_WORKER_SCOPE",tl="RED_WORKER_MEMORY_CEILING",rl="RED_WORKER_SCOPE_DEGRADATION",Qr={scope:null,memory_ceiling:null,scope_degradation:null};function zr(e){return{scope:Jr(e[nl]),memory_ceiling:Jr(e[tl]),scope_degradation:Jr(e[rl])}}function On(e){let n={};return e.scope!=null&&e.scope!==""&&(n[nl]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[tl]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[rl]=e.scope_degradation),n}function Jr(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as gf,readdirSync as kf,readFileSync as ll,rmSync as Rf,writeFileSync as bf}from"node:fs";import{basename as _f,join as en}from"node:path";import{isAbsolute as aw,join as wt,resolve as dw}from"node:path";function hf(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var ol="deaths",sl="deaths.toonl";function xt(e){return wt(hf(e),ol)}function An(e){return wt(xt(e),sl)}var Ln="live",il="attributions.toonl";function St(e){return wt(xt(e),Ln)}function Yr(e){return wt(xt(e),il)}var Zr=en("sys","kernel","random","boot_id"),al=1;function eo(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:al,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:dl(en(t,Zr)),cgroup:wf(t,r),last_phase:e.last_phase}}function dl(e){try{let n=ll(e,"utf8").trim();return n===""?null:n}catch{return null}}function wf(e,n){let t=dl(en(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
|
|
42
|
+
`),o=r.find(i=>i.startsWith("0::"));if(o)return o.slice(3)||null;let s=r[0]?.split(":").slice(2).join(":");return s===void 0||s===""?null:s}function no(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function to(e,n){let t=en(e,no(n));try{return gf(e,{recursive:!0,mode:448}),bf(t,pe({trailer:!1}).push(Sf(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function Ae(e,n){try{Rf(en(e,no(n)),{force:!0})}catch{}}function ro(e,n){let t;try{t=kf(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=en(e,o);try{let a=Re(ll(s,"utf8"))[0];if(a===void 0)throw new Error("anchor holds no record");r.push(xf(a))}catch(i){n?.(_f(s),i instanceof Error?i.message:String(i))}}return r}function xf(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:Xr(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:Xr(e.pid),ppid:Xr(e.ppid),boot_id:e.boot_id==null?null:String(e.boot_id),cgroup:e.cgroup==null?null:String(e.cgroup),last_phase:String(e.last_phase)}}function Xr(e){return typeof e=="number"?e:Number(e)}function Sf(e){return{...e}}var Df=1,Of=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Af(e){return typeof e=="string"&&Of.has(e)}var Lf="startup";function Tf(e,n){return{...e.scope??Qr,version:Df,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,exit_path:e.exit_path,signal:e.signal??null,exit_code:e.exit_code??null,last_phase:e.last_phase,detail:e.detail??null,...n}}function $f(e){let n=e.resourceUsage();return{uptime_s:Math.round(e.uptime()),rss_kb:Math.round(e.memoryUsage().rss/1024),max_rss_kb:n.maxRSS,user_cpu_us:n.userCPUTime,system_cpu_us:n.systemCPUTime,minor_page_faults:n.minorPageFault,major_page_faults:n.majorPageFault,voluntary_ctx_switches:n.voluntaryContextSwitches,involuntary_ctx_switches:n.involuntaryContextSwitches}}var so={mkdir(e){Ef(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=Pf(e).size}catch{return!0}if(n===0)return!0;try{return cl(e,"utf8").endsWith(`
|
|
43
|
+
`)}catch{return!0}},append(e,n){vf(e,n,{encoding:"utf8",mode:384})},read(e){return cl(e,"utf8")}};function If(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function Nf(e,n,t=so){let r=pe({trailer:!1}).push(If(n));return t.mkdir(pl(e)),t.endsClean(e)||t.append(e,`
|
|
44
|
+
`),t.append(e,r),n}function fl(e){let n=e.endsWith(`
|
|
45
45
|
`)?e:e.slice(0,e.lastIndexOf(`
|
|
46
|
-
`)+1);return n===""?[]:
|
|
47
|
-
`).filter(u=>u.trim()!=="");a.push(...p),r.push({source:l,result:p.length===0?"empty":"read",detail:`${p.length} lines`})}catch(d){r.push({source:l,result:
|
|
46
|
+
`)+1);return n===""?[]:Re(n).map(Cf)}function Cf(e){let n=e.exit_path;if(!Af(n))throw new Error(`death record has unknown exit_path ${JSON.stringify(n)}`);let t=e.kind;if(t!=="launcher"&&t!=="worker"&&t!=="daemon")throw new Error(`death record has unknown kind ${JSON.stringify(t)}`);return{version:J(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:J(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:J(e.exit_code),last_phase:String(e.last_phase),detail:e.detail==null?null:String(e.detail),scope:e.scope==null?null:String(e.scope),memory_ceiling:e.memory_ceiling==null?null:String(e.memory_ceiling),scope_degradation:e.scope_degradation==null?null:String(e.scope_degradation),uptime_s:J(e.uptime_s),rss_kb:J(e.rss_kb),max_rss_kb:J(e.max_rss_kb),user_cpu_us:J(e.user_cpu_us),system_cpu_us:J(e.system_cpu_us),minor_page_faults:J(e.minor_page_faults),major_page_faults:J(e.major_page_faults),voluntary_ctx_switches:J(e.voluntary_ctx_switches),involuntary_ctx_switches:J(e.involuntary_ctx_switches)}}function J(e){return typeof e=="number"?e:Number(e)}function ml(e,n=so){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return fl(t)}var Mf=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],oo=null;function hl(e){let n=e.host??process,t=e.io??so,r=e.clock??(()=>new Date().toISOString()),o=n.pid,s=e.scope??zr(process.env),i=e.phase??Lf,a=null,l=e.presenceDir===void 0?jf(pl(e.lanePath),Ln):e.presenceDir,d=null,p=()=>{l!==null&&(d=eo({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),to(l,d))},u=k=>{if(!a){try{a=Nf(e.lanePath,Tf({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...k},$f(n)),t)}catch{}l!==null&&d!==null&&Ae(l,d)}},f={signal(k){u({exit_path:"signal",signal:k})},exit(k){u({exit_path:"exit",exit_code:k})},uncaughtException(k){u({exit_path:"uncaught-exception",detail:ul(k)})},unhandledRejection(k){u({exit_path:"unhandled-rejection",detail:ul(k)})}},h=[...(e.signals??Mf).map(k=>{let _=()=>{if(f.signal(k),!(n.listenerCount?.(k)!==1||!n.kill)){n.off(k,_);try{n.kill(o,k)}catch{}}};return[k,_]}),["uncaughtException",(...k)=>f.uncaughtException(k[0])],["unhandledRejection",(...k)=>f.unhandledRejection(k[0])],["exit",(...k)=>f.exit(typeof k[0]=="number"?k[0]:null)]];for(let[k,_]of h)n.on(k,_);let b={lanePath:e.lanePath,phase(k){i=k,a||p()},currentPhase:()=>i,written:()=>a,uninstall(){for(let[k,_]of h)n.off(k,_);l!==null&&d!==null&&Ae(l,d),oo===b&&(oo=null)},handlers:f};return e.setActive!==!1&&(oo=b),p(),b}function ul(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Wf,readdirSync as Bf,readFileSync as vt,statSync as Ff,writeFileSync as Uf}from"node:fs";import{join as Rl}from"node:path";var Hf=1,Gf=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],Kf=512*1024;function Vf(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??Gf,r=[],o=Rl(n,Zr),s=null;try{let l=vt(o,"utf8").trim();s=l===""?null:l,r.push({source:o,result:s?"read":"empty",detail:s})}catch(l){r.push({source:o,result:io(l),detail:null})}let i=new Set;try{for(let l of Bf(n))/^\d+$/.test(l)&&i.add(Number(l));r.push({source:n,result:"read",detail:`${i.size} live pids`})}catch(l){r.push({source:n,result:io(l),detail:null})}let a=[];for(let l of t)try{let p=qf(l,e.tailBytes??Kf).split(`
|
|
47
|
+
`).filter(u=>u.trim()!=="");a.push(...p),r.push({source:l,result:p.length===0?"empty":"read",detail:`${p.length} lines`})}catch(d){r.push({source:l,result:io(d),detail:null})}return{boot_id:s,live_pids:i,journal:a,probes:r}}function io(e){return e.code==="ENOENT"?"absent":"unreadable"}function qf(e,n){let t=Ff(e).size,r=vt(e,"utf8");return t<=n?r:r.slice(r.length-n)}var Jf=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,Qf=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,zf=/Killed (\/\S*) due to memory pressure/,Yf=/\bopid=(\d+)\b/,yl=/\bsig=(\d+)\b/,Xf=/\buid=(\d+)\b/,Zf=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,em={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function nm(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,s=[...n.probes.map(u=>`${u.source}: ${u.result}${u.detail?` (${u.detail})`:""}`),`boot id: anchored under ${e.boot_id??"unknown"}, host now ${n.boot_id??"unknown"} (${o?"changed":"same"})`,`parent account: ppid ${e.ppid}`,`cgroup: ${e.cgroup??"unknown"}`],i=(u,f,m,h)=>({version:Hf,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:u,confidence:f,signal:m,host_boot_changed:o,evidence:h,checked:s}),a=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],l=n.journal.find(u=>gl(u,e.pid,Jf)||gl(u,e.pid,Qf));if(l!==void 0)return i("oomd",o?"medium":"high","SIGKILL",[l,...a]);if(e.cgroup!==null)for(let u of n.journal){let f=zf.exec(u)?.[1];if(f!==void 0){if(f===e.cgroup)return i("oomd",o?"medium":"high","SIGKILL",[u,...a]);if(e.cgroup.startsWith(`${f}/`))return i("oomd","medium","SIGKILL",[u,`the killed scope ${f} is an ancestor of this process's ${e.cgroup}`,...a])}}let d=n.journal.find(u=>Number(Yf.exec(u)?.[1])===e.pid&&yl.test(u));if(d!==void 0){let u=Number(yl.exec(d)?.[1]),f=Xf.exec(d)?.[1];return i("user-signal",o?"medium":"high",em[u]??null,[d,...f===void 0?[]:[`sent by uid ${f}`],...a])}let p=t.find(u=>u.pid===e.ppid);if(p!==void 0&&!n.live_pids.has(e.ppid))return i("parent-death","medium",null,[`parent pid ${e.ppid} (${p.kind} ${p.id}) recorded its own death at ${p.ts} via ${p.exit_path}${p.signal?` ${p.signal}`:""}`]);if(o){let u=n.journal.find(f=>Zf.test(f));return u!==void 0?i("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,u]):i("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,"no shutdown record on any journal read: the host stopped without announcing it (a freeze or a power loss, not an orderly teardown)"])}return i("unknown","none",null,[])}function gl(e,n,t){return Number(t.exec(e)?.[1])===n}var tm=" | ";function kl(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(tm)}function rm(e){return{version:e.version,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.last_seen,last_phase:e.last_phase,sender_class:e.sender_class,confidence:e.confidence,signal:e.signal,host_boot_changed:e.host_boot_changed,evidence:kl(e.evidence),checked:kl(e.checked)}}function om(e){let n=pe({trailer:!1});return e.map(t=>n.push(rm(t))).join("")}function bl(e){let n=St(e.stateRoot),t=Yr(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??Vf({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=ro(n,u=>s.push(u)),a=ml(An(e.stateRoot)),l=[],d=[],p=[];for(let u of i){if(o.live_pids.has(u.pid)){d.push(u);continue}if(a.find(m=>m.pid===u.pid&&m.id===u.id)!==void 0){p.push(u),Ae(n,u);continue}l.push(nm(u,o,a,r())),Ae(n,u)}return l.length>0&&sm(t,l),{attributions:l,alive:d,self_recorded:p,skipped:s,laneText:()=>{try{return vt(t,"utf8")}catch{return""}}}}function _l(e){let n=e.skipped.length===0?"":` | unreadable anchors=${e.skipped.join(",")}`;if(e.attributions.length===0)return`death reaper: no un-recorded deaths (live=${e.alive.length} self-recorded=${e.self_recorded.length})${n}`;let t=e.attributions.map(r=>` | ${r.kind} ${r.id} pid=${r.pid} ${r.sender_class}/${r.confidence} phase=${r.last_phase}`+(r.evidence[0]?` evidence="${r.evidence[0]}"`:"")).join("");return`death reaper: attributed ${e.attributions.length}${t}${n}`}function sm(e,n){try{Wf(Rl(e,".."),{recursive:!0,mode:448});let t=im(e),r=t===""||t.endsWith(`
|
|
48
48
|
`)?"":`
|
|
49
|
-
`;
|
|
50
|
-
`)){let o=r.replace(/\r$/,""),
|
|
51
|
-
`||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=
|
|
52
|
-
`);return
|
|
49
|
+
`;Uf(e,`${t}${r}${om(n)}`,{encoding:"utf8",mode:384})}catch{}}function im(e){try{return vt(e,"utf8")}catch{return""}}import{join as lm}from"node:path";var am=[".red","redskilled"],le=448;function Le(e){return lm(e,...am)}import{execFileSync as wm}from"node:child_process";import{readFileSync as xm}from"node:fs";import{dirname as jl,join as Sm}from"node:path";import{existsSync as dm,readFileSync as Bw}from"node:fs";import{dirname as cm,join as um}from"node:path";function wl(e,n){let t=e;for(let r=0;r<16;r++){let o=um(t,n);if(dm(o))return o;let s=cm(t);if(s===t)break;t=s}return null}function pm(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function nn(e,n){let t=[];for(let r of e.split(`
|
|
50
|
+
`)){let o=r.replace(/\r$/,""),s=o.trim();if(!s||s.startsWith("#"))continue;let i=o.indexOf(":");if(i<0)continue;let a=o.length-o.trimStart().length,l=o.slice(0,i).trim();if(!l)continue;let d=o.slice(i+1).trim();for(;t.length&&t[t.length-1].indent>=a;)t.pop();if(t.push({indent:a,key:l}),d&&t.map(u=>u.key).join(".")===n)return pm(d)}}import{createHash as fm}from"node:crypto";var mm="project.name";function Sl(e){let n=nn(e,mm)?.trim();return n===void 0||n===""?void 0:n}var hm=8,vl="project";function El(e){let n=bm(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:ym(e.remoteUrl)??{name:gm(e.checkoutPath,n),source:"basename"},o=Rm(n??lo(e.checkoutPath));return{name:r.name,slug:`${km(r.name)}-${o}`,hash:o,source:r.source}}function Pl(e){let n=(e??"").trim();if(n==="")return;let t=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),r=/^[^/]*?:(?!\d)(.+)$/.exec(t),s=(r?r[1]:t.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(i=>i.trim()).filter(i=>i!=="");if(s.length!==0)return s.slice(-2).join("/")}function ym(e){let n=Pl(e);return n===void 0?void 0:{name:n,source:"remote"}}function gm(e,n){let t=n===void 0?"":xl(_m(n));if(t!=="")return t;let r=xl(lo(e));return r===""?vl:r}function km(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?vl:t}function Rm(e){return fm("sha256").update(e).digest("hex").slice(0,hm)}function bm(e){let n=lo(e??"");return n===""?void 0:n}function lo(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function xl(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function _m(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var vm=2e3;function Dl(e){return Em(e).name}function Em(e){let n=co(e),t=ao(e,["rev-parse","--absolute-git-dir"])??ao(e,["rev-parse","--git-common-dir"]),r=ao(e,["remote","get-url","origin"]);return El({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function co(e){let n=wl(e,Sm(".red","config.yaml"));if(n==null)return{};let t;try{t=xm(n,"utf8")}catch{return{}}let r=Sl(t),o=jl(jl(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function ao(e,n){try{let t=wm("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:vm}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as jc}from"node:crypto";import{spawn as _R}from"node:child_process";import{mkdir as wR,rm as xR}from"node:fs/promises";import{dirname as SR}from"node:path";import{createHash as Dm}from"node:crypto";import{constants as ho}from"node:fs";import{mkdir as Om,open as Am}from"node:fs/promises";import{createConnection as Lm}from"node:net";import{tmpdir as Tm}from"node:os";import{dirname as $m,join as Tn}from"node:path";var Pm="toon";function Ll(e){return e.trimStart().startsWith("{")?"json":"toon"}function po(e){let n=0;for(;e[n]===`
|
|
51
|
+
`||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=Ll(t);if(r==="json"){let s=t.indexOf(`
|
|
52
|
+
`);return s<0?null:{frame:t.slice(0,s),dialect:r,rest:t.slice(s+1)}}let o=t.indexOf(`
|
|
53
53
|
|
|
54
|
-
`);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function
|
|
54
|
+
`);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function fo(e){let n=Ll(e)==="json"?uo:Ol,t=n===uo?Ol:uo;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function uo(e){return JSON.parse(e)}function Ol(e){return q(e)}function mo(e,n){if(n==="toon"){let t=jm(e);if(t!==null)return t.endsWith(`
|
|
55
55
|
`)?`${t}
|
|
56
56
|
`:`${t}
|
|
57
57
|
|
|
58
58
|
`}return`${JSON.stringify(e)}
|
|
59
|
-
`}function am(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=M(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function hl(e,n){return!fl(e)||!fl(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function fl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var gl=new Set;function yl(e){return gl.has(e)?"json":lm}function kl(e){gl.add(e)}var hm=108;async function gt(e,n,t="resident server"){let r=e.wire,o=r??yl(e.socketPath),i=await bl(e,n,t,o);return r||o==="json"||!hl(n,i)?i:(kl(e.socketPath),await bl(e,n,t,"json"))}async function bl(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((i,s)=>{let a=pm(e.socketPath),l=!1,d="",p=setTimeout(()=>{u(()=>s(new Error(`${t} timed out`))),a.destroy()},o);function u(f){l||(l=!0,clearTimeout(p),f())}a.on("connect",()=>{a.write(Zr(n,r))}),a.on("data",f=>{d+=f.toString("utf8");let m=Yr(d);m&&(d=m.rest,u(()=>{try{i(Xr(m.frame))}catch(h){s(h)}}),a.end())}),a.on("error",f=>u(()=>s(f))),a.on("close",()=>{l||u(()=>s(new Error(`${t} closed without response`)))})})}function Rl(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let i=Yr(r);if(!i)return;r=i.rest,e.pause();let s=a=>{if(!(e.destroyed||!e.writable))try{e.write(Zr(a,i.dialect))}catch{}};(async()=>{let a;try{a=Xr(i.frame),await n(a,s)}catch(l){t(l,a,s)}finally{e.end()}})()})}async function _l(e){await cm(mm(e),{recursive:!0,mode:448});try{return await um(e,eo.O_CREAT|eo.O_EXCL|eo.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}function H(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var gm="/tmp";function yt(e){let n=e.env??process.env,t=dm("sha256").update(e.key).digest("hex").slice(0,20),r=l=>Pn(l,e.socketFileName).length<hm,o=n.XDG_RUNTIME_DIR;if(o){let l=Pn(o,"red-skills",t);if(r(l))return l}let i=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),s=Pn(`red-skills-${i}`,t),a=Pn(fm(),s);return r(a)||process.platform==="win32"?a:Pn(gm,s)}pe();import{homedir as Wm}from"node:os";import{join as ao}from"node:path";import{spawnSync as Fm}from"node:child_process";import{createHash as Bm}from"node:crypto";import{existsSync as Hm}from"node:fs";import{mkdir as jl,readFile as Um,writeFile as Gm}from"node:fs/promises";import{dirname as Km}from"node:path";var Te="@reddb-io/red-skills",Pm="https://registry.npmjs.org",jm="canary",Ye=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function Dm(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function _t(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return wt(r,Dm(n,t,o))}function Om(e){return e==="dev"?["rsp","redskilled"]:[]}function Am(e){return`${e}.bundle.min.mjs`}function Tm(e){return wt("dist",Am(e))}function $m(e,n="stable"){return`${Te}@${n==="canary"?jm:e}`}function Lm(e=Te){return`${Pm}/${e.replace("/","%2F")}`}async function lo(e,n){let{plugin:t,version:r,cacheDir:o,channel:i="stable"}=n,s=_t({plugin:t,version:r,cacheDir:o,channel:i}),a=Om(t),l=a.map(f=>_t({plugin:f,version:r,cacheDir:o,channel:i}));if(i!=="canary"&&await e.exists(s)&&await Im(e,l))return s;let d=$m(r,i),p=wt(o,`.staging-${t}-${i==="canary"?"canary":r}`),u;try{u=await e.materialize(d,p)}catch(f){throw Pl(f,d)}for(let f of[t,...a]){let m=Tm(f),h=wt(u,m);if(!await e.exists(h))throw new Ye("bundle-missing",`npm package ${d} has no ${m}`);let R=f===t?s:_t({plugin:f,version:r,cacheDir:o,channel:i});await e.writeFile(R,await e.readFile(h))}return s}async function Im(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function vl(e,n,t=Te){let r;try{r=await e.fetchText(Lm(t))}catch(i){throw Pl(i,t)}let o=Nm(r);return{sameMajor:Cm(o,n),newest:Mm(o)}}function Nm(e){let n;try{n=JSON.parse(e)}catch{return[]}if(typeof n!="object"||n===null)return[];let t=n.versions;return typeof t!="object"||t===null?[]:Object.keys(t)}function Cm(e,n){let t=so(n);if(t===null)return null;let r=null;for(let o of e)so(o)===t&&(r===null||El(o,r)>0)&&(r=o);return r}function Mm(e){let n=null;for(let t of e){let r=String(t).trim();so(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||El(r,n)>0)&&(n=r)}return n}function so(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function El(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n.trim());return!t||!r?0:Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function Pl(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Ye("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Ye("package-missing",`npm could not resolve ${n}: ${t}`,e):new Ye("network",`failed to resolve ${n}: ${t}`,e)}function wt(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}pe();var Vm={async materialize(e,n){await jl(n,{recursive:!0});let t=Fm("npm",["install",e,"--prefix",n,"--no-save","--no-audit","--no-fund","--ignore-scripts","--loglevel=error"],{stdio:["ignore","ignore","pipe"],encoding:"utf8"});if(t.error)throw t.error;if(t.status!==0)throw new Error(`npm install ${e} -> ${t.status}: ${(t.stderr||"").trim()}`);return ao(n,"node_modules",...Te.split("/"))},async readFile(e){return new Uint8Array(await Um(e))},async writeFile(e,n){await jl(Km(e),{recursive:!0}),await Gm(e,n)},async exists(e){return Hm(e)},sha256(e){return Bm("sha256").update(e).digest("hex")},async fetchText(e){let n=await fetch(e,{redirect:"follow"});if(!n.ok)throw new Error(`GET ${e} -> ${n.status}`);return await n.text()}},qm="redskilled";function Jm(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||ao(e.HOME||Wm(),".cache");return ao(n,"red-skills","bundles")}async function Qm(e={},n={},t={}){let r=Re(e,n);if(ae(r))return r;let o=t.env??n.env??process.env;try{await lo(t.bundleIO??Vm,{plugin:qm,version:t.version??"",cacheDir:Jm(o)})}catch{return r}return Re(e,n)}async function Dl(e={},n={},t={}){let r=await Qm(e,n,t);if(ae(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(pe(),Sl));throw new o(r)}import{randomUUID as Wn}from"node:crypto";import{mkdir as Xk,rm as oc}from"node:fs/promises";import{createServer as Zk}from"node:net";import{dirname as eb}from"node:path";import{totalmem as Ym}from"node:os";function On(e){if(e.applied_budget!=null)return e.applied_budget;let n=e.budget??{};return n.memory_max==null&&n.memory_high==null&&e.memory_ceiling!=null?{...n,memory_max:e.memory_ceiling}:n}function Ol(e,n={}){let t=0,r=0,o=0,i=[],s=[];for(let d of e){let p=On(d),u=!1;for(let[f,m]of[[p.memory_high,h=>t+=h],[p.memory_max,h=>r+=h]]){if(f==null)continue;let h=Xe(f);h==null?u=!0:m(h)}p.cpu_weight!=null&&(o+=p.cpu_weight),u&&i.push(d.worker_id),d.isolated||s.push(d.worker_id)}let a=n.hostCeilingBytes??null,l=a==null?0:Math.max(0,r-a);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:r,cpu_weight_total:o,unaccounted_workers:i.sort(),unisolated_workers:s.sort(),memory_ceiling_bytes:a,over_committed_bytes:l,over_commitment_reason:l===0?null:zm(e.length,r,a,l)}}function zm(e,n,t,r){return`this host's ${e} Worker(s) carry ${n} bytes of applied MemoryMax against a host ceiling of ${t} bytes \u2014 ${r} bytes over. A per-Worker MemoryMax is a wall rather than a reservation, so the host stays safe only while the Workers do not all peak together; the ceiling is not enforced host-wide.`}function Xe(e){let n=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!n)return null;let t={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[n[2].toLowerCase()];return Math.round(Number(n[1])*t)}function Al(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&Number.isInteger(n.worker_count)&&typeof n.memory_high_bytes=="number"&&typeof n.memory_max_bytes=="number"&&typeof n.cpu_weight_total=="number"&&Array.isArray(n.unaccounted_workers)&&Array.isArray(n.unisolated_workers)}var Xm="REDSKILLED_MEMORY_CEILING",Tl="REDSKILLED_WORKER_CEILING",Zm=.7;function $l(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return Xe(n)}function xt(e){let n=0,t=[];for(let r of e){let o=$l(r.budget);o===null?t.push(r.worker_id):o!==void 0&&(n+=o)}return{worker_count:e.length,memory_bytes:n,unaccounted_workers:t.sort()}}function Ll(e){let{ceiling:n}=e,t=xt(e.workers),r=$l(e.budget),o=r===void 0?null:r,i=t.memory_bytes+(r??0),s=t.worker_count+1,a=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",l=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,d=(p,u)=>({version:1,admitted:!1,verdict:p,reason:u,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:s,projected_memory_bytes:i});return n.worker_count!=null&&s>n.worker_count?d("refused-over-worker-ceiling",`redskilled refused this Worker${a}: it would be Worker ${s} past a host ceiling of ${n.worker_count} Worker(s), and ${l}`):n.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 ${n.memory_bytes} bytes, and ${l}`):n.memory_bytes!=null&&i>n.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 ${n.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 ${n.memory_bytes??"unbounded"} bytes, and ${l}`,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:s,projected_memory_bytes:i}}function Il(e){let n=e.budget?.memory_max??e.budget?.memory_high;if(n!=null)return{memory_max:n,reason:`the client declared this Worker's memory ceiling (${n}), so the host derived none`};if(e.ceiling.memory_bytes==null)return{memory_max:null,reason:"this host admits Workers against no memory ceiling, so there is no accounting to derive a per-Worker ceiling from; the daemon's RSS sampling floor is the only remaining ceiling"};let t=xt(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,i=o==null?r:Math.floor(e.ceiling.memory_bytes/o),s=Math.min(r,i);if(s<=0)return{memory_max:null,reason:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes is already fully committed to ${t.worker_count} Worker(s), so no positive per-Worker ceiling can be derived; the daemon's RSS sampling floor is the only remaining ceiling`};let a=o==null?`the headroom under this host's memory ceiling of ${e.ceiling.memory_bytes} bytes; this host declares no Worker slot count (${Tl} is unset), so this ceiling is a per-Worker wall and not memory the host sets aside \u2014 N Workers may carry N such walls, and the host ceiling is not enforced host-wide. Declare a slot count to make it divide into shares that sum to it`:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes shared across its ${o} Worker slot(s)`;return{memory_max:String(s),reason:`derived from ${a} (ceiling source: ${e.ceiling.source})`}}function Nl(e=process.env,n=Ym()){let t=(e[Xm]??"").trim(),r=(e[Tl]??"").trim(),o=nh(r);if(t!==""){let i=eh(t,n);if(i!==void 0)return{memory_bytes:i,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(n*Zm),worker_count:o,source:r!==""?"declared":"host-fraction"}}function eh(e,n){let t=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(t))return null;let r=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return r?Math.floor(n*(Number(r[1])/100)):Xe(e)??void 0}function nh(e){if(e===""||["infinity","none","off","unbounded"].includes(e.toLowerCase()))return null;let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:null}import{appendFile as th,mkdir as rh,open as oh,readFile as ih,stat as sh,truncate as Cl}from"node:fs/promises";import{dirname as lh}from"node:path";var Ml="redskilled.events.toonl";function ah(e){let n=e.worker.budget??{};return{version:1,ts:e.ts,event:e.event,worker_id:e.worker.worker_id,project_label:e.worker.project_label,pid:e.worker.pid,workspace_path:e.worker.workspace_path,log_path:e.worker.log_path??null,isolated:e.worker.isolated,unit:e.worker.unit??null,memory_high:n.memory_high??null,memory_max:n.memory_max??null,cpu_weight:n.cpu_weight??null,detail:e.detail??null,exit_code:e.exitCode??null,signal:e.signal??null,reason:e.reason??null}}var dh="daemon:";function ch(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${dh}${e.pid}`,project_label:"",pid:e.pid,workspace_path:e.socketPath,log_path:null,isolated:!1,unit:null,memory_high:null,memory_max:null,cpu_weight:null,detail:e.detail,exit_code:null,signal:e.signal??null,reason:e.reason}}function Wl(e){let n=ue({trailer:!1}),t=Promise.resolve();async function r(o){let i=t.then(async()=>{await rh(lh(e),{recursive:!0,mode:448}),await uh(e),await th(e,n.push(hh(o)),{encoding:"utf8",mode:384})});return t=i.catch(()=>{}),await i,o}return{path:e,record:o=>r(ah(o)),recordDaemonStop:o=>r(ch(o)),read:()=>ph(e),flush:async()=>{await t}}}async function uh(e){let n;try{n=(await sh(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await oh(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let i=n;i>0;i-=t){let s=Math.min(t,i),a=Buffer.alloc(s);await r.read(a,0,s,i-s);let l=a.lastIndexOf(10);if(l>=0){await Cl(e,i-s+l+1);return}}await Cl(e,0)}finally{await r.close()}}async function ph(e){let n;try{n=await ih(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return fh(n)}function fh(e){let n=e.split(`
|
|
60
|
-
`);return n.
|
|
59
|
+
`}function jm(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=M(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function Tl(e,n){return!Al(e)||!Al(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function Al(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var $l=new Set;function Il(e){return $l.has(e)?"json":Pm}function Nl(e){$l.add(e)}var Im=108;async function Et(e,n,t="resident server"){let r=e.wire,o=r??Il(e.socketPath),s=await Cl(e,n,t,o);return r||o==="json"||!Tl(n,s)?s:(Nl(e.socketPath),await Cl(e,n,t,"json"))}async function Cl(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let a=Lm(e.socketPath),l=!1,d="",p=setTimeout(()=>{u(()=>i(new Error(`${t} timed out`))),a.destroy()},o);function u(f){l||(l=!0,clearTimeout(p),f())}a.on("connect",()=>{a.write(mo(n,r))}),a.on("data",f=>{d+=f.toString("utf8");let m=po(d);m&&(d=m.rest,u(()=>{try{s(fo(m.frame))}catch(h){i(h)}}),a.end())}),a.on("error",f=>u(()=>i(f))),a.on("close",()=>{l||u(()=>i(new Error(`${t} closed without response`)))})})}function Ml(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=po(r);if(!s)return;r=s.rest,e.pause();let i=a=>{if(!(e.destroyed||!e.writable))try{e.write(mo(a,s.dialect))}catch{}};(async()=>{let a;try{a=fo(s.frame),await n(a,i)}catch(l){t(l,a,i)}finally{e.end()}})()})}async function Wl(e){await Om($m(e),{recursive:!0,mode:448});try{return await Am(e,ho.O_CREAT|ho.O_EXCL|ho.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}function H(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var Nm="/tmp";function Pt(e){let n=e.env??process.env,t=Dm("sha256").update(e.key).digest("hex").slice(0,20),r=l=>Tn(l,e.socketFileName).length<Im,o=n.XDG_RUNTIME_DIR;if(o){let l=Tn(o,"red-skills",t);if(r(l))return l}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=Tn(`red-skills-${s}`,t),a=Tn(Tm(),i);return r(a)||process.platform==="win32"?a:Tn(Nm,i)}fe();import{homedir as sh}from"node:os";import{join as xo}from"node:path";import{spawnSync as ih}from"node:child_process";import{createHash as lh}from"node:crypto";import{existsSync as ah}from"node:fs";import{mkdir as Vl,readFile as dh,writeFile as ch}from"node:fs/promises";import{dirname as uh}from"node:path";var $e="@reddb-io/red-skills",qm="https://registry.npmjs.org",Jm="canary",tn=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function Qm(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function At(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return Lt(r,Qm(n,t,o))}function zm(e){return e==="dev"?["rsp","redskilled"]:[]}function Ym(e){return`${e}.bundle.min.mjs`}function Xm(e){return Lt("dist",Ym(e))}function Zm(e,n="stable"){return`${$e}@${n==="canary"?Jm:e}`}function eh(e=$e){return`${qm}/${e.replace("/","%2F")}`}async function wo(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=At({plugin:t,version:r,cacheDir:o,channel:s}),a=zm(t),l=a.map(f=>At({plugin:f,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await nh(e,l))return i;let d=Zm(r,s),p=Lt(o,`.staging-${t}-${s==="canary"?"canary":r}`),u;try{u=await e.materialize(d,p)}catch(f){throw Kl(f,d)}for(let f of[t,...a]){let m=Xm(f),h=Lt(u,m);if(!await e.exists(h))throw new tn("bundle-missing",`npm package ${d} has no ${m}`);let b=f===t?i:At({plugin:f,version:r,cacheDir:o,channel:s});await e.writeFile(b,await e.readFile(h))}return i}async function nh(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function Hl(e,n,t=$e){let r;try{r=await e.fetchText(eh(t))}catch(s){throw Kl(s,t)}let o=th(r);return{sameMajor:rh(o,n),newest:oh(o)}}function th(e){let n;try{n=JSON.parse(e)}catch{return[]}if(typeof n!="object"||n===null)return[];let t=n.versions;return typeof t!="object"||t===null?[]:Object.keys(t)}function rh(e,n){let t=_o(n);if(t===null)return null;let r=null;for(let o of e)_o(o)===t&&(r===null||Gl(o,r)>0)&&(r=o);return r}function oh(e){let n=null;for(let t of e){let r=String(t).trim();_o(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||Gl(r,n)>0)&&(n=r)}return n}function _o(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function Gl(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n.trim());return!t||!r?0:Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function Kl(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new tn("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new tn("package-missing",`npm could not resolve ${n}: ${t}`,e):new tn("network",`failed to resolve ${n}: ${t}`,e)}function Lt(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}fe();var ph={async materialize(e,n){await Vl(n,{recursive:!0});let t=ih("npm",["install",e,"--prefix",n,"--no-save","--no-audit","--no-fund","--ignore-scripts","--loglevel=error"],{stdio:["ignore","ignore","pipe"],encoding:"utf8"});if(t.error)throw t.error;if(t.status!==0)throw new Error(`npm install ${e} -> ${t.status}: ${(t.stderr||"").trim()}`);return xo(n,"node_modules",...$e.split("/"))},async readFile(e){return new Uint8Array(await dh(e))},async writeFile(e,n){await Vl(uh(e),{recursive:!0}),await ch(e,n)},async exists(e){return ah(e)},sha256(e){return lh("sha256").update(e).digest("hex")},async fetchText(e){let n=await fetch(e,{redirect:"follow"});if(!n.ok)throw new Error(`GET ${e} -> ${n.status}`);return await n.text()}},fh="redskilled";function mh(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||xo(e.HOME||sh(),".cache");return xo(n,"red-skills","bundles")}async function hh(e={},n={},t={}){let r=_e(e,n);if(de(r))return r;let o=t.env??n.env??process.env;try{await wo(t.bundleIO??ph,{plugin:fh,version:t.version??"",cacheDir:mh(o)})}catch{return r}return _e(e,n)}async function ql(e={},n={},t={}){let r=await hh(e,n,t);if(de(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(fe(),Ul));throw new o(r)}import{randomUUID as Qn}from"node:crypto";import{mkdir as dR,rm as Sc}from"node:fs/promises";import{createServer as cR}from"node:net";import{dirname as uR}from"node:path";import{totalmem as gh}from"node:os";function Nn(e){if(e.applied_budget!=null)return e.applied_budget;let n=e.budget??{};return n.memory_max==null&&n.memory_high==null&&e.memory_ceiling!=null?{...n,memory_max:e.memory_ceiling}:n}function Jl(e,n={}){let t=0,r=0,o=0,s=[],i=[];for(let d of e){let p=Nn(d),u=!1;for(let[f,m]of[[p.memory_high,h=>t+=h],[p.memory_max,h=>r+=h]]){if(f==null)continue;let h=rn(f);h==null?u=!0:m(h)}p.cpu_weight!=null&&(o+=p.cpu_weight),u&&s.push(d.worker_id),d.isolated||i.push(d.worker_id)}let a=n.hostCeilingBytes??null,l=a==null?0:Math.max(0,r-a);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:r,cpu_weight_total:o,unaccounted_workers:s.sort(),unisolated_workers:i.sort(),memory_ceiling_bytes:a,over_committed_bytes:l,over_commitment_reason:l===0?null:yh(e.length,r,a,l)}}function yh(e,n,t,r){return`this host's ${e} Worker(s) carry ${n} bytes of applied MemoryMax against a host ceiling of ${t} bytes \u2014 ${r} bytes over. A per-Worker MemoryMax is a wall rather than a reservation, so the host stays safe only while the Workers do not all peak together; the ceiling is not enforced host-wide.`}function rn(e){let n=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!n)return null;let t={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[n[2].toLowerCase()];return Math.round(Number(n[1])*t)}function Ql(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&Number.isInteger(n.worker_count)&&typeof n.memory_high_bytes=="number"&&typeof n.memory_max_bytes=="number"&&typeof n.cpu_weight_total=="number"&&Array.isArray(n.unaccounted_workers)&&Array.isArray(n.unisolated_workers)}var zl="REDSKILLED_MEMORY_CEILING",So="REDSKILLED_WORKER_CEILING",Yl=.7;function Zl(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return rn(n)}function Tt(e){let n=0,t=[];for(let r of e){let o=Zl(r.budget);o===null?t.push(r.worker_id):o!==void 0&&(n+=o)}return{worker_count:e.length,memory_bytes:n,unaccounted_workers:t.sort()}}function ea(e){let{ceiling:n}=e,t=Tt(e.workers),r=Zl(e.budget),o=r===void 0?null:r,s=t.memory_bytes+(r??0),i=t.worker_count+1,a=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",l=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,d=(p,u)=>({version:1,admitted:!1,verdict:p,reason:u,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s});return n.worker_count!=null&&i>n.worker_count?d("refused-over-worker-ceiling",`redskilled refused this Worker${a}: it would be Worker ${i} past a host ceiling of ${n.worker_count} Worker(s), and ${l}`):n.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 ${n.memory_bytes} bytes, and ${l}`):n.memory_bytes!=null&&s>n.memory_bytes?d("refused-over-memory-ceiling",`redskilled refused this Worker${a}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${n.memory_bytes} bytes, and ${l}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${a}: ${s} bytes of declared Worker memory against a host ceiling of ${n.memory_bytes??"unbounded"} bytes, and ${l}`,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function na(e){let n=e.budget?.memory_max??e.budget?.memory_high;if(n!=null)return{memory_max:n,reason:`the client declared this Worker's memory ceiling (${n}), so the host derived none`};if(e.ceiling.memory_bytes==null)return{memory_max:null,reason:"this host admits Workers against no memory ceiling, so there is no accounting to derive a per-Worker ceiling from; the daemon's RSS sampling floor is the only remaining ceiling"};let t=Tt(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,s=o==null?r:Math.floor(e.ceiling.memory_bytes/o),i=Math.min(r,s);if(i<=0)return{memory_max:null,reason:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes is already fully committed to ${t.worker_count} Worker(s), so no positive per-Worker ceiling can be derived; the daemon's RSS sampling floor is the only remaining ceiling`};let a=o==null?`the headroom under this host's memory ceiling of ${e.ceiling.memory_bytes} bytes; this host declares no Worker slot count (${So} is unset), so this ceiling is a per-Worker wall and not memory the host sets aside \u2014 N Workers may carry N such walls, and the host ceiling is not enforced host-wide. Declare a slot count to make it divide into shares that sum to it`:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes shared across its ${o} Worker slot(s)`;return{memory_max:String(i),reason:`derived from ${a} (ceiling source: ${e.ceiling.source})`}}function ta(e=process.env,n=gh()){let t=(e[zl]??"").trim(),r=(e[So]??"").trim(),o=bh(r);if(t!==""){let s=Rh(t,n);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"};Xl(`redskilled: ${zl}=${JSON.stringify(t)} is not a memory ceiling this host can read; using ${Yl*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return r!==""&&o===null&&!kh(r)&&Xl(`redskilled: ${So}=${JSON.stringify(r)} is not a positive integer; this host admits an unbounded number of Workers instead.`),{memory_bytes:Math.floor(n*Yl),worker_count:o,source:"host-fraction"}}function kh(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var Xl=e=>process.stderr.write(`${e}
|
|
60
|
+
`);function Rh(e,n){let t=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(t))return null;let r=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return r?Math.floor(n*(Number(r[1])/100)):rn(e)??void 0}function bh(e){if(e===""||["infinity","none","off","unbounded"].includes(e.toLowerCase()))return null;let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:null}import{appendFile as _h,mkdir as wh,open as xh,readFile as Sh,stat as vh,truncate as ra}from"node:fs/promises";import{dirname as Eh}from"node:path";var oa="redskilled.events.toonl";function Ph(e){let n=e.worker.budget??{};return{version:1,ts:e.ts,event:e.event,worker_id:e.worker.worker_id,project_label:e.worker.project_label,pid:e.worker.pid,workspace_path:e.worker.workspace_path,log_path:e.worker.log_path??null,isolated:e.worker.isolated,unit:e.worker.unit??null,memory_high:n.memory_high??null,memory_max:n.memory_max??null,cpu_weight:n.cpu_weight??null,detail:e.detail??null,exit_code:e.exitCode??null,signal:e.signal??null,reason:e.reason??null}}var jh="daemon:";function Dh(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${jh}${e.pid}`,project_label:"",pid:e.pid,workspace_path:e.socketPath,log_path:null,isolated:!1,unit:null,memory_high:null,memory_max:null,cpu_weight:null,detail:e.detail,exit_code:null,signal:e.signal??null,reason:e.reason}}function sa(e){let n=pe({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await wh(Eh(e),{recursive:!0,mode:448}),await Oh(e),await _h(e,n.push($h(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(Ph(o)),recordDaemonStop:o=>r(Dh(o)),read:()=>Ah(e),flush:async()=>{await t}}}async function Oh(e){let n;try{n=(await vh(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await xh(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let s=n;s>0;s-=t){let i=Math.min(t,s),a=Buffer.alloc(i);await r.read(a,0,i,s-i);let l=a.lastIndexOf(10);if(l>=0){await ra(e,s-i+l+1);return}}await ra(e,0)}finally{await r.close()}}async function Ah(e){let n;try{n=await Sh(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return Lh(n)}function Lh(e){let n=e.split(`
|
|
61
|
+
`);return n.pop(),n.length===0?[]:Re(`${n.join(`
|
|
61
62
|
`)}
|
|
62
|
-
`).filter(
|
|
63
|
-
`}function Th(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Y(n)}catch{return null}}}function $h(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||n.scope!=="machine"||!Number.isInteger(n.pid)||n.pid<=0||!Number.isInteger(n.uid))return!1;for(let t of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var Lh=["worker_id","slot","workspace_path","log_path"],po=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${Lh.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},Ih=/\{\{([a-z_]+)\}\}/g;function Nh(e,n){let t=(s,a)=>s.replace(Ih,(l,d)=>{switch(d){case"worker_id":return n.worker_id;case"slot":return String(n.slot);case"workspace_path":return n.workspace_path;case"log_path":return n.log_path??"";default:throw new po(d,a)}}),r=e.argv.map((s,a)=>t(s,`argv word ${a}`)),o={};for(let[s,a]of Object.entries(e.env??{}))o[s]=t(a,`env entry ${JSON.stringify(s)}`);let i=e.log_path==null?void 0:t(e.log_path,"the log path");return{argv:r,env:o,...i==null||i===""?{}:{log_path:i}}}function ta(e,n,t){let r=Nh(e,n),o=r.log_path??n.log_path,[i,...s]=r.argv;if(i===void 0||i==="")throw new Error(`redskilled cannot start a Worker for project ${JSON.stringify(t.project_label)}: its launch expanded to an argv with no command`);return{worker_id:n.worker_id,project_label:t.project_label,workspace_path:n.workspace_path,...o==null||o===""?{}:{log_path:o},command:i,args:s,env:r.env}}function fo(e,n){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(n)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((t,r)=>{if(typeof t!="string"||t==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${r} of project ${JSON.stringify(n)} is not`);return t})}function mo(e,n){if(e!=null){if(typeof e!="string"||e.trim()==="")throw new Error(`redskilled needs a declared log path to be a non-empty string to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}: a project that declares an empty path states a Worker whose output no surface can ever show, which reads as a Worker with nothing to say`);return e}}function ho(e,n){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error(`redskilled needs a launch env to be a map of strings to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}`);let t={};for(let[r,o]of Object.entries(e)){if(r==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(n)} to be named`);if(typeof o!="string")throw new Error(`redskilled needs every launch env value to be a string, and ${JSON.stringify(r)} of project ${JSON.stringify(n)} is ${JSON.stringify(o)}`);t[r]=o}return t}var Ch=3e5,Mh=.5,yo=class extends Error{constructor(t){super(`redskilled already holds a registration for project ${JSON.stringify(t.project_label)}, registered at ${t.registered_at} for a target of ${t.target} and standing until ${t.renew_by}: a project contributes one registration, so a second one is refused rather than silently replacing the first`);this.held=t;this.name="RedskilledProjectRegisteredError"}};function ra(e,n){if(n.held!=null)throw new yo(n.held);let t=go(e.project_label,"a project label"),r=go(e.selector,"a selector"),o=fo(e.argv,t),i=ho(e.env,t),s=mo(e.log_path,t),a=go(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.target)}`);let l=e.renew_within_ms??Ch;if(!Number.isFinite(l)||l<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let d=Date.parse(n.now);if(!Number.isFinite(d))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(n.now)}`);return{version:1,project_label:t,selector:r,argv:o,workspace_path:a,env:i,...s==null?{}:{log_path:s},target:e.target,registered_at:new Date(d).toISOString(),renew_within_ms:l,renew_by:new Date(d+l).toISOString(),renewed_at:new Date(d).toISOString(),renewals:0,launch_revision:0}}var Pt=class extends Error{constructor(t){super(`redskilled holds no registration for project ${JSON.stringify(t)} to renew: it lapsed or was never held, and a renewal never mints a record \u2014 register again, stating the selector, the argv and the target`);this.projectLabel=t;this.name="RedskilledProjectUnregisteredError"}};function oa(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(n.now)}`);let r=n.renew_within_ms??e.renew_within_ms;if(!Number.isFinite(r)||r<=0)throw new Error(`redskilled needs a positive renewal window to renew project ${JSON.stringify(e.project_label)}, not ${JSON.stringify(n.renew_within_ms)}`);let o=n.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:fo(n.launch.argv,e.project_label),env:ho(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},i=n.launch==null?e.log_path:mo(n.launch.log_path,e.project_label),{log_path:s,...a}=e;return{...a,...i==null?{}:{log_path:i},...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1}}function ia(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(n.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,n.liveWorkers??0),i=n.queue,s=i!=null&&i.outcome==="counted"?i.depth:null,a=s!=null&&s>0?"open-work":o>0?"live-worker":null;if(a==null){let l=s===0?"drained":"uncounted";return{registration:e,verdict:l,detail:l==="drained"?`project ${r} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${r}, and an uncounted queue never sustains a registration \u2014 it stands on its own deadline of ${e.renew_by}`}}return{registration:{...e,renew_by:new Date(t+e.renew_within_ms).toISOString(),sustained_at:new Date(t).toISOString(),sustains:(e.sustains??0)+1,sustained_by:a},verdict:a,detail:a==="open-work"?`project ${r} has ${s} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function Wh(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function sa(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=i=>Number.isFinite(i)&&n-i<=e.renew_within_ms*Mh;if(r(t))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return r(o)?"self-renewing":"running-on"}function la(e,n){let t=[],r=[];for(let o of e)(Wh(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function ko(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.project_label=="string"&&typeof n.selector=="string"&&Array.isArray(n.argv)&&n.argv.every(t=>typeof t=="string")&&typeof n.workspace_path=="string"&&Number.isInteger(n.target)&&typeof n.registered_at=="string"&&typeof n.renew_within_ms=="number"&&typeof n.renew_by=="string"&&(n.renewed_at===void 0||typeof n.renewed_at=="string")&&(n.renewals===void 0||Number.isInteger(n.renewals))&&(n.env===void 0||Fh(n.env))&&(n.log_path===void 0||typeof n.log_path=="string")&&(n.launch_revision===void 0||Number.isInteger(n.launch_revision))&&(n.sustained_at===void 0||typeof n.sustained_at=="string")&&(n.sustains===void 0||Number.isInteger(n.sustains))&&(n.sustained_by===void 0||n.sustained_by==="open-work"||n.sustained_by==="live-worker")}function Fh(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function go(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var Bh={ping:"host-read","host-state":"host-read","statusline-payload":"host-read",shutdown:"daemon-life","worker-start":"project-write","worker-stop":"project-write","worker-recycle":"project-write","worker-steer":"project-write","worker-heartbeat":"project-write","project-register":"project-write","project-renew":"project-write","project-deregister":"project-write"};function aa(e){return`worker-${e}`}function da(e){let n=Bh[e.op]??"project-write",t=e.sessionProject??null,r=e.targetProject??null,o={version:1,op:e.op,reach:n,session_project:t,target_project:r};return n==="host-read"?{...o,permitted:!0,verdict:"permitted-host-read",reason:`redskilled permitted ${e.op}: a session reads the whole host, whichever project it was started in`}:n==="daemon-life"?{...o,permitted:!0,verdict:"permitted-daemon-life",reason:`redskilled permitted ${e.op}: it acts on the daemon's own process, not on any project's Workers`}:t==null||t===""?{...o,permitted:!0,verdict:"permitted-unattributed",reason:`redskilled permitted ${e.op}: the session named no project of its own, so there is nothing to refuse it against`}:r!=null&&r===t?{...o,permitted:!0,verdict:"permitted-own-project",reason:`redskilled permitted ${e.op}: the target belongs to project ${JSON.stringify(t)}, which is this session's own`}:{...o,permitted:!1,verdict:"refused-cross-project",reason:`redskilled refused ${e.op} from a session in project ${JSON.stringify(t)}: ${r==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(r)}`}. A session reads the whole host and writes only its own project.`}}function ca(e){return e==="single-object"?"rest":"graphql"}function T(e,n,t,r,o){return{key:e,kind:"read",cardinality:n,surface:o??ca(n),budget:t,...o?{only:o}:{},why:r}}function B(e,n,t,r){return{key:e,kind:"write",cardinality:"single-object",surface:n,budget:t,why:r}}var ua=[T("issue view","single-object","rest","one issue by number; REST answers it in one request against the idle pool"),T("pr view","single-object","rest","one pull request by number, polled per Worker per iteration"),T("repo view","single-object","rest","one repository's own metadata"),T("run view","single-object","rest","one Actions run; the Actions API has no GraphQL surface either way"),T("release view","single-object","rest","one release by tag"),T("pr diff","single-object","rest","one pull request's diff, served by a REST media type"),T("issue list","multi-node","graphql","a connection of issues; one GraphQL query beats N REST pages"),T("pr list","multi-node","graphql","a connection of pull requests; one GraphQL query beats N REST pages"),T("pr checks","multi-node","graphql","every check context on one commit, which is a connection, not an object"),T("release list","multi-node","rest","Releases have no GraphQL connection gh reads; REST pages them","rest"),T("run list","multi-node","rest","the Actions API has no GraphQL surface, so a listing draws the request pool","rest"),T("label list","multi-node","graphql","a connection of labels inside one repository"),T("issue list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),T("pr list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),T("search issues","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("search prs","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("search repos","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("api graphql","multi-node","graphql","the caller wrote the query; `gh api graphql` is GraphQL by construction"),T("api rest","single-object","rest","any `gh api <path>` that is not `graphql` is a REST request"),B("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),B("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),B("issue close","graphql","graphql","gh closes with the closeIssue mutation"),B("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),B("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),B("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),B("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),B("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),B("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),B("pr close","graphql","graphql","gh closes with a GraphQL mutation"),B("pr edit","graphql","graphql","gh edits with GraphQL mutations"),B("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),B("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),B("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],Hh=new Map(ua.map(e=>[e.key,e]));function pa(e){let n=[],t=0;for(;t<e.length&&e[t].startsWith("-");)t+=e[t]==="-R"||e[t]==="--repo"?2:1;for(;t<e.length&&!e[t].startsWith("-")&&n.length<2;)n.push(e[t]),t+=1;return n}function bo(e){let n=pa(e);if(n.length===0)return"";if(n[0]==="api")return n[1]==="graphql"?"api graphql":"api rest";let t=n.length===1?n[0]:`${n[0]} ${n[1]}`;return n[1]==="list"&&e.includes("--search")?`${t} (search)`:t}var jt=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(n){let t=bo(n);super(`unclassified GitHub operation ${JSON.stringify(t||"(empty argv)")}: add an entry to GITHUB_OPERATIONS in packages/github/surface.ts stating its cardinality. Defaulting to GraphQL is what sent every single-object poll to the node-point pool (ADR 0132 decision 4).`),this.operation=t,this.args=[...n]}};function fa(e){return Hh.get(bo(e))??null}function ma(e){let n=fa(e);if(!n)throw new jt(e);return n}function Ro(e){return ma(e).surface}var ga="rate_limit",ya={rest:"core",graphql:"graphql",search:"search"},me=["rest","graphql","search"];function Tt(e,n){return{version:1,origin:"asked",outcome:"unanswered",source:"GET /rate_limit",asked_at:e,request_count:0,pools:{rest:null,graphql:null,search:null},unreported_pools:[...me],detail:n??"no balance has been asked for yet, so none is known"}}var wo=15e3,Ze=.15,Ot=[{at_or_below_fraction:0,every_ms:wo,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:Ze,every_ms:3e4,why:"inside the reserved band: the posture can change between two calls"},{at_or_below_fraction:.5,every_ms:12e4,why:"below half: tightening, because the band is now reachable inside one window"},{at_or_below_fraction:1,every_ms:6e5,why:"above half: rare, because nothing this balance decides is anywhere close"}],_o=2;function ka(e,n){let t=ha(e),r=ha(t.resources),o={rest:null,graphql:null,search:null},i=[];for(let a of me){let l=ya[a],d=r[l],p=Kh(a,l,d);o[a]=p,p==null&&i.push(a)}let s=me.length-i.length;return{version:1,origin:"asked",outcome:s>0?"asked":"unanswered",source:"GET /rate_limit",asked_at:n.askedAt,request_count:1,pools:o,unreported_pools:i,detail:s>0?`the token's own answer for ${s} of ${me.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function xo(e){try{let n=await e.transport();return ka(n,{askedAt:e.now})}catch(n){let t=n instanceof Error?n.message:String(n);return{...Tt(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function So(e){let n=null;for(let t of me){let r=e.pools[t];r!=null&&(n==null||r.fraction<n.fraction)&&(n=r)}return n}function $t(e,n){let t=So(e);if(t==null)return At(Ze).every_ms;let r=At(t.fraction);if(t.remaining>0)return r.every_ms;let o=Ra(n.now,t.reset_at);return o==null?r.every_ms:Math.max(wo,Math.min(r.every_ms,o))}function vo(e,n=Ze){return Math.ceil(e.limit*n)}function ba(e,n,t=Ze){let r=e.pools[n];return r==null?"unknown":r.remaining<=0?"spent":r.remaining<vo(r,t)?"reserved":"open"}function Eo(e){let n=e.reservedFraction??Ze,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:At(n).every_ms*_o,stale:!1,posture:"unknown",reserved_fraction:n,next_poll_ms:At(n).every_ms,pools:[],unreported_pools:[...me],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let r=$t(t,{now:e.now}),o=e.stalenessMs??r*_o,i=Ra(t.asked_at,e.now),s=t.outcome==="asked"&&(i==null||i>o),a=me.map(p=>t.pools[p]).filter(p=>p!=null),l=Gh(t,n),d=So(t);return{version:1,origin:"asked",outcome:t.outcome,asked_at:t.asked_at,age_ms:i,threshold_ms:o,stale:s,posture:l,reserved_fraction:n,next_poll_ms:r,pools:a,unreported_pools:t.unreported_pools,reason:s?`this balance is stale: asked ${i==null?"at an unreadable instant":`${i}ms ago`}, past the ${o}ms window, so the posture below is the last one the token confirmed and not the current one`:Uh(l,d,t,n)}}function Uh(e,n,t,r){if(n==null)return t.detail;let o=vo(n,r);switch(e){case"spent":return`the ${n.pool} pool is spent and resets at ${n.reset_at}: work is not queued, it is refused`;case"reserved":return`the ${n.pool} pool has ${n.remaining} of ${n.limit} left, inside the reserved band of ${o}: convenience reads are refused and the claim, a landing and a closing comment still pass`;default:return`the ${n.pool} pool is the tightest at ${n.remaining} of ${n.limit}, above the reserved band of ${o}`}}function Gh(e,n){let t="unknown";for(let r of me){if(e.pools[r]==null)continue;let o=ba(e,r,n);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function At(e){for(let n of Ot)if(e<=n.at_or_below_fraction)return n;return Ot[Ot.length-1]}function Kh(e,n,t){if(!_a(t))return null;let r=Dt(t.limit),o=Dt(t.remaining),i=Dt(t.used),s=Dt(t.reset);return r==null||r<=0||o==null?null:{pool:e,resource:n,limit:r,remaining:o,used:i??0,reset_at:s==null?"":new Date(s*1e3).toISOString(),fraction:o/r}}function Po(e){let n=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let r=await t(`${n}/${ga}`,{method:"GET",headers:{authorization:`bearer ${e.token}`,accept:"application/vnd.github+json"}});if(!r.ok)throw new Error(`the balance ask was refused with HTTP ${r.status}`);return await r.json()}}function Ra(e,n){let t=Date.parse(e),r=Date.parse(n);return!Number.isFinite(t)||!Number.isFinite(r)?null:Math.max(0,r-t)}function Dt(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function ha(e){return _a(e)?e:{}}function _a(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ea(e){return{generated_at:e.now,hour:wa("hour",36e5,e),day:wa("day",864e5,e)}}function Lt(e,n,t){let r=An(t.now),o=t.retentionMs??864e5,i=t.limit??8192,s=e.filter(a=>{let l=An(n(a));return l==null?!1:r==null||r-l<=o});return s.length<=i?s:s.slice(s.length-i)}function wa(e,n,t){let r=An(t.now),o=r==null?null:r-n,i=e==="hour"?"1h":"24h",s=t.observations.map(u=>({observation:u,at:An(u.observed_at)})).filter(u=>u.at!=null&&va(u.at,o,r)).sort((u,f)=>u.at-f.at),a=t.outcomes.map(u=>An(u.ts)).filter(u=>u!=null&&va(u,o,r)),l=xa(s,u=>u.tokens,"tokens",i),d=xa(s,u=>u.tools,"tools",i),p=[];return s.length===0?p.push("worker-vitals"):(l.samples===0&&p.push("worker-vitals.tokens"),d.samples===0&&p.push("worker-vitals.tools")),a.length===0&&p.push("worker-outcomes"),{window:e,window_ms:n,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:l,tools_per_min:d,issues_per_hour:qh(a.length,n,i),runner_share:Sa("runner",s,u=>u.runner,i),model_share:Sa("model",s,u=>u.model,i),unavailable:p}}function xa(e,n,t,r){let o=new Map,i=0;for(let d of e){let p=n(d.observation);if(p==null||!Number.isFinite(p))continue;i+=1;let u=o.get(d.observation.worker_id)??[];u.push({at:d.at,count:p}),o.set(d.observation.worker_id,u)}if(i===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${r}`,samples:0};let s=0,a=null,l=null;for(let d of o.values()){if(d.length<2)continue;for(let f=1;f<d.length;f++){let m=d[f-1],h=d[f];m==null||h==null||(s+=Math.max(0,h.count-m.count))}let p=d[0],u=d[d.length-1];p!=null&&(a=a==null?p.at:Math.min(a,p.at)),u!=null&&(l=l==null?u.at:Math.max(l,u.at))}return a==null||l==null||l<=a?{value:null,absent_reason:`the last ${r} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:i}:{value:s/((l-a)/6e4),absent_reason:null,samples:i}}function qh(e,n,t){return e===0?{value:null,absent_reason:`no Worker outcome was recorded in the last ${t}`,samples:0}:{value:e/(n/36e5),absent_reason:null,samples:e}}function Sa(e,n,t,r){let o=new Map;for(let d of n){let p=t(d.observation);p!=null?o.set(d.observation.worker_id,p):o.has(d.observation.worker_id)||o.set(d.observation.worker_id,null)}let i=new Map,s=0,a=0;for(let d of o.values()){if(d==null){a+=1;continue}s+=1,i.set(d,(i.get(d)??0)+1)}let l=[...i.entries()].map(([d,p])=>({key:d,worker_count:p,share:p/s})).sort((d,p)=>p.worker_count-d.worker_count||d.key.localeCompare(p.key));return{dimension:e,attributed_workers:s,unattributed_workers:a,shares:l,absent_reason:l.length>0?null:o.size===0?`no Worker was observed in the last ${r}`:`no Worker published a ${e} in the last ${r}`}}function va(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function An(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}import{execFileSync as Jh}from"node:child_process";import{existsSync as Qh,readFileSync as It,readdirSync as zh}from"node:fs";import{dirname as Yh,join as $e}from"node:path";function Tn(e){let n=On(e),t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let i=Xe(o);return i==null?null:{name:r,declared:o,bytes:i}}return null}function Pa(e){let n=[],t=[];for(let r of e.workers){let o=Tn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(On(r).memory_max??On(r).memory_high)==null?"this Worker declared no memory budget and the host derived no ceiling for it, so the sampler has none to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let i=e.rss[r.worker_id];if(typeof i!="number"||!Number.isFinite(i)){t.push({worker_id:r.worker_id,reason:"the host produced no RSS reading for this Worker on this tick, and an unmeasured Worker is never killed on suspicion"});continue}if(!(i<=o.bytes)){if(e.sources?.[r.worker_id]==="cgroup"&&o.name==="MemoryMax"){t.push({worker_id:r.worker_id,reason:`this Worker's ${o.name} of ${o.declared} is held by the kernel on its own cgroup, and the reading is memory.current \u2014 which counts reclaimable page cache the kernel drops before it kills anything, so the daemon does not duplicate an enforcement that can tell cache from anonymous memory`});continue}n.push(Xh(r,o,i))}}return{terminations:n,unenforceable:t}}function Xh(e,n,t){let r=`Worker ${JSON.stringify(e.worker_id)} of project ${JSON.stringify(e.project_label)}`;return{version:1,worker_id:e.worker_id,project_label:e.project_label,outcome:"terminated-over-memory-budget",classification:"budget-exceeded",stall:!1,budget_name:n.name,budget_declared:n.declared,budget_bytes:n.bytes,observed_rss_bytes:t,workspace_path:e.workspace_path,reason:`redskilled terminated ${r}: its tree RSS of ${t} bytes exceeded its ${n.name} budget of ${n.declared} (${n.bytes} bytes). This is a budget termination, not a stall, and the work in ${JSON.stringify(e.workspace_path)} is handed forward.`}}var Zh=4096;function ja(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return r;let o={},i={},s={},a=ng(e,t,n);for(let[u,f]of a){let m=og(f);m!=null&&(o[u]=m.memoryBytes,m.cpuSeconds!=null&&(i[u]=m.cpuSeconds),s[u]="cgroup")}let l=e.filter(u=>s[u.worker_id]==null);if(l.length===0)return{rss:o,cpu_seconds:i,sources:s};let d=lg(t,n);if(d.size===0)return{rss:o,cpu_seconds:i,sources:s};let p=new Map;for(let u of d.values()){let f=p.get(u.ppid);f?f.push(u.pid):p.set(u.ppid,[u.pid])}for(let u of l){if(!d.has(u.pid))continue;let f=0,m=0,h=[u.pid],R=new Set;for(;h.length>0;){let k=h.pop();if(R.has(k))continue;R.add(k);let _=d.get(k);if(_){f+=_.rssBytes,m+=_.cpuSeconds;for(let j of p.get(k)??[])h.push(j)}}o[u.worker_id]=f,i[u.worker_id]=m,s[u.worker_id]="process-tree"}return{rss:o,cpu_seconds:i,sources:s}}var eg="/sys/fs/cgroup";function ng(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let i=t.cgroupRoot??eg,s=e.filter(l=>l.unit!=null&&l.unit!=="");if(s.length===0)return r;let a=tg(i,t);for(let l of s)for(let d of a){let p=$e(d,l.unit);if(Qh($e(p,"memory.current"))){r.set(l.worker_id,p);break}}return r}function tg(e,n){let t=n.selfCgroupPath??rg(),r=[],o=a=>{r.includes(a)||r.push(a)},i=t;for(;i!=null&&i!==""&&i!=="/"&&i!==".";){o($e(e,i));let a=Yh(i);if(a===i)break;i=a}o(e);let s=n.uid??process.getuid?.();return s!=null&&o($e(e,"user.slice",`user-${s}.slice`,`user@${s}.service`,"app.slice")),r}function rg(){try{for(let e of It("/proc/self/cgroup","utf8").split(`
|
|
64
|
-
`))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function
|
|
65
|
-
`)){let[t,r]=n.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(r);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function
|
|
66
|
-
`)){let r=t.trim().split(/\s+/);if(r.length!==4)continue;let[o,i
|
|
67
|
-
`),aliases:i,closed_since:o}}function wg(e,n,t){let r=en(n),o=en(r.data),i=Array.isArray(r.errors)?r.errors.map(en):[],s=vg(o.rateLimit,i),a=e.aliases.map(({alias:l,search_alias:d,project:p})=>{let u=p.owner+"/"+p.name,f=o[l],m=i.find(h=>Oa(h.path,l)||Oa(h.path,d));if(Na(f)){let h=Aa(f.open_pull_requests),R=Aa(f.open_issues),k=Eg(o[d]);if(h!=null&&R!=null&&k!=null)return{project_label:p.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:h,open_issues:R,recently_closed:k},detail:`counted ${u} for project ${JSON.stringify(p.project_label)}`}}return s.exhausted||Ia(m)?{project_label:p.project_label,repository:u,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${u} answered, so this project has no counts rather than zero counts${s.reset_at==null?"":`; the quota resets at ${s.reset_at}`}`}:{project_label:p.project_label,repository:u,outcome:"unreachable",counts:null,detail:`${u} is not reachable with the host token: ${Do(m?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:a.length,rate_limit:s,projects:a}}function xg(e){return{version:1,fetched_at:e,request_count:0,project_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1,point_cost:null},projects:[]}}async function Ta(e){if(e.projects.length===0)return xg(e.now);Ao(e.projects,e.hostTokenRef);let n=_g(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return wg(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,point_cost:null},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 $a(e){let n=e.stalenessMs??bg,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,point_cost:null},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(a=>({...a,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 La(e){let n=e.endpoint??kg(yg),t=e.fetchImpl??fetch;return async r=>{let o=await t(n,{method:"POST",headers:{authorization:`bearer ${e.token}`,"content-type":"application/json",accept:"application/vnd.github+json"},body:JSON.stringify({query:r})});if(!o.ok){let i=o.headers.get("x-ratelimit-remaining"),s=o.status===429||i==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(s?": the host token's rate limit is spent":""))}return await o.json()}}function Sg(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>Da)throw new Error(`redskilled activity fetch spans at most ${Da} 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 vg(e,n){let t=en(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,i=n.some(Ia),s=typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:null;return{remaining:r,reset_at:o,exhausted:i||r===0,point_cost:s}}function Ia(e){if(e==null)return!1;let n=Do(e.type),t=Do(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function Oa(e,n){return Array.isArray(e)&&e.includes(n)}function Aa(e){let n=en(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function Eg(e){let n=en(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function en(e){return Na(e)?e:{}}function Na(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Do(e){return typeof e=="string"?e:""}var Pg=3e4,jg=4;function Ca(e){let n=e.stalenessMs??Pg,t=$n(e.now),r=e.sampledAt==null?null:$n(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),i=o!=null&&o<=n,s=new Set(e.reattachedWorkerIds??[]),a=e.hostState.workers.map(f=>Ag(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:i,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:s.has(f.worker_id)?"reattached":"running"})),l=a.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=a.length-l.length,p=a.reduce((f,m)=>f+(m.vitals.rss_bytes??0),0),u=xt(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:Ig({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:a.length,measuredCount:d,unmeasured:l}),host:{worker_count:a.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:u,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:p,measured_worker_count:d,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:u.memory_bytes/e.ceiling.memory_bytes},projects:Lg(a),known_projects:$g(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,m)=>f.localeCompare(m)),workers:a,github_balance:Eo({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:$a({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:Dg(e.deaths,e.recentDeathLimit??jg)},engine:Og(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function Dg(e,n){let t=[...e].sort((o,i)=>($n(i.ts)??0)-($n(o.ts)??0)),r=t.slice(0,Math.max(0,Math.floor(n))).map(o=>({kind:o.kind,id:o.id,pid:o.pid,ts:o.ts,last_seen:o.last_seen,last_phase:o.last_phase,sender_class:o.sender_class,confidence:o.confidence,signal:o.signal,evidence:o.evidence[0]??null}));return{count:t.length,recent:r,latest:r[0]??null,reaped_at:r[0]?.ts??null}}function Og(e){let n=e.upgrade,t=n?.running_version??e.daemon_version,r=n?.published_version??null,o=n?.newest_published_version??null,i=(n?.newer_published??0)>0,s=(n?.major_held??0)>0;return{running_version:t,published_version:r,newer_published:i,major_held:s,current:r==null&&o==null?null:!i&&!s}}function Ag(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=Tn(e),i=e.budget?.memory_max??e.budget?.memory_high??null,s=$n(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,rss_source:r==null?null:e.rss_source??null},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:Tg(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function Tg(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 $g(e){let n=new Set;for(let t of e.registrations??[])n.add(t.project_label);for(let t of e.projects)n.add(t.project_label);return[...n].sort((t,r)=>t.localeCompare(r))}function Lg(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 Ig(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 $n(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}var $={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Ma(e,n=$){let t=Hg(e,n),r=Fg(e,n),o=Bg(e,n),i=Ug(e,n,r,t),s=Mg(n,r,o),a={detail:"host",line:i};for(let u of s){let f=ey(i,Wg(u,n,r,o),n.separator);if(a={detail:u,line:f},ny(f)<=n.maxWidth)break}let l=Co(a.line,n.maxWidth),d=n.verbose&&a.detail==="workers"?zg(r,n):[],p=r.length>0?"workers":"host";return{version:1,line:l,lines:[l,...d],verbose:n.verbose,mode:n.mode,project:n.project,project_match:t,detail:a.detail,degraded:a.detail!==p||l!==a.line,stale:e.staleness.stale,generated_at:e.generated_at}}function Wa(e){let n=e.options??$,t=Co(Cg,n.maxWidth);return{version:1,line:t,lines:[t],verbose:n.verbose,mode:n.mode,project:n.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}var Ng="!unregistered",$o="\u21E1",Nt="\u2020",Lo="\u25D0",Io="\u25EF",Cg="redskilled unreachable \u2014 Worker state unknown";function Mg(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 Wg(e,n,t,r){return e==="workers"?t.map(o=>Qg(o,n)):e==="projects"?r.map(Zg):[]}function Fg(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Bg(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function Hg(e,n){return No(e,n.project)}function No(e,n){return n==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(n)?e.registered_projects==null||e.registered_projects.includes(n)?"matched":"name-only":"unregistered"}function Ug(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(To(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(To(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(To(e,n)),o.push(Ng)):o.push(qg(n.project,r)),o.push(Gg(e));let i=Kg(e);i!=null&&o.push(i);let s=Vg(e);return s!=null&&o.push(s),e.staleness.stale&&o.push(Jg(e)),o.join(" ")}function Gg(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${$o}`}function Kg(e){let n=e.github_balance;return n==null?null:n.posture==="spent"?`${Io} quota spent`:n.posture==="reserved"?`${Lo} quota band`:null}function Vg(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Nt}${n.count} ${n.latest.sender_class}`}function qg(e,n){return n==="unregistered"?`project unknown \u2014 ${e} is not registered on this host`:"project unknown \u2014 this directory resolved to no project"}function To(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?`${X(t)}/${X(r)}`:X(t)}function Jg(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function Qg(e,n){let t=Fa(e,n),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?X(r):`${X(r)}/${X(e.budget.bytes)}`;return`${t} ${o}`}function zg(e,n){let t=[];for(let r of e){let o=Xg(r.log.last_line);o!=null&&t.push(Co(` ${Yg} ${Fa(r,n)}: ${o}`,n.maxWidth))}return t}var Yg="\u21B3";function Xg(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}function Fa(e,n){return n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Zg(e){return`${e.project_label} ${e.worker_count}w ${X(e.observed_rss_bytes)}`}function ey(e,n,t){return[e,...n].join(t)}function ny(e){return[...e].length}function Co(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 X(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}var Mo={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},ty=["runner","model","effort","origin","issue","phase","step","heartbeat"],ry=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function Ba(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...Mo};for(let r of ty){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of ry){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}var Ct=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],tn={mode:"local",project:null,maxWidth:200,maxRows:16};var oy=" ",Ha="\u2588",iy="\u25B6",sy="\u2717",ly="\u2591";function Ua(e,n=tn){let t=No(e,n.project),r=ay(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),i=o.map(u=>dy(u,n)),s=by(i),a=o.map((u,f)=>({worker_id:u.worker_id,project_label:u.project_label,mine:n.project!=null&&u.project_label===n.project,cells:i[f],line:nn(Ry(i[f],s),n.maxWidth)})),l=uy(e,n,r,t),d=r.length-o.length,p=[l.line,...a.map(u=>u.line)];return d>0&&p.push(nn(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),p.push(...my(e,n)),p.push(...fy(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Ct,header:l,rows:a,lines:p,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function ay(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function dy(e,n){let t=e.display??Mo,r=[t.runner,t.model,t.effort].filter(o=>!!o).join(" ");return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:r===""?"":`run=${r}`,org:t.origin==null?"":`org=${t.origin}`,iss:t.issue==null?"":`iss=${t.issue}`,bar:cy(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:ky(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:yy(t.added,t.removed),tks:t.tokens==null?"":`tks=${Ga(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function cy(e){let n=e.phase_total,t=e.phase_index;if(n==null||n<=0||t==null||t<0)return"";let r=Math.min(Math.floor(t),Math.floor(n));if(r>=n)return Ha.repeat(Math.floor(n));let o=e.failed?sy:iy;return`${Ha.repeat(r)}${o}${ly.repeat(Math.floor(n)-r-1)}`}function uy(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(_=>_.project_label===n.project),i={open_pull_requests:o?.counts?.open_pull_requests??null,recently_closed:o?.counts?.recently_closed??null,open_issues:o?.counts?.open_issues??null,stale:o?.stale===!0},s={memory_used_fraction:e.host.ceiling_used_fraction,memory_used_bytes:e.host.consumption.memory_bytes,memory_ceiling_bytes:e.host.ceiling.memory_bytes,worker_count:e.host.worker_count,worker_ceiling:e.host.ceiling.worker_count},a=gy(t),l=o?.repository??n.project,d=e.engine??null,p=d?.running_version??e.daemon.daemon_version,u=e.deaths??null,f=e.metrics??null,m=[`\xBB ${l??"host"} v${p}${d!=null&&d.current===!1?$o:""}`];r==="unregistered"&&m.push("!unregistered"),r==="name-only"&&m.push("!lapsed"),a!=null&&m.push(a),m.push(`wrk=${t.length}/${e.host.worker_count}`),m.push(s.worker_ceiling==null?"slots=\u221E":`slots=${s.worker_count}/${s.worker_ceiling}`),m.push(hy(s)),i.open_pull_requests!=null&&m.push(`prs=${i.open_pull_requests}`),i.recently_closed!=null&&m.push(`cpr=${i.recently_closed}`),i.open_issues!=null&&m.push(`iss=${i.open_issues}`),i.stale&&m.push("!counts stale");let h=f==null?null:py(f.hour);if(h!=null&&m.push(h),u!=null&&u.count>0&&u.latest!=null&&m.push(`${Nt}${u.count} ${u.latest.sender_class}`),e.staleness.stale){let _=e.staleness.age_ms;m.push(_==null?"!unmeasured":`!stale ${Math.round(_/1e3)}s`)}let R=m.join(" \xB7 "),k=h!=null&&Fo(R)>n.maxWidth?m.filter(_=>_!==h).join(" \xB7 "):R;return{repo:l,project:n.project,project_match:r,version:p,engine:d,deaths:u,metrics:f,model:a,windows:s,counts:i,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:nn(k,n.maxWidth)}}function py(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${Wo(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${Wo(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${Wo(e.issues_per_hour.value)}`);let t=e.runner_share.shares[0];return t!=null&&n.push(`${t.key}=${Math.round(t.share*100)}%`),n.length===0?null:n.join(" ")}function fy(e,n){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let r=t.posture==="spent"?Io:Lo,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[nn(`${r} github budget ${t.posture}${o} \u2014 ${t.reason}`,n.maxWidth)]}function my(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(i=>nn(`${Nt} ${i.kind} ${i.id} pid=${i.pid} ${i.sender_class}/${i.confidence} phase=${i.last_phase}`+(i.signal==null?"":` signal=${i.signal}`)+(i.evidence==null?"":` \u2014 ${i.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(nn(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function hy(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${X(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${X(e.memory_used_bytes)}/${X(e.memory_ceiling_bytes)}${n}`}function gy(e){for(let n of e){let t=n.display;if(t==null)continue;let r=[t.runner,t.model,t.effort].filter(o=>!!o);if(r.length>0)return r.join("\xB7")}return null}function yy(e,n){if(e==null&&n==null)return"";let t=[];return e!=null&&e>0&&t.push(`+${e}`),n!=null&&n>0&&t.push(`-${n}`),`loc=${t.length>0?t.join(" "):"0"}`}function Ga(e){if(!Number.isFinite(e)||e<=0)return"0";let n=(t,r)=>{let o=(Math.round(t*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${r}`};return e>=1e9?n(e/1e9,"B"):e>=1e6?n(e/1e6,"M"):e>=1e3?n(e/1e3,"k"):String(Math.round(e))}function Wo(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return Ga(e);if(e<=0)return"0";let n=(Math.round(e*10)/10).toFixed(1);return n.endsWith(".0")?n.slice(0,-2):n}function ky(e){if(e==null||!Number.isFinite(e)||e<0)return"\u2014";let n=Math.floor(e/1e3);if(n<60)return`${n}s`;let t=Math.floor(n/60);if(t<60)return`${t}m${n%60}s`;let r=Math.floor(t/60);return r<24?`${r}h${t%60}m`:`${Math.floor(r/24)}d${r%24}h`}function by(e){let n=Object.fromEntries(Ct.map(t=>[t,0]));for(let t of e)for(let r of Ct)n[r]=Math.max(n[r],Fo(t[r]));return n}function Ry(e,n){return Ct.filter(r=>n[r]>0).map(r=>_y(e[r],n[r])).join(oy).replace(/\s+$/,"")}function _y(e,n){return e+" ".repeat(Math.max(0,n-Fo(e)))}function Fo(e){return[...e].length}function nn(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}var Mt=1;async function Ln(e,n){return await gt(e,n,"redskilled daemon")}function Ka(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.line=="string"&&Array.isArray(n.lines)&&n.lines.every(t=>typeof t=="string")&&typeof n.verbose=="boolean"&&(n.mode==="local"||n.mode==="global")&&(n.project===null||typeof n.project=="string")&&typeof n.detail=="string"&&(n.project_match===void 0||typeof n.project_match=="string")&&typeof n.degraded=="boolean"&&typeof n.stale=="boolean"&&typeof n.generated_at=="string"}function Va(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:Mt,daemon_version:e.daemonVersion,machine_id_hash:e.machineIdHash,session_key_hash:e.sessionKeyHash,pid:e.pid,started_at:e.startedAt,...e.scope==null?{}:{scope:e.scope},workers:n,projects:[...t.entries()].map(([r,o])=>({project_label:r,worker_count:o})).sort((r,o)=>r.project_label.localeCompare(o.project_label)),registrations:Sy(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:Ol(n,{hostCeilingBytes:e.hostCeilingBytes??null}),upgrade:vy(e)}}function Sy(e){let n=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(n),r=e.queue??null,o=new Map(r==null?[]:r.projects.map(i=>[i.project_label,i]));return[...e.registrations??[]].map(i=>{let s=o.get(i.project_label);return{...i,...t?{renewal:sa(i,n)}:{},...r==null||s==null?{}:{last_poll:{at:r.fetched_at,outcome:s.outcome,depth:s.depth,request_count:r.request_count,detail:s.detail}}}}).sort((i,s)=>i.project_label.localeCompare(s.project_label))}function vy(e){let n=e.daemonVersion,t=e.published?.version??null,r=e.published?.majorHold??null;return{running_version:n,published_version:t,published_unknown:+(t===null),newer_published:+(e.published?.newer===!0),replacement:e.published?.replacement??"none",checked_at:e.published?.checkedAt??null,checks:e.published?.checks??0,hold_reason:e.published?.holdReason??null,newest_published_version:e.published?.newest??null,major_held:+(r!==null),major_hold:r}}function qa(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)&&Al(n.budget_accounting)&&(n.scope===void 0||na(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(ko))&&(n.upgrade===void 0||Ey(n.upgrade))}function Ey(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")&&typeof n.published_unknown=="number"&&typeof n.newer_published=="number"&&(n.replacement==="none"||n.replacement==="pending"||n.replacement==="in-progress")&&(n.checked_at===null||typeof n.checked_at=="string")&&(n.newest_published_version===void 0||n.newest_published_version===null||typeof n.newest_published_version=="string")&&(n.major_held===void 0||typeof n.major_held=="number")&&(n.checks===void 0||typeof n.checks=="number")&&(n.hold_reason===void 0||n.hold_reason===null||typeof n.hold_reason=="string")&&(n.major_hold===void 0||n.major_hold===null||Py(n.major_hold))}function Py(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.version=="string"&&Number.isInteger(n.running_major)&&Number.isInteger(n.held_major)&&typeof n.reason=="string"&&typeof n.action=="string"&&n.action.trim()!==""}import{spawnSync as Bt}from"node:child_process";import{existsSync as Ko}from"node:fs";import{delimiter as Ny,join as rd}from"node:path";import{join as Ja}from"node:path";import{existsSync as jy}from"node:fs";import{createRequire as Dy}from"node:module";var Qa="redskilled-job-object.node",Le=100;function rn(e){return{available:!1,reason:e}}function Oy(e,n,t){return[Ja(t,"prebuilds",`${e}-${n}`,Qa),Ja(t,"native","build","Release",Qa)]}function za(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return rn(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??Ty(),o=e.exists??jy,i=Oy(n,t,r),s=i.find(d=>o(d));if(s==null)return rn(`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 a=e.requireFn??Dy(import.meta.url),l;try{l=a(s)}catch(d){return rn(`the Job Object addon at ${s} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return Ay(l)?{available:!0,binding:l}:rn(`the Job Object addon at ${s} does not export createJobObject, so it cannot be the native reach`)}function Ay(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Ty(){return new URL("..",import.meta.url).pathname}function Ya(e){let n=e??{},t=[],r=$y(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<Le?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 ${Le}, 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 $y(e){return Tn({budget:e})}var Wt=5,Xa=19;function Bo(e){return{available:!1,reason:e}}var Ly="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 ed(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=Wt;else if(t.cpu_weight<Le){let a=Math.round(Xa*(Le-t.cpu_weight)/Le);o=Math.min(Xa,Math.max(Wt,a))}else o=Wt,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${Le}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Wt}`);let i=Za(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=Za(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:Ly,...r.length>0?{note:r.join("; ")}:{}}}function nd(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 ${Iy(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
|
|
68
|
-
`),e.command,...e.args]}function
|
|
69
|
-
`).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function
|
|
70
|
-
`),aliases:r}}function
|
|
71
|
-
`);for(let t=n.length-1;t>=0;t-=1){let r=n[t].replace(/\r$/,"");if(r.trim()!=="")return r}return null}import{spawn as
|
|
72
|
-
`)}function
|
|
63
|
+
`).filter(Ih).map(Nh)}function ia(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,Th(t)):n.delete(t.worker_id));return[...n.values()]}function Th(e){let n={...e.memory_high!=null?{memory_high:e.memory_high}:{},...e.memory_max!=null?{memory_max:e.memory_max}:{},...e.cpu_weight!=null?{cpu_weight:e.cpu_weight}:{}};return{worker_id:e.worker_id,project_label:e.project_label,pid:e.pid,started_at:e.ts,workspace_path:e.workspace_path,...e.log_path!=null?{log_path:e.log_path}:{},isolated:e.isolated,...e.unit!=null?{unit:e.unit}:{},...Object.keys(n).length>0?{budget:n}:{},warnings:[]}}function $h(e){return{...e}}function Ih(e){return e.version===1&&typeof e.ts=="string"&&typeof e.worker_id=="string"&&(e.event==="worker-birth"||e.event==="worker-death"||e.event==="worker-budget-kill"||e.event==="daemon-stop")}function Nh(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:me(e.project_label)??"",pid:Number(e.pid??0),workspace_path:me(e.workspace_path)??"",log_path:me(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:me(e.unit),memory_high:me(e.memory_high),memory_max:me(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:me(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:me(e.signal),reason:me(e.reason)}}function me(e){return e==null||e===""?null:String(e)}function la(e){let n=[...e.projects].sort((i,a)=>i.project_label.localeCompare(a.project_label)),t=e.backoffUntilMs??null,r=t!=null&&e.nowMs<t,o=[],s=[];for(let i of n){let a=Math.max(0,e.live[i.project_label]??0),l=Object.prototype.hasOwnProperty.call(e.queue,i.project_label),d=l?e.queue[i.project_label]??null:null,p={project_label:i.project_label,queue_depth:d,target:i.target,live:a};if(r){o.push({...p,outcome:"backing-off",wanted:0,detail:`the host refused a Worker, so no project is asked for one again before ${new Date(t).toISOString()}`});continue}let u=e.birthHaltUntilMs?.[i.project_label];if(u!=null&&e.nowMs<u){o.push({...p,outcome:"birth-halted",wanted:0,detail:`project ${JSON.stringify(i.project_label)} lost 3 Workers in a row inside 60000ms of birth, so it is not asked for another before ${new Date(u).toISOString()} \u2014 a Worker that cannot survive boot will not survive the next one either, and every birth spends host quota shared with every project`});continue}if(d==null){o.push({...p,outcome:"queue-unknown",wanted:0,detail:l?`the last poll produced no depth for project ${JSON.stringify(i.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(i.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...p,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(i.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,i.target),d)-a);if(f===0){o.push({...p,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(i.project_label)} holds ${a} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for none`});continue}o.push({...p,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(i.project_label)} holds ${a} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for ${f} more`});for(let m=0;m<f;m+=1)(s[m]??(s[m]=[])).push({project_label:i.project_label,index:a+m,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function aa(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}var $t={shortLifeStreak:0,haltUntilMs:null};function da(e,n,t){if(n>=6e4)return $t;let r=e.shortLifeStreak+1;return r<3?{shortLifeStreak:r,haltUntilMs:null}:{shortLifeStreak:r,haltUntilMs:t+6e5}}function ca(e,n){let t={};for(let[r,o]of Object.entries(e))o.haltUntilMs!=null&&n<o.haltUntilMs&&(t[r]=o.haltUntilMs);return t}function pa(e){let n=e.workers.map(Ch),t=[...new Set([...n.map(o=>o.project_label),...e.projects??[]])].filter(o=>o!=="").sort(),r=n.filter(o=>o.survives).map(o=>o.worker_id);return{version:1,running:!0,stopped:!0,reason:e.reason,socket_path:e.socketPath,daemon_version:e.daemonVersion,pid:e.pid,holding:{workers:n,projects:t},surviving:r,detail:Wh({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function fa(e){return{version:1,running:!1,stopped:!1,reason:"not-running",socket_path:e,daemon_version:null,pid:null,holding:{workers:[],projects:[]},surviving:[],detail:`no redskilled daemon is answering on ${JSON.stringify(e)}, so there was nothing to stop`}}function Ch(e){return{worker_id:e.worker_id,project_label:e.project_label,pid:e.pid,unit:e.unit??null,isolated:e.isolated,survives:!0}}function Mh(e){return e==="requested"?"an operator asked for it":e==="signal"?"the daemon was signalled":e==="idle"?"the daemon was idle and held nothing":e==="replaced"?"a newer published bundle is taking the session over":"no daemon was running"}function Wh(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Mh(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${ua(e.held,"Worker")} across ${ua(e.projects,"project")}, and ${e.surviving} of them survive it \u2014 a Worker is an init-system unit, so this is a restart and not an evacuation`}function ua(e,n){return`${e} ${n}${e===1?"":"s"}`}function vo(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.holding;return n.version===1&&typeof n.running=="boolean"&&typeof n.stopped=="boolean"&&typeof n.reason=="string"&&typeof n.socket_path=="string"&&typeof n.detail=="string"&&(n.daemon_version===null||typeof n.daemon_version=="string")&&(n.pid===null||typeof n.pid=="number")&&t!=null&&Array.isArray(t.workers)&&Array.isArray(t.projects)&&Array.isArray(n.surviving)}import{chmod as Bh,mkdir as Fh,readFile as Uh,rm as Hh,writeFile as Gh}from"node:fs/promises";import{dirname as ma,join as ka}from"node:path";import{tmpdir as ha}from"node:os";var Kh="redskilled.machine.claim.toon",Vh="REDSKILLED_MACHINE_DIR",qh=8,we=class extends Error{constructor(t,r,o){super(Qh(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},ya;function Ra(){return ya??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},ya}function Jh(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[Vh]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||ha():ha();return ka(o,`redskilled-${e.machineIdHash}`)}function It(e){return ka(Jh(e),Kh)}function Nt(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??H;async function s(){let l;try{l=await Uh(e,"utf8")}catch(p){if(p.code==="ENOENT"||Eo(p))return;throw p}let d=Yh(l);return Xh(d)?d:void 0}function i(l,d){return{version:1,scope:"machine",pid:l.pid,start_time:l.startTime,uid:l.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}async function a(){try{return await Hh(e,{force:!0}),!0}catch(l){if(Eo(l))return!1;throw l}}return{claimPath:e,read:s,async claim(l){await Fh(ma(e),{recursive:!0,mode:1023})!=null&&await Bh(ma(e),1023).catch(()=>{});let p=!1;for(let u=0;u<qh;u+=1){let f=i(l,r());try{return await Gh(e,zh(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:p,claim:f}}catch(h){if(h.code!=="EEXIST"){if(Eo(h))return{claimed:!1,reason:"stale-claim-not-reapable"};throw h}}let m=await s();if(!m){if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable"};p=!0;continue}if(ga(m,l,n.socketPath))return{claimed:!0,reaped:p,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};p=!0}return{claimed:!1,reason:"contended"}},async release(l){let d=await s();return!d||!ga(d,l,n.socketPath)?!1:await a()}}}function ba(e,n,t){return{kind:"machine",claim_path:e,owner_uid:t.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath}}function _a(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.kind==="machine"&&typeof n.claim_path=="string"&&typeof n.owner_uid=="number"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&typeof n.socket_path=="string"}function Qh(e,n,t){let r=t==null?"":` \u2014 held by pid ${t.pid} (uid ${t.uid}) on socket ${JSON.stringify(t.socket_path)}`;return n==="held"?`this machine already has a redskilled daemon${r}; a second one would void the host budget, so none was started. Reach that daemon, or stop it before starting another.`:n==="stale-claim-not-reapable"?`the redskilled machine claim ${JSON.stringify(e)} is stale and cannot be removed by this user${r}; remove it as its owner, then start again. No second daemon was started.`:`the redskilled machine claim ${JSON.stringify(e)} changed hands repeatedly; no daemon was started.`}function Eo(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function ga(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function zh(e){return`${M(e,{keyedMapCollapse:!0})}
|
|
64
|
+
`}function Yh(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return q(n)}catch{return null}}}function Xh(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||n.scope!=="machine"||!Number.isInteger(n.pid)||n.pid<=0||!Number.isInteger(n.uid))return!1;for(let t of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var Zh=["worker_id","slot","workspace_path","log_path"],Po=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${Zh.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},ey=/\{\{([a-z_]+)\}\}/g;function ny(e,n){let t=(i,a)=>i.replace(ey,(l,d)=>{switch(d){case"worker_id":return n.worker_id;case"slot":return String(n.slot);case"workspace_path":return n.workspace_path;case"log_path":return n.log_path??"";default:throw new Po(d,a)}}),r=e.argv.map((i,a)=>t(i,`argv word ${a}`)),o={};for(let[i,a]of Object.entries(e.env??{}))o[i]=t(a,`env entry ${JSON.stringify(i)}`);let s=e.log_path==null?void 0:t(e.log_path,"the log path");return{argv:r,env:o,...s==null||s===""?{}:{log_path:s}}}function wa(e,n,t){let r=ny(e,n),o=r.log_path??n.log_path,[s,...i]=r.argv;if(s===void 0||s==="")throw new Error(`redskilled cannot start a Worker for project ${JSON.stringify(t.project_label)}: its launch expanded to an argv with no command`);return{worker_id:n.worker_id,project_label:t.project_label,workspace_path:n.workspace_path,...o==null||o===""?{}:{log_path:o},command:s,args:i,env:r.env}}function jo(e,n){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(n)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((t,r)=>{if(typeof t!="string"||t==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${r} of project ${JSON.stringify(n)} is not`);return t})}function Do(e,n){if(e!=null){if(typeof e!="string"||e.trim()==="")throw new Error(`redskilled needs a declared log path to be a non-empty string to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}: a project that declares an empty path states a Worker whose output no surface can ever show, which reads as a Worker with nothing to say`);return e}}function Oo(e,n){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error(`redskilled needs a launch env to be a map of strings to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}`);let t={};for(let[r,o]of Object.entries(e)){if(r==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(n)} to be named`);if(typeof o!="string")throw new Error(`redskilled needs every launch env value to be a string, and ${JSON.stringify(r)} of project ${JSON.stringify(n)} is ${JSON.stringify(o)}`);t[r]=o}return t}var ty=3e5,ry=.5,Lo=class extends Error{constructor(t){super(`redskilled already holds a registration for project ${JSON.stringify(t.project_label)}, registered at ${t.registered_at} for a target of ${t.target} and standing until ${t.renew_by}: a project contributes one registration, so a second one is refused rather than silently replacing the first`);this.held=t;this.name="RedskilledProjectRegisteredError"}};function xa(e,n){if(n.held!=null)throw new Lo(n.held);let t=Ao(e.project_label,"a project label"),r=Ao(e.selector,"a selector"),o=jo(e.argv,t),s=Oo(e.env,t),i=Do(e.log_path,t),a=Ao(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.target)}`);let l=e.renew_within_ms??ty;if(!Number.isFinite(l)||l<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let d=Date.parse(n.now);if(!Number.isFinite(d))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(n.now)}`);return{version:1,project_label:t,selector:r,argv:o,workspace_path:a,env:s,...i==null?{}:{log_path:i},target:e.target,registered_at:new Date(d).toISOString(),renew_within_ms:l,renew_by:new Date(d+l).toISOString(),renewed_at:new Date(d).toISOString(),renewals:0,launch_revision:0}}var Ct=class extends Error{constructor(t){super(`redskilled holds no registration for project ${JSON.stringify(t)} to renew: it lapsed or was never held, and a renewal never mints a record \u2014 register again, stating the selector, the argv and the target`);this.projectLabel=t;this.name="RedskilledProjectUnregisteredError"}};function Sa(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(n.now)}`);let r=n.renew_within_ms??e.renew_within_ms;if(!Number.isFinite(r)||r<=0)throw new Error(`redskilled needs a positive renewal window to renew project ${JSON.stringify(e.project_label)}, not ${JSON.stringify(n.renew_within_ms)}`);let o=n.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:jo(n.launch.argv,e.project_label),env:Oo(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=n.launch==null?e.log_path:Do(n.launch.log_path,e.project_label),{log_path:i,...a}=e;return{...a,...s==null?{}:{log_path:s},...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1}}function va(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(n.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,n.liveWorkers??0),s=n.queue,i=s!=null&&s.outcome==="counted"?s.depth:null,a=i!=null&&i>0?"open-work":o>0?"live-worker":null;if(a==null){let l=i===0?"drained":"uncounted";return{registration:e,verdict:l,detail:l==="drained"?`project ${r} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${r}, and an uncounted queue never sustains a registration \u2014 it stands on its own deadline of ${e.renew_by}`}}return{registration:{...e,renew_by:new Date(t+e.renew_within_ms).toISOString(),sustained_at:new Date(t).toISOString(),sustains:(e.sustains??0)+1,sustained_by:a},verdict:a,detail:a==="open-work"?`project ${r} has ${i} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function oy(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function Ea(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*ry;if(r(t))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return r(o)?"self-renewing":"running-on"}function Pa(e,n){let t=[],r=[];for(let o of e)(oy(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function To(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.project_label=="string"&&typeof n.selector=="string"&&Array.isArray(n.argv)&&n.argv.every(t=>typeof t=="string")&&typeof n.workspace_path=="string"&&Number.isInteger(n.target)&&typeof n.registered_at=="string"&&typeof n.renew_within_ms=="number"&&typeof n.renew_by=="string"&&(n.renewed_at===void 0||typeof n.renewed_at=="string")&&(n.renewals===void 0||Number.isInteger(n.renewals))&&(n.env===void 0||sy(n.env))&&(n.log_path===void 0||typeof n.log_path=="string")&&(n.launch_revision===void 0||Number.isInteger(n.launch_revision))&&(n.sustained_at===void 0||typeof n.sustained_at=="string")&&(n.sustains===void 0||Number.isInteger(n.sustains))&&(n.sustained_by===void 0||n.sustained_by==="open-work"||n.sustained_by==="live-worker")}function sy(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function Ao(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var iy={ping:"host-read","host-state":"host-read","statusline-payload":"host-read",shutdown:"daemon-life","worker-start":"project-write","worker-stop":"project-write","worker-recycle":"project-write","worker-steer":"project-write","worker-heartbeat":"project-write","project-register":"project-write","project-renew":"project-write","project-deregister":"project-write"};function ja(e){return`worker-${e}`}function Da(e){let n=iy[e.op]??"project-write",t=e.sessionProject??null,r=e.targetProject??null,o={version:1,op:e.op,reach:n,session_project:t,target_project:r};return n==="host-read"?{...o,permitted:!0,verdict:"permitted-host-read",reason:`redskilled permitted ${e.op}: a session reads the whole host, whichever project it was started in`}:n==="daemon-life"?{...o,permitted:!0,verdict:"permitted-daemon-life",reason:`redskilled permitted ${e.op}: it acts on the daemon's own process, not on any project's Workers`}:t==null||t===""?{...o,permitted:!0,verdict:"permitted-unattributed",reason:`redskilled permitted ${e.op}: the session named no project of its own, so there is nothing to refuse it against`}:r!=null&&r===t?{...o,permitted:!0,verdict:"permitted-own-project",reason:`redskilled permitted ${e.op}: the target belongs to project ${JSON.stringify(t)}, which is this session's own`}:{...o,permitted:!1,verdict:"refused-cross-project",reason:`redskilled refused ${e.op} from a session in project ${JSON.stringify(t)}: ${r==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(r)}`}. A session reads the whole host and writes only its own project.`}}function Oa(e){return e==="single-object"?"rest":"graphql"}function T(e,n,t,r,o){return{key:e,kind:"read",cardinality:n,surface:o??Oa(n),budget:t,...o?{only:o}:{},why:r}}function F(e,n,t,r){return{key:e,kind:"write",cardinality:"single-object",surface:n,budget:t,why:r}}var Aa=[T("issue view","single-object","rest","one issue by number; REST answers it in one request against the idle pool"),T("pr view","single-object","rest","one pull request by number, polled per Worker per iteration"),T("repo view","single-object","rest","one repository's own metadata"),T("run view","single-object","rest","one Actions run; the Actions API has no GraphQL surface either way"),T("release view","single-object","rest","one release by tag"),T("pr diff","single-object","rest","one pull request's diff, served by a REST media type"),T("issue list","multi-node","graphql","a connection of issues; one GraphQL query beats N REST pages"),T("pr list","multi-node","graphql","a connection of pull requests; one GraphQL query beats N REST pages"),T("pr checks","multi-node","graphql","every check context on one commit, which is a connection, not an object"),T("release list","multi-node","rest","Releases have no GraphQL connection gh reads; REST pages them","rest"),T("run list","multi-node","rest","the Actions API has no GraphQL surface, so a listing draws the request pool","rest"),T("label list","multi-node","graphql","a connection of labels inside one repository"),T("issue list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),T("pr list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),T("search issues","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("search prs","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("search repos","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("api graphql","multi-node","graphql","the caller wrote the query; `gh api graphql` is GraphQL by construction"),T("api rest","single-object","rest","any `gh api <path>` that is not `graphql` is a REST request"),F("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),F("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),F("issue close","graphql","graphql","gh closes with the closeIssue mutation"),F("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),F("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),F("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),F("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),F("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),F("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),F("pr close","graphql","graphql","gh closes with a GraphQL mutation"),F("pr edit","graphql","graphql","gh edits with GraphQL mutations"),F("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),F("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),F("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],ly=new Map(Aa.map(e=>[e.key,e]));function La(e){let n=[],t=0;for(;t<e.length&&e[t].startsWith("-");)t+=e[t]==="-R"||e[t]==="--repo"?2:1;for(;t<e.length&&!e[t].startsWith("-")&&n.length<2;)n.push(e[t]),t+=1;return n}function $o(e){let n=La(e);if(n.length===0)return"";if(n[0]==="api")return n[1]==="graphql"?"api graphql":"api rest";let t=n.length===1?n[0]:`${n[0]} ${n[1]}`;return n[1]==="list"&&e.includes("--search")?`${t} (search)`:t}var Mt=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(n){let t=$o(n);super(`unclassified GitHub operation ${JSON.stringify(t||"(empty argv)")}: add an entry to GITHUB_OPERATIONS in packages/github/surface.ts stating its cardinality. Defaulting to GraphQL is what sent every single-object poll to the node-point pool (ADR 0132 decision 4).`),this.operation=t,this.args=[...n]}};function Ta(e){return ly.get($o(e))??null}function $a(e){let n=Ta(e);if(!n)throw new Mt(e);return n}function Io(e){return $a(e).surface}var Na="rate_limit",Ca={rest:"core",graphql:"graphql",search:"search"},he=["rest","graphql","search"];function Ut(e,n){return{version:1,origin:"asked",outcome:"unanswered",source:"GET /rate_limit",asked_at:e,request_count:0,pools:{rest:null,graphql:null,search:null},unreported_pools:[...he],detail:n??"no balance has been asked for yet, so none is known"}}var Co=15e3,on=.15,Bt=[{at_or_below_fraction:0,every_ms:Co,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:on,every_ms:3e4,why:"inside the reserved band: the posture can change between two calls"},{at_or_below_fraction:.5,every_ms:12e4,why:"below half: tightening, because the band is now reachable inside one window"},{at_or_below_fraction:1,every_ms:6e5,why:"above half: rare, because nothing this balance decides is anywhere close"}],No=2;function Ma(e,n){let t=Ia(e),r=Ia(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let a of he){let l=Ca[a],d=r[l],p=cy(a,l,d);o[a]=p,p==null&&s.push(a)}let i=he.length-s.length;return{version:1,origin:"asked",outcome:i>0?"asked":"unanswered",source:"GET /rate_limit",asked_at:n.askedAt,request_count:1,pools:o,unreported_pools:s,detail:i>0?`the token's own answer for ${i} of ${he.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function Mo(e){try{let n=await e.transport();return Ma(n,{askedAt:e.now})}catch(n){let t=n instanceof Error?n.message:String(n);return{...Ut(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function Wo(e){let n=null;for(let t of he){let r=e.pools[t];r!=null&&(n==null||r.fraction<n.fraction)&&(n=r)}return n}function Ht(e,n){let t=Wo(e);if(t==null)return Ft(on).every_ms;let r=Ft(t.fraction);if(t.remaining>0)return r.every_ms;let o=Ba(n.now,t.reset_at);return o==null?r.every_ms:Math.max(Co,Math.min(r.every_ms,o))}function Bo(e,n=on){return Math.ceil(e.limit*n)}function Wa(e,n,t=on){let r=e.pools[n];return r==null?"unknown":r.remaining<=0?"spent":r.remaining<Bo(r,t)?"reserved":"open"}function Fo(e){let n=e.reservedFraction??on,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:Ft(n).every_ms*No,stale:!1,posture:"unknown",reserved_fraction:n,next_poll_ms:Ft(n).every_ms,pools:[],unreported_pools:[...he],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let r=Ht(t,{now:e.now}),o=e.stalenessMs??r*No,s=Ba(t.asked_at,e.now),i=t.outcome==="asked"&&(s==null||s>o),a=he.map(p=>t.pools[p]).filter(p=>p!=null),l=dy(t,n),d=Wo(t);return{version:1,origin:"asked",outcome:t.outcome,asked_at:t.asked_at,age_ms:s,threshold_ms:o,stale:i,posture:l,reserved_fraction:n,next_poll_ms:r,pools:a,unreported_pools:t.unreported_pools,reason:i?`this balance is stale: asked ${s==null?"at an unreadable instant":`${s}ms ago`}, past the ${o}ms window, so the posture below is the last one the token confirmed and not the current one`:ay(l,d,t,n)}}function Uo(e){if(!Go(e))return!1;let n=e;return n.version===1&&n.origin==="asked"&&(n.outcome==="asked"||n.outcome==="unanswered")&&(n.asked_at===null||typeof n.asked_at=="string")&&(n.age_ms===null||typeof n.age_ms=="number")&&typeof n.threshold_ms=="number"&&typeof n.stale=="boolean"&&typeof n.posture=="string"&&typeof n.reserved_fraction=="number"&&typeof n.next_poll_ms=="number"&&Array.isArray(n.pools)&&Array.isArray(n.unreported_pools)&&typeof n.reason=="string"}function ay(e,n,t,r){if(n==null)return t.detail;let o=Bo(n,r);switch(e){case"spent":return`the ${n.pool} pool is spent and resets at ${n.reset_at}: work is not queued, it is refused`;case"reserved":return`the ${n.pool} pool has ${n.remaining} of ${n.limit} left, inside the reserved band of ${o}: convenience reads are refused and the claim, a landing and a closing comment still pass`;default:return`the ${n.pool} pool is the tightest at ${n.remaining} of ${n.limit}, above the reserved band of ${o}`}}function dy(e,n){let t="unknown";for(let r of he){if(e.pools[r]==null)continue;let o=Wa(e,r,n);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function Ft(e){for(let n of Bt)if(e<=n.at_or_below_fraction)return n;return Bt[Bt.length-1]}function cy(e,n,t){if(!Go(t))return null;let r=Wt(t.limit),o=Wt(t.remaining),s=Wt(t.used),i=Wt(t.reset);return r==null||r<=0||o==null?null:{pool:e,resource:n,limit:r,remaining:o,used:s??0,reset_at:i==null?"":new Date(i*1e3).toISOString(),fraction:o/r}}function Ho(e){let n=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let r=await t(`${n}/${Na}`,{method:"GET",headers:{authorization:`bearer ${e.token}`,accept:"application/vnd.github+json"}});if(!r.ok)throw new Error(`the balance ask was refused with HTTP ${r.status}`);return await r.json()}}function Ba(e,n){let t=Date.parse(e),r=Date.parse(n);return!Number.isFinite(t)||!Number.isFinite(r)?null:Math.max(0,r-t)}function Wt(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function Ia(e){return Go(e)?e:{}}function Go(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Va(e){return{generated_at:e.now,hour:Fa("hour",36e5,e),day:Fa("day",864e5,e)}}function Gt(e,n,t){let r=Cn(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(a=>{let l=Cn(n(a));return l==null?!1:r==null||r-l<=o});return i.length<=s?i:i.slice(i.length-s)}function Fa(e,n,t){let r=Cn(t.now),o=r==null?null:r-n,s=e==="hour"?"1h":"24h",i=t.observations.map(u=>({observation:u,at:Cn(u.observed_at)})).filter(u=>u.at!=null&&Ga(u.at,o,r)).sort((u,f)=>u.at-f.at),a=t.outcomes.map(u=>Cn(u.ts)).filter(u=>u!=null&&Ga(u,o,r)),l=Ua(i,u=>u.tokens,"tokens",s),d=Ua(i,u=>u.tools,"tools",s),p=[];return i.length===0?p.push("worker-vitals"):(l.samples===0&&p.push("worker-vitals.tokens"),d.samples===0&&p.push("worker-vitals.tools")),a.length===0&&p.push("worker-outcomes"),{window:e,window_ms:n,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:l,tools_per_min:d,issues_per_hour:uy(a.length,n,s),runner_share:Ha("runner",i,u=>u.runner,s),model_share:Ha("model",i,u=>u.model,s),unavailable:p}}function Ua(e,n,t,r){let o=new Map,s=0;for(let d of e){let p=n(d.observation);if(p==null||!Number.isFinite(p))continue;s+=1;let u=o.get(d.observation.worker_id)??[];u.push({at:d.at,count:p}),o.set(d.observation.worker_id,u)}if(s===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${r}`,samples:0};let i=0,a=null,l=null;for(let d of o.values()){if(d.length<2)continue;for(let f=1;f<d.length;f++){let m=d[f-1],h=d[f];m==null||h==null||(i+=Math.max(0,h.count-m.count))}let p=d[0],u=d[d.length-1];p!=null&&(a=a==null?p.at:Math.min(a,p.at)),u!=null&&(l=l==null?u.at:Math.max(l,u.at))}return a==null||l==null||l<=a?{value:null,absent_reason:`the last ${r} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:s}:{value:i/((l-a)/6e4),absent_reason:null,samples:s}}function uy(e,n,t){return e===0?{value:null,absent_reason:`no Worker outcome was recorded in the last ${t}`,samples:0}:{value:e/(n/36e5),absent_reason:null,samples:e}}function Ha(e,n,t,r){let o=new Map;for(let d of n){let p=t(d.observation);p!=null?o.set(d.observation.worker_id,p):o.has(d.observation.worker_id)||o.set(d.observation.worker_id,null)}let s=new Map,i=0,a=0;for(let d of o.values()){if(d==null){a+=1;continue}i+=1,s.set(d,(s.get(d)??0)+1)}let l=[...s.entries()].map(([d,p])=>({key:d,worker_count:p,share:p/i})).sort((d,p)=>p.worker_count-d.worker_count||d.key.localeCompare(p.key));return{dimension:e,attributed_workers:i,unattributed_workers:a,shares:l,absent_reason:l.length>0?null:o.size===0?`no Worker was observed in the last ${r}`:`no Worker published a ${e} in the last ${r}`}}function Ga(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function Cn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function qa(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.generated_at=="string"&&Ka(n.hour)&&Ka(n.day)}function Ka(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.window=="string"&&typeof n.window_ms=="number"&&Ko(n.tokens_per_min)&&Ko(n.tools_per_min)&&Ko(n.issues_per_hour)&&Array.isArray(n.unavailable)}function Ko(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return(n.value===null||typeof n.value=="number")&&(n.absent_reason===null||typeof n.absent_reason=="string")&&Number.isInteger(n.samples)}import{execFileSync as py}from"node:child_process";import{existsSync as fy,readFileSync as Kt,readdirSync as my}from"node:fs";import{dirname as hy,join as Ie}from"node:path";function Mn(e){let n=Nn(e),t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let s=rn(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function Ja(e){let n=[],t=[];for(let r of e.workers){let o=Mn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(Nn(r).memory_max??Nn(r).memory_high)==null?"this Worker declared no memory budget and the host derived no ceiling for it, so the sampler has none to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let s=e.rss[r.worker_id];if(typeof s!="number"||!Number.isFinite(s)){t.push({worker_id:r.worker_id,reason:"the host produced no RSS reading for this Worker on this tick, and an unmeasured Worker is never killed on suspicion"});continue}if(!(s<=o.bytes)){if(e.sources?.[r.worker_id]==="cgroup"&&o.name==="MemoryMax"){t.push({worker_id:r.worker_id,reason:`this Worker's ${o.name} of ${o.declared} is held by the kernel on its own cgroup, and the reading is memory.current \u2014 which counts reclaimable page cache the kernel drops before it kills anything, so the daemon does not duplicate an enforcement that can tell cache from anonymous memory`});continue}n.push(yy(r,o,s))}}return{terminations:n,unenforceable:t}}function yy(e,n,t){let r=`Worker ${JSON.stringify(e.worker_id)} of project ${JSON.stringify(e.project_label)}`;return{version:1,worker_id:e.worker_id,project_label:e.project_label,outcome:"terminated-over-memory-budget",classification:"budget-exceeded",stall:!1,budget_name:n.name,budget_declared:n.declared,budget_bytes:n.bytes,observed_rss_bytes:t,workspace_path:e.workspace_path,reason:`redskilled terminated ${r}: its tree RSS of ${t} bytes exceeded its ${n.name} budget of ${n.declared} (${n.bytes} bytes). This is a budget termination, not a stall, and the work in ${JSON.stringify(e.workspace_path)} is handed forward.`}}var gy=4096;function Qa(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return r;let o={},s={},i={},a=Ry(e,t,n);for(let[u,f]of a){let m=wy(f);m!=null&&(o[u]=m.memoryBytes,m.cpuSeconds!=null&&(s[u]=m.cpuSeconds),i[u]="cgroup")}let l=e.filter(u=>i[u.worker_id]==null);if(l.length===0)return{rss:o,cpu_seconds:s,sources:i};let d=vy(t,n);if(d.size===0)return{rss:o,cpu_seconds:s,sources:i};let p=new Map;for(let u of d.values()){let f=p.get(u.ppid);f?f.push(u.pid):p.set(u.ppid,[u.pid])}for(let u of l){if(!d.has(u.pid))continue;let f=0,m=0,h=[u.pid],b=new Set;for(;h.length>0;){let k=h.pop();if(b.has(k))continue;b.add(k);let _=d.get(k);if(_){f+=_.rssBytes,m+=_.cpuSeconds;for(let j of p.get(k)??[])h.push(j)}}o[u.worker_id]=f,s[u.worker_id]=m,i[u.worker_id]="process-tree"}return{rss:o,cpu_seconds:s,sources:i}}var ky="/sys/fs/cgroup";function Ry(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let s=t.cgroupRoot??ky,i=e.filter(l=>l.unit!=null&&l.unit!=="");if(i.length===0)return r;let a=by(s,t);for(let l of i)for(let d of a){let p=Ie(d,l.unit);if(fy(Ie(p,"memory.current"))){r.set(l.worker_id,p);break}}return r}function by(e,n){let t=n.selfCgroupPath??_y(),r=[],o=a=>{r.includes(a)||r.push(a)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(Ie(e,s));let a=hy(s);if(a===s)break;s=a}o(e);let i=n.uid??process.getuid?.();return i!=null&&o(Ie(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),r}function _y(){try{for(let e of Kt("/proc/self/cgroup","utf8").split(`
|
|
65
|
+
`))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function wy(e){let n;try{n=Kt(Ie(e,"memory.current"),"utf8")}catch{return null}let t=Number(n.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:xy(e)}}function xy(e){let n;try{n=Kt(Ie(e,"cpu.stat"),"utf8")}catch{return null}return Sy(n)}function Sy(e){for(let n of e.split(`
|
|
66
|
+
`)){let[t,r]=n.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(r);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function vy(e,n){return n.procRoot!=null||e==="linux"?Ay(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?Dy(Ey(n.psTable)):new Map}function Ey(e){try{return(e??Py)()}catch{return""}}function Py(){return py("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var jy=1024;function Dy(e){let n=new Map;for(let t of e.split(`
|
|
67
|
+
`)){let r=t.trim().split(/\s+/);if(r.length!==4)continue;let[o,s,i]=r.slice(0,3).map(Number);if(![o,s,i].every(l=>l!=null&&Number.isSafeInteger(l)&&l>=0))continue;let a=Oy(r[3]);a!=null&&n.set(o,{pid:o,ppid:s,rssBytes:i*jy,cpuSeconds:a})}return n}function Oy(e){let n=e.indexOf("-"),t=n<0?0:Number(e.slice(0,n));if(!Number.isFinite(t)||t<0)return null;let r=e.slice(n+1).split(":"),o=t*86400,s=1;for(let i=r.length-1;i>=0;i--){let a=Number(r[i]);if(!Number.isFinite(a)||a<0||r[i]==="")return null;o+=a*s,s*=60}return o}function Ay(e){let n=new Map,t;try{t=my(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=Kt(Ie(e,r,"stat"),"utf8")}catch{continue}let s=Ty(o);s&&n.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*gy,cpuSeconds:s.cpuTicks/Ly})}return n}var Ly=100;function Ty(e){let n=e.lastIndexOf(")");if(n<0)return null;let t=Number(e.slice(0,e.indexOf(" "))),r=e.slice(n+1).trim().split(/\s+/),o=Number(r[1]),s=Number(r[11]),i=Number(r[12]),a=Number(r[21]);return!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||!Number.isFinite(a)||!Number.isFinite(s)||!Number.isFinite(i)?null:{pid:t,ppid:o,rssPages:Math.max(0,a),cpuTicks:Math.max(0,s)+Math.max(0,i)}}var $y=["api","graphql"],Iy=Io($y);function Ny(e,n="https://api.github.com"){return e==="graphql"?`${n}/graphql`:n}var za=100,Jo=6e4,Cy=2*Jo,My=7*24*60*60*1e3,Vo=class extends Error{constructor(t,r,o){super(`redskilled polls every repository with one host token ${JSON.stringify(o)}, and project ${JSON.stringify(t)} declares its own credential ${JSON.stringify(r)}: a project needing its own credential invalidates the host-scoped poller (ADR 0130 Amendment 1) rather than bending it, so the poller returns to the projects instead of reaching this repository under the wrong identity`);this.projectLabel=t;this.tokenRef=r;this.hostTokenRef=o;this.name="RedskilledSplitCredentialError"}};function Qo(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new Vo(t.project_label,t.token_ref,n)}function Wy(e,n={now:new Date(0).toISOString()}){Uy(e);let t=n.closedWindowMs??My,r=Date.parse(n.now);if(!Number.isFinite(r))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(n.now)}`);let o=new Date(r-Math.max(0,t)).toISOString(),s=e.map((l,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:l}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { cost remaining resetAt }",...s.flatMap(({alias:l,search_alias:d,project:p})=>{let u=JSON.stringify(p.owner),f=JSON.stringify(p.name),m=JSON.stringify(`repo:${p.owner}/${p.name} is:closed closed:>=${o}`);return[` ${l}: repository(owner: ${u}, name: ${f}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${d}: search(query: ${m}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
|
|
68
|
+
`),aliases:s,closed_since:o}}function By(e,n,t){let r=sn(n),o=sn(r.data),s=Array.isArray(r.errors)?r.errors.map(sn):[],i=Hy(o.rateLimit,s),a=e.aliases.map(({alias:l,search_alias:d,project:p})=>{let u=p.owner+"/"+p.name,f=o[l],m=s.find(h=>Ya(h.path,l)||Ya(h.path,d));if(Vt(f)){let h=Xa(f.open_pull_requests),b=Xa(f.open_issues),k=Gy(o[d]);if(h!=null&&b!=null&&k!=null)return{project_label:p.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:h,open_issues:b,recently_closed:k},detail:`counted ${u} for project ${JSON.stringify(p.project_label)}`}}return i.exhausted||rd(m)?{project_label:p.project_label,repository:u,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${u} answered, so this project has no counts rather than zero counts${i.reset_at==null?"":`; the quota resets at ${i.reset_at}`}`}:{project_label:p.project_label,repository:u,outcome:"unreachable",counts:null,detail:`${u} is not reachable with the host token: ${qo(m?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:a.length,rate_limit:i,projects:a}}function Fy(e){return{version:1,fetched_at:e,request_count:0,project_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1,point_cost:null},projects:[]}}async function Za(e){if(e.projects.length===0)return Fy(e.now);Qo(e.projects,e.hostTokenRef);let n=Wy(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return By(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,point_cost:null},projects:e.projects.map(s=>({project_label:s.project_label,repository:`${s.owner}/${s.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${s.owner}/${s.name} answered: ${r}`}))}}}function ed(e){let n=e.stalenessMs??Cy,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,point_cost:null},projects:[],reason:"the daemon polls no repository, so there are no counts to age"};let r=Date.parse(e.now),o=Date.parse(t.fetched_at),s=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,i=s==null||s>n;return{version:1,fetched_at:t.fetched_at,age_ms:s,threshold_ms:n,stale:t.projects.length>0&&i,request_count:t.request_count,rate_limit:t.rate_limit,projects:t.projects.map(a=>({...a,fetched_at:t.fetched_at,age_ms:s,stale:i})),reason:t.projects.length===0?"the daemon polls no repository, so there are no counts to age":s==null?"these counts carry no readable instant, so they cannot be presented as current":i?`these counts are ${s}ms old, past the ${n}ms window`:`fetched ${s}ms ago, within the ${n}ms window`}}function nd(e){if(!Vt(e))return!1;let n=e;return n.version===1&&(n.fetched_at===null||typeof n.fetched_at=="string")&&(n.age_ms===null||typeof n.age_ms=="number")&&typeof n.threshold_ms=="number"&&typeof n.stale=="boolean"&&Number.isInteger(n.request_count)&&Vt(n.rate_limit)&&Array.isArray(n.projects)&&typeof n.reason=="string"}function td(e){let n=e.endpoint??Ny(Iy),t=e.fetchImpl??fetch;return async r=>{let o=await t(n,{method:"POST",headers:{authorization:`bearer ${e.token}`,"content-type":"application/json",accept:"application/vnd.github+json"},body:JSON.stringify({query:r})});if(!o.ok){let s=o.headers.get("x-ratelimit-remaining"),i=o.status===429||s==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(i?": the host token's rate limit is spent":""))}return await o.json()}}function Uy(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>za)throw new Error(`redskilled activity fetch spans at most ${za} 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 Hy(e,n){let t=sn(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(rd),i=typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:null;return{remaining:r,reset_at:o,exhausted:s||r===0,point_cost:i}}function rd(e){if(e==null)return!1;let n=qo(e.type),t=qo(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function Ya(e,n){return Array.isArray(e)&&e.includes(n)}function Xa(e){let n=sn(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function Gy(e){let n=sn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function sn(e){return Vt(e)?e:{}}function Vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qo(e){return typeof e=="string"?e:""}var Ky=3e4,Vy=4,qy=["logs","vitals","display"];function od(e,n){if(n===void 0)return e;let t=qy.filter(o=>n[o]!==!0);if(t.length===0)return e;let r=o=>n[o]===!0;return{...e,workers:e.workers.map(o=>({...o,...r("vitals")?{}:{vitals:Jy,budget:{...o.budget,used_bytes:null,used_fraction:null}},...r("logs")?{}:{log:Qy},...r("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var Jy={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},Qy={last_line:null,published_at:null,source:null};function sd(e){let n=e.stalenessMs??Ky,t=Wn(e.now),r=e.sampledAt==null?null:Wn(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),s=o!=null&&o<=n,i=new Set(e.reattachedWorkerIds??[]),a=e.hostState.workers.map(f=>Xy(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:i.has(f.worker_id)?"reattached":"running"})),l=a.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=a.length-l.length,p=a.reduce((f,m)=>f+(m.vitals.rss_bytes??0),0),u=Tt(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:tg({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:a.length,measuredCount:d,unmeasured:l}),host:{worker_count:a.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:u,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:p,measured_worker_count:d,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:u.memory_bytes/e.ceiling.memory_bytes},projects:ng(a),known_projects:eg(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,m)=>f.localeCompare(m)),workers:a,github_balance:Fo({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:ed({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:zy(e.deaths,e.recentDeathLimit??Vy)},engine:Yy(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function zy(e,n){let t=[...e].sort((o,s)=>(Wn(s.ts)??0)-(Wn(o.ts)??0)),r=t.slice(0,Math.max(0,Math.floor(n))).map(o=>({kind:o.kind,id:o.id,pid:o.pid,ts:o.ts,last_seen:o.last_seen,last_phase:o.last_phase,sender_class:o.sender_class,confidence:o.confidence,signal:o.signal,evidence:o.evidence[0]??null}));return{count:t.length,recent:r,latest:r[0]??null,reaped_at:r[0]?.ts??null}}function Yy(e){let n=e.upgrade,t=n?.running_version??e.daemon_version,r=n?.published_version??null,o=n?.newest_published_version??null,s=(n?.newer_published??0)>0,i=(n?.major_held??0)>0;return{running_version:t,published_version:r,newer_published:s,major_held:i,current:r==null&&o==null?null:!s&&!i}}function Xy(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=Mn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=Wn(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms:n.nowMs==null||i==null?null:Math.max(0,n.nowMs-i),state:n.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:r,sampled_at:r==null?null:n.sampledAt,age_ms:r==null?null:n.ageMs,fresh:r!=null&&n.sampleFresh,rss_source:r==null?null:e.rss_source??null},budget:{name:o?.name??null,declared:o?.declared??s,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:Zy(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function Zy(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 eg(e){let n=new Set;for(let t of e.registrations??[])n.add(t.project_label);for(let t of e.projects)n.add(t.project_label);return[...n].sort((t,r)=>t.localeCompare(r))}function ng(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 tg(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 Wn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function zo(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.daemon,r=n.staleness,o=n.host;return n.version===1&&typeof n.generated_at=="string"&&t!=null&&typeof t=="object"&&Number.isInteger(t.pid)&&typeof t.daemon_version=="string"&&typeof t.protocol_version=="number"&&r!=null&&typeof r=="object"&&typeof r.stale=="boolean"&&typeof r.threshold_ms=="number"&&Array.isArray(r.unmeasured_workers)&&o!=null&&typeof o=="object"&&Number.isInteger(o.worker_count)&&Number.isInteger(o.project_count)&&typeof o.observed_rss_bytes=="number"&&Array.isArray(n.projects)&&Array.isArray(n.workers)&&(n.known_projects===void 0||Array.isArray(n.known_projects)&&n.known_projects.every(s=>typeof s=="string"))&&(n.registered_projects===void 0||Array.isArray(n.registered_projects)&&n.registered_projects.every(s=>typeof s=="string"))&&(n.repository_activity===void 0||nd(n.repository_activity))&&(n.github_balance===void 0||Uo(n.github_balance))&&(n.deaths===void 0||rg(n.deaths))&&(n.engine===void 0||og(n.engine))&&(n.metrics===void 0||qa(n.metrics))}function rg(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return Number.isInteger(n.count)&&Array.isArray(n.recent)}function og(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")}var id={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null};function Ne(e){return[...e].length}function G(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 Yo(e,n){return e+" ".repeat(Math.max(0,n-Ne(e)))}function U(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}function qt(e){if(!Number.isFinite(e)||e<=0)return"0";let n=(t,r)=>{let o=(Math.round(t*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${r}`};return e>=1e9?n(e/1e9,"B"):e>=1e6?n(e/1e6,"M"):e>=1e3?n(e/1e3,"k"):String(Math.round(e))}function Bn(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return qt(e);if(e<=0)return"0";let n=(Math.round(e*10)/10).toFixed(1);return n.endsWith(".0")?n.slice(0,-2):n}function Jt(e){if(e==null||!Number.isFinite(e)||e<0)return"\u2014";let n=Math.floor(e/1e3);if(n<60)return`${n}s`;let t=Math.floor(n/60);if(t<60)return`${t}m${n%60}s`;let r=Math.floor(t/60);return r<24?`${r}h${t%60}m`:`${Math.floor(r/24)}d${r%24}h`}function Xo(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}var Zo="!unregistered",Fn="\u21E1",Ce="\u2020",ln="\u25D0",an="\u25EF",es="\u21B3",ns="redskilled unreachable \u2014 Worker state unknown";function dn(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Qt(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function Un(e,n){return n==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(n)?e.registered_projects==null||e.registered_projects.includes(n)?"matched":"name-only":"unregistered"}function ts(e){let n=[];return e.workers.length>0&&e.workers.length<=e.maxWorkers&&n.push("workers"),e.mode==="global"&&e.projects.length>0&&e.projects.length<=e.maxProjects&&n.push("projects"),n.push("host"),n}var D={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Me(e,n=D){let t=Un(e,n.project),r=dn(e,n),o=Qt(e,n),s=ig(e,n,r,t),i=ts({mode:n.mode,maxWorkers:n.maxWorkers,maxProjects:n.maxProjects,workers:r,projects:o}),a={detail:"host",line:s};for(let u of i){let f=hg(s,sg(u,n,r,o),n.separator);if(a={detail:u,line:f},Ne(f)<=n.maxWidth)break}let l=G(a.line,n.maxWidth),d=n.verbose&&a.detail==="workers"?fg(r,n):[],p=r.length>0?"workers":"host";return{version:1,line:l,lines:[l,...d],verbose:n.verbose,mode:n.mode,project:n.project,project_match:t,detail:a.detail,degraded:a.detail!==p||l!==a.line,stale:e.staleness.stale,generated_at:e.generated_at}}function os(e){let n=e.options??D,t=G(ns,n.maxWidth);return{version:1,line:t,lines:[t],verbose:n.verbose,mode:n.mode,project:n.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}function sg(e,n,t,r){return e==="workers"?t.map(o=>pg(o,n)):e==="projects"?r.map(mg):[]}function ig(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(rs(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(rs(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(rs(e,n)),o.push(Zo)):o.push(cg(n.project,r)),o.push(lg(e));let s=ag(e);s!=null&&o.push(s);let i=dg(e);return i!=null&&o.push(i),e.staleness.stale&&o.push(ug(e)),o.join(" ")}function lg(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${Fn}`}function ag(e){let n=e.github_balance;return n==null?null:n.posture==="spent"?`${an} quota spent`:n.posture==="reserved"?`${ln} quota band`:null}function dg(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Ce}${n.count} ${n.latest.sender_class}`}function cg(e,n){return n==="unregistered"?`project unknown \u2014 ${e} is not registered on this host`:"project unknown \u2014 this directory resolved to no project"}function rs(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,s)=>o+s.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${U(t)}/${U(r)}`:U(t)}function ug(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function pg(e,n){let t=zt(e,n.mode),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?U(r):`${U(r)}/${U(e.budget.bytes)}`;return`${t} ${o}`}function fg(e,n){let t=[];for(let r of e){let o=Xo(r.log.last_line);o!=null&&t.push(G(` ${es} ${zt(r,n.mode)}: ${o}`,n.maxWidth))}return t}function zt(e,n){return n==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function mg(e){return`${e.project_label} ${e.worker_count}w ${U(e.observed_rss_bytes)}`}function hg(e,n,t){return[e,...n].join(t)}var Hn=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],xe={mode:"local",project:null,maxWidth:200,maxRows:16},yg=" ",ld="\u2588",gg="\u25B6",kg="\u2717",Rg="\u2591";function Yt(e,n=xe){let t=Un(e,n.project),r=dn(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(u=>bg(u,n)),i=Pg(s),a=o.map((u,f)=>({worker_id:u.worker_id,project_label:u.project_label,mine:n.project!=null&&u.project_label===n.project,cells:s[f],line:G(jg(s[f],i),n.maxWidth)})),l=_g(e,n,r,t),d=r.length-o.length,p=[l.line,...a.map(u=>u.line)];return d>0&&p.push(G(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),p.push(...xg(e,n)),p.push(...wg(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Hn,header:l,rows:a,lines:p,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function bg(e,n){let t=e.display??id,r=[t.runner,t.model,t.effort].filter(o=>!!o).join(" ");return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:r===""?"":`run=${r}`,org:t.origin==null?"":`org=${t.origin}`,iss:t.issue==null?"":`iss=${t.issue}`,bar:ad(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:Jt(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:Eg(t.added,t.removed),tks:t.tokens==null?"":`tks=${qt(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function ad(e){let n=e.phase_total,t=e.phase_index;if(n==null||n<=0||t==null||t<0)return"";let r=Math.min(Math.floor(t),Math.floor(n));if(r>=n)return ld.repeat(Math.floor(n));let o=e.failed?kg:gg;return`${ld.repeat(r)}${o}${Rg.repeat(Math.floor(n)-r-1)}`}function _g(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(_=>_.project_label===n.project),s={open_pull_requests:o?.counts?.open_pull_requests??null,recently_closed:o?.counts?.recently_closed??null,open_issues:o?.counts?.open_issues??null,stale:o?.stale===!0},i={memory_used_fraction:e.host.ceiling_used_fraction,memory_used_bytes:e.host.consumption.memory_bytes,memory_ceiling_bytes:e.host.ceiling.memory_bytes,worker_count:e.host.worker_count,worker_ceiling:e.host.ceiling.worker_count},a=vg(t),l=o?.repository??n.project,d=e.engine??null,p=d?.running_version??e.daemon.daemon_version,u=e.deaths??null,f=e.metrics??null,m=[`\xBB ${l??"host"} v${p}${d!=null&&d.current===!1?Fn:""}`];r==="unregistered"&&m.push("!unregistered"),r==="name-only"&&m.push("!lapsed"),a!=null&&m.push(a),m.push(`wrk=${t.length}/${e.host.worker_count}`),m.push(i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`),m.push(Sg(i)),s.open_pull_requests!=null&&m.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&m.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&m.push(`iss=${s.open_issues}`),s.stale&&m.push("!counts stale");let h=f==null?null:dd(f.hour);if(h!=null&&m.push(h),u!=null&&u.count>0&&u.latest!=null&&m.push(`${Ce}${u.count} ${u.latest.sender_class}`),e.staleness.stale){let _=e.staleness.age_ms;m.push(_==null?"!unmeasured":`!stale ${Math.round(_/1e3)}s`)}let b=m.join(" \xB7 "),k=h!=null&&Ne(b)>n.maxWidth?m.filter(_=>_!==h).join(" \xB7 "):b;return{repo:l,project:n.project,project_match:r,version:p,engine:d,deaths:u,metrics:f,model:a,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:G(k,n.maxWidth)}}function dd(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${Bn(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${Bn(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${Bn(e.issues_per_hour.value)}`);let t=e.runner_share.shares[0];return t!=null&&n.push(`${t.key}=${Math.round(t.share*100)}%`),n.length===0?null:n.join(" ")}function wg(e,n){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let r=t.posture==="spent"?an:ln,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[G(`${r} github budget ${t.posture}${o} \u2014 ${t.reason}`,n.maxWidth)]}function xg(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(s=>G(`${Ce} ${s.kind} ${s.id} pid=${s.pid} ${s.sender_class}/${s.confidence} phase=${s.last_phase}`+(s.signal==null?"":` signal=${s.signal}`)+(s.evidence==null?"":` \u2014 ${s.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(G(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function Sg(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${U(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${U(e.memory_used_bytes)}/${U(e.memory_ceiling_bytes)}${n}`}function vg(e){for(let n of e){let t=n.display;if(t==null)continue;let r=[t.runner,t.model,t.effort].filter(o=>!!o);if(r.length>0)return r.join("\xB7")}return null}function Eg(e,n){if(e==null&&n==null)return"";let t=[];return e!=null&&e>0&&t.push(`+${e}`),n!=null&&n>0&&t.push(`-${n}`),`loc=${t.length>0?t.join(" "):"0"}`}function Pg(e){let n=Object.fromEntries(Hn.map(t=>[t,0]));for(let t of e)for(let r of Hn)n[r]=Math.max(n[r],Ne(t[r]));return n}function jg(e,n){return Hn.filter(r=>n[r]>0).map(r=>Yo(e[r],n[r])).join(yg).replace(/\s+$/,"")}var Xt=1;async function Gn(e,n){return await Et(e,n,"redskilled daemon")}function ud(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:Xt,daemon_version:e.daemonVersion,machine_id_hash:e.machineIdHash,session_key_hash:e.sessionKeyHash,pid:e.pid,started_at:e.startedAt,...e.scope==null?{}:{scope:e.scope},workers:n,projects:[...t.entries()].map(([r,o])=>({project_label:r,worker_count:o})).sort((r,o)=>r.project_label.localeCompare(o.project_label)),registrations:Lg(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:Jl(n,{hostCeilingBytes:e.hostCeilingBytes??null}),upgrade:Tg(e)}}function Lg(e){let n=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(n),r=e.queue??null,o=new Map(r==null?[]:r.projects.map(s=>[s.project_label,s]));return[...e.registrations??[]].map(s=>{let i=o.get(s.project_label);return{...s,...t?{renewal:Ea(s,n)}:{},...r==null||i==null?{}:{last_poll:{at:r.fetched_at,outcome:i.outcome,depth:i.depth,request_count:r.request_count,detail:i.detail}}}}).sort((s,i)=>s.project_label.localeCompare(i.project_label))}function Tg(e){let n=e.daemonVersion,t=e.published?.version??null,r=e.published?.majorHold??null;return{running_version:n,published_version:t,published_unknown:+(t===null),newer_published:+(e.published?.newer===!0),replacement:e.published?.replacement??"none",checked_at:e.published?.checkedAt??null,checks:e.published?.checks??0,hold_reason:e.published?.holdReason??null,newest_published_version:e.published?.newest??null,major_held:+(r!==null),major_hold:r}}function pd(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)&&Ql(n.budget_accounting)&&(n.scope===void 0||_a(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(To))&&(n.upgrade===void 0||$g(n.upgrade))}function $g(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")&&typeof n.published_unknown=="number"&&typeof n.newer_published=="number"&&(n.replacement==="none"||n.replacement==="pending"||n.replacement==="in-progress")&&(n.checked_at===null||typeof n.checked_at=="string")&&(n.newest_published_version===void 0||n.newest_published_version===null||typeof n.newest_published_version=="string")&&(n.major_held===void 0||typeof n.major_held=="number")&&(n.checks===void 0||typeof n.checks=="number")&&(n.hold_reason===void 0||n.hold_reason===null||typeof n.hold_reason=="string")&&(n.major_hold===void 0||n.major_hold===null||Ig(n.major_hold))}function Ig(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.version=="string"&&Number.isInteger(n.running_major)&&Number.isInteger(n.held_major)&&typeof n.reason=="string"&&typeof n.action=="string"&&n.action.trim()!==""}import{spawnSync as nr}from"node:child_process";import{existsSync as ds}from"node:fs";import{delimiter as Gg,join as wd}from"node:path";import{join as fd}from"node:path";import{existsSync as Ng}from"node:fs";import{createRequire as Cg}from"node:module";var md="redskilled-job-object.node",We=100;function cn(e){return{available:!1,reason:e}}function Mg(e,n,t){return[fd(t,"prebuilds",`${e}-${n}`,md),fd(t,"native","build","Release",md)]}function hd(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return cn(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??Bg(),o=e.exists??Ng,s=Mg(n,t,r),i=s.find(d=>o(d));if(i==null)return cn(`no Job Object addon was found for ${n}-${t} (looked in ${s.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let a=e.requireFn??Cg(import.meta.url),l;try{l=a(i)}catch(d){return cn(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return Wg(l)?{available:!0,binding:l}:cn(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function Wg(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Bg(){return new URL("..",import.meta.url).pathname}function yd(e){let n=e??{},t=[],r=Fg(n);r==null&&(n.memory_max??n.memory_high)!=null&&t.push("the declared memory budget could not be reduced to bytes, so the job carries no memory ceiling");let o;return n.cpu_weight!=null&&(n.cpu_weight<We?o=Math.max(1,Math.min(100,Math.round(n.cpu_weight))):t.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${We}, and Windows CPU rate control is an absolute cap rather than a share, so no rate limit is set`)),{...r!=null?{memory_limit_bytes:r.bytes,memory_budget_name:r.name,memory_budget_declared:r.declared}:{},...o!=null?{cpu_rate_percent:o}:{},kill_on_close:!0,...t.length>0?{note:t.join("; ")}:{}}}function Fg(e){return Mn({budget:e})}var Zt=5,gd=19;function ss(e){return{available:!1,reason:e}}var Ug="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 Rd(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=Zt;else if(t.cpu_weight<We){let a=Math.round(gd*(We-t.cpu_weight)/We);o=Math.min(gd,Math.max(Zt,a))}else o=Zt,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${We}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Zt}`);let s=kd(t.max_processes);s==null&&t.max_processes!=null&&r.push(`max_processes=${t.max_processes} is not a positive whole number, so no ulimit -u is set`);let i=kd(t.cpu_seconds);return i==null&&t.cpu_seconds!=null&&r.push(`cpu_seconds=${t.cpu_seconds} is not a positive whole number, so no ulimit -t is set`),{...o!=null?{nice:o}:{},...s!=null?{max_processes:s}:{},...i!=null?{cpu_seconds:i}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:Ug,...r.length>0?{note:r.join("; ")}:{}}}function bd(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 ${Hg(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
|
|
69
|
+
`),e.command,...e.args]}function _d(e){let n=[];return e.nice!=null?n.push(`the Worker runs at nice ${e.nice} so it yields to interactive work`):n.push("no priority control was applied"),e.max_processes!=null&&n.push(`its processes are capped at ${e.max_processes}`),e.cpu_seconds!=null&&n.push(`its CPU time is capped at ${e.cpu_seconds} seconds`),`macOS placement applied POSIX limits: ${n.join(", ")}. macOS has no resource-group equivalent, so the Worker is charged to the daemon's own resource group, and ${e.memory_ceiling_reason}`+(e.note!=null?` (${e.note})`:"")}function is(e){let n=e??{},t=[n.max_processes!=null?"max_processes":null,n.cpu_seconds!=null?"cpu_seconds":null].filter(r=>r!=null);return t.length===0?null:`${t.join(" and ")} ${t.length===1?"is a POSIX rlimit":"are POSIX rlimits"} honoured only by the macOS placement backend, so this placement carries no equivalent`}function kd(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function Hg(e){return`'${e.replace(/'/g,"'\\''")}'`}var xd="REDSKILLED_PLACEMENT",er="red-worker",ls="/bin/sh";function Sd(e=process.env,n=process.platform){let t=ss(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:hd({platform:n}),posix:t};let r=cn(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);if(n==="darwin")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:Kg(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&ds(wd(o,"systemd","private"));return{platform:n,systemdRun:jd("systemd-run",e),userSession:s,jobObjects:r,posix:t}}function Kg(e){return ds(ls)?{available:!0,shell:ls,nice:jd("nice",e)}:ss(`no POSIX shell was found at ${ls}, so there is nothing to apply rlimits or priority in`)}function vd(e=process.env){let n=(e[xd]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Vg(e,n,t=er){return Ed(e,n,t).replace(/\.service$/,"")}function Ed(e,n,t=er){return`${as(t,"red-worker",24)}-${as(e,"project",32)}-${as(n,"worker",32)}.service`}function Pd(e){let n=[...e.args??[]],t={...e.budget??{},...e.budget?.memory_max==null&&e.memoryCeiling?.memory_max!=null?{memory_max:e.memoryCeiling.memory_max}:{}},r=t.memory_max??t.memory_high??null,o=t.memory_high!=null||t.memory_max!=null||t.cpu_weight!=null,s=e.target??{isolation:"transient-unit"},i=u=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:u,budget:t,...r!=null?{memoryCeiling:r}:{},environment:On({scope:null,memory_ceiling:r,scope_degradation:u}),...o?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(s.isolation==="inherit")return i("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return i(`worker isolation disabled by ${xd}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return Jg(e,n,t,r,o,i);if(e.probes.platform==="darwin")return qg(e,n,t,r,i);if(e.probes.platform!=="linux")return i(`transient-unit placement is the Linux backend (platform=${e.probes.platform}): the Worker is charged to the daemon's own resource group`);if(!e.probes.systemdRun)return i("transient-unit placement unavailable: systemd-run is not on PATH; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");if(!e.probes.userSession)return i("transient-unit placement unavailable: no systemd --user session; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");let a=Ed(e.projectLabel,e.workerId,s.unit_prefix),l=["--user","--collect","--quiet","--wait",`--unit=${a}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&l.push("--pipe"),t.memory_high!=null&&l.push(`--property=MemoryHigh=${t.memory_high}`),t.memory_max!=null&&l.push(`--property=MemoryMax=${t.memory_max}`),t.cpu_weight!=null&&l.push(`--property=CPUWeight=${t.cpu_weight}`);let d=On({scope:a,memory_ceiling:r,scope_degradation:null});for(let[u,f]of Object.entries({...e.env??{},...d}))l.push(`--setenv=${u}=${f}`);let p=is(e.budget);return{isolated:!0,backend:"transient-unit",unit:a,command:e.probes.systemdRun,args:[...l,"--",e.command,...n],budget:t,...r!=null?{memoryCeiling:r}:{},environment:d,...p!=null?{budgetWarning:p}:{}}}function qg(e,n,t,r,o){let s=e.probes.posix;if(!s.available)return o(`POSIX limit placement unavailable: ${s.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let i=Rd(t,{canRenice:s.nice!=null}),a=t.memory_high!=null||t.memory_max!=null,l=_d(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:bd({limits:i,nice:s.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:i,warning:l,budget:t,...r!=null?{memoryCeiling:r}:{},environment:On({scope:null,memory_ceiling:r,scope_degradation:l}),...a?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+i.memory_ceiling_reason}:{}}}function Jg(e,n,t,r,o,s){let i=e.probes.jobObjects;if(!i.available)return s(`Job Object placement unavailable: ${i.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let a=yd(t),l=Vg(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...n],cwd:e.workspacePath,job:{name:l,limits:a},budget:t,...r!=null?{memoryCeiling:r}:{},environment:On({scope:l,memory_ceiling:r,scope_degradation:null}),...Qg(o&&a.note!=null?`${a.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,is(e.budget))}}function Qg(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function jd(e,n){for(let t of(n.PATH??"").split(Gg)){if(!t)continue;let r=wd(t,e);if(ds(r))return r}return null}function as(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function cs(e,n){let t=[],r=[];for(let o of e){let s=!1;try{s=await n(o)===!0}catch{s=!1}(s?t:r).push(o)}return{alive:t,dead:r}}function Dd(e){return e.unit!=null&&e.unit!==""?zg(e.unit):H(e.pid)}function zg(e){let n=nr("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var Yg="REDSKILLED_UNIT_DISCOVERY",Od="(unowned)";function Ad(e){let n=nr("systemctl",["--user","show","--property=MainPID","--value",e],{encoding:"utf8"});if(n.error!=null||n.status!==0)return null;let t=Number.parseInt((n.stdout??"").trim(),10);return Number.isInteger(t)&&t>0?t:null}function Xg(e=process.env){let n=(e[Yg]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Ld(e,n,t=process.env){return Xg(t)&&e===n}function Td(e=er){let n=nr("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return n.error!=null||n.status!==0?[]:(n.stdout??"").split(`
|
|
70
|
+
`).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function $d(e){let n=new Set(e.held.map(o=>o.unit).filter(o=>o!=null&&o!=="")),t=new Set,r=[];for(let o of e.units)o===""||n.has(o)||t.has(o)||(t.add(o),r.push({worker_id:o.replace(/\.service$/,""),project_label:Od,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 Id(e){return e.project_label.trim()!==""?e:{...e,project_label:Od,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 Nd(e){if(e.unit!=null&&e.unit!==""){let n=nr("systemctl",["--user","stop",e.unit],{stdio:"ignore"});return n.error==null&&n.status===0}try{return process.kill(e.pid,"SIGTERM"),!0}catch{return!1}}function Zg(e,n=50){if(Bd(e),!Number.isInteger(n)||n<=0)throw new Error(`redskilled queue discovery needs a whole, positive batch size, not ${JSON.stringify(n)}`);let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}function ek(e,n={}){let t=n.batchSize??50;if(Bd(e),e.length>t)throw new Error(`redskilled queue discovery spans at most ${t} selectors in one query, and this batch holds ${e.length}: split it with planQueueDiscoveryBatches rather than dropping the remainder`);let r=e.map((i,a)=>({alias:`q${a}`,project:i}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...r.map(({alias:i,project:a})=>` ${i}: search(query: ${JSON.stringify(a.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
|
|
71
|
+
`),aliases:r}}function nk(e,n){let t=Kn(n),r=Kn(t.data),o=Array.isArray(t.errors)?t.errors.map(Kn):[],s=rk(r.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=sk(r[a]);if(d!=null)return{project_label:l.project_label,outcome:"counted",depth:d,detail:`project ${JSON.stringify(l.project_label)} has ${d} item(s) matching its selector`};let p=o.find(u=>ok(u.path,a));return s.exhausted||Fd(p)?{project_label:l.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(l.project_label)} answered, so this queue has no depth rather than a depth of zero`+(s.reset_at==null?"":`; the quota resets at ${s.reset_at}`)}:{project_label:l.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(l.project_label)} could not be counted with the host token: ${us(p?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function tk(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function Md(e,n,t){return{version:1,fetched_at:n,request_count:0,project_count:e.length,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:e.map(r=>({project_label:r.project_label,outcome:"unconfigured",depth:null,detail:`project ${JSON.stringify(r.project_label)} was not counted because this host polls no tracker: ${t}`}))}}async function Wd(e){if(e.projects.length===0)return tk(e.now);let n=e.batchSize??50,t=Zg(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=ek(s,{batchSize:n});try{let a=await e.transport(i.query),l=nk(i,a);r.push(...l.projects),o=Cd(o,l.rate_limit)}catch(a){let l=a instanceof Error?a.message:String(a),d=/rate limit|secondary rate|429/i.test(l);o=Cd(o,{remaining:null,reset_at:null,exhausted:d});for(let p of s)r.push({project_label:p.project_label,outcome:d?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(p.project_label)} answered: ${l}`})}}return{version:1,fetched_at:e.now,request_count:t.length,project_count:r.length,batch_size:n,rate_limit:o,projects:r}}function Bd(e){if(e.length===0)throw new Error("redskilled queue discovery needs at least one registered project");let n=new Set;for(let t of e){if(typeof t.project_label!="string"||t.project_label==="")throw new Error("redskilled queue discovery needs a project label for every registered project");if(typeof t.selector!="string"||t.selector==="")throw new Error(`redskilled queue discovery needs a selector for project ${JSON.stringify(t.project_label)}: a project that names no work has no queue to discover`);if(n.has(t.project_label))throw new Error(`redskilled holds one selector per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function Cd(e,n){return{remaining:n.remaining==null?e.remaining:e.remaining==null?n.remaining:Math.min(e.remaining,n.remaining),reset_at:n.reset_at??e.reset_at,exhausted:e.exhausted||n.exhausted}}function rk(e,n){let t=Kn(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null;return{remaining:r,reset_at:o,exhausted:n.some(Fd)||r===0}}function Fd(e){return e==null?!1:us(e.type)==="RATE_LIMITED"||/rate limit/i.test(us(e.message))}function ok(e,n){return Array.isArray(e)&&e.includes(n)}function sk(e){let n=Kn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Kn(e){return ik(e)?e:{}}function ik(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function us(e){return typeof e=="string"?e:""}var lk={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},ak=["runner","model","effort","origin","issue","phase","step","heartbeat"],dk=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function Ud(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...lk};for(let r of ak){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of dk){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}import{randomUUID as Kd}from"node:crypto";import{spawn as fk}from"node:child_process";import{closeSync as mk,mkdirSync as hk,openSync as yk}from"node:fs";import{dirname as gk}from"node:path";import{delimiter as Hd,dirname as ck}from"node:path";function uk(e,n=Hd){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function pk(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=ck(n);return t===""||t==="."?null:t}function Gd(e,n=process.execPath,t=Hd){let r=uk(e,t),o=pk(n);return o==null?r.join(t):[o,...r.filter(s=>s!==o)].join(t)}var Vn=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},tr=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function kk(e){if(e==null||e.trim()==="")return null;try{return hk(gk(e),{recursive:!0}),yk(e,"a")}catch{return null}}function Rk(e){try{mk(e)}catch{}}function bk(e){let n=[["project_label",e.project_label],["workspace_path",e.workspace_path],["command",e.command]];for(let[t,r]of n)if(typeof r!="string"||r.trim()==="")throw new Vn(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new Vn("redskilled worker spec args must be an array")}function _k(e){if(e==null)throw new tr("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new tr(e.reason,e)}function qd(e){let{spec:n,admission:t}=e;_k(t),bk(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(n.worker_id??e.workerId??Kd()).trim()||Kd(),i=e.probes??Sd(r),a=e.openLog===!1?null:kk(n.log_path),l={...n.env??{},PATH:Gd(n.env?.PATH??r.PATH,e.execPath??process.execPath)},d=Pd({workerId:s,projectLabel:n.project_label,workspacePath:n.workspace_path,command:n.command,args:n.args,budget:n.budget,...e.memoryCeiling!=null?{memoryCeiling:e.memoryCeiling}:{},target:n.placement,env:l,enabled:e.enabled??vd(r),probes:i,pipeOutput:a!==null}),u=(e.spawnFn??fk)(d.command,d.args,{...d.cwd!=null?{cwd:d.cwd}:{},detached:!0,stdio:a===null?"ignore":["ignore",a,a],env:d.backend==="transient-unit"?{...r}:{...r,...l,...d.environment}});if(a!==null&&Rk(a),u.pid==null)throw u.once("error",()=>{}),new Vn(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${s}`);let f=d.job!=null?wk(d,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(k,_)=>{try{f?.job?.close()}catch{}e.onExit?.(s,k,_)}),u.unref();let m=d.job!=null?f?.job!=null:d.isolated,h=[d.warning,f?.warning,d.budgetWarning].filter(k=>k!=null);return{worker:{worker_id:s,project_label:n.project_label,pid:u.pid,started_at:o(),workspace_path:n.workspace_path,...n.log_path!=null?{log_path:n.log_path}:{},isolated:m,...d.unit!=null?{unit:d.unit}:{},...n.budget!=null?{budget:n.budget}:{},...Object.keys(d.budget).length>0?{applied_budget:d.budget}:{},...d.memoryCeiling!=null?{memory_ceiling:d.memoryCeiling,memory_ceiling_reason:e.memoryCeiling?.reason??"this Worker's ceiling is the budget its client declared"}:{},warnings:h},admission:t,warnings:h,plan:d,child:u,...f?.job!=null?{job:f.job}:{}}}function wk(e,n,t){let r=e.job;if(r==null)return{};let o="the Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling";if(!n.jobObjects.available)return{warning:`Job Object placement unavailable: ${n.jobObjects.reason}. ${o}`};let s;try{s=n.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(i){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${Vd(i)}. ${o}`}}try{s.assign(t)}catch(i){try{s.close()}catch{}return{warning:`Worker pid ${t} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${Vd(i)}. ${o}`}}return{job:s}}function Vd(e){return e instanceof Error?e.message:String(e)}import{open as xk,stat as Sk}from"node:fs/promises";var vk=16*1024;async function Jd(e,n=vk){let t;try{t=(await Sk(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let s=await xk(e,"r");try{let i=Buffer.alloc(r);await s.read(i,0,r,t-r),o=i.toString("utf8")}finally{await s.close()}}catch{return null}return Ek(o)}function Ek(e){let n=e.split(`
|
|
72
|
+
`);for(let t=n.length-1;t>=0;t-=1){let r=n[t].replace(/\r$/,"");if(r.trim()!=="")return r}return null}import{spawn as Fk}from"node:child_process";import{existsSync as Uk,readdirSync as Hk}from"node:fs";import{dirname as Gk,join as ec,resolve as Kk}from"node:path";var Pk="<version>";function Se(e,n=[],t){let r=t&&t.trim().length>0?t.trim():Pk;return[`npx -y -p ${$e}@${r}`,e,...n].join(" ")}function ee(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?{major:Number(n[1]),minor:Number(n[2]),patch:Number(n[3])}:null}function ps(e,n){let t=ee(e),r=ee(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var iE=4*60*60*1e3;fe();fe();import{spawnSync as jk}from"node:child_process";import{mkdir as Dk,rm as Ok,writeFile as Ak}from"node:fs/promises";import{existsSync as Lk}from"node:fs";import{homedir as Tk}from"node:os";import{dirname as $k,join as fs}from"node:path";var un="redskilled.service",ms="REDSKILLED_SUPERVISED",Ik="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function Nk(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||fs(e.HOME?.trim()||Tk(),".config");return fs(n,"systemd","user")}function hs(e=process.env){return fs(Nk(e),un)}function Qd(e,n={}){let t=n.env??process.env,r=Ot(n.override??{},n.entryLookup??{}),o=[...r.args,...Te(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:un,unitPath:hs(t),command:r.command,args:o,text:Ck(r.command,o,e)}}function Ck(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${Ik}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(Mk).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${ms}=1"`,`Environment="REDSKILLED_SESSION=${zd(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
|
|
73
|
+
`)}function Mk(e){return/[\s"'\\$%]/.test(e)?`"${zd(e)}"`:e}function zd(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function Yd(e,n={}){let t=n.writeFile??Wk,r=n.run??ys,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(rr("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(rr("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function Xd(e={}){let n=e.removeFile??Bk,t=e.run??ys,r=hs(e.env??process.env),o=[rr("disable",t,["systemctl","--user","disable","--now",un])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(rr("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function Zd(e={}){let n=e.exists??Lk,t=e.run??ys,r=hs(e.env??process.env),o=n(r);return{unitName:un,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",un]).status===0,active:o&&t(["systemctl","--user","is-active",un]).status===0,floor:"auto-spawn"}}function rr(e,n,t){let r=n(t),o=(r.stderr??r.stdout??"").trim();return{step:e,argv:t,ok:r.status===0,...o?{detail:o}:{}}}async function Wk(e,n){await Dk($k(e),{recursive:!0}),await Ak(e,n,{encoding:"utf8",mode:420})}async function Bk(e){await Ok(e,{force:!0})}function ys(e){let n=jk(e[0],[...e.slice(1)],{encoding:"utf8"});return n.error!=null?{status:null,stderr:n.error.message}:{status:n.status,stdout:n.stdout??"",stderr:n.stderr??""}}var nc=75,rc=9e5,tc="redskilled-replacement-entry-unresolved",Vk="REDSKILLED_NO_REGISTRY_PROBE",oc="REDSKILLED_BORN_BY_REPLACEMENT";function sc(e=process.env){return e[oc]==="1"}function ic(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function lc(e){let n=e.running.trim();if(qn(n))return null;let t=e.newest?.trim()??"",r=ee(t),o=ee(n);return r===null||o===null||r.major<=o.major?null:{version:t,running_major:o.major,held_major:r.major,reason:`redskilled ${t} is published and this daemon runs ${n}; a major version is deliberately never adopted by the background check, because a breaking change must not arrive on a machine that is holding Workers`,action:qk(r.major,e.supervised)}}function qk(e,n){let t=`install the ${e}.x bundle (update this machine's plugin pin), then `;return n?`${t}re-point the unit and restart it: ${Se("red-skills-redskilled",["unit","install"])} && systemctl --user restart redskilled.service`:`${t}stop this daemon \u2014 the next client start resolves the newly installed bundle`}function ac(e){let n=e.running.trim();if(qn(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||ee(t)===null?{act:"hold",reason:"published-unknown"}:ps(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function qn(e){let n=e.trim();return ee(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function dc(e=process.env){return e[ms]==="1"}var gs=class extends Error{code=tc;searched;constructor(n,t){super(`${tc}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
|
|
73
74
|
searched:
|
|
74
75
|
${t.map(r=>` ${r}`).join(`
|
|
75
|
-
`)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function
|
|
76
|
-
`}function Vk(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Y(n)}catch{return null}}}function qk(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 ri=3e5,nb=1e4,tb=6e4,rb=15e3,ob=3e4,rc=16,sn=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},ib="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function ic(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??ri,o=e.clock??(()=>new Date().toISOString()),i=e.launch??Pd,s=e.ceiling??Nl();e.repositoryActivity!=null&&Ao(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??nc(),l=e.leaseStore??tc(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??Zl(),p={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},u=e.machineClaimStore??Et(n.machineClaimPath,p,{clock:o});await Xk(eb(n.socketPath),{recursive:!0,mode:448});let f=await u.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new sn(n.socketPath):new _e(u.claimPath,f.reason,f.claim);let m=await l.acquire(a);if(!m.acquired)throw await u.release(d).catch(()=>{}),new sn(n.socketPath,m.lease);let h;try{h=await sb(n.socketPath)}catch(c){throw await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),c}let R=o(),k=e.eventLane??Wl(n.eventLanePath),_=e.liveness??cd,j=e.stopWorker??yd,ne=e.unitInventory??(()=>fd(n.machineClaimPath,vt({machineIdHash:n.machineIdHash}))?md():[]),q=e.unitMainPid??pd,xe=e.treeSampler??ja,Ne=e.readLogTail??jd,Bn=e.sampleMs??rb,gi=e.leaseRenewMs??ob,yi=e.publishedVersion??(c=>Vd(c)),ki=e.replaceCheckMs??Cd,bi=e.publishedProbeTimeoutMs??nb,Bc=e.localPublishedEvidence??(c=>qd(c,e.replacementIO?.env??process.env)),Hc=e.bornByReplacement??Wd(),Ri=e.replaceBootCheckMs??tb,_i=e.supervised??Ud(),wi=e.replacementIO??{},te=e.repositoryActivity,xi=te?.intervalMs??Oo,Hn=e.githubBalance,Se=e.queueDiscovery,Un=Se?.transport??te?.transport,Jt=Se?.unconfiguredReason??ib,Si=Se?.intervalMs??15e3,vi=e.demandMs??15e3,Uc=e.demandBackoffMs??3e4,v=new Map,ge=new Set,Ce=new Map,Gn=new Map,Qt=[],Kn=[],L=new Map,zt=new Set,Ei={},Yt=null,Pi=null,Xt=null,ji=!1,Zt=0,er=null,an="none",nr=null,Di=null,tr=null,dn=null,ye=null,Vn=null,cn=[],un=null,qn={},rr=!1,Me,pn,fn,mn,hn,Jn,gn,We,yn,U=!1,or=!1,Qn=null,Oi,ir=new Promise(c=>{Oi=c});function kn(c){Ai(c);let g=Date.parse(c),y=la(L.values(),g);for(let w of y.lapsed)L.delete(w.project_label),Gc(w,g);return y.lapsed}function Gc(c,g){let y=Number.isFinite(g)?new Date(g).toISOString():c.renew_by;cn.push({project_label:c.project_label,at:y,renew_by:c.renew_by,renewals:c.renewals,sustains:c.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(c.project_label)}: it stood until ${c.renew_by} and nothing renewed it \u2014 no session spoke for it, and no poll found it work or a Worker to hold it up`}),cn.length>rc&&cn.splice(0,cn.length-rc)}function Ai(c){if(L.size===0)return;let g=Date.parse(c);if(!Number.isFinite(g))return;let y={};for(let x of v.values())y[x.project_label]=(y[x.project_label]??0)+1;let w=new Map((ye?.projects??[]).map(x=>[x.project_label,x]));for(let x of[...L.values()]){let P=w.get(x.project_label),ce=ia(x,{now:c,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:y[x.project_label]??0});ce.registration!==x&&L.set(x.project_label,ce.registration)}}function zn(){let c=o();return kn(c),Va({now:c,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:a.pid,startedAt:R,scope:ea(u.claimPath,p,d),workers:[...v.values()],registrations:[...L.values()],lapses:cn,queue:ye,published:{version:Pi,checkedAt:Xt,newer:ji,replacement:an,newest:nr,majorHold:Di,checks:Zt,holdReason:er}})}function Yn(){return Ca({hostState:zn(),ceiling:s,rss:Ei,sampledAt:Yt,logLines:Object.fromEntries(Ce),displays:Object.fromEntries(Gn),now:o(),reattachedWorkerIds:[...ge],repositoryActivity:tr,githubBalance:dn,...e.deaths===void 0?{}:{deaths:e.deaths},metrics:Ea({observations:Qt,outcomes:Kn,now:o()})})}function Kc(c,g){Qt=Lt([...Qt,{worker_id:g,observed_at:c.published_at,tokens:c.display.tokens,tools:c.display.tools,runner:c.display.runner,model:c.display.model}],y=>y.observed_at,{now:o()})}function Vc(c){Kn=Lt([...Kn,c],g=>g.ts,{now:o()})}async function sr(){return te==null||te.projects.length===0?null:(tr=await Ta({projects:te.projects,hostTokenRef:te.hostTokenRef,transport:te.transport,closedWindowMs:te.closedWindowMs,now:o()}),tr)}async function Ti(){return Hn==null?null:(dn=await xo({transport:Hn.transport,now:o()}),dn)}function qc(){if(U||We!=null||Hn==null)return;let c=()=>{We=void 0,Ti().catch(()=>{}).then(()=>{if(U)return;let g=Hn.intervalMsOverride??$t(dn??Jc(),{now:o()});We=setTimeout(c,g),We.unref()})};c()}function Jc(){return Tt(o())}function Qc(){if(!(Un!=null||Se?.armTransport==null))try{let c=Se.armTransport();if(c.transport!=null){Un=c.transport;return}c.unconfiguredReason!=null&&(Jt=c.unconfiguredReason)}catch(c){Jt=`this host could not resolve a tracker credential: ${c instanceof Error?c.message:String(c)}`}}async function $i(){let c=o();kn(c);let g=[...L.values()].map(y=>({project_label:y.project_label,selector:y.selector})).sort((y,w)=>y.project_label.localeCompare(w.project_label));return g.length===0?null:(Qc(),Un==null?(ye=bd(g,c,Jt),ye):(ye=await Rd({projects:g,transport:Un,now:c,...Se?.batchSize==null?{}:{batchSize:Se.batchSize}}),Ai(o()),ye))}async function Li(){let c=o();if(rr)return Vn??Hl(c);rr=!0;try{let g={};for(let O of v.values())g[O.project_label]=(g[O.project_label]??0)+1;let y={};for(let O of ye?.projects??[])y[O.project_label]=O.depth;let w=Date.parse(c),x=Bl({projects:[...L.values()].map(O=>({project_label:O.project_label,selector:O.selector,argv:O.argv,workspace_path:O.workspace_path,target:O.target})),queue:y,live:g,nowMs:Number.isFinite(w)?w:0,backoffUntilMs:un,birthHaltUntilMs:Gl(qn,Number.isFinite(w)?w:0)}),P=[],ce=null;for(let O of x.births){let Be,gu=Wn(),tt=L.get(O.project_label),Ji=ta({argv:O.argv,...tt?.env==null?{}:{env:tt.env},...tt?.log_path==null?{}:{log_path:tt.log_path}},{worker_id:gu,slot:O.index,workspace_path:O.workspace_path},{project_label:O.project_label});try{Be=lr(Ji)}catch(cr){ce=cr instanceof Error?cr.message:String(cr),un=(Number.isFinite(w)?w:Date.now())+Uc;break}P.push({project_label:O.project_label,worker_id:Be.worker.worker_id,pid:Be.worker.pid,warnings:Ji.log_path==null?[...Be.warnings,`project ${JSON.stringify(O.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(Be.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:Be.warnings})}return ce==null&&x.births.length>0&&(un=null),Vn={version:1,at:c,requested:x.births.length,granted:P,shortfall:x.births.length-P.length,refusal:ce,retry_after:un==null?null:new Date(un).toISOString(),projects:x.intents},Vn}finally{rr=!1}}function zc(c){return Ma(Yn(),{...$,mode:c?.mode??$.mode,project:c?.project??$.project,maxWorkers:c?.max_workers??$.maxWorkers,maxProjects:c?.max_projects??$.maxProjects,maxWidth:c?.max_width??$.maxWidth,verbose:c?.verbose??$.verbose})}function Yc(c){return Ua(Yn(),{mode:c?.mode??tn.mode,project:c?.project??tn.project,maxWidth:c?.max_width??tn.maxWidth,maxRows:c?.max_rows??tn.maxRows})}function Fe(c,g,y){return da({op:c,sessionProject:g??null,targetProject:y})}async function Xc(c){let g=v.get(c.worker_id),y=Fe(aa(c.command),c.session_project,g?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(c.command!=="stop")throw new Error(`redskilled does not implement ${c.command}: it owns birth, death and limits, and ${c.command} is a work decision the project's own bundle makes on top of them`);let w=g!=null&&await ru(g,c.detail??"stopped by its own project");return{version:1,command:c.command,worker_id:c.worker_id,applied:w,reach:y,detail:w?`redskilled stopped Worker ${JSON.stringify(c.worker_id)} of project ${JSON.stringify(g.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function Xn(c){v.delete(c),ge.delete(c),Ce.delete(c),Gn.delete(c)}function Ii(c){let g=v.get(c.worker_id),y=Fe("worker-heartbeat",c.session_project,g?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(typeof c.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:c.worker_id,accepted:!1,reach:y,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to publish a line for`};let w=o();Ce.set(c.worker_id,{line:c.last_log_line,published_at:w,source:"heartbeat"});let x=c.display===void 0?null:Ba(c.display);if(x!=null){let P={display:x,published_at:w};Gn.set(c.worker_id,P),Kc(P,c.worker_id)}return{version:1,worker_id:c.worker_id,accepted:!0,reach:y,published_at:w,detail:`redskilled stored a line for Worker ${JSON.stringify(c.worker_id)} without reading it`}}async function Zc(c,g,y){let w=`exit code=${g??"null"} signal=${y??"null"}`;if(c.unit!=null&&c.unit!==""&&await nu(c)){tu(c,`its launch client ended (${w}) while unit ${JSON.stringify(c.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}Xn(c.worker_id),de("worker-death",c,w,{exitCode:g,signal:y}),I()}function eu(c,g){if(!Number.isFinite(g)||g<0){qn[c]=St;return}let y=qn[c]??St,w=Ul(y,g,Date.parse(o()));qn[c]=w,w.haltUntilMs!=null&&y.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(c)} lost ${w.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(w.haltUntilMs).toISOString()}
|
|
77
|
-
`)}async function nu(c){try{return await _(c)===!0}catch{return!1}}function tu(c,g){let y=c.unit==null?null:q(c.unit);v.set(c.worker_id,{...c,...y!=null&&y>0?{pid:y}:{},warnings:[...c.warnings,g]}),ge.add(c.worker_id),I()}function Ni(c,g){let y=Fe("project-register",g,c.project_label);if(!y.permitted)throw new Error(y.reason);let w=o();kn(w);let x=ra(c,{now:w,held:L.get(c.project_label)});return L.set(x.project_label,x),I(),{version:1,registration:x,reach:y,detail:`redskilled holds a registration for project ${JSON.stringify(x.project_label)} at a target of ${x.target} until ${x.renew_by}, and has read neither its selector nor its argv`}}function Ci(c,g={}){let y=Fe("project-renew",g.sessionProject,c);if(!y.permitted)throw new Error(y.reason);let w=o();kn(w);let x=L.get(c);if(x==null)throw new Pt(c);let P=oa(x,{now:w,...g.renewWithinMs==null?{}:{renew_within_ms:g.renewWithinMs},...g.launch==null?{}:{launch:g.launch}});return L.set(P.project_label,P),I(),{version:1,registration:P,reach:y,detail:`redskilled renewed the registration for project ${JSON.stringify(P.project_label)}, which now stands until ${P.renew_by} after renewal ${P.renewals}`+(g.launch==null?"":`, carrying launch revision ${P.launch_revision} for its next Worker`)}}function Mi(c,g){let y=Fe("project-deregister",g,c);if(!y.permitted)throw new Error(y.reason);let w=L.delete(c);return{version:1,project_label:c,released:w,reach:y,detail:w?`redskilled released the registration for project ${JSON.stringify(c)}`:`redskilled held no registration for project ${JSON.stringify(c)}, so there was nothing to release`}}async function ru(c,g){try{await j(c)}catch{}return Xn(c.worker_id),de("worker-death",c,g),I(),!0}function Wi(c){return Ll({ceiling:s,workers:[...v.values()],budget:c.budget,projectLabel:c.project_label})}function lr(c){let g=Il({ceiling:s,workers:[...v.values()],budget:c.budget}),y=i({spec:c,admission:Wi(c),memoryCeiling:g,clock:o,onExit:(w,x,P)=>{let ce=v.get(w);if(ce==null){I();return}Zc(ce,x,P).catch(()=>{})}});return v.set(y.worker.worker_id,y.worker),de("worker-birth",y.worker,null),I(),y}function de(c,g,y,w={}){if(U)return;let x=o();(c==="worker-death"||c==="worker-budget-kill")&&(Vc({worker_id:g.worker_id,ts:x,outcome:c}),eu(g.project_label,Date.parse(x)-Date.parse(g.started_at))),k.record({event:c,worker:g,ts:x,detail:y,...w.exitCode!==void 0?{exitCode:w.exitCode}:{},...w.signal!==void 0?{signal:w.signal}:{}}).catch(()=>{})}async function Fi(){let c=[...ge].map(y=>v.get(y)).filter(y=>y!=null);if(c.length===0)return[];let{dead:g}=await Vo(c,_);for(let y of g)Xn(y.worker_id),de("worker-death",y,"the host no longer confirms this Worker");return g.length>0&&I(),g}async function Bi(c,g){let y=v.get(c);if(!y)return!1;try{await j(y)}catch{}return Xn(c),de("worker-budget-kill",y,g),I(),!0}async function Hi(){let c=[...v.values()];if(c.length===0)return[];let g;try{g=await xe(c)}catch{return[]}let y=g.rss;Ei=y,Yt=o(),ou(g.cpu_seconds,Yt);let{terminations:w}=Pa({workers:c,rss:y}),x=[];for(let P of w)await Bi(P.worker_id,P.reason)&&x.push(P);return x}function ou(c,g){for(let[y,w]of Object.entries(c)){if(typeof w!="number"||!Number.isFinite(w))continue;let x=v.get(y);x&&v.set(y,{...x,cpu:{cpu_seconds:w,sampled_at:g}})}}async function iu(){try{return bi<=0?await yi(t):await new Promise(c=>{let g=setTimeout(()=>c(ar()),bi);g.unref(),yi(t).then(y=>{clearTimeout(g),c(y)},()=>{clearTimeout(g),c(ar())})})}catch{return ar()}}function ar(){try{return Bc(t)}catch{return null}}async function Ui(){if(Cn(t))return Zt+=1,Xt=o(),er="local-build",{act:"hold",reason:"local-build"};let c=Fd(await iu()),g=c.version;Pi=g,nr=c.newest??null,Xt=o(),Di=Bd({running:t,newest:nr,supervised:_i});let y=Hd({running:t,published:g,supervised:_i});return ji=y.act==="replace",Zt+=1,er=y.act==="hold"?y.reason:null,an!=="in-progress"&&(an=y.act==="replace"?"pending":"none"),y}async function Zn(){let c=await Ui();if(c.act!=="replace"||an==="in-progress")return c;let g=Gd(c,wi);return an="in-progress",await k.flush().catch(()=>{}),await nt({reason:"replaced"}),Kd(g,n,{...r==null?{}:{idleMs:r},io:wi}),c}function su(){U||hn!=null||ki<=0||(!Hc&&Ri>0&&(Jn=setTimeout(()=>{Zn().catch(()=>{})},Ri),Jn.unref()),hn=setInterval(()=>{Zn().catch(()=>{})},ki),hn.unref())}async function Gi(){return await l.renew(a).catch(()=>null)}function lu(){U||fn!=null||gi<=0||(fn=setInterval(()=>{Gi()},gi),fn.unref())}function au(){U||pn!=null||Bn<=0||(pn=setInterval(()=>{Hi().catch(()=>{})},Bn),pn.unref())}function du(){U||gn!=null||te==null||te.projects.length===0||xi<=0||(sr().catch(()=>{}),gn=setInterval(()=>{sr().catch(()=>{})},xi),gn.unref())}function cu(){U||yn!=null||Si<=0||(yn=setInterval(()=>{$i().catch(()=>{})},Si),yn.unref())}function uu(){U||mn!=null||vi<=0||(mn=setInterval(()=>{Li().catch(()=>{})},vi),mn.unref())}function I(){U||(Me&&clearTimeout(Me),Me=setTimeout(()=>{Fi().catch(()=>{}).then(()=>Ki())},r),Me.unref())}function Ki(){return v.size>0?(I(),"held-by-workers"):(kn(o()),L.size>0?(I(),"held-by-registrations"):(pu(),"exited"))}async function pu(){if(!Cn(t)){if((await Zn().catch(()=>null))?.act==="replace"||or||U)return;if(v.size>0||L.size>0){I();return}}await nt({reason:"idle"})}function et(c){return Vl({reason:c,socketPath:n.socketPath,daemonVersion:t,pid:a.pid,workers:[...v.values()],projects:[...L.keys()]})}function Vi(c){if(Qn!=null)return Qn;let g=c.reason??"requested",y=c.note?.trim();return Qn=k.recordDaemonStop({ts:o(),pid:a.pid,socketPath:n.socketPath,reason:g,detail:y==null||y===""?et(g).detail:`${et(g).detail} \u2014 ${y}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),Qn}async function nt(c={}){if(or)return await ir;or=!0,await Vi(c),U=!0,Me&&clearTimeout(Me),pn&&clearInterval(pn),fn&&clearInterval(fn),hn&&clearInterval(hn),Jn&&clearTimeout(Jn),gn&&clearInterval(gn),We&&clearTimeout(We),yn&&clearInterval(yn),mn&&clearInterval(mn),await k.flush().catch(()=>{}),h.close();for(let g of zt)g.destroy();return await new Promise(g=>h.once("close",()=>g())),await oc(n.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),Oi(),await ir}let qi=await k.read().catch(()=>[]);Kn=Lt(qi.filter(c=>c.event==="worker-death"||c.event==="worker-budget-kill").map(c=>({worker_id:c.worker_id,ts:c.ts,outcome:c.event})),c=>c.ts,{now:o()});let fu=Fl(qi),dr=await Vo(fu,_);for(let c of dr.alive){let g=gd(c),y=g.unit==null||H(g.pid)?null:q(g.unit);v.set(g.worker_id,y!=null&&y>0?{...g,pid:y}:g),ge.add(g.worker_id)}for(let c of dr.dead)de("worker-death",c,"the Worker ended while no daemon was watching");let mu=hd({units:await Promise.resolve(ne()).catch(()=>[]),held:[...v.values()],mainPid:q,now:R});for(let c of mu)v.set(c.worker_id,c),ge.add(c.worker_id),de("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of dr.alive){if(c.log_path==null||Ce.has(c.worker_id))continue;let g=await Ne(c.log_path).catch(()=>null);g==null||g.trim()===""||Ce.set(c.worker_id,{line:g,published_at:o(),source:"rehydrated"})}h.on("connection",c=>{zt.add(c),c.once("close",()=>zt.delete(c)),I(),lb(c,async(g,y)=>{I();let w=await hu(g);y(w),g.op==="shutdown"&&setImmediate(()=>void nt({reason:"requested"}))})});async function hu(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:Mt,daemon_version:t,pid:a.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:zn()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:Yn()};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:zc(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:Yc(c.dashboard)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:Ii(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:Ni(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:Ci(c.project_label,{...c.session_project==null?{}:{sessionProject:c.session_project},...c.renew_within_ms==null?{}:{renewWithinMs:c.renew_within_ms},...c.launch==null?{}:{launch:c.launch}})};if(c.op==="project-deregister")return{id:c.id,ok:!0,value:Mi(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await Xc(c.command)};if(c.op==="worker-start"){let y=Fe("worker-start",c.session_project,c.spec.project_label);if(!y.permitted)return{id:c.id,ok:!1,error:y.reason};let w=lr(c.spec);return await k.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:w.worker,admission:w.admission,warnings:w.warnings}}}if(c.op==="shutdown"){let y=et("requested");return await Vi({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:y}}let g=c;return{id:g.id??Wn(),ok:!1,error:`unsupported redskilled op: ${g.op??"unknown"}`}}catch(g){return{id:c.id??Wn(),ok:!1,error:g instanceof Error?g.message:String(g)}}}return I(),au(),lu(),su(),du(),qc(),cu(),uu(),{socketPath:n.socketPath,lease:m.lease,startedAt:R,closed:ir,startWorker:lr,admit:Wi,ceiling:()=>s,killWorkerOverBudget:Bi,sampleMemoryBudgets:Hi,renewLease:Gi,pollRepositoryActivity:sr,pollGithubBalance:Ti,githubBalance:()=>dn,pollQueueDiscovery:$i,queueDiscovery:()=>ye,driveDemand:Li,demand:()=>Vn,sweepReattached:Fi,publishWorkerHeartbeat:Ii,reattached:()=>[...ge].map(c=>v.get(c)).filter(c=>c!=null),flushEvents:()=>k.flush(),trackWorker(c){v.set(c.worker_id,c),de("worker-birth",c,null),I()},releaseWorker(c){let g=v.get(c),y=v.delete(c);return ge.delete(c),Ce.delete(c),Gn.delete(c),g&&de("worker-death",g,"released by the daemon"),I(),y},workerCount:()=>v.size,registerProject:Ni,renewProject:Ci,deregisterProject:Mi,registrations:()=>zn().registrations??[],hostState:zn,statuslinePayload:Yn,evaluateIdle:Ki,observePublishedVersion:Ui,checkForReplacement:Zn,stopReport:et,stop:nt}}async function sb(e){for(let n=0;n<2;n++){let t=Zk();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 ee(e))throw new sn(e);await oc(e,{force:!0})}}throw new sn(e)}async function ee(e,n=250){try{return(await gt({socketPath:e,timeoutMs:n},{id:Wn(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function lb(e,n){Rl(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??Wn(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function oi(e){let n=e.socketPath,t=ab(e);return e.answers?{version:1,kind:"answering",socket_path:n,holder:t,reason:`a redskilled daemon answered on ${JSON.stringify(n)}`,repair:"nothing to repair"}:t!=null?{version:1,kind:"held-unresponsive",socket_path:n,holder:t,reason:`redskilled pid ${t.pid} is alive and has held ${JSON.stringify(n)} since ${t.acquired_at}${t.uptime_ms==null?"":` (up ${sc(t.uptime_ms)})`}, but it did not answer a ping \u2014 this is a daemon that could not be REACHED, not one that is missing.`,repair:`Do not provision: a daemon is already running. Inspect it (\`ps -p ${t.pid}\`), or stop it with \`${we("red-skills-redskilled",["stop"])}\` and let the next client start a fresh one.`}:{version:1,kind:"absent",socket_path:n,holder:null,reason:`nothing answered on ${JSON.stringify(n)} and no live process holds its lease`,repair:`Install and start one with \`${we("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function ii(e){return`${e.reason} ${e.repair}`}function ab(e){let n=e.lease;return n==null||e.holderAlive!==!0||n.socket_path!==e.socketPath?null:{pid:n.pid,socket_path:n.socket_path,acquired_at:n.acquired_at,renewed_at:n.renewed_at,uptime_ms:db(n.acquired_at,e.now??new Date().toISOString())}}function db(e,n){let t=Date.parse(e),r=Date.parse(n);return!Number.isFinite(t)||!Number.isFinite(r)?null:Math.max(0,r-t)}function sc(e){let n=Math.floor(e/1e3),t=Math.floor(n/3600),r=Math.floor(n%3600/60),o=n%60;return t>0?`${t}h${String(r).padStart(2,"0")}m`:r>0?`${r}m${String(o).padStart(2,"0")}s`:`${o}s`}pe();var dc=1e4,Ie=class extends Error{constructor(t,r,o){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}${o!=null&&o.kind==="held-unresponsive"?`. ${ii(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},si=class extends Ie{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}};async function Kt(e,n={}){let t=n.answers??await ee(e.socketPath),r=await Mn(e.leasePath).catch(()=>{});return oi({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&H(r.pid)})}async function li(e,n={}){try{return await mb(e,n)}catch(t){if(t instanceof _e||t instanceof Ie)throw t;let r=await Kt(e).catch(()=>{});throw new Ie(e.socketPath,t,r)}}async function mb(e,n){if(await ub(fb(e.socketPath),{recursive:!0,mode:448}),await ee(e.socketPath))return"already-running";await gb(e);let t=await hb(e,n);if(t!=null)return t;let r=await _l(e.lockPath);if(!r)return await lc(e,n),"joined";try{if(await ee(e.socketPath))return"already-running";let o=await bb(e,n);return await lc(e,n,o),"spawned"}finally{await r.close(),await pb(e.lockPath,{force:!0})}}async function hb(e,n){let t=await Kt(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??dc,o=Date.now()+r;for(;;){if(await ee(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(s=>setTimeout(s,25))}let i=await Kt(e).catch(()=>{});if(i==null||i.kind!=="held-unresponsive")return null;throw new si(e.socketPath,i,new Error(`it did not answer a ping within ${r}ms, and no second daemon was spawned because pid ${i.holder?.pid??"unknown"} still holds this socket`))}async function gb(e){let t=await Et(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&H(t.pid))throw new _e(e.machineClaimPath,"held",t)}async function cc(e,n,t={}){await li(e,t);let r;try{r=await Ln({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:ac()})}catch(o){throw new Ie(e.socketPath,o,await Kt(e).catch(()=>{}))}if(!r.ok)throw new Error(r.error);return r.value}async function uc(e,n={},t={}){if(!await ee(e.socketPath))return ql(e.socketPath);let r;try{r=await Ln({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:ac(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(s){throw new Ie(e.socketPath,s)}if(!r.ok)throw new Error(r.error);if(!co(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await yb(e.socketPath,n.settleTimeoutMs??5e3)?o:{...o,stopped:!1,detail:`${o.detail}; the daemon accepted the stop and is still answering on ${JSON.stringify(e.socketPath)}`}}async function yb(e,n){let t=Date.now()+n;for(;;){if(!await ee(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function pc(e,n={}){let t=await cc(e,{op:"host-state"},n);if(!qa(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function fc(e,n=void 0,t={}){let r=await cc(e,{op:"statusline-string",...t.sessionProject!=null?{session_project:t.sessionProject}:{},...n==null?{}:{render:kb(n)}},t);if(!Ka(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function kb(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 lc(e,n,t){let r=Date.now()+(n.readyTimeoutMs??dc);for(;;){if(await ee(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=r){let o=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${o}`)}await new Promise(o=>setTimeout(o,25))}}async function bb(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await Dl({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},i=[...r.args,...Ae(e,n.idleMs==null?{}:{idleMs:n.idleMs})],s=cb(r.command,i,{detached:!0,stdio:"ignore",env:{...n.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}pe();import{chmod as Rc,mkdir as wc,readFile as xc,stat as Ob,writeFile as Ab}from"node:fs/promises";import{homedir as ci}from"node:os";import{dirname as Tb,join as ui}from"node:path";import{join as Rb}from"node:path";var mc=["local","tmp","host"],_b="local",Fn="plugins.dev.workspace.target";var ai=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function gc(e){let n=ze(e,Fn),t=Sb(n??"").trim();return t===""?void 0:t}function yc(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:_b};let t=mc.find(r=>r===n.toLowerCase());if(t)return{kind:"preset",preset:t};if(n.startsWith("/")||n==="~"||n.startsWith("~/"))return{kind:"custom",parentDir:n};throw new ai(`${Fn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${mc.join(", ")}) or an absolute parent directory for Workers.`)}function kc(e,n){return e.kind==="preset"?e.preset==="host":xb(wb(e.parentDir,n),Oe(n))}function wb(e,n){return e==="~"?hc(n):e.startsWith("~/")?Rb(n,e.slice(2)):hc(e)}function xb(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function hc(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function Sb(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}pe();import{createHash as vb}from"node:crypto";import{hostname as Eb}from"node:os";import{join as Vt}from"node:path";var ln="redskilled.sock",Pb="REDSKILLED_SESSION";function jb(e={}){let n=e.env??process.env,t=n[Pb]?.trim();if(t)return t;let r=n.XDG_RUNTIME_DIR?.trim();return r||`uid:${e.uid??(typeof process.getuid=="function"?process.getuid():"nouid")}`}function Db(e={}){return bc(e.host??Eb())}function he(e={}){let n=jb(e),t=e.runtimeDir??yt({key:`redskilled:${n}`,socketFileName:ln,env:e.env,uid:e.uid}),r=Db(e);return{sessionKey:n,sessionKeyHash:bc(n),machineIdHash:r,runtimeDir:t,socketPath:Vt(t,ln),lockPath:Vt(t,"redskilled.spawn.lock"),leasePath:Vt(t,"redskilled.lease.toon"),eventLanePath:Vt(t,Ml),machineClaimPath:e.machineClaimPath??vt({env:e.env,machineIdHash:r,platform:e.platform})}}function bc(e){return vb("sha256").update(e).digest("hex").slice(0,12)}var di=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${we("red-skills-redskilled",["provision"])}\` directly`;async function Sc(e=ci()){let n=Oe(e),t=await fi(n);return t===void 0?(await wc(n,{recursive:!0,mode:se}),await Rc(n,se),{path:n,created:!0,tightened:!1,mode:se}):t===se?{path:n,created:!1,tightened:!1,mode:t}:(await Rc(n,se),{path:n,created:!1,tightened:!0,mode:se})}var vc={needed:!1,declaredBy:`no ${Fn} in view`};async function pi(e={}){let n=e.homeDir??ci(),t=e.declaredTarget?.trim();if(t)return _c(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return vc;let o=ui(r,".red","config.yaml"),i=await xc(o,"utf8").catch(()=>{});if(i===void 0)return{needed:!1,declaredBy:`no ${o}`};let s=gc(i);return s===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:_c(s,n,o)}function _c(e,n,t){let r=`${Fn}: ${e} (${t})`;try{return{needed:kc(yc(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function Ec(e){let n=[$b(e),Lb(e),Ib(e),Nb(e)],t=n.filter(o=>o.verdict!=="ok");return{verdict:t.some(o=>o.verdict==="missing")?"missing":t.length>0?"degraded":"ok",rows:n,findings:t}}function $b(e){let n=e.homeNeed??vc;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:di}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??se;return t!==se?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${se.toString(8)}`,fix:`${di} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function Lb(e){return ae(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 \`${we("red-skills-redskilled",["provision"])}\``}}function Ib(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:`${di} \u2014 it starts the daemon and waits for the socket`}}function Nb(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 Pc(e={}){let n=e.env??process.env,t=e.homeDir??ci(),r=e.paths??he({env:n}),o=Oe(t),[i,s,a]=await Promise.all([fi(o),ee(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):pi({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:i!==void 0,homeMode:i,homeNeed:a,entry:Re(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:s,supervisorUnit:await Mb(Wb(e,n,t),n)}}var Cb="redskilled.service";function jc(e){return ui(e,"systemd","user",Cb)}function Dc(e){let n=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${n}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
|
|
78
|
-
`)}async function
|
|
76
|
+
`)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function Jk(e,n={}){let t=n.env??process.env,r=n.exists??Uk,o=n.execPath??process.execPath,s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[ec(Dt(t),i),"bundle-cache"]];s&&l.push([ec(Gk(Kk(s)),i),"caller-sibling-bundle"]);for(let[d,p]of l)if(a.push(d),r(d))return{command:o,args:[d],version:e,source:p,searched:a};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new gs(e,a);return{command:t.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:a}}function cc(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>Jk(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function uc(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??zk)(nc),{...e,exitCode:nc};let o=[...e.entry.args,...Te(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??Qk(r.env))(e.entry,o),e}function Qk(e){return(n,t)=>{let r=Fk(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[oc]:"1"}});r.on("error",()=>{}),r.unref()}}function zk(e){process.exitCode=e,process.exit(e)}async function pc(e,n=process.env,t=Yk){let r=mc(n),o=hc(e,n);if(n[Vk]==="1")return{version:o,newest:r};let s=ee(e)===null?"0.0.0":e;try{let i=await Hl({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function fc(e,n=process.env,t){let r=t??ks;return{version:hc(e,n,r),newest:mc(n,r)}}function mc(e=process.env,n=ks){return gc(yc(e,n))}function hc(e,n=process.env,t=ks){let r=ee(e.trim())?.major;return r===void 0?null:gc(yc(n,t).filter(o=>ee(o)?.major===r))}function yc(e,n){let t=[];for(let r of n(Dt(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||ee(o)===null||t.push(o)}return t}function gc(e){let n=null;for(let t of e)(n===null||ps(t,n)>0)&&(n=t);return n}function ks(e){try{return Hk(e)}catch{return[]}}async function Yk(e){let n=await fetch(e,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`registry read failed with HTTP ${n.status}`);return await n.text()}import{mkdir as Xk,readFile as Zk,rename as eR,rm as Rs,writeFile as kc}from"node:fs/promises";import{randomUUID as nR}from"node:crypto";import{dirname as tR}from"node:path";var or=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function Jn(e){let n;try{n=await Zk(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=rR(n);return oR(t)?t:void 0}var Rc;function _c(){return Rc??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Rc}function wc(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??H;async function s(){return await Jn(e)}async function i(l){let d=`${e}.${l.pid}.${nR()}.tmp`;await kc(d,bc(l),{encoding:"utf8",mode:384}),await eR(d,e)}function a(l,d){return{version:1,pid:l.pid,start_time:l.startTime,session_key_hash:n.sessionKeyHash,machine_id_hash:n.machineIdHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}return{read:s,async acquire(l){await Xk(tR(e),{recursive:!0,mode:448});let d=!1;for(;;){let p=r(),u=a(l,p);try{return await kc(e,bc(u),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:u}}catch(m){if(m.code!=="EEXIST")throw m}let f=await s();if(!f){await Rs(e,{force:!0}),d=!0;continue}if(bs(f,l))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await Rs(e,{force:!0}),d=!0}},async renew(l){let d=await s();if(!d||!bs(d,l))throw new or(e);let p={...d,renewed_at:r()};return await i(p),p},async release(l){let d=await s();if(!d)return!1;if(!bs(d,l))throw new or(e);return await Rs(e,{force:!0}),!0}}}function bs(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function bc(e){return`${M(e,{keyedMapCollapse:!0})}
|
|
77
|
+
`}function rR(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return q(n)}catch{return null}}}function oR(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 _s=3e5,pR=1e4,fR=6e4,mR=15e3,hR=3e4,xc=16,pn=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},yR="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function vc(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??_s,o=e.clock??(()=>new Date().toISOString()),s=e.launch??qd,i=e.ceiling??ta();e.repositoryActivity!=null&&Qo(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??_c(),l=e.leaseStore??wc(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??Ra(),p={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},u=e.machineClaimStore??Nt(n.machineClaimPath,p,{clock:o});await dR(uR(n.socketPath),{recursive:!0,mode:448});let f=await u.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new pn(n.socketPath):new we(u.claimPath,f.reason,f.claim);let m=await l.acquire(a);if(!m.acquired)throw await u.release(d).catch(()=>{}),new pn(n.socketPath,m.lease);let h;try{h=await gR(n.socketPath)}catch(c){throw await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),c}let b=o(),k=e.eventLane??sa(n.eventLanePath),_=e.liveness??Dd,j=e.stopWorker??Nd,te=e.unitInventory??(()=>Ld(n.machineClaimPath,It({machineIdHash:n.machineIdHash}))?Td():[]),z=e.unitMainPid??Ad,ve=e.treeSampler??Qa,Fe=e.readLogTail??Jd,Yn=e.sampleMs??mR,$s=e.leaseRenewMs??hR,Is=e.publishedVersion??(c=>pc(c)),Ns=e.replaceCheckMs??rc,Cs=e.publishedProbeTimeoutMs??pR,lu=e.localPublishedEvidence??(c=>fc(c,e.replacementIO?.env??process.env)),au=e.bornByReplacement??sc(),Ms=e.replaceBootCheckMs??fR,Ws=e.supervised??dc(),Bs=e.replacementIO??{},re=e.repositoryActivity,Fs=re?.intervalMs??Jo,Xn=e.githubBalance,Ee=e.queueDiscovery,Zn=Ee?.transport??re?.transport,ar=Ee?.unconfiguredReason??yR,Us=Ee?.intervalMs??15e3,Hs=e.demandMs??15e3,du=e.demandBackoffMs??3e4,v=new Map,ge=new Set,Ue=new Map,et=new Map,dr=[],nt=[],$=new Map,cr=new Set,Gs={},ur=null,Ks=null,pr=null,Vs=!1,fr=0,mr=null,mn="none",hr=null,qs=null,yr=null,hn=null,ke=null,tt=null,yn=[],gn=null,rt={},gr=!1,He,kn,Rn,bn,_n,ot,wn,Ge,xn,K=!1,kr=!1,st=null,Js,Rr=new Promise(c=>{Js=c});function Sn(c){Qs(c);let y=Date.parse(c),g=Pa($.values(),y);for(let w of g.lapsed)$.delete(w.project_label),cu(w,y);return g.lapsed}function cu(c,y){let g=Number.isFinite(y)?new Date(y).toISOString():c.renew_by;yn.push({project_label:c.project_label,at:g,renew_by:c.renew_by,renewals:c.renewals,sustains:c.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(c.project_label)}: it stood until ${c.renew_by} and nothing renewed it \u2014 no session spoke for it, and no poll found it work or a Worker to hold it up`}),yn.length>xc&&yn.splice(0,yn.length-xc)}function Qs(c){if($.size===0)return;let y=Date.parse(c);if(!Number.isFinite(y))return;let g={};for(let x of v.values())g[x.project_label]=(g[x.project_label]??0)+1;let w=new Map((ke?.projects??[]).map(x=>[x.project_label,x]));for(let x of[...$.values()]){let P=w.get(x.project_label),ue=va(x,{now:c,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:g[x.project_label]??0});ue.registration!==x&&$.set(x.project_label,ue.registration)}}function it(){let c=o();return Sn(c),ud({now:c,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:a.pid,startedAt:b,scope:ba(u.claimPath,p,d),workers:[...v.values()],registrations:[...$.values()],lapses:yn,queue:ke,published:{version:Ks,checkedAt:pr,newer:Vs,replacement:mn,newest:hr,majorHold:qs,checks:fr,holdReason:mr}})}function lt(){return sd({hostState:it(),ceiling:i,rss:Gs,sampledAt:ur,logLines:Object.fromEntries(Ue),displays:Object.fromEntries(et),now:o(),reattachedWorkerIds:[...ge],repositoryActivity:yr,githubBalance:hn,...e.deaths===void 0?{}:{deaths:e.deaths},metrics:Va({observations:dr,outcomes:nt,now:o()})})}function uu(c,y){dr=Gt([...dr,{worker_id:y,observed_at:c.published_at,tokens:c.display.tokens,tools:c.display.tools,runner:c.display.runner,model:c.display.model}],g=>g.observed_at,{now:o()})}function pu(c){nt=Gt([...nt,c],y=>y.ts,{now:o()})}async function br(){return re==null||re.projects.length===0?null:(yr=await Za({projects:re.projects,hostTokenRef:re.hostTokenRef,transport:re.transport,closedWindowMs:re.closedWindowMs,now:o()}),yr)}async function zs(){return Xn==null?null:(hn=await Mo({transport:Xn.transport,now:o()}),hn)}function fu(){if(K||Ge!=null||Xn==null)return;let c=()=>{Ge=void 0,zs().catch(()=>{}).then(()=>{if(K)return;let y=Xn.intervalMsOverride??Ht(hn??mu(),{now:o()});Ge=setTimeout(c,y),Ge.unref()})};c()}function mu(){return Ut(o())}function hu(){if(!(Zn!=null||Ee?.armTransport==null))try{let c=Ee.armTransport();if(c.transport!=null){Zn=c.transport;return}c.unconfiguredReason!=null&&(ar=c.unconfiguredReason)}catch(c){ar=`this host could not resolve a tracker credential: ${c instanceof Error?c.message:String(c)}`}}async function Ys(){let c=o();Sn(c);let y=[...$.values()].map(g=>({project_label:g.project_label,selector:g.selector})).sort((g,w)=>g.project_label.localeCompare(w.project_label));return y.length===0?null:(hu(),Zn==null?(ke=Md(y,c,ar),ke):(ke=await Wd({projects:y,transport:Zn,now:c,...Ee?.batchSize==null?{}:{batchSize:Ee.batchSize}}),Qs(o()),ke))}async function Xs(){let c=o();if(gr)return tt??aa(c);gr=!0;try{let y={};for(let A of v.values())y[A.project_label]=(y[A.project_label]??0)+1;let g={};for(let A of ke?.projects??[])g[A.project_label]=A.depth;let w=Date.parse(c),x=la({projects:[...$.values()].map(A=>({project_label:A.project_label,selector:A.selector,argv:A.argv,workspace_path:A.workspace_path,target:A.target})),queue:g,live:y,nowMs:Number.isFinite(w)?w:0,backoffUntilMs:gn,birthHaltUntilMs:ca(rt,Number.isFinite(w)?w:0)}),P=[],ue=null;for(let A of x.births){let Ve,Nu=Qn(),pt=$.get(A.project_label),pi=wa({argv:A.argv,...pt?.env==null?{}:{env:pt.env},...pt?.log_path==null?{}:{log_path:pt.log_path}},{worker_id:Nu,slot:A.index,workspace_path:A.workspace_path},{project_label:A.project_label});try{Ve=_r(pi)}catch(Sr){ue=Sr instanceof Error?Sr.message:String(Sr),gn=(Number.isFinite(w)?w:Date.now())+du;break}P.push({project_label:A.project_label,worker_id:Ve.worker.worker_id,pid:Ve.worker.pid,warnings:pi.log_path==null?[...Ve.warnings,`project ${JSON.stringify(A.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(Ve.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:Ve.warnings})}return ue==null&&x.births.length>0&&(gn=null),tt={version:1,at:c,requested:x.births.length,granted:P,shortfall:x.births.length-P.length,refusal:ue,retry_after:gn==null?null:new Date(gn).toISOString(),projects:x.intents},tt}finally{gr=!1}}function yu(c){return Me(lt(),{...D,mode:c?.mode??D.mode,project:c?.project??D.project,maxWorkers:c?.max_workers??D.maxWorkers,maxProjects:c?.max_projects??D.maxProjects,maxWidth:c?.max_width??D.maxWidth,verbose:c?.verbose??D.verbose})}function gu(c){return Yt(lt(),{mode:c?.mode??xe.mode,project:c?.project??xe.project,maxWidth:c?.max_width??xe.maxWidth,maxRows:c?.max_rows??xe.maxRows})}function Ke(c,y,g){return Da({op:c,sessionProject:y??null,targetProject:g})}async function ku(c){let y=v.get(c.worker_id),g=Ke(ja(c.command),c.session_project,y?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(c.command!=="stop")throw new Error(`redskilled does not implement ${c.command}: it owns birth, death and limits, and ${c.command} is a work decision the project's own bundle makes on top of them`);let w=y!=null&&await xu(y,c.detail??"stopped by its own project");return{version:1,command:c.command,worker_id:c.worker_id,applied:w,reach:g,detail:w?`redskilled stopped Worker ${JSON.stringify(c.worker_id)} of project ${JSON.stringify(y.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function at(c){v.delete(c),ge.delete(c),Ue.delete(c),et.delete(c)}function Zs(c){let y=v.get(c.worker_id),g=Ke("worker-heartbeat",c.session_project,y?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(typeof c.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(y==null)return{version:1,worker_id:c.worker_id,accepted:!1,reach:g,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to publish a line for`};let w=o();Ue.set(c.worker_id,{line:c.last_log_line,published_at:w,source:"heartbeat"});let x=c.display===void 0?null:Ud(c.display);if(x!=null){let P={display:x,published_at:w};et.set(c.worker_id,P),uu(P,c.worker_id)}return{version:1,worker_id:c.worker_id,accepted:!0,reach:g,published_at:w,detail:`redskilled stored a line for Worker ${JSON.stringify(c.worker_id)} without reading it`}}async function Ru(c,y,g){let w=`exit code=${y??"null"} signal=${g??"null"}`;if(c.unit!=null&&c.unit!==""&&await _u(c)){wu(c,`its launch client ended (${w}) while unit ${JSON.stringify(c.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}at(c.worker_id),ce("worker-death",c,w,{exitCode:y,signal:g}),I()}function bu(c,y){if(!Number.isFinite(y)||y<0){rt[c]=$t;return}let g=rt[c]??$t,w=da(g,y,Date.parse(o()));rt[c]=w,w.haltUntilMs!=null&&g.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(c)} lost ${w.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(w.haltUntilMs).toISOString()}
|
|
78
|
+
`)}async function _u(c){try{return await _(c)===!0}catch{return!1}}function wu(c,y){let g=c.unit==null?null:z(c.unit);v.set(c.worker_id,{...c,...g!=null&&g>0?{pid:g}:{},warnings:[...c.warnings,y]}),ge.add(c.worker_id),I()}function ei(c,y){let g=Ke("project-register",y,c.project_label);if(!g.permitted)throw new Error(g.reason);let w=o();Sn(w);let x=xa(c,{now:w,held:$.get(c.project_label)});return $.set(x.project_label,x),I(),{version:1,registration:x,reach:g,detail:`redskilled holds a registration for project ${JSON.stringify(x.project_label)} at a target of ${x.target} until ${x.renew_by}, and has read neither its selector nor its argv`}}function ni(c,y={}){let g=Ke("project-renew",y.sessionProject,c);if(!g.permitted)throw new Error(g.reason);let w=o();Sn(w);let x=$.get(c);if(x==null)throw new Ct(c);let P=Sa(x,{now:w,...y.renewWithinMs==null?{}:{renew_within_ms:y.renewWithinMs},...y.launch==null?{}:{launch:y.launch}});return $.set(P.project_label,P),I(),{version:1,registration:P,reach:g,detail:`redskilled renewed the registration for project ${JSON.stringify(P.project_label)}, which now stands until ${P.renew_by} after renewal ${P.renewals}`+(y.launch==null?"":`, carrying launch revision ${P.launch_revision} for its next Worker`)}}function ti(c,y){let g=Ke("project-deregister",y,c);if(!g.permitted)throw new Error(g.reason);let w=$.delete(c);return{version:1,project_label:c,released:w,reach:g,detail:w?`redskilled released the registration for project ${JSON.stringify(c)}`:`redskilled held no registration for project ${JSON.stringify(c)}, so there was nothing to release`}}async function xu(c,y){try{await j(c)}catch{}return at(c.worker_id),ce("worker-death",c,y),I(),!0}function ri(c){return ea({ceiling:i,workers:[...v.values()],budget:c.budget,projectLabel:c.project_label})}function _r(c){let y=na({ceiling:i,workers:[...v.values()],budget:c.budget}),g=s({spec:c,admission:ri(c),memoryCeiling:y,clock:o,onExit:(w,x,P)=>{let ue=v.get(w);if(ue==null){I();return}Ru(ue,x,P).catch(()=>{})}});return v.set(g.worker.worker_id,g.worker),ce("worker-birth",g.worker,null),I(),g}function ce(c,y,g,w={}){if(K)return;let x=o();(c==="worker-death"||c==="worker-budget-kill")&&(pu({worker_id:y.worker_id,ts:x,outcome:c}),bu(y.project_label,Date.parse(x)-Date.parse(y.started_at))),k.record({event:c,worker:y,ts:x,detail:g,...w.exitCode!==void 0?{exitCode:w.exitCode}:{},...w.signal!==void 0?{signal:w.signal}:{}}).catch(()=>{})}async function oi(){let c=[...ge].map(g=>v.get(g)).filter(g=>g!=null);if(c.length===0)return[];let{dead:y}=await cs(c,_);for(let g of y)at(g.worker_id),ce("worker-death",g,"the host no longer confirms this Worker");return y.length>0&&I(),y}async function si(c,y){let g=v.get(c);if(!g)return!1;try{await j(g)}catch{}return at(c),ce("worker-budget-kill",g,y),I(),!0}async function ii(){let c=[...v.values()];if(c.length===0)return[];let y;try{y=await ve(c)}catch{return[]}let g=y.rss;Gs=g,ur=o(),Su(y.cpu_seconds,ur);let{terminations:w}=Ja({workers:c,rss:g}),x=[];for(let P of w)await si(P.worker_id,P.reason)&&x.push(P);return x}function Su(c,y){for(let[g,w]of Object.entries(c)){if(typeof w!="number"||!Number.isFinite(w))continue;let x=v.get(g);x&&v.set(g,{...x,cpu:{cpu_seconds:w,sampled_at:y}})}}async function vu(){try{return Cs<=0?await Is(t):await new Promise(c=>{let y=setTimeout(()=>c(wr()),Cs);y.unref(),Is(t).then(g=>{clearTimeout(y),c(g)},()=>{clearTimeout(y),c(wr())})})}catch{return wr()}}function wr(){try{return lu(t)}catch{return null}}async function li(){if(qn(t))return fr+=1,pr=o(),mr="local-build",{act:"hold",reason:"local-build"};let c=ic(await vu()),y=c.version;Ks=y,hr=c.newest??null,pr=o(),qs=lc({running:t,newest:hr,supervised:Ws});let g=ac({running:t,published:y,supervised:Ws});return Vs=g.act==="replace",fr+=1,mr=g.act==="hold"?g.reason:null,mn!=="in-progress"&&(mn=g.act==="replace"?"pending":"none"),g}async function dt(){let c=await li();if(c.act!=="replace"||mn==="in-progress")return c;let y=cc(c,Bs);return mn="in-progress",await k.flush().catch(()=>{}),await ut({reason:"replaced"}),uc(y,n,{...r==null?{}:{idleMs:r},io:Bs}),c}function Eu(){K||_n!=null||Ns<=0||(!au&&Ms>0&&(ot=setTimeout(()=>{dt().catch(()=>{})},Ms),ot.unref()),_n=setInterval(()=>{dt().catch(()=>{})},Ns),_n.unref())}async function ai(){return await l.renew(a).catch(()=>null)}function Pu(){K||Rn!=null||$s<=0||(Rn=setInterval(()=>{ai()},$s),Rn.unref())}function ju(){K||kn!=null||Yn<=0||(kn=setInterval(()=>{ii().catch(()=>{})},Yn),kn.unref())}function Du(){K||wn!=null||re==null||re.projects.length===0||Fs<=0||(br().catch(()=>{}),wn=setInterval(()=>{br().catch(()=>{})},Fs),wn.unref())}function Ou(){K||xn!=null||Us<=0||(xn=setInterval(()=>{Ys().catch(()=>{})},Us),xn.unref())}function Au(){K||bn!=null||Hs<=0||(bn=setInterval(()=>{Xs().catch(()=>{})},Hs),bn.unref())}function I(){K||(He&&clearTimeout(He),He=setTimeout(()=>{oi().catch(()=>{}).then(()=>di())},r),He.unref())}function di(){return v.size>0?(I(),"held-by-workers"):(Sn(o()),$.size>0?(I(),"held-by-registrations"):(Lu(),"exited"))}async function Lu(){if(!qn(t)){if((await dt().catch(()=>null))?.act==="replace"||kr||K)return;if(v.size>0||$.size>0){I();return}}await ut({reason:"idle"})}function ct(c){return pa({reason:c,socketPath:n.socketPath,daemonVersion:t,pid:a.pid,workers:[...v.values()],projects:[...$.keys()]})}function ci(c){if(st!=null)return st;let y=c.reason??"requested",g=c.note?.trim();return st=k.recordDaemonStop({ts:o(),pid:a.pid,socketPath:n.socketPath,reason:y,detail:g==null||g===""?ct(y).detail:`${ct(y).detail} \u2014 ${g}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),st}async function ut(c={}){if(kr)return await Rr;kr=!0,await ci(c),K=!0,He&&clearTimeout(He),kn&&clearInterval(kn),Rn&&clearInterval(Rn),_n&&clearInterval(_n),ot&&clearTimeout(ot),wn&&clearInterval(wn),Ge&&clearTimeout(Ge),xn&&clearInterval(xn),bn&&clearInterval(bn),await k.flush().catch(()=>{}),h.close();for(let y of cr)y.destroy();return await new Promise(y=>h.once("close",()=>y())),await Sc(n.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),Js(),await Rr}let ui=await k.read().catch(()=>[]);nt=Gt(ui.filter(c=>c.event==="worker-death"||c.event==="worker-budget-kill").map(c=>({worker_id:c.worker_id,ts:c.ts,outcome:c.event})),c=>c.ts,{now:o()});let Tu=ia(ui),xr=await cs(Tu,_);for(let c of xr.alive){let y=Id(c),g=y.unit==null||H(y.pid)?null:z(y.unit);v.set(y.worker_id,g!=null&&g>0?{...y,pid:g}:y),ge.add(y.worker_id)}for(let c of xr.dead)ce("worker-death",c,"the Worker ended while no daemon was watching");let $u=$d({units:await Promise.resolve(te()).catch(()=>[]),held:[...v.values()],mainPid:z,now:b});for(let c of $u)v.set(c.worker_id,c),ge.add(c.worker_id),ce("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of xr.alive){if(c.log_path==null||Ue.has(c.worker_id))continue;let y=await Fe(c.log_path).catch(()=>null);y==null||y.trim()===""||Ue.set(c.worker_id,{line:y,published_at:o(),source:"rehydrated"})}h.on("connection",c=>{cr.add(c),c.once("close",()=>cr.delete(c)),I(),kR(c,async(y,g)=>{I();let w=await Iu(y);g(w),y.op==="shutdown"&&setImmediate(()=>void ut({reason:"requested"}))})});async function Iu(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:Xt,daemon_version:t,pid:a.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:it()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:od(lt(),c.extras)};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:yu(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:gu(c.dashboard)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:Zs(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:ei(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:ni(c.project_label,{...c.session_project==null?{}:{sessionProject:c.session_project},...c.renew_within_ms==null?{}:{renewWithinMs:c.renew_within_ms},...c.launch==null?{}:{launch:c.launch}})};if(c.op==="project-deregister")return{id:c.id,ok:!0,value:ti(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await ku(c.command)};if(c.op==="worker-start"){let g=Ke("worker-start",c.session_project,c.spec.project_label);if(!g.permitted)return{id:c.id,ok:!1,error:g.reason};let w=_r(c.spec);return await k.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:w.worker,admission:w.admission,warnings:w.warnings}}}if(c.op==="shutdown"){let g=ct("requested");return await ci({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:g}}let y=c;return{id:y.id??Qn(),ok:!1,error:`unsupported redskilled op: ${y.op??"unknown"}`}}catch(y){return{id:c.id??Qn(),ok:!1,error:y instanceof Error?y.message:String(y)}}}return I(),ju(),Pu(),Eu(),Du(),fu(),Ou(),Au(),{socketPath:n.socketPath,lease:m.lease,startedAt:b,closed:Rr,startWorker:_r,admit:ri,ceiling:()=>i,killWorkerOverBudget:si,sampleMemoryBudgets:ii,renewLease:ai,pollRepositoryActivity:br,pollGithubBalance:zs,githubBalance:()=>hn,pollQueueDiscovery:Ys,queueDiscovery:()=>ke,driveDemand:Xs,demand:()=>tt,sweepReattached:oi,publishWorkerHeartbeat:Zs,reattached:()=>[...ge].map(c=>v.get(c)).filter(c=>c!=null),flushEvents:()=>k.flush(),trackWorker(c){v.set(c.worker_id,c),ce("worker-birth",c,null),I()},releaseWorker(c){let y=v.get(c),g=v.delete(c);return ge.delete(c),Ue.delete(c),et.delete(c),y&&ce("worker-death",y,"released by the daemon"),I(),g},workerCount:()=>v.size,registerProject:ei,renewProject:ni,deregisterProject:ti,registrations:()=>it().registrations??[],hostState:it,statuslinePayload:lt,evaluateIdle:di,observePublishedVersion:li,checkForReplacement:dt,stopReport:ct,stop:ut}}async function gR(e){for(let n=0;n<2;n++){let t=cR();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 ne(e))throw new pn(e);await Sc(e,{force:!0})}}throw new pn(e)}async function ne(e,n=250){try{return(await Et({socketPath:e,timeoutMs:n},{id:Qn(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function kR(e,n){Ml(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??Qn(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function ws(e){let n=e.socketPath,t=RR(e);return e.answers?{version:1,kind:"answering",socket_path:n,holder:t,reason:`a redskilled daemon answered on ${JSON.stringify(n)}`,repair:"nothing to repair"}:t!=null?{version:1,kind:"held-unresponsive",socket_path:n,holder:t,reason:`redskilled pid ${t.pid} is alive and has held ${JSON.stringify(n)} since ${t.acquired_at}${t.uptime_ms==null?"":` (up ${Ec(t.uptime_ms)})`}, but it did not answer a ping \u2014 this is a daemon that could not be REACHED, not one that is missing.`,repair:`Do not provision: a daemon is already running. Inspect it (\`ps -p ${t.pid}\`), or stop it with \`${Se("red-skills-redskilled",["stop"])}\` and let the next client start a fresh one.`}:{version:1,kind:"absent",socket_path:n,holder:null,reason:`nothing answered on ${JSON.stringify(n)} and no live process holds its lease`,repair:`Install and start one with \`${Se("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function xs(e){return`${e.reason} ${e.repair}`}function RR(e){let n=e.lease;return n==null||e.holderAlive!==!0||n.socket_path!==e.socketPath?null:{pid:n.pid,socket_path:n.socket_path,acquired_at:n.acquired_at,renewed_at:n.renewed_at,uptime_ms:bR(n.acquired_at,e.now??new Date().toISOString())}}function bR(e,n){let t=Date.parse(e),r=Date.parse(n);return!Number.isFinite(t)||!Number.isFinite(r)?null:Math.max(0,r-t)}function Ec(e){let n=Math.floor(e/1e3),t=Math.floor(n/3600),r=Math.floor(n%3600/60),o=n%60;return t>0?`${t}h${String(r).padStart(2,"0")}m`:r>0?`${r}m${String(o).padStart(2,"0")}s`:`${o}s`}fe();var Dc=1e4,Be=class extends Error{constructor(t,r,o){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}${o!=null&&o.kind==="held-unresponsive"?`. ${xs(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},Ss=class extends Be{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}};async function sr(e,n={}){let t=n.answers??await ne(e.socketPath),r=await Jn(e.leasePath).catch(()=>{});return ws({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&H(r.pid)})}async function vs(e,n={}){try{return await vR(e,n)}catch(t){if(t instanceof we||t instanceof Be)throw t;let r=await sr(e).catch(()=>{});throw new Be(e.socketPath,t,r)}}async function vR(e,n){if(await wR(SR(e.socketPath),{recursive:!0,mode:448}),await ne(e.socketPath))return"already-running";await PR(e);let t=await ER(e,n);if(t!=null)return t;let r=await Wl(e.lockPath);if(!r)return await Pc(e,n),"joined";try{if(await ne(e.socketPath))return"already-running";let o=await OR(e,n);return await Pc(e,n,o),"spawned"}finally{await r.close(),await xR(e.lockPath,{force:!0})}}async function ER(e,n){let t=await sr(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??Dc,o=Date.now()+r;for(;;){if(await ne(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(i=>setTimeout(i,25))}let s=await sr(e).catch(()=>{});if(s==null||s.kind!=="held-unresponsive")return null;throw new Ss(e.socketPath,s,new Error(`it did not answer a ping within ${r}ms, and no second daemon was spawned because pid ${s.holder?.pid??"unknown"} still holds this socket`))}async function PR(e){let t=await Nt(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&H(t.pid))throw new we(e.machineClaimPath,"held",t)}async function Oc(e,n,t={}){await vs(e,t);let r;try{r=await Gn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:jc()})}catch(o){throw new Be(e.socketPath,o,await sr(e).catch(()=>{}))}if(!r.ok)throw new Error(r.error);return r.value}async function Ac(e,n={},t={}){if(!await ne(e.socketPath))return fa(e.socketPath);let r;try{r=await Gn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:jc(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new Be(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!vo(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await jR(e.socketPath,n.settleTimeoutMs??5e3)?o:{...o,stopped:!1,detail:`${o.detail}; the daemon accepted the stop and is still answering on ${JSON.stringify(e.socketPath)}`}}async function jR(e,n){let t=Date.now()+n;for(;;){if(!await ne(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function Lc(e,n={}){let t=await Oc(e,{op:"host-state"},n);if(!pd(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function DR(e,n={},t){let r=await Oc(e,{op:"statusline-payload",...n.sessionProject!=null?{session_project:n.sessionProject}:{},...t==null?{}:{extras:t}},n);if(!zo(r))throw new Error("redskilled daemon returned a malformed statusline payload");return r}async function Tc(e,n=D,t={}){let r=await DR(e,t,{vitals:!0,logs:n.verbose});return Me(r,n)}async function Pc(e,n,t){let r=Date.now()+(n.readyTimeoutMs??Dc);for(;;){if(await ne(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=r){let o=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${o}`)}await new Promise(o=>setTimeout(o,25))}}async function OR(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await ql({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,...Te(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=_R(r.command,s,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return i.on("error",a=>{o.failure=a}),i.on("exit",(a,l)=>{o.exit=l?`died on ${l}`:`exited with code ${a??-1}`}),i.unref(),o}fe();import{chmod as Bc,mkdir as Uc,readFile as Hc,stat as FR,writeFile as UR}from"node:fs/promises";import{homedir as js}from"node:os";import{dirname as HR,join as Ds}from"node:path";import{join as AR}from"node:path";var $c=["local","tmp","host"],LR="local",zn="plugins.dev.workspace.target";var Es=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function Nc(e){let n=nn(e,zn),t=IR(n??"").trim();return t===""?void 0:t}function Cc(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:LR};let t=$c.find(r=>r===n.toLowerCase());if(t)return{kind:"preset",preset:t};if(n.startsWith("/")||n==="~"||n.startsWith("~/"))return{kind:"custom",parentDir:n};throw new Es(`${zn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${$c.join(", ")}) or an absolute parent directory for Workers.`)}function Mc(e,n){return e.kind==="preset"?e.preset==="host":$R(TR(e.parentDir,n),Le(n))}function TR(e,n){return e==="~"?Ic(n):e.startsWith("~/")?AR(n,e.slice(2)):Ic(e)}function $R(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Ic(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function IR(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}fe();import{createHash as NR}from"node:crypto";import{hostname as CR}from"node:os";import{join as ir}from"node:path";var fn="redskilled.sock",MR="REDSKILLED_SESSION";function WR(e={}){let n=e.env??process.env,t=n[MR]?.trim();if(t)return t;let r=n.XDG_RUNTIME_DIR?.trim();return r||`uid:${e.uid??(typeof process.getuid=="function"?process.getuid():"nouid")}`}function BR(e={}){return Wc(e.host??CR())}function ye(e={}){let n=WR(e),t=e.runtimeDir??Pt({key:`redskilled:${n}`,socketFileName:fn,env:e.env,uid:e.uid}),r=BR(e);return{sessionKey:n,sessionKeyHash:Wc(n),machineIdHash:r,runtimeDir:t,socketPath:ir(t,fn),lockPath:ir(t,"redskilled.spawn.lock"),leasePath:ir(t,"redskilled.lease.toon"),eventLanePath:ir(t,oa),machineClaimPath:e.machineClaimPath??It({env:e.env,machineIdHash:r,platform:e.platform})}}function Wc(e){return NR("sha256").update(e).digest("hex").slice(0,12)}var Ps=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${Se("red-skills-redskilled",["provision"])}\` directly`;async function Gc(e=js()){let n=Le(e),t=await As(n);return t===void 0?(await Uc(n,{recursive:!0,mode:le}),await Bc(n,le),{path:n,created:!0,tightened:!1,mode:le}):t===le?{path:n,created:!1,tightened:!1,mode:t}:(await Bc(n,le),{path:n,created:!1,tightened:!0,mode:le})}var Kc={needed:!1,declaredBy:`no ${zn} in view`};async function Os(e={}){let n=e.homeDir??js(),t=e.declaredTarget?.trim();if(t)return Fc(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return Kc;let o=Ds(r,".red","config.yaml"),s=await Hc(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=Nc(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Fc(i,n,o)}function Fc(e,n,t){let r=`${zn}: ${e} (${t})`;try{return{needed:Mc(Cc(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function Vc(e){let n=[GR(e),KR(e),VR(e),qR(e)],t=n.filter(o=>o.verdict!=="ok");return{verdict:t.some(o=>o.verdict==="missing")?"missing":t.length>0?"degraded":"ok",rows:n,findings:t}}function GR(e){let n=e.homeNeed??Kc;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:Ps}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??le;return t!==le?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${le.toString(8)}`,fix:`${Ps} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function KR(e){return de(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 \`${Se("red-skills-redskilled",["provision"])}\``}}function VR(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:`${Ps} \u2014 it starts the daemon and waits for the socket`}}function qR(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 qc(e={}){let n=e.env??process.env,t=e.homeDir??js(),r=e.paths??ye({env:n}),o=Le(t),[s,i,a]=await Promise.all([As(o),ne(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Os({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:a,entry:_e(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await QR(zR(e,n,t),n)}}var JR="redskilled.service";function Jc(e){return Ds(e,"systemd","user",JR)}function Qc(e){let n=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${n}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
|
|
79
|
+
`)}async function zc(e){let n=Jc(e.configHome);return await As(n)!==void 0?{path:n,status:"already-present"}:(await Uc(HR(n),{recursive:!0}),await UR(n,e.unit,"utf8"),{path:n,status:"installed"})}async function QR(e,n){if(process.platform!=="linux")return"unsupported";try{return await Hc(Jc(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function zR(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??Ds(t,".config")}async function As(e){try{return(await FR(e)).mode&511}catch{return}}import{readdir as Xc,rm as YR,stat as XR}from"node:fs/promises";import{dirname as ZR,join as Ls}from"node:path";var eb=5*6e4,nb="redskilled.";function tb(e={}){let n=e.env??process.env,t=i=>ZR(Pt({key:"redskilled:reclaim-probe",socketFileName:fn,env:i,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=n,s=[t(n),t(o)];return[...new Set(s)]}async function Zc(e={}){let n=e.roots??tb(e),t=e.graceMs??eb,r=e.now??Date.now,o=e.isPidAlive??H,s=e.answers??ib,i=e.dryRun===!0,a=[];for(let l of n){let d;try{d=(await Xc(l,{withFileTypes:!0})).filter(p=>p.isDirectory()).map(p=>p.name)}catch{continue}for(let p of d.sort())a.push(await rb(Ls(l,p),{graceMs:t,now:r,pidAlive:o,answers:s,dryRun:i}))}return{roots:n,scanned:a.length,reclaimed:a.filter(l=>l.verdict==="reclaimed").length,dryRun:i,entries:a}}async function rb(e,n){let t;try{t=(await Xc(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:eu(i),removed:[]}}let r=t.filter(i=>i.startsWith(nb));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await ob(Ls(e,"redskilled.lease.toon"));if(o!==void 0)return await n.pidAlive(o.pid)?{dir:e,verdict:"live",reason:`lease pid ${o.pid} is alive`,removed:[]}:await Yc(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(fn)&&await n.answers(Ls(e,fn)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await sb(e,n.now);return s!==void 0&&s<n.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(s/1e3)}s ago`,removed:[]}:await Yc(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function Yc(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await YR(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:eu(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function ob(e){try{return await Jn(e)}catch{return}}async function sb(e,n){try{return Math.max(0,n()-(await XR(e)).mtimeMs)}catch{return}}async function ib(e){try{return(await Gn({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function eu(e){return e instanceof Error?e.message:String(e)}var lb="plugins.dev.statusline",ab="dev.statusline";function db(e){let n=[],t=a=>{for(let l of[lb,ab]){let d=`${l}.${a}`,p=nn(e,d)?.trim();if(p!=null&&p!=="")return{key:d,value:p}}},r=t("mode"),o={};r!=null&&(r.value==="local"||r.value==="global"?o.mode=r.value:n.push({...r,reason:"expected `local` or `global`"}));let s=[{leaf:"max_workers",assign:a=>{o.maxWorkers=a}},{leaf:"max_projects",assign:a=>{o.maxProjects=a}},{leaf:"max_width",assign:a=>{o.maxWidth=a}}];for(let a of s){let l=t(a.leaf);if(l==null)continue;let d=Number(l.value);Number.isInteger(d)&&d>=0?a.assign(d):n.push({...l,reason:"expected a whole number of zero or more"})}let i=t("verbose");return i!=null&&(i.value==="true"||i.value==="false"?o.verbose=i.value==="true":n.push({...i,reason:"expected `true` or `false`"})),{config:o,warnings:n}}var cb={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 nu(e){let{values:n,positionals:t}=Oe(e,cb),r=[],o={},s=n.mode??t.find(a=>a==="global"||a==="local");s!=null&&(s==="local"||s==="global"?o.mode=s:r.push({key:"--mode",value:s,reason:"expected `local` or `global`"})),n.project!=null&&(o.project=n.project),n.verbose!==void 0&&(o.verbose=n.verbose===!0);let i=[{flag:"max-workers",assign:a=>{o.maxWorkers=a}},{flag:"max-projects",assign:a=>{o.maxProjects=a}},{flag:"max-width",assign:a=>{o.maxWidth=a}}];for(let a of i){let l=n[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 tu(e={}){let n=e.configText==null?{config:{},warnings:[]}:db(e.configText),t=e.flags??{};return{options:{...D,mode:t.mode??n.config.mode??D.mode,project:t.project!==void 0?t.project:e.project??D.project,maxWorkers:t.maxWorkers??n.config.maxWorkers??D.maxWorkers,maxProjects:t.maxProjects??n.config.maxProjects??D.maxProjects,maxWidth:t.maxWidth??n.config.maxWidth??D.maxWidth,verbose:t.verbose??n.config.verbose??D.verbose},warnings:n.warnings}}var pb=`Usage: redskilled <command> [options]
|
|
79
80
|
|
|
80
81
|
Commands:
|
|
81
82
|
host-state (default) print the host's state as JSON
|
|
@@ -87,7 +88,7 @@ Commands:
|
|
|
87
88
|
|
|
88
89
|
Run \`redskilled <command> --help\` for a command's own usage.
|
|
89
90
|
\`--version\` (\`-v\`) prints the build stamp; both answer offline.
|
|
90
|
-
`,
|
|
91
|
+
`,fb={serve:`Usage: redskilled serve [options]
|
|
91
92
|
|
|
92
93
|
Runs the daemon in this process. Every path is a flag and none is derived
|
|
93
94
|
(ADR 0130 rule 3); what is absent falls back to the session derivation.
|
|
@@ -151,19 +152,19 @@ Reports every session runtime dir it looked at and why it kept or removed it.
|
|
|
151
152
|
|
|
152
153
|
--dry-run the same report with nothing removed
|
|
153
154
|
--grace-ms <n> how long a dir must be idle before it is reclaimed
|
|
154
|
-
`};function
|
|
155
|
-
`:`${
|
|
156
|
-
`),0}if(
|
|
157
|
-
`);let d=
|
|
158
|
-
`),0}var
|
|
159
|
-
`),o.running&&!o.stopped?1:0}async function
|
|
160
|
-
`),0;if(o==="install"){let
|
|
161
|
-
`),
|
|
162
|
-
`),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function
|
|
163
|
-
`);let a;try{a=await
|
|
164
|
-
`),a=
|
|
155
|
+
`};function mb(e){return e==="--help"||e==="-h"||e==="help"}var hb={socket:{kind:"value",coerce:e=>e},lease:{kind:"value",coerce:e=>e},events:{kind:"value",coerce:e=>e},"session-key-hash":{kind:"value",coerce:e=>e},"machine-id-hash":{kind:"value",coerce:e=>e},"machine-claim":{kind:"value",coerce:e=>e},"idle-ms":{kind:"value",coerce:e=>Number(e)},"daemon-version":{kind:"value",coerce:e=>e},"queue-endpoint":{kind:"value",coerce:e=>e},"queue-ms":{kind:"value",coerce:e=>Number(e)},"demand-ms":{kind:"value",coerce:e=>Number(e)}},su="REDSKILLED_HOST_TOKEN";function lr(){try{let n=ub("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function iu(e=process.env,n=lr){let t=(e[su]??e.GITHUB_TOKEN??e.GH_TOKEN??"").trim();if(t!=="")return{token:t,source:"env"};let r=(n()??"").trim();return r!==""?{token:r,source:"tracker-cli"}:null}function yb(e,n=process.env,t=lr){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...ru(e,n,t),armTransport:()=>ru(e,n,t)}}function gb(e,n=process.env,t=lr){let r=iu(n,t);if(r==null)return null;let o=n.GITHUB_API_URL;return{transport:Ho({token:r.token,...o?{origin:o}:{}})}}function ru(e,n=process.env,t=lr){let r=iu(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${su}, GITHUB_TOKEN and GH_TOKEN are all unset in the daemon's environment and \`gh auth token\` returned nothing \u2014 so no queue depth is asked for, and no depth is invented either`};let o=e["queue-endpoint"]??n.GITHUB_GRAPHQL_URL;return{transport:td({token:r.token,...o?{endpoint:o}:{}})}}async function kb(e){if(e[0]==="--version"||e[0]==="-v"){let o=Gr("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
|
|
156
|
+
`:`${zi(o)}
|
|
157
|
+
`),0}if(mb(e[0]))return process.stdout.write(pb),0;let{command:n,args:t}=el(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(fb[n]),0;if(n==="serve"){let{values:o}=Oe(t,hb),s=yb(o),i=gb(o),a=ou(Le(Ts()),"state"),l=bl({stateRoot:a});process.stderr.write(`${_l(l)}
|
|
158
|
+
`);let d=hl({lanePath:An(a),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),p=await vc({paths:Db(o),idleMs:o["idle-ms"]??_s,daemonVersion:o["daemon-version"]??Gr("redskilled").version,deaths:l.attributions,queueDiscovery:s,...i==null?{}:{githubBalance:i},...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let u of["SIGTERM","SIGINT"])process.once(u,()=>void p.stop({reason:"signal",signal:u}).catch(()=>{}));return await p.closed,d.phase("closed"),0}if(n==="stop")return await bb(t);if(n==="statusline")return await wb(t);if(n==="unit")return await _b(t);if(n==="provision")return await Sb(t);if(n==="reclaim")return await Eb(t);let r=await Lc(ye());return process.stdout.write(`${JSON.stringify(r,null,2)}
|
|
159
|
+
`),0}var Rb={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function bb(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=Oe(e,Rb),o=await Ac(n.paths??ye(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${M({running:o.running,stopped:o.stopped,reason:o.reason,socket:o.socket_path,daemon_version:o.daemon_version,pid:o.pid,holding:{workers:o.holding.workers.length,projects:[...o.holding.projects]},surviving:[...o.surviving],workers:o.holding.workers.map(s=>({worker_id:s.worker_id,project_label:s.project_label,pid:s.pid,unit:s.unit,isolated:s.isolated,survives:s.survives})),detail:o.detail})}
|
|
160
|
+
`),o.running&&!o.stopped?1:0}async function _b(e,n={}){let t=n.write??(s=>process.stdout.write(s)),r=n.paths??ye(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(Zd(n.unitIO??{}),null,2)}
|
|
161
|
+
`),0;if(o==="install"){let s=await Yd(Qd(r),n.unitIO??{});return t(`${JSON.stringify(s,null,2)}
|
|
162
|
+
`),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await Xd(n.unitIO??{}),null,2)}
|
|
163
|
+
`),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function wb(e,n={}){let t=n.write??(l=>process.stdout.write(l)),r=n.warn??(l=>process.stderr.write(l)),o=nu(e),s=jb(n.cwd??process.cwd()),i=tu({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let l of[...i.warnings,...o.warnings])r(`redskilled statusline: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
|
|
164
|
+
`);let a;try{a=await Tc(n.paths??ye(),i.options,{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(l){r(`redskilled statusline: ${l instanceof Error?l.message:String(l)}
|
|
165
|
+
`),a=os({options:i.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${a.lines.join(`
|
|
165
166
|
`)}
|
|
166
|
-
`),0}var
|
|
167
|
-
`),u.verdict==="ok"?0:1}var
|
|
168
|
-
`),o.entries.some(
|
|
169
|
-
`),process.exitCode=1});export{
|
|
167
|
+
`),0}var xb={"no-start":{kind:"boolean"},"install-unit":{kind:"boolean"},check:{kind:"boolean"},project:{kind:"value",coerce:e=>e},workspace:{kind:"value",coerce:e=>e}};async function Sb(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=Oe(e,xb),o=n.paths??ye(),s=n.homeDir??Ts(),i=await Os({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),a=r.check||!i.needed?void 0:await Gc(s),l;if(!r.check&&!r["no-start"])try{await vs(o,n.client??{})}catch(f){l=f instanceof Error?f.message:String(f)}let d=await qc({paths:o,homeNeed:i,...n.homeDir==null?{}:{homeDir:n.homeDir},...n.configHome==null?{}:{configHome:n.configHome},...n.client?.serverCommand==null?{}:{entryOverride:{serverCommand:n.client.serverCommand,serverArgs:n.client.serverArgs}}}),p=r["install-unit"]&&de(d.entry)?await zc({configHome:n.configHome??Pb(),unit:Qc({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=Vc(d);return t(`${M({verdict:u.verdict,home:{path:a?.path??d.homePath,created:a?.created??!1,tightened:a?.tightened??!1,needed:i.needed,needed_by:i.declaredBy},socket:d.socketPath,...l==null?{}:{start_error:l},...p==null?{}:{unit:{path:p.path,status:p.status}},checks:u.rows.map(f=>({check:f.check,verdict:f.verdict,evidence:f.evidence})),fixes:u.findings.map(f=>({check:f.check,fix:f.fix}))})}
|
|
168
|
+
`),u.verdict==="ok"?0:1}var vb={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function Eb(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=Oe(e,vb),o=await Zc({...n.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return t(`${M({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(s=>({dir:s.dir,verdict:s.verdict,reason:s.reason,removed:[...s.removed]}))})}
|
|
169
|
+
`),o.entries.some(s=>s.verdict==="failed")?1:0}function Pb(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:ou(Ts(),".config")}function jb(e){let n=co(e);return n.configText==null?{label:null}:{configText:n.configText,label:Dl(e)}}function Db(e){let n=ye();return{...n,socketPath:e.socket??n.socketPath,leasePath:e.lease??n.leasePath,eventLanePath:e.events??n.eventLanePath,sessionKeyHash:e["session-key-hash"]??n.sessionKeyHash,machineIdHash:e["machine-id-hash"]??n.machineIdHash,machineClaimPath:e["machine-claim"]??n.machineClaimPath}}var Ob=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;Ob&&kb(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
|
|
170
|
+
`),process.exitCode=1});export{su as REDSKILLED_HOST_TOKEN_ENV,pb as REDSKILLED_USAGE,ru as armRedskilledQueueTransport,iu as resolveRedskilledHostToken,gb as resolveServeGithubBalance,yb as resolveServeQueueDiscovery,Sb as runProvision,Eb as runReclaim,kb as runRedskilledCli,wb as runStatusline,bb as runStop,_b as runUnit};
|