@reddb-io/red-skills 3.6.0 → 3.6.2
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 +352 -352
- package/dist/code-nav.bundle.min.mjs +1 -1
- package/dist/dev.bundle.min.mjs +579 -579
- package/dist/memory.bundle.min.mjs +1 -1
- package/dist/redskilled.bundle.min.mjs +89 -87
- package/dist/rsp.bundle.min.mjs +166 -153
- package/package.json +1 -1
|
@@ -1,72 +1,72 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
3
|
-
var
|
|
3
|
+
var $f=Object.create;var as=Object.defineProperty;var If=Object.getOwnPropertyDescriptor;var Cf=Object.getOwnPropertyNames;var Nf=Object.getPrototypeOf,Mf=Object.prototype.hasOwnProperty;var Ff=(e,r)=>()=>(e&&(r=e(e=0)),r);var Al=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),Wf=(e,r)=>{for(var t in r)as(e,t,{get:r[t],enumerable:!0})},Uf=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of Cf(r))!Mf.call(e,o)&&o!==t&&as(e,o,{get:()=>r[o],enumerable:!(n=If(r,o))||n.enumerable});return e};var ls=(e,r,t)=>(t=e!=null?$f(Nf(e)):{},Uf(r||!e||!e.__esModule?as(t,"default",{value:e,enumerable:!0}):t,e));var pc={};Wf(pc,{REDSKILLED_BIN_ENV:()=>ri,REDSKILLED_BUNDLE_ASSET:()=>Ne,REDSKILLED_ENTRY_UNRESOLVED:()=>Bt,RedskilledDaemonEntryError:()=>Ht,isRedskilledEntryPath:()=>ni,isResolvedRedskilledEntry:()=>Me,redskilledBundleCacheRoot:()=>io,redskilledServeArgv:()=>vr,requireRedskilledEntry:()=>ao,resolveRedskilledEntry:()=>nr});import{existsSync as Vb,readdirSync as Kb}from"node:fs";import{homedir as Jb}from"node:os";import{basename as ei,dirname as Zs,join as _e,resolve as so}from"node:path";function Me(e){return"command"in e}function vr(e,r={}){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 r.idleMs!=null&&t.push("--idle-ms",String(r.idleMs)),r.daemonVersion!=null&&t.push("--daemon-version",r.daemonVersion),t}function io(e=process.env){return uc(e)}function nr(e={},r={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=r.env??process.env,n=r.exists??Vb,o=r.execPath??process.execPath,s=r.execArgv??[],i=r.callerEntry===void 0?process.argv[1]:r.callerEntry,a=(c,u)=>({command:o,args:[...s,c],source:u,entry:c}),l=t[ri];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(i&&ni(i))return a(so(i),"caller-entry");let d=[];for(let[c,u]of Xb(i,r.rootDir,t,r.listDir??rk))if(d.push(c),n(c))return a(c,u);return{diagnostic:Bt,searched:d,...i?{callerEntry:so(i)}:{}}}function ao(e={},r={}){let t=nr(e,r);if(Me(t))return t;throw new Ht(t)}function ni(e){let r=ei(e);return r===Ne||ti.test(r)||r==="red-skills-redskilled"||r==="red-skills-redskilled.mjs"?!0:r!=="cli.js"&&r!=="cli.mjs"&&r!=="cli.ts"?!1:Yb(so(e))}function Yb(e){let r=Zs(e);for(let t=0;t<4;t++){if(ei(r)==="redskilled")return!0;let n=Zs(r);if(n===r)return!1;r=n}return!1}function*Xb(e,r,t,n){if(e){let s=Zs(so(e));yield[_e(s,Ne),"caller-sibling-bundle"];let i=zb.exec(ei(e));i&&(yield[_e(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[_e(s,"..","dist",Ne),"caller-sibling-bundle"]}for(let s of Qb){let i=t[s];i&&(yield[_e(i,"dist",Ne),"plugin-root-bundle"],yield[_e(i,"..","..","dist",Ne),"plugin-root-bundle"])}r&&(yield[_e(r,"dist",Ne),"repo-bundle"],yield[_e(r,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[_e(r,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=uc(t);yield[_e(o,Ne),"bundle-cache"];for(let s of Zb(o,n))yield[_e(o,s),"bundle-cache"]}function uc(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let r=e.XDG_CACHE_HOME||_e(e.HOME||Jb(),".cache");return _e(r,"red-skills","bundles")}function Zb(e,r){return r(e).filter(t=>ti.test(t)).sort((t,n)=>ek(cc(n),cc(t)))}function cc(e){return ti.exec(e)?.[1]??""}function ek(e,r){let t=s=>s.split(".").map(i=>Number.parseInt(i,10)),[n,o]=[t(e),t(r)];for(let s=0;s<Math.max(n.length,o.length);s++){let[i,a]=[n[s],o[s]];if(Number.isNaN(i)||i===void 0)return Number.isNaN(a)||a===void 0?e.localeCompare(r):-1;if(Number.isNaN(a)||a===void 0)return 1;if(i!==a)return i-a}return 0}function rk(e){try{return Kb(e)}catch{return[]}}var Ne,Bt,ri,Ht,zb,ti,Qb,Ke=Ff(()=>{"use strict";Ne="redskilled.bundle.min.mjs",Bt="redskilled-daemon-entry-unresolved",ri="REDSKILLED_BIN";Ht=class extends Error{code=Bt;searched;callerEntry;constructor(r){super(`${Bt}: no published ${Ne} found to spawn the redskilled daemon from${r.callerEntry?` (caller entry: ${r.callerEntry}, which is NOT used as a fallback)`:""}
|
|
4
4
|
searched:
|
|
5
5
|
${r.searched.map(t=>` ${t}`).join(`
|
|
6
|
-
`)}`),this.name="RedskilledDaemonEntryError",this.searched=r.searched,r.callerEntry!=null&&(this.callerEntry=r.callerEntry)}};Hk=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,ri=/^redskilled-(.+)\.bundle\.min\.mjs$/,qk=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});var Pi=Ol((Ti,xi)=>{(function(e,r){typeof Ti=="object"&&typeof xi<"u"?xi.exports=r():typeof define=="function"&&define.amd?define(r):e.Bottleneck=r()})(Ti,function(){"use strict";var e=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function r(D){return D&&D.default||D}var t=function(D,k,g={}){var b,R,w;for(b in k)w=k[b],g[b]=(R=D[b])!=null?R:w;return g},n=function(D,k,g={}){var b,R;for(b in D)R=D[b],k[b]!==void 0&&(g[b]=R);return g},o={load:t,overwrite:n},s;s=class{constructor(k,g){this.incr=k,this.decr=g,this._first=null,this._last=null,this.length=0}push(k){var g;this.length++,typeof this.incr=="function"&&this.incr(),g={value:k,prev:this._last,next:null},this._last!=null?(this._last.next=g,this._last=g):this._first=this._last=g}shift(){var k;if(this._first!=null)return this.length--,typeof this.decr=="function"&&this.decr(),k=this._first.value,(this._first=this._first.next)!=null?this._first.prev=null:this._last=null,k}first(){if(this._first!=null)return this._first.value}getArray(){var k,g,b;for(k=this._first,b=[];k!=null;)b.push((g=k,k=k.next,g.value));return b}forEachShift(k){var g;for(g=this.shift();g!=null;)k(g),g=this.shift()}debug(){var k,g,b,R,w;for(k=this._first,w=[];k!=null;)w.push((g=k,k=k.next,{value:g.value,prev:(b=g.prev)!=null?b.value:void 0,next:(R=g.next)!=null?R.value:void 0}));return w}};var i=s,a;a=class{constructor(k){if(this.instance=k,this._events={},this.instance.on!=null||this.instance.once!=null||this.instance.removeAllListeners!=null)throw new Error("An Emitter already exists for this object");this.instance.on=(g,b)=>this._addListener(g,"many",b),this.instance.once=(g,b)=>this._addListener(g,"once",b),this.instance.removeAllListeners=(g=null)=>g!=null?delete this._events[g]:this._events={}}_addListener(k,g,b){var R;return(R=this._events)[k]==null&&(R[k]=[]),this._events[k].push({cb:b,status:g}),this.instance}listenerCount(k){return this._events[k]!=null?this._events[k].length:0}async trigger(k,...g){var b,R;try{return k!=="debug"&&this.trigger("debug",`Event triggered: ${k}`,g),this._events[k]==null?void 0:(this._events[k]=this._events[k].filter(function(w){return w.status!=="none"}),R=this._events[k].map(async w=>{var T,O;if(w.status!=="none"){w.status==="once"&&(w.status="none");try{return O=typeof w.cb=="function"?w.cb(...g):void 0,typeof O?.then=="function"?await O:O}catch($){return T=$,this.trigger("error",T),null}}}),(await Promise.all(R)).find(function(w){return w!=null}))}catch(w){return b=w,this.trigger("error",b),null}}};var l=a,d,c,u;d=i,c=l,u=class{constructor(k){var g;this.Events=new c(this),this._length=0,this._lists=function(){var b,R,w;for(w=[],g=b=1,R=k;1<=R?b<=R:b>=R;g=1<=R?++b:--b)w.push(new d(()=>this.incr(),()=>this.decr()));return w}.call(this)}incr(){if(this._length++===0)return this.Events.trigger("leftzero")}decr(){if(--this._length===0)return this.Events.trigger("zero")}push(k){return this._lists[k.options.priority].push(k)}queued(k){return k!=null?this._lists[k].length:this._length}shiftAll(k){return this._lists.forEach(function(g){return g.forEachShift(k)})}getFirst(k=this._lists){var g,b,R;for(g=0,b=k.length;g<b;g++)if(R=k[g],R.length>0)return R;return[]}shiftLastFrom(k){return this.getFirst(this._lists.slice(k).reverse()).shift()}};var m=u,h;h=class extends Error{};var f=h,S,_,v,C,H;C=10,_=5,H=o,S=f,v=class{constructor(k,g,b,R,w,T,O,$){this.task=k,this.args=g,this.rejectOnDrop=w,this.Events=T,this._states=O,this.Promise=$,this.options=H.load(b,R),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===R.id&&(this.options.id=`${this.options.id}-${this._randomIndex()}`),this.promise=new this.Promise((q,B)=>{this._resolve=q,this._reject=B}),this.retryCount=0}_sanitizePriority(k){var g;return g=~~k!==k?_:k,g<0?0:g>C-1?C-1:g}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:k,message:g="This job has been dropped by Bottleneck"}={}){return this._states.remove(this.options.id)?(this.rejectOnDrop&&this._reject(k??new S(g)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0):!1}_assertStatus(k){var g;if(g=this._states.jobStatus(this.options.id),!(g===k||k==="DONE"&&g===null))throw new S(`Invalid job status ${g}, expected ${k}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`)}doReceive(){return this._states.start(this.options.id),this.Events.trigger("received",{args:this.args,options:this.options})}doQueue(k,g){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:k,blocked:g})}doRun(){return this.retryCount===0?(this._assertStatus("QUEUED"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),this.Events.trigger("scheduled",{args:this.args,options:this.options})}async doExecute(k,g,b,R){var w,T,O;this.retryCount===0?(this._assertStatus("RUNNING"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),T={args:this.args,options:this.options,retryCount:this.retryCount},this.Events.trigger("executing",T);try{if(O=await(k!=null?k.schedule(this.options,this.task,...this.args):this.task(...this.args)),g())return this.doDone(T),await R(this.options,T),this._assertStatus("DONE"),this._resolve(O)}catch($){return w=$,this._onFailure(w,T,g,b,R)}}doExpire(k,g,b){var R,w;return this._states.jobStatus(this.options.id==="RUNNING")&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),w={args:this.args,options:this.options,retryCount:this.retryCount},R=new S(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(R,w,k,g,b)}async _onFailure(k,g,b,R,w){var T,O;if(b())return T=await this.Events.trigger("failed",k,g),T!=null?(O=~~T,this.Events.trigger("retry",`Retrying ${this.options.id} after ${O} ms`,g),this.retryCount++,R(O)):(this.doDone(g),await w(this.options,g),this._assertStatus("DONE"),this._reject(k))}doDone(k){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",k)}};var L=v,Q,ee,le;le=o,Q=f,ee=class{constructor(k,g,b){this.instance=k,this.storeOptions=g,this.clientId=this.instance._randomIndex(),le.load(b,b,this),this._nextRequest=this._lastReservoirRefresh=this._lastReservoirIncrease=Date.now(),this._running=0,this._done=0,this._unblockTime=0,this.ready=this.Promise.resolve(),this.clients={},this._startHeartbeat()}_startHeartbeat(){var k;return this.heartbeat==null&&(this.storeOptions.reservoirRefreshInterval!=null&&this.storeOptions.reservoirRefreshAmount!=null||this.storeOptions.reservoirIncreaseInterval!=null&&this.storeOptions.reservoirIncreaseAmount!=null)?typeof(k=this.heartbeat=setInterval(()=>{var g,b,R,w,T;if(w=Date.now(),this.storeOptions.reservoirRefreshInterval!=null&&w>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=w,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),this.storeOptions.reservoirIncreaseInterval!=null&&w>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval&&({reservoirIncreaseAmount:g,reservoirIncreaseMaximum:R,reservoir:T}=this.storeOptions,this._lastReservoirIncrease=w,b=R!=null?Math.min(g,R-T):g,b>0))return this.storeOptions.reservoir+=b,this.instance._drainAll(this.computeCapacity())},this.heartbeatInterval)).unref=="function"?k.unref():void 0:clearInterval(this.heartbeat)}async __publish__(k){return await this.yieldLoop(),this.instance.Events.trigger("message",k.toString())}async __disconnect__(k){return await this.yieldLoop(),clearInterval(this.heartbeat),this.Promise.resolve()}yieldLoop(k=0){return new this.Promise(function(g,b){return setTimeout(g,k)})}computePenalty(){var k;return(k=this.storeOptions.penalty)!=null?k:15*this.storeOptions.minTime||5e3}async __updateSettings__(k){return await this.yieldLoop(),le.overwrite(k,k,this.storeOptions),this._startHeartbeat(),this.instance._drainAll(this.computeCapacity()),!0}async __running__(){return await this.yieldLoop(),this._running}async __queued__(){return await this.yieldLoop(),this.instance.queued()}async __done__(){return await this.yieldLoop(),this._done}async __groupCheck__(k){return await this.yieldLoop(),this._nextRequest+this.timeout<k}computeCapacity(){var k,g;return{maxConcurrent:k,reservoir:g}=this.storeOptions,k!=null&&g!=null?Math.min(k-this._running,g):k!=null?k-this._running:g??null}conditionsCheck(k){var g;return g=this.computeCapacity(),g==null||k<=g}async __incrementReservoir__(k){var g;return await this.yieldLoop(),g=this.storeOptions.reservoir+=k,this.instance._drainAll(this.computeCapacity()),g}async __currentReservoir__(){return await this.yieldLoop(),this.storeOptions.reservoir}isBlocked(k){return this._unblockTime>=k}check(k,g){return this.conditionsCheck(k)&&this._nextRequest-g<=0}async __check__(k){var g;return await this.yieldLoop(),g=Date.now(),this.check(k,g)}async __register__(k,g,b){var R,w;return await this.yieldLoop(),R=Date.now(),this.conditionsCheck(g)?(this._running+=g,this.storeOptions.reservoir!=null&&(this.storeOptions.reservoir-=g),w=Math.max(this._nextRequest-R,0),this._nextRequest=R+w+this.storeOptions.minTime,{success:!0,wait:w,reservoir:this.storeOptions.reservoir}):{success:!1}}strategyIsBlock(){return this.storeOptions.strategy===3}async __submit__(k,g){var b,R,w;if(await this.yieldLoop(),this.storeOptions.maxConcurrent!=null&&g>this.storeOptions.maxConcurrent)throw new Q(`Impossible to add a job having a weight of ${g} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`);return R=Date.now(),w=this.storeOptions.highWater!=null&&k===this.storeOptions.highWater&&!this.check(g,R),b=this.strategyIsBlock()&&(w||this.isBlocked(R)),b&&(this._unblockTime=R+this.computePenalty(),this._nextRequest=this._unblockTime+this.storeOptions.minTime,this.instance._dropAllQueued()),{reachedHWM:w,blocked:b,strategy:this.storeOptions.strategy}}async __free__(k,g){return await this.yieldLoop(),this._running-=g,this._done+=g,this.instance._drainAll(this.computeCapacity()),{running:this._running}}};var Ye=ee,Lr,mt;Lr=f,mt=class{constructor(k){this.status=k,this._jobs={},this.counts=this.status.map(function(){return 0})}next(k){var g,b;if(g=this._jobs[k],b=g+1,g!=null&&b<this.status.length)return this.counts[g]--,this.counts[b]++,this._jobs[k]++;if(g!=null)return this.counts[g]--,delete this._jobs[k]}start(k){var g;return g=0,this._jobs[k]=g,this.counts[g]++}remove(k){var g;return g=this._jobs[k],g!=null&&(this.counts[g]--,delete this._jobs[k]),g!=null}jobStatus(k){var g;return(g=this.status[this._jobs[k]])!=null?g:null}statusJobs(k){var g,b,R,w,T;if(k!=null){if(b=this.status.indexOf(k),b<0)throw new Lr(`status must be one of ${this.status.join(", ")}`);R=this._jobs,w=[];for(g in R)T=R[g],T===b&&w.push(g);return w}else return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce((k,g,b)=>(k[this.status[b]]=g,k),{})}};var Sn=mt,gt,ft;gt=i,ft=class{constructor(k,g){this.schedule=this.schedule.bind(this),this.name=k,this.Promise=g,this._running=0,this._queue=new gt}isEmpty(){return this._queue.length===0}async _tryToRun(){var k,g,b,R,w,T,O;if(this._running<1&&this._queue.length>0)return this._running++,{task:O,args:k,resolve:w,reject:R}=this._queue.shift(),g=await async function(){try{return T=await O(...k),function(){return w(T)}}catch($){return b=$,function(){return R(b)}}}(),this._running--,this._tryToRun(),g()}schedule(k,...g){var b,R,w;return w=R=null,b=new this.Promise(function(T,O){return w=T,R=O}),this._queue.push({task:k,args:g,resolve:w,reject:R}),this._tryToRun(),b}};var Tn=ft,xn="2.19.5",zo={version:xn},Pn=Object.freeze({version:xn,default:zo}),ht=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),yt=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),he=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),kt,pr,De,mr,Ir,Xe;Xe=o,kt=l,mr=ht,De=yt,Ir=he,pr=function(){class D{constructor(g={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=g,Xe.load(this.limiterOptions,this.defaults,this),this.Events=new kt(this),this.instances={},this.Bottleneck=Mr,this._startAutoCleanup(),this.sharedConnection=this.connection!=null,this.connection==null&&(this.limiterOptions.datastore==="redis"?this.connection=new mr(Object.assign({},this.limiterOptions,{Events:this.Events})):this.limiterOptions.datastore==="ioredis"&&(this.connection=new De(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(g=""){var b;return(b=this.instances[g])!=null?b:(()=>{var R;return R=this.instances[g]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${g}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",R,g),R})()}async deleteKey(g=""){var b,R;return R=this.instances[g],this.connection&&(b=await this.connection.__runCommand__(["del",...Ir.allKeys(`${this.id}-${g}`)])),R!=null&&(delete this.instances[g],await R.disconnect()),R!=null||b>0}limiters(){var g,b,R,w;b=this.instances,R=[];for(g in b)w=b[g],R.push({key:g,limiter:w});return R}keys(){return Object.keys(this.instances)}async clusterKeys(){var g,b,R,w,T,O,$,q,B;if(this.connection==null)return this.Promise.resolve(this.keys());for(O=[],g=null,B=`b_${this.id}-`.length,b=9;g!==0;)for([q,R]=await this.connection.__runCommand__(["scan",g??0,"match",`b_${this.id}-*_settings`,"count",1e4]),g=~~q,w=0,$=R.length;w<$;w++)T=R[w],O.push(T.slice(B,-b));return O}_startAutoCleanup(){var g;return clearInterval(this.interval),typeof(g=this.interval=setInterval(async()=>{var b,R,w,T,O,$;O=Date.now(),w=this.instances,T=[];for(R in w){$=w[R];try{await $._store.__groupCheck__(O)?T.push(this.deleteKey(R)):T.push(void 0)}catch(q){b=q,T.push($.Events.trigger("error",b))}}return T},this.timeout/2)).unref=="function"?g.unref():void 0}updateSettings(g={}){if(Xe.overwrite(g,this.defaults,this),Xe.overwrite(g,g,this.limiterOptions),g.timeout!=null)return this._startAutoCleanup()}disconnect(g=!0){var b;if(!this.sharedConnection)return(b=this.connection)!=null?b.disconnect(g):void 0}}return D.prototype.defaults={timeout:1e3*60*5,connection:null,Promise,id:"group-key"},D}.call(e);var On=pr,An,N,we;we=o,N=l,An=function(){class D{constructor(g={}){this.options=g,we.load(this.options,this.defaults,this),this.Events=new N(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise((g,b)=>this._resolve=g)}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(g){var b;return this._arr.push(g),b=this._promise,this._arr.length===this.maxSize?this._flush():this.maxTime!=null&&this._arr.length===1&&(this._timeout=setTimeout(()=>this._flush(),this.maxTime)),b}}return D.prototype.defaults={maxTime:null,maxSize:null,Promise},D}.call(e);var Ze=An,$r=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),bt=r(Pn),gr,fr,_t,hr,W,Y,Gr,Rt,Cr,Nr,de,wt=[].splice;Y=10,fr=5,de=o,Gr=m,hr=L,W=Ye,Rt=$r,_t=l,Cr=Sn,Nr=Tn,gr=function(){class D{constructor(g={},...b){var R,w;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(g,b),de.load(g,this.instanceDefaults,this),this._queues=new Gr(Y),this._scheduled={},this._states=new Cr(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new _t(this),this._submitLock=new Nr("submit",this.Promise),this._registerLock=new Nr("register",this.Promise),w=de.load(g,this.storeDefaults,{}),this._store=function(){if(this.datastore==="redis"||this.datastore==="ioredis"||this.connection!=null)return R=de.load(g,this.redisStoreDefaults,{}),new Rt(this,w,R);if(this.datastore==="local")return R=de.load(g,this.localStoreDefaults,{}),new W(this,w,R);throw new D.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}.call(this),this._queues.on("leftzero",()=>{var T;return(T=this._store.heartbeat)!=null&&typeof T.ref=="function"?T.ref():void 0}),this._queues.on("zero",()=>{var T;return(T=this._store.heartbeat)!=null&&typeof T.unref=="function"?T.unref():void 0})}_validateOptions(g,b){if(!(g!=null&&typeof g=="object"&&b.length===0))throw new D.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.")}ready(){return this._store.ready}clients(){return this._store.clients}channel(){return`b_${this.id}`}channel_client(){return`b_${this.id}_${this._store.clientId}`}publish(g){return this._store.__publish__(g)}disconnect(g=!0){return this._store.__disconnect__(g)}chain(g){return this._limiter=g,this}queued(g){return this._queues.queued(g)}clusterQueued(){return this._store.__queued__()}empty(){return this.queued()===0&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(g){return this._states.jobStatus(g)}jobs(g){return this._states.statusJobs(g)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(g=1){return this._store.__check__(g)}_clearGlobalState(g){return this._scheduled[g]!=null?(clearTimeout(this._scheduled[g].expiration),delete this._scheduled[g],!0):!1}async _free(g,b,R,w){var T,O;try{if({running:O}=await this._store.__free__(g,R.weight),this.Events.trigger("debug",`Freed ${R.id}`,w),O===0&&this.empty())return this.Events.trigger("idle")}catch($){return T=$,this.Events.trigger("error",T)}}_run(g,b,R){var w,T,O;return b.doRun(),w=this._clearGlobalState.bind(this,g),O=this._run.bind(this,g,b),T=this._free.bind(this,g,b),this._scheduled[g]={timeout:setTimeout(()=>b.doExecute(this._limiter,w,O,T),R),expiration:b.options.expiration!=null?setTimeout(function(){return b.doExpire(w,O,T)},R+b.options.expiration):void 0,job:b}}_drainOne(g){return this._registerLock.schedule(()=>{var b,R,w,T,O;return this.queued()===0?this.Promise.resolve(null):(O=this._queues.getFirst(),{options:T,args:b}=w=O.first(),g!=null&&T.weight>g?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${T.id}`,{args:b,options:T}),R=this._randomIndex(),this._store.__register__(R,T.weight,T.expiration).then(({success:$,wait:q,reservoir:B})=>{var X;return this.Events.trigger("debug",`Drained ${T.id}`,{success:$,args:b,options:T}),$?(O.shift(),X=this.empty(),X&&this.Events.trigger("empty"),B===0&&this.Events.trigger("depleted",X),this._run(R,w,q),this.Promise.resolve(T.weight)):this.Promise.resolve(null)})))})}_drainAll(g,b=0){return this._drainOne(g).then(R=>{var w;return R!=null?(w=g!=null?g-R:g,this._drainAll(w,b+R)):this.Promise.resolve(b)}).catch(R=>this.Events.trigger("error",R))}_dropAllQueued(g){return this._queues.shiftAll(function(b){return b.doDrop({message:g})})}stop(g={}){var b,R;return g=de.load(g,this.stopDefaults),R=w=>{var T;return T=()=>{var O;return O=this._states.counts,O[0]+O[1]+O[2]+O[3]===w},new this.Promise((O,$)=>T()?O():this.on("done",()=>{if(T())return this.removeAllListeners("done"),O()}))},b=g.dropWaitingJobs?(this._run=function(w,T){return T.doDrop({message:g.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule(()=>this._submitLock.schedule(()=>{var w,T,O;T=this._scheduled;for(w in T)O=T[w],this.jobStatus(O.job.options.id)==="RUNNING"&&(clearTimeout(O.timeout),clearTimeout(O.expiration),O.job.doDrop({message:g.dropErrorMessage}));return this._dropAllQueued(g.dropErrorMessage),R(0)}))):this.schedule({priority:Y-1,weight:0},()=>R(1)),this._receive=function(w){return w._reject(new D.prototype.BottleneckError(g.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new D.prototype.BottleneckError("stop() has already been called")),b}async _addToQueue(g){var b,R,w,T,O,$,q;({args:b,options:T}=g);try{({reachedHWM:O,blocked:R,strategy:q}=await this._store.__submit__(this.queued(),T.weight))}catch(B){return w=B,this.Events.trigger("debug",`Could not queue ${T.id}`,{args:b,options:T,error:w}),g.doDrop({error:w}),!1}return R?(g.doDrop(),!0):O&&($=q===D.prototype.strategy.LEAK?this._queues.shiftLastFrom(T.priority):q===D.prototype.strategy.OVERFLOW_PRIORITY?this._queues.shiftLastFrom(T.priority+1):q===D.prototype.strategy.OVERFLOW?g:void 0,$?.doDrop(),$==null||q===D.prototype.strategy.OVERFLOW)?($==null&&g.doDrop(),O):(g.doQueue(O,R),this._queues.push(g),await this._drainAll(),O)}_receive(g){return this._states.jobStatus(g.options.id)!=null?(g._reject(new D.prototype.BottleneckError(`A job with the same id already exists (id=${g.options.id})`)),!1):(g.doReceive(),this._submitLock.schedule(this._addToQueue,g))}submit(...g){var b,R,w,T,O,$,q;return typeof g[0]=="function"?(O=g,[R,...g]=O,[b]=wt.call(g,-1),T=de.load({},this.jobDefaults)):($=g,[T,R,...g]=$,[b]=wt.call(g,-1),T=de.load(T,this.jobDefaults)),q=(...B)=>new this.Promise(function(X,vt){return R(...B,function(...Be){return(Be[0]!=null?vt:X)(Be)})}),w=new hr(q,g,T,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),w.promise.then(function(B){return typeof b=="function"?b(...B):void 0}).catch(function(B){return Array.isArray(B)?typeof b=="function"?b(...B):void 0:typeof b=="function"?b(B):void 0}),this._receive(w)}schedule(...g){var b,R,w;return typeof g[0]=="function"?([w,...g]=g,R={}):[R,w,...g]=g,b=new hr(w,g,R,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(b),b.promise}wrap(g){var b,R;return b=this.schedule.bind(this),R=function(...w){return b(g.bind(this),...w)},R.withOptions=function(w,...T){return b(w,g,...T)},R}async updateSettings(g={}){return await this._store.__updateSettings__(de.overwrite(g,this.storeDefaults)),de.overwrite(g,this.instanceDefaults,this),this}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(g=0){return this._store.__incrementReservoir__(g)}}return D.default=D,D.Events=_t,D.version=D.prototype.version=bt.version,D.strategy=D.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},D.BottleneckError=D.prototype.BottleneckError=f,D.Group=D.prototype.Group=On,D.RedisConnection=D.prototype.RedisConnection=ht,D.IORedisConnection=D.prototype.IORedisConnection=yt,D.Batcher=D.prototype.Batcher=Ze,D.prototype.jobDefaults={priority:fr,weight:1,expiration:null,id:"<no-id>"},D.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:D.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},D.prototype.localStoreDefaults={Promise,timeout:null,heartbeatInterval:250},D.prototype.redisStoreDefaults={Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},D.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise},D.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},D}.call(e);var Mr=gr,Et=Mr;return Et})});var $u=Ol(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.format=dR;yo.parse=cR;var iR=/^[\u0009\u0020-\u007e\u0080-\u00ff]*$/,Au=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,aR=/[\\"]/g,lR=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,Du=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function dR(e){let{type:r,parameters:t}=e;if(!r||!lR.test(r))throw new TypeError(`Invalid type: ${r}`);let n=r;if(t)for(let o of Object.keys(t)){if(!Au.test(o))throw new TypeError(`Invalid parameter name: ${o}`);n+=`; ${o}=${gR(t[o])}`}return n}function cR(e,r){let t=e.length,n=Ii(e,0,t),o=n;n=Li(e,n,t);let s=$i(e,o,n),i=e.slice(o,s).toLowerCase(),a=r?.parameters===!1?new Du:mR(e,n,t);return{type:i,parameters:a}}var ju=32,Lu=9,Iu=59,uR=61,Ou=34,pR=92;function mR(e,r,t){let n=new Du;e:for(;r<t;){r=Ii(e,r+1,t);let o=r;for(;r<t;){let s=e.charCodeAt(r);if(s===Iu)continue e;if(s===uR){let i=$i(e,o,r),a=e.slice(o,i).toLowerCase();if(r=Ii(e,r+1,t),r<t&&e.charCodeAt(r)===Ou){r++;let d="";for(;r<t;){let c=e.charCodeAt(r++);if(c===Ou){r=Li(e,r,t),n[a]===void 0&&(n[a]=d);break}if(c===pR&&r<t){d+=e[r++];continue}d+=String.fromCharCode(c)}continue e}let l=r;if(r=Li(e,r,t),n[a]===void 0){let d=$i(e,l,r);n[a]=e.slice(l,d)}continue e}r++}}return n}function Li(e,r,t){for(;r<t&&e.charCodeAt(r)!==Iu;)r++;return r}function Ii(e,r,t){for(;r<t;){let n=e.charCodeAt(r);if(n!==ju&&n!==Lu)break;r++}return r}function $i(e,r,t){for(;t>r;){let n=e.charCodeAt(t-1);if(n!==ju&&n!==Lu)break;t--}return t}function gR(e){if(Au.test(e))return e;if(iR.test(e))return`"${e.replace(aR,"\\$&")}"`;throw new TypeError(`Invalid parameter value: ${e}`)}});import{execFileSync as WT}from"node:child_process";import{homedir as En}from"node:os";import{join as Jo}from"node:path";var Hr=class extends Error{constructor(r,t){super(r===0?t:`line ${r}: ${t}`),this.name="ToonError",this.line=r,this.reason=t}},kr=class extends Error{constructor(r,t){super(r===0?t:`line ${r}: ${t}`),this.name="ToonlError",this.line=r,this.reason=t}};function x(e,r){return new Hr(e,r)}function M(e,r){return new kr(e,r)}function qr(e){return e instanceof kr?e:e instanceof Hr?new kr(e.line,e.reason):new kr(0,String(e&&e.message?e.message:e))}var Al=["type","kind","event"],br="|",Dl=new Set(["order","discriminator","rows","common"]);var V=",";function Un(e){let r=e.split(`
|
|
7
|
-
`);return r.length>0&&r[r.length-1]===""&&r.pop(),r.map(t=>t.endsWith("\r")?t.slice(0,-1):t)}function
|
|
8
|
-
`;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let i=e.slice(n,n+4);if(!/^[0-9a-fA-F]{4}$/.test(i))throw
|
|
9
|
-
`),e.push(" order: ",ae(t.order.encoded,
|
|
10
|
-
`),e.push(" discriminator: ",ae(t.discriminator,
|
|
6
|
+
`)}`),this.name="RedskilledDaemonEntryError",this.searched=r.searched,r.callerEntry!=null&&(this.callerEntry=r.callerEntry)}};zb=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,ti=/^redskilled-(.+)\.bundle\.min\.mjs$/,Qb=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});var Oi=Al((xi,Pi)=>{(function(e,r){typeof xi=="object"&&typeof Pi<"u"?Pi.exports=r():typeof define=="function"&&define.amd?define(r):e.Bottleneck=r()})(xi,function(){"use strict";var e=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function r(D){return D&&D.default||D}var t=function(D,k,g={}){var _,R,w;for(_ in k)w=k[_],g[_]=(R=D[_])!=null?R:w;return g},n=function(D,k,g={}){var _,R;for(_ in D)R=D[_],k[_]!==void 0&&(g[_]=R);return g},o={load:t,overwrite:n},s;s=class{constructor(k,g){this.incr=k,this.decr=g,this._first=null,this._last=null,this.length=0}push(k){var g;this.length++,typeof this.incr=="function"&&this.incr(),g={value:k,prev:this._last,next:null},this._last!=null?(this._last.next=g,this._last=g):this._first=this._last=g}shift(){var k;if(this._first!=null)return this.length--,typeof this.decr=="function"&&this.decr(),k=this._first.value,(this._first=this._first.next)!=null?this._first.prev=null:this._last=null,k}first(){if(this._first!=null)return this._first.value}getArray(){var k,g,_;for(k=this._first,_=[];k!=null;)_.push((g=k,k=k.next,g.value));return _}forEachShift(k){var g;for(g=this.shift();g!=null;)k(g),g=this.shift()}debug(){var k,g,_,R,w;for(k=this._first,w=[];k!=null;)w.push((g=k,k=k.next,{value:g.value,prev:(_=g.prev)!=null?_.value:void 0,next:(R=g.next)!=null?R.value:void 0}));return w}};var i=s,a;a=class{constructor(k){if(this.instance=k,this._events={},this.instance.on!=null||this.instance.once!=null||this.instance.removeAllListeners!=null)throw new Error("An Emitter already exists for this object");this.instance.on=(g,_)=>this._addListener(g,"many",_),this.instance.once=(g,_)=>this._addListener(g,"once",_),this.instance.removeAllListeners=(g=null)=>g!=null?delete this._events[g]:this._events={}}_addListener(k,g,_){var R;return(R=this._events)[k]==null&&(R[k]=[]),this._events[k].push({cb:_,status:g}),this.instance}listenerCount(k){return this._events[k]!=null?this._events[k].length:0}async trigger(k,...g){var _,R;try{return k!=="debug"&&this.trigger("debug",`Event triggered: ${k}`,g),this._events[k]==null?void 0:(this._events[k]=this._events[k].filter(function(w){return w.status!=="none"}),R=this._events[k].map(async w=>{var T,O;if(w.status!=="none"){w.status==="once"&&(w.status="none");try{return O=typeof w.cb=="function"?w.cb(...g):void 0,typeof O?.then=="function"?await O:O}catch(I){return T=I,this.trigger("error",T),null}}}),(await Promise.all(R)).find(function(w){return w!=null}))}catch(w){return _=w,this.trigger("error",_),null}}};var l=a,d,c,u;d=i,c=l,u=class{constructor(k){var g;this.Events=new c(this),this._length=0,this._lists=function(){var _,R,w;for(w=[],g=_=1,R=k;1<=R?_<=R:_>=R;g=1<=R?++_:--_)w.push(new d(()=>this.incr(),()=>this.decr()));return w}.call(this)}incr(){if(this._length++===0)return this.Events.trigger("leftzero")}decr(){if(--this._length===0)return this.Events.trigger("zero")}push(k){return this._lists[k.options.priority].push(k)}queued(k){return k!=null?this._lists[k].length:this._length}shiftAll(k){return this._lists.forEach(function(g){return g.forEachShift(k)})}getFirst(k=this._lists){var g,_,R;for(g=0,_=k.length;g<_;g++)if(R=k[g],R.length>0)return R;return[]}shiftLastFrom(k){return this.getFirst(this._lists.slice(k).reverse()).shift()}};var m=u,f;f=class extends Error{};var h=f,v,y,S,G,H;G=10,y=5,H=o,v=h,S=class{constructor(k,g,_,R,w,T,O,I){this.task=k,this.args=g,this.rejectOnDrop=w,this.Events=T,this._states=O,this.Promise=I,this.options=H.load(_,R),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===R.id&&(this.options.id=`${this.options.id}-${this._randomIndex()}`),this.promise=new this.Promise((q,B)=>{this._resolve=q,this._reject=B}),this.retryCount=0}_sanitizePriority(k){var g;return g=~~k!==k?y:k,g<0?0:g>G-1?G-1:g}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:k,message:g="This job has been dropped by Bottleneck"}={}){return this._states.remove(this.options.id)?(this.rejectOnDrop&&this._reject(k??new v(g)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0):!1}_assertStatus(k){var g;if(g=this._states.jobStatus(this.options.id),!(g===k||k==="DONE"&&g===null))throw new v(`Invalid job status ${g}, expected ${k}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`)}doReceive(){return this._states.start(this.options.id),this.Events.trigger("received",{args:this.args,options:this.options})}doQueue(k,g){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:k,blocked:g})}doRun(){return this.retryCount===0?(this._assertStatus("QUEUED"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),this.Events.trigger("scheduled",{args:this.args,options:this.options})}async doExecute(k,g,_,R){var w,T,O;this.retryCount===0?(this._assertStatus("RUNNING"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),T={args:this.args,options:this.options,retryCount:this.retryCount},this.Events.trigger("executing",T);try{if(O=await(k!=null?k.schedule(this.options,this.task,...this.args):this.task(...this.args)),g())return this.doDone(T),await R(this.options,T),this._assertStatus("DONE"),this._resolve(O)}catch(I){return w=I,this._onFailure(w,T,g,_,R)}}doExpire(k,g,_){var R,w;return this._states.jobStatus(this.options.id==="RUNNING")&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),w={args:this.args,options:this.options,retryCount:this.retryCount},R=new v(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(R,w,k,g,_)}async _onFailure(k,g,_,R,w){var T,O;if(_())return T=await this.Events.trigger("failed",k,g),T!=null?(O=~~T,this.Events.trigger("retry",`Retrying ${this.options.id} after ${O} ms`,g),this.retryCount++,R(O)):(this.doDone(g),await w(this.options,g),this._assertStatus("DONE"),this._reject(k))}doDone(k){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",k)}};var L=S,Q,ee,le;le=o,Q=h,ee=class{constructor(k,g,_){this.instance=k,this.storeOptions=g,this.clientId=this.instance._randomIndex(),le.load(_,_,this),this._nextRequest=this._lastReservoirRefresh=this._lastReservoirIncrease=Date.now(),this._running=0,this._done=0,this._unblockTime=0,this.ready=this.Promise.resolve(),this.clients={},this._startHeartbeat()}_startHeartbeat(){var k;return this.heartbeat==null&&(this.storeOptions.reservoirRefreshInterval!=null&&this.storeOptions.reservoirRefreshAmount!=null||this.storeOptions.reservoirIncreaseInterval!=null&&this.storeOptions.reservoirIncreaseAmount!=null)?typeof(k=this.heartbeat=setInterval(()=>{var g,_,R,w,T;if(w=Date.now(),this.storeOptions.reservoirRefreshInterval!=null&&w>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=w,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),this.storeOptions.reservoirIncreaseInterval!=null&&w>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval&&({reservoirIncreaseAmount:g,reservoirIncreaseMaximum:R,reservoir:T}=this.storeOptions,this._lastReservoirIncrease=w,_=R!=null?Math.min(g,R-T):g,_>0))return this.storeOptions.reservoir+=_,this.instance._drainAll(this.computeCapacity())},this.heartbeatInterval)).unref=="function"?k.unref():void 0:clearInterval(this.heartbeat)}async __publish__(k){return await this.yieldLoop(),this.instance.Events.trigger("message",k.toString())}async __disconnect__(k){return await this.yieldLoop(),clearInterval(this.heartbeat),this.Promise.resolve()}yieldLoop(k=0){return new this.Promise(function(g,_){return setTimeout(g,k)})}computePenalty(){var k;return(k=this.storeOptions.penalty)!=null?k:15*this.storeOptions.minTime||5e3}async __updateSettings__(k){return await this.yieldLoop(),le.overwrite(k,k,this.storeOptions),this._startHeartbeat(),this.instance._drainAll(this.computeCapacity()),!0}async __running__(){return await this.yieldLoop(),this._running}async __queued__(){return await this.yieldLoop(),this.instance.queued()}async __done__(){return await this.yieldLoop(),this._done}async __groupCheck__(k){return await this.yieldLoop(),this._nextRequest+this.timeout<k}computeCapacity(){var k,g;return{maxConcurrent:k,reservoir:g}=this.storeOptions,k!=null&&g!=null?Math.min(k-this._running,g):k!=null?k-this._running:g??null}conditionsCheck(k){var g;return g=this.computeCapacity(),g==null||k<=g}async __incrementReservoir__(k){var g;return await this.yieldLoop(),g=this.storeOptions.reservoir+=k,this.instance._drainAll(this.computeCapacity()),g}async __currentReservoir__(){return await this.yieldLoop(),this.storeOptions.reservoir}isBlocked(k){return this._unblockTime>=k}check(k,g){return this.conditionsCheck(k)&&this._nextRequest-g<=0}async __check__(k){var g;return await this.yieldLoop(),g=Date.now(),this.check(k,g)}async __register__(k,g,_){var R,w;return await this.yieldLoop(),R=Date.now(),this.conditionsCheck(g)?(this._running+=g,this.storeOptions.reservoir!=null&&(this.storeOptions.reservoir-=g),w=Math.max(this._nextRequest-R,0),this._nextRequest=R+w+this.storeOptions.minTime,{success:!0,wait:w,reservoir:this.storeOptions.reservoir}):{success:!1}}strategyIsBlock(){return this.storeOptions.strategy===3}async __submit__(k,g){var _,R,w;if(await this.yieldLoop(),this.storeOptions.maxConcurrent!=null&&g>this.storeOptions.maxConcurrent)throw new Q(`Impossible to add a job having a weight of ${g} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`);return R=Date.now(),w=this.storeOptions.highWater!=null&&k===this.storeOptions.highWater&&!this.check(g,R),_=this.strategyIsBlock()&&(w||this.isBlocked(R)),_&&(this._unblockTime=R+this.computePenalty(),this._nextRequest=this._unblockTime+this.storeOptions.minTime,this.instance._dropAllQueued()),{reachedHWM:w,blocked:_,strategy:this.storeOptions.strategy}}async __free__(k,g){return await this.yieldLoop(),this._running-=g,this._done+=g,this.instance._drainAll(this.computeCapacity()),{running:this._running}}};var Xe=ee,$r,ht;$r=h,ht=class{constructor(k){this.status=k,this._jobs={},this.counts=this.status.map(function(){return 0})}next(k){var g,_;if(g=this._jobs[k],_=g+1,g!=null&&_<this.status.length)return this.counts[g]--,this.counts[_]++,this._jobs[k]++;if(g!=null)return this.counts[g]--,delete this._jobs[k]}start(k){var g;return g=0,this._jobs[k]=g,this.counts[g]++}remove(k){var g;return g=this._jobs[k],g!=null&&(this.counts[g]--,delete this._jobs[k]),g!=null}jobStatus(k){var g;return(g=this.status[this._jobs[k]])!=null?g:null}statusJobs(k){var g,_,R,w,T;if(k!=null){if(_=this.status.indexOf(k),_<0)throw new $r(`status must be one of ${this.status.join(", ")}`);R=this._jobs,w=[];for(g in R)T=R[g],T===_&&w.push(g);return w}else return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce((k,g,_)=>(k[this.status[_]]=g,k),{})}};var xn=ht,yt,bt;yt=i,bt=class{constructor(k,g){this.schedule=this.schedule.bind(this),this.name=k,this.Promise=g,this._running=0,this._queue=new yt}isEmpty(){return this._queue.length===0}async _tryToRun(){var k,g,_,R,w,T,O;if(this._running<1&&this._queue.length>0)return this._running++,{task:O,args:k,resolve:w,reject:R}=this._queue.shift(),g=await async function(){try{return T=await O(...k),function(){return w(T)}}catch(I){return _=I,function(){return R(_)}}}(),this._running--,this._tryToRun(),g()}schedule(k,...g){var _,R,w;return w=R=null,_=new this.Promise(function(T,O){return w=T,R=O}),this._queue.push({task:k,args:g,resolve:w,reject:R}),this._tryToRun(),_}};var Pn=bt,On="2.19.5",Qo={version:On},An=Object.freeze({version:On,default:Qo}),kt=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),_t=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),he=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Rt,gr,je,fr,Ir,Ze;Ze=o,Rt=l,fr=kt,je=_t,Ir=he,gr=function(){class D{constructor(g={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=g,Ze.load(this.limiterOptions,this.defaults,this),this.Events=new Rt(this),this.instances={},this.Bottleneck=Wr,this._startAutoCleanup(),this.sharedConnection=this.connection!=null,this.connection==null&&(this.limiterOptions.datastore==="redis"?this.connection=new fr(Object.assign({},this.limiterOptions,{Events:this.Events})):this.limiterOptions.datastore==="ioredis"&&(this.connection=new je(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(g=""){var _;return(_=this.instances[g])!=null?_:(()=>{var R;return R=this.instances[g]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${g}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",R,g),R})()}async deleteKey(g=""){var _,R;return R=this.instances[g],this.connection&&(_=await this.connection.__runCommand__(["del",...Ir.allKeys(`${this.id}-${g}`)])),R!=null&&(delete this.instances[g],await R.disconnect()),R!=null||_>0}limiters(){var g,_,R,w;_=this.instances,R=[];for(g in _)w=_[g],R.push({key:g,limiter:w});return R}keys(){return Object.keys(this.instances)}async clusterKeys(){var g,_,R,w,T,O,I,q,B;if(this.connection==null)return this.Promise.resolve(this.keys());for(O=[],g=null,B=`b_${this.id}-`.length,_=9;g!==0;)for([q,R]=await this.connection.__runCommand__(["scan",g??0,"match",`b_${this.id}-*_settings`,"count",1e4]),g=~~q,w=0,I=R.length;w<I;w++)T=R[w],O.push(T.slice(B,-_));return O}_startAutoCleanup(){var g;return clearInterval(this.interval),typeof(g=this.interval=setInterval(async()=>{var _,R,w,T,O,I;O=Date.now(),w=this.instances,T=[];for(R in w){I=w[R];try{await I._store.__groupCheck__(O)?T.push(this.deleteKey(R)):T.push(void 0)}catch(q){_=q,T.push(I.Events.trigger("error",_))}}return T},this.timeout/2)).unref=="function"?g.unref():void 0}updateSettings(g={}){if(Ze.overwrite(g,this.defaults,this),Ze.overwrite(g,g,this.limiterOptions),g.timeout!=null)return this._startAutoCleanup()}disconnect(g=!0){var _;if(!this.sharedConnection)return(_=this.connection)!=null?_.disconnect(g):void 0}}return D.prototype.defaults={timeout:1e3*60*5,connection:null,Promise,id:"group-key"},D}.call(e);var Dn=gr,jn,N,Ee;Ee=o,N=l,jn=function(){class D{constructor(g={}){this.options=g,Ee.load(this.options,this.defaults,this),this.Events=new N(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise((g,_)=>this._resolve=g)}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(g){var _;return this._arr.push(g),_=this._promise,this._arr.length===this.maxSize?this._flush():this.maxTime!=null&&this._arr.length===1&&(this._timeout=setTimeout(()=>this._flush(),this.maxTime)),_}}return D.prototype.defaults={maxTime:null,maxSize:null,Promise},D}.call(e);var er=jn,Cr=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),wt=r(An),hr,yr,Et,br,W,Y,Nr,vt,Mr,Fr,de,St=[].splice;Y=10,yr=5,de=o,Nr=m,br=L,W=Xe,vt=Cr,Et=l,Mr=xn,Fr=Pn,hr=function(){class D{constructor(g={},..._){var R,w;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(g,_),de.load(g,this.instanceDefaults,this),this._queues=new Nr(Y),this._scheduled={},this._states=new Mr(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new Et(this),this._submitLock=new Fr("submit",this.Promise),this._registerLock=new Fr("register",this.Promise),w=de.load(g,this.storeDefaults,{}),this._store=function(){if(this.datastore==="redis"||this.datastore==="ioredis"||this.connection!=null)return R=de.load(g,this.redisStoreDefaults,{}),new vt(this,w,R);if(this.datastore==="local")return R=de.load(g,this.localStoreDefaults,{}),new W(this,w,R);throw new D.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}.call(this),this._queues.on("leftzero",()=>{var T;return(T=this._store.heartbeat)!=null&&typeof T.ref=="function"?T.ref():void 0}),this._queues.on("zero",()=>{var T;return(T=this._store.heartbeat)!=null&&typeof T.unref=="function"?T.unref():void 0})}_validateOptions(g,_){if(!(g!=null&&typeof g=="object"&&_.length===0))throw new D.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.")}ready(){return this._store.ready}clients(){return this._store.clients}channel(){return`b_${this.id}`}channel_client(){return`b_${this.id}_${this._store.clientId}`}publish(g){return this._store.__publish__(g)}disconnect(g=!0){return this._store.__disconnect__(g)}chain(g){return this._limiter=g,this}queued(g){return this._queues.queued(g)}clusterQueued(){return this._store.__queued__()}empty(){return this.queued()===0&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(g){return this._states.jobStatus(g)}jobs(g){return this._states.statusJobs(g)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(g=1){return this._store.__check__(g)}_clearGlobalState(g){return this._scheduled[g]!=null?(clearTimeout(this._scheduled[g].expiration),delete this._scheduled[g],!0):!1}async _free(g,_,R,w){var T,O;try{if({running:O}=await this._store.__free__(g,R.weight),this.Events.trigger("debug",`Freed ${R.id}`,w),O===0&&this.empty())return this.Events.trigger("idle")}catch(I){return T=I,this.Events.trigger("error",T)}}_run(g,_,R){var w,T,O;return _.doRun(),w=this._clearGlobalState.bind(this,g),O=this._run.bind(this,g,_),T=this._free.bind(this,g,_),this._scheduled[g]={timeout:setTimeout(()=>_.doExecute(this._limiter,w,O,T),R),expiration:_.options.expiration!=null?setTimeout(function(){return _.doExpire(w,O,T)},R+_.options.expiration):void 0,job:_}}_drainOne(g){return this._registerLock.schedule(()=>{var _,R,w,T,O;return this.queued()===0?this.Promise.resolve(null):(O=this._queues.getFirst(),{options:T,args:_}=w=O.first(),g!=null&&T.weight>g?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${T.id}`,{args:_,options:T}),R=this._randomIndex(),this._store.__register__(R,T.weight,T.expiration).then(({success:I,wait:q,reservoir:B})=>{var X;return this.Events.trigger("debug",`Drained ${T.id}`,{success:I,args:_,options:T}),I?(O.shift(),X=this.empty(),X&&this.Events.trigger("empty"),B===0&&this.Events.trigger("depleted",X),this._run(R,w,q),this.Promise.resolve(T.weight)):this.Promise.resolve(null)})))})}_drainAll(g,_=0){return this._drainOne(g).then(R=>{var w;return R!=null?(w=g!=null?g-R:g,this._drainAll(w,_+R)):this.Promise.resolve(_)}).catch(R=>this.Events.trigger("error",R))}_dropAllQueued(g){return this._queues.shiftAll(function(_){return _.doDrop({message:g})})}stop(g={}){var _,R;return g=de.load(g,this.stopDefaults),R=w=>{var T;return T=()=>{var O;return O=this._states.counts,O[0]+O[1]+O[2]+O[3]===w},new this.Promise((O,I)=>T()?O():this.on("done",()=>{if(T())return this.removeAllListeners("done"),O()}))},_=g.dropWaitingJobs?(this._run=function(w,T){return T.doDrop({message:g.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule(()=>this._submitLock.schedule(()=>{var w,T,O;T=this._scheduled;for(w in T)O=T[w],this.jobStatus(O.job.options.id)==="RUNNING"&&(clearTimeout(O.timeout),clearTimeout(O.expiration),O.job.doDrop({message:g.dropErrorMessage}));return this._dropAllQueued(g.dropErrorMessage),R(0)}))):this.schedule({priority:Y-1,weight:0},()=>R(1)),this._receive=function(w){return w._reject(new D.prototype.BottleneckError(g.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new D.prototype.BottleneckError("stop() has already been called")),_}async _addToQueue(g){var _,R,w,T,O,I,q;({args:_,options:T}=g);try{({reachedHWM:O,blocked:R,strategy:q}=await this._store.__submit__(this.queued(),T.weight))}catch(B){return w=B,this.Events.trigger("debug",`Could not queue ${T.id}`,{args:_,options:T,error:w}),g.doDrop({error:w}),!1}return R?(g.doDrop(),!0):O&&(I=q===D.prototype.strategy.LEAK?this._queues.shiftLastFrom(T.priority):q===D.prototype.strategy.OVERFLOW_PRIORITY?this._queues.shiftLastFrom(T.priority+1):q===D.prototype.strategy.OVERFLOW?g:void 0,I?.doDrop(),I==null||q===D.prototype.strategy.OVERFLOW)?(I==null&&g.doDrop(),O):(g.doQueue(O,R),this._queues.push(g),await this._drainAll(),O)}_receive(g){return this._states.jobStatus(g.options.id)!=null?(g._reject(new D.prototype.BottleneckError(`A job with the same id already exists (id=${g.options.id})`)),!1):(g.doReceive(),this._submitLock.schedule(this._addToQueue,g))}submit(...g){var _,R,w,T,O,I,q;return typeof g[0]=="function"?(O=g,[R,...g]=O,[_]=St.call(g,-1),T=de.load({},this.jobDefaults)):(I=g,[T,R,...g]=I,[_]=St.call(g,-1),T=de.load(T,this.jobDefaults)),q=(...B)=>new this.Promise(function(X,xt){return R(...B,function(...He){return(He[0]!=null?xt:X)(He)})}),w=new br(q,g,T,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),w.promise.then(function(B){return typeof _=="function"?_(...B):void 0}).catch(function(B){return Array.isArray(B)?typeof _=="function"?_(...B):void 0:typeof _=="function"?_(B):void 0}),this._receive(w)}schedule(...g){var _,R,w;return typeof g[0]=="function"?([w,...g]=g,R={}):[R,w,...g]=g,_=new br(w,g,R,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(_),_.promise}wrap(g){var _,R;return _=this.schedule.bind(this),R=function(...w){return _(g.bind(this),...w)},R.withOptions=function(w,...T){return _(w,g,...T)},R}async updateSettings(g={}){return await this._store.__updateSettings__(de.overwrite(g,this.storeDefaults)),de.overwrite(g,this.instanceDefaults,this),this}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(g=0){return this._store.__incrementReservoir__(g)}}return D.default=D,D.Events=Et,D.version=D.prototype.version=wt.version,D.strategy=D.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},D.BottleneckError=D.prototype.BottleneckError=h,D.Group=D.prototype.Group=Dn,D.RedisConnection=D.prototype.RedisConnection=kt,D.IORedisConnection=D.prototype.IORedisConnection=_t,D.Batcher=D.prototype.Batcher=er,D.prototype.jobDefaults={priority:yr,weight:1,expiration:null,id:"<no-id>"},D.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:D.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},D.prototype.localStoreDefaults={Promise,timeout:null,heartbeatInterval:250},D.prototype.redisStoreDefaults={Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},D.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise},D.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},D}.call(e);var Wr=hr,Tt=Wr;return Tt})});var Cu=Al(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.format=gR;ko.parse=fR;var uR=/^[\u0009\u0020-\u007e\u0080-\u00ff]*$/,ju=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,pR=/[\\"]/g,mR=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,Lu=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function gR(e){let{type:r,parameters:t}=e;if(!r||!mR.test(r))throw new TypeError(`Invalid type: ${r}`);let n=r;if(t)for(let o of Object.keys(t)){if(!ju.test(o))throw new TypeError(`Invalid parameter name: ${o}`);n+=`; ${o}=${kR(t[o])}`}return n}function fR(e,r){let t=e.length,n=$i(e,0,t),o=n;n=Gi(e,n,t);let s=Ii(e,o,n),i=e.slice(o,s).toLowerCase(),a=r?.parameters===!1?new Lu:bR(e,n,t);return{type:i,parameters:a}}var Gu=32,$u=9,Iu=59,hR=61,Du=34,yR=92;function bR(e,r,t){let n=new Lu;e:for(;r<t;){r=$i(e,r+1,t);let o=r;for(;r<t;){let s=e.charCodeAt(r);if(s===Iu)continue e;if(s===hR){let i=Ii(e,o,r),a=e.slice(o,i).toLowerCase();if(r=$i(e,r+1,t),r<t&&e.charCodeAt(r)===Du){r++;let d="";for(;r<t;){let c=e.charCodeAt(r++);if(c===Du){r=Gi(e,r,t),n[a]===void 0&&(n[a]=d);break}if(c===yR&&r<t){d+=e[r++];continue}d+=String.fromCharCode(c)}continue e}let l=r;if(r=Gi(e,r,t),n[a]===void 0){let d=Ii(e,l,r);n[a]=e.slice(l,d)}continue e}r++}}return n}function Gi(e,r,t){for(;r<t&&e.charCodeAt(r)!==Iu;)r++;return r}function $i(e,r,t){for(;r<t;){let n=e.charCodeAt(r);if(n!==Gu&&n!==$u)break;r++}return r}function Ii(e,r,t){for(;t>r;){let n=e.charCodeAt(t-1);if(n!==Gu&&n!==$u)break;t--}return t}function kR(e){if(ju.test(e))return e;if(uR.test(e))return`"${e.replace(pR,"\\$&")}"`;throw new TypeError(`Invalid parameter value: ${e}`)}});import{execFileSync as zT}from"node:child_process";import{homedir as Sn}from"node:os";import{join as zo}from"node:path";var Vr=class extends Error{constructor(r,t){super(r===0?t:`line ${r}: ${t}`),this.name="ToonError",this.line=r,this.reason=t}},_r=class extends Error{constructor(r,t){super(r===0?t:`line ${r}: ${t}`),this.name="ToonlError",this.line=r,this.reason=t}};function x(e,r){return new Vr(e,r)}function M(e,r){return new _r(e,r)}function Kr(e){return e instanceof _r?e:e instanceof Vr?new _r(e.line,e.reason):new _r(0,String(e&&e.message?e.message:e))}var Dl=["type","kind","event"],Rr="|",jl=new Set(["order","discriminator","rows","common"]);var V=",";function Hn(e){let r=e.split(`
|
|
7
|
+
`);return r.length>0&&r[r.length-1]===""&&r.pop(),r.map(t=>t.endsWith("\r")?t.slice(0,-1):t)}function Le(e){return x(e,"invalid quoted string")}function be(e,r){if(e==="")return"";if(e.startsWith('"'))return $l(e,r);if(e.includes('"'))throw Le(r);return e==="true"?!0:e==="false"?!1:e==="null"?null:Bf(e)?Number(e):e}function Se(e,r){let t=e.trim();if(t.startsWith('"'))return[$l(t,r),!0];if(t.includes('"')||/\s/.test(t))throw x(r,"expected non-empty field name");return[t,!1]}var Ll=/["\\\u0000-\u0008\u000a-\u001f]/g;function $l(e,r){if(e.charCodeAt(0)!==34)throw Le(r);let t="",n=1;for(;n<e.length;){Ll.lastIndex=n;let o=Ll.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(n,o.index);throw Le(r)}if(o[0]!=="\\")throw Le(r);t+=e.slice(n,o.index);let s=e[o.index+1];switch(n=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(n,n+4);if(!/^[0-9a-fA-F]{4}$/.test(i))throw Le(r);let a=Number.parseInt(i,16);if(a>=55296&&a<=57343)throw Le(r);t+=String.fromCharCode(a),n+=4;break}default:throw Le(r)}}throw Le(r)}function Il(e,r,t){for(;;){let n=e.indexOf('"',r),o=e.indexOf("\\",r);if(o!==-1&&(n===-1||o<n)){if(o===e.length-1)throw Le(t);r=o+2;continue}if(n===-1)throw Le(t);return n+1}}function Te(e,r,t){if(e==="")return[];let n=[],o=0,s=0;for(;s<e.length;){let i=e.indexOf('"',s),a=e.indexOf(r,s);if(a!==-1&&(i===-1||a<i))n.push(e.slice(o,a).trim()),o=a+1,s=a+1;else if(i!==-1)s=Il(e,i+1,t);else break}return n.push(e.slice(o).trim()),n}function ie(e,r,t){let n=0;for(;n<e.length;){let o=e.indexOf('"',n),s=e.indexOf(r,n);if(s!==-1&&(o===-1||s<o))return s;if(o===-1)return-1;n=Il(e,o+1,t)}return-1}function Bf(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Hf(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function qf(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw x(0,"number is not representable in TOON");return String(e)}function Ge(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function ae(e,r){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return qf(e);if(typeof e=="string")return Kf(e,r);throw x(0,"not a primitive")}function Vf(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function te(e){return Vf(e)?e:qn(e)}function Kf(e,r){return ds(e,r)?qn(e):e}function ds(e,r){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Hf(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(r)||e.startsWith("-")}var Gl=/["\\\u0000-\u001f]/g;function qn(e){let r='"',t=0;Gl.lastIndex=0;let n;for(;(n=Gl.exec(e))!==null;){let o=e.charCodeAt(n.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")}`,r+=e.slice(t,n.index)+s,t=n.index+1}return`${r}${e.slice(t)}"`}function xe(e,r,t){Object.defineProperty(e,r,{value:t,writable:!0,enumerable:!0,configurable:!0})}function K(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cl(e={}){let r=e.maxDepth??1e3,t=r===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(r));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 Nl(e,r){let t=[],n=!1;return Hn(e).forEach((o,s)=>{let i=s+1;if(o.trim()===""){n=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw x(i,"invalid indentation");if(r.strict&&a%r.indent!==0)throw x(i,"invalid indentation");let l=Math.floor(a/r.indent);$e(l,i,r),t.push({number:i,depth:l,content:o.slice(a),blankBefore:n}),n=!1}),t}function $e(e,r,t){if(t.maxDepth!==0&&e>t.maxDepth)throw x(r,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function It(e,r,t){if(t.maxDepth===0)return;let n=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==="{"?(n+=1,$e(n,r,t)):i==="}"&&(n=Math.max(0,n-1)))}}function Wl(e){if(!K(e)||Object.keys(e).length===0)return e;let r={};for(let[t,n]of Object.entries(e)){let o=Jf(n,1);if(o===void 0)return e;xe(r,t,o)}return r}function Jf(e,r){if(!K(e)||!zf(e))return;let{order:t,discriminator:n,rows:o}=e;if(typeof t!="string"||typeof n!="string"||!Number.isSafeInteger(o)||o<0)throw ne(r);let s=Qf(t,o,r),i=e.common,a=i===void 0?Array.from({length:o},()=>({})):i;if(!Array.isArray(a)||a.length!==o||!a.every(K))throw Ul(r);let l=new Map;for(let[u,m]of Object.entries(e))if(!jl.has(u)){if(!Array.isArray(m)||!m.every(K))throw ne(r);l.set(u,m)}if(l.size===0)throw ne(r);let d=new Map,c=s.map((u,m)=>{let f=l.get(u);if(f===void 0)throw cs(r);let h=d.get(u)??0,v=f[h];if(v===void 0)throw cs(r);return d.set(u,h+1),Yf(n,u,a[m],v,r)});for(let[u,m]of l)if((d.get(u)??0)!==m.length)throw cs(r);return c}function zf(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function Qf(e,r,t){if(!e.startsWith("cycle("))throw ne(t);let n=e.slice(6),o=n.indexOf(")*");if(o===-1)throw ne(t);let s=n.slice(0,o),i=n.slice(o+2);if(s===""||i.includes("+tail("))throw ne(t);let a=s.split(",").map(c=>rh(c,t));if(a.some(c=>c===""))throw ne(t);let l=eh(i,t),d=a.length*l;if(!Number.isSafeInteger(d))throw ne(t);if(d!==r)throw Ul(t);return Array.from({length:d},(c,u)=>a[u%a.length])}function Yf(e,r,t,n,o){let s={};xe(s,e,r);for(let[i,a]of Object.entries(t??{})){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw ne(o);xe(s,i,a)}for(let[i,a]of Object.entries(Xf(n,o))){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw ne(o);xe(s,i,a)}return s}function Xf(e,r){let t={};for(let[n,o]of Object.entries(e))Zf(t,n.split("."),o,r);return Vn(t,r)}function Zf(e,r,t,n){if(r.some(s=>s===""))throw ne(n);let o=e;for(let s=0;s<r.length;s+=1){let i=r[s];if(s===r.length-1){o[i]=t;return}if(o[i]??={},o=o[i],!K(o))throw ne(n)}}function Vn(e,r){return Array.isArray(e)?e.map(t=>Vn(t,r)):K(e)?Number.isSafeInteger(e.length)&&e.length>=0?Array.from({length:e.length},(t,n)=>{if(!Object.prototype.hasOwnProperty.call(e,String(n)))throw ne(r);return Vn(e[String(n)],r)}):Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Vn(n,r)])):e}function eh(e,r){if(e===""||e.length>1&&e.startsWith("0")||!/^[0-9]+$/.test(e))throw ne(r);let t=Number(e);if(!Number.isSafeInteger(t))throw ne(r);return t}function rh(e,r){try{return decodeURIComponent(e)}catch{throw ne(r)}}function Ml(e){return encodeURIComponent(e)}function ne(e){return x(e,"invalid cyclic array wire")}function Ul(e){return x(e,"cyclic array length mismatch")}function cs(e){return x(e,"cyclic array group length mismatch")}function Bl(e){if(!K(e))return;let r=Object.entries(e);if(r.length===0)return;let t=[];for(let[o,s]of r){let i=th(s);if(i===void 0)return;t.push([o,i])}let n=[];for(let[o,s]of t)ih(n,o,s);return n.join("")}function th(e){if(!Array.isArray(e)||e.length===0||!e.every(K))return;let r=nh(e);if(r===void 0)return;let t=e.map(a=>a[r]),n=oh(t);if(n===void 0)return;let o=sh(e,r),s=new Map;for(let a of e){let l=a[r];s.has(l)||s.set(l,[]);let d={};for(let[c,u]of Object.entries(a))if(c!==r&&!o.includes(c)&&!us(u,c,d))return;s.get(l).push(d)}let i=[];for(let a of n.cycle){let l=s.get(a),d=lh(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:r,groups:i,order:n,rows:e}}function nh(e){return Dl.find(r=>e.every(t=>typeof t[r]=="string"))}function oh(e){if(!(e.length<12))for(let r=2;r<=Math.min(8,Math.floor(e.length/3));r+=1){if(e.length%r!==0)continue;let t=e.slice(0,r);if(new Set(t).size<2||!e.every((i,a)=>i===t[a%r]))continue;let n=e.length/r;if(n<3)continue;let o=e.map(Ml).join(","),s=`cycle(${t.map(Ml).join(",")})*${n}`;if(s.length<=o.length*.4)return{cycle:t,encoded:s,repeats:n}}}function sh(e,r){let t=[],n=Object.keys(e[0]),o=n.indexOf(r)+1;for(let s of n.slice(o).filter(i=>i!==r)){if(!ah(s)||!e.every(i=>Object.prototype.hasOwnProperty.call(i,s))||!e.every(i=>Ge(i[s])))break;t.push(s)}return t}function ih(e,r,t){e.push(te(r),`:
|
|
9
|
+
`),e.push(" order: ",ae(t.order.encoded,Rr),`
|
|
10
|
+
`),e.push(" discriminator: ",ae(t.discriminator,Rr),`
|
|
11
11
|
`),e.push(" rows: ",String(t.rows.length),`
|
|
12
|
-
`),t.common.length>0&&
|
|
13
|
-
`);for(let o of n)e.push(" ",t.map(s=>ae(o[s],
|
|
14
|
-
`)}function th(e){return e!==""&&us(e)}function cs(e,r,t,n=new Set){if(!us(r))return!1;if(Le(e))return t[r]=e,!0;if(Array.isArray(e)){if(n.has(e))return!1;n.add(e),t[`${r}.length`]=e.length;let o=e.every((s,i)=>cs(s,`${r}.${i}`,t,n));return n.delete(e),o}if(K(e)){if(n.has(e))return!1;n.add(e);let o=Object.entries(e).every(([s,i])=>!s.includes(".")&&cs(i,`${r}.${s}`,t,n));return n.delete(e),o}return!1}function nh(e){let r=Object.keys(e[0]??{});if(e.every(t=>oh(Object.keys(t),r)))return r.every(us)?r:void 0}function oh(e,r){return e.length===r.length&&e.every((t,n)=>t===r[n])}function us(e){return e.split(".").every(r=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(r))}function Vr(e,r){let t=e[r]??e[e.length-1];return x(t===void 0?1:t.number,"array length mismatch")}function qn(e,r){if(r===-1)throw x(0,"array header missing colon");let t=e.slice(0,r),n=ie(t,"[",0);if(n===-1)throw x(0,"invalid array header");let o,s;try{[o,s]=ve(t.slice(0,n),0)}catch{throw x(0,"invalid array header")}let i=t.slice(n+1),a=i.indexOf("]");if(a===-1)throw x(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 x(0,"invalid array header");let c=Number.parseInt(d,10),u;switch(l.slice(d.length)){case"":u=",";break;case" ":u=" ";break;case"|":u="|";break;default:throw x(0,"invalid array header")}let m=i.slice(a+1),h,f;if(m==="")h=void 0,f=void 0;else if(m.startsWith("{")&&m.endsWith("}")&&m.length>=2)try{f=ih(m.slice(1,-1),u),h=ms(f)}catch(S){throw x(0,S.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw x(0,"invalid array header");return{key:o,keyQuoted:s,len:c,delimiter:u,fields:h,fieldTree:f}}function Bl(e){let r=ie(e,"{",0);if(r===-1||!e.endsWith("}"))throw x(0,"invalid keyed map header");let t,n;try{[t,n]=ve(e.slice(0,r),0)}catch{throw x(0,"invalid keyed map header")}if(t===""&&!n)throw x(0,"expected non-empty field name");let o=e.slice(r+1,-1),s=V;(o.startsWith("|")||o.startsWith(" "))&&(s=o[0],o=o.slice(1));let i;try{i=sh(o,s,s)}catch(a){throw x(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:n,delimiter:s,fields:i}}function sh(e,r,t){let n=[],o=0;function s(l,d){let c=0;for(;o<e.length&&!(d&&e[o]==="}");){if(e[o]===r||e[o]==="}")throw x(0,"invalid array header");let u=o;for(;o<e.length;){let f=e[o];if(f==='"'){i();continue}if(f===r||f==="{"||f==="}"||f==="[")break;o+=1}let[m,h]=ve(e.slice(u,o),0);if(m===""&&!h)throw x(0,"invalid array header");if(c+=1,e[o]==="["){o+=1;let f=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw x(0,"invalid array header");let S=e.slice(f,o);if(!Hl(S,t))throw x(0,"invalid array header");o+=1,n.push({path:[...l,m],listDelimiter:S})}else if(e[o]==="{"){o+=1;let f=n.length;if(s([...l,m],!0),e[o]!=="}"||n.length===f)throw x(0,"invalid array header");o+=1}else n.push({path:[...l,m],listDelimiter:void 0});if(e[o]===r){if(o+=1,o>=e.length||e[o]==="}")throw x(0,"invalid array header");continue}if(d?e[o]==="}":o===e.length)break;throw x(0,"invalid array header")}if(c===0)throw x(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 x(0,"invalid array header");let a=new Set;for(let l=0;l<n.length;l+=1)for(let d=l+1;d<n.length;d+=1)if(ql(n[l].path,n[d].path)||It(n[l].path,n[d].path)||It(n[d].path,n[l].path))throw x(0,"duplicate key");for(let l of n){let c=l.path.join("\0");if(a.has(c))throw x(0,"duplicate key");a.add(c)}return n}function ih(e,r){if(r!==V&&e.includes(V)&&(e.includes("[")||e.includes("{")))return ps(e,V,r);try{return ps(e,r,r)}catch(t){if(r!==V&&t.reason!=="duplicate key")return ps(e,V,r);throw t}}function ps(e,r,t){let n=0;function o(l){let d=[];for(;n<e.length&&!(l&&e[n]==="}");){if(e[n]===r||e[n]==="}")throw x(0,"invalid array header");let c=n;for(;n<e.length;){let f=e[n];if(f==='"'){s();continue}if(f===r||f==="{"||f==="}"||f==="[")break;n+=1}let[u,m]=ve(e.slice(c,n),0);if(u===""&&!m)throw x(0,"invalid array header");let h={key:u};if(e[n]==="["){n+=1;let f=n;for(;n<e.length&&e[n]!=="]";)n+=1;if(n>=e.length)throw x(0,"invalid array header");let S=e.slice(f,n);n+=1;let _=ah(S);if(_!==void 0){if(_.delimiter!==t)throw x(0,"invalid array header");h.fixedLength=_.len,h.fixedDelimiter=_.delimiter}else if(Hl(S,t))h.listDelimiter=S;else throw x(0,"invalid array header")}else if(e[n]==="{"){if(n+=1,h.children=o(!0),e[n]!=="}"||h.children.length===0)throw x(0,"invalid array header");n+=1}if(d.push(h),e[n]===r){if(n+=1,n>=e.length||e[n]==="}")throw x(0,"invalid array header");continue}if(l?e[n]==="}":n===e.length)break;throw x(0,"invalid array header")}if(d.length===0)throw x(0,"invalid array header");return d}function s(){for(n+=1;n<e.length;){let l=e[n];if(n+=1,l==="\\")n+=1;else if(l==='"')return}}let i=o(!1);if(n!==e.length)throw x(0,"invalid array header");let a=ms(i);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(ql(a[l].path,a[d].path)||It(a[l].path,a[d].path)||It(a[d].path,a[l].path))throw x(0,"duplicate key");return i}function ah(e){let r=/^[0-9]+/.exec(e)?.[0];if(r===void 0||r.length>1&&r.startsWith("0"))return;let t=e.slice(r.length),n;switch(t){case"":n=V;break;case" ":n=" ";break;case"|":n="|";break;default:return}return{len:Number.parseInt(r,10),delimiter:n}}function ms(e,r=[]){return e.flatMap(t=>{let n=[...r,t.key];return t.children!==void 0?ms(t.children,n):[{path:n,listDelimiter:t.listDelimiter}]})}function Vn(e,r,t){return e.listDelimiter===void 0?ke(r,t):Se(r,e.listDelimiter,t).map(n=>ke(n,t))}function Hl(e,r){return e.length===1&&e!==r&&!/[ \t\r\n"[\]{}:]/.test(e)}function ql(e,r){return e.length===r.length&&It(e,r)}function It(e,r){return r.every((t,n)=>e[n]===t)}function Kn(e,r){return x(r,e.reason??String(e.message))}function ue(e,r){let t=Gl(r),n=Cl(e,t),o=n[0];if(o===void 0)return{};if(o.depth!==0)throw x(o.number,"invalid indentation");let s=n.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){Lt(o.content,o.number,t);let d;try{d=qn(o.content,ie(o.content,":",o.number))}catch(c){if(t.strict)throw Kn(c,o.number);d=void 0}if(d!==void 0)return ch(d,n,t)}if(s&&ie(o.content,":",o.number)===-1)return ke(o.content.trim(),o.number);let i={index:0},a=fs(n,i,0,t),l=n[i.index];if(l!==void 0)throw x(l.number,"expected end of document");return t.cyclicDiscriminatedArrays?Fl(a):a}function fs(e,r,t,n){let o={};for(;r.index<e.length;){let s=e[r.index];if(s.depth<t)break;if(s.depth>t)throw x(s.number,"invalid indentation");let{key:i,quoted:a,value:l}=lh(e,r,t,n);Xl(o,i,a,l,n,s.number)}return o}function lh(e,r,t,n){let o=e[r.index],s=o.content,i=ie(s,":",o.number);if(i===-1)throw x(o.number,"expected `key: value`");let a=s.slice(0,i),l=s.slice(i+1),d=ie(a,"[",o.number),c=ie(a,"{",o.number);if(c!==-1&&(d===-1||c<d)){Lt(a,o.number,n);let f;try{f=Bl(a)}catch(_){if(n.strict)throw Kn(_,o.number);r.index+=1;let v=gs(e,r,t,l,o.number,n);return{key:a.trim(),quoted:!1,value:v}}if(l.trim()!=="")throw x(o.number,"expected keyed map rows");let S=dh(f,e,r,t+1,n);return{key:f.key,quoted:f.keyQuoted,value:S}}if(d!==-1){Lt(a,o.number,n);let f;try{f=qn(a,i)}catch(_){if(n.strict)throw Kn(_,o.number);r.index+=1;let v=gs(e,r,t,l,o.number,n);return{key:a.trim(),quoted:!1,value:v}}if(f.key===""&&!f.keyQuoted)throw x(o.number,"expected non-empty field name");let S=hs(f,l,e,r,t,n);return{key:f.key,quoted:f.keyQuoted,value:S}}let[u,m]=ve(a,o.number);if(u===""&&!m)throw x(o.number,"expected non-empty field name");r.index+=1;let h=gs(e,r,t,l,o.number,n);return{key:u,quoted:m,value:h}}function gs(e,r,t,n,o,s){let i=n.trim();if(i==="[]")return[];if(i!=="")return ke(i,o);let a=e[r.index];return a!==void 0&&a.depth>t?fs(e,r,t+1,s):{}}function dh(e,r,t,n,o){let s={};for(t.index+=1;t.index<r.length;){let i=r[t.index];if(i.depth<n)break;if(i.depth>n)throw x(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw x(i.number,"blank line inside keyed map");let a=ie(i.content,":",i.number);if(a===-1)throw x(i.number,"expected `key: value`");let[l,d]=ve(i.content.slice(0,a),i.number);if(l===""&&!d)throw x(i.number,"expected non-empty field name");let c=Se(i.content.slice(a+1).trim(),e.delimiter,i.number);if(c.length!==e.fields.length)throw x(i.number,"keyed map row length mismatch");let u={};e.fields.forEach((m,h)=>{Jr(u,m.path,Vn(m,c[h],i.number),o,i.number)}),Xl(s,l,d,u,o,i.number),t.index+=1}return s}function ch(e,r,t){let n=r[0],o=ie(n.content,":",n.number);if(o===-1)throw x(n.number,"expected `key: value`");let s=n.content.slice(o+1),i={index:0},a=hs(e,s,r,i,0,t),l=r[i.index];if(l!==void 0)throw x(l.number,"expected end of document");return a}function hs(e,r,t,n,o,s){let i=t[n.index].number,a=r.trim();if(n.index+=1,e.fields!==void 0){if(a!=="")throw x(i,"expected tabular rows");return uh(e,e.fields,t,n,o+1,s)}if(a!==""){let l=Se(a,e.delimiter,i).map(d=>ke(d,i));if(l.length!==e.len)throw x(i,"array length mismatch");return l}return kh(e,t,n,o+1,s)}function uh(e,r,t,n,o,s){if(e.fieldTree!==void 0&&hh(e.fieldTree))return ph(e,t,n,o,s);let i=[];for(;i.length<e.len;){let l=t[n.index];if(l===void 0)throw Vr(t,n.index);if(l.depth<o)break;if(l.depth>o)throw x(l.number,"invalid indentation");if(l.blankBefore&&s.strict)throw x(l.number,"blank line inside array");if(!Kr(l.content,e.delimiter,l.number))break;let d=Se(l.content,e.delimiter,l.number);if(d.length!==r.length)throw x(l.number,"array row length mismatch");let c={};r.forEach((u,m)=>{Jr(c,u.path,Vn(u,d[m],l.number),s,l.number)}),i.push(c),n.index+=1}if(i.length!==e.len)throw Vr(t,n.index);let a=t[n.index];if(a!==void 0&&a.depth>=o&&Kr(a.content,e.delimiter,a.number))throw x(a.number,"array length mismatch");return i}function ph(e,r,t,n,o){return Vl(e.len,e.fieldTree,e.delimiter,r,t,n,o,!0)}function Vl(e,r,t,n,o,s,i,a){let l=[],d=Jl(e,r,t,n,o.index,s,i);for(;l.length<e;){let u=n[o.index];if(u===void 0)throw Vr(n,o.index);if(u.depth<s)break;if(u.depth>s)throw x(u.number,"invalid indentation");if(u.blankBefore&&i.strict)throw x(u.number,"blank line inside array");if(!Kr(u.content,t,u.number))break;let m=Se(u.content,t,u.number),h={cellIndex:0,nextIndex:o.index+1,flatWidth:Jn(r),childTableFields:d},f=Kl(r,m,u.number,n,h,s+1,t,i);if(h.cellIndex!==m.length)throw x(u.number,"array row length mismatch");l.push(fh(r,f,a)),o.index=h.nextIndex}if(l.length!==e)throw Vr(n,o.index);let c=n[o.index];if(c!==void 0&&c.depth>=s&&Kr(c.content,t,c.number))throw x(c.number,"array length mismatch");return l}function Kl(e,r,t,n,o,s,i,a){let l={};return e.forEach((d,c)=>{let u=e.slice(c+1),m=mh(d,u,r,t,n,o,s,i,a);Jr(l,[d.key],m,a,t)}),l}function mh(e,r,t,n,o,s,i,a,l){if(e.fixedLength!==void 0){if(s.cellIndex+e.fixedLength>t.length)throw x(n,"array row length mismatch");let c=t.slice(s.cellIndex,s.cellIndex+e.fixedLength).map(u=>ke(u,n));return s.cellIndex+=e.fixedLength,c}if(e.children!==void 0){let c=Jn(e.children),u=t[s.cellIndex],m=Ql(u),h=t.length-s.cellIndex-1,f=o[s.nextIndex],S=f!==void 0&&f.depth===i,_=s.childTableFields===void 0?void 0:s.childTableFields.has(e);if(_===void 0?m!==void 0&&(S||t.length!==s.flatWidth&&h<c+yh(r)):_){if(m===void 0)throw x(n,"array row length mismatch");return s.cellIndex+=1,Vl(m,e.children,a,o,{get index(){return s.nextIndex},set index(C){s.nextIndex=C}},i,l,!1)}return Kl(e.children,t,n,o,s,i,a,l)}let d=t[s.cellIndex];if(d===void 0)throw x(n,"array row length mismatch");return s.cellIndex+=1,Vn(e,d,n)}function Jl(e,r,t,n,o,s,i){let a=r.filter(c=>c.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let l,d=1<<a.length;for(let c=0;c<d;c+=1){let u=new Set;a.forEach((h,f)=>{c&1<<f&&u.add(h)});let m=zl(e,r,u,t,n,o,s,i);m!==void 0&&(l===void 0||m.consumedChildRows>l.consumedChildRows||m.consumedChildRows===l.consumedChildRows&&u.size<l.childTableFields.size)&&(l={childTableFields:u,consumedChildRows:m.consumedChildRows})}return l?.childTableFields}function zl(e,r,t,n,o,s,i,a){let l=s,d=0;try{for(let u=0;u<e;u+=1){let m=o[l];if(m===void 0||m.depth!==i||m.blankBefore&&a.strict||!Kr(m.content,n,m.number))return;let h=Se(m.content,n,m.number),f=gh(r,t,h,n,o,l+1,i+1,a);if(f===void 0||o[f.nextIndex]?.depth>i)return;d+=f.consumedChildRows,l=f.nextIndex}let c=o[l];if(c!==void 0&&c.depth>=i&&Kr(c.content,n,c.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function gh(e,r,t,n,o,s,i,a){let l=0,d=s,c=0;for(let u of e){if(u.fixedLength!==void 0)l+=u.fixedLength;else if(u.children!==void 0)if(r.has(u)){let m=Ql(t[l]);if(m===void 0)return;l+=1;let h=Jl(m,u.children,n,o,d,i,a);if(h===void 0)return;let f=zl(m,u.children,h,n,o,d,i,a);if(f===void 0)return;d=f.nextIndex,c+=m+f.consumedChildRows}else l+=Jn(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:c}}function fh(e,r,t){return t&&e.length===1&&e[0].fixedLength!==void 0?r[e[0].key]:r}function Ql(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function hh(e){return e.some(r=>r.fixedLength!==void 0||r.children!==void 0)}function Jn(e){return e.reduce((r,t)=>r+Yl(t),0)}function Yl(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?Jn(e.children):1}function yh(e){return e.reduce((r,t)=>t.children!==void 0?r+1:r+Yl(t),0)}function Kr(e,r,t){let n=ie(e,":",t);if(n===-1)return!0;let o=ie(e,r,t);return o===-1?!1:o<n}function kh(e,r,t,n,o){let s=[];for(;s.length<e.len;){let a=r[t.index];if(a===void 0||a.depth<n)throw Vr(r,t.index);if(a.depth>n)throw x(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw x(a.number,"blank line inside array");s.push(bh(r,t,n,o))}let i=r[t.index];if(i!==void 0&&i.depth>=n)throw x(i.number,"array length mismatch");return s}function bh(e,r,t,n){let o=e[r.index];if(!o.content.startsWith("-"))throw x(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return r.index+=1,{};if(s.startsWith("[")){let i=ie(s,":",o.number);Lt(s,o.number,n);let a;try{a=qn(s,i)}catch{a=void 0}if(a!==void 0){let l=s.slice(i+1);return hs(a,l,e,r,t,n)}}if(ie(s,":",o.number)!==-1){let i=[{number:o.number,depth:t+1,content:s,blankBefore:!1}];for(r.index+=1;r.index<e.length;){let a=e[r.index];if(a.depth<=t)break;i.push(a),r.index+=1}return fs(i,{index:0},t+1,n)}return r.index+=1,ke(s,o.number)}function Xl(e,r,t,n,o,s){if(o.expandPaths&&!t&&r.includes(".")){let i=r.split(".");if(i.every(_h)){Jr(e,i,n,o,s);return}}Jr(e,[r],n,o,s)}function Jr(e,r,t,n,o){Ie(r.length-1,o,n);let s=r[0],i=Object.prototype.hasOwnProperty.call(e,s);if(r.length===1){if(i&&n.strict)throw x(o,"duplicate key");Te(e,s,t);return}if(i&&!K(e[s])){if(n.strict)throw x(o,"path expansion conflict");Te(e,s,{})}else i||Te(e,s,{});Jr(e[s],r.slice(1),t,n,o)}function _h(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function J(e,r={}){let t=r.maxDepth??1e3,n=r.delimiter??V;if(![V,"|"," "].includes(n))throw x(0,"invalid array header");let o={nestedTabularHeaders:r.nestedTabularHeaders===!0,keyedMapCollapse:r.keyedMapCollapse===!0,primitiveArrayColumns:r.primitiveArrayColumns===!0,objectArrayColumns:r.objectArrayColumns===!0,cyclicDiscriminatedArrays:r.cyclicDiscriminatedArrays===!0,delimiter:n,maxDepth:t===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(t))};if(o.cyclicDiscriminatedArrays){let i=Ul(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?_s(s,void 0,e,0,!1,o):K(e)?Zl(s,e,0,o):s.push(ae(e,n)),s.join("")}function zr(e,r){e.push(" ".repeat(r*2))}function Zl(e,r,t,n){Ie(t,0,n);for(let[o,s]of Object.entries(r))zr(e,t),ks(e,o,s,t,n)}function ks(e,r,t,n,o){if(Ie(n,0,o),Array.isArray(t)){_s(e,r,t,n,!1,o);return}if(K(t)){let s=o.keyedMapCollapse?wh(t,o,n+1):void 0;if(s!==void 0){e.push(te(r),"{",Rs(o.delimiter),s.fields.map(i=>vs(i,o.delimiter)).join(o.delimiter),`}:
|
|
15
|
-
`);for(let[i,a]of Object.entries(t)){
|
|
12
|
+
`),t.common.length>0&&Fl(e,"common",t.common,t.commonRows);for(let n of t.groups)Fl(e,n.label,n.fields,n.rows)}function Fl(e,r,t,n){e.push(" ",te(r),"[",String(n.length),Rr,"]{",t.map(te).join(Rr),`}:
|
|
13
|
+
`);for(let o of n)e.push(" ",t.map(s=>ae(o[s],Rr)).join(Rr),`
|
|
14
|
+
`)}function ah(e){return e!==""&&ps(e)}function us(e,r,t,n=new Set){if(!ps(r))return!1;if(Ge(e))return t[r]=e,!0;if(Array.isArray(e)){if(n.has(e))return!1;n.add(e),t[`${r}.length`]=e.length;let o=e.every((s,i)=>us(s,`${r}.${i}`,t,n));return n.delete(e),o}if(K(e)){if(n.has(e))return!1;n.add(e);let o=Object.entries(e).every(([s,i])=>!s.includes(".")&&us(i,`${r}.${s}`,t,n));return n.delete(e),o}return!1}function lh(e){let r=Object.keys(e[0]??{});if(e.every(t=>dh(Object.keys(t),r)))return r.every(ps)?r:void 0}function dh(e,r){return e.length===r.length&&e.every((t,n)=>t===r[n])}function ps(e){return e.split(".").every(r=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(r))}function Jr(e,r){let t=e[r]??e[e.length-1];return x(t===void 0?1:t.number,"array length mismatch")}function Kn(e,r){if(r===-1)throw x(0,"array header missing colon");let t=e.slice(0,r),n=ie(t,"[",0);if(n===-1)throw x(0,"invalid array header");let o,s;try{[o,s]=Se(t.slice(0,n),0)}catch{throw x(0,"invalid array header")}let i=t.slice(n+1),a=i.indexOf("]");if(a===-1)throw x(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 x(0,"invalid array header");let c=Number.parseInt(d,10),u;switch(l.slice(d.length)){case"":u=",";break;case" ":u=" ";break;case"|":u="|";break;default:throw x(0,"invalid array header")}let m=i.slice(a+1),f,h;if(m==="")f=void 0,h=void 0;else if(m.startsWith("{")&&m.endsWith("}")&&m.length>=2)try{h=uh(m.slice(1,-1),u),f=gs(h)}catch(v){throw x(0,v.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw x(0,"invalid array header");return{key:o,keyQuoted:s,len:c,delimiter:u,fields:f,fieldTree:h}}function Hl(e){let r=ie(e,"{",0);if(r===-1||!e.endsWith("}"))throw x(0,"invalid keyed map header");let t,n;try{[t,n]=Se(e.slice(0,r),0)}catch{throw x(0,"invalid keyed map header")}if(t===""&&!n)throw x(0,"expected non-empty field name");let o=e.slice(r+1,-1),s=V;(o.startsWith("|")||o.startsWith(" "))&&(s=o[0],o=o.slice(1));let i;try{i=ch(o,s,s)}catch(a){throw x(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:n,delimiter:s,fields:i}}function ch(e,r,t){let n=[],o=0;function s(l,d){let c=0;for(;o<e.length&&!(d&&e[o]==="}");){if(e[o]===r||e[o]==="}")throw x(0,"invalid array header");let u=o;for(;o<e.length;){let h=e[o];if(h==='"'){i();continue}if(h===r||h==="{"||h==="}"||h==="[")break;o+=1}let[m,f]=Se(e.slice(u,o),0);if(m===""&&!f)throw x(0,"invalid array header");if(c+=1,e[o]==="["){o+=1;let h=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw x(0,"invalid array header");let v=e.slice(h,o);if(!ql(v,t))throw x(0,"invalid array header");o+=1,n.push({path:[...l,m],listDelimiter:v})}else if(e[o]==="{"){o+=1;let h=n.length;if(s([...l,m],!0),e[o]!=="}"||n.length===h)throw x(0,"invalid array header");o+=1}else n.push({path:[...l,m],listDelimiter:void 0});if(e[o]===r){if(o+=1,o>=e.length||e[o]==="}")throw x(0,"invalid array header");continue}if(d?e[o]==="}":o===e.length)break;throw x(0,"invalid array header")}if(c===0)throw x(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 x(0,"invalid array header");let a=new Set;for(let l=0;l<n.length;l+=1)for(let d=l+1;d<n.length;d+=1)if(Vl(n[l].path,n[d].path)||Ct(n[l].path,n[d].path)||Ct(n[d].path,n[l].path))throw x(0,"duplicate key");for(let l of n){let c=l.path.join("\0");if(a.has(c))throw x(0,"duplicate key");a.add(c)}return n}function uh(e,r){if(r!==V&&e.includes(V)&&(e.includes("[")||e.includes("{")))return ms(e,V,r);try{return ms(e,r,r)}catch(t){if(r!==V&&t.reason!=="duplicate key")return ms(e,V,r);throw t}}function ms(e,r,t){let n=0;function o(l){let d=[];for(;n<e.length&&!(l&&e[n]==="}");){if(e[n]===r||e[n]==="}")throw x(0,"invalid array header");let c=n;for(;n<e.length;){let h=e[n];if(h==='"'){s();continue}if(h===r||h==="{"||h==="}"||h==="[")break;n+=1}let[u,m]=Se(e.slice(c,n),0);if(u===""&&!m)throw x(0,"invalid array header");let f={key:u};if(e[n]==="["){n+=1;let h=n;for(;n<e.length&&e[n]!=="]";)n+=1;if(n>=e.length)throw x(0,"invalid array header");let v=e.slice(h,n);n+=1;let y=ph(v);if(y!==void 0){if(y.delimiter!==t)throw x(0,"invalid array header");f.fixedLength=y.len,f.fixedDelimiter=y.delimiter}else if(ql(v,t))f.listDelimiter=v;else throw x(0,"invalid array header")}else if(e[n]==="{"){if(n+=1,f.children=o(!0),e[n]!=="}"||f.children.length===0)throw x(0,"invalid array header");n+=1}if(d.push(f),e[n]===r){if(n+=1,n>=e.length||e[n]==="}")throw x(0,"invalid array header");continue}if(l?e[n]==="}":n===e.length)break;throw x(0,"invalid array header")}if(d.length===0)throw x(0,"invalid array header");return d}function s(){for(n+=1;n<e.length;){let l=e[n];if(n+=1,l==="\\")n+=1;else if(l==='"')return}}let i=o(!1);if(n!==e.length)throw x(0,"invalid array header");let a=gs(i);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(Vl(a[l].path,a[d].path)||Ct(a[l].path,a[d].path)||Ct(a[d].path,a[l].path))throw x(0,"duplicate key");return i}function ph(e){let r=/^[0-9]+/.exec(e)?.[0];if(r===void 0||r.length>1&&r.startsWith("0"))return;let t=e.slice(r.length),n;switch(t){case"":n=V;break;case" ":n=" ";break;case"|":n="|";break;default:return}return{len:Number.parseInt(r,10),delimiter:n}}function gs(e,r=[]){return e.flatMap(t=>{let n=[...r,t.key];return t.children!==void 0?gs(t.children,n):[{path:n,listDelimiter:t.listDelimiter}]})}function Jn(e,r,t){return e.listDelimiter===void 0?be(r,t):Te(r,e.listDelimiter,t).map(n=>be(n,t))}function ql(e,r){return e.length===1&&e!==r&&!/[ \t\r\n"[\]{}:]/.test(e)}function Vl(e,r){return e.length===r.length&&Ct(e,r)}function Ct(e,r){return r.every((t,n)=>e[n]===t)}function zn(e,r){return x(r,e.reason??String(e.message))}function ue(e,r){let t=Cl(r),n=Nl(e,t),o=n[0];if(o===void 0)return{};if(o.depth!==0)throw x(o.number,"invalid indentation");let s=n.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){It(o.content,o.number,t);let d;try{d=Kn(o.content,ie(o.content,":",o.number))}catch(c){if(t.strict)throw zn(c,o.number);d=void 0}if(d!==void 0)return fh(d,n,t)}if(s&&ie(o.content,":",o.number)===-1)return be(o.content.trim(),o.number);let i={index:0},a=hs(n,i,0,t),l=n[i.index];if(l!==void 0)throw x(l.number,"expected end of document");return t.cyclicDiscriminatedArrays?Wl(a):a}function hs(e,r,t,n){let o={};for(;r.index<e.length;){let s=e[r.index];if(s.depth<t)break;if(s.depth>t)throw x(s.number,"invalid indentation");let{key:i,quoted:a,value:l}=mh(e,r,t,n);Zl(o,i,a,l,n,s.number)}return o}function mh(e,r,t,n){let o=e[r.index],s=o.content,i=ie(s,":",o.number);if(i===-1)throw x(o.number,"expected `key: value`");let a=s.slice(0,i),l=s.slice(i+1),d=ie(a,"[",o.number),c=ie(a,"{",o.number);if(c!==-1&&(d===-1||c<d)){It(a,o.number,n);let h;try{h=Hl(a)}catch(y){if(n.strict)throw zn(y,o.number);r.index+=1;let S=fs(e,r,t,l,o.number,n);return{key:a.trim(),quoted:!1,value:S}}if(l.trim()!=="")throw x(o.number,"expected keyed map rows");let v=gh(h,e,r,t+1,n);return{key:h.key,quoted:h.keyQuoted,value:v}}if(d!==-1){It(a,o.number,n);let h;try{h=Kn(a,i)}catch(y){if(n.strict)throw zn(y,o.number);r.index+=1;let S=fs(e,r,t,l,o.number,n);return{key:a.trim(),quoted:!1,value:S}}if(h.key===""&&!h.keyQuoted)throw x(o.number,"expected non-empty field name");let v=ys(h,l,e,r,t,n);return{key:h.key,quoted:h.keyQuoted,value:v}}let[u,m]=Se(a,o.number);if(u===""&&!m)throw x(o.number,"expected non-empty field name");r.index+=1;let f=fs(e,r,t,l,o.number,n);return{key:u,quoted:m,value:f}}function fs(e,r,t,n,o,s){let i=n.trim();if(i==="[]")return[];if(i!=="")return be(i,o);let a=e[r.index];return a!==void 0&&a.depth>t?hs(e,r,t+1,s):{}}function gh(e,r,t,n,o){let s={};for(t.index+=1;t.index<r.length;){let i=r[t.index];if(i.depth<n)break;if(i.depth>n)throw x(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw x(i.number,"blank line inside keyed map");let a=ie(i.content,":",i.number);if(a===-1)throw x(i.number,"expected `key: value`");let[l,d]=Se(i.content.slice(0,a),i.number);if(l===""&&!d)throw x(i.number,"expected non-empty field name");let c=Te(i.content.slice(a+1).trim(),e.delimiter,i.number);if(c.length!==e.fields.length)throw x(i.number,"keyed map row length mismatch");let u={};e.fields.forEach((m,f)=>{Qr(u,m.path,Jn(m,c[f],i.number),o,i.number)}),Zl(s,l,d,u,o,i.number),t.index+=1}return s}function fh(e,r,t){let n=r[0],o=ie(n.content,":",n.number);if(o===-1)throw x(n.number,"expected `key: value`");let s=n.content.slice(o+1),i={index:0},a=ys(e,s,r,i,0,t),l=r[i.index];if(l!==void 0)throw x(l.number,"expected end of document");return a}function ys(e,r,t,n,o,s){let i=t[n.index].number,a=r.trim();if(n.index+=1,e.fields!==void 0){if(a!=="")throw x(i,"expected tabular rows");return hh(e,e.fields,t,n,o+1,s)}if(a!==""){let l=Te(a,e.delimiter,i).map(d=>be(d,i));if(l.length!==e.len)throw x(i,"array length mismatch");return l}return Eh(e,t,n,o+1,s)}function hh(e,r,t,n,o,s){if(e.fieldTree!==void 0&&Rh(e.fieldTree))return yh(e,t,n,o,s);let i=[];for(;i.length<e.len;){let l=t[n.index];if(l===void 0)throw Jr(t,n.index);if(l.depth<o)break;if(l.depth>o)throw x(l.number,"invalid indentation");if(l.blankBefore&&s.strict)throw x(l.number,"blank line inside array");if(!zr(l.content,e.delimiter,l.number))break;let d=Te(l.content,e.delimiter,l.number);if(d.length!==r.length)throw x(l.number,"array row length mismatch");let c={};r.forEach((u,m)=>{Qr(c,u.path,Jn(u,d[m],l.number),s,l.number)}),i.push(c),n.index+=1}if(i.length!==e.len)throw Jr(t,n.index);let a=t[n.index];if(a!==void 0&&a.depth>=o&&zr(a.content,e.delimiter,a.number))throw x(a.number,"array length mismatch");return i}function yh(e,r,t,n,o){return Kl(e.len,e.fieldTree,e.delimiter,r,t,n,o,!0)}function Kl(e,r,t,n,o,s,i,a){let l=[],d=zl(e,r,t,n,o.index,s,i);for(;l.length<e;){let u=n[o.index];if(u===void 0)throw Jr(n,o.index);if(u.depth<s)break;if(u.depth>s)throw x(u.number,"invalid indentation");if(u.blankBefore&&i.strict)throw x(u.number,"blank line inside array");if(!zr(u.content,t,u.number))break;let m=Te(u.content,t,u.number),f={cellIndex:0,nextIndex:o.index+1,flatWidth:Qn(r),childTableFields:d},h=Jl(r,m,u.number,n,f,s+1,t,i);if(f.cellIndex!==m.length)throw x(u.number,"array row length mismatch");l.push(_h(r,h,a)),o.index=f.nextIndex}if(l.length!==e)throw Jr(n,o.index);let c=n[o.index];if(c!==void 0&&c.depth>=s&&zr(c.content,t,c.number))throw x(c.number,"array length mismatch");return l}function Jl(e,r,t,n,o,s,i,a){let l={};return e.forEach((d,c)=>{let u=e.slice(c+1),m=bh(d,u,r,t,n,o,s,i,a);Qr(l,[d.key],m,a,t)}),l}function bh(e,r,t,n,o,s,i,a,l){if(e.fixedLength!==void 0){if(s.cellIndex+e.fixedLength>t.length)throw x(n,"array row length mismatch");let c=t.slice(s.cellIndex,s.cellIndex+e.fixedLength).map(u=>be(u,n));return s.cellIndex+=e.fixedLength,c}if(e.children!==void 0){let c=Qn(e.children),u=t[s.cellIndex],m=Yl(u),f=t.length-s.cellIndex-1,h=o[s.nextIndex],v=h!==void 0&&h.depth===i,y=s.childTableFields===void 0?void 0:s.childTableFields.has(e);if(y===void 0?m!==void 0&&(v||t.length!==s.flatWidth&&f<c+wh(r)):y){if(m===void 0)throw x(n,"array row length mismatch");return s.cellIndex+=1,Kl(m,e.children,a,o,{get index(){return s.nextIndex},set index(G){s.nextIndex=G}},i,l,!1)}return Jl(e.children,t,n,o,s,i,a,l)}let d=t[s.cellIndex];if(d===void 0)throw x(n,"array row length mismatch");return s.cellIndex+=1,Jn(e,d,n)}function zl(e,r,t,n,o,s,i){let a=r.filter(c=>c.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let l,d=1<<a.length;for(let c=0;c<d;c+=1){let u=new Set;a.forEach((f,h)=>{c&1<<h&&u.add(f)});let m=Ql(e,r,u,t,n,o,s,i);m!==void 0&&(l===void 0||m.consumedChildRows>l.consumedChildRows||m.consumedChildRows===l.consumedChildRows&&u.size<l.childTableFields.size)&&(l={childTableFields:u,consumedChildRows:m.consumedChildRows})}return l?.childTableFields}function Ql(e,r,t,n,o,s,i,a){let l=s,d=0;try{for(let u=0;u<e;u+=1){let m=o[l];if(m===void 0||m.depth!==i||m.blankBefore&&a.strict||!zr(m.content,n,m.number))return;let f=Te(m.content,n,m.number),h=kh(r,t,f,n,o,l+1,i+1,a);if(h===void 0||o[h.nextIndex]?.depth>i)return;d+=h.consumedChildRows,l=h.nextIndex}let c=o[l];if(c!==void 0&&c.depth>=i&&zr(c.content,n,c.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function kh(e,r,t,n,o,s,i,a){let l=0,d=s,c=0;for(let u of e){if(u.fixedLength!==void 0)l+=u.fixedLength;else if(u.children!==void 0)if(r.has(u)){let m=Yl(t[l]);if(m===void 0)return;l+=1;let f=zl(m,u.children,n,o,d,i,a);if(f===void 0)return;let h=Ql(m,u.children,f,n,o,d,i,a);if(h===void 0)return;d=h.nextIndex,c+=m+h.consumedChildRows}else l+=Qn(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:c}}function _h(e,r,t){return t&&e.length===1&&e[0].fixedLength!==void 0?r[e[0].key]:r}function Yl(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function Rh(e){return e.some(r=>r.fixedLength!==void 0||r.children!==void 0)}function Qn(e){return e.reduce((r,t)=>r+Xl(t),0)}function Xl(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?Qn(e.children):1}function wh(e){return e.reduce((r,t)=>t.children!==void 0?r+1:r+Xl(t),0)}function zr(e,r,t){let n=ie(e,":",t);if(n===-1)return!0;let o=ie(e,r,t);return o===-1?!1:o<n}function Eh(e,r,t,n,o){let s=[];for(;s.length<e.len;){let a=r[t.index];if(a===void 0||a.depth<n)throw Jr(r,t.index);if(a.depth>n)throw x(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw x(a.number,"blank line inside array");s.push(vh(r,t,n,o))}let i=r[t.index];if(i!==void 0&&i.depth>=n)throw x(i.number,"array length mismatch");return s}function vh(e,r,t,n){let o=e[r.index];if(!o.content.startsWith("-"))throw x(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return r.index+=1,{};if(s.startsWith("[")){let i=ie(s,":",o.number);It(s,o.number,n);let a;try{a=Kn(s,i)}catch{a=void 0}if(a!==void 0){let l=s.slice(i+1);return ys(a,l,e,r,t,n)}}if(ie(s,":",o.number)!==-1){let i=[{number:o.number,depth:t+1,content:s,blankBefore:!1}];for(r.index+=1;r.index<e.length;){let a=e[r.index];if(a.depth<=t)break;i.push(a),r.index+=1}return hs(i,{index:0},t+1,n)}return r.index+=1,be(s,o.number)}function Zl(e,r,t,n,o,s){if(o.expandPaths&&!t&&r.includes(".")){let i=r.split(".");if(i.every(Sh)){Qr(e,i,n,o,s);return}}Qr(e,[r],n,o,s)}function Qr(e,r,t,n,o){$e(r.length-1,o,n);let s=r[0],i=Object.prototype.hasOwnProperty.call(e,s);if(r.length===1){if(i&&n.strict)throw x(o,"duplicate key");xe(e,s,t);return}if(i&&!K(e[s])){if(n.strict)throw x(o,"path expansion conflict");xe(e,s,{})}else i||xe(e,s,{});Qr(e[s],r.slice(1),t,n,o)}function Sh(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function J(e,r={}){let t=r.maxDepth??1e3,n=r.delimiter??V;if(![V,"|"," "].includes(n))throw x(0,"invalid array header");let o={nestedTabularHeaders:r.nestedTabularHeaders===!0,keyedMapCollapse:r.keyedMapCollapse===!0,primitiveArrayColumns:r.primitiveArrayColumns===!0,objectArrayColumns:r.objectArrayColumns===!0,cyclicDiscriminatedArrays:r.cyclicDiscriminatedArrays===!0,delimiter:n,maxDepth:t===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(t))};if(o.cyclicDiscriminatedArrays){let i=Bl(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?Rs(s,void 0,e,0,!1,o):K(e)?ed(s,e,0,o):s.push(ae(e,n)),s.join("")}function Yr(e,r){e.push(" ".repeat(r*2))}function ed(e,r,t,n){$e(t,0,n);for(let[o,s]of Object.entries(r))Yr(e,t),ks(e,o,s,t,n)}function ks(e,r,t,n,o){if($e(n,0,o),Array.isArray(t)){Rs(e,r,t,n,!1,o);return}if(K(t)){let s=o.keyedMapCollapse?xh(t,o,n+1):void 0;if(s!==void 0){e.push(te(r),"{",ws(o.delimiter),s.fields.map(i=>Ss(i,o.delimiter)).join(o.delimiter),`}:
|
|
15
|
+
`);for(let[i,a]of Object.entries(t)){Yr(e,n+1);let l=[];e.push(te(i),": ",s.paths.map(d=>Ts(vs(a,d.path),d,o.delimiter,o,l,n+2)).join(o.delimiter),`
|
|
16
16
|
`),e.push(...l)}return}e.push(te(r),`:
|
|
17
|
-
`),
|
|
18
|
-
`)}function
|
|
17
|
+
`),ed(e,t,n+1,o);return}e.push(te(r),": ",ae(t,o.delimiter),`
|
|
18
|
+
`)}function Rs(e,r,t,n,o,s){if($e(n,0,s),t.length===0){r!==void 0?e.push(te(r),`: []
|
|
19
19
|
`):o?e.push(`[0]:
|
|
20
20
|
`):e.push(`[]
|
|
21
|
-
`);return}if(t.every(
|
|
22
|
-
`);return}let i=o?void 0:
|
|
23
|
-
`);for(let a of t){
|
|
24
|
-
`),e.push(...l)}return}
|
|
25
|
-
`);for(let a of t)
|
|
26
|
-
`);return}e.push("- "),ks(e,o[0][0],o[0][1],t+1,n);for(let[s,i]of o.slice(1))
|
|
27
|
-
`)}function
|
|
28
|
-
`),e.push(...i)}}function
|
|
29
|
-
`}function
|
|
30
|
-
`}function
|
|
31
|
-
`,
|
|
32
|
-
`;return
|
|
33
|
-
`},end(){return u?"":(u=!0,
|
|
21
|
+
`);return}if(t.every(Ge)){bs(e,r,t.length,void 0,s.delimiter),e.push(" "),e.push(t.map(a=>ae(a,s.delimiter)).join(s.delimiter)),e.push(`
|
|
22
|
+
`);return}let i=o?void 0:rd(t,s,n+1);if(i!==void 0){bs(e,r,t.length,i.fields,s.delimiter),e.push(`
|
|
23
|
+
`);for(let a of t){Yr(e,n+1);let l=[];e.push(i.paths.map(d=>Ts(vs(a,d.path),d,s.delimiter,s,l,n+2)).join(s.delimiter)),e.push(`
|
|
24
|
+
`),e.push(...l)}return}bs(e,r,t.length,void 0,s.delimiter),e.push(`
|
|
25
|
+
`);for(let a of t)Yr(e,n+1),Th(e,a,n+1,s)}function Th(e,r,t,n){if($e(t,0,n),Array.isArray(r)){e.push("- "),Rs(e,void 0,r,t,!0,n);return}if(K(r)){let o=Object.entries(r);if(o.length===0){e.push(`-
|
|
26
|
+
`);return}e.push("- "),ks(e,o[0][0],o[0][1],t+1,n);for(let[s,i]of o.slice(1))Yr(e,t+1),ks(e,s,i,t+1,n);return}e.push("- ",ae(r,n.delimiter),`
|
|
27
|
+
`)}function bs(e,r,t,n,o){r!==void 0&&e.push(te(r)),e.push("[",String(t),ws(o),"]"),n!==void 0&&e.push("{",n.map(s=>Ss(s,o)).join(o),"}"),e.push(":")}function ws(e){return e===V?"":e}function rd(e,r,t){let n=Ph(e,r);if(n!==void 0)return n;let o=_s(e.map(s=>({value:s})),r,t);return o===void 0?void 0:{fields:o,paths:Es(o)}}function xh(e,r,t){let n=Object.values(e);if(!(n.length<2))return rd(n,r,t)}function _s(e,r,t){$e(t,0,r);let n=e[0]?.value;if(!K(n))return;let o=Object.keys(n).map(s=>({key:s}));if(o.length!==0){for(let{value:s}of e)if(!K(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})=>Ge(l)))continue;if(r.primitiveArrayColumns&&i.every(({value:l})=>Array.isArray(l)&&l.every(Ge))){s.listDelimiter=";";continue}if(r.objectArrayColumns&&i.every(({value:l})=>Array.isArray(l))){let l=td(i.map(({value:c})=>c));if(l!==void 0){s.fixedLength=l.fixedLength,s.fixedDelimiter=r.delimiter;continue}let d=_s(i.flatMap(({value:c})=>c.map(u=>({value:u}))),r,t+1);if(d!==void 0){s.children=d,s.childTable=!0;continue}}if(!r.nestedTabularHeaders)return;let a=_s(i,r,t+1);if(a===void 0)return;s.children=a}return o}}function Ph(e,r){if(!r.objectArrayColumns)return;let t=td(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:r.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function td(e){let r=e[0]?.length;if(!(!Number.isInteger(r)||r===0)&&e.every(t=>Array.isArray(t)&&t.length===r&&t.every(Ge)))return{fixedLength:r}}function Es(e,r=[]){return e.flatMap(t=>{let n=[...r,t.key];return t.childTable===!0?[{path:n,childFields:t.children}]:t.fixedLength!==void 0?[{path:n,fixedLength:t.fixedLength}]:t.children===void 0?[{path:n,listDelimiter:t.listDelimiter}]:Es(t.children,n)})}function vs(e,r){let t=e;for(let n of r)t=t[n];return t}function Ss(e,r){return e.listDelimiter!==void 0?`${te(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${te(e.key)}[${e.fixedLength}${ws(r)}]`:e.children===void 0?te(e.key):`${te(e.key)}{${e.children.map(t=>Ss(t,r)).join(r)}}`}function Ts(e,r,t,n,o,s){return r.childFields!==void 0?(Oh(o,e,r.childFields,n,s),String(e.length)):r.fixedLength!==void 0?e.map(i=>ae(i,t)).join(t):r.listDelimiter===void 0?ae(e,t):e.map(i=>Ah(i,t,r.listDelimiter)).join(r.listDelimiter)}function Oh(e,r,t,n,o){for(let s of r){Yr(e,o);let i=[];e.push(Es(t).map(a=>Ts(vs(s,a.path),a,n.delimiter,n,i,o+1)).join(n.delimiter)),e.push(`
|
|
28
|
+
`),e.push(...i)}}function Ah(e,r,t){return typeof e!="string"?ae(e,r):ds(e,r)||e.includes(t)?qn(e):e}var cd=[V,"|"," "];var ud=8,pd=/^[A-Za-z0-9_-]+$/,fP=new TextEncoder,hP=new TextDecoder;function Gh(e,r){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw M(r,"invalid trailer count");return Number.parseInt(t,10)}function md(e,r){if(!pd.test(e))throw M(r,"invalid tag")}function $h(e,r){let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t);if(!pd.test(n)){if(/^[A-Za-z0-9_-]/.test(n)&&/^[^,[\]|{}:\t ]+$/.test(n))throw M(r,"invalid tag");return null}return{tag:n,cellsText:e.slice(t+1)}}function Ih(e,r){if(!e.startsWith("["))return null;let t=e.slice(1),n=t.indexOf("]");if(n===-1)throw M(r,"invalid header");let o=t.slice(0,n),s=o.startsWith("~"),i=s?o.slice(1):o;if(!s&&i.startsWith("="))return null;if(!cd.includes(i)&&i!=="")throw M(r,"invalid header delimiter");let a=i===""?V:i,l=t.slice(n+1),d=null;if(!s&&l.startsWith("<")){let m=l.indexOf(">");if(m===-1)throw M(r,"invalid tag");if(d=l.slice(1,m),md(d,r),i!=="")throw M(r,"invalid header delimiter");l=l.slice(m+1)}if(!l.startsWith("{")||!l.endsWith("}:"))throw M(r,"invalid header");let c=l.slice(1,-2),u;try{u=Te(c,a,r).map(m=>Se(m,r)[0])}catch(m){throw Kr(m)}if(u.length===0||u.some(m=>m===""))throw M(r,"invalid header fields");return{delimiter:a,fields:u,fieldText:c,continuation:s,tag:d}}function Ch(e,r,t){if(e===null||e.delimiter===void 0)throw M(t,"continuation header before header");if(e.delimiter!==r.delimiter||e.fieldText!==r.fieldText)throw M(t,"continuation header mismatch")}function nd(e,r,t,n){let o;try{o=Te(e,r,n)}catch(s){throw Kr(s)}if(o.length!==t)throw M(n,"row arity mismatch");for(let s of o)try{be(s,n)}catch(i){throw Kr(i)}return o}function Nh(e,r,t){let n={};return e.forEach((o,s)=>{try{xe(n,o,be(r[s],t))}catch(i){throw Kr(i)}}),n}function Mh(e,r,t){if(e.startsWith("- "))throw M(r,"reserved line prefix");let n=Gh(e,r);if(n!==null){if(t===null||t.delimiter===void 0)throw M(r,"trailer without header");if(t.rowCount!==n)throw M(r,"trailer count mismatch");return{kind:"trailer"}}let o=Ih(e,r);if(o!==null)return o.continuation?(Ch(t,o,r),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=$h(e,r);if(s!==null){let i=t?.taggedLanes?.get(s.tag);if(i===void 0)throw M(r,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:nd(s.cellsText,i.delimiter,i.fields.length,r)}}if(t===null||t.delimiter===void 0)throw M(r,"row before header");return{kind:"row",cells:nd(e,t.delimiter,t.fields.length,r)}}function Fh(e,r={}){let t=[],n=new Map,o=[],s=[],i=null,a=!1,l=!1;function d(f,h){let v=s.at(-1);if(v!==void 0&&v.lane===f.lane&&v.delimiter===f.delimiter&&v.fieldText===f.fieldText){v.rows.push(h);return}s.push({lane:f.lane,delimiter:f.delimiter,fields:f.fields,fieldText:f.fieldText,rows:[h]})}function c(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function u(f,h,v){let y=n.get(f);if(y===void 0){if(n.size>=ud)throw M(v,"too many tagged lanes");y={segments:[],current:null},n.set(f,y),t.push(f)}else y.current!==null&&y.segments.push(y.current);y.current={lane:f,delimiter:h.delimiter,fields:h.fields,fieldText:h.fieldText,rows:[]},y.delimiter=h.delimiter,y.fields=h.fields,y.fieldText=h.fieldText}if(Hn(e).forEach((f,h)=>{let v=h+1;if(f==="")return;let y=i===null?{taggedLanes:n}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:n},S=Mh(f,v,y);if(S.kind==="trailer"){c(),i=null;return}if(S.kind!=="continuation"){if(S.kind==="tag-header"){l=!0,u(S.header.tag,S.header,v);return}if(S.kind==="header"){c(),a||(t.push(null),a=!0),i={lane:null,delimiter:S.header.delimiter,fields:S.header.fields,fieldText:S.header.fieldText,rows:[]};return}if(S.kind==="tagged-row"){l=!0;let G=n.get(S.tag).current;G.rows.push(S.cells),d(G,S.cells);return}if(i===null)throw M(v,"row before header");i.rows.push(S.cells),d(i,S.cells)}}),!l)return c(),r.preserveInterleaving===!0,o;let m=[];c();for(let f of t){if(f===null){m.push(...o);continue}let h=n.get(f);m.push(...h.segments),h.current!==null&&m.push(h.current)}return r.preserveInterleaving===!0?s:m}function Ie(e){return Fh(e).flatMap(r=>r.rows.map(t=>Nh(r.fields,t,0)))}function Wh(e){if(!cd.includes(e))throw M(0,"invalid header delimiter")}function od(e,r,t=!1){return`[${`${t?"~":""}${e===V?"":e}`}]{${r}}:
|
|
29
|
+
`}function sd(e,r){return`[]<${e}>{${r}}:
|
|
30
|
+
`}function xs(e,r){return r.map(te).join(e)}function Uh(e){if(!Array.isArray(e)||e.length===0)throw M(0,"TOONL header requires fields");return e.map(r=>{let t;try{[t]=Se(String(r),0)}catch(n){throw Kr(n)}if(t==="")throw M(0,"TOONL header requires fields");return t})}function id(e,r){return e!==null&&e.length===r.length&&e.every((t,n)=>t===r[n])}function ad(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw M(0,"TOONL continuation cadence must be positive")}function Bh(e,r,t){return e.continuationEveryRows!==void 0&&r>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function ld(e){if(e===null||typeof e!="object"||Array.isArray(e))throw M(0,"TOONL output requires object rows");let r=Object.keys(e);if(r.length===0)throw M(0,"TOONL output requires object rows");if(r.some(t=>!Ge(e[t])))throw M(0,"TOONL rows must be flat objects");return r}function Hh(e){return JSON.stringify([...e].sort())}function dd(e,r){let t=Hh(e),n=r.get(t);return n!==void 0?n:(r.set(t,e),e)}function ge({delimiter:e=V,trailer:r=!0,continuationEveryRows:t,continuationEveryBytes:n}={}){Wh(e),ad(t),ad(n);let o=null,s="",i=new Map,a=0,l=0,d=0,c=new Map,u=!1,m={continuationEveryRows:t,continuationEveryBytes:n},f=()=>o===null||!r?"":`[=${a}]
|
|
31
|
+
`,h=()=>Bh(m,l,d)?(l=0,d=0,od(e,s,!0)):"",v=y=>{md(y,0);let S=c.get(y);if(S===void 0){if(c.size>=ud)throw M(0,"too many tagged lanes");S={fields:null,fieldsByShape:new Map},c.set(y,S)}return S};return{push(y){if(u)throw M(0,"TOONL encoder is closed");let S=dd(ld(y),i),G="";(o===null||o.length!==S.length||o.some((Q,ee)=>Q!==S[ee]))&&(G+=f(),o=S,s=xs(e,o),a=0,l=0,d=0,G+=od(e,s));let H=o.map(Q=>ae(y[Q],e));G+=h();let L=`${H.join(e)}
|
|
32
|
+
`;return G+=L,a+=1,l+=1,d+=L.length,G},declareLane(y,S){if(u)throw M(0,"TOONL encoder is closed");let G=Uh(S),H=xs(V,G),L=v(y);return id(L.fields,G)?"":(L.fields=G,sd(y,H))},pushTagged(y,S){if(u)throw M(0,"TOONL encoder is closed");let G=v(y),H=dd(ld(S),G.fieldsByShape),L=xs(V,H),Q=H.map(le=>ae(S[le],V)),ee="";return id(G.fields,H)||(G.fields=H,ee+=sd(y,L)),`${ee}${y}:${Q.join(V)}
|
|
33
|
+
`},end(){return u?"":(u=!0,f())}}}function Ps(e){let r={app:e,version:qh(Xr("__RED_BUILD_VERSION__",()=>"3.6.2")??"0.0.0-dev"),gitSha:Xr("__RED_BUILD_GIT_SHA__",()=>"4a05257f346bc0c1025d1696e9f180f9185f5fe3")??"unknown",buildTime:Xr("__RED_BUILD_TIME__",()=>"2026-08-05T08:36:37Z")??"unknown",bundleAsset:Xr("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=Xr("__REDDB_SDK_VERSION__",()=>""),n=Xr("__REDDB_BINARY_TAG__",()=>"");return t&&(r.reddbSdkVersion=t),n&&(r.reddbBinaryTag=n),r}function qh(e){return e.startsWith("v")?e.slice(1):e}function gd(e){return`${e.app} ${e.version} ${e.gitSha}`}function Xr(e,r){try{let t=r();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var fd={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Vh=/^[a-z][a-z0-9+.-]*:\/\//i;function Kh(e,r){return typeof r=="string"?{separator:e,to:r,typed:!1,prefix:!1}:{separator:e,to:r.to,typed:r.typed??!1,prefix:r.prefix??!1}}function Jh(e=fd){return Object.entries(e).map(([r,t])=>Kh(r,t)).sort((r,t)=>t.separator.length-r.separator.length)}function zh(e){return/^-\d+(\.\d+)?$/.test(e)}function Nt(e){return!(!e||e.startsWith("-")&&!zh(e))}function Yn(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let r=Number(e);return!Number.isNaN(r)&&Number.isFinite(r)&&e.trim()!==""?r:e}function hd(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 r=Number(e);return!Number.isNaN(r)&&Number.isFinite(r)&&e.trim()!==""?r:e.includes(",")?e.split(",").map(t=>hd(t.trim())):e}function wr(e,r){switch(r){case"boolean":return Qh(e);case"number":return Yh(e);case"array":return e.split(",").map(t=>Yn(t.trim()));case"string":default:return e}}function Qh(e){let r=e.toLowerCase().trim();return r==="true"||r==="yes"||r==="1"||r==="on"}function Yh(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let r=Number(e);if(Number.isNaN(r))throw new TypeError(`Cannot convert "${e}" to number`);return r}function rr(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Xh(e,r={}){return e.map(t=>{let n=r[t.type];return n?n(t.value):t.value}).join("")}function F(e,r){return{type:e,value:r}}function Zh(e){let r=[],t=ry(e);if(r.push(F("section-header","Usage:"),F("text"," "),F("usage-text",t),F("newline",`
|
|
34
34
|
`),F("newline",`
|
|
35
35
|
`)),e.positional&&e.positional.length>0){r.push(F("section-header","Arguments:"),F("newline",`
|
|
36
36
|
`));for(let n of e.positional)if(n.description){let o=n.variadic?`${n.name}...`:n.name;r.push(F("indent"," "),F("positional-name",`<${o}>`)),n.required||r.push(F("positional-optional"," (optional)")),r.push(F("newline",`
|
|
37
37
|
`),F("indent"," "),F("option-description",n.description),F("newline",`
|
|
38
38
|
`))}r.push(F("newline",`
|
|
39
39
|
`))}if(e.options&&Object.keys(e.options).length>0){r.push(F("section-header","Options:"),F("newline",`
|
|
40
|
-
`));let n=
|
|
41
|
-
`))}return t}function
|
|
42
|
-
`),o=n.find(i=>i.startsWith("0::"));if(o)return o.slice(3)||null;let s=n[0]?.split(":").slice(2).join(":");return s===void 0||s===""?null:s}function
|
|
43
|
-
`)}catch{return!0}},append(e,r){
|
|
44
|
-
`),t.append(e,n),r}function
|
|
40
|
+
`));let n=ty(e.options);r.push(...n)}return r}function ey(e,r){let t=Zh(e);return Xh(t,r)}function ry(e){let r=["[options]"];if(e.positional)for(let t of e.positional)t.variadic?r.push(t.required?`<${t.name}...>`:`[${t.name}...]`):r.push(t.required?`<${t.name}>`:`[${t.name}]`);return r.join(" ")}function ty(e,r=!1){let t=[],n=[],o=r?"global-option-flag":"option-flag",s=r?"global-option-type":"option-type",i=r?"global-option-default":"option-default",a=r?"global-option-description":"option-description";for(let[d,c]of Object.entries(e)){if(c.hidden)continue;let u=[],m=v=>{u.includes(v)||u.push(v)};c.short&&m(`-${c.short}`),m(`--${d}`);for(let v of c.aliases??[])v.length===1?m(`-${v}`):m(`--${v}`);let f=u.join(", "),h=c.type&&c.type!=="boolean"?`<${c.type}>`:void 0;n.push({flags:f,type:h,desc:c.description??"",default:c.default!==void 0?String(c.default):void 0})}let l=Math.max(...n.map(d=>d.flags.length+(d.type?d.type.length+1:0)),20);for(let d of n){let c=d.flags.length+(d.type?d.type.length+1:0),u=" ".repeat(l-c+2);t.push(F("indent"," ")),t.push(F(o,d.flags)),d.type&&(t.push(F("text"," ")),t.push(F(s,d.type))),t.push(F("text",u)),t.push(F(a,d.desc)),d.default!==void 0&&(t.push(F("text"," ")),t.push(F(i,`(default: ${d.default})`))),t.push(F("newline",`
|
|
41
|
+
`))}return t}function yd(e){let r=dy(e.options??{},e.autoShort??!1),t=Jh(e.separators??fd);return{schema:e,parse(n){return ny(n,e,r,t)},help(){return ey(e,e.formatter)}}}function ny(e,r,t,n){let o={positional:{},options:{},errors:[],rest:[]},s=new Set(n.map(c=>c.to));for(let c of s)o[c]={};let i=0,a=r.positional??[],l=0,d=!1;for(;l<e.length;){let c=e[l];if(r.stopEarly&&i>0){o.rest=e.slice(l);break}if(c==="--"&&!d){d=!0,l++;continue}if(d){if(i<a.length){let m=a[i];if(m.variadic){let f=[];for(;l<e.length;){let h=e[l];f.push(m.type?wr(h,m.type):h),l++}o.positional[m.name]=f,i++}else{let f=m.type?wr(c,m.type):c;o.positional[m.name]=f,i++,l++}}else r.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(c)),l++;continue}if(c.startsWith("--")){l=ay(c,l,e,o,t,r);continue}if(c.startsWith("-")&&c.length>1&&!gy(c)){l=ly(c,l,e,o,t,r);continue}let u=oy(c,n);if(u){let{key:m,value:f,config:h}=u,v=o,y=v[h.to]??(v[h.to]={});y[m]=h.typed?hd(f):rr(f),l++;continue}if(i<a.length){let m=a[i];if(m.variadic){let h=[];for(;l<e.length&&!e[l].startsWith("-");){let v=e[l];h.push(m.type?wr(v,m.type):v),l++}o.positional[m.name]=h,i++;continue}let f=m.type?wr(c,m.type):c;o.positional[m.name]=f,i++}else r.allowUnknown!==!1?o.rest.push(c):o.errors.push(`Unexpected positional argument: ${c}`);l++}return uy(o,r,t),py(o,r,a),my(o,r,t),o}function oy(e,r){if(Vh.test(e))return null;for(let t of r){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(sy(i))return{key:i,value:a,config:t}}continue}let n=e.indexOf(t.separator);if(n>0){let o=e.slice(0,n),s=e.slice(n+t.separator.length);if(iy(o,s,t))return{key:o,value:s,config:t}}}return null}function sy(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function iy(e,r,t){return e?t.separator===":"?e.includes("/")||e.includes(".")||/^\d+$/.test(r)?!1:/^[A-Z][a-zA-Z0-9-]*$/.test(e):!((t.separator==="="||t.separator===":=")&&e.includes("/")):!1}function ay(e,r,t,n,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 n.options[d.name]=!1,r+1}if(i.includes("=")){let l=i.indexOf("="),d=i.slice(0,l),c=i.slice(l+1);return Xn(d,c,r+1,n,o,s)}let a=o.get(i);if(a){if(a.type!=="boolean"){let l=t[r+1];return Nt(l)?Xn(a.name,l,r+2,n,o,s):(n.errors.push(`Option --${i} requires a value`),r+1)}return n.options[a.name]=!0,r+1}return s.strict?n.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(n.options[i]=!0),r+1}function ly(e,r,t,n,o,s){let i=e.slice(1);if(i.includes("=")){let a=i.indexOf("="),l=i.slice(0,a),d=i.slice(a+1),c=Os(l,o);return c?Xn(c.name,d,r+1,n,o,s):(s.strict?n.errors.push(`Unknown option: -${l}`):s.allowUnknown!==!1&&(n.options[l]=Yn(rr(d))),r+1)}if(i.length===1){let a=Os(i,o);if(a){if(a.type!=="boolean"){let l=t[r+1];return Nt(l)?Xn(a.name,l,r+2,n,o,s):(n.errors.push(`Option -${i} requires a value`),r+1)}return n.options[a.name]=!0,r+1}if(s.strict)n.errors.push(`Unknown option: -${i}`);else if(s.allowUnknown!==!1){let l=t[r+1];if(Nt(l))return n.options[i]=Yn(rr(l)),r+2;n.options[i]=!0}return r+1}for(let a of i){let l=Os(a,o);l?l.type==="boolean"?n.options[l.name]=!0:n.errors.push(`Option -${a} requires a value`):s.strict?n.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(n.options[a]=!0)}return r+1}function Xn(e,r,t,n,o,s){let i=o.get(e);if(i){if(i.choices){let l=i.type?wr(rr(r),i.type):rr(r);if(!i.choices.includes(l))return n.errors.push(`Invalid value for '${e}': '${r}'. Allowed: ${i.choices.join(", ")}`),t}let a=i.type?wr(rr(r),i.type):rr(r);if(i.type==="array"){let l=n.options[e];Array.isArray(l)?l.push(...a):n.options[e]=a}else n.options[e]=a}else s.strict?n.errors.push(`Unknown option: --${e}`):s.allowUnknown!==!1&&(n.options[e]=Yn(rr(r)));return t}function dy(e,r=!1){let t=new Map,n=Object.entries(e).sort(([s],[i])=>s.localeCompare(i)),o=new Set;for(let[,s]of n)s.short&&o.add(s.short);for(let[s,i]of n){let a=i.short??"";r&&!a&&(a=cy(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 cy(e,r){for(let t of e){if(!/[a-zA-Z]/.test(t))continue;let n=t.toLowerCase();if(!r.has(n))return n;let o=t.toUpperCase();if(!r.has(o))return o}return""}function Os(e,r){for(let t of r.values())if(t.short===e||t.aliases.includes(e))return t}function uy(e,r,t){for(let n of t.values())if(e.options[n.name]===void 0)if(n.env&&process.env[n.env]!==void 0){let o=process.env[n.env];e.options[n.name]=n.type?wr(o,n.type):o}else n.default!==void 0&&(e.options[n.name]=n.default);for(let n of r.positional??[])e.positional[n.name]===void 0&&n.default!==void 0&&(e.positional[n.name]=n.default)}function py(e,r,t){if(r.options)for(let[n,o]of Object.entries(r.options))o.required&&e.options[n]===void 0&&e.errors.push(`Missing required option: --${n}`);for(let n of t)n.required&&e.positional[n.name]===void 0&&e.errors.push(`Missing required argument: <${n.name}>`)}function my(e,r,t){for(let n of t.values()){let o=e.options[n.name];if(n.validate&&o!==void 0){let s=n.validate(o);s!==!0&&e.errors.push(s)}}for(let n of r.positional??[]){let o=e.positional[n.name];if(n.validate&&o!==void 0){let s=n.validate(o);s!==!0&&e.errors.push(s)}}}function gy(e){return/^-\d+(\.\d+)?$/.test(e)}var As=class extends Error{flag;known;constructor(r,t){super(`unknown flag '${r}'; expected one of: ${t.join(", ")}`),this.name="UnknownFlagError",this.flag=r,this.known=t}};function fy(e){let r={};for(let[t,n]of Object.entries(e))r[t]={type:n.kind==="boolean"?"boolean":"string",...t.length===1?{short:t}:{},...n.aliases===void 0?{}:{aliases:n.aliases}};return r}function hy(e,r){let t=new Map;for(let[o,s]of Object.entries(r))if(!(s.kind!=="value"||s.type!=="array")){t.set(o,o);for(let i of s.aliases??[])t.set(i,o)}let n=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&&Nt(e[o+1])&&(l=e[o+1],o+=1),l===void 0)continue;let d=n.get(a)??[];d.push(l),n.set(a,d)}return n}function tr(e,r,t={}){let o=yd({options:fy(r),separators:{},allowUnknown:!0}).parse([...e]),s={},i=hy(e,r),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(r));for(let d of Object.keys(o.options))if(!l.has(d))throw new As(d.length===1?`-${d}`:`--${d}`,Object.keys(r).map(c=>c.length===1?`-${c}`:`--${c}`))}for(let[l,d]of Object.entries(r)){let c=o.options[l];c!==void 0&&(d.kind==="boolean"?s[l]=c:d.type==="array"?s[l]=(i.get(l)??[]).map(u=>d.coerce(u)):s[l]=d.coerce(String(c)))}return{values:s,positionals:o.rest}}var Ds=class extends Error{token;known;constructor(r,t){super(`unknown command '${r}'; expected one of: ${t.join(", ")}`),this.name="UnknownCommandError",this.token=r,this.known=t}};function bd(e,r){let[t,...n]=e;if(t!==void 0){for(let[s,i]of Object.entries(r.commands))if(t===s||(i.aliases??[]).includes(t))return{command:s,args:n};if(r.errorOnUnknownCommand&&!t.startsWith("-"))throw new Ds(t,Object.keys(r.commands))}let o=r.keepArgvOnDefault??!0;return{command:r.default,args:o?[...e]:n}}import{appendFileSync as xy,mkdirSync as Py,readFileSync as Pd,statSync as Oy}from"node:fs";import{dirname as Ad,join as Ay}from"node:path";var kd="RED_WORKER_SCOPE",_d="RED_WORKER_MEMORY_CEILING",Rd="RED_WORKER_SCOPE_DEGRADATION",Ls={scope:null,memory_ceiling:null,scope_degradation:null};function Gs(e){return{scope:js(e[kd]),memory_ceiling:js(e[_d]),scope_degradation:js(e[Rd])}}function Mt(e){let r={};return e.scope!=null&&e.scope!==""&&(r[kd]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(r[_d]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(r[Rd]=e.scope_degradation),r}function js(e){let r=(e??"").trim();return r===""?null:r}import{mkdirSync as ky,readdirSync as _y,readFileSync as Sd,rmSync as Ry,writeFileSync as wy}from"node:fs";import{basename as Ey,join as Zr}from"node:path";import{isAbsolute as zP,join as Zn,resolve as QP}from"node:path";function yy(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var wd="deaths",Ed="deaths.toonl";function eo(e){return Zn(yy(e),wd)}function Ft(e){return Zn(eo(e),Ed)}var Wt="live",vd="attributions.toonl";function ro(e){return Zn(eo(e),Wt)}function $s(e){return Zn(eo(e),vd)}var Cs=Zr("sys","kernel","random","boot_id"),Td=1;function Ns(e,r={}){let t=r.procRoot??"/proc",n=e.pid??process.pid;return{version:Td,ts:(r.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:n,ppid:e.ppid??process.ppid,boot_id:xd(Zr(t,Cs)),cgroup:vy(t,n),last_phase:e.last_phase}}function xd(e){try{let r=Sd(e,"utf8").trim();return r===""?null:r}catch{return null}}function vy(e,r){let t=xd(Zr(e,String(r),"cgroup"));if(t===null)return null;let n=t.split(`
|
|
42
|
+
`),o=n.find(i=>i.startsWith("0::"));if(o)return o.slice(3)||null;let s=n[0]?.split(":").slice(2).join(":");return s===void 0||s===""?null:s}function Ms(e){let r=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${r}-${e.pid}.toon`}function Fs(e,r){let t=Zr(e,Ms(r));try{return ky(e,{recursive:!0,mode:448}),wy(t,ge({trailer:!1}).push(Ty(r)),{encoding:"utf8",mode:384}),t}catch{return null}}function Er(e,r){try{Ry(Zr(e,Ms(r)),{force:!0})}catch{}}function Ws(e,r){let t;try{t=_y(e)}catch{return[]}let n=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=Zr(e,o);try{let a=Ie(Sd(s,"utf8"))[0];if(a===void 0)throw new Error("anchor holds no record");n.push(Sy(a))}catch(i){r?.(Ey(s),i instanceof Error?i.message:String(i))}}return n}function Sy(e){let r=e.kind;if(r!=="launcher"&&r!=="worker"&&r!=="daemon")throw new Error(`presence anchor has unknown kind ${String(r)}`);return{version:Is(e.version),ts:String(e.ts),kind:r,id:String(e.id),pid:Is(e.pid),ppid:Is(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 Is(e){return typeof e=="number"?e:Number(e)}function Ty(e){return{...e}}var Dy=1,jy=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Ly(e){return typeof e=="string"&&jy.has(e)}var Gy="startup";function $y(e,r){return{...e.scope??Ls,version:Dy,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,...r}}function Iy(e){let r=e.resourceUsage();return{uptime_s:Math.round(e.uptime()),rss_kb:Math.round(e.memoryUsage().rss/1024),max_rss_kb:r.maxRSS,user_cpu_us:r.userCPUTime,system_cpu_us:r.systemCPUTime,minor_page_faults:r.minorPageFault,major_page_faults:r.majorPageFault,voluntary_ctx_switches:r.voluntaryContextSwitches,involuntary_ctx_switches:r.involuntaryContextSwitches}}var Bs={mkdir(e){Py(e,{recursive:!0,mode:448})},endsClean(e){let r;try{r=Oy(e).size}catch{return!0}if(r===0)return!0;try{return Pd(e,"utf8").endsWith(`
|
|
43
|
+
`)}catch{return!0}},append(e,r){xy(e,r,{encoding:"utf8",mode:384})},read(e){return Pd(e,"utf8")}};function Cy(e){let r={};for(let[t,n]of Object.entries(e))r[t]=n;return r}function Ny(e,r,t=Bs){let n=ge({trailer:!1}).push(Cy(r));return t.mkdir(Ad(e)),t.endsClean(e)||t.append(e,`
|
|
44
|
+
`),t.append(e,n),r}function Dd(e){let r=e.endsWith(`
|
|
45
45
|
`)?e:e.slice(0,e.lastIndexOf(`
|
|
46
|
-
`)+1);return r===""?[]
|
|
47
|
-
`).filter(u=>u.trim()!=="");a.push(...c),n.push({source:l,result:c.length===0?"empty":"read",detail:`${c.length} lines`})}catch(d){n.push({source:l,result:
|
|
46
|
+
`)+1);return r===""?[]:Ie(r).map(My)}function My(e){let r=e.exit_path;if(!Ly(r))throw new Error(`death record has unknown exit_path ${JSON.stringify(r)}`);let t=e.kind;if(t!=="launcher"&&t!=="worker"&&t!=="daemon")throw new Error(`death record has unknown kind ${JSON.stringify(t)}`);return{version:ke(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:ke(e.pid),exit_path:r,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:ke(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:ke(e.uptime_s),rss_kb:ke(e.rss_kb),max_rss_kb:ke(e.max_rss_kb),user_cpu_us:ke(e.user_cpu_us),system_cpu_us:ke(e.system_cpu_us),minor_page_faults:ke(e.minor_page_faults),major_page_faults:ke(e.major_page_faults),voluntary_ctx_switches:ke(e.voluntary_ctx_switches),involuntary_ctx_switches:ke(e.involuntary_ctx_switches)}}function ke(e){return typeof e=="number"?e:Number(e)}function jd(e,r=Bs){let t;try{t=r.read(e)}catch(n){if(n.code==="ENOENT")return[];throw n}return Dd(t)}var Fy=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],Us=null;function Ld(e){let r=e.host??process,t=e.io??Bs,n=e.clock??(()=>new Date().toISOString()),o=r.pid,s=e.scope??Gs(process.env),i=e.phase??Gy,a=null,l=e.presenceDir===void 0?Ay(Ad(e.lanePath),Wt):e.presenceDir,d=null,c=()=>{l!==null&&(d=Ns({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),Fs(l,d))},u=y=>{if(!a){try{a=Ny(e.lanePath,$y({ts:n(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...y},Iy(r)),t)}catch{}l!==null&&d!==null&&Er(l,d)}},m={signal(y){u({exit_path:"signal",signal:y})},exit(y){u({exit_path:"exit",exit_code:y})},uncaughtException(y){u({exit_path:"uncaught-exception",detail:Od(y)})},unhandledRejection(y){u({exit_path:"unhandled-rejection",detail:Od(y)})}},h=[...(e.signals??Fy).map(y=>{let S=()=>{if(m.signal(y),!(r.listenerCount?.(y)!==1||!r.kill)){r.off(y,S);try{r.kill(o,y)}catch{}}};return[y,S]}),["uncaughtException",(...y)=>m.uncaughtException(y[0])],["unhandledRejection",(...y)=>m.unhandledRejection(y[0])],["exit",(...y)=>m.exit(typeof y[0]=="number"?y[0]:null)]];for(let[y,S]of h)r.on(y,S);let v={lanePath:e.lanePath,phase(y){i=y,a||c()},currentPhase:()=>i,written:()=>a,uninstall(){for(let[y,S]of h)r.off(y,S);l!==null&&d!==null&&Er(l,d),Us===v&&(Us=null)},handlers:m};return e.setActive!==!1&&(Us=v),c(),v}function Od(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Wy,readdirSync as Uy,readFileSync as to,statSync as By,writeFileSync as Hy}from"node:fs";import{join as Cd}from"node:path";var qy=1,Vy=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],Ky=512*1024;function Jy(e={}){let r=e.procRoot??"/proc",t=e.journalPaths??Vy,n=[],o=Cd(r,Cs),s=null;try{let l=to(o,"utf8").trim();s=l===""?null:l,n.push({source:o,result:s?"read":"empty",detail:s})}catch(l){n.push({source:o,result:Hs(l),detail:null})}let i=new Set;try{for(let l of Uy(r))/^\d+$/.test(l)&&i.add(Number(l));n.push({source:r,result:"read",detail:`${i.size} live pids`})}catch(l){n.push({source:r,result:Hs(l),detail:null})}let a=[];for(let l of t)try{let c=zy(l,e.tailBytes??Ky).split(`
|
|
47
|
+
`).filter(u=>u.trim()!=="");a.push(...c),n.push({source:l,result:c.length===0?"empty":"read",detail:`${c.length} lines`})}catch(d){n.push({source:l,result:Hs(d),detail:null})}return{boot_id:s,live_pids:i,journal:a,probes:n}}function Hs(e){return e.code==="ENOENT"?"absent":"unreadable"}function zy(e,r){let t=By(e).size,n=to(e,"utf8");return t<=r?n:n.slice(n.length-r)}var Qy=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,Yy=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,Xy=/Killed (\/\S*) due to memory pressure/,Zy=/\bopid=(\d+)\b/,Gd=/\bsig=(\d+)\b/,eb=/\buid=(\d+)\b/,rb=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,tb={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function nb(e,r,t,n){let o=e.boot_id!==null&&r.boot_id!==null&&e.boot_id!==r.boot_id,s=[...r.probes.map(u=>`${u.source}: ${u.result}${u.detail?` (${u.detail})`:""}`),`boot id: anchored under ${e.boot_id??"unknown"}, host now ${r.boot_id??"unknown"} (${o?"changed":"same"})`,`parent account: ppid ${e.ppid}`,`cgroup: ${e.cgroup??"unknown"}`],i=(u,m,f,h)=>({version:qy,ts:n,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:u,confidence:m,signal:f,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=r.journal.find(u=>$d(u,e.pid,Qy)||$d(u,e.pid,Yy));if(l!==void 0)return i("oomd",o?"medium":"high","SIGKILL",[l,...a]);if(e.cgroup!==null)for(let u of r.journal){let m=Xy.exec(u)?.[1];if(m!==void 0){if(m===e.cgroup)return i("oomd",o?"medium":"high","SIGKILL",[u,...a]);if(e.cgroup.startsWith(`${m}/`))return i("oomd","medium","SIGKILL",[u,`the killed scope ${m} is an ancestor of this process's ${e.cgroup}`,...a])}}let d=r.journal.find(u=>Number(Zy.exec(u)?.[1])===e.pid&&Gd.test(u));if(d!==void 0){let u=Number(Gd.exec(d)?.[1]),m=eb.exec(d)?.[1];return i("user-signal",o?"medium":"high",tb[u]??null,[d,...m===void 0?[]:[`sent by uid ${m}`],...a])}let c=t.find(u=>u.pid===e.ppid);if(c!==void 0&&!r.live_pids.has(e.ppid))return i("parent-death","medium",null,[`parent pid ${e.ppid} (${c.kind} ${c.id}) recorded its own death at ${c.ts} via ${c.exit_path}${c.signal?` ${c.signal}`:""}`]);if(o){let u=r.journal.find(m=>rb.test(m));return u!==void 0?i("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${r.boot_id}`,u]):i("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${r.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 $d(e,r,t){return Number(t.exec(e)?.[1])===r}var ob=" | ";function Id(e){return e.map(r=>r.replace(/[|\n\r]+/g," ").trim()).join(ob)}function sb(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:Id(e.evidence),checked:Id(e.checked)}}function ib(e){let r=ge({trailer:!1});return e.map(t=>r.push(sb(t))).join("")}function Nd(e){let r=ro(e.stateRoot),t=$s(e.stateRoot),n=e.now??(()=>new Date().toISOString()),o=e.evidence??Jy({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=Ws(r,u=>s.push(u)),a=jd(Ft(e.stateRoot)),l=[],d=[],c=[];for(let u of i){if(o.live_pids.has(u.pid)){d.push(u);continue}if(a.find(f=>f.pid===u.pid&&f.id===u.id)!==void 0){c.push(u),Er(r,u);continue}l.push(nb(u,o,a,n())),Er(r,u)}return l.length>0&&ab(t,l),{attributions:l,alive:d,self_recorded:c,skipped:s,laneText:()=>{try{return to(t,"utf8")}catch{return""}}}}function Md(e){let r=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})${r}`;let t=e.attributions.map(n=>` | ${n.kind} ${n.id} pid=${n.pid} ${n.sender_class}/${n.confidence} phase=${n.last_phase}`+(n.evidence[0]?` evidence="${n.evidence[0]}"`:"")).join("");return`death reaper: attributed ${e.attributions.length}${t}${r}`}function ab(e,r){try{Wy(Cd(e,".."),{recursive:!0,mode:448});let t=lb(e),n=t===""||t.endsWith(`
|
|
48
48
|
`)?"":`
|
|
49
|
-
`;
|
|
50
|
-
`)){let o=n.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(".")===r)return
|
|
51
|
-
`||e[r]==="\r";)r+=1;let t=e.slice(r);if(t==="")return null;let n=
|
|
49
|
+
`;Hy(e,`${t}${n}${ib(r)}`,{encoding:"utf8",mode:384})}catch{}}function lb(e){try{return to(e,"utf8")}catch{return""}}import{join as db}from"node:path";var cb=[".red","redskilled"],Ve=448;function Ce(e){return db(e,...cb)}import{execFileSync as vb}from"node:child_process";import{readFileSync as Sb}from"node:fs";import{dirname as Vd,join as Tb}from"node:path";import{existsSync as ub,readFileSync as xO}from"node:fs";import{dirname as pb,join as mb}from"node:path";function Fd(e,r){let t=e;for(let n=0;n<16;n++){let o=mb(t,r);if(ub(o))return o;let s=pb(t);if(s===t)break;t=s}return null}function gb(e){let r=e.indexOf(" #");return(r>=0?e.slice(0,r):e).trim()}function et(e,r){let t=[];for(let n of e.split(`
|
|
50
|
+
`)){let o=n.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(".")===r)return gb(d)}}import{createHash as fb}from"node:crypto";var hb="project.name";function Ud(e){let r=et(e,hb)?.trim();return r===void 0||r===""?void 0:r}var yb=8,Bd="project";function Hd(e){let r=wb(e.gitCommonDir),t=(e.declaredName??"").trim(),n=t!==""?{name:t,source:"declared"}:bb(e.remoteUrl)??{name:kb(e.checkoutPath,r),source:"basename"},o=Rb(r??qs(e.checkoutPath));return{name:n.name,slug:`${_b(n.name)}-${o}`,hash:o,source:n.source}}function qd(e){let r=(e??"").trim();if(r==="")return;let t=r.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),n=/^[^/]*?:(?!\d)(.+)$/.exec(t),s=(n?n[1]:t.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(i=>i.trim()).filter(i=>i!=="");if(s.length!==0)return s.slice(-2).join("/")}function bb(e){let r=qd(e);return r===void 0?void 0:{name:r,source:"remote"}}function kb(e,r){let t=r===void 0?"":Wd(Eb(r));if(t!=="")return t;let n=Wd(qs(e));return n===""?Bd:n}function _b(e){let t=e.split("/").map(n=>n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(n=>n!=="").join("--");return t===""?Bd:t}function Rb(e){return fb("sha256").update(e).digest("hex").slice(0,yb)}function wb(e){let r=qs(e??"");return r===""?void 0:r}function qs(e){let r=e.trim().replace(/\\/g,"/");return r.length>1?r.replace(/\/+$/,""):r}function Wd(e){let r=e.split("/").filter(t=>t!=="");return r[r.length-1]??""}function Eb(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var xb=2e3;function Kd(e){return Pb(e).name}function Pb(e){let r=Ks(e),t=Vs(e,["rev-parse","--absolute-git-dir"])??Vs(e,["rev-parse","--git-common-dir"]),n=Vs(e,["remote","get-url","origin"]);return Hd({checkoutPath:r.root??e,...t!==void 0?{gitCommonDir:t}:{},...n!==void 0?{remoteUrl:n}:{},...r.name!==void 0?{declaredName:r.name}:{}})}function Ks(e){let r=Fd(e,Tb(".red","config.yaml"));if(r==null)return{};let t;try{t=Sb(r,"utf8")}catch{return{}}let n=Ud(t),o=Vd(Vd(r));return{...n===void 0?{}:{name:n},configText:t,root:o}}function Vs(e,r){try{let t=vb("git",[...r],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:xb}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as Eg}from"node:crypto";import{spawn as QS}from"node:child_process";import{mkdir as YS}from"node:fs/promises";import{dirname as XS}from"node:path";import{createHash as Db}from"node:crypto";import{constants as Xs}from"node:fs";import{mkdir as tc,open as jb,readFile as Lb,rm as nc,stat as Gb}from"node:fs/promises";import{createConnection as $b}from"node:net";import{tmpdir as Ib}from"node:os";import{dirname as oc,join as Ut}from"node:path";var Ob="toon";function Qd(e){return e.trimStart().startsWith("{")?"json":"toon"}function zs(e){let r=0;for(;e[r]===`
|
|
51
|
+
`||e[r]==="\r";)r+=1;let t=e.slice(r);if(t==="")return null;let n=Qd(t);if(n==="json"){let s=t.indexOf(`
|
|
52
52
|
`);return s<0?null:{frame:t.slice(0,s),dialect:n,rest:t.slice(s+1)}}let o=t.indexOf(`
|
|
53
53
|
|
|
54
|
-
`);return o<0?null:{frame:t.slice(0,o+1),dialect:n,rest:t.slice(o+2)}}function
|
|
54
|
+
`);return o<0?null:{frame:t.slice(0,o+1),dialect:n,rest:t.slice(o+2)}}function Qs(e){let r=Qd(e)==="json"?Js:Jd,t=r===Js?Jd:Js;try{return r(e)}catch(n){try{return t(e)}catch{throw n}}}function Js(e){return JSON.parse(e)}function Jd(e){return ue(e)}function Ys(e,r){if(r==="toon"){let t=Ab(e);if(t!==null)return t.endsWith(`
|
|
55
55
|
`)?`${t}
|
|
56
56
|
`:`${t}
|
|
57
57
|
|
|
58
58
|
`}return`${JSON.stringify(e)}
|
|
59
|
-
`}function
|
|
60
|
-
`).catch(()=>{}),{acquired:!0,lockPath:e,handle:l,reaped:i};let d=await
|
|
61
|
-
`,1)[0]?.trim()??"";if(!r.startsWith(sc))return null;let t=Number(/\bpid=(\d+)\b/.exec(r)?.[1]??""),n=/\btaken=(\S+)/.exec(r)?.[1]??"";return!Number.isInteger(t)||t<=0||!Number.isFinite(Date.parse(n))?null:{pid:t,takenAt:n}}async function Mk(e,r,t){let n=r==null?Number.NaN:Date.parse(r.takenAt);if(Number.isFinite(n))return Math.max(0,t-n);try{return Math.max(0,t-(await Ok(e)).mtimeMs)}catch{return null}}function oe(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}var Fk="/tmp";function to(e){let r=e.env??process.env,t=Tk("sha256").update(e.key).digest("hex").slice(0,20),n=l=>Mt(l,e.socketFileName).length<jk,o=r.XDG_RUNTIME_DIR;if(o){let l=Mt(o,"red-skills",t);if(n(l))return l}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=Mt(`red-skills-${s}`,t),a=Mt(Dk(),i);return n(a)||process.platform==="win32"?a:Mt(Fk,i)}Ve();import{homedir as db}from"node:os";import{join as di}from"node:path";import{spawnSync as cb}from"node:child_process";import{createHash as ub}from"node:crypto";import{existsSync as pb,readdirSync as mb}from"node:fs";import{mkdir as hc,readFile as gb,rename as fb,writeFile as hb}from"node:fs/promises";import{dirname as yb}from"node:path";var vr="@reddb-io/red-skills",Yk="https://registry.npmjs.org",Xk="canary",Er=class extends Error{kind;cause;constructor(r,t,n){super(t),this.name="BundleFetchError",this.kind=r,this.cause=n}},Zk=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;function oi(e){return typeof e=="string"&&Zk.test(e.trim())}function pc(e){return`${e}-.bundle.min.mjs`}var eb=".unversioned";function rb(e,r,t="stable"){if(t==="canary")return`${e}-canary.bundle.min.mjs`;if(!oi(r))throw new Er("invalid-version",`refusing to key the ${e} bundle cache on ${JSON.stringify(r??"")}: it would mint ${pc(e)}, a name no resolver prefers and one whose mere existence satisfies the cache-first test forever (#3153)`);return`${e}-${r.trim()}.bundle.min.mjs`}function io(e){let{plugin:r,version:t,cacheDir:n,channel:o}=e;return Ut(n,rb(r,t,o))}function tb(e){return e==="dev"?["rsp","redskilled"]:[]}function nb(e){return`${e}.bundle.min.mjs`}function ob(e){return Ut("dist",nb(e))}function sb(e,r="stable"){return`${vr}@${r==="canary"?Xk:e}`}function si(e=vr){return`${Yk}/${e.replace("/","%2F")}`}async function ii(e,r){let{plugin:t,version:n,cacheDir:o,channel:s="stable"}=r,i=io({plugin:t,version:n,cacheDir:o,channel:s}),a=tb(t),l=a.map(m=>io({plugin:m,version:n,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await ab(e,l))return i;let d=sb(n,s),c=Ut(o,`.staging-${t}-${s==="canary"?"canary":n}`),u;try{u=await e.materialize(d,c)}catch(m){throw fc(m,d)}for(let m of[t,...a]){let h=ob(m),f=Ut(u,h);if(!await e.exists(f))throw new Er("bundle-missing",`npm package ${d} has no ${h}`);let S=m===t?i:io({plugin:m,version:n,cacheDir:o,channel:s});await e.writeFile(S,await e.readFile(f))}return await ib(e,o,[t,...a]),i}async function ib(e,r,t){if(e.rename)for(let n of t){let o=Ut(r,pc(n));try{if(!await e.exists(o))continue;await e.rename(o,`${o}${eb}`)}catch{}}}async function ab(e,r){for(let t of r)if(!await e.exists(t))return!1;return!0}async function mc(e,r,t=vr){let n;try{n=await e.fetchText(si(t))}catch(s){throw fc(s,t)}let o=ai(n);return{sameMajor:lb(o,r),newest:li(o)}}function ai(e){let r;try{r=JSON.parse(e)}catch{return[]}if(typeof r!="object"||r===null)return[];let t=r.versions;return typeof t!="object"||t===null?[]:Object.keys(t)}function lb(e,r){let t=ni(r);if(t===null)return null;let n=null;for(let o of e)ni(o)===t&&(n===null||gc(o,n)>0)&&(n=o);return n}function li(e){let r=null;for(let t of e){let n=String(t).trim();ni(n)===null||/^\d+\.\d+\.\d+[-+]/.test(n)||(r===null||gc(n,r)>0)&&(r=n)}return r}function ni(e){let r=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return r?Number(r[1]):null}function gc(e,r){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),n=/^(\d+)\.(\d+)\.(\d+)/.exec(r.trim());return!t||!n?0:Number(t[1])-Number(n[1])||Number(t[2])-Number(n[2])||Number(t[3])-Number(n[3])}function fc(e,r){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Er("npm-unavailable",`npm is unavailable while resolving ${r}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Er("package-missing",`npm could not resolve ${r}: ${t}`,e):new Er("network",`failed to resolve ${r}: ${t}`,e)}function Ut(e,r){return e.endsWith("/")?`${e}${r}`:`${e}/${r}`}Ve();var yc={async materialize(e,r){await hc(r,{recursive:!0});let t=cb("npm",["install",e,"--prefix",r,"--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 di(r,"node_modules",...vr.split("/"))},async readFile(e){return new Uint8Array(await gb(e))},async writeFile(e,r){await hc(yb(e),{recursive:!0}),await hb(e,r)},async exists(e){return pb(e)},sha256(e){return ub("sha256").update(e).digest("hex")},async fetchText(e){let r=await fetch(e,{redirect:"follow"});if(!r.ok)throw new Error(`GET ${e} -> ${r.status}`);return await r.text()},async rename(e,r){await fb(e,r)}},kb="redskilled";function bb(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let r=e.XDG_CACHE_HOME||di(e.HOME||db(),".cache");return di(r,"red-skills","bundles")}var _b=/^([a-z0-9-]+)-(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?)\.bundle\.min\.mjs$/;async function Rb(e,r){if(oi(e.version))return e.version.trim();let t=e.listCacheDir??vb,n=wb(t(r),"dev");if(n)return n;try{let s=await(e.bundleIO??yc).fetchText(si());return li(ai(s))}catch{return null}}function wb(e,r){let t=null;for(let n of e){let o=_b.exec(n);if(!o||o[1]!==r)continue;let s=o[2];(t===null||Eb(s,t)>0)&&(t=s)}return t}function Eb(e,r){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e),n=/^(\d+)\.(\d+)\.(\d+)/.exec(r);return Number(t[1])-Number(n[1])||Number(t[2])-Number(n[2])||Number(t[3])-Number(n[3])}function vb(e){try{return mb(e)}catch{return[]}}async function Sb(e={},r={},t={}){let n=tr(e,r);if(Ne(n))return n;let o=t.env??r.env??process.env,s=bb(o),i=await Rb(t,s);if(i===null)return n;try{await ii(t.bundleIO??yc,{plugin:kb,version:i,cacheDir:s})}catch{return n}return tr(e,r)}async function kc(e={},r={},t={}){let n=await Sb(e,r,t);if(Ne(n))return n;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(Ve(),uc));throw new o(n)}import{randomUUID as Bo}from"node:crypto";import{mkdir as TS,rm as gg}from"node:fs/promises";import{connect as xS,createServer as PS}from"node:net";import{dirname as OS}from"node:path";import{availableParallelism as Rc,totalmem as xb}from"node:os";function Bt(e){if(e.applied_budget!=null)return e.applied_budget;let r=e.budget??{};return r.memory_max==null&&r.memory_high==null&&e.memory_ceiling!=null?{...r,memory_max:e.memory_ceiling}:r}function bc(e,r={}){let t=0,n=0,o=0,s=[],i=[];for(let d of e){let c=Bt(d),u=!1;for(let[m,h]of[[c.memory_high,f=>t+=f],[c.memory_max,f=>n+=f]]){if(m==null)continue;let f=Zr(m);f==null?u=!0:h(f)}c.cpu_weight!=null&&(o+=c.cpu_weight),u&&s.push(d.worker_id),d.isolated||i.push(d.worker_id)}let a=r.hostCeilingBytes??null,l=a==null?0:Math.max(0,n-a);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:n,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:Tb(e.length,n,a,l)}}function Tb(e,r,t,n){return`this host's ${e} Worker(s) carry ${r} bytes of applied MemoryMax against a host ceiling of ${t} bytes \u2014 ${n} 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 Zr(e){let r=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!r)return null;let t={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[r[2].toLowerCase()];return Math.round(Number(r[1])*t)}function _c(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.version===1&&Number.isInteger(r.worker_count)&&typeof r.memory_high_bytes=="number"&&typeof r.memory_max_bytes=="number"&&typeof r.cpu_weight_total=="number"&&Array.isArray(r.unaccounted_workers)&&Array.isArray(r.unisolated_workers)}var wc="REDSKILLED_MEMORY_CEILING",ui="REDSKILLED_WORKER_CEILING",Tc="REDSKILLED_VALIDATION_CEILING",Ec="REDSKILLED_INTERACTIVE_RESERVATION",Ht=1,vc=.7,Pb=2*1024**3,Ob=2;function xc(e){let r=e?.memory_max??e?.memory_high;if(r!=null)return Zr(r)}function lo(e){let r=0,t=[];for(let n of e){let o=xc(n.budget);o===null?t.push(n.worker_id):o!==void 0&&(r+=o)}return{worker_count:e.length,memory_bytes:r,unaccounted_workers:t.sort()}}function Pc(e){let{ceiling:r}=e,t=lo(e.workers),n=xc(e.budget),o=n===void 0?null:n,s=t.memory_bytes+(n??0),i=t.worker_count+1,a=Math.max(0,r.interactive_reservation??Ht),l=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",d=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,c=(h,f)=>({version:1,admitted:!1,verdict:h,reason:f,ceiling:r,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}),u=r.worker_count==null?0:i-r.worker_count;if(u>0){if(e.reservation!=="interactive")return c("refused-over-worker-ceiling",`redskilled refused this Worker${l}: it would be Worker ${i} past a host ceiling of ${r.worker_count} Worker(s); ${a} extra slot(s) are reserved for interactive dispatches, and ${d}`);if(u>a)return c("refused-over-interactive-reservation",`redskilled refused this interactive Worker${l}: reserved slot ${u}/${a} is outside the bounded interactive reservation above the host ceiling of ${r.worker_count} Worker(s), and ${d}`)}if(r.memory_bytes!=null&&n===null)return c("refused-unaccountable-budget",`redskilled refused this Worker${l}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${r.memory_bytes} bytes, and ${d}`);if(r.memory_bytes!=null&&s>r.memory_bytes)return c("refused-over-memory-ceiling",`redskilled refused this Worker${l}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${r.memory_bytes} bytes, and ${d}`);let m=e.reservation==="interactive"&&u>0;return{version:1,admitted:!0,verdict:m?"admitted-interactive-reservation":"admitted",reason:m?`redskilled admitted this interactive Worker${l} into reserved interactive slot ${u}/${a} above the host ceiling of ${r.worker_count} Worker(s): ${s} bytes of declared Worker memory against a host ceiling of ${r.memory_bytes??"unbounded"} bytes, and ${d}`:`redskilled admitted this Worker${l}: ${s} bytes of declared Worker memory against a host ceiling of ${r.memory_bytes??"unbounded"} bytes, and ${d}`,ceiling:r,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function Oc(e){let r=e.budget?.memory_max??e.budget?.memory_high;if(r!=null)return{memory_max:r,reason:`the client declared this Worker's memory ceiling (${r}), 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=lo(e.workers),n=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,s=o==null?n:Math.floor(e.ceiling.memory_bytes/o),i=Math.min(n,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 (${ui} 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 co(e=process.env,r=xb(),t={}){let n=ci(t.flags?.memoryCeiling,e[wc],t.config?.memoryCeiling),o=ci(t.flags?.workerCeiling,e[ui],t.config?.workerCeiling),s=ci(t.flags?.validationCeiling,e[Tc],t.config?.validationCeiling),i=n?.value??"",a=o?.value??"",l=(e[Ec]??"").trim(),d=Ac(a),c=l===""?Ht:jb(l),u=o?.source??"derived-default";if(a!==""&&d===null&&!Ab(a)&&(ao(`redskilled: ${pi(o)} ${ui}=${JSON.stringify(a)} is not a positive integer; this host admits an unbounded number of Workers instead.`),u="derived-default"),i!==""){let m=Db(i,r);if(m!==void 0)return Sc({memory_bytes:m,worker_count:d,interactive_reservation:c??Ht,source:"declared",memory_source:n.source,worker_source:u},s,t.availableParallelism??Rc());ao(`redskilled: ${pi(n)} ${wc}=${JSON.stringify(i)} is not a memory ceiling this host can read; using ${vc*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return l!==""&&c===void 0&&ao(`redskilled: ${Ec}=${JSON.stringify(l)} is not a non-negative integer; using the default reservation of ${Ht} Worker(s) instead.`),Sc({memory_bytes:Math.floor(r*vc),worker_count:d,interactive_reservation:c??Ht,memory_source:"derived-default",worker_source:u,source:"host-fraction"},s,t.availableParallelism??Rc())}function Sc(e,r,t){if(r!==void 0){let i=Ac(r.value);if(i!==null)return{...e,validation_count:i,validation_source:r.source};ao(`redskilled: ${pi(r)} ${Tc}=${JSON.stringify(r.value)} is not a positive integer; deriving the validation ceiling from host CPU, memory, and Worker capacity instead.`)}let n=Math.max(1,Math.floor(Math.max(1,t)/Ob)),o=e.memory_bytes==null?Number.POSITIVE_INFINITY:Math.max(1,Math.floor(e.memory_bytes/Pb)),s=e.worker_count??Number.POSITIVE_INFINITY;return{...e,validation_count:Math.max(1,Math.min(n,o,s)),validation_source:"derived-default"}}function ci(e,r,t){if(e?.trim())return{value:e.trim(),source:"flag"};if(r?.trim())return{value:r.trim(),source:"environment"};if(t?.trim())return{value:t.trim(),source:"home-config"}}function pi(e){return e.source==="flag"?"serve flag":e.source==="environment"?"environment":e.source==="home-config"?"home config":"derived default"}function Ab(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var ao=e=>process.stderr.write(`${e}
|
|
62
|
-
`);function
|
|
63
|
-
`);return r.pop(),r.length===0?[]
|
|
59
|
+
`}function Ab(e){try{let r=JSON.stringify(e);if(r===void 0)return null;let t=J(JSON.parse(r));return t.trim()===""?null:t}catch{return null}}function Yd(e,r){return!zd(e)||!zd(r)||r.ok!==!1?!1:typeof e.id=="string"&&typeof r.id=="string"&&r.id!==e.id}function zd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Xd=new Set;function Zd(e){return Xd.has(e)?"json":Ob}function ec(e){Xd.add(e)}var Cb=108;async function no(e,r,t="resident server"){let n=e.wire,o=n??Zd(e.socketPath),s=await rc(e,r,t,o);return n||o==="json"||!Yd(r,s)?s:(ec(e.socketPath),await rc(e,r,t,"json"))}async function rc(e,r,t,n){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let a=$b(e.socketPath),l=!1,d="",c=setTimeout(()=>{u(()=>i(new Error(`${t} timed out`))),a.destroy()},o);function u(m){l||(l=!0,clearTimeout(c),m())}a.on("connect",()=>{a.write(Ys(r,n))}),a.on("data",m=>{d+=m.toString("utf8");let f=zs(d);f&&(d=f.rest,u(()=>{try{s(Qs(f.frame))}catch(h){i(h)}}),a.end())}),a.on("error",m=>u(()=>i(m))),a.on("close",()=>{l||u(()=>i(new Error(`${t} closed without response`)))})})}function sc(e,r,t){let n="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{n+=o;let s=zs(n);if(!s)return;n=s.rest,e.pause();let i=a=>{if(!(e.destroyed||!e.writable))try{e.write(Ys(a,s.dialect))}catch{}};(async()=>{let a;try{a=Qs(s.frame),await r(a,i)}catch(l){t(l,a,i)}finally{e.end()}})()})}async function Nb(e){await tc(oc(e),{recursive:!0,mode:448});try{return await jb(e,Xs.O_CREAT|Xs.O_EXCL|Xs.O_RDWR)}catch(r){if(r.code!=="EEXIST")throw r;return null}}var Mb=6e4,ic="resident-spawn-lock v1",Fb=3;async function ac(e,r={}){let t=r.maxAgeMs??Mb,n=r.now??Date.now,o=r.pid??process.pid,s=r.isPidAlive??oe;await tc(oc(e),{recursive:!0,mode:448});let i=[];for(let a=0;;a+=1){let l=await Nb(e);if(l)return await l.writeFile(`${ic} pid=${o} taken=${new Date(n()).toISOString()}
|
|
60
|
+
`).catch(()=>{}),{acquired:!0,lockPath:e,handle:l,reaped:i};let d=await Ub(e),c=await Hb(e,d,n());if(a>=Fb||c==null)return{acquired:!1,lockPath:e,holder:d,ageMs:c};let u=Wb(d,c,t,s);if(u==null)return{acquired:!1,lockPath:e,holder:d,ageMs:c};let m={lockPath:e,reason:u,holder:d,ageMs:c};await nc(e,{force:!0}),i.push(m),r.onReap?.(m)}}async function lc(e){await e.handle.close().catch(()=>{}),await nc(e.lockPath,{force:!0})}function Wb(e,r,t,n){return e==null?r>t?"unattributed":null:n(e.pid)?r>t?"aged-out":null:"holder-dead"}function dc(e){let r=e.ageMs==null?"of unknown age":`taken ${Math.round(e.ageMs/1e3)}s ago`,t=e.holder==null?"an owner it does not name":`pid ${e.holder.pid} (at ${e.holder.takenAt})`;return`no spawn was attempted: the spawn lock ${JSON.stringify(e.lockPath)} is held by ${t}, ${r}. If that process is gone, remove the file to clear it`}async function Ub(e){try{return Bb(await Lb(e,"utf8"))}catch{return null}}function Bb(e){let r=e.split(`
|
|
61
|
+
`,1)[0]?.trim()??"";if(!r.startsWith(ic))return null;let t=Number(/\bpid=(\d+)\b/.exec(r)?.[1]??""),n=/\btaken=(\S+)/.exec(r)?.[1]??"";return!Number.isInteger(t)||t<=0||!Number.isFinite(Date.parse(n))?null:{pid:t,takenAt:n}}async function Hb(e,r,t){let n=r==null?Number.NaN:Date.parse(r.takenAt);if(Number.isFinite(n))return Math.max(0,t-n);try{return Math.max(0,t-(await Gb(e)).mtimeMs)}catch{return null}}function oe(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}var qb="/tmp";function oo(e){let r=e.env??process.env,t=Db("sha256").update(e.key).digest("hex").slice(0,20),n=l=>Ut(l,e.socketFileName).length<Cb,o=r.XDG_RUNTIME_DIR;if(o){let l=Ut(o,"red-skills",t);if(n(l))return l}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=Ut(`red-skills-${s}`,t),a=Ut(Ib(),i);return n(a)||process.platform==="win32"?a:Ut(qb,i)}Ke();import{homedir as gk}from"node:os";import{join as ci}from"node:path";import{spawnSync as fk}from"node:child_process";import{createHash as hk}from"node:crypto";import{existsSync as yk,readdirSync as bk}from"node:fs";import{mkdir as yc,readFile as kk,rename as _k,writeFile as Rk}from"node:fs/promises";import{dirname as wk}from"node:path";var Tr="@reddb-io/red-skills",tk="https://registry.npmjs.org",nk="canary",Sr=class extends Error{kind;cause;constructor(r,t,n){super(t),this.name="BundleFetchError",this.kind=r,this.cause=n}},ok=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;function si(e){return typeof e=="string"&&ok.test(e.trim())}function mc(e){return`${e}-.bundle.min.mjs`}var sk=".unversioned";function ik(e,r,t="stable"){if(t==="canary")return`${e}-canary.bundle.min.mjs`;if(!si(r))throw new Sr("invalid-version",`refusing to key the ${e} bundle cache on ${JSON.stringify(r??"")}: it would mint ${mc(e)}, a name no resolver prefers and one whose mere existence satisfies the cache-first test forever (#3153)`);return`${e}-${r.trim()}.bundle.min.mjs`}function lo(e){let{plugin:r,version:t,cacheDir:n,channel:o}=e;return qt(n,ik(r,t,o))}function ak(e){return e==="dev"?["rsp","redskilled"]:[]}function lk(e){return`${e}.bundle.min.mjs`}function dk(e){return qt("dist",lk(e))}function ck(e,r="stable"){return`${Tr}@${r==="canary"?nk:e}`}function ii(e=Tr){return`${tk}/${e.replace("/","%2F")}`}async function ai(e,r){let{plugin:t,version:n,cacheDir:o,channel:s="stable"}=r,i=lo({plugin:t,version:n,cacheDir:o,channel:s}),a=ak(t),l=a.map(m=>lo({plugin:m,version:n,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await pk(e,l))return i;let d=ck(n,s),c=qt(o,`.staging-${t}-${s==="canary"?"canary":n}`),u;try{u=await e.materialize(d,c)}catch(m){throw hc(m,d)}for(let m of[t,...a]){let f=dk(m),h=qt(u,f);if(!await e.exists(h))throw new Sr("bundle-missing",`npm package ${d} has no ${f}`);let v=m===t?i:lo({plugin:m,version:n,cacheDir:o,channel:s});await e.writeFile(v,await e.readFile(h))}return await uk(e,o,[t,...a]),i}async function uk(e,r,t){if(e.rename)for(let n of t){let o=qt(r,mc(n));try{if(!await e.exists(o))continue;await e.rename(o,`${o}${sk}`)}catch{}}}async function pk(e,r){for(let t of r)if(!await e.exists(t))return!1;return!0}async function gc(e,r,t=Tr){let n;try{n=await e.fetchText(ii(t))}catch(s){throw hc(s,t)}let o=li(n);return{sameMajor:mk(o,r),newest:di(o)}}function li(e){let r;try{r=JSON.parse(e)}catch{return[]}if(typeof r!="object"||r===null)return[];let t=r.versions;return typeof t!="object"||t===null?[]:Object.keys(t)}function mk(e,r){let t=oi(r);if(t===null)return null;let n=null;for(let o of e)oi(o)===t&&(n===null||fc(o,n)>0)&&(n=o);return n}function di(e){let r=null;for(let t of e){let n=String(t).trim();oi(n)===null||/^\d+\.\d+\.\d+[-+]/.test(n)||(r===null||fc(n,r)>0)&&(r=n)}return r}function oi(e){let r=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return r?Number(r[1]):null}function fc(e,r){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),n=/^(\d+)\.(\d+)\.(\d+)/.exec(r.trim());return!t||!n?0:Number(t[1])-Number(n[1])||Number(t[2])-Number(n[2])||Number(t[3])-Number(n[3])}function hc(e,r){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Sr("npm-unavailable",`npm is unavailable while resolving ${r}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Sr("package-missing",`npm could not resolve ${r}: ${t}`,e):new Sr("network",`failed to resolve ${r}: ${t}`,e)}function qt(e,r){return e.endsWith("/")?`${e}${r}`:`${e}/${r}`}Ke();var bc={async materialize(e,r){await yc(r,{recursive:!0});let t=fk("npm",["install",e,"--prefix",r,"--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 ci(r,"node_modules",...Tr.split("/"))},async readFile(e){return new Uint8Array(await kk(e))},async writeFile(e,r){await yc(wk(e),{recursive:!0}),await Rk(e,r)},async exists(e){return yk(e)},sha256(e){return hk("sha256").update(e).digest("hex")},async fetchText(e){let r=await fetch(e,{redirect:"follow"});if(!r.ok)throw new Error(`GET ${e} -> ${r.status}`);return await r.text()},async rename(e,r){await _k(e,r)}},Ek="redskilled";function vk(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let r=e.XDG_CACHE_HOME||ci(e.HOME||gk(),".cache");return ci(r,"red-skills","bundles")}var Sk=/^([a-z0-9-]+)-(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?)\.bundle\.min\.mjs$/;async function Tk(e,r){if(si(e.version))return e.version.trim();let t=e.listCacheDir??Ok,n=xk(t(r),"dev");if(n)return n;try{let s=await(e.bundleIO??bc).fetchText(ii());return di(li(s))}catch{return null}}function xk(e,r){let t=null;for(let n of e){let o=Sk.exec(n);if(!o||o[1]!==r)continue;let s=o[2];(t===null||Pk(s,t)>0)&&(t=s)}return t}function Pk(e,r){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e),n=/^(\d+)\.(\d+)\.(\d+)/.exec(r);return Number(t[1])-Number(n[1])||Number(t[2])-Number(n[2])||Number(t[3])-Number(n[3])}function Ok(e){try{return bk(e)}catch{return[]}}async function Ak(e={},r={},t={}){let n=nr(e,r);if(Me(n))return n;let o=t.env??r.env??process.env,s=vk(o),i=await Tk(t,s);if(i===null)return n;try{await ai(t.bundleIO??bc,{plugin:Ek,version:i,cacheDir:s})}catch{return n}return nr(e,r)}async function kc(e={},r={},t={}){let n=await Ak(e,r,t);if(Me(n))return n;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(Ke(),pc));throw new o(n)}import{randomUUID as Ho}from"node:crypto";import{mkdir as GS,rm as kg}from"node:fs/promises";import{connect as $S,createServer as IS}from"node:net";import{dirname as CS}from"node:path";import{availableParallelism as wc,totalmem as jk}from"node:os";function Vt(e){if(e.applied_budget!=null)return e.applied_budget;let r=e.budget??{};return r.memory_max==null&&r.memory_high==null&&e.memory_ceiling!=null?{...r,memory_max:e.memory_ceiling}:r}function _c(e,r={}){let t=0,n=0,o=0,s=[],i=[];for(let d of e){let c=Vt(d),u=!1;for(let[m,f]of[[c.memory_high,h=>t+=h],[c.memory_max,h=>n+=h]]){if(m==null)continue;let h=rt(m);h==null?u=!0:f(h)}c.cpu_weight!=null&&(o+=c.cpu_weight),u&&s.push(d.worker_id),d.isolated||i.push(d.worker_id)}let a=r.hostCeilingBytes??null,l=a==null?0:Math.max(0,n-a);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:n,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:Dk(e.length,n,a,l)}}function Dk(e,r,t,n){return`this host's ${e} Worker(s) carry ${r} bytes of applied MemoryMax against a host ceiling of ${t} bytes \u2014 ${n} 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 rt(e){let r=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!r)return null;let t={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[r[2].toLowerCase()];return Math.round(Number(r[1])*t)}function Rc(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.version===1&&Number.isInteger(r.worker_count)&&typeof r.memory_high_bytes=="number"&&typeof r.memory_max_bytes=="number"&&typeof r.cpu_weight_total=="number"&&Array.isArray(r.unaccounted_workers)&&Array.isArray(r.unisolated_workers)}var Ec="REDSKILLED_MEMORY_CEILING",pi="REDSKILLED_WORKER_CEILING",xc="REDSKILLED_VALIDATION_CEILING",vc="REDSKILLED_INTERACTIVE_RESERVATION",Kt=1,Sc=.7,Lk=2*1024**3,Gk=2;function Pc(e){let r=e?.memory_max??e?.memory_high;if(r!=null)return rt(r)}function uo(e){let r=0,t=[];for(let n of e){let o=Pc(n.budget);o===null?t.push(n.worker_id):o!==void 0&&(r+=o)}return{worker_count:e.length,memory_bytes:r,unaccounted_workers:t.sort()}}function Oc(e){let{ceiling:r}=e,t=uo(e.workers),n=Pc(e.budget),o=n===void 0?null:n,s=t.memory_bytes+(n??0),i=t.worker_count+1,a=Math.max(0,r.interactive_reservation??Kt),l=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",d=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,c=(f,h)=>({version:1,admitted:!1,verdict:f,reason:h,ceiling:r,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}),u=r.worker_count==null?0:i-r.worker_count;if(u>0){if(e.reservation!=="interactive")return c("refused-over-worker-ceiling",`redskilled refused this Worker${l}: it would be Worker ${i} past a host ceiling of ${r.worker_count} Worker(s); ${a} extra slot(s) are reserved for interactive dispatches, and ${d}`);if(u>a)return c("refused-over-interactive-reservation",`redskilled refused this interactive Worker${l}: reserved slot ${u}/${a} is outside the bounded interactive reservation above the host ceiling of ${r.worker_count} Worker(s), and ${d}`)}if(r.memory_bytes!=null&&n===null)return c("refused-unaccountable-budget",`redskilled refused this Worker${l}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${r.memory_bytes} bytes, and ${d}`);if(r.memory_bytes!=null&&s>r.memory_bytes)return c("refused-over-memory-ceiling",`redskilled refused this Worker${l}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${r.memory_bytes} bytes, and ${d}`);let m=e.reservation==="interactive"&&u>0;return{version:1,admitted:!0,verdict:m?"admitted-interactive-reservation":"admitted",reason:m?`redskilled admitted this interactive Worker${l} into reserved interactive slot ${u}/${a} above the host ceiling of ${r.worker_count} Worker(s): ${s} bytes of declared Worker memory against a host ceiling of ${r.memory_bytes??"unbounded"} bytes, and ${d}`:`redskilled admitted this Worker${l}: ${s} bytes of declared Worker memory against a host ceiling of ${r.memory_bytes??"unbounded"} bytes, and ${d}`,ceiling:r,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function Ac(e){let r=e.budget?.memory_max??e.budget?.memory_high;if(r!=null)return{memory_max:r,reason:`the client declared this Worker's memory ceiling (${r}), 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=uo(e.workers),n=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,s=o==null?n:Math.floor(e.ceiling.memory_bytes/o),i=Math.min(n,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 (${pi} 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 po(e=process.env,r=jk(),t={}){let n=ui(t.flags?.memoryCeiling,e[Ec],t.config?.memoryCeiling),o=ui(t.flags?.workerCeiling,e[pi],t.config?.workerCeiling),s=ui(t.flags?.validationCeiling,e[xc],t.config?.validationCeiling),i=n?.value??"",a=o?.value??"",l=(e[vc]??"").trim(),d=Dc(a),c=l===""?Kt:Ck(l),u=o?.source??"derived-default";if(a!==""&&d===null&&!$k(a)&&(co(`redskilled: ${mi(o)} ${pi}=${JSON.stringify(a)} is not a positive integer; this host admits an unbounded number of Workers instead.`),u="derived-default"),i!==""){let m=Ik(i,r);if(m!==void 0)return Tc({memory_bytes:m,worker_count:d,interactive_reservation:c??Kt,source:"declared",memory_source:n.source,worker_source:u},s,t.availableParallelism??wc());co(`redskilled: ${mi(n)} ${Ec}=${JSON.stringify(i)} is not a memory ceiling this host can read; using ${Sc*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return l!==""&&c===void 0&&co(`redskilled: ${vc}=${JSON.stringify(l)} is not a non-negative integer; using the default reservation of ${Kt} Worker(s) instead.`),Tc({memory_bytes:Math.floor(r*Sc),worker_count:d,interactive_reservation:c??Kt,memory_source:"derived-default",worker_source:u,source:"host-fraction"},s,t.availableParallelism??wc())}function Tc(e,r,t){if(r!==void 0){let i=Dc(r.value);if(i!==null)return{...e,validation_count:i,validation_source:r.source};co(`redskilled: ${mi(r)} ${xc}=${JSON.stringify(r.value)} is not a positive integer; deriving the validation ceiling from host CPU, memory, and Worker capacity instead.`)}let n=Math.max(1,Math.floor(Math.max(1,t)/Gk)),o=e.memory_bytes==null?Number.POSITIVE_INFINITY:Math.max(1,Math.floor(e.memory_bytes/Lk)),s=e.worker_count??Number.POSITIVE_INFINITY;return{...e,validation_count:Math.max(1,Math.min(n,o,s)),validation_source:"derived-default"}}function ui(e,r,t){if(e?.trim())return{value:e.trim(),source:"flag"};if(r?.trim())return{value:r.trim(),source:"environment"};if(t?.trim())return{value:t.trim(),source:"home-config"}}function mi(e){return e.source==="flag"?"serve flag":e.source==="environment"?"environment":e.source==="home-config"?"home config":"derived default"}function $k(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var co=e=>process.stderr.write(`${e}
|
|
62
|
+
`);function Ik(e,r){let t=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(t))return null;let n=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return n?Math.floor(r*(Number(n[1])/100)):rt(e)??void 0}function Dc(e){if(e===""||["infinity","none","off","unbounded"].includes(e.toLowerCase()))return null;let r=Number(e);return Number.isSafeInteger(r)&&r>0?r:null}function Ck(e){let r=Number(e);return Number.isSafeInteger(r)&&r>=0?r:void 0}import{appendFile as Nk,mkdir as Mk,open as Fk,readFile as Wk,stat as Uk,truncate as jc}from"node:fs/promises";import{dirname as Bk}from"node:path";var Lc="redskilled.log.toonl";function Hk(e){let r=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:r.memory_high??null,memory_max:r.memory_max??null,cpu_weight:r.cpu_weight??null,detail:e.detail??null,exit_code:e.exitCode??null,signal:e.signal??null,reason:e.reason??null}}var qk="daemon:";function Vk(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${qk}${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 Kk(e){return{version:1,ts:e.ts,event:"demand-refusal",worker_id:`demand:${e.projectLabel}`,project_label:e.projectLabel,pid:0,workspace_path:"",log_path:null,isolated:!1,unit:null,memory_high:null,memory_max:null,cpu_weight:null,detail:e.detail,exit_code:null,signal:null,reason:null}}function Gc(e){let r=ge({trailer:!1}),t=Promise.resolve();async function n(o){let s=t.then(async()=>{await Mk(Bk(e),{recursive:!0,mode:448}),await Jk(e),await Nk(e,r.push(Xk(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>n(Hk(o)),recordDemandRefusal:o=>n(Kk(o)),recordDaemonStop:o=>n(Vk(o)),read:()=>zk(e),flush:async()=>{await t}}}async function Jk(e){let r;try{r=(await Uk(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(r===0)return;let t=64*1024,n=await Fk(e,"r");try{let o=Buffer.alloc(1);if(await n.read(o,0,1,r-1),o[0]===10)return;for(let s=r;s>0;s-=t){let i=Math.min(t,s),a=Buffer.alloc(i);await n.read(a,0,i,s-i);let l=a.lastIndexOf(10);if(l>=0){await jc(e,s-i+l+1);return}}await jc(e,0)}finally{await n.close()}}async function zk(e){let r;try{r=await Wk(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return Qk(r)}function Qk(e){let r=e.split(`
|
|
63
|
+
`);return r.pop(),r.length===0?[]:Ie(`${r.join(`
|
|
64
64
|
`)}
|
|
65
|
-
`).filter(Jb).map(zb)}function Ic(e){let r=new Map;for(let t of e)t.event==="daemon-stop"||t.event==="demand-refusal"||(t.event==="worker-birth"?r.set(t.worker_id,Vb(t)):r.delete(t.worker_id));return[...r.values()]}function Vb(e){let r={...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(r).length>0?{budget:r}:{},warnings:[]}}function Kb(e){return{...e}}function Jb(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==="demand-refusal"||e.event==="daemon-stop")}function zb(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:Ke(e.project_label)??"",pid:Number(e.pid??0),workspace_path:Ke(e.workspace_path)??"",log_path:Ke(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:Ke(e.unit),memory_high:Ke(e.memory_high),memory_max:Ke(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:Ke(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:Ke(e.signal),reason:Ke(e.reason)}}function Ke(e){return e==null||e===""?null:String(e)}function $c(e){let r=[...e.projects].sort((i,a)=>i.project_label.localeCompare(a.project_label)),t=e.backoffUntilMs??null,n=t!=null&&e.nowMs<t,o=[],s=[];for(let i of r){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,c={project_label:i.project_label,queue_depth:d,target:i.target,live:a};if(n){o.push({...c,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.birthHealth?.[i.project_label],m=u?.haltUntilMs??e.birthHaltUntilMs?.[i.project_label];if(m!=null&&e.nowMs<m){o.push({...c,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(m).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(u?.probeWorkerId!=null){o.push({...c,outcome:"half-open-probe",wanted:0,detail:`project ${JSON.stringify(i.project_label)} is half-open and probe Worker ${JSON.stringify(u.probeWorkerId)} has not yet survived 60000ms, so no second birth is admitted`});continue}if(d==null){o.push({...c,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({...c,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(i.project_label)} has nothing queued, so it is asked for no Worker`});continue}let h=Math.max(0,Math.min(Math.max(0,i.target),d)-a);if(h===0){o.push({...c,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}let f=u?.haltUntilMs!=null&&e.nowMs>=u.haltUntilMs,S=f?1:h;o.push({...c,outcome:f?"half-open-probe":"asking",wanted:S,detail:f?`project ${JSON.stringify(i.project_label)} finished its birth-breaker cooldown, so exactly one probe Worker is admitted before the remaining ${Math.max(0,h-1)} birth(s)`:`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 ${h} more`});for(let _=0;_<S;_+=1)(s[_]??(s[_]=[])).push({project_label:i.project_label,index:a+_,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function Gc(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function Cc(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.version===1&&typeof r.at=="string"&&Number.isInteger(r.requested)&&Array.isArray(r.granted)&&Number.isInteger(r.shortfall)&&(r.refusal===null||typeof r.refusal=="string")&&(r.retry_after===null||typeof r.retry_after=="string")&&Array.isArray(r.projects)}var qt={shortLifeStreak:0,haltUntilMs:null,openedAtMs:null,probeWorkerId:null};function Nc(e,r,t){if(r>=6e4)return qt;let n=e.shortLifeStreak+1;return!(e.haltUntilMs!=null||e.probeWorkerId!=null)&&n<3?{shortLifeStreak:n,haltUntilMs:null,openedAtMs:null,probeWorkerId:null}:{shortLifeStreak:n,haltUntilMs:t+6e5,openedAtMs:t,probeWorkerId:null}}function Mc(e,r){return e.haltUntilMs==null?e:{...e,probeWorkerId:r}}function mi(){return qt}function Qb(e,r,t){if(r.haltUntilMs==null||r.openedAtMs==null)return null;let n=t>=r.haltUntilMs;return{name:"project-birth-breaker",project_label:e,state:n?"half-open":"open",opened_at:new Date(r.openedAtMs).toISOString(),reason:`${r.shortLifeStreak} Workers from this project died before surviving 60000ms`,closes:n?r.probeWorkerId==null?"the next demand tick admits one probe Worker; surviving the short-life window closes the latch":`probe Worker ${JSON.stringify(r.probeWorkerId)} surviving 60000ms closes the latch; a fast death re-opens it with a fresh cooldown`:`the cooldown ends at ${new Date(r.haltUntilMs).toISOString()}, then one probe Worker is admitted; surviving the short-life window closes the latch`,probe_worker_id:r.probeWorkerId,repair:{tool:"project_reset",args:{latch:"project-birth-breaker"},why:"clear the project's birth-breaker history and allow the next demand tick to birth normally"}}}function Fc(e,r){return Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>Qb(t,n,r)).filter(t=>t!=null)}function Uc(e){let r=e.workers.map(Yb),t=[...new Set([...r.map(o=>o.project_label),...e.projects??[]])].filter(o=>o!=="").sort(),n=r.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:r,projects:t},surviving:n,detail:Zb({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:r.length,projects:t.length,surviving:n.length})}}function Bc(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 Yb(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 Xb(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 Zb(e){let r=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Xb(e.reason)}`;return e.held===0?`${r}; it holds no Workers, so nothing survives the stop`:`${r}; it holds ${Wc(e.held,"Worker")} across ${Wc(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 Wc(e,r){return`${e} ${r}${e===1?"":"s"}`}function gi(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e,t=r.holding;return r.version===1&&typeof r.running=="boolean"&&typeof r.stopped=="boolean"&&typeof r.reason=="string"&&typeof r.socket_path=="string"&&typeof r.detail=="string"&&(r.daemon_version===null||typeof r.daemon_version=="string")&&(r.pid===null||typeof r.pid=="number")&&t!=null&&Array.isArray(t.workers)&&Array.isArray(t.projects)&&Array.isArray(r.surviving)}import{chmod as e_,mkdir as r_,readFile as t_,rm as n_,writeFile as o_}from"node:fs/promises";import{dirname as Hc,join as Jc}from"node:path";import{tmpdir as qc}from"node:os";var s_="redskilled.machine.claim.toon",i_="REDSKILLED_MACHINE_DIR",a_=8,nr=class extends Error{constructor(t,n,o){super(d_(t,n,o));this.claimPath=t;this.reason=n;this.claim=o;this.name="RedskilledMachineHeldError"}},Vc;function zc(){return Vc??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},Vc}function l_(e={machineIdHash:"unknown"}){let r=e.env??process.env,t=r[i_]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?r.PROGRAMDATA?.trim()||qc():qc();return Jc(o,`redskilled-${e.machineIdHash}`)}function uo(e){return Jc(l_(e),s_)}function po(e,r,t={}){let n=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??oe;async function s(){let l;try{l=await t_(e,"utf8")}catch(c){if(c.code==="ENOENT"||fi(c))return;throw c}let d=u_(l);return p_(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:r.machineIdHash,session_key_hash:r.sessionKeyHash,socket_path:r.socketPath,acquired_at:d,renewed_at:d}}async function a(){try{return await n_(e,{force:!0}),!0}catch(l){if(fi(l))return!1;throw l}}return{claimPath:e,read:s,async claim(l){await r_(Hc(e),{recursive:!0,mode:1023})!=null&&await e_(Hc(e),1023).catch(()=>{});let c=!1;for(let u=0;u<a_;u+=1){let m=i(l,n());try{return await o_(e,c_(m),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:c,claim:m}}catch(f){if(f.code!=="EEXIST"){if(fi(f))return{claimed:!1,reason:"stale-claim-not-reapable"};throw f}}let h=await s();if(!h){if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable"};c=!0;continue}if(Kc(h,l,r.socketPath))return{claimed:!0,reaped:c,claim:h};if(await o(h.pid))return{claimed:!1,reason:"held",claim:h};if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable",claim:h};c=!0}return{claimed:!1,reason:"contended"}},async release(l){let d=await s();return!d||!Kc(d,l,r.socketPath)?!1:await a()}}}function Qc(e,r,t){return{kind:"machine",claim_path:e,owner_uid:t.uid,machine_id_hash:r.machineIdHash,session_key_hash:r.sessionKeyHash,socket_path:r.socketPath}}function Yc(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.kind==="machine"&&typeof r.claim_path=="string"&&typeof r.owner_uid=="number"&&typeof r.machine_id_hash=="string"&&typeof r.session_key_hash=="string"&&typeof r.socket_path=="string"}function d_(e,r,t){let n=t==null?"":` \u2014 held by pid ${t.pid} (uid ${t.uid}) on socket ${JSON.stringify(t.socket_path)}`;return r==="held"?`this machine already has a redskilled daemon${n}; a second one would void the host budget, so none was started. Reach that daemon, or stop it before starting another.`:r==="stale-claim-not-reapable"?`the redskilled machine claim ${JSON.stringify(e)} is stale and cannot be removed by this user${n}; 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 fi(e){let r=e?.code;return r==="EACCES"||r==="EPERM"||r==="EROFS"}function Kc(e,r,t){return e.pid===r.pid&&e.start_time===r.startTime&&e.socket_path===t}function c_(e){return`${J(e,{keyedMapCollapse:!0})}
|
|
66
|
-
`}function u_(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return ue(r)}catch{return null}}}function p_(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;if(r.version!==1||r.scope!=="machine"||!Number.isInteger(r.pid)||r.pid<=0||!Number.isInteger(r.uid))return!1;for(let t of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof r[t]!="string"||r[t].length===0)return!1;return!0}var m_=["worker_id","slot","workspace_path","log_path"],hi=class extends Error{constructor(t,n){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${n}: the facts a birth supplies are ${m_.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},g_=/\{\{([a-z_]+)\}\}/g;function f_(e,r){let t=(i,a)=>i.replace(g_,(l,d)=>{switch(d){case"worker_id":return r.worker_id;case"slot":return String(r.slot);case"workspace_path":return r.workspace_path;case"log_path":return r.log_path??"";default:throw new hi(d,a)}}),n=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:n,env:o,...s==null||s===""?{}:{log_path:s}}}function Xc(e,r,t){let n=f_(e,r),o=n.log_path??r.log_path,[s,...i]=n.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:r.worker_id,project_label:t.project_label,workspace_path:r.workspace_path,...o==null||o===""?{}:{log_path:o},command:s,args:i,env:n.env}}function yi(e,r){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(r)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((t,n)=>{if(typeof t!="string"||t==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${n} of project ${JSON.stringify(r)} is not`);return t})}function ki(e,r){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(r)}, 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 bi(e,r){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(r)}, not ${JSON.stringify(e)}`);let t={};for(let[n,o]of Object.entries(e)){if(n==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(r)} to be named`);if(typeof o!="string")throw new Error(`redskilled needs every launch env value to be a string, and ${JSON.stringify(n)} of project ${JSON.stringify(r)} is ${JSON.stringify(o)}`);t[n]=o}return t}var h_=3e5,y_=.5,Ri=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 Zc(e,r){if(r.held!=null)throw new Ri(r.held);let t=_i(e.project_label,"a project label"),n=_i(e.selector,"a selector"),o=__(e.queue_poll,t),s=yi(e.argv,t),i=bi(e.env,t),a=ki(e.log_path,t),l=_i(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 d=e.renew_within_ms??h_;if(!Number.isFinite(d)||d<=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 c=Date.parse(r.now);if(!Number.isFinite(c))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(r.now)}`);return{version:1,project_label:t,selector:n,...o==null?{}:{queue_poll:o},argv:s,workspace_path:l,env:i,...a==null?{}:{log_path:a},target:e.target,registered_at:new Date(c).toISOString(),renew_within_ms:d,renew_by:new Date(c+d).toISOString(),renewed_at:new Date(c).toISOString(),renewals:0,session_renewals:0,launch_revision:0}}var Sr=class extends Error{constructor(t,n={kind:"never"}){super(k_(t,n));this.projectLabel=t;this.absence=n;this.name="RedskilledProjectUnregisteredError"}};function k_(e,r){let t=JSON.stringify(e);if(r.kind==="lapsed"){let n=r.registered_at==null?"":` (registered ${r.registered_at})`;return`redskilled holds no registration for project ${t} to renew: it lapsed at ${r.at}${n}; renewal stopped \u2014 find why before registering it again`}return r.kind==="stopped"?`redskilled holds no registration for project ${t} to renew: it was stopped at ${r.at}; this is the requested state, so there is nothing to renew`:r.kind==="orphaned"?`redskilled holds no registration for project ${t} to renew: it is registered on a daemon this socket does not reach \u2014 do not register it again`:`redskilled holds no registration for project ${t} to renew: it was never registered on this host; register it first, stating the selector, the argv and the target`}function eu(e,r){let t=Date.parse(r.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(r.now)}`);let n=r.renew_within_ms??e.renew_within_ms;if(!Number.isFinite(n)||n<=0)throw new Error(`redskilled needs a positive renewal window to renew project ${JSON.stringify(e.project_label)}, not ${JSON.stringify(r.renew_within_ms)}`);let o=r.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:yi(r.launch.argv,e.project_label),env:bi(r.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=r.launch==null?e.log_path:ki(r.launch.log_path,e.project_label),{log_path:i,...a}=e;return{...a,...s==null?{}:{log_path:s},...o,renew_within_ms:n,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+n).toISOString(),renewals:e.renewals+1,session_renewals:(e.session_renewals??e.renewals)+1}}function wi(e,r){let t=Date.parse(r.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(r.now)}`);let n=JSON.stringify(e.project_label),o=Math.max(0,r.liveWorkers??0),s=r.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 ${n} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${n}, 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,renewals:e.renewals+1,session_renewals:e.session_renewals??e.renewals},verdict:a,detail:a==="open-work"?`project ${n} has ${i} item(s) queued, so its registration stands past its window`:`project ${n} holds ${o} Worker(s), so its registration stands past its window`}}function b_(e,r){let t=Date.parse(e.renew_by);return Number.isFinite(t)?r>=t:!1}function ru(e,r){let t=Date.parse(e.renewed_at??e.registered_at),n=s=>Number.isFinite(s)&&r-s<=e.renew_within_ms*y_;if(n(t))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return n(o)?"self-renewing":"running-on"}function tu(e,r){let t=[],n=[];for(let o of e)(b_(o,r)?n:t).push(o);return{standing:t,lapsed:n}}function Vt(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.version===1&&typeof r.project_label=="string"&&typeof r.selector=="string"&&(r.queue_poll===void 0||nu(r.queue_poll))&&Array.isArray(r.argv)&&r.argv.every(t=>typeof t=="string")&&typeof r.workspace_path=="string"&&Number.isInteger(r.target)&&typeof r.registered_at=="string"&&typeof r.renew_within_ms=="number"&&typeof r.renew_by=="string"&&(r.renewed_at===void 0||typeof r.renewed_at=="string")&&(r.renewals===void 0||Number.isInteger(r.renewals))&&(r.session_renewals===void 0||Number.isInteger(r.session_renewals))&&(r.env===void 0||R_(r.env))&&(r.log_path===void 0||typeof r.log_path=="string")&&(r.launch_revision===void 0||Number.isInteger(r.launch_revision))&&(r.sustained_at===void 0||typeof r.sustained_at=="string")&&(r.sustains===void 0||Number.isInteger(r.sustains))&&(r.sustained_by===void 0||r.sustained_by==="open-work"||r.sustained_by==="live-worker")}function __(e,r){if(e!==void 0){if(!nu(e))throw new Error(`redskilled needs a complete queue poll plan for project ${JSON.stringify(r)} when one is stated`);return e}}function nu(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.owner=="string"&&r.owner!==""&&typeof r.repo=="string"&&r.repo!==""&&Array.isArray(r.labels)&&r.labels.length>0&&r.labels.every(t=>typeof t=="string"&&t!=="")&&(r.creator===void 0||typeof r.creator=="string")}function R_(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(r=>typeof r=="string")}function _i(e,r){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${r} to register a project, not ${JSON.stringify(e)}`);return e}var w_={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-reset":"project-write","project-deregister":"project-write"};function ou(e){return`worker-${e}`}function su(e){let r=w_[e.op]??"project-write",t=e.sessionProject??null,n=e.targetProject??null,o={version:1,op:e.op,reach:r,session_project:t,target_project:n};return r==="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`}:r==="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`}:n!=null&&n===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)}: ${n==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(n)}`}. A session reads the whole host and writes only its own project.`}}function iu(e){return e==="single-object"?"rest":"graphql"}function z(e,r,t,n,o,s){return{key:e,kind:"read",cardinality:r,volatility:t,surface:s??iu(r),budget:n,...s?{only:s}:{},why:o}}function pe(e,r,t,n){return{key:e,kind:"write",cardinality:"single-object",surface:r,budget:t,why:n}}var au=[z("issue view","single-object","stable-poll","rest","one issue by number, repeatedly polled while usually unchanged; REST answers in one request"),z("pr view","single-object","stable-poll","rest","one pull request by number, polled per Worker per iteration"),z("repo view","single-object","stable-poll","rest","one repository's own metadata, repeatedly read while usually unchanged"),z("run view","single-object","stable-poll","rest","one Actions run repeatedly polled to terminal; Actions has no GraphQL surface"),z("release view","single-object","stable-poll","rest","one release by tag, repeatedly checked while usually absent or unchanged"),z("pr diff","single-object","one-shot","rest","one pull request's diff, read once for review and served by a REST media type"),z("issue list","multi-node","stable-poll","graphql","a repeatedly polled, usually-unchanged issue connection; GraphQL avoids N REST pages"),z("pr list","multi-node","stable-poll","graphql","a repeatedly polled, usually-unchanged pull-request connection; GraphQL avoids N REST pages"),z("pr checks","multi-node","stable-poll","graphql","check contexts form a connection repeatedly polled while awaiting terminal state"),z("release list","multi-node","stable-poll","rest","release waits poll a usually-unchanged list; Releases has no GraphQL connection gh reads","rest"),z("run list","multi-node","stable-poll","rest","run waits poll a usually-unchanged list; Actions has no GraphQL surface","rest"),z("label list","multi-node","one-shot","graphql","a label connection loaded once for the current operation"),z("issue list (search)","multi-node","stable-poll","search","queue discovery polls usually-unchanged search results through the 30/min search connection"),z("pr list (search)","multi-node","stable-poll","search","PR discovery polls usually-unchanged search results through the 30/min search connection"),z("search issues","multi-repository","one-shot","search","a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),z("search prs","multi-repository","one-shot","search","a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),z("search repos","multi-repository","one-shot","search","a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),z("api graphql","multi-node","one-shot","graphql","the caller supplies one explicit GraphQL query rather than a routed poll"),z("api rest","single-object","one-shot","rest","the caller supplies one explicit REST path rather than a routed poll"),pe("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),pe("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),pe("issue close","graphql","graphql","gh closes with the closeIssue mutation"),pe("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),pe("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),pe("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),pe("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),pe("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),pe("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),pe("pr close","graphql","graphql","gh closes with a GraphQL mutation"),pe("pr edit","graphql","graphql","gh edits with GraphQL mutations"),pe("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),pe("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),pe("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],E_=new Map(au.map(e=>[e.key,e]));function lu(e){let r=[],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("-")&&r.length<2;)r.push(e[t]),t+=1;return r}function Ei(e){let r=lu(e);if(r.length===0)return"";if(r[0]==="api")return r[1]==="graphql"?"api graphql":"api rest";let t=r.length===1?r[0]:`${r[0]} ${r[1]}`;return r[1]==="list"&&e.includes("--search")?`${t} (search)`:t}var mo=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(r){let t=Ei(r);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=[...r]}};function du(e){return E_.get(Ei(e))??null}function cu(e){let r=du(e);if(!r)throw new mo(e);return r}function vi(e){return cu(e).surface}import{appendFile as v_,mkdir as S_,readFile as T_}from"node:fs/promises";import{dirname as x_}from"node:path";function go(e){let r=e.now??(()=>new Date().toISOString()),t=Promise.resolve();return{record(n){let o=P_(n.operation,n.cost,n.observedAt??r(),n.actor),s=ge().push(A_(o));return t=t.then(async()=>{await S_(x_(e.path),{recursive:!0}),await v_(e.path,s,"utf8")}),t},async report(n){await t;let o=Si(n.from,"report window start"),s=Si(n.to,"report window end");if(s<=o)throw new Error("GitHub attribution report window end must be after its start");let i=await O_(e.path),a=new Map;for(let d of i.observations){let c=Date.parse(d.observed_at);if(c<o||c>=s||n.pool!==void 0&&d.pool!==n.pool)continue;let u=`${d.pool}\0${d.operation_key}\0${d.actor??""}`,m=a.get(u);a.set(u,{operation_key:d.operation_key,pool:d.pool,...d.actor===void 0?{}:{actor:d.actor},count:(m?.count??0)+1,cost:(m?.cost??0)+d.cost})}let l=[...a.values()].sort((d,c)=>c.cost-d.cost||c.count-d.count||d.operation_key.localeCompare(c.operation_key)||d.pool.localeCompare(c.pool)||(d.actor??"").localeCompare(c.actor??""));return{version:1,origin:"process-attribution",window:{from:n.from,to:n.to},pool:n.pool??null,total_count:l.reduce((d,c)=>d+c.count,0),total_cost:l.reduce((d,c)=>d+c.cost,0),operations:l,unreadable_records:i.unreadable}}}}function P_(e,r,t,n){if(Si(t,"GitHub spend observation"),!Number.isSafeInteger(r)||r<0)throw new Error(`GitHub spend observation cost must be a non-negative safe integer; received ${r}`);if(n!==void 0&&n.trim()==="")throw new Error("GitHub spend observation actor must be non-empty when supplied");return{version:1,observed_at:t,operation_key:e.key,pool:e.budget,...n===void 0?{}:{actor:n},cost:r}}async function O_(e){let r;try{r=await T_(e,"utf8")}catch(s){if(L_(s)&&s.code==="ENOENT")return{observations:[],unreadable:0};throw s}let t=[],n=0,o=r.split(`
|
|
67
|
-
`);for(let s=0;s<o.length;s+=1){let i=o[s];if(i.trim()==="")continue;let a=o[s+1];if(!i.startsWith("[]{")||a===void 0||a.trim()===""){n+=1;continue}let l;try{l
|
|
65
|
+
`).filter(Zk).map(e_)}function $c(e){let r=new Map;for(let t of e)t.event==="daemon-stop"||t.event==="demand-refusal"||(t.event==="worker-birth"?r.set(t.worker_id,Yk(t)):r.delete(t.worker_id));return[...r.values()]}function Yk(e){let r={...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(r).length>0?{budget:r}:{},warnings:[]}}function Xk(e){return{...e}}function Zk(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==="demand-refusal"||e.event==="daemon-stop")}function e_(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:Je(e.project_label)??"",pid:Number(e.pid??0),workspace_path:Je(e.workspace_path)??"",log_path:Je(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:Je(e.unit),memory_high:Je(e.memory_high),memory_max:Je(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:Je(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:Je(e.signal),reason:Je(e.reason)}}function Je(e){return e==null||e===""?null:String(e)}function Ic(e){let r=[...e.projects].sort((i,a)=>i.project_label.localeCompare(a.project_label)),t=e.backoffUntilMs??null,n=t!=null&&e.nowMs<t,o=[],s=[];for(let i of r){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,c={project_label:i.project_label,queue_depth:d,target:i.target,live:a};if(n){o.push({...c,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.birthHealth?.[i.project_label],m=u?.haltUntilMs??e.birthHaltUntilMs?.[i.project_label];if(m!=null&&e.nowMs<m){o.push({...c,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(m).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(u?.probeWorkerId!=null){o.push({...c,outcome:"half-open-probe",wanted:0,detail:`project ${JSON.stringify(i.project_label)} is half-open and probe Worker ${JSON.stringify(u.probeWorkerId)} has not yet survived 60000ms, so no second birth is admitted`});continue}if(d==null){o.push({...c,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({...c,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({...c,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}let h=u?.haltUntilMs!=null&&e.nowMs>=u.haltUntilMs,v=h?1:f;o.push({...c,outcome:h?"half-open-probe":"asking",wanted:v,detail:h?`project ${JSON.stringify(i.project_label)} finished its birth-breaker cooldown, so exactly one probe Worker is admitted before the remaining ${Math.max(0,f-1)} birth(s)`:`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 y=0;y<v;y+=1)(s[y]??(s[y]=[])).push({project_label:i.project_label,index:a+y,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function Cc(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function Nc(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.version===1&&typeof r.at=="string"&&Number.isInteger(r.requested)&&Array.isArray(r.granted)&&Number.isInteger(r.shortfall)&&(r.refusal===null||typeof r.refusal=="string")&&(r.retry_after===null||typeof r.retry_after=="string")&&Array.isArray(r.projects)}var Jt={shortLifeStreak:0,haltUntilMs:null,openedAtMs:null,probeWorkerId:null};function Mc(e,r,t){if(r>=6e4)return Jt;let n=e.shortLifeStreak+1;return!(e.haltUntilMs!=null||e.probeWorkerId!=null)&&n<3?{shortLifeStreak:n,haltUntilMs:null,openedAtMs:null,probeWorkerId:null}:{shortLifeStreak:n,haltUntilMs:t+6e5,openedAtMs:t,probeWorkerId:null}}function Fc(e,r){return e.haltUntilMs==null?e:{...e,probeWorkerId:r}}function gi(){return Jt}function r_(e,r,t){if(r.haltUntilMs==null||r.openedAtMs==null)return null;let n=t>=r.haltUntilMs;return{name:"project-birth-breaker",project_label:e,state:n?"half-open":"open",opened_at:new Date(r.openedAtMs).toISOString(),reason:`${r.shortLifeStreak} Workers from this project died before surviving 60000ms`,closes:n?r.probeWorkerId==null?"the next demand tick admits one probe Worker; surviving the short-life window closes the latch":`probe Worker ${JSON.stringify(r.probeWorkerId)} surviving 60000ms closes the latch; a fast death re-opens it with a fresh cooldown`:`the cooldown ends at ${new Date(r.haltUntilMs).toISOString()}, then one probe Worker is admitted; surviving the short-life window closes the latch`,probe_worker_id:r.probeWorkerId,repair:{tool:"project_reset",args:{latch:"project-birth-breaker"},why:"clear the project's birth-breaker history and allow the next demand tick to birth normally"}}}function Wc(e,r){return Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>r_(t,n,r)).filter(t=>t!=null)}function Bc(e){let r=e.workers.map(t_),t=[...new Set([...r.map(o=>o.project_label),...e.projects??[]])].filter(o=>o!=="").sort(),n=r.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:r,projects:t},surviving:n,detail:o_({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:r.length,projects:t.length,surviving:n.length})}}function Hc(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 t_(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 n_(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 o_(e){let r=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${n_(e.reason)}`;return e.held===0?`${r}; it holds no Workers, so nothing survives the stop`:`${r}; it holds ${Uc(e.held,"Worker")} across ${Uc(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 Uc(e,r){return`${e} ${r}${e===1?"":"s"}`}function fi(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e,t=r.holding;return r.version===1&&typeof r.running=="boolean"&&typeof r.stopped=="boolean"&&typeof r.reason=="string"&&typeof r.socket_path=="string"&&typeof r.detail=="string"&&(r.daemon_version===null||typeof r.daemon_version=="string")&&(r.pid===null||typeof r.pid=="number")&&t!=null&&Array.isArray(t.workers)&&Array.isArray(t.projects)&&Array.isArray(r.surviving)}import{chmod as s_,mkdir as i_,readFile as a_,rm as l_,writeFile as d_}from"node:fs/promises";import{dirname as qc,join as zc}from"node:path";import{tmpdir as Vc}from"node:os";var c_="redskilled.machine.claim.toon",u_="REDSKILLED_MACHINE_DIR",p_=8,or=class extends Error{constructor(t,n,o){super(g_(t,n,o));this.claimPath=t;this.reason=n;this.claim=o;this.name="RedskilledMachineHeldError"}},Kc;function Qc(){return Kc??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},Kc}function m_(e={machineIdHash:"unknown"}){let r=e.env??process.env,t=r[u_]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?r.PROGRAMDATA?.trim()||Vc():Vc();return zc(o,`redskilled-${e.machineIdHash}`)}function mo(e){return zc(m_(e),c_)}function go(e,r,t={}){let n=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??oe;async function s(){let l;try{l=await a_(e,"utf8")}catch(c){if(c.code==="ENOENT"||hi(c))return;throw c}let d=h_(l);return y_(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:r.machineIdHash,session_key_hash:r.sessionKeyHash,socket_path:r.socketPath,acquired_at:d,renewed_at:d}}async function a(){try{return await l_(e,{force:!0}),!0}catch(l){if(hi(l))return!1;throw l}}return{claimPath:e,read:s,async claim(l){await i_(qc(e),{recursive:!0,mode:1023})!=null&&await s_(qc(e),1023).catch(()=>{});let c=!1;for(let u=0;u<p_;u+=1){let m=i(l,n());try{return await d_(e,f_(m),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:c,claim:m}}catch(h){if(h.code!=="EEXIST"){if(hi(h))return{claimed:!1,reason:"stale-claim-not-reapable"};throw h}}let f=await s();if(!f){if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable"};c=!0;continue}if(Jc(f,l,r.socketPath))return{claimed:!0,reaped:c,claim:f};if(await o(f.pid))return{claimed:!1,reason:"held",claim:f};if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable",claim:f};c=!0}return{claimed:!1,reason:"contended"}},async release(l){let d=await s();return!d||!Jc(d,l,r.socketPath)?!1:await a()}}}function Yc(e,r,t){return{kind:"machine",claim_path:e,owner_uid:t.uid,machine_id_hash:r.machineIdHash,session_key_hash:r.sessionKeyHash,socket_path:r.socketPath}}function Xc(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.kind==="machine"&&typeof r.claim_path=="string"&&typeof r.owner_uid=="number"&&typeof r.machine_id_hash=="string"&&typeof r.session_key_hash=="string"&&typeof r.socket_path=="string"}function g_(e,r,t){let n=t==null?"":` \u2014 held by pid ${t.pid} (uid ${t.uid}) on socket ${JSON.stringify(t.socket_path)}`;return r==="held"?`this machine already has a redskilled daemon${n}; a second one would void the host budget, so none was started. Reach that daemon, or stop it before starting another.`:r==="stale-claim-not-reapable"?`the redskilled machine claim ${JSON.stringify(e)} is stale and cannot be removed by this user${n}; 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 hi(e){let r=e?.code;return r==="EACCES"||r==="EPERM"||r==="EROFS"}function Jc(e,r,t){return e.pid===r.pid&&e.start_time===r.startTime&&e.socket_path===t}function f_(e){return`${J(e,{keyedMapCollapse:!0})}
|
|
66
|
+
`}function h_(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return ue(r)}catch{return null}}}function y_(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;if(r.version!==1||r.scope!=="machine"||!Number.isInteger(r.pid)||r.pid<=0||!Number.isInteger(r.uid))return!1;for(let t of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof r[t]!="string"||r[t].length===0)return!1;return!0}var b_=["worker_id","slot","workspace_path","log_path"],yi=class extends Error{constructor(t,n){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${n}: the facts a birth supplies are ${b_.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},k_=/\{\{([a-z_]+)\}\}/g;function __(e,r){let t=(i,a)=>i.replace(k_,(l,d)=>{switch(d){case"worker_id":return r.worker_id;case"slot":return String(r.slot);case"workspace_path":return r.workspace_path;case"log_path":return r.log_path??"";default:throw new yi(d,a)}}),n=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:n,env:o,...s==null||s===""?{}:{log_path:s}}}function Zc(e,r,t){let n=__(e,r),o=n.log_path??r.log_path,[s,...i]=n.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:r.worker_id,project_label:t.project_label,workspace_path:r.workspace_path,...o==null||o===""?{}:{log_path:o},command:s,args:i,env:n.env}}function bi(e,r){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(r)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((t,n)=>{if(typeof t!="string"||t==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${n} of project ${JSON.stringify(r)} is not`);return t})}function ki(e,r){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(r)}, 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 _i(e,r){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(r)}, not ${JSON.stringify(e)}`);let t={};for(let[n,o]of Object.entries(e)){if(n==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(r)} to be named`);if(typeof o!="string")throw new Error(`redskilled needs every launch env value to be a string, and ${JSON.stringify(n)} of project ${JSON.stringify(r)} is ${JSON.stringify(o)}`);t[n]=o}return t}var R_=3e5,w_=.5,wi=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 eu(e,r){if(r.held!=null)throw new wi(r.held);let t=Ri(e.project_label,"a project label"),n=Ri(e.selector,"a selector"),o=S_(e.queue_poll,t),s=bi(e.argv,t),i=_i(e.env,t),a=ki(e.log_path,t),l=Ri(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 d=e.renew_within_ms??R_;if(!Number.isFinite(d)||d<=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 c=Date.parse(r.now);if(!Number.isFinite(c))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(r.now)}`);return{version:1,project_label:t,selector:n,...o==null?{}:{queue_poll:o},argv:s,workspace_path:l,env:i,...a==null?{}:{log_path:a},target:e.target,registered_at:new Date(c).toISOString(),renew_within_ms:d,renew_by:new Date(c+d).toISOString(),renewed_at:new Date(c).toISOString(),renewals:0,session_renewals:0,launch_revision:0}}var xr=class extends Error{constructor(t,n={kind:"never"}){super(E_(t,n));this.projectLabel=t;this.absence=n;this.name="RedskilledProjectUnregisteredError"}};function E_(e,r){let t=JSON.stringify(e);if(r.kind==="lapsed"){let n=r.registered_at==null?"":` (registered ${r.registered_at})`;return`redskilled holds no registration for project ${t} to renew: it lapsed at ${r.at}${n}; renewal stopped \u2014 find why before registering it again`}return r.kind==="stopped"?`redskilled holds no registration for project ${t} to renew: it was stopped at ${r.at}; this is the requested state, so there is nothing to renew`:r.kind==="orphaned"?`redskilled holds no registration for project ${t} to renew: it is registered on a daemon this socket does not reach \u2014 do not register it again`:`redskilled holds no registration for project ${t} to renew: it was never registered on this host; register it first, stating the selector, the argv and the target`}function ru(e,r){let t=Date.parse(r.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(r.now)}`);let n=r.renew_within_ms??e.renew_within_ms;if(!Number.isFinite(n)||n<=0)throw new Error(`redskilled needs a positive renewal window to renew project ${JSON.stringify(e.project_label)}, not ${JSON.stringify(r.renew_within_ms)}`);let o=r.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:bi(r.launch.argv,e.project_label),env:_i(r.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=r.launch==null?e.log_path:ki(r.launch.log_path,e.project_label),{log_path:i,...a}=e;return{...a,...s==null?{}:{log_path:s},...o,renew_within_ms:n,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+n).toISOString(),renewals:e.renewals+1,session_renewals:(e.session_renewals??e.renewals)+1}}function Ei(e,r){let t=Date.parse(r.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(r.now)}`);let n=JSON.stringify(e.project_label),o=Math.max(0,r.liveWorkers??0),s=r.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 ${n} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${n}, 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,renewals:e.renewals+1,session_renewals:e.session_renewals??e.renewals},verdict:a,detail:a==="open-work"?`project ${n} has ${i} item(s) queued, so its registration stands past its window`:`project ${n} holds ${o} Worker(s), so its registration stands past its window`}}function v_(e,r){let t=Date.parse(e.renew_by);return Number.isFinite(t)?r>=t:!1}function tu(e,r){let t=Date.parse(e.renewed_at??e.registered_at),n=s=>Number.isFinite(s)&&r-s<=e.renew_within_ms*w_;if(n(t))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return n(o)?"self-renewing":"running-on"}function nu(e,r){let t=[],n=[];for(let o of e)(v_(o,r)?n:t).push(o);return{standing:t,lapsed:n}}function zt(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.version===1&&typeof r.project_label=="string"&&typeof r.selector=="string"&&(r.queue_poll===void 0||ou(r.queue_poll))&&Array.isArray(r.argv)&&r.argv.every(t=>typeof t=="string")&&typeof r.workspace_path=="string"&&Number.isInteger(r.target)&&typeof r.registered_at=="string"&&typeof r.renew_within_ms=="number"&&typeof r.renew_by=="string"&&(r.renewed_at===void 0||typeof r.renewed_at=="string")&&(r.renewals===void 0||Number.isInteger(r.renewals))&&(r.session_renewals===void 0||Number.isInteger(r.session_renewals))&&(r.env===void 0||T_(r.env))&&(r.log_path===void 0||typeof r.log_path=="string")&&(r.launch_revision===void 0||Number.isInteger(r.launch_revision))&&(r.sustained_at===void 0||typeof r.sustained_at=="string")&&(r.sustains===void 0||Number.isInteger(r.sustains))&&(r.sustained_by===void 0||r.sustained_by==="open-work"||r.sustained_by==="live-worker")}function S_(e,r){if(e!==void 0){if(!ou(e))throw new Error(`redskilled needs a complete queue poll plan for project ${JSON.stringify(r)} when one is stated`);return e}}function ou(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.owner=="string"&&r.owner!==""&&typeof r.repo=="string"&&r.repo!==""&&Array.isArray(r.labels)&&r.labels.length>0&&r.labels.every(t=>typeof t=="string"&&t!=="")&&(r.creator===void 0||typeof r.creator=="string")}function T_(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(r=>typeof r=="string")}function Ri(e,r){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${r} to register a project, not ${JSON.stringify(e)}`);return e}var x_={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-reset":"project-write","project-deregister":"project-write"};function su(e){return`worker-${e}`}function iu(e){let r=x_[e.op]??"project-write",t=e.sessionProject??null,n=e.targetProject??null,o={version:1,op:e.op,reach:r,session_project:t,target_project:n};return r==="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`}:r==="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`}:n!=null&&n===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)}: ${n==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(n)}`}. A session reads the whole host and writes only its own project.`}}function au(e){return e==="single-object"?"rest":"graphql"}function lu(e,r){return e==="stable-poll"?"rest":au(r)}function Re(e){return{none:e}}function z(e,r,t,n,o,s,i){let a=typeof o=="string"?{fallback:o}:{fallback:null,noFallbackBecause:o.none};return{key:e,kind:"read",cardinality:r,volatility:t,surface:i??lu(t,r),budget:n,...a,...i?{only:i}:{},why:s}}function pe(e,r,t,n){return{key:e,kind:"write",cardinality:"single-object",surface:r,budget:t,fallback:null,noFallbackBecause:"a mutation has one observed GitHub API method",why:n}}var du=[z("issue view","single-object","stable-poll","rest","graphql","one issue by number, repeatedly polled while usually unchanged; REST answers in one request"),z("pr view","single-object","stable-poll","rest","graphql","one pull request by number, polled per Worker per iteration"),z("repo view","single-object","stable-poll","rest","graphql","one repository's own metadata, repeatedly read while usually unchanged"),z("run view","single-object","stable-poll","rest",Re("Actions runs have no GraphQL resource"),"one Actions run repeatedly polled to terminal"),z("release view","single-object","stable-poll","rest",Re("release lookup has no GraphQL client method"),"one release by tag, repeatedly checked while usually absent or unchanged"),z("pr diff","single-object","one-shot","rest",Re("the complete diff is exposed as a REST media type"),"one pull request's diff, read once for review"),z("issue list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged issue collection; REST can make an unchanged poll free"),z("pr list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged pull-request collection; REST can make an unchanged poll free"),z("pr checks","multi-node","stable-poll","rest","graphql","check contexts are repeatedly polled while awaiting terminal state"),z("release list","multi-node","stable-poll","rest",Re("Releases has no GraphQL collection client method"),"release waits poll a usually-unchanged list"),z("run list","multi-node","stable-poll","rest",Re("Actions has no GraphQL collection client method"),"run waits poll a usually-unchanged list"),z("label list","multi-node","one-shot","graphql","rest","a label connection loaded once for the current operation"),z("issue list (search)","multi-node","stable-poll","search",Re("search is ineligible for diverted traffic"),"queue discovery polls usually-unchanged search results through the 30/min search connection"),z("pr list (search)","multi-node","stable-poll","search",Re("search is ineligible for diverted traffic"),"PR discovery polls usually-unchanged search results through the 30/min search connection"),z("search issues","multi-repository","one-shot","search",Re("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),z("search prs","multi-repository","one-shot","search",Re("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),z("search repos","multi-repository","one-shot","search",Re("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),z("api graphql","multi-node","one-shot","graphql",Re("the caller explicitly chose GraphQL"),"the caller supplies one explicit GraphQL query rather than a routed poll"),z("api rest","single-object","one-shot","rest",Re("the caller explicitly chose REST"),"the caller supplies one explicit REST path rather than a routed poll"),pe("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),pe("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),pe("issue close","graphql","graphql","gh closes with the closeIssue mutation"),pe("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),pe("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),pe("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),pe("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),pe("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),pe("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),pe("pr close","graphql","graphql","gh closes with a GraphQL mutation"),pe("pr edit","graphql","graphql","gh edits with GraphQL mutations"),pe("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),pe("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),pe("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],P_=new Map(du.map(e=>[e.key,e]));function cu(e){let r=[],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("-")&&r.length<2;)r.push(e[t]),t+=1;return r}function vi(e){let r=cu(e);if(r.length===0)return"";if(r[0]==="api")return r[1]==="graphql"?"api graphql":"api rest";let t=r.length===1?r[0]:`${r[0]} ${r[1]}`;return r[1]==="list"&&e.includes("--search")?`${t} (search)`:t}var fo=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(r){let t=vi(r);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=[...r]}};function uu(e){return P_.get(vi(e))??null}function pu(e){let r=uu(e);if(!r)throw new fo(e);return r}function Si(e){return pu(e).surface}import{appendFile as O_,mkdir as A_,readFile as D_}from"node:fs/promises";import{dirname as j_}from"node:path";function ho(e){let r=e.now??(()=>new Date().toISOString()),t=Promise.resolve();return{record(n){let o=L_(n.operation,n.cost,n.observedAt??r(),n.actor),s=ge().push($_(o));return t=t.then(async()=>{await A_(j_(e.path),{recursive:!0}),await O_(e.path,s,"utf8")}),t},async report(n){await t;let o=Ti(n.from,"report window start"),s=Ti(n.to,"report window end");if(s<=o)throw new Error("GitHub attribution report window end must be after its start");let i=await G_(e.path),a=new Map;for(let d of i.observations){let c=Date.parse(d.observed_at);if(c<o||c>=s||n.pool!==void 0&&d.pool!==n.pool)continue;let u=`${d.pool}\0${d.operation_key}\0${d.actor??""}`,m=a.get(u);a.set(u,{operation_key:d.operation_key,pool:d.pool,...d.actor===void 0?{}:{actor:d.actor},count:(m?.count??0)+1,cost:(m?.cost??0)+d.cost})}let l=[...a.values()].sort((d,c)=>c.cost-d.cost||c.count-d.count||d.operation_key.localeCompare(c.operation_key)||d.pool.localeCompare(c.pool)||(d.actor??"").localeCompare(c.actor??""));return{version:1,origin:"process-attribution",window:{from:n.from,to:n.to},pool:n.pool??null,total_count:l.reduce((d,c)=>d+c.count,0),total_cost:l.reduce((d,c)=>d+c.cost,0),operations:l,unreadable_records:i.unreadable}}}}function L_(e,r,t,n){if(Ti(t,"GitHub spend observation"),!Number.isSafeInteger(r)||r<0)throw new Error(`GitHub spend observation cost must be a non-negative safe integer; received ${r}`);if(n!==void 0&&n.trim()==="")throw new Error("GitHub spend observation actor must be non-empty when supplied");return{version:1,observed_at:t,operation_key:e.key,pool:e.budget,...n===void 0?{}:{actor:n},cost:r}}async function G_(e){let r;try{r=await D_(e,"utf8")}catch(s){if(N_(s)&&s.code==="ENOENT")return{observations:[],unreadable:0};throw s}let t=[],n=0,o=r.split(`
|
|
67
|
+
`);for(let s=0;s<o.length;s+=1){let i=o[s];if(i.trim()==="")continue;let a=o[s+1];if(!i.startsWith("[]{")||a===void 0||a.trim()===""){n+=1;continue}let l;try{l=Ie(`${i}
|
|
68
68
|
${a}
|
|
69
|
-
`)[0]}catch{n+=1,s+=1;continue}if(!
|
|
69
|
+
`)[0]}catch{n+=1,s+=1;continue}if(!I_(l)){n+=1,s+=1;continue}t.push(l),s+=1}return{observations:t,unreadable:n}}function $_(e){return{version:e.version,observed_at:e.observed_at,operation_key:e.operation_key,pool:e.pool,...e.actor===void 0?{}:{actor:e.actor},cost:e.cost}}function I_(e){return C_(e)?e.version===1&&typeof e.observed_at=="string"&&Number.isFinite(Date.parse(e.observed_at))&&typeof e.operation_key=="string"&&e.operation_key!==""&&(e.pool==="rest"||e.pool==="graphql"||e.pool==="search")&&(e.actor===void 0||typeof e.actor=="string"&&e.actor!=="")&&typeof e.cost=="number"&&Number.isSafeInteger(e.cost)&&e.cost>=0:!1}function Ti(e,r){let t=Date.parse(e);if(!Number.isFinite(t))throw new Error(`${r} must be an ISO-8601 instant; received ${JSON.stringify(e)}`);return t}function C_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function N_(e){return e instanceof Error&&"code"in e}var gu=ls(Oi(),1);var ze=class extends Error{name;status;request;response;constructor(r,t,n){super(r,{cause:n.cause}),this.name="HttpError",this.status=Number.parseInt(t),Number.isNaN(this.status)&&(this.status=0);"response"in n&&(this.response=n.response);let o=Object.assign({},n.request);n.request.headers.authorization&&(o.headers=Object.assign({},n.request.headers,{authorization:n.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),o.url=o.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=o}};var M_="0.0.0-development";function F_(e){return e.request!==void 0}async function mu(e,r,t,n){if(!F_(t)||!t?.request.request)throw t;if(t.status>=400&&!e.doNotRetry.includes(t.status)){let o=n.request.retries!=null?n.request.retries:e.retries,s=Math.pow((n.request.retryCount||0)+1,2);throw r.retry.retryRequest(t,o,s)}throw t}async function W_(e,r,t,n){let o=new gu.default;return o.on("failed",function(s,i){let a=~~s.request.request?.retries,l=~~s.request.request?.retryAfter;if(n.request.retryCount=i.retryCount+1,a>i.retryCount)return l*e.retryAfterBaseValue}),o.schedule(U_.bind(null,e,r,t),n)}async function U_(e,r,t,n){let o=await t(n);if(o.data&&o.data.errors&&o.data.errors.length>0&&/Something went wrong while executing your query/.test(o.data.errors[0].message)){let s=new ze(o.data.errors[0].message,500,{request:n,response:o});return mu(e,r,s,n)}return o}function Ai(e,r){let t=Object.assign({enabled:!0,retryAfterBaseValue:1e3,doNotRetry:[400,401,403,404,410,422,451],retries:3},r.retry),n={retry:{retryRequest:(o,s,i)=>(o.request.request=Object.assign({},o.request.request,{retries:s,retryAfter:i}),o)}};return t.enabled&&(e.hook.error("request",mu.bind(null,t,n)),e.hook.wrap("request",W_.bind(null,t,n))),n}Ai.VERSION=M_;var hu=ls(Oi(),1),B_="0.0.0-development",Di=()=>Promise.resolve();function H_(e,r,t){return e.retryLimiter.schedule(q_,e,r,t)}async function q_(e,r,t){let{pathname:n}=new URL(t.url,"http://github.test"),o=V_(t.method,n),s=!o&&t.method!=="GET"&&t.method!=="HEAD",i=t.method==="GET"&&n.startsWith("/search/"),a=n.startsWith("/graphql"),d=~~r.retryCount>0?{priority:0,weight:0}:{};e.clustering&&(d.expiration=1e3*60),(s||a)&&await e.write.key(e.id).schedule(d,Di),s&&e.triggersNotification(n)&&await e.notifications.key(e.id).schedule(d,Di),i&&await e.search.key(e.id).schedule(d,Di);let c=(o?e.auth:e.global).key(e.id).schedule(d,r,t);if(a){let u=await c;if(u.data.errors!=null&&u.data.errors.some(m=>m.type==="RATE_LIMITED"))throw Object.assign(new Error("GraphQL Rate Limit Exceeded"),{response:u,data:u.data})}return c}function V_(e,r){return e==="PATCH"&&/^\/applications\/[^/]+\/token\/scoped$/.test(r)||e==="POST"&&(/^\/applications\/[^/]+\/token$/.test(r)||/^\/app\/installations\/[^/]+\/access_tokens$/.test(r)||r==="/login/oauth/access_token")}var K_=["/orgs/{org}/invitations","/orgs/{org}/invitations/{invitation_id}","/orgs/{org}/teams/{team_slug}/discussions","/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments","/repos/{owner}/{repo}/collaborators/{username}","/repos/{owner}/{repo}/commits/{commit_sha}/comments","/repos/{owner}/{repo}/issues","/repos/{owner}/{repo}/issues/{issue_number}/comments","/repos/{owner}/{repo}/issues/{issue_number}/sub_issue","/repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority","/repos/{owner}/{repo}/pulls","/repos/{owner}/{repo}/pulls/{pull_number}/comments","/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies","/repos/{owner}/{repo}/pulls/{pull_number}/merge","/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers","/repos/{owner}/{repo}/pulls/{pull_number}/reviews","/repos/{owner}/{repo}/releases","/teams/{team_id}/discussions","/teams/{team_id}/discussions/{discussion_number}/comments"];function J_(e){let t=`^(?:${e.map(n=>n.split("/").map(o=>o.startsWith("{")?"(?:.+?)":o).join("/")).map(n=>`(?:${n})`).join("|")})[^/]*$`;return new RegExp(t,"i")}var fu=J_(K_),yu=fu.test.bind(fu),Pe={},z_=function(e,r){Pe.global=new e.Group({id:"octokit-global",maxConcurrent:10,...r}),Pe.auth=new e.Group({id:"octokit-auth",maxConcurrent:1,...r}),Pe.search=new e.Group({id:"octokit-search",maxConcurrent:1,minTime:2e3,...r}),Pe.write=new e.Group({id:"octokit-write",maxConcurrent:1,minTime:1e3,...r}),Pe.notifications=new e.Group({id:"octokit-notifications",maxConcurrent:1,minTime:3e3,...r})};function yo(e,r){let{enabled:t=!0,Bottleneck:n=hu.default,id:o="no-id",timeout:s=1e3*60*2,connection:i}=r.throttle||{};if(!t)return{};let a={timeout:s};typeof i<"u"&&(a.connection=i);let l=Object.assign({clustering:i!=null,triggersNotification:yu,fallbackSecondaryRateRetryAfter:60,retryAfterBaseValue:1e3,id:o},r.throttle);if(typeof l.onSecondaryRateLimit!="function"||typeof l.onRateLimit!="function")throw new Error(`octokit/plugin-throttling error:
|
|
70
70
|
You must pass the onSecondaryRateLimit and onRateLimit error handlers.
|
|
71
71
|
See https://octokit.github.io/rest.js/#throttling
|
|
72
72
|
|
|
@@ -76,30 +76,32 @@ ${a}
|
|
|
76
76
|
onRateLimit: (retryAfter, options) => {/* ... */}
|
|
77
77
|
}
|
|
78
78
|
})
|
|
79
|
-
`);let d=!1,c=()=>{if(d)return;d=!0,
|
|
80
|
-
`+n.repeat(u));let
|
|
81
|
-
`+n.repeat(u)+
|
|
82
|
-
`+n.repeat(u)),c.push(
|
|
79
|
+
`);let d=!1,c=()=>{if(d)return;d=!0,Pe.global==null&&z_(n,a),l.global=l.global??Pe.global,l.auth=l.auth??Pe.auth,l.search=l.search??Pe.search,l.write=l.write??Pe.write,l.notifications=l.notifications??Pe.notifications,l.retryLimiter=l.retryLimiter??new n;let u={},m=new n.Events(u);u.on("secondary-limit",l.onSecondaryRateLimit),u.on("rate-limit",l.onRateLimit),u.on("error",f=>e.log.warn("Error in throttling-plugin limit handler",f)),l.retryLimiter.on("failed",async function(f,h){let[v,y,S]=h.args,{pathname:G}=new URL(S.url,"http://github.test");if(!(G.startsWith("/graphql")&&f.status!==401||f.status===403||f.status===429))return;let L=~~y.retryCount;y.retryCount=L,S.request.retryCount=L;let{wantRetry:Q,retryAfter:ee=0}=await async function(){if(/\bsecondary rate\b/i.test(f.message)){let le=Number(f.response.headers["retry-after"])||v.fallbackSecondaryRateRetryAfter;return{wantRetry:await m.trigger("secondary-limit",le,S,e,L),retryAfter:le}}if(f.response.headers!=null&&f.response.headers["x-ratelimit-remaining"]==="0"||(f.response.data?.errors??[]).some(le=>le.type==="RATE_LIMITED")){let le=new Date(~~f.response.headers["x-ratelimit-reset"]*1e3).getTime(),Xe=Math.max(Math.ceil((le-Date.now())/1e3)+1,0);return{wantRetry:await m.trigger("rate-limit",Xe,S,e,L),retryAfter:Xe}}return{}}();if(Q)return y.retryCount++,ee*v.retryAfterBaseValue})};return e.hook.wrap("request",(u,m)=>(c(),H_(l,u,m))),{}}yo.VERSION=B_;yo.triggersNotification=yu;function sr(){return typeof navigator=="object"&&"userAgent"in navigator?navigator.userAgent:typeof process=="object"&&process.version!==void 0?`Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`:"<environment undetectable>"}function bo(e,r,t,n){if(typeof t!="function")throw new Error("method for before hook must be a function");return n||(n={}),Array.isArray(r)?r.reverse().reduce((o,s)=>bo.bind(null,e,s,o,n),t)():Promise.resolve().then(()=>e.registry[r]?e.registry[r].reduce((o,s)=>s.hook.bind(null,o,n),t)():t(n))}function bu(e,r,t,n){let o=n;e.registry[t]||(e.registry[t]=[]),r==="before"&&(n=(s,i)=>Promise.resolve().then(o.bind(null,i)).then(s.bind(null,i))),r==="after"&&(n=(s,i)=>{let a;return Promise.resolve().then(s.bind(null,i)).then(l=>(a=l,o(a,i))).then(()=>a)}),r==="error"&&(n=(s,i)=>Promise.resolve().then(s.bind(null,i)).catch(a=>o(a,i))),e.registry[t].push({hook:n,orig:o})}function ku(e,r,t){if(!e.registry[r])return;let n=e.registry[r].map(o=>o.orig).indexOf(t);n!==-1&&e.registry[r].splice(n,1)}var _u=Function.bind,Ru=_u.bind(_u);function wu(e,r,t){let n=Ru(ku,null).apply(null,t?[r,t]:[r]);e.api={remove:n},e.remove=n,["before","error","after","wrap"].forEach(o=>{let s=t?[r,o,t]:[r,o];e[o]=e.api[o]=Ru(bu,null).apply(null,s)})}function Q_(){let e=Symbol("Singular"),r={registry:{}},t=bo.bind(null,r,e);return wu(t,r,e),t}function Y_(){let e={registry:{}},r=bo.bind(null,e);return wu(r,e),r}var Eu={Singular:Q_,Collection:Y_};var X_="0.0.0-development",Z_=`octokit-endpoint.js/${X_} ${sr()}`,eR={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":Z_},mediaType:{format:""}};function rR(e){return e?Object.keys(e).reduce((r,t)=>(r[t.toLowerCase()]=e[t],r),{}):{}}function tR(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let r=Object.getPrototypeOf(e);if(r===null)return!0;let t=Object.prototype.hasOwnProperty.call(r,"constructor")&&r.constructor;return typeof t=="function"&&t instanceof t&&Function.prototype.call(t)===Function.prototype.call(e)}function Tu(e,r){let t=Object.assign({},e);return Object.keys(r).forEach(n=>{tR(r[n])?n in e?t[n]=Tu(e[n],r[n]):Object.assign(t,{[n]:r[n]}):Object.assign(t,{[n]:r[n]})}),t}function vu(e){for(let r in e)e[r]===void 0&&delete e[r];return e}function Li(e,r,t){if(typeof r=="string"){let[o,s]=r.split(" ");t=Object.assign(s?{method:o,url:s}:{url:o},t)}else t=Object.assign({},r);t.headers=rR(t.headers),vu(t),vu(t.headers);let n=Tu(e||{},t);return t.url==="/graphql"&&(e&&e.mediaType.previews?.length&&(n.mediaType.previews=e.mediaType.previews.filter(o=>!n.mediaType.previews.includes(o)).concat(n.mediaType.previews)),n.mediaType.previews=(n.mediaType.previews||[]).map(o=>o.replace(/-preview/,""))),n}function nR(e,r){let t=/\?/.test(e)?"&":"?",n=Object.keys(r);return n.length===0?e:e+t+n.map(o=>o==="q"?"q="+r.q.split("+").map(encodeURIComponent).join("+"):`${o}=${encodeURIComponent(r[o])}`).join("&")}var oR=/\{[^{}}]+\}/g;function sR(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function iR(e){let r=e.match(oR);return r?r.map(sR).reduce((t,n)=>t.concat(n),[]):[]}function Su(e,r){let t={__proto__:null};for(let n of Object.keys(e))r.indexOf(n)===-1&&(t[n]=e[n]);return t}function xu(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(r){return/%[0-9A-Fa-f]/.test(r)||(r=encodeURI(r).replace(/%5B/g,"[").replace(/%5D/g,"]")),r}).join("")}function nt(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(r){return"%"+r.charCodeAt(0).toString(16).toUpperCase()})}function Qt(e,r,t){return r=e==="+"||e==="#"?xu(r):nt(r),t?nt(t)+"="+r:r}function tt(e){return e!=null}function ji(e){return e===";"||e==="&"||e==="?"}function aR(e,r,t,n){var o=e[t],s=[];if(tt(o)&&o!=="")if(typeof o=="string"||typeof o=="number"||typeof o=="bigint"||typeof o=="boolean")o=o.toString(),n&&n!=="*"&&(o=o.substring(0,parseInt(n,10))),s.push(Qt(r,o,ji(r)?t:""));else if(n==="*")Array.isArray(o)?o.filter(tt).forEach(function(i){s.push(Qt(r,i,ji(r)?t:""))}):Object.keys(o).forEach(function(i){tt(o[i])&&s.push(Qt(r,o[i],i))});else{let i=[];Array.isArray(o)?o.filter(tt).forEach(function(a){i.push(Qt(r,a))}):Object.keys(o).forEach(function(a){tt(o[a])&&(i.push(nt(a)),i.push(Qt(r,o[a].toString())))}),ji(r)?s.push(nt(t)+"="+i.join(",")):i.length!==0&&s.push(i.join(","))}else r===";"?tt(o)&&s.push(nt(t)):o===""&&(r==="&"||r==="?")?s.push(nt(t)+"="):o===""&&s.push("");return s}function lR(e){return{expand:dR.bind(null,e)}}function dR(e,r){var t=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(n,o,s){if(o){let a="",l=[];if(t.indexOf(o.charAt(0))!==-1&&(a=o.charAt(0),o=o.substr(1)),o.split(/,/g).forEach(function(d){var c=/([^:\*]*)(?::(\d+)|(\*))?/.exec(d);l.push(aR(r,a,c[1],c[2]||c[3]))}),a&&a!=="+"){var i=",";return a==="?"?i="&":a!=="#"&&(i=a),(l.length!==0?a:"")+l.join(i)}else return l.join(",")}else return xu(s)}),e==="/"?e:e.replace(/\/$/,"")}function Pu(e){let r=e.method.toUpperCase(),t=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),n=Object.assign({},e.headers),o,s=Su(e,["method","baseUrl","url","headers","request","mediaType"]),i=iR(t);t=lR(t).expand(s),/^http/.test(t)||(t=e.baseUrl+t);let a=Object.keys(e).filter(c=>i.includes(c)).concat("baseUrl"),l=Su(s,a);if(!/application\/octet-stream/i.test(n.accept)&&(e.mediaType.format&&(n.accept=n.accept.split(/,/).map(c=>c.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(",")),t.endsWith("/graphql")&&e.mediaType.previews?.length)){let c=n.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[];n.accept=c.concat(e.mediaType.previews).map(u=>{let m=e.mediaType.format?`.${e.mediaType.format}`:"+json";return`application/vnd.github.${u}-preview${m}`}).join(",")}return["GET","HEAD"].includes(r)?t=nR(t,l):"data"in l?o=l.data:Object.keys(l).length&&(o=l),!n["content-type"]&&typeof o<"u"&&(n["content-type"]="application/json; charset=utf-8"),["PATCH","PUT"].includes(r)&&typeof o>"u"&&(o=""),Object.assign({method:r,url:t,headers:n},typeof o<"u"?{body:o}:null,e.request?{request:e.request}:null)}function cR(e,r,t){return Pu(Li(e,r,t))}function Ou(e,r){let t=Li(e,r),n=cR.bind(null,t);return Object.assign(n,{DEFAULTS:t,defaults:Ou.bind(null,t),merge:Li.bind(null,t),parse:Pu})}var Au=Ou(null,eR);var Ju=ls(Cu(),1);var _R=/^-?\d+$/,Ro=/^-?\d+n+$/,ir=JSON.stringify,Ci=JSON.parse,Uu=/^-?\d+n$/,Nu=/([\[:])?"(-?\d+)n"($|\s*[,\}\]])/g,Mu=/([\[:])?("-?\d+n+)n("$|"\s*[,\}\]])/g,Ni=e=>e===void 0||typeof e=="function"||typeof e=="symbol",Mi=e=>e!==null&&typeof e=="object"&&e.constructor&&e.constructor.name==="RawJSON",RR=(e,r,t)=>{let n="";typeof t=="number"?n=" ".repeat(Math.min(10,Math.max(0,Math.floor(t)))):typeof t=="string"&&(n=t.slice(0,10));let o=typeof r=="function",s=Array.isArray(r)?new Set(r.map(String)):null,i=(h,v,y)=>(y!==null&&typeof y=="object"&&typeof y.toJSON=="function"&&(y=y.toJSON(v)),typeof y=="string"&&Ro.test(y)?y+"n":typeof y=="bigint"?"rawJSON"in JSON?JSON.rawJSON(y.toString()):y.toString()+"n":(o&&(y=r.call(h,v,y)),y!==null&&typeof y=="object"&&(y instanceof Number||y instanceof String||y instanceof Boolean)&&(y=y.valueOf()),y)),a=i({"":e},"",e);if(Ni(a))return;let l=a===null||typeof a!="object",d=Mi(a);if(l||d)return ir(a);let c=[],u=0,m=[{parent:{"":a},key:"",val:a,isArray:Array.isArray(a),keys:Array.isArray(a)?null:Object.keys(a),index:0,first:!0}],f=new WeakSet([a]);for(;m.length>0;){let h=m[m.length-1];h.index===0&&(c.push(h.isArray?"[":"{"),u++);let v=!1;if(h.isArray)if(h.index<h.val.length){h.first||c.push(","),n&&c.push(`
|
|
80
|
+
`+n.repeat(u));let y=h.val[h.index],S=i(h.val,String(h.index),y);if(Ni(S))c.push("null"),h.first=!1,h.index++;else{let G=S!==null&&typeof S=="object",H=Mi(S);if(G&&!H){if(f.has(S))throw new TypeError("Converting circular structure to JSON");f.add(S),m.push({parent:h.val,key:String(h.index),val:S,isArray:Array.isArray(S),keys:Array.isArray(S)?null:Object.keys(S),index:0,first:!0}),h.first=!1,h.index++}else c.push(ir(S)),h.first=!1,h.index++}}else v=!0;else{for(;h.index<h.keys.length;){let S=h.keys[h.index++];if(s&&!s.has(S))continue;let H=h.val[S],L=i(h.val,S,H);if(Ni(L))continue;h.first||c.push(","),n?c.push(`
|
|
81
|
+
`+n.repeat(u)+ir(S)+": "):c.push(ir(S)+":");let Q=L!==null&&typeof L=="object",ee=Mi(L);if(Q&&!ee){if(f.has(L))throw new TypeError("Converting circular structure to JSON");f.add(L),m.push({parent:h.val,key:S,val:L,isArray:Array.isArray(L),keys:Array.isArray(L)?null:Object.keys(L),index:0,first:!0}),h.first=!1;break}else c.push(ir(L)),h.first=!1}h.index>=h.keys.length&&m[m.length-1]===h&&(v=!0)}v&&(u--,!h.first&&n&&c.push(`
|
|
82
|
+
`+n.repeat(u)),c.push(h.isArray?"]":"}"),f.delete(h.val),m.pop())}return c.join("")},Bu=(e,r,t)=>{try{return"rawJSON"in JSON?ir(e,(a,l)=>typeof l=="bigint"?JSON.rawJSON(l.toString()):typeof r=="function"?r(a,l):(Array.isArray(r)&&r.includes(a),l),t):e?ir(e,(a,l)=>typeof l=="string"&&Ro.test(l)||typeof l=="bigint"?l.toString()+"n":typeof r=="function"?r(a,l):(Array.isArray(r)&&r.includes(a),l),t).replace(Nu,"$1$2$3").replace(Mu,"$1$2$3"):ir(e,r,t)}catch(n){if(n instanceof RangeError){let o=RR(e,r,t);return o===void 0?void 0:"rawJSON"in JSON?o:o.replace(Nu,"$1$2$3").replace(Mu,"$1$2$3")}throw n}},_o=new Map,wR=()=>{let e=JSON.parse.toString();if(_o.has(e))return _o.get(e);try{let r=JSON.parse("1",(t,n,o)=>!!o?.source&&o.source==="1");return _o.set(e,r),r}catch{return _o.set(e,!1),!1}},ER=(e,r,t,n)=>typeof r=="string"&&Uu.test(r)?BigInt(r.slice(0,-1)):typeof r=="string"&&Ro.test(r)?r.slice(0,-1):typeof n=="function"?n(e,r,t):r,vR=(e,r)=>JSON.parse(e,(t,n,o)=>{let s=typeof n=="number",i=n>Number.MAX_SAFE_INTEGER||n<Number.MIN_SAFE_INTEGER,a=s&&i,l=o&&_R.test(o.source);return a&&l?BigInt(o.source):typeof r=="function"?r(t,n,o):n}),Hu=Number.MAX_SAFE_INTEGER.toString(),Fu=Hu.length,SR=/"(?:\\.|[^"])*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g,TR=/^"-?\d+n+"$/,xR=(e,r)=>{let t={"":e},n=[{parent:t,key:"",visited:!1}];for(;n.length>0;){let o=n[n.length-1];if(o.visited){let{parent:s,key:i}=o,a=s[i];typeof a=="string"&&(Uu.test(a)?a=BigInt(a.slice(0,-1)):Ro.test(a)&&(a=a.slice(0,-1))),typeof r=="function"&&(a=r.call(s,i,a)),a===void 0?delete s[i]:s[i]=a,n.pop()}else{o.visited=!0;let s=o.parent[o.key];if(s!==null&&typeof s=="object"){let a=Object.keys(s);for(let l=a.length-1;l>=0;l--)n.push({parent:s,key:a[l],visited:!1})}}}return t[""]},Wu=e=>e.replace(SR,(r,t,n,o)=>{let s=r[0]==='"';if(s&&TR.test(r))return r.substring(0,r.length-1)+'n"';let a=n||o,l=t&&(t.length<Fu||t.length===Fu&&t<=Hu);return s||a||l?r:'"'+r+'n"'}),qu=(e,r)=>{if(!e)return Ci(e,r);try{if(wR())return vR(e,r);let t=Wu(e);return Ci(t,(n,o,s)=>ER(n,o,s,r))}catch(t){if(t instanceof RangeError){let n=Wu(e),o=Ci(n);return xR(o,r)}throw t}};var PR="10.0.13",OR={headers:{"user-agent":`octokit-request.js/${PR} ${sr()}`}};function AR(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let r=Object.getPrototypeOf(e);if(r===null)return!0;let t=Object.prototype.hasOwnProperty.call(r,"constructor")&&r.constructor;return typeof t=="function"&&t instanceof t&&Function.prototype.call(t)===Function.prototype.call(e)}var Vu=()=>"";async function Ku(e){let r=e.request?.fetch||globalThis.fetch;if(!r)throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");let t=e.request?.log||console,n=e.request?.parseSuccessResponseBody!==!1,o=AR(e.body)||Array.isArray(e.body)?Bu(e.body):e.body,s=Object.fromEntries(Object.entries(e.headers).map(([u,m])=>[u,String(m)])),i;try{i=await r(e.url,{method:e.method,body:o,redirect:e.request?.redirect,headers:s,signal:e.request?.signal,...e.body&&{duplex:"half"}})}catch(u){let m="Unknown Error";if(u instanceof Error){if(u.name==="AbortError")throw u.status=500,u;m=u.message,u.name==="TypeError"&&"cause"in u&&(u.cause instanceof Error?m=u.cause.message:typeof u.cause=="string"&&(m=u.cause))}let f=new ze(m,500,{request:e});throw f.cause=u,f}let a=i.status,l=i.url,d={};for(let[u,m]of i.headers)d[u]=m;let c={url:l,status:a,headers:d,data:""};if("deprecation"in d){let u=d.link&&d.link.match(/<([^<>]+)>; rel="deprecation"/),m=u&&u.pop();t.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${d.sunset}${m?`. See ${m}`:""}`)}if(a===204||a===205)return c;if(e.method==="HEAD"){if(a<400)return c;throw new ze(i.statusText,a,{response:c,request:e})}if(a===304)throw c.data=await Fi(i),new ze("Not modified",a,{response:c,request:e});if(a>=400)throw c.data=await Fi(i),new ze(jR(c.data),a,{response:c,request:e});return c.data=n?await Fi(i):i.body,c}async function Fi(e){let r=e.headers.get("content-type");if(!r)return e.text().catch(Vu);let t=(0,Ju.parse)(r);if(DR(t)){let n="";try{return n=await e.text(),qu(n)}catch{return n}}else return t.type.startsWith("text/")||t.parameters.charset?.toLowerCase()==="utf-8"&&t.type!=="application/octet-stream"?e.text().catch(Vu):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function DR(e){return e.type==="application/json"||e.type==="application/scim+json"}function jR(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return"Unknown error";if(typeof e=="object"&&e!==null&&"message"in e){let r=e,t="documentation_url"in r?` - ${r.documentation_url}`:"";return Array.isArray(r.errors)?`${r.message}: ${r.errors.map(n=>JSON.stringify(n)).join(", ")}${t}`:`${r.message}${t}`}return`Unknown error: ${JSON.stringify(e)}`}function Wi(e,r){let t=e.defaults(r);return Object.assign(function(o,s){let i=t.merge(o,s);if(!i.request||!i.request.hook)return Ku(t.parse(i));let a=(l,d)=>Ku(t.parse(t.merge(l,d)));return Object.assign(a,{endpoint:t,defaults:Wi.bind(null,t)}),i.request.hook(a,i)},{endpoint:t,defaults:Wi.bind(null,t)})}var Yt=Wi(Au,OR);var LR="0.0.0-development";function GR(e){return`Request failed due to following response errors:
|
|
83
83
|
`+e.errors.map(r=>` - ${r.message}`).join(`
|
|
84
|
-
`)}var AR=class extends Error{constructor(e,r,t){super(OR(t)),this.request=e,this.headers=r,this.response=t,this.errors=t.errors,this.data=t.data,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}request;headers;response;name="GraphqlResponseError";errors;data},DR=["method","baseUrl","url","headers","request","query","mediaType","operationName"],jR=["query","method","url"],Ku=/\/api\/v3\/?$/;function LR(e,r,t){if(t){if(typeof r=="string"&&"query"in t)return Promise.reject(new Error('[@octokit/graphql] "query" cannot be used as variable name'));for(let i in t)if(jR.includes(i))return Promise.reject(new Error(`[@octokit/graphql] "${i}" cannot be used as variable name`))}let n=typeof r=="string"?Object.assign({query:r},t):r,o=Object.keys(n).reduce((i,a)=>DR.includes(a)?(i[a]=n[a],i):(i.variables||(i.variables={}),i.variables[a]=n[a],i),{}),s=n.baseUrl||e.endpoint.DEFAULTS.baseUrl;return Ku.test(s)&&(o.url=s.replace(Ku,"/api/graphql")),e(o).then(i=>{if(i.data.errors){let a={};for(let l of Object.keys(i.headers))a[l]=i.headers[l];throw new AR(o,a,i.data)}return i.data.data})}function Wi(e,r){let t=e.defaults(r);return Object.assign((o,s)=>LR(t,o,s),{defaults:Wi.bind(null,t),endpoint:t.endpoint})}var nD=Wi(Jt,{headers:{"user-agent":`octokit-graphql.js/${PR} ${or()}`},method:"POST",url:"/graphql"});function Ju(e){return Wi(e,{method:"POST",url:"/graphql"})}var Ui="(?:[a-zA-Z0-9_-]+)",zu="\\.",Qu=new RegExp(`^${Ui}${zu}${Ui}${zu}${Ui}$`),IR=Qu.test.bind(Qu);async function $R(e){let r=IR(e),t=e.startsWith("v1.")||e.startsWith("ghs_"),n=e.startsWith("ghu_");return{type:"token",token:e,tokenType:r?"app":t?"installation":n?"user-to-server":"oauth"}}function GR(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function CR(e,r,t,n){let o=r.endpoint.merge(t,n);return o.headers.authorization=GR(e),r(o)}var Yu=function(r){if(!r)throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");if(typeof r!="string")throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");return r=r.replace(/^(token|bearer) +/i,""),Object.assign($R.bind(null,r),{hook:CR.bind(null,r)})};var Bi="7.0.7";var Xu=()=>{},NR=console.warn.bind(console),MR=console.error.bind(console);function FR(e={}){return typeof e.debug!="function"&&(e.debug=Xu),typeof e.info!="function"&&(e.info=Xu),typeof e.warn!="function"&&(e.warn=NR),typeof e.error!="function"&&(e.error=MR),e}var Zu=`octokit-core.js/${Bi} ${or()}`,_o=class{static VERSION=Bi;static defaults(r){return class extends this{constructor(...n){let o=n[0]||{};if(typeof r=="function"){super(r(o));return}super(Object.assign({},r,o,o.userAgent&&r.userAgent?{userAgent:`${o.userAgent} ${r.userAgent}`}:null))}}}static plugins=[];static plugin(...r){let t=this.plugins;return class extends this{static plugins=t.concat(r.filter(o=>!t.includes(o)))}}constructor(r={}){let t=new Ru.Collection,n={baseUrl:Jt.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},r.request,{hook:t.bind(null,"request")}),mediaType:{previews:[],format:""}};if(n.headers["user-agent"]=r.userAgent?`${r.userAgent} ${Zu}`:Zu,r.baseUrl&&(n.baseUrl=r.baseUrl),r.previews&&(n.mediaType.previews=r.previews),r.timeZone&&(n.headers["time-zone"]=r.timeZone),this.request=Jt.defaults(n),this.graphql=Ju(this.request).defaults(n),this.log=FR(r.log),this.hook=t,r.authStrategy){let{authStrategy:s,...i}=r,a=s(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:i},r.auth));t.wrap("request",a.hook),this.auth=a}else if(!r.auth)this.auth=async()=>({type:"unauthenticated"});else{let s=Yu(r.auth);t.wrap("request",s.hook),this.auth=s}let o=this.constructor;for(let s=0;s<o.plugins.length;++s)Object.assign(this,o.plugins[s](this,r))}request;graphql;log;hook;auth};var ep="6.0.0";function Hi(e){e.hook.wrap("request",(r,t)=>{e.log.debug("request",t);let n=Date.now(),o=e.request.endpoint.parse(t),s=o.url.replace(t.baseUrl,"");return r(t).then(i=>{let a=i.headers["x-github-request-id"];return e.log.info(`${o.method} ${s} - ${i.status} with id ${a} in ${Date.now()-n}ms`),i}).catch(i=>{let a=i.response?.headers["x-github-request-id"]||"UNKNOWN";throw e.log.error(`${o.method} ${s} - ${i.status} with id ${a} in ${Date.now()-n}ms`),i})})}Hi.VERSION=ep;var WR="0.0.0-development";function UR(e){if(!e.data)return{...e,data:[]};if(!(("total_count"in e.data||"total_commits"in e.data)&&!("url"in e.data)))return e;let t=e.data.incomplete_results,n=e.data.repository_selection,o=e.data.total_count,s=e.data.total_commits;delete e.data.incomplete_results,delete e.data.repository_selection,delete e.data.total_count,delete e.data.total_commits;let i=Object.keys(e.data)[0],a=e.data[i];return e.data=a,typeof t<"u"&&(e.data.incomplete_results=t),typeof n<"u"&&(e.data.repository_selection=n),e.data.total_count=o,e.data.total_commits=s,e}function qi(e,r,t){let n=typeof r=="function"?r.endpoint(t):e.request.endpoint(r,t),o=typeof r=="function"?r:e.request,s=n.method,i=n.headers,a=n.url;return{[Symbol.asyncIterator]:()=>({async next(){if(!a)return{done:!0};try{let l=await o({method:s,url:a,headers:i}),d=UR(l);if(a=((d.headers.link||"").match(/<([^<>]+)>;\s*rel="next"/)||[])[1],!a&&"total_commits"in d.data){let c=new URL(d.url),u=c.searchParams,m=parseInt(u.get("page")||"1",10),h=parseInt(u.get("per_page")||"250",10);m*h<d.data.total_commits&&(u.set("page",String(m+1)),a=c.toString())}return{value:d}}catch(l){if(l.status!==409)throw l;return a="",{value:{status:200,headers:{},data:[]}}}}})}}function rp(e,r,t,n){return typeof t=="function"&&(n=t,t=void 0),tp(e,[],qi(e,r,t)[Symbol.asyncIterator](),n)}function tp(e,r,t,n){return t.next().then(o=>{if(o.done)return r;let s=!1;function i(){s=!0}return r=r.concat(n?n(o.value,i):o.value.data),s?r:tp(e,r,t,n)})}var _D=Object.assign(rp,{iterator:qi});function Vi(e){return{paginate:Object.assign(rp.bind(null,e),{iterator:qi.bind(null,e)})}}Vi.VERSION=WR;var Ki="17.0.0";var BR={actions:{addCustomLabelsToSelfHostedRunnerForOrg:["POST /orgs/{org}/actions/runners/{runner_id}/labels"],addCustomLabelsToSelfHostedRunnerForRepo:["POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],addRepoAccessToSelfHostedRunnerGroupInOrg:["PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}"],addSelectedRepoToOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],addSelectedRepoToOrgVariable:["PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"],approveWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"],cancelWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"],createEnvironmentVariable:["POST /repos/{owner}/{repo}/environments/{environment_name}/variables"],createHostedRunnerForOrg:["POST /orgs/{org}/actions/hosted-runners"],createOrUpdateEnvironmentSecret:["PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],createOrUpdateOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"],createOrgVariable:["POST /orgs/{org}/actions/variables"],createRegistrationTokenForOrg:["POST /orgs/{org}/actions/runners/registration-token"],createRegistrationTokenForRepo:["POST /repos/{owner}/{repo}/actions/runners/registration-token"],createRemoveTokenForOrg:["POST /orgs/{org}/actions/runners/remove-token"],createRemoveTokenForRepo:["POST /repos/{owner}/{repo}/actions/runners/remove-token"],createRepoVariable:["POST /repos/{owner}/{repo}/actions/variables"],createWorkflowDispatch:["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"],deleteActionsCacheById:["DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}"],deleteActionsCacheByKey:["DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}"],deleteArtifact:["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],deleteCustomImageFromOrg:["DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}"],deleteCustomImageVersionFromOrg:["DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}"],deleteEnvironmentSecret:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],deleteEnvironmentVariable:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],deleteHostedRunnerForOrg:["DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],deleteOrgSecret:["DELETE /orgs/{org}/actions/secrets/{secret_name}"],deleteOrgVariable:["DELETE /orgs/{org}/actions/variables/{name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"],deleteRepoVariable:["DELETE /repos/{owner}/{repo}/actions/variables/{name}"],deleteSelfHostedRunnerFromOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}"],deleteSelfHostedRunnerFromRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"],deleteWorkflowRun:["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],deleteWorkflowRunLogs:["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],disableSelectedRepositoryGithubActionsOrganization:["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"],disableWorkflow:["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"],downloadArtifact:["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"],downloadJobLogsForWorkflowRun:["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"],downloadWorkflowRunAttemptLogs:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"],downloadWorkflowRunLogs:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],enableSelectedRepositoryGithubActionsOrganization:["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"],enableWorkflow:["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"],forceCancelWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel"],generateRunnerJitconfigForOrg:["POST /orgs/{org}/actions/runners/generate-jitconfig"],generateRunnerJitconfigForRepo:["POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig"],getActionsCacheList:["GET /repos/{owner}/{repo}/actions/caches"],getActionsCacheUsage:["GET /repos/{owner}/{repo}/actions/cache/usage"],getActionsCacheUsageByRepoForOrg:["GET /orgs/{org}/actions/cache/usage-by-repository"],getActionsCacheUsageForOrg:["GET /orgs/{org}/actions/cache/usage"],getAllowedActionsOrganization:["GET /orgs/{org}/actions/permissions/selected-actions"],getAllowedActionsRepository:["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"],getArtifact:["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],getCustomImageForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}"],getCustomImageVersionForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}"],getCustomOidcSubClaimForRepo:["GET /repos/{owner}/{repo}/actions/oidc/customization/sub"],getEnvironmentPublicKey:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key"],getEnvironmentSecret:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],getEnvironmentVariable:["GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],getGithubActionsDefaultWorkflowPermissionsOrganization:["GET /orgs/{org}/actions/permissions/workflow"],getGithubActionsDefaultWorkflowPermissionsRepository:["GET /repos/{owner}/{repo}/actions/permissions/workflow"],getGithubActionsPermissionsOrganization:["GET /orgs/{org}/actions/permissions"],getGithubActionsPermissionsRepository:["GET /repos/{owner}/{repo}/actions/permissions"],getHostedRunnerForOrg:["GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],getHostedRunnersGithubOwnedImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/github-owned"],getHostedRunnersLimitsForOrg:["GET /orgs/{org}/actions/hosted-runners/limits"],getHostedRunnersMachineSpecsForOrg:["GET /orgs/{org}/actions/hosted-runners/machine-sizes"],getHostedRunnersPartnerImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/partner"],getHostedRunnersPlatformsForOrg:["GET /orgs/{org}/actions/hosted-runners/platforms"],getJobForWorkflowRun:["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],getOrgPublicKey:["GET /orgs/{org}/actions/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/actions/secrets/{secret_name}"],getOrgVariable:["GET /orgs/{org}/actions/variables/{name}"],getPendingDeploymentsForRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],getRepoPermissions:["GET /repos/{owner}/{repo}/actions/permissions",{},{renamed:["actions","getGithubActionsPermissionsRepository"]}],getRepoPublicKey:["GET /repos/{owner}/{repo}/actions/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],getRepoVariable:["GET /repos/{owner}/{repo}/actions/variables/{name}"],getReviewsForRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"],getSelfHostedRunnerForOrg:["GET /orgs/{org}/actions/runners/{runner_id}"],getSelfHostedRunnerForRepo:["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"],getWorkflow:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],getWorkflowAccessToRepository:["GET /repos/{owner}/{repo}/actions/permissions/access"],getWorkflowRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],getWorkflowRunAttempt:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"],getWorkflowRunUsage:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"],getWorkflowUsage:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"],listArtifactsForRepo:["GET /repos/{owner}/{repo}/actions/artifacts"],listCustomImageVersionsForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions"],listCustomImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom"],listEnvironmentSecrets:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets"],listEnvironmentVariables:["GET /repos/{owner}/{repo}/environments/{environment_name}/variables"],listGithubHostedRunnersInGroupForOrg:["GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners"],listHostedRunnersForOrg:["GET /orgs/{org}/actions/hosted-runners"],listJobsForWorkflowRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"],listJobsForWorkflowRunAttempt:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"],listLabelsForSelfHostedRunnerForOrg:["GET /orgs/{org}/actions/runners/{runner_id}/labels"],listLabelsForSelfHostedRunnerForRepo:["GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],listOrgSecrets:["GET /orgs/{org}/actions/secrets"],listOrgVariables:["GET /orgs/{org}/actions/variables"],listRepoOrganizationSecrets:["GET /repos/{owner}/{repo}/actions/organization-secrets"],listRepoOrganizationVariables:["GET /repos/{owner}/{repo}/actions/organization-variables"],listRepoSecrets:["GET /repos/{owner}/{repo}/actions/secrets"],listRepoVariables:["GET /repos/{owner}/{repo}/actions/variables"],listRepoWorkflows:["GET /repos/{owner}/{repo}/actions/workflows"],listRunnerApplicationsForOrg:["GET /orgs/{org}/actions/runners/downloads"],listRunnerApplicationsForRepo:["GET /repos/{owner}/{repo}/actions/runners/downloads"],listSelectedReposForOrgSecret:["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"],listSelectedReposForOrgVariable:["GET /orgs/{org}/actions/variables/{name}/repositories"],listSelectedRepositoriesEnabledGithubActionsOrganization:["GET /orgs/{org}/actions/permissions/repositories"],listSelfHostedRunnersForOrg:["GET /orgs/{org}/actions/runners"],listSelfHostedRunnersForRepo:["GET /repos/{owner}/{repo}/actions/runners"],listWorkflowRunArtifacts:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"],listWorkflowRuns:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"],listWorkflowRunsForRepo:["GET /repos/{owner}/{repo}/actions/runs"],reRunJobForWorkflowRun:["POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun"],reRunWorkflow:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],reRunWorkflowFailedJobs:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs"],removeAllCustomLabelsFromSelfHostedRunnerForOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}/labels"],removeAllCustomLabelsFromSelfHostedRunnerForRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],removeCustomLabelFromSelfHostedRunnerForOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}"],removeCustomLabelFromSelfHostedRunnerForRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],removeSelectedRepoFromOrgVariable:["DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"],reviewCustomGatesForRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule"],reviewPendingDeploymentsForRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],setAllowedActionsOrganization:["PUT /orgs/{org}/actions/permissions/selected-actions"],setAllowedActionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"],setCustomLabelsForSelfHostedRunnerForOrg:["PUT /orgs/{org}/actions/runners/{runner_id}/labels"],setCustomLabelsForSelfHostedRunnerForRepo:["PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],setCustomOidcSubClaimForRepo:["PUT /repos/{owner}/{repo}/actions/oidc/customization/sub"],setGithubActionsDefaultWorkflowPermissionsOrganization:["PUT /orgs/{org}/actions/permissions/workflow"],setGithubActionsDefaultWorkflowPermissionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions/workflow"],setGithubActionsPermissionsOrganization:["PUT /orgs/{org}/actions/permissions"],setGithubActionsPermissionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"],setSelectedReposForOrgVariable:["PUT /orgs/{org}/actions/variables/{name}/repositories"],setSelectedRepositoriesEnabledGithubActionsOrganization:["PUT /orgs/{org}/actions/permissions/repositories"],setWorkflowAccessToRepository:["PUT /repos/{owner}/{repo}/actions/permissions/access"],updateEnvironmentVariable:["PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],updateHostedRunnerForOrg:["PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],updateOrgVariable:["PATCH /orgs/{org}/actions/variables/{name}"],updateRepoVariable:["PATCH /repos/{owner}/{repo}/actions/variables/{name}"]},activity:{checkRepoIsStarredByAuthenticatedUser:["GET /user/starred/{owner}/{repo}"],deleteRepoSubscription:["DELETE /repos/{owner}/{repo}/subscription"],deleteThreadSubscription:["DELETE /notifications/threads/{thread_id}/subscription"],getFeeds:["GET /feeds"],getRepoSubscription:["GET /repos/{owner}/{repo}/subscription"],getThread:["GET /notifications/threads/{thread_id}"],getThreadSubscriptionForAuthenticatedUser:["GET /notifications/threads/{thread_id}/subscription"],listEventsForAuthenticatedUser:["GET /users/{username}/events"],listNotificationsForAuthenticatedUser:["GET /notifications"],listOrgEventsForAuthenticatedUser:["GET /users/{username}/events/orgs/{org}"],listPublicEvents:["GET /events"],listPublicEventsForRepoNetwork:["GET /networks/{owner}/{repo}/events"],listPublicEventsForUser:["GET /users/{username}/events/public"],listPublicOrgEvents:["GET /orgs/{org}/events"],listReceivedEventsForUser:["GET /users/{username}/received_events"],listReceivedPublicEventsForUser:["GET /users/{username}/received_events/public"],listRepoEvents:["GET /repos/{owner}/{repo}/events"],listRepoNotificationsForAuthenticatedUser:["GET /repos/{owner}/{repo}/notifications"],listReposStarredByAuthenticatedUser:["GET /user/starred"],listReposStarredByUser:["GET /users/{username}/starred"],listReposWatchedByUser:["GET /users/{username}/subscriptions"],listStargazersForRepo:["GET /repos/{owner}/{repo}/stargazers"],listWatchedReposForAuthenticatedUser:["GET /user/subscriptions"],listWatchersForRepo:["GET /repos/{owner}/{repo}/subscribers"],markNotificationsAsRead:["PUT /notifications"],markRepoNotificationsAsRead:["PUT /repos/{owner}/{repo}/notifications"],markThreadAsDone:["DELETE /notifications/threads/{thread_id}"],markThreadAsRead:["PATCH /notifications/threads/{thread_id}"],setRepoSubscription:["PUT /repos/{owner}/{repo}/subscription"],setThreadSubscription:["PUT /notifications/threads/{thread_id}/subscription"],starRepoForAuthenticatedUser:["PUT /user/starred/{owner}/{repo}"],unstarRepoForAuthenticatedUser:["DELETE /user/starred/{owner}/{repo}"]},apps:{addRepoToInstallation:["PUT /user/installations/{installation_id}/repositories/{repository_id}",{},{renamed:["apps","addRepoToInstallationForAuthenticatedUser"]}],addRepoToInstallationForAuthenticatedUser:["PUT /user/installations/{installation_id}/repositories/{repository_id}"],checkToken:["POST /applications/{client_id}/token"],createFromManifest:["POST /app-manifests/{code}/conversions"],createInstallationAccessToken:["POST /app/installations/{installation_id}/access_tokens"],deleteAuthorization:["DELETE /applications/{client_id}/grant"],deleteInstallation:["DELETE /app/installations/{installation_id}"],deleteToken:["DELETE /applications/{client_id}/token"],getAuthenticated:["GET /app"],getBySlug:["GET /apps/{app_slug}"],getInstallation:["GET /app/installations/{installation_id}"],getOrgInstallation:["GET /orgs/{org}/installation"],getRepoInstallation:["GET /repos/{owner}/{repo}/installation"],getSubscriptionPlanForAccount:["GET /marketplace_listing/accounts/{account_id}"],getSubscriptionPlanForAccountStubbed:["GET /marketplace_listing/stubbed/accounts/{account_id}"],getUserInstallation:["GET /users/{username}/installation"],getWebhookConfigForApp:["GET /app/hook/config"],getWebhookDelivery:["GET /app/hook/deliveries/{delivery_id}"],listAccountsForPlan:["GET /marketplace_listing/plans/{plan_id}/accounts"],listAccountsForPlanStubbed:["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"],listInstallationReposForAuthenticatedUser:["GET /user/installations/{installation_id}/repositories"],listInstallationRequestsForAuthenticatedApp:["GET /app/installation-requests"],listInstallations:["GET /app/installations"],listInstallationsForAuthenticatedUser:["GET /user/installations"],listPlans:["GET /marketplace_listing/plans"],listPlansStubbed:["GET /marketplace_listing/stubbed/plans"],listReposAccessibleToInstallation:["GET /installation/repositories"],listSubscriptionsForAuthenticatedUser:["GET /user/marketplace_purchases"],listSubscriptionsForAuthenticatedUserStubbed:["GET /user/marketplace_purchases/stubbed"],listWebhookDeliveries:["GET /app/hook/deliveries"],redeliverWebhookDelivery:["POST /app/hook/deliveries/{delivery_id}/attempts"],removeRepoFromInstallation:["DELETE /user/installations/{installation_id}/repositories/{repository_id}",{},{renamed:["apps","removeRepoFromInstallationForAuthenticatedUser"]}],removeRepoFromInstallationForAuthenticatedUser:["DELETE /user/installations/{installation_id}/repositories/{repository_id}"],resetToken:["PATCH /applications/{client_id}/token"],revokeInstallationAccessToken:["DELETE /installation/token"],scopeToken:["POST /applications/{client_id}/token/scoped"],suspendInstallation:["PUT /app/installations/{installation_id}/suspended"],unsuspendInstallation:["DELETE /app/installations/{installation_id}/suspended"],updateWebhookConfigForApp:["PATCH /app/hook/config"]},billing:{getGithubActionsBillingOrg:["GET /orgs/{org}/settings/billing/actions"],getGithubActionsBillingUser:["GET /users/{username}/settings/billing/actions"],getGithubBillingPremiumRequestUsageReportOrg:["GET /organizations/{org}/settings/billing/premium_request/usage"],getGithubBillingPremiumRequestUsageReportUser:["GET /users/{username}/settings/billing/premium_request/usage"],getGithubBillingUsageReportOrg:["GET /organizations/{org}/settings/billing/usage"],getGithubBillingUsageReportUser:["GET /users/{username}/settings/billing/usage"],getGithubPackagesBillingOrg:["GET /orgs/{org}/settings/billing/packages"],getGithubPackagesBillingUser:["GET /users/{username}/settings/billing/packages"],getSharedStorageBillingOrg:["GET /orgs/{org}/settings/billing/shared-storage"],getSharedStorageBillingUser:["GET /users/{username}/settings/billing/shared-storage"]},campaigns:{createCampaign:["POST /orgs/{org}/campaigns"],deleteCampaign:["DELETE /orgs/{org}/campaigns/{campaign_number}"],getCampaignSummary:["GET /orgs/{org}/campaigns/{campaign_number}"],listOrgCampaigns:["GET /orgs/{org}/campaigns"],updateCampaign:["PATCH /orgs/{org}/campaigns/{campaign_number}"]},checks:{create:["POST /repos/{owner}/{repo}/check-runs"],createSuite:["POST /repos/{owner}/{repo}/check-suites"],get:["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"],getSuite:["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"],listAnnotations:["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"],listForRef:["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"],listForSuite:["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"],listSuitesForRef:["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"],rerequestRun:["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"],rerequestSuite:["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"],setSuitesPreferences:["PATCH /repos/{owner}/{repo}/check-suites/preferences"],update:["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]},codeScanning:{commitAutofix:["POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits"],createAutofix:["POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"],createVariantAnalysis:["POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses"],deleteAnalysis:["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"],deleteCodeqlDatabase:["DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"],getAlert:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}",{},{renamedParameters:{alert_id:"alert_number"}}],getAnalysis:["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"],getAutofix:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"],getCodeqlDatabase:["GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"],getDefaultSetup:["GET /repos/{owner}/{repo}/code-scanning/default-setup"],getSarif:["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],getVariantAnalysis:["GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}"],getVariantAnalysisRepoTask:["GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}"],listAlertInstances:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"],listAlertsForOrg:["GET /orgs/{org}/code-scanning/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/code-scanning/alerts"],listAlertsInstances:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",{},{renamed:["codeScanning","listAlertInstances"]}],listCodeqlDatabases:["GET /repos/{owner}/{repo}/code-scanning/codeql/databases"],listRecentAnalyses:["GET /repos/{owner}/{repo}/code-scanning/analyses"],updateAlert:["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"],updateDefaultSetup:["PATCH /repos/{owner}/{repo}/code-scanning/default-setup"],uploadSarif:["POST /repos/{owner}/{repo}/code-scanning/sarifs"]},codeSecurity:{attachConfiguration:["POST /orgs/{org}/code-security/configurations/{configuration_id}/attach"],attachEnterpriseConfiguration:["POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach"],createConfiguration:["POST /orgs/{org}/code-security/configurations"],createConfigurationForEnterprise:["POST /enterprises/{enterprise}/code-security/configurations"],deleteConfiguration:["DELETE /orgs/{org}/code-security/configurations/{configuration_id}"],deleteConfigurationForEnterprise:["DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}"],detachConfiguration:["DELETE /orgs/{org}/code-security/configurations/detach"],getConfiguration:["GET /orgs/{org}/code-security/configurations/{configuration_id}"],getConfigurationForRepository:["GET /repos/{owner}/{repo}/code-security-configuration"],getConfigurationsForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations"],getConfigurationsForOrg:["GET /orgs/{org}/code-security/configurations"],getDefaultConfigurations:["GET /orgs/{org}/code-security/configurations/defaults"],getDefaultConfigurationsForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations/defaults"],getRepositoriesForConfiguration:["GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories"],getRepositoriesForEnterpriseConfiguration:["GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories"],getSingleConfigurationForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}"],setConfigurationAsDefault:["PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults"],setConfigurationAsDefaultForEnterprise:["PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults"],updateConfiguration:["PATCH /orgs/{org}/code-security/configurations/{configuration_id}"],updateEnterpriseConfiguration:["PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}"]},codesOfConduct:{getAllCodesOfConduct:["GET /codes_of_conduct"],getConductCode:["GET /codes_of_conduct/{key}"]},codespaces:{addRepositoryForSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],addSelectedRepoToOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"],checkPermissionsForDevcontainer:["GET /repos/{owner}/{repo}/codespaces/permissions_check"],codespaceMachinesForAuthenticatedUser:["GET /user/codespaces/{codespace_name}/machines"],createForAuthenticatedUser:["POST /user/codespaces"],createOrUpdateOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],createOrUpdateSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}"],createWithPrForAuthenticatedUser:["POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces"],createWithRepoForAuthenticatedUser:["POST /repos/{owner}/{repo}/codespaces"],deleteForAuthenticatedUser:["DELETE /user/codespaces/{codespace_name}"],deleteFromOrganization:["DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}"],deleteOrgSecret:["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],deleteSecretForAuthenticatedUser:["DELETE /user/codespaces/secrets/{secret_name}"],exportForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/exports"],getCodespacesForUserInOrg:["GET /orgs/{org}/members/{username}/codespaces"],getExportDetailsForAuthenticatedUser:["GET /user/codespaces/{codespace_name}/exports/{export_id}"],getForAuthenticatedUser:["GET /user/codespaces/{codespace_name}"],getOrgPublicKey:["GET /orgs/{org}/codespaces/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/codespaces/secrets/{secret_name}"],getPublicKeyForAuthenticatedUser:["GET /user/codespaces/secrets/public-key"],getRepoPublicKey:["GET /repos/{owner}/{repo}/codespaces/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],getSecretForAuthenticatedUser:["GET /user/codespaces/secrets/{secret_name}"],listDevcontainersInRepositoryForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/devcontainers"],listForAuthenticatedUser:["GET /user/codespaces"],listInOrganization:["GET /orgs/{org}/codespaces",{},{renamedParameters:{org_id:"org"}}],listInRepositoryForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces"],listOrgSecrets:["GET /orgs/{org}/codespaces/secrets"],listRepoSecrets:["GET /repos/{owner}/{repo}/codespaces/secrets"],listRepositoriesForSecretForAuthenticatedUser:["GET /user/codespaces/secrets/{secret_name}/repositories"],listSecretsForAuthenticatedUser:["GET /user/codespaces/secrets"],listSelectedReposForOrgSecret:["GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories"],preFlightWithRepoForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/new"],publishForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/publish"],removeRepositoryForSecretForAuthenticatedUser:["DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"],repoMachinesForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/machines"],setRepositoriesForSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}/repositories"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories"],startForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/start"],stopForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/stop"],stopInOrganization:["POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop"],updateForAuthenticatedUser:["PATCH /user/codespaces/{codespace_name}"]},copilot:{addCopilotSeatsForTeams:["POST /orgs/{org}/copilot/billing/selected_teams"],addCopilotSeatsForUsers:["POST /orgs/{org}/copilot/billing/selected_users"],cancelCopilotSeatAssignmentForTeams:["DELETE /orgs/{org}/copilot/billing/selected_teams"],cancelCopilotSeatAssignmentForUsers:["DELETE /orgs/{org}/copilot/billing/selected_users"],copilotMetricsForOrganization:["GET /orgs/{org}/copilot/metrics"],copilotMetricsForTeam:["GET /orgs/{org}/team/{team_slug}/copilot/metrics"],getCopilotOrganizationDetails:["GET /orgs/{org}/copilot/billing"],getCopilotSeatDetailsForUser:["GET /orgs/{org}/members/{username}/copilot"],listCopilotSeats:["GET /orgs/{org}/copilot/billing/seats"]},credentials:{revoke:["POST /credentials/revoke"]},dependabot:{addSelectedRepoToOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],createOrUpdateOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],deleteOrgSecret:["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],getAlert:["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],getOrgPublicKey:["GET /orgs/{org}/dependabot/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/dependabot/secrets/{secret_name}"],getRepoPublicKey:["GET /repos/{owner}/{repo}/dependabot/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],listAlertsForEnterprise:["GET /enterprises/{enterprise}/dependabot/alerts"],listAlertsForOrg:["GET /orgs/{org}/dependabot/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/dependabot/alerts"],listOrgSecrets:["GET /orgs/{org}/dependabot/secrets"],listRepoSecrets:["GET /repos/{owner}/{repo}/dependabot/secrets"],listSelectedReposForOrgSecret:["GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],repositoryAccessForOrg:["GET /organizations/{org}/dependabot/repository-access"],setRepositoryAccessDefaultLevel:["PUT /organizations/{org}/dependabot/repository-access/default-level"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],updateAlert:["PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],updateRepositoryAccessForOrg:["PATCH /organizations/{org}/dependabot/repository-access"]},dependencyGraph:{createRepositorySnapshot:["POST /repos/{owner}/{repo}/dependency-graph/snapshots"],diffRange:["GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}"],exportSbom:["GET /repos/{owner}/{repo}/dependency-graph/sbom"]},emojis:{get:["GET /emojis"]},enterpriseTeamMemberships:{add:["PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"],bulkAdd:["POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add"],bulkRemove:["POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove"],get:["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"],list:["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships"],remove:["DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"]},enterpriseTeamOrganizations:{add:["PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],bulkAdd:["POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add"],bulkRemove:["POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove"],delete:["DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],getAssignment:["GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],getAssignments:["GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations"]},enterpriseTeams:{create:["POST /enterprises/{enterprise}/teams"],delete:["DELETE /enterprises/{enterprise}/teams/{team_slug}"],get:["GET /enterprises/{enterprise}/teams/{team_slug}"],list:["GET /enterprises/{enterprise}/teams"],update:["PATCH /enterprises/{enterprise}/teams/{team_slug}"]},gists:{checkIsStarred:["GET /gists/{gist_id}/star"],create:["POST /gists"],createComment:["POST /gists/{gist_id}/comments"],delete:["DELETE /gists/{gist_id}"],deleteComment:["DELETE /gists/{gist_id}/comments/{comment_id}"],fork:["POST /gists/{gist_id}/forks"],get:["GET /gists/{gist_id}"],getComment:["GET /gists/{gist_id}/comments/{comment_id}"],getRevision:["GET /gists/{gist_id}/{sha}"],list:["GET /gists"],listComments:["GET /gists/{gist_id}/comments"],listCommits:["GET /gists/{gist_id}/commits"],listForUser:["GET /users/{username}/gists"],listForks:["GET /gists/{gist_id}/forks"],listPublic:["GET /gists/public"],listStarred:["GET /gists/starred"],star:["PUT /gists/{gist_id}/star"],unstar:["DELETE /gists/{gist_id}/star"],update:["PATCH /gists/{gist_id}"],updateComment:["PATCH /gists/{gist_id}/comments/{comment_id}"]},git:{createBlob:["POST /repos/{owner}/{repo}/git/blobs"],createCommit:["POST /repos/{owner}/{repo}/git/commits"],createRef:["POST /repos/{owner}/{repo}/git/refs"],createTag:["POST /repos/{owner}/{repo}/git/tags"],createTree:["POST /repos/{owner}/{repo}/git/trees"],deleteRef:["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],getBlob:["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],getCommit:["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],getRef:["GET /repos/{owner}/{repo}/git/ref/{ref}"],getTag:["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],getTree:["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],listMatchingRefs:["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],updateRef:["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]},gitignore:{getAllTemplates:["GET /gitignore/templates"],getTemplate:["GET /gitignore/templates/{name}"]},hostedCompute:{createNetworkConfigurationForOrg:["POST /orgs/{org}/settings/network-configurations"],deleteNetworkConfigurationFromOrg:["DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}"],getNetworkConfigurationForOrg:["GET /orgs/{org}/settings/network-configurations/{network_configuration_id}"],getNetworkSettingsForOrg:["GET /orgs/{org}/settings/network-settings/{network_settings_id}"],listNetworkConfigurationsForOrg:["GET /orgs/{org}/settings/network-configurations"],updateNetworkConfigurationForOrg:["PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}"]},interactions:{getRestrictionsForAuthenticatedUser:["GET /user/interaction-limits"],getRestrictionsForOrg:["GET /orgs/{org}/interaction-limits"],getRestrictionsForRepo:["GET /repos/{owner}/{repo}/interaction-limits"],getRestrictionsForYourPublicRepos:["GET /user/interaction-limits",{},{renamed:["interactions","getRestrictionsForAuthenticatedUser"]}],removeRestrictionsForAuthenticatedUser:["DELETE /user/interaction-limits"],removeRestrictionsForOrg:["DELETE /orgs/{org}/interaction-limits"],removeRestrictionsForRepo:["DELETE /repos/{owner}/{repo}/interaction-limits"],removeRestrictionsForYourPublicRepos:["DELETE /user/interaction-limits",{},{renamed:["interactions","removeRestrictionsForAuthenticatedUser"]}],setRestrictionsForAuthenticatedUser:["PUT /user/interaction-limits"],setRestrictionsForOrg:["PUT /orgs/{org}/interaction-limits"],setRestrictionsForRepo:["PUT /repos/{owner}/{repo}/interaction-limits"],setRestrictionsForYourPublicRepos:["PUT /user/interaction-limits",{},{renamed:["interactions","setRestrictionsForAuthenticatedUser"]}]},issues:{addAssignees:["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"],addBlockedByDependency:["POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by"],addLabels:["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],addSubIssue:["POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"],checkUserCanBeAssigned:["GET /repos/{owner}/{repo}/assignees/{assignee}"],checkUserCanBeAssignedToIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}"],create:["POST /repos/{owner}/{repo}/issues"],createComment:["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"],createLabel:["POST /repos/{owner}/{repo}/labels"],createMilestone:["POST /repos/{owner}/{repo}/milestones"],deleteComment:["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"],deleteLabel:["DELETE /repos/{owner}/{repo}/labels/{name}"],deleteMilestone:["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"],get:["GET /repos/{owner}/{repo}/issues/{issue_number}"],getComment:["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],getEvent:["GET /repos/{owner}/{repo}/issues/events/{event_id}"],getLabel:["GET /repos/{owner}/{repo}/labels/{name}"],getMilestone:["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],getParent:["GET /repos/{owner}/{repo}/issues/{issue_number}/parent"],list:["GET /issues"],listAssignees:["GET /repos/{owner}/{repo}/assignees"],listComments:["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],listCommentsForRepo:["GET /repos/{owner}/{repo}/issues/comments"],listDependenciesBlockedBy:["GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by"],listDependenciesBlocking:["GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking"],listEvents:["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],listEventsForRepo:["GET /repos/{owner}/{repo}/issues/events"],listEventsForTimeline:["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"],listForAuthenticatedUser:["GET /user/issues"],listForOrg:["GET /orgs/{org}/issues"],listForRepo:["GET /repos/{owner}/{repo}/issues"],listLabelsForMilestone:["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"],listLabelsForRepo:["GET /repos/{owner}/{repo}/labels"],listLabelsOnIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"],listMilestones:["GET /repos/{owner}/{repo}/milestones"],listSubIssues:["GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"],lock:["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],removeAllLabels:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"],removeAssignees:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"],removeDependencyBlockedBy:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}"],removeLabel:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"],removeSubIssue:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue"],reprioritizeSubIssue:["PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority"],setLabels:["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],unlock:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],update:["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],updateComment:["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],updateLabel:["PATCH /repos/{owner}/{repo}/labels/{name}"],updateMilestone:["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"]},licenses:{get:["GET /licenses/{license}"],getAllCommonlyUsed:["GET /licenses"],getForRepo:["GET /repos/{owner}/{repo}/license"]},markdown:{render:["POST /markdown"],renderRaw:["POST /markdown/raw",{headers:{"content-type":"text/plain; charset=utf-8"}}]},meta:{get:["GET /meta"],getAllVersions:["GET /versions"],getOctocat:["GET /octocat"],getZen:["GET /zen"],root:["GET /"]},migrations:{deleteArchiveForAuthenticatedUser:["DELETE /user/migrations/{migration_id}/archive"],deleteArchiveForOrg:["DELETE /orgs/{org}/migrations/{migration_id}/archive"],downloadArchiveForOrg:["GET /orgs/{org}/migrations/{migration_id}/archive"],getArchiveForAuthenticatedUser:["GET /user/migrations/{migration_id}/archive"],getStatusForAuthenticatedUser:["GET /user/migrations/{migration_id}"],getStatusForOrg:["GET /orgs/{org}/migrations/{migration_id}"],listForAuthenticatedUser:["GET /user/migrations"],listForOrg:["GET /orgs/{org}/migrations"],listReposForAuthenticatedUser:["GET /user/migrations/{migration_id}/repositories"],listReposForOrg:["GET /orgs/{org}/migrations/{migration_id}/repositories"],listReposForUser:["GET /user/migrations/{migration_id}/repositories",{},{renamed:["migrations","listReposForAuthenticatedUser"]}],startForAuthenticatedUser:["POST /user/migrations"],startForOrg:["POST /orgs/{org}/migrations"],unlockRepoForAuthenticatedUser:["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"],unlockRepoForOrg:["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"]},oidc:{getOidcCustomSubTemplateForOrg:["GET /orgs/{org}/actions/oidc/customization/sub"],updateOidcCustomSubTemplateForOrg:["PUT /orgs/{org}/actions/oidc/customization/sub"]},orgs:{addSecurityManagerTeam:["PUT /orgs/{org}/security-managers/teams/{team_slug}",{},{deprecated:"octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team"}],assignTeamToOrgRole:["PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"],assignUserToOrgRole:["PUT /orgs/{org}/organization-roles/users/{username}/{role_id}"],blockUser:["PUT /orgs/{org}/blocks/{username}"],cancelInvitation:["DELETE /orgs/{org}/invitations/{invitation_id}"],checkBlockedUser:["GET /orgs/{org}/blocks/{username}"],checkMembershipForUser:["GET /orgs/{org}/members/{username}"],checkPublicMembershipForUser:["GET /orgs/{org}/public_members/{username}"],convertMemberToOutsideCollaborator:["PUT /orgs/{org}/outside_collaborators/{username}"],createArtifactStorageRecord:["POST /orgs/{org}/artifacts/metadata/storage-record"],createInvitation:["POST /orgs/{org}/invitations"],createIssueType:["POST /orgs/{org}/issue-types"],createWebhook:["POST /orgs/{org}/hooks"],customPropertiesForOrgsCreateOrUpdateOrganizationValues:["PATCH /organizations/{org}/org-properties/values"],customPropertiesForOrgsGetOrganizationValues:["GET /organizations/{org}/org-properties/values"],customPropertiesForReposCreateOrUpdateOrganizationDefinition:["PUT /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposCreateOrUpdateOrganizationDefinitions:["PATCH /orgs/{org}/properties/schema"],customPropertiesForReposCreateOrUpdateOrganizationValues:["PATCH /orgs/{org}/properties/values"],customPropertiesForReposDeleteOrganizationDefinition:["DELETE /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposGetOrganizationDefinition:["GET /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposGetOrganizationDefinitions:["GET /orgs/{org}/properties/schema"],customPropertiesForReposGetOrganizationValues:["GET /orgs/{org}/properties/values"],delete:["DELETE /orgs/{org}"],deleteAttestationsBulk:["POST /orgs/{org}/attestations/delete-request"],deleteAttestationsById:["DELETE /orgs/{org}/attestations/{attestation_id}"],deleteAttestationsBySubjectDigest:["DELETE /orgs/{org}/attestations/digest/{subject_digest}"],deleteIssueType:["DELETE /orgs/{org}/issue-types/{issue_type_id}"],deleteWebhook:["DELETE /orgs/{org}/hooks/{hook_id}"],disableSelectedRepositoryImmutableReleasesOrganization:["DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}"],enableSelectedRepositoryImmutableReleasesOrganization:["PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}"],get:["GET /orgs/{org}"],getImmutableReleasesSettings:["GET /orgs/{org}/settings/immutable-releases"],getImmutableReleasesSettingsRepositories:["GET /orgs/{org}/settings/immutable-releases/repositories"],getMembershipForAuthenticatedUser:["GET /user/memberships/orgs/{org}"],getMembershipForUser:["GET /orgs/{org}/memberships/{username}"],getOrgRole:["GET /orgs/{org}/organization-roles/{role_id}"],getOrgRulesetHistory:["GET /orgs/{org}/rulesets/{ruleset_id}/history"],getOrgRulesetVersion:["GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}"],getWebhook:["GET /orgs/{org}/hooks/{hook_id}"],getWebhookConfigForOrg:["GET /orgs/{org}/hooks/{hook_id}/config"],getWebhookDelivery:["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"],list:["GET /organizations"],listAppInstallations:["GET /orgs/{org}/installations"],listArtifactStorageRecords:["GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records"],listAttestationRepositories:["GET /orgs/{org}/attestations/repositories"],listAttestations:["GET /orgs/{org}/attestations/{subject_digest}"],listAttestationsBulk:["POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}"],listBlockedUsers:["GET /orgs/{org}/blocks"],listFailedInvitations:["GET /orgs/{org}/failed_invitations"],listForAuthenticatedUser:["GET /user/orgs"],listForUser:["GET /users/{username}/orgs"],listInvitationTeams:["GET /orgs/{org}/invitations/{invitation_id}/teams"],listIssueTypes:["GET /orgs/{org}/issue-types"],listMembers:["GET /orgs/{org}/members"],listMembershipsForAuthenticatedUser:["GET /user/memberships/orgs"],listOrgRoleTeams:["GET /orgs/{org}/organization-roles/{role_id}/teams"],listOrgRoleUsers:["GET /orgs/{org}/organization-roles/{role_id}/users"],listOrgRoles:["GET /orgs/{org}/organization-roles"],listOrganizationFineGrainedPermissions:["GET /orgs/{org}/organization-fine-grained-permissions"],listOutsideCollaborators:["GET /orgs/{org}/outside_collaborators"],listPatGrantRepositories:["GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories"],listPatGrantRequestRepositories:["GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories"],listPatGrantRequests:["GET /orgs/{org}/personal-access-token-requests"],listPatGrants:["GET /orgs/{org}/personal-access-tokens"],listPendingInvitations:["GET /orgs/{org}/invitations"],listPublicMembers:["GET /orgs/{org}/public_members"],listSecurityManagerTeams:["GET /orgs/{org}/security-managers",{},{deprecated:"octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams"}],listWebhookDeliveries:["GET /orgs/{org}/hooks/{hook_id}/deliveries"],listWebhooks:["GET /orgs/{org}/hooks"],pingWebhook:["POST /orgs/{org}/hooks/{hook_id}/pings"],redeliverWebhookDelivery:["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],removeMember:["DELETE /orgs/{org}/members/{username}"],removeMembershipForUser:["DELETE /orgs/{org}/memberships/{username}"],removeOutsideCollaborator:["DELETE /orgs/{org}/outside_collaborators/{username}"],removePublicMembershipForAuthenticatedUser:["DELETE /orgs/{org}/public_members/{username}"],removeSecurityManagerTeam:["DELETE /orgs/{org}/security-managers/teams/{team_slug}",{},{deprecated:"octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team"}],reviewPatGrantRequest:["POST /orgs/{org}/personal-access-token-requests/{pat_request_id}"],reviewPatGrantRequestsInBulk:["POST /orgs/{org}/personal-access-token-requests"],revokeAllOrgRolesTeam:["DELETE /orgs/{org}/organization-roles/teams/{team_slug}"],revokeAllOrgRolesUser:["DELETE /orgs/{org}/organization-roles/users/{username}"],revokeOrgRoleTeam:["DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"],revokeOrgRoleUser:["DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}"],setImmutableReleasesSettings:["PUT /orgs/{org}/settings/immutable-releases"],setImmutableReleasesSettingsRepositories:["PUT /orgs/{org}/settings/immutable-releases/repositories"],setMembershipForUser:["PUT /orgs/{org}/memberships/{username}"],setPublicMembershipForAuthenticatedUser:["PUT /orgs/{org}/public_members/{username}"],unblockUser:["DELETE /orgs/{org}/blocks/{username}"],update:["PATCH /orgs/{org}"],updateIssueType:["PUT /orgs/{org}/issue-types/{issue_type_id}"],updateMembershipForAuthenticatedUser:["PATCH /user/memberships/orgs/{org}"],updatePatAccess:["POST /orgs/{org}/personal-access-tokens/{pat_id}"],updatePatAccesses:["POST /orgs/{org}/personal-access-tokens"],updateWebhook:["PATCH /orgs/{org}/hooks/{hook_id}"],updateWebhookConfigForOrg:["PATCH /orgs/{org}/hooks/{hook_id}/config"]},packages:{deletePackageForAuthenticatedUser:["DELETE /user/packages/{package_type}/{package_name}"],deletePackageForOrg:["DELETE /orgs/{org}/packages/{package_type}/{package_name}"],deletePackageForUser:["DELETE /users/{username}/packages/{package_type}/{package_name}"],deletePackageVersionForAuthenticatedUser:["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],deletePackageVersionForOrg:["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],deletePackageVersionForUser:["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],getAllPackageVersionsForAPackageOwnedByAnOrg:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions",{},{renamed:["packages","getAllPackageVersionsForPackageOwnedByOrg"]}],getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions",{},{renamed:["packages","getAllPackageVersionsForPackageOwnedByAuthenticatedUser"]}],getAllPackageVersionsForPackageOwnedByAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions"],getAllPackageVersionsForPackageOwnedByOrg:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"],getAllPackageVersionsForPackageOwnedByUser:["GET /users/{username}/packages/{package_type}/{package_name}/versions"],getPackageForAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}"],getPackageForOrganization:["GET /orgs/{org}/packages/{package_type}/{package_name}"],getPackageForUser:["GET /users/{username}/packages/{package_type}/{package_name}"],getPackageVersionForAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],getPackageVersionForOrganization:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],getPackageVersionForUser:["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],listDockerMigrationConflictingPackagesForAuthenticatedUser:["GET /user/docker/conflicts"],listDockerMigrationConflictingPackagesForOrganization:["GET /orgs/{org}/docker/conflicts"],listDockerMigrationConflictingPackagesForUser:["GET /users/{username}/docker/conflicts"],listPackagesForAuthenticatedUser:["GET /user/packages"],listPackagesForOrganization:["GET /orgs/{org}/packages"],listPackagesForUser:["GET /users/{username}/packages"],restorePackageForAuthenticatedUser:["POST /user/packages/{package_type}/{package_name}/restore{?token}"],restorePackageForOrg:["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"],restorePackageForUser:["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"],restorePackageVersionForAuthenticatedUser:["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],restorePackageVersionForOrg:["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],restorePackageVersionForUser:["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"]},privateRegistries:{createOrgPrivateRegistry:["POST /orgs/{org}/private-registries"],deleteOrgPrivateRegistry:["DELETE /orgs/{org}/private-registries/{secret_name}"],getOrgPrivateRegistry:["GET /orgs/{org}/private-registries/{secret_name}"],getOrgPublicKey:["GET /orgs/{org}/private-registries/public-key"],listOrgPrivateRegistries:["GET /orgs/{org}/private-registries"],updateOrgPrivateRegistry:["PATCH /orgs/{org}/private-registries/{secret_name}"]},projects:{addItemForOrg:["POST /orgs/{org}/projectsV2/{project_number}/items"],addItemForUser:["POST /users/{username}/projectsV2/{project_number}/items"],deleteItemForOrg:["DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],deleteItemForUser:["DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}"],getFieldForOrg:["GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}"],getFieldForUser:["GET /users/{username}/projectsV2/{project_number}/fields/{field_id}"],getForOrg:["GET /orgs/{org}/projectsV2/{project_number}"],getForUser:["GET /users/{username}/projectsV2/{project_number}"],getOrgItem:["GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],getUserItem:["GET /users/{username}/projectsV2/{project_number}/items/{item_id}"],listFieldsForOrg:["GET /orgs/{org}/projectsV2/{project_number}/fields"],listFieldsForUser:["GET /users/{username}/projectsV2/{project_number}/fields"],listForOrg:["GET /orgs/{org}/projectsV2"],listForUser:["GET /users/{username}/projectsV2"],listItemsForOrg:["GET /orgs/{org}/projectsV2/{project_number}/items"],listItemsForUser:["GET /users/{username}/projectsV2/{project_number}/items"],updateItemForOrg:["PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],updateItemForUser:["PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}"]},pulls:{checkIfMerged:["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],create:["POST /repos/{owner}/{repo}/pulls"],createReplyForReviewComment:["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"],createReview:["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],createReviewComment:["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"],deletePendingReview:["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],deleteReviewComment:["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"],dismissReview:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"],get:["GET /repos/{owner}/{repo}/pulls/{pull_number}"],getReview:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],getReviewComment:["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],list:["GET /repos/{owner}/{repo}/pulls"],listCommentsForReview:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"],listCommits:["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],listFiles:["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],listRequestedReviewers:["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],listReviewComments:["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"],listReviewCommentsForRepo:["GET /repos/{owner}/{repo}/pulls/comments"],listReviews:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],merge:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],removeRequestedReviewers:["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],requestReviewers:["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],submitReview:["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"],update:["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],updateBranch:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"],updateReview:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],updateReviewComment:["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"]},rateLimit:{get:["GET /rate_limit"]},reactions:{createForCommitComment:["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"],createForIssue:["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"],createForIssueComment:["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],createForPullRequestReviewComment:["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],createForRelease:["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"],createForTeamDiscussionCommentInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],createForTeamDiscussionInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"],deleteForCommitComment:["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"],deleteForIssue:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"],deleteForIssueComment:["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"],deleteForPullRequestComment:["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"],deleteForRelease:["DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}"],deleteForTeamDiscussion:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"],deleteForTeamDiscussionComment:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"],listForCommitComment:["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"],listForIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"],listForIssueComment:["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],listForPullRequestReviewComment:["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],listForRelease:["GET /repos/{owner}/{repo}/releases/{release_id}/reactions"],listForTeamDiscussionCommentInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],listForTeamDiscussionInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"]},repos:{acceptInvitation:["PATCH /user/repository_invitations/{invitation_id}",{},{renamed:["repos","acceptInvitationForAuthenticatedUser"]}],acceptInvitationForAuthenticatedUser:["PATCH /user/repository_invitations/{invitation_id}"],addAppAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],addCollaborator:["PUT /repos/{owner}/{repo}/collaborators/{username}"],addStatusCheckContexts:["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],addTeamAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],addUserAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],cancelPagesDeployment:["POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel"],checkAutomatedSecurityFixes:["GET /repos/{owner}/{repo}/automated-security-fixes"],checkCollaborator:["GET /repos/{owner}/{repo}/collaborators/{username}"],checkImmutableReleases:["GET /repos/{owner}/{repo}/immutable-releases"],checkPrivateVulnerabilityReporting:["GET /repos/{owner}/{repo}/private-vulnerability-reporting"],checkVulnerabilityAlerts:["GET /repos/{owner}/{repo}/vulnerability-alerts"],codeownersErrors:["GET /repos/{owner}/{repo}/codeowners/errors"],compareCommits:["GET /repos/{owner}/{repo}/compare/{base}...{head}"],compareCommitsWithBasehead:["GET /repos/{owner}/{repo}/compare/{basehead}"],createAttestation:["POST /repos/{owner}/{repo}/attestations"],createAutolink:["POST /repos/{owner}/{repo}/autolinks"],createCommitComment:["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"],createCommitSignatureProtection:["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],createCommitStatus:["POST /repos/{owner}/{repo}/statuses/{sha}"],createDeployKey:["POST /repos/{owner}/{repo}/keys"],createDeployment:["POST /repos/{owner}/{repo}/deployments"],createDeploymentBranchPolicy:["POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"],createDeploymentProtectionRule:["POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"],createDeploymentStatus:["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],createDispatchEvent:["POST /repos/{owner}/{repo}/dispatches"],createForAuthenticatedUser:["POST /user/repos"],createFork:["POST /repos/{owner}/{repo}/forks"],createInOrg:["POST /orgs/{org}/repos"],createOrUpdateEnvironment:["PUT /repos/{owner}/{repo}/environments/{environment_name}"],createOrUpdateFileContents:["PUT /repos/{owner}/{repo}/contents/{path}"],createOrgRuleset:["POST /orgs/{org}/rulesets"],createPagesDeployment:["POST /repos/{owner}/{repo}/pages/deployments"],createPagesSite:["POST /repos/{owner}/{repo}/pages"],createRelease:["POST /repos/{owner}/{repo}/releases"],createRepoRuleset:["POST /repos/{owner}/{repo}/rulesets"],createUsingTemplate:["POST /repos/{template_owner}/{template_repo}/generate"],createWebhook:["POST /repos/{owner}/{repo}/hooks"],customPropertiesForReposCreateOrUpdateRepositoryValues:["PATCH /repos/{owner}/{repo}/properties/values"],customPropertiesForReposGetRepositoryValues:["GET /repos/{owner}/{repo}/properties/values"],declineInvitation:["DELETE /user/repository_invitations/{invitation_id}",{},{renamed:["repos","declineInvitationForAuthenticatedUser"]}],declineInvitationForAuthenticatedUser:["DELETE /user/repository_invitations/{invitation_id}"],delete:["DELETE /repos/{owner}/{repo}"],deleteAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],deleteAdminBranchProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],deleteAnEnvironment:["DELETE /repos/{owner}/{repo}/environments/{environment_name}"],deleteAutolink:["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"],deleteBranchProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"],deleteCommitComment:["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],deleteCommitSignatureProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],deleteDeployKey:["DELETE /repos/{owner}/{repo}/keys/{key_id}"],deleteDeployment:["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"],deleteDeploymentBranchPolicy:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],deleteFile:["DELETE /repos/{owner}/{repo}/contents/{path}"],deleteInvitation:["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"],deleteOrgRuleset:["DELETE /orgs/{org}/rulesets/{ruleset_id}"],deletePagesSite:["DELETE /repos/{owner}/{repo}/pages"],deletePullRequestReviewProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],deleteRelease:["DELETE /repos/{owner}/{repo}/releases/{release_id}"],deleteReleaseAsset:["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"],deleteRepoRuleset:["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"],deleteWebhook:["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],disableAutomatedSecurityFixes:["DELETE /repos/{owner}/{repo}/automated-security-fixes"],disableDeploymentProtectionRule:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"],disableImmutableReleases:["DELETE /repos/{owner}/{repo}/immutable-releases"],disablePrivateVulnerabilityReporting:["DELETE /repos/{owner}/{repo}/private-vulnerability-reporting"],disableVulnerabilityAlerts:["DELETE /repos/{owner}/{repo}/vulnerability-alerts"],downloadArchive:["GET /repos/{owner}/{repo}/zipball/{ref}",{},{renamed:["repos","downloadZipballArchive"]}],downloadTarballArchive:["GET /repos/{owner}/{repo}/tarball/{ref}"],downloadZipballArchive:["GET /repos/{owner}/{repo}/zipball/{ref}"],enableAutomatedSecurityFixes:["PUT /repos/{owner}/{repo}/automated-security-fixes"],enableImmutableReleases:["PUT /repos/{owner}/{repo}/immutable-releases"],enablePrivateVulnerabilityReporting:["PUT /repos/{owner}/{repo}/private-vulnerability-reporting"],enableVulnerabilityAlerts:["PUT /repos/{owner}/{repo}/vulnerability-alerts"],generateReleaseNotes:["POST /repos/{owner}/{repo}/releases/generate-notes"],get:["GET /repos/{owner}/{repo}"],getAccessRestrictions:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],getAdminBranchProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],getAllDeploymentProtectionRules:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"],getAllEnvironments:["GET /repos/{owner}/{repo}/environments"],getAllStatusCheckContexts:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"],getAllTopics:["GET /repos/{owner}/{repo}/topics"],getAppsWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"],getAutolink:["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"],getBranch:["GET /repos/{owner}/{repo}/branches/{branch}"],getBranchProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection"],getBranchRules:["GET /repos/{owner}/{repo}/rules/branches/{branch}"],getClones:["GET /repos/{owner}/{repo}/traffic/clones"],getCodeFrequencyStats:["GET /repos/{owner}/{repo}/stats/code_frequency"],getCollaboratorPermissionLevel:["GET /repos/{owner}/{repo}/collaborators/{username}/permission"],getCombinedStatusForRef:["GET /repos/{owner}/{repo}/commits/{ref}/status"],getCommit:["GET /repos/{owner}/{repo}/commits/{ref}"],getCommitActivityStats:["GET /repos/{owner}/{repo}/stats/commit_activity"],getCommitComment:["GET /repos/{owner}/{repo}/comments/{comment_id}"],getCommitSignatureProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],getCommunityProfileMetrics:["GET /repos/{owner}/{repo}/community/profile"],getContent:["GET /repos/{owner}/{repo}/contents/{path}"],getContributorsStats:["GET /repos/{owner}/{repo}/stats/contributors"],getCustomDeploymentProtectionRule:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"],getDeployKey:["GET /repos/{owner}/{repo}/keys/{key_id}"],getDeployment:["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],getDeploymentBranchPolicy:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],getDeploymentStatus:["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"],getEnvironment:["GET /repos/{owner}/{repo}/environments/{environment_name}"],getLatestPagesBuild:["GET /repos/{owner}/{repo}/pages/builds/latest"],getLatestRelease:["GET /repos/{owner}/{repo}/releases/latest"],getOrgRuleSuite:["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"],getOrgRuleSuites:["GET /orgs/{org}/rulesets/rule-suites"],getOrgRuleset:["GET /orgs/{org}/rulesets/{ruleset_id}"],getOrgRulesets:["GET /orgs/{org}/rulesets"],getPages:["GET /repos/{owner}/{repo}/pages"],getPagesBuild:["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],getPagesDeployment:["GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}"],getPagesHealthCheck:["GET /repos/{owner}/{repo}/pages/health"],getParticipationStats:["GET /repos/{owner}/{repo}/stats/participation"],getPullRequestReviewProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],getPunchCardStats:["GET /repos/{owner}/{repo}/stats/punch_card"],getReadme:["GET /repos/{owner}/{repo}/readme"],getReadmeInDirectory:["GET /repos/{owner}/{repo}/readme/{dir}"],getRelease:["GET /repos/{owner}/{repo}/releases/{release_id}"],getReleaseAsset:["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],getReleaseByTag:["GET /repos/{owner}/{repo}/releases/tags/{tag}"],getRepoRuleSuite:["GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}"],getRepoRuleSuites:["GET /repos/{owner}/{repo}/rulesets/rule-suites"],getRepoRuleset:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"],getRepoRulesetHistory:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history"],getRepoRulesetVersion:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}"],getRepoRulesets:["GET /repos/{owner}/{repo}/rulesets"],getStatusChecksProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],getTeamsWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"],getTopPaths:["GET /repos/{owner}/{repo}/traffic/popular/paths"],getTopReferrers:["GET /repos/{owner}/{repo}/traffic/popular/referrers"],getUsersWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"],getViews:["GET /repos/{owner}/{repo}/traffic/views"],getWebhook:["GET /repos/{owner}/{repo}/hooks/{hook_id}"],getWebhookConfigForRepo:["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"],getWebhookDelivery:["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"],listActivities:["GET /repos/{owner}/{repo}/activity"],listAttestations:["GET /repos/{owner}/{repo}/attestations/{subject_digest}"],listAutolinks:["GET /repos/{owner}/{repo}/autolinks"],listBranches:["GET /repos/{owner}/{repo}/branches"],listBranchesForHeadCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"],listCollaborators:["GET /repos/{owner}/{repo}/collaborators"],listCommentsForCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"],listCommitCommentsForRepo:["GET /repos/{owner}/{repo}/comments"],listCommitStatusesForRef:["GET /repos/{owner}/{repo}/commits/{ref}/statuses"],listCommits:["GET /repos/{owner}/{repo}/commits"],listContributors:["GET /repos/{owner}/{repo}/contributors"],listCustomDeploymentRuleIntegrations:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps"],listDeployKeys:["GET /repos/{owner}/{repo}/keys"],listDeploymentBranchPolicies:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"],listDeploymentStatuses:["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],listDeployments:["GET /repos/{owner}/{repo}/deployments"],listForAuthenticatedUser:["GET /user/repos"],listForOrg:["GET /orgs/{org}/repos"],listForUser:["GET /users/{username}/repos"],listForks:["GET /repos/{owner}/{repo}/forks"],listInvitations:["GET /repos/{owner}/{repo}/invitations"],listInvitationsForAuthenticatedUser:["GET /user/repository_invitations"],listLanguages:["GET /repos/{owner}/{repo}/languages"],listPagesBuilds:["GET /repos/{owner}/{repo}/pages/builds"],listPublic:["GET /repositories"],listPullRequestsAssociatedWithCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"],listReleaseAssets:["GET /repos/{owner}/{repo}/releases/{release_id}/assets"],listReleases:["GET /repos/{owner}/{repo}/releases"],listTags:["GET /repos/{owner}/{repo}/tags"],listTeams:["GET /repos/{owner}/{repo}/teams"],listWebhookDeliveries:["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"],listWebhooks:["GET /repos/{owner}/{repo}/hooks"],merge:["POST /repos/{owner}/{repo}/merges"],mergeUpstream:["POST /repos/{owner}/{repo}/merge-upstream"],pingWebhook:["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],redeliverWebhookDelivery:["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],removeAppAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],removeCollaborator:["DELETE /repos/{owner}/{repo}/collaborators/{username}"],removeStatusCheckContexts:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],removeStatusCheckProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],removeTeamAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],removeUserAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],renameBranch:["POST /repos/{owner}/{repo}/branches/{branch}/rename"],replaceAllTopics:["PUT /repos/{owner}/{repo}/topics"],requestPagesBuild:["POST /repos/{owner}/{repo}/pages/builds"],setAdminBranchProtection:["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],setAppAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],setStatusCheckContexts:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],setTeamAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],setUserAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],testPushWebhook:["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],transfer:["POST /repos/{owner}/{repo}/transfer"],update:["PATCH /repos/{owner}/{repo}"],updateBranchProtection:["PUT /repos/{owner}/{repo}/branches/{branch}/protection"],updateCommitComment:["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],updateDeploymentBranchPolicy:["PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],updateInformationAboutPagesSite:["PUT /repos/{owner}/{repo}/pages"],updateInvitation:["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"],updateOrgRuleset:["PUT /orgs/{org}/rulesets/{ruleset_id}"],updatePullRequestReviewProtection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],updateRelease:["PATCH /repos/{owner}/{repo}/releases/{release_id}"],updateReleaseAsset:["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"],updateRepoRuleset:["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"],updateStatusCheckPotection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks",{},{renamed:["repos","updateStatusCheckProtection"]}],updateStatusCheckProtection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],updateWebhook:["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],updateWebhookConfigForRepo:["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"],uploadReleaseAsset:["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}",{baseUrl:"https://uploads.github.com"}]},search:{code:["GET /search/code"],commits:["GET /search/commits"],issuesAndPullRequests:["GET /search/issues"],labels:["GET /search/labels"],repos:["GET /search/repositories"],topics:["GET /search/topics"],users:["GET /search/users"]},secretScanning:{createPushProtectionBypass:["POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses"],getAlert:["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],getScanHistory:["GET /repos/{owner}/{repo}/secret-scanning/scan-history"],listAlertsForOrg:["GET /orgs/{org}/secret-scanning/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/secret-scanning/alerts"],listLocationsForAlert:["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"],listOrgPatternConfigs:["GET /orgs/{org}/secret-scanning/pattern-configurations"],updateAlert:["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],updateOrgPatternConfigs:["PATCH /orgs/{org}/secret-scanning/pattern-configurations"]},securityAdvisories:{createFork:["POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks"],createPrivateVulnerabilityReport:["POST /repos/{owner}/{repo}/security-advisories/reports"],createRepositoryAdvisory:["POST /repos/{owner}/{repo}/security-advisories"],createRepositoryAdvisoryCveRequest:["POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve"],getGlobalAdvisory:["GET /advisories/{ghsa_id}"],getRepositoryAdvisory:["GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}"],listGlobalAdvisories:["GET /advisories"],listOrgRepositoryAdvisories:["GET /orgs/{org}/security-advisories"],listRepositoryAdvisories:["GET /repos/{owner}/{repo}/security-advisories"],updateRepositoryAdvisory:["PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}"]},teams:{addOrUpdateMembershipForUserInOrg:["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"],addOrUpdateRepoPermissionsInOrg:["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],checkPermissionsForRepoInOrg:["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],create:["POST /orgs/{org}/teams"],createDiscussionCommentInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],createDiscussionInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions"],deleteDiscussionCommentInOrg:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],deleteDiscussionInOrg:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],deleteInOrg:["DELETE /orgs/{org}/teams/{team_slug}"],getByName:["GET /orgs/{org}/teams/{team_slug}"],getDiscussionCommentInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],getDiscussionInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],getMembershipForUserInOrg:["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"],list:["GET /orgs/{org}/teams"],listChildInOrg:["GET /orgs/{org}/teams/{team_slug}/teams"],listDiscussionCommentsInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],listDiscussionsInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions"],listForAuthenticatedUser:["GET /user/teams"],listMembersInOrg:["GET /orgs/{org}/teams/{team_slug}/members"],listPendingInvitationsInOrg:["GET /orgs/{org}/teams/{team_slug}/invitations"],listReposInOrg:["GET /orgs/{org}/teams/{team_slug}/repos"],removeMembershipForUserInOrg:["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"],removeRepoInOrg:["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],updateDiscussionCommentInOrg:["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],updateDiscussionInOrg:["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],updateInOrg:["PATCH /orgs/{org}/teams/{team_slug}"]},users:{addEmailForAuthenticated:["POST /user/emails",{},{renamed:["users","addEmailForAuthenticatedUser"]}],addEmailForAuthenticatedUser:["POST /user/emails"],addSocialAccountForAuthenticatedUser:["POST /user/social_accounts"],block:["PUT /user/blocks/{username}"],checkBlocked:["GET /user/blocks/{username}"],checkFollowingForUser:["GET /users/{username}/following/{target_user}"],checkPersonIsFollowedByAuthenticated:["GET /user/following/{username}"],createGpgKeyForAuthenticated:["POST /user/gpg_keys",{},{renamed:["users","createGpgKeyForAuthenticatedUser"]}],createGpgKeyForAuthenticatedUser:["POST /user/gpg_keys"],createPublicSshKeyForAuthenticated:["POST /user/keys",{},{renamed:["users","createPublicSshKeyForAuthenticatedUser"]}],createPublicSshKeyForAuthenticatedUser:["POST /user/keys"],createSshSigningKeyForAuthenticatedUser:["POST /user/ssh_signing_keys"],deleteAttestationsBulk:["POST /users/{username}/attestations/delete-request"],deleteAttestationsById:["DELETE /users/{username}/attestations/{attestation_id}"],deleteAttestationsBySubjectDigest:["DELETE /users/{username}/attestations/digest/{subject_digest}"],deleteEmailForAuthenticated:["DELETE /user/emails",{},{renamed:["users","deleteEmailForAuthenticatedUser"]}],deleteEmailForAuthenticatedUser:["DELETE /user/emails"],deleteGpgKeyForAuthenticated:["DELETE /user/gpg_keys/{gpg_key_id}",{},{renamed:["users","deleteGpgKeyForAuthenticatedUser"]}],deleteGpgKeyForAuthenticatedUser:["DELETE /user/gpg_keys/{gpg_key_id}"],deletePublicSshKeyForAuthenticated:["DELETE /user/keys/{key_id}",{},{renamed:["users","deletePublicSshKeyForAuthenticatedUser"]}],deletePublicSshKeyForAuthenticatedUser:["DELETE /user/keys/{key_id}"],deleteSocialAccountForAuthenticatedUser:["DELETE /user/social_accounts"],deleteSshSigningKeyForAuthenticatedUser:["DELETE /user/ssh_signing_keys/{ssh_signing_key_id}"],follow:["PUT /user/following/{username}"],getAuthenticated:["GET /user"],getById:["GET /user/{account_id}"],getByUsername:["GET /users/{username}"],getContextForUser:["GET /users/{username}/hovercard"],getGpgKeyForAuthenticated:["GET /user/gpg_keys/{gpg_key_id}",{},{renamed:["users","getGpgKeyForAuthenticatedUser"]}],getGpgKeyForAuthenticatedUser:["GET /user/gpg_keys/{gpg_key_id}"],getPublicSshKeyForAuthenticated:["GET /user/keys/{key_id}",{},{renamed:["users","getPublicSshKeyForAuthenticatedUser"]}],getPublicSshKeyForAuthenticatedUser:["GET /user/keys/{key_id}"],getSshSigningKeyForAuthenticatedUser:["GET /user/ssh_signing_keys/{ssh_signing_key_id}"],list:["GET /users"],listAttestations:["GET /users/{username}/attestations/{subject_digest}"],listAttestationsBulk:["POST /users/{username}/attestations/bulk-list{?per_page,before,after}"],listBlockedByAuthenticated:["GET /user/blocks",{},{renamed:["users","listBlockedByAuthenticatedUser"]}],listBlockedByAuthenticatedUser:["GET /user/blocks"],listEmailsForAuthenticated:["GET /user/emails",{},{renamed:["users","listEmailsForAuthenticatedUser"]}],listEmailsForAuthenticatedUser:["GET /user/emails"],listFollowedByAuthenticated:["GET /user/following",{},{renamed:["users","listFollowedByAuthenticatedUser"]}],listFollowedByAuthenticatedUser:["GET /user/following"],listFollowersForAuthenticatedUser:["GET /user/followers"],listFollowersForUser:["GET /users/{username}/followers"],listFollowingForUser:["GET /users/{username}/following"],listGpgKeysForAuthenticated:["GET /user/gpg_keys",{},{renamed:["users","listGpgKeysForAuthenticatedUser"]}],listGpgKeysForAuthenticatedUser:["GET /user/gpg_keys"],listGpgKeysForUser:["GET /users/{username}/gpg_keys"],listPublicEmailsForAuthenticated:["GET /user/public_emails",{},{renamed:["users","listPublicEmailsForAuthenticatedUser"]}],listPublicEmailsForAuthenticatedUser:["GET /user/public_emails"],listPublicKeysForUser:["GET /users/{username}/keys"],listPublicSshKeysForAuthenticated:["GET /user/keys",{},{renamed:["users","listPublicSshKeysForAuthenticatedUser"]}],listPublicSshKeysForAuthenticatedUser:["GET /user/keys"],listSocialAccountsForAuthenticatedUser:["GET /user/social_accounts"],listSocialAccountsForUser:["GET /users/{username}/social_accounts"],listSshSigningKeysForAuthenticatedUser:["GET /user/ssh_signing_keys"],listSshSigningKeysForUser:["GET /users/{username}/ssh_signing_keys"],setPrimaryEmailVisibilityForAuthenticated:["PATCH /user/email/visibility",{},{renamed:["users","setPrimaryEmailVisibilityForAuthenticatedUser"]}],setPrimaryEmailVisibilityForAuthenticatedUser:["PATCH /user/email/visibility"],unblock:["DELETE /user/blocks/{username}"],unfollow:["DELETE /user/following/{username}"],updateAuthenticated:["PATCH /user"]}},np=BR;var Tr=new Map;for(let[e,r]of Object.entries(np))for(let[t,n]of Object.entries(r)){let[o,s,i]=n,[a,l]=o.split(/ /),d=Object.assign({method:a,url:l},s);Tr.has(e)||Tr.set(e,new Map),Tr.get(e).set(t,{scope:e,methodName:t,endpointDefaults:d,decorations:i})}var HR={has({scope:e},r){return Tr.get(e).has(r)},getOwnPropertyDescriptor(e,r){return{value:this.get(e,r),configurable:!0,writable:!0,enumerable:!0}},defineProperty(e,r,t){return Object.defineProperty(e.cache,r,t),!0},deleteProperty(e,r){return delete e.cache[r],!0},ownKeys({scope:e}){return[...Tr.get(e).keys()]},set(e,r,t){return e.cache[r]=t},get({octokit:e,scope:r,cache:t},n){if(t[n])return t[n];let o=Tr.get(r).get(n);if(!o)return;let{endpointDefaults:s,decorations:i}=o;return i?t[n]=qR(e,r,n,s,i):t[n]=e.request.defaults(s),t[n]}};function Ji(e){let r={};for(let t of Tr.keys())r[t]=new Proxy({octokit:e,scope:t,cache:{}},HR);return r}function qR(e,r,t,n,o){let s=e.request.defaults(n);function i(...a){let l=s.endpoint.merge(...a);if(o.mapToData)return l=Object.assign({},l,{data:l[o.mapToData],[o.mapToData]:void 0}),s(l);if(o.renamed){let[d,c]=o.renamed;e.log.warn(`octokit.${r}.${t}() has been renamed to octokit.${d}.${c}()`)}if(o.deprecated&&e.log.warn(o.deprecated),o.renamedParameters){let d=s.endpoint.merge(...a);for(let[c,u]of Object.entries(o.renamedParameters))c in d&&(e.log.warn(`"${c}" parameter is deprecated for "octokit.${r}.${t}()". Use "${u}" instead`),u in d||(d[u]=d[c]),delete d[c]);return s(d)}return s(...a)}return Object.assign(i,s)}function VR(e){return{rest:Ji(e)}}VR.VERSION=Ki;function zi(e){let r=Ji(e);return{...r,rest:r}}zi.VERSION=Ki;var op="22.0.1";var sp=_o.plugin(Hi,zi,Vi).defaults({userAgent:`octokit-rest.js/${op}`});var KR=sp.plugin(Oi,fo);function ip(){let e=new Map;return{get:r=>e.get(r),set:(r,t)=>e.set(r,t)}}var Qt=class extends Error{status=401;constructor(r){super("GitHub rejected the host credential; refresh the stored login with `gh auth login` or provide a current host token",r),this.name="GithubCredentialError"}};function Qi(e){let r=e.etags??ip(),t=new KR({auth:e.token,log:{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},...e.baseUrl?{baseUrl:e.baseUrl}:{},...e.fetchImpl?{request:{fetch:e.fetchImpl}}:{},retry:{doNotRetry:[304,403,429],...e.retryCount===void 0?{}:{retries:e.retryCount}},throttle:e.throttle===!1?{enabled:!1}:{onRateLimit:()=>!1,onSecondaryRateLimit:()=>!1}}),n=async o=>{let s=r.get(o.cacheKey),i={...o.parameters??{}},a=zt(i.headers)?i.headers:{};i.headers={...a,...s?{"if-none-match":s.etag}:{}};try{let l=await t.request(o.route,i),d=l.headers,c=wo(d,"etag");return c!==void 0&&r.set(o.cacheKey,{etag:c,data:l.data,headers:d}),await e.attribution?.record({operation:o.operation,cost:1}),{data:l.data,headers:d}}catch(l){if(Ro(l)===304){if(s===void 0)throw new Error(`GitHub returned 304 for ${JSON.stringify(o.cacheKey)} without a held answer to reuse`,{cause:l});let d=ap(l),c={...s.headers,...d},u=wo(c,"etag")??s.etag;return r.set(o.cacheKey,{etag:u,data:s.data,headers:c}),await e.attribution?.record({operation:o.operation,cost:0}),{data:s.data,headers:c}}throw Ro(l)===401?new Qt({cause:l}):l}};return{conditionalRest:n,async conditionalPaginate(o){let s=[],i={},a=0,l=1;for(;;){let d=await n({...o,cacheKey:`${o.cacheKey}:page:${l}`,parameters:{...o.parameters??{},per_page:100,page:l}});if(a+=1,!Array.isArray(d.data))throw new Error(`GitHub returned a non-list body for ${JSON.stringify(o.cacheKey)} page ${l}`);if(s.push(...d.data),i=d.headers,!JR(d.headers))break;l+=1}return{data:s,headers:i,requestCount:a}},async graphql(o,s={}){try{return await t.graphql(o,s)}catch(i){throw Ro(i)===401?new Qt({cause:i}):i}}}}function JR(e){let r=wo(e,"link");return r!==void 0&&/(?:^|,)\s*<[^>]+>;\s*rel="next"(?:\s*;|\s*(?:,|$))/i.test(r)}function Yt(e){let r=Ro(e),t=ap(e);return r===429||r===403&&wo(t,"x-ratelimit-remaining")==="0"||e instanceof Error&&/secondary rate|rate limit/i.test(e.message)}function Ro(e){if(zt(e))return typeof e.status=="number"?e.status:void 0}function ap(e){return!zt(e)||!zt(e.response)||!zt(e.response.headers)?{}:e.response.headers}function wo(e,r){let t=e[r]??e[r.toLowerCase()];return typeof t=="string"?t:typeof t=="number"?String(t):void 0}function zt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var dp="rate_limit",cp={rest:"core",graphql:"graphql",search:"search"},ze=["rest","graphql","search"];function To(e,r){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:[...ze],detail:r??"no balance has been asked for yet, so none is known"}}var Xi=15e3,tt=.15,vo=[{at_or_below_fraction:0,every_ms:Xi,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:tt,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"}],Yi=2;function up(e,r){let t=lp(e),n=lp(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let a of ze){let l=cp[a],d=n[l],c=YR(a,l,d);o[a]=c,c==null&&s.push(a)}let i=ze.length-s.length;return{version:1,origin:"asked",outcome:i>0?"asked":"unanswered",source:"GET /rate_limit",asked_at:r.askedAt,request_count:1,pools:o,unreported_pools:s,detail:i>0?`the token's own answer for ${i} of ${ze.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function Zi(e){try{let r=await e.transport();return up(r,{askedAt:e.now})}catch(r){let t=r instanceof Error?r.message:String(r);return{...To(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function ea(e){let r=null;for(let t of ze){let n=e.pools[t];n!=null&&(r==null||n.fraction<r.fraction)&&(r=n)}return r}function xo(e,r){let t=ea(e);if(t==null)return So(tt).every_ms;let n=So(t.fraction);if(t.remaining>0)return n.every_ms;let o=mp(r.now,t.reset_at);return o==null?n.every_ms:Math.max(Xi,Math.min(n.every_ms,o))}function ra(e,r=tt){return Math.ceil(e.limit*r)}function pp(e,r,t=tt){let n=e.pools[r];return n==null?"unknown":n.remaining<=0?"spent":n.remaining<ra(n,t)?"reserved":"open"}function ta(e){let r=e.reservedFraction??tt,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:So(r).every_ms*Yi,stale:!1,posture:"unknown",reserved_fraction:r,next_poll_ms:So(r).every_ms,pools:[],unreported_pools:[...ze],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let n=xo(t,{now:e.now}),o=e.stalenessMs??n*Yi,s=mp(t.asked_at,e.now),i=t.outcome==="asked"&&(s==null||s>o),a=ze.map(c=>t.pools[c]).filter(c=>c!=null),l=QR(t,r),d=ea(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:r,next_poll_ms:n,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`:zR(l,d,t,r)}}function na(e){if(!sa(e))return!1;let r=e;return r.version===1&&r.origin==="asked"&&(r.outcome==="asked"||r.outcome==="unanswered")&&(r.asked_at===null||typeof r.asked_at=="string")&&(r.age_ms===null||typeof r.age_ms=="number")&&typeof r.threshold_ms=="number"&&typeof r.stale=="boolean"&&typeof r.posture=="string"&&typeof r.reserved_fraction=="number"&&typeof r.next_poll_ms=="number"&&Array.isArray(r.pools)&&Array.isArray(r.unreported_pools)&&typeof r.reason=="string"}function zR(e,r,t,n){if(r==null)return t.detail;let o=ra(r,n);switch(e){case"spent":return`the ${r.pool} pool is spent and resets at ${r.reset_at}: work is not queued, it is refused`;case"reserved":return`the ${r.pool} pool has ${r.remaining} of ${r.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 ${r.pool} pool is the tightest at ${r.remaining} of ${r.limit}, above the reserved band of ${o}`}}function QR(e,r){let t="unknown";for(let n of ze){if(e.pools[n]==null)continue;let o=pp(e,n,r);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function So(e){for(let r of vo)if(e<=r.at_or_below_fraction)return r;return vo[vo.length-1]}function YR(e,r,t){if(!sa(t))return null;let n=Eo(t.limit),o=Eo(t.remaining),s=Eo(t.used),i=Eo(t.reset);return n==null||n<=0||o==null?null:{pool:e,resource:r,limit:n,remaining:o,used:s??0,reset_at:i==null?"":new Date(i*1e3).toISOString(),fraction:o/n}}function oa(e){let r=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let n=await t(`${r}/${dp}`,{method:"GET",headers:{authorization:`bearer ${e.token}`,accept:"application/vnd.github+json"}});if(!n.ok)throw new Error(`the balance ask was refused with HTTP ${n.status}`);return await n.json()}}function mp(e,r){let t=Date.parse(e),n=Date.parse(r);return!Number.isFinite(t)||!Number.isFinite(n)?null:Math.max(0,n-t)}function Eo(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function lp(e){return sa(e)?e:{}}function sa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bp(e){return{generated_at:e.now,hour:gp("hour",36e5,e),day:gp("day",864e5,e)}}function Zt(e,r,t){let n=Xt(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(a=>{let l=Xt(r(a));return l==null?!1:n==null||n-l<=o});return i.length<=s?i:i.slice(i.length-s)}function gp(e,r,t){let n=Xt(t.now),o=n==null?null:n-r,s=e==="hour"?"1h":"24h",i=t.observations.map(u=>({observation:u,at:Xt(u.observed_at)})).filter(u=>u.at!=null&&yp(u.at,o,n)).sort((u,m)=>u.at-m.at),a=t.outcomes.map(u=>Xt(u.ts)).filter(u=>u!=null&&yp(u,o,n)),l=fp(i,u=>u.tokens,"tokens",s),d=fp(i,u=>u.tools,"tools",s),c=[];return i.length===0?c.push("worker-vitals"):(l.samples===0&&c.push("worker-vitals.tokens"),d.samples===0&&c.push("worker-vitals.tools")),a.length===0&&c.push("worker-outcomes"),{window:e,window_ms:r,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:l,tools_per_min:d,issues_per_hour:XR(a.length,r,s),runner_share:hp("runner",i,u=>u.runner,s),model_share:hp("model",i,u=>u.model,s),unavailable:c}}function fp(e,r,t,n){let o=new Map,s=0;for(let d of e){let c=r(d.observation);if(c==null||!Number.isFinite(c))continue;s+=1;let u=o.get(d.observation.worker_id)??[];u.push({at:d.at,count:c}),o.set(d.observation.worker_id,u)}if(s===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${n}`,samples:0};let i=0,a=null,l=null;for(let d of o.values()){if(d.length<2)continue;for(let m=1;m<d.length;m++){let h=d[m-1],f=d[m];h==null||f==null||(i+=Math.max(0,f.count-h.count))}let c=d[0],u=d[d.length-1];c!=null&&(a=a==null?c.at:Math.min(a,c.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 ${n} 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 XR(e,r,t){return e===0?{value:null,absent_reason:`no Worker outcome was recorded in the last ${t}`,samples:0}:{value:e/(r/36e5),absent_reason:null,samples:e}}function hp(e,r,t,n){let o=new Map;for(let d of r){let c=t(d.observation);c!=null?o.set(d.observation.worker_id,c):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,c])=>({key:d,worker_count:c,share:c/i})).sort((d,c)=>c.worker_count-d.worker_count||d.key.localeCompare(c.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 ${n}`:`no Worker published a ${e} in the last ${n}`}}function yp(e,r,t){return r==null||t==null?!0:e>=r&&e<=t}function Xt(e){let r=Date.parse(e);return Number.isFinite(r)?r:null}function _p(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.generated_at=="string"&&kp(r.hour)&&kp(r.day)}function kp(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.window=="string"&&typeof r.window_ms=="number"&&ia(r.tokens_per_min)&&ia(r.tools_per_min)&&ia(r.issues_per_hour)&&Array.isArray(r.unavailable)}function ia(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return(r.value===null||typeof r.value=="number")&&(r.absent_reason===null||typeof r.absent_reason=="string")&&Number.isInteger(r.samples)}import{execFileSync as ZR}from"node:child_process";import{existsSync as ew,readFileSync as Po,readdirSync as rw}from"node:fs";import{dirname as tw,join as xr}from"node:path";function en(e){let r=Bt(e),t=[["MemoryMax",r.memory_max],["MemoryHigh",r.memory_high]];for(let[n,o]of t){if(o==null)continue;let s=Zr(o);return s==null?null:{name:n,declared:o,bytes:s}}return null}function Rp(e){let r=[],t=[];for(let n of e.workers){let o=en(n);if(o==null){t.push({worker_id:n.worker_id,reason:(Bt(n).memory_max??Bt(n).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[n.worker_id];if(typeof s!="number"||!Number.isFinite(s)){t.push({worker_id:n.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?.[n.worker_id]==="cgroup"&&o.name==="MemoryMax"){t.push({worker_id:n.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}r.push(nw(n,o,s))}}return{terminations:r,unenforceable:t}}function nw(e,r,t){let n=`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:r.name,budget_declared:r.declared,budget_bytes:r.bytes,observed_rss_bytes:t,workspace_path:e.workspace_path,reason:`redskilled terminated ${n}: its tree RSS of ${t} bytes exceeded its ${r.name} budget of ${r.declared} (${r.bytes} bytes). This is a budget termination, not a stall, and the work in ${JSON.stringify(e.workspace_path)} is handed forward.`}}var ow=4096;function wp(e,r={}){let t=r.platform??process.platform,n={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return n;let o={},s={},i={},a=iw(e,t,r);for(let[u,m]of a){let h=dw(m);h!=null&&(o[u]=h.memoryBytes,h.cpuSeconds!=null&&(s[u]=h.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=pw(t,r);if(d.size===0)return{rss:o,cpu_seconds:s,sources:i};let c=new Map;for(let u of d.values()){let m=c.get(u.ppid);m?m.push(u.pid):c.set(u.ppid,[u.pid])}for(let u of l){if(!d.has(u.pid))continue;let m=0,h=0,f=[u.pid],S=new Set;for(;f.length>0;){let _=f.pop();if(S.has(_))continue;S.add(_);let v=d.get(_);if(v){m+=v.rssBytes,h+=v.cpuSeconds;for(let C of c.get(_)??[])f.push(C)}}o[u.worker_id]=m,s[u.worker_id]=h,i[u.worker_id]="process-tree"}return{rss:o,cpu_seconds:s,sources:i}}var sw="/sys/fs/cgroup";function iw(e,r,t){let n=new Map;if(!(t.cgroupRoot!=null)&&r!=="linux")return n;let s=t.cgroupRoot??sw,i=e.filter(l=>l.unit!=null&&l.unit!=="");if(i.length===0)return n;let a=aw(s,t);for(let l of i)for(let d of a){let c=xr(d,l.unit);if(ew(xr(c,"memory.current"))){n.set(l.worker_id,c);break}}return n}function aw(e,r){let t=r.selfCgroupPath??lw(),n=[],o=a=>{n.includes(a)||n.push(a)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(xr(e,s));let a=tw(s);if(a===s)break;s=a}o(e);let i=r.uid??process.getuid?.();return i!=null&&o(xr(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),n}function lw(){try{for(let e of Po("/proc/self/cgroup","utf8").split(`
|
|
85
|
-
`)
|
|
86
|
-
`)){let[t,n]=r.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(n);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function pw(e,r){return r.procRoot!=null||e==="linux"?kw(r.procRoot??"/proc"):r.psTable!=null||e==="darwin"?hw(mw(r.psTable)):new Map}function mw(e){try{return(e??gw)()}catch{return""}}function gw(){return ZR("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var fw=1024;function hw(e){let r=new Map;for(let t of e.split(`
|
|
87
|
-
`))
|
|
88
|
-
`),aliases:s,closed_since:o}}function vw(e,r,t){let n=nt(r),o=nt(n.data),s=Array.isArray(n.errors)?n.errors.map(nt):[],i=Aw(o.rateLimit,s),a=e.aliases.map(({alias:l,search_alias:d,project:c})=>{let u=c.owner+"/"+c.name,m=o[l],h=s.find(f=>Tp(f.path,l)||Tp(f.path,d));if(rn(m)){let f=xp(m.open_pull_requests),S=xp(m.open_issues),_=Dw(o[d]);if(f!=null&&S!=null&&_!=null)return{project_label:c.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:f,open_issues:S,recently_closed:_},detail:`counted ${u} for project ${JSON.stringify(c.project_label)}`}}return i.exhausted||Ip(h)?{project_label:c.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:c.project_label,repository:u,outcome:"unreachable",counts:null,detail:`${u} is not reachable with the host token: ${Oo(h?.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 Sw(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 Op(e){if(e.projects.length===0)return Sw(e.now);if(da(e.projects,e.hostTokenRef),e.transport.conditionalList)return await xw(e);let r=Pp(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(r.query);return vw(r,t,{fetchedAt:e.now})}catch(t){let n=t instanceof Error?t.message:String(t),o=/rate limit|secondary rate|429/i.test(n);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: ${n}`}))}}}var Tw={key:"redskilled repository activity poll",budget:"rest"};async function xw(e){Lp(e.projects);let r=Date.parse(e.now),t=Number.isFinite(r)?new Date(Math.floor(r/(60*60*1e3))*60*60*1e3).toISOString():e.now,n=Pp(e.projects,{now:t,closedWindowMs:e.closedWindowMs}),o=e.transport.conditionalList,s=[],i=0,a={remaining:null,reset_at:null,exhausted:!1,point_cost:null};for(let l of e.projects){let d=`${l.owner}/${l.name}`,c=[["open-prs","GET /repos/{owner}/{repo}/pulls",{owner:l.owner,repo:l.name,state:"open"}],["open-issues","GET /repos/{owner}/{repo}/issues",{owner:l.owner,repo:l.name,state:"open"}],["recently-closed","GET /repos/{owner}/{repo}/issues",{owner:l.owner,repo:l.name,state:"closed",since:n.closed_since}]],u=[];try{for(let[m,h,f]of c){let S=await o({cacheKey:`activity:${d}:${m}:${JSON.stringify(f)}`,route:h,parameters:f,operation:Tw});i+=S.requestCount;let _=m==="open-prs"?S.data:S.data.filter(v=>!rn(v.pull_request));u.push(m==="recently-closed"?_.filter(v=>Oo(v.closed_at)>=n.closed_since).length:_.length),a=vp(a,Ow(S.headers))}s.push({project_label:l.project_label,repository:d,outcome:"counted",counts:{open_pull_requests:u[0],open_issues:u[1],recently_closed:u[2]},detail:`counted ${d} for project ${JSON.stringify(l.project_label)}`})}catch(m){let h=Yt(m);a=vp(a,{remaining:null,reset_at:null,exhausted:h,point_cost:null}),s.push({project_label:l.project_label,repository:d,outcome:h?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${d} answered: ${m instanceof Error?m.message:String(m)}`})}}return{version:1,fetched_at:e.now,request_count:i,project_count:s.length,rate_limit:a,projects:s}}function Ap(e){let r=e.stalenessMs??ww,t=e.activity;if(t==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:r,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 n=Date.parse(e.now),o=Date.parse(t.fetched_at),s=Number.isFinite(n)&&Number.isFinite(o)?Math.max(0,n-o):null,i=s==null||s>r;return{version:1,fetched_at:t.fetched_at,age_ms:s,threshold_ms:r,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 ${r}ms window`:`fetched ${s}ms ago, within the ${r}ms window`}}function Dp(e){if(!rn(e))return!1;let r=e;return r.version===1&&(r.fetched_at===null||typeof r.fetched_at=="string")&&(r.age_ms===null||typeof r.age_ms=="number")&&typeof r.threshold_ms=="number"&&typeof r.stale=="boolean"&&Number.isInteger(r.request_count)&&rn(r.rate_limit)&&Array.isArray(r.projects)&&typeof r.reason=="string"}function jp(e){let r=e.endpoint==null?void 0:Pw(e.endpoint),t=Qi({token:e.token,...r?{baseUrl:r}:{},...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},...e.attribution?{attribution:e.attribution}:{},...e.retryCount===void 0?{}:{retryCount:e.retryCount},...e.throttle===void 0?{}:{throttle:e.throttle}}),n=async o=>await t.graphql(o);return n.conditionalList=async o=>await t.conditionalPaginate({cacheKey:o.cacheKey,route:o.route,parameters:o.parameters,operation:o.operation}),n}function Pw(e){let r=new URL(e);return/\/api\/graphql\/?$/.test(r.pathname)?r.pathname=r.pathname.replace(/\/api\/graphql\/?$/,"/api/v3"):r.pathname=r.pathname.replace(/\/graphql\/?$/,""),r.search="",r.hash="",r.toString().replace(/\/$/,"")}function Ow(e){let r=Sp(e,"x-ratelimit-remaining"),t=Sp(e,"x-ratelimit-reset");return{remaining:r,reset_at:t==null?null:new Date(t*1e3).toISOString(),exhausted:r===0,point_cost:null}}function vp(e,r){return{remaining:r.remaining==null?e.remaining:e.remaining==null?r.remaining:Math.min(e.remaining,r.remaining),reset_at:r.reset_at??e.reset_at,exhausted:e.exhausted||r.exhausted,point_cost:null}}function Sp(e,r){let t=e[r];if(typeof t!="string"&&typeof t!="number")return null;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:null}function Lp(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>Ep)throw new Error(`redskilled activity fetch spans at most ${Ep} repositories in one query`);let r=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(r.has(t.project_label))throw new Error(`redskilled holds one repository per project, and ${JSON.stringify(t.project_label)} is registered twice`);r.add(t.project_label)}}function Aw(e,r){let t=nt(e),n=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=r.some(Ip),i=typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:null;return{remaining:n,reset_at:o,exhausted:s||n===0,point_cost:i}}function Ip(e){if(e==null)return!1;let r=Oo(e.type),t=Oo(e.message);return r==="RATE_LIMITED"||/rate limit/i.test(t)}function Tp(e,r){return Array.isArray(e)&&e.includes(r)}function xp(e){let r=nt(e);return Number.isInteger(r.totalCount)?r.totalCount:null}function Dw(e){let r=nt(e);return Number.isInteger(r.issueCount)?r.issueCount:null}function nt(e){return rn(e)?e:{}}function rn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Oo(e){return typeof e=="string"?e:""}var jw=3e4,Lw=2,Iw=3,$w=4,Gw=["logs","vitals","display"];function $p(e,r){if(r===void 0)return e;let t=Gw.filter(o=>r[o]!==!0);if(t.length===0)return e;let n=o=>r[o]===!0;return{...e,workers:e.workers.map(o=>({...o,...n("vitals")?{}:{vitals:Cw,budget:{...o.budget,used_bytes:null,used_fraction:null}},...n("logs")?{}:{log:Nw},...n("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var Cw={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},Nw={last_line:null,published_at:null,source:null};function Gp(e){let r=e.stalenessMs??jw,t=ir(e.now),n=e.sampledAt==null?null:ir(e.sampledAt),o=t==null||n==null?null:Math.max(0,t-n),s=o!=null&&o<=r,i=new Set(e.reattachedWorkerIds??[]),a=e.hostState.workers.map(m=>Uw(m,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[m.worker_id],display:e.displays?.[m.worker_id],state:i.has(m.worker_id)?"reattached":"running"})),l=a.filter(m=>m.vitals.rss_bytes==null).map(m=>m.worker_id).sort(),d=a.length-l.length,c=a.reduce((m,h)=>m+(h.vitals.rss_bytes??0),0),u=lo(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:Vw({sampledAt:e.sampledAt,ageMs:o,threshold:r,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:c,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:qw(a),known_projects:Hw(e.hostState),registered_projects:(e.hostState.registrations??[]).map(m=>m.project_label).sort((m,h)=>m.localeCompare(h)),lapsed_projects:(e.hostState.lapsed_registrations??[]).map(m=>({project_label:m.project_label,at:m.at,...m.registered_at==null?{}:{registered_at:m.registered_at},reason:m.detail})),stopped_projects:(e.hostState.stopped_registrations??[]).map(m=>({project_label:m.project_label,at:m.at})),orphaned_projects:(e.hostState.orphaned_registrations??[]).map(m=>m.project_label),workers:a,github_balance:ta({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:Ap({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:Mw(e.deaths,e.recentDeathLimit??$w)},engine:Ww(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function Mw(e,r){let t=[...e].sort((s,i)=>(ir(i.ts)??0)-(ir(s.ts)??0)),n=t.slice(0,Math.max(0,Math.floor(r))).map(s=>({kind:s.kind,id:s.id,pid:s.pid,ts:s.ts,last_seen:s.last_seen,last_phase:s.last_phase,sender_class:s.sender_class,confidence:s.confidence,signal:s.signal,evidence:s.evidence[0]??null})),o=Fw(t);return{count:t.length,recent:n,latest:n[0]??null,reaped_at:n[0]?.ts??null,...o==null?{}:{boot_loop:o}}}function Fw(e){let r=new Map;for(let n of e){if(n.sender_class!=="boot-refused"||n.uptime_s==null||n.uptime_s>Lw||n.project_label==null||n.project_label===""||ir(n.ts)==null)continue;let o=r.get(n.project_label)??[];o.push(n),r.set(n.project_label,o)}return[...r.entries()].filter(([,n])=>n.length>=Iw).map(([n,o])=>{let s=o[0],i=ir(s.ts),a=Math.min(...o.map(d=>ir(d.ts))),l=s.detail?.trim()||s.evidence[0]?.trim();return l==null||l===""?null:{project_label:n,count:o.length,span_ms:Math.max(0,i-a),latest_refusal:l}}).filter(n=>n!=null).sort((n,o)=>o.count-n.count||o.span_ms-n.span_ms)[0]??null}function Ww(e){let r=e.upgrade,t=r?.running_version??e.daemon_version,n=r?.published_version??null,o=r?.newest_published_version??null,s=(r?.newer_published??0)>0,i=(r?.major_held??0)>0;return{running_version:t,published_version:n,newer_published:s,major_held:i,current:n==null&&o==null?null:!s&&!i}}function Uw(e,r){let t=r.rss[e.worker_id],n=typeof t=="number"&&Number.isFinite(t)?t:null,o=en(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=ir(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:r.nowMs==null||i==null?null:Math.max(0,r.nowMs-i),state:r.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:n,sampled_at:n==null?null:r.sampledAt,age_ms:n==null?null:r.ageMs,fresh:n!=null&&r.sampleFresh,rss_source:n==null?null:e.rss_source??null},budget:{name:o?.name??null,declared:o?.declared??s,bytes:o?.bytes??null,used_bytes:n,used_fraction:o==null||o.bytes<=0||n==null?null:n/o.bytes,enforceable:o!=null},log:Bw(r.log),display:r.display?.display??null,display_published_at:r.display?.published_at??null}}function Bw(e){let r={last_line:null,published_at:null,source:null};return e==null||e.line.trim()===""?r:{last_line:e.line,published_at:e.published_at,source:e.source}}function Hw(e){let r=new Set;for(let t of e.registrations??[])r.add(t.project_label);for(let t of e.projects)r.add(t.project_label);for(let t of e.lapsed_registrations??[])r.add(t.project_label);for(let t of e.stopped_registrations??[])r.add(t.project_label);for(let t of e.orphaned_registrations??[])r.add(t.project_label);return[...r].sort((t,n)=>t.localeCompare(n))}function qw(e){let r=new Map;for(let t of e){let n=r.get(t.project_label)??{workers:0,declared:0,observed:0,measured:0};n.workers+=1,n.declared+=t.budget.bytes??0,n.observed+=t.vitals.rss_bytes??0,n.measured+=t.vitals.rss_bytes==null?0:1,r.set(t.project_label,n)}return[...r.entries()].map(([t,n])=>({project_label:t,worker_count:n.workers,declared_memory_bytes:n.declared,observed_rss_bytes:n.observed,measured_worker_count:n.measured})).sort((t,n)=>t.project_label.localeCompare(n.project_label))}function Vw(e){let r={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?{...r,stale:!1,reason:"the host holds no Workers, so there is nothing to measure and nothing to age"}:e.sampledAt==null||e.ageMs==null?{...r,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?{...r,stale:!0,reason:`this answer is stale: its measurement is ${e.ageMs}ms old, past the ${e.threshold}ms staleness window`}:{...r,stale:!1,reason:`measured ${e.ageMs}ms ago, within the ${e.threshold}ms staleness window`}}function ir(e){let r=Date.parse(e);return Number.isFinite(r)?r:null}function ca(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e,t=r.daemon,n=r.staleness,o=r.host;return r.version===1&&typeof r.generated_at=="string"&&t!=null&&typeof t=="object"&&Number.isInteger(t.pid)&&typeof t.daemon_version=="string"&&typeof t.protocol_version=="number"&&n!=null&&typeof n=="object"&&typeof n.stale=="boolean"&&typeof n.threshold_ms=="number"&&Array.isArray(n.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(r.projects)&&Array.isArray(r.workers)&&(r.known_projects===void 0||Array.isArray(r.known_projects)&&r.known_projects.every(s=>typeof s=="string"))&&(r.registered_projects===void 0||Array.isArray(r.registered_projects)&&r.registered_projects.every(s=>typeof s=="string"))&&(r.lapsed_projects===void 0||Array.isArray(r.lapsed_projects)&&r.lapsed_projects.every(Kw))&&(r.stopped_projects===void 0||Array.isArray(r.stopped_projects)&&r.stopped_projects.every(Jw))&&(r.orphaned_projects===void 0||Array.isArray(r.orphaned_projects)&&r.orphaned_projects.every(s=>typeof s=="string"))&&(r.repository_activity===void 0||Dp(r.repository_activity))&&(r.github_balance===void 0||na(r.github_balance))&&(r.deaths===void 0||zw(r.deaths))&&(r.engine===void 0||Qw(r.engine))&&(r.metrics===void 0||_p(r.metrics))}function Kw(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.project_label=="string"&&typeof r.at=="string"&&(r.registered_at===void 0||typeof r.registered_at=="string")&&typeof r.reason=="string"}function Jw(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.project_label=="string"&&typeof r.at=="string"}function zw(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return Number.isInteger(r.count)&&Array.isArray(r.recent)}function Qw(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.running_version=="string"&&(r.published_version===null||typeof r.published_version=="string")}var Cp={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,wait_kind:null,wait_subject:null,wait_pid:null,wait_started_at:null,wait_deadline:null,wait_escalation:null,started_at:null,context:null,eta:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null};function Np(e,r){let t=e.display?.started_at;if(t!=null&&t!==""){let n=Date.parse(t),o=Date.parse(r);if(Number.isFinite(n)&&Number.isFinite(o))return Math.max(0,o-n)}return e.uptime_ms}var se=e=>`\x1B[${e}m`,tn=se("48;2;114;47;55"),ua=se("48;2;88;36;42"),ar=se("38;2;255;255;255"),pa=se("38;2;201;150;158"),nn=se("38;2;255;214;214"),on=se("39"),fe=se("38;2;224;138;148"),ma=se("38;2;240;200;120"),ga=se("38;2;240;110;120"),fa=se("38;2;255;214;214"),ha=se("38;2;146;84;94"),ya=se("38;2;255;95;95"),Me=se("49"),Pe=se("0"),Ao=se("1"),Do=se("22");var Yw=/\x1b\[[0-9;]*m/g,Xw=/(\x1b\[[0-9;]*m)/,Zw=/^\x1b\[[0-9;]*m$/;function Mp(e){return e.replace(Yw,"")}function eE(e){return e.slice(2,-1).split(";").every(t=>t===""||Number(t)===0)}function Re(e){return[...Mp(e)].length}function me(e,r){if(r<=0)return"";if(Re(e)<=r)return e;if(r===1)return"\u2026";let t=r-1,n=0,o=!1,s="";for(let i of e.split(Xw))if(i!==""){if(Zw.test(i)){s+=i,o=!eE(i);continue}for(let a of i){if(n===t)return`${s}\u2026${o?Pe:""}`;s+=a,n+=1}}return`${s}\u2026${o?Pe:""}`}function sn(e,r){return e+" ".repeat(Math.max(0,r-Re(e)))}function ka(e){let r=e.toLowerCase();for(let t of["opus","sonnet","haiku","fable"]){let n=r.indexOf(t);if(n===-1)continue;let s=r.slice(n+t.length).match(/^-(\d+(?:[-.]\d+)*)/)?.[1]?.split(/[-.]/)??[];return/^\d{8}$/.test(s.at(-1)??"")&&s.pop(),s.length===0?t:`${t}-${s.join(".")}`}return e}function Oe(e){if(!Number.isFinite(e)||e<=0)return"0B";let r=["B","K","M","G","T"],t=e,n=0;for(;t>=1024&&n<r.length-1;)t/=1024,n+=1;return`${t>=100||n===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${r[n]}`}function an(e){if(!Number.isFinite(e)||e<=0)return"0";let r=(t,n)=>{let o=(Math.round(t*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${n}`};return e>=1e9?r(e/1e9,"B"):e>=1e6?r(e/1e6,"M"):e>=1e3?r(e/1e3,"k"):String(Math.round(e))}function ln(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return an(e);if(e<=0)return"0";let r=(Math.round(e*10)/10).toFixed(1);return r.endsWith(".0")?r.slice(0,-2):r}function lr(e){if(e==null||!Number.isFinite(e)||e<0)return"\u2014";let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let t=Math.floor(r/60);if(t<60)return`${t}m${r%60}s`;let n=Math.floor(t/60);return n<24?`${n}h${t%60}m`:`${Math.floor(n/24)}d${n%24}h`}function ot(e){if(e==null)return null;let r=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return r===""?null:r}var dn="!unregistered",ba="!lapsed",cn="\u21E1",Qe="\u2020",st="\u25D0",it="\u25EF",_a="\u21B3",Ra="redskilled unreachable \u2014 Worker state unknown";function at(e,r){return r.mode==="global"?e.workers:r.project==null?[]:e.workers.filter(t=>t.project_label===r.project)}function jo(e,r){return r.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===r.project)}function un(e,r){return r==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(r)?e.registered_projects==null||e.registered_projects.includes(r)?"matched":e.orphaned_projects?.includes(r)===!0?"orphaned":e.stopped_projects?.some(t=>t.project_label===r)===!0?"stopped":e.lapsed_projects?.some(t=>t.project_label===r)===!0?"lapsed":"name-only":"unregistered"}function wa(e){let r=[];return e.workers.length>0&&e.workers.length<=e.maxWorkers&&r.push("workers"),e.mode==="global"&&e.projects.length>0&&e.projects.length<=e.maxProjects&&r.push("projects"),r.push("host"),r}var cr=["wid","run","org","iss","bar","phase","elapsed","eta","hb","loc","tks","ctx","tls","rsn","txt"],Fe={mode:"local",project:null,maxWidth:200,maxRows:16},rE=" ",Fp="\u2588",tE="\u25B6",nE="\u2717",oE="\u2591",sE=new Set(["gate","push-pr","merge","cascade"]),iE=new Set(["requeue"]),aE="repair";function pn(e){return e.display?.origin===aE}function lt(e,r=Fe){let t=un(e,r.project),n=at(e,r),o=n.slice(0,Math.max(0,Math.floor(r.maxRows))),s=o.map(u=>Lo(u,r,e.generated_at)),i=yE(s),a=o.map((u,m)=>({worker_id:u.worker_id,project_label:u.project_label,mine:r.project!=null&&u.project_label===r.project,cells:s[m],line:me(kE(s[m],i),r.maxWidth)})),l=dE(e,r,n,t),d=n.length-o.length,c=[l.line,...a.map(u=>u.line)];return d>0&&c.push(me(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,r.maxWidth)),c.push(...mE(e,r)),c.push(...pE(e,r)),{version:1,generated_at:e.generated_at,mode:r.mode,project:r.project,columns:cr,header:l,rows:a,lines:c,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Lo(e,r,t){let n=e.display??Cp,o=pn(e),s=[n.runner,n.model==null?null:ka(n.model),n.effort].filter(l=>!!l).join(" "),i=n.phase!=null&&sE.has(n.phase),a=o||i||n.origin!=null&&iE.has(n.origin);return{wid:r.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:o||s===""?"":`run=${s}`,org:o?"lane=repair":i?"org=landing":n.origin==null?"":`org=${n.origin}`,iss:n.issue==null?"":o?`pr=#${n.issue.replace(/^#/,"")}`:`iss=${n.issue}`,bar:Wp(n),phase:[n.phase,n.step].filter(l=>!!l).join("\xB7"),elapsed:lr(Np(e,t)),eta:n.eta==null?"":`eta=${lr(n.eta*1e3)}`,hb:lE(n,t)??`hb=${n.heartbeat??"?"}`,loc:a?"":hE(n.added,n.removed),tks:a||n.tokens==null?"":`tks=${an(n.tokens)}`,ctx:n.context==null?"":`ctx=${an(n.context)}`,tls:a||n.tools==null?"":`tls=${n.tools}`,rsn:a||n.reasoning==null?"":`rsn=${n.reasoning}`,txt:a||n.text==null?"":`txt=${n.text}`}}function lE(e,r){if(e.wait_kind==null||e.wait_subject==null||e.wait_pid==null||e.wait_pid<=0||e.wait_started_at==null)return null;let t=Date.parse(e.wait_started_at),n=Date.parse(r);return!Number.isFinite(t)||!Number.isFinite(n)?null:`${e.wait_kind}=${e.wait_subject} ${lr(Math.max(0,n-t))}`}function Wp(e){let r=e.phase_total,t=e.phase_index;if(r==null||r<=0||t==null||t<0)return"";let n=Math.min(Math.floor(t),Math.floor(r));if(n>=r)return Fp.repeat(Math.floor(r));let o=e.failed?nE:tE;return`${Fp.repeat(n)}${o}${oE.repeat(Math.floor(r)-n-1)}`}function dE(e,r,t,n){let o=(e.repository_activity?.projects??[]).find(L=>L.project_label===r.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,interactive_reservation:e.host.ceiling.interactive_reservation??0},a=fE(t),l=o?.repository??r.project,d=e.engine??null,c=d?.running_version??e.daemon.daemon_version,u=e.deaths??null,m=e.metrics??null,h=[cE(l??"host",c,d!=null&&d.current===!1?cn:"")];(n==="unregistered"||n==="name-only")&&h.push(dn),n==="lapsed"&&h.push(ba),a!=null&&h.push(`${tn}${ar}${a}${Me}${fe}`);let f=e.workers.filter(pn).length;if(f>0){let L=Math.max(0,e.host.worker_count-f);h.push(`${dr(`workers=${L} coding +`)} ${tn}${ar}${f} repairing${Me}${fe}`)}else h.push(dr(`wrk=${t.length}/${e.host.worker_count}`));let S=i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`;h.push(dr(`${S} reserve=${i.interactive_reservation} interactive`)),h.push(dr(gE(i))),s.open_pull_requests!=null&&h.push(dr(`prs=${s.open_pull_requests}`)),s.recently_closed!=null&&h.push(dr(`cpr=${s.recently_closed}`)),s.open_issues!=null&&h.push(dr(`iss=${s.open_issues}`)),s.stale&&h.push("!counts stale");let _=m==null?null:Up(m.hour),v=_==null?null:dr(_);if(v!=null&&h.push(v),u!=null&&u.count>0&&u.latest!=null){let L=u.boot_loop,Q=ot(L?.latest_refusal);h.push(L==null?`${Qe}${u.count} ${u.latest.sender_class}`:`${Qe}${u.count} boot-refused \xD7${L.count} in ${uE(L.span_ms)}`+(Q==null?"":` \u2014 ${Q}`))}if(e.staleness.stale){let L=e.staleness.age_ms;h.push(L==null?"!unmeasured":`!stale ${Math.round(L/1e3)}s`)}let C=`${h.join(" \xB7 ")}${Pe}`,H=_!=null&&Re(C)>r.maxWidth?`${h.filter(L=>L!==v).join(" \xB7 ")}${Pe}`:C;return{repo:l,project:r.project,project_match:n,version:c,engine:d,deaths:u,metrics:m,model:a,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:me(H,r.maxWidth)}}function cE(e,r,t){return`${ua}${ar}${ma}\xBB${ar} ${Ao}${e}${Do} ${pa}v${r}${t}${ar}${Me}${fe}`}function dr(e){return e.replace(/(^|\s)([A-Za-z][A-Za-z0-9/]*=)([^\s]+)/g,(r,t,n,o)=>`${t}${nn}${n}${on}${o}${fe}`)}function uE(e){return lr(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function Up(e){let r=[];e.tokens_per_min.value!=null&&r.push(`tk/m=${ln(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&r.push(`tl/m=${ln(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&r.push(`iss/h=${ln(e.issues_per_hour.value)}`);let t=e.runner_share.shares[0];return t!=null&&r.push(`${t.key}=${Math.round(t.share*100)}%`),r.length===0?null:r.join(" ")}function pE(e,r){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let n=t.posture==="spent"?it:st,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[me(`${n} github budget ${t.posture}${o} \u2014 ${t.reason}`,r.maxWidth)]}function mE(e,r){let t=e.deaths;if(t==null||t.count<=0)return[];let n=t.recent.map(s=>me(`${Qe} ${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}`),r.maxWidth)),o=t.count-t.recent.length;return o>0&&n.push(me(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,r.maxWidth)),n}function gE(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${Oe(e.memory_used_bytes)}`;let r=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${Oe(e.memory_used_bytes)}/${Oe(e.memory_ceiling_bytes)}${r}`}function fE(e){for(let r of e){let t=r.display;if(t==null)continue;let n=[t.runner,t.model,t.effort].filter(o=>!!o);if(n.length>0)return n.join("\xB7")}return null}function hE(e,r){if(e==null&&r==null)return"";let t=[];return e!=null&&e>0&&t.push(`+${e}`),r!=null&&r>0&&t.push(`-${r}`),`loc=${t.length>0?t.join(" "):"0"}`}function yE(e){let r=Object.fromEntries(cr.map(t=>[t,0]));for(let t of e)for(let n of cr)r[n]=Math.max(r[n],Re(t[n]));return r}function kE(e,r){let t=cr.filter(o=>r[o]>0);if(t.length===0)return"";let n=t.map((o,s)=>Io(o,sn(e[o],s===t.length-1?Re(e[o]):r[o])));return`${Me}${fe}${n.join(rE)}${Pe}`}function Io(e,r){if(e==="wid")return`${Ao}${r}${Do}`;if(e==="org"&&r.trim()==="lane=repair"){let n=r.slice(r.trimEnd().length);return`${tn}${ar}${r.trimEnd()}${Me}${fe}${n}`}if(e==="bar")return r.replace(/█+/g,n=>`${ga}${n}`).replace("\u25B6",`${fa}\u25B6`).replace("\u2717",`${ya}\u2717`).replace(/░+/g,n=>`${ha}${n}`)+fe;let t=r.indexOf("=");return t>0?`${nn}${r.slice(0,t+1)}${on}${r.slice(t+1)}${fe}`:r}function va(e){return Object.freeze({none:!0,reason:e})}function mn(){return{tool:"project_start",args:{runner:"claude",target:1},why:"register this project with the host so its queue can drain"}}function Ea(e,r){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError("repair args must contain only finite JSON numbers");return e}if(r.has(e))throw new TypeError("repair args must not contain cycles");r.add(e);try{if(Array.isArray(e))return Object.freeze(e.map(n=>Ea(n,r)));let t={};for(let[n,o]of Object.entries(e))t[n]=Ea(o,r);return Object.freeze(t)}finally{r.delete(e)}}function bE(e){let r=Ea(e.args,new Set);return Object.freeze({tool:e.tool,args:r,why:e.why})}function Pr(e){if("none"in e.repair)return{prose:`${e.state}; repair: none because ${e.repair.reason}`,repair:"none",repair_reason:e.repair.reason};let r=bE(e.repair);return{prose:`${e.state}; repair: call \`${r.tool}\` with \`${JSON.stringify(r.args)}\` because ${r.why}`,repair:r}}var U={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Or(e,r=U){let t=un(e,r.project),n=at(e,r),o=jo(e,r),s=SE(e,r.project,t),i=RE(e,r,n,t,s.prose),a=wa({mode:r.mode,maxWorkers:r.maxWorkers,maxProjects:r.maxProjects,workers:n,projects:o}),l={detail:"host",line:i};for(let h of a){let f=h==="workers"?i:AE(i,_E(h,o),r.separator);if(l={detail:h,line:f},h==="workers"||Re(f)<=r.maxWidth)break}let d=me(l.line,r.maxWidth),c=l.detail==="workers"?xE(n,r,e.generated_at):{lines:[],degraded:!1},u=l.detail==="workers"?n.flatMap((h,f)=>{let S=r.verbose?PE(h,r):null;return S==null?[c.lines[f]]:[c.lines[f],S]}):[],m=n.length>0?"workers":"host";return{version:1,line:d,lines:[d,...u],verbose:r.verbose,mode:r.mode,project:r.project,project_match:t,...s.repair===void 0?{}:{repair:s.repair},...s.repair_reason===void 0?{}:{repair_reason:s.repair_reason},detail:l.detail,degraded:l.detail!==m||d!==l.line||c.degraded,stale:e.staleness.stale,generated_at:e.generated_at}}function Pa(e){let r=e.options??U,t=me(Ra,r.maxWidth);return{version:1,line:t,lines:[t],verbose:r.verbose,mode:r.mode,project:r.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}function _E(e,r){return e==="projects"?r.map(OE):[]}function RE(e,r,t,n,o){let s=[],i=n!=="matched"&&n!=="name-only";r.mode==="global"?(s.push(`host ${Sa(e.workers,e.host.worker_count)}/${e.host.project_count}p`),s.push(xa(e,r))):n==="matched"?(s.push(`${r.project} ${Sa(t,t.length)}`),s.push(xa(e,r)),t.length===0&&s.push("idle")):n==="name-only"?(s.push(`${r.project} ${Sa(t,t.length)}`),s.push(xa(e,r)),s.push(dn)):s.push(o),s.push(Bp(e));let a=wE(e);a!=null&&s.push(a);let l=EE(e);l!=null&&s.push(l),e.staleness.stale&&s.push(Hp(e));let d=s.join(" ");return!i||Re(d)<=r.maxWidth||a==null&&l==null?d:[a,l,o,Bp(e),e.staleness.stale?Hp(e):null].filter(c=>c!=null).join(" ")}function Sa(e,r){let t=e.filter(pn).length;return t===0?`${r}w`:`${Math.max(0,r-t)} coding + ${t} repairing`}function Bp(e){let r=e.engine,t=r?.running_version??e.daemon.daemon_version;return r==null||r.current!==!1?`v${t}`:`v${t}${cn}`}function wE(e){let r=e.github_balance;return r==null?null:r.posture==="spent"?`${it} quota spent`:r.posture==="reserved"?`${st} quota band`:null}function EE(e){let r=e.deaths;if(r==null||r.count<=0||r.latest==null)return null;let t=r.boot_loop;if(t!=null){let n=ot(t.latest_refusal);return`${Qe}${r.count} boot-refused \xD7${t.count} in ${vE(t.span_ms)}`+(n==null?"":` \u2014 ${n}`)}return`${Qe}${r.count} ${r.latest.sender_class}`}function vE(e){return lr(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function SE(e,r,t){if(t==="unregistered")return Pr({state:`project unknown \u2014 ${r} was never registered on this host`,repair:mn()});if(t==="orphaned")return Pr({state:`project unknown \u2014 ${r} is registered on a daemon this socket does not reach`,repair:va("this socket cannot safely replace a registration owned by an unreachable daemon")});if(t==="stopped"){let n=e.stopped_projects?.find(o=>o.project_label===r);return Pr({state:`project unknown \u2014 ${r} was stopped${n==null?"":` at ${Ta(n.at)}`}`,repair:mn()})}if(t==="lapsed"){let n=e.lapsed_projects?.find(o=>o.project_label===r);if(n!=null){let o=n.registered_at==null?"":` (registered ${Ta(n.registered_at)})`;return Pr({state:`project unknown \u2014 ${r} lapsed at ${Ta(n.at)}${o}`,repair:mn()})}return Pr({state:`project unknown \u2014 ${r} lapsed`,repair:mn()})}return t==="unresolved"?Pr({state:"project unknown \u2014 this directory resolved to no project",repair:va("the directory must resolve to a project before registration args can be safe")}):{prose:""}}function Ta(e){return/^\d{4}-\d{2}-\d{2}T(\d{2}:\d{2}:\d{2})/.exec(e)?.[1]??e}function xa(e,r){let t=r.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===r.project).reduce((o,s)=>o+s.observed_rss_bytes,0),n=e.host.ceiling.memory_bytes;return r.mode==="global"&&n!=null&&n>0?`${Oe(t)}/${Oe(n)}`:Oe(t)}function Hp(e){let r=e.staleness.age_ms;return r==null?"!unmeasured":`!stale ${Math.round(r/1e3)}s`}function TE(e,r,t,n){let o=t.map(s=>Io(s,sn(e[s],r[s])));return me(`${Me}${fe}${o.join(" ")}${Pe}`,n)}function xE(e,r,t){let n=e.map(a=>Lo(a,r,t)),o=cr.filter(a=>n.some(l=>Re(l[a])>0)),s=[...o],i=qp(n,s);for(;s.length>1&&Vp(i,s)>r.maxWidth;)s.pop(),i=qp(n,s);return{lines:n.map(a=>TE(a,i,s,r.maxWidth)),degraded:s.length<o.length||Vp(i,s)>r.maxWidth}}function qp(e,r){let t=Object.fromEntries(cr.map(n=>[n,0]));for(let n of e)for(let o of r)t[o]=Math.max(t[o],Re(n[o]));return t}function Vp(e,r){return r.reduce((t,n)=>t+e[n],0)+Math.max(0,r.length-1)*2}function PE(e,r){let t=ot(e.log.last_line);return t==null?null:me(` ${_a} ${Kp(e,r.mode)}: ${t}`,r.maxWidth)}function Kp(e,r){return r==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function OE(e){return`${e.project_label} ${e.worker_count}w ${Oe(e.observed_rss_bytes)}`}function AE(e,r,t){return[e,...r].join(t)}var $o=1;async function gn(e,r){return await ro(e,r,"redskilled daemon")}function zp(e){let r=[...e.workers??[]],t=new Map;for(let n of r)t.set(n.project_label,(t.get(n.project_label)??0)+1);return{version:1,protocol_version:$o,daemon_version:e.daemonVersion,machine_id_hash:e.machineIdHash,session_key_hash:e.sessionKeyHash,pid:e.pid,started_at:e.startedAt,...e.ceiling==null?{}:{ceiling:e.ceiling},...e.scope==null?{}:{scope:e.scope},workers:r,projects:[...t.entries()].map(([n,o])=>({project_label:n,worker_count:o})).sort((n,o)=>n.project_label.localeCompare(o.project_label)),registrations:IE(e),...e.demand==null?{}:{demand:e.demand},...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},...e.stops==null||e.stops.length===0?{}:{stopped_registrations:[...e.stops]},...e.orphanedRegistrations==null||e.orphanedRegistrations.length===0?{}:{orphaned_registrations:[...e.orphanedRegistrations]},birth_latches:[...e.birthLatches??[]],budget_accounting:bc(r,{hostCeilingBytes:e.ceiling?.memory_bytes??e.hostCeilingBytes??null}),upgrade:$E(e)}}function IE(e){let r=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(r),n=e.queue??null,o=new Map(n==null?[]:n.projects.map(s=>[s.project_label,s]));return[...e.registrations??[]].map(s=>{let i=o.get(s.project_label);return{...s,...t?{renewal:ru(s,r)}:{},...n==null||i==null?{}:{last_poll:{at:n.fetched_at,outcome:i.outcome,depth:i.depth,request_count:n.request_count,detail:i.detail}}}}).sort((s,i)=>s.project_label.localeCompare(i.project_label))}function $E(e){let r=e.daemonVersion,t=e.published?.version??null,n=e.published?.majorHold??null;return{running_version:r,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:+(n!==null),major_hold:n}}function Qp(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.version===1&&typeof r.protocol_version=="number"&&typeof r.daemon_version=="string"&&typeof r.machine_id_hash=="string"&&typeof r.session_key_hash=="string"&&Number.isInteger(r.pid)&&typeof r.started_at=="string"&&(r.ceiling===void 0||FE(r.ceiling))&&Array.isArray(r.workers)&&Array.isArray(r.projects)&&_c(r.budget_accounting)&&(r.scope===void 0||Yc(r.scope))&&(r.registrations===void 0||Array.isArray(r.registrations)&&r.registrations.every(Vt))&&(r.demand===void 0||Cc(r.demand))&&(r.lapsed_registrations===void 0||Array.isArray(r.lapsed_registrations)&&r.lapsed_registrations.every(CE))&&(r.stopped_registrations===void 0||Array.isArray(r.stopped_registrations)&&r.stopped_registrations.every(NE))&&(r.orphaned_registrations===void 0||Array.isArray(r.orphaned_registrations)&&r.orphaned_registrations.every(ME))&&(r.birth_latches===void 0||Array.isArray(r.birth_latches)&&r.birth_latches.every(GE))&&(r.upgrade===void 0||WE(r.upgrade))}function GE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e,t=r.repair;return r.name==="project-birth-breaker"&&typeof r.project_label=="string"&&(r.state==="open"||r.state==="half-open")&&typeof r.opened_at=="string"&&typeof r.reason=="string"&&typeof r.closes=="string"&&(r.probe_worker_id===null||typeof r.probe_worker_id=="string")&&t!=null&&t.tool==="project_reset"&&typeof t.args=="object"&&t.args!==null&&typeof t.why=="string"}function CE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.project_label=="string"&&(r.registered_at===void 0||typeof r.registered_at=="string")&&typeof r.at=="string"&&typeof r.renew_by=="string"&&Number.isInteger(r.renewals)&&Number.isInteger(r.sustains)&&typeof r.detail=="string"}function NE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.project_label=="string"&&typeof r.registered_at=="string"&&typeof r.at=="string"&&typeof r.detail=="string"}function ME(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.project_label=="string"&&(r.registered_at===void 0||typeof r.registered_at=="string")}function FE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e,t=new Set(["flag","environment","home-config","derived-default"]);return(r.memory_bytes===null||typeof r.memory_bytes=="number")&&(r.worker_count===null||typeof r.worker_count=="number")&&(r.validation_count===void 0||Number.isInteger(r.validation_count)&&Number(r.validation_count)>0)&&(r.source==="declared"||r.source==="host-fraction")&&(r.memory_source===void 0||t.has(String(r.memory_source)))&&(r.worker_source===void 0||t.has(String(r.worker_source)))&&(r.validation_source===void 0||t.has(String(r.validation_source)))}function WE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.running_version=="string"&&(r.published_version===null||typeof r.published_version=="string")&&typeof r.published_unknown=="number"&&typeof r.newer_published=="number"&&(r.replacement==="none"||r.replacement==="pending"||r.replacement==="in-progress")&&(r.checked_at===null||typeof r.checked_at=="string")&&(r.newest_published_version===void 0||r.newest_published_version===null||typeof r.newest_published_version=="string")&&(r.major_held===void 0||typeof r.major_held=="number")&&(r.checks===void 0||typeof r.checks=="number")&&(r.hold_reason===void 0||r.hold_reason===null||typeof r.hold_reason=="string")&&(r.major_hold===void 0||r.major_hold===null||UE(r.major_hold))}function UE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.version=="string"&&Number.isInteger(r.running_major)&&Number.isInteger(r.held_major)&&typeof r.reason=="string"&&typeof r.action=="string"&&r.action.trim()!==""}import{randomUUID as BE}from"node:crypto";import{mkdir as HE,readFile as qE,rename as VE,writeFile as KE}from"node:fs/promises";import{dirname as JE}from"node:path";function Yp(e){let r=Promise.resolve(),t=null;async function n(){await r;let s;try{s=await qE(e,"utf8")}catch(a){if(a.code==="ENOENT")return[];throw a}let i=zE(s);return QE(i)?i.registrations:[]}async function o(s){await HE(JE(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.${BE()}.tmp`,a={version:1,registrations:[...s]};await KE(i,`${J(a,{keyedMapCollapse:!0})}
|
|
89
|
-
|
|
90
|
-
`),e.command,...e.args]}function im(e){let r=[];return e.nice!=null?r.push(`the Worker runs at nice ${e.nice} so it yields to interactive work`):r.push("no priority control was applied"),e.max_processes!=null&&r.push(`its processes are capped at ${e.max_processes}`),e.cpu_seconds!=null&&r.push(`its CPU time is capped at ${e.cpu_seconds} seconds`),`macOS placement applied POSIX limits: ${r.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 Aa(e){let r=e??{},t=[r.max_processes!=null?"max_processes":null,r.cpu_seconds!=null?"cpu_seconds":null].filter(n=>n!=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 nm(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function ov(e){return`'${e.replace(/'/g,"'\\''")}'`}var lm="REDSKILLED_PLACEMENT",Co="red-worker",Da="/bin/sh";function dm(e=process.env,r=process.platform){let t=Oa(`POSIX rlimit and priority placement is the macOS backend (platform=${r})`);if(r==="win32")return{platform:r,systemdRun:null,userSession:!1,jobObjects:em({platform:r}),posix:t};let n=dt(`Job Object placement is the Windows backend (platform=${r}), so there is no native reach to load here`);if(r==="darwin")return{platform:r,systemdRun:null,userSession:!1,jobObjects:n,posix:iv(e)};if(r!=="linux")return{platform:r,systemdRun:null,userSession:!1,jobObjects:n,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&La(am(o,"systemd","private"));return{platform:r,systemdRun:mm("systemd-run",e),userSession:s,jobObjects:n,posix:t}}function iv(e){return La(Da)?{available:!0,shell:Da,nice:mm("nice",e)}:Oa(`no POSIX shell was found at ${Da}, so there is nothing to apply rlimits or priority in`)}function cm(e=process.env){let r=(e[lm]??"").trim().toLowerCase();return r===""?!0:!["off","false","0","no"].includes(r)}function av(e,r,t=Co){return um(e,r,t).replace(/\.service$/,"")}function um(e,r,t=Co){return`${ja(t,"red-worker",24)}-${ja(e,"project",32)}-${ja(r,"worker",32)}.service`}function pm(e){let r=[...e.args??[]],t={...e.budget??{},...e.budget?.memory_max==null&&e.memoryCeiling?.memory_max!=null?{memory_max:e.memoryCeiling.memory_max}:{}},n=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:r,cwd:e.workspacePath,warning:u,budget:t,...n!=null?{memoryCeiling:n}:{},environment:Gt({scope:null,memory_ceiling:n,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 ${lm}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return dv(e,r,t,n,o,i);if(e.probes.platform==="darwin")return lv(e,r,t,n,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=um(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=Gt({scope:a,memory_ceiling:n,scope_degradation:null});for(let[u,m]of Object.entries({...e.env??{},...d}))l.push(`--setenv=${u}=${m}`);let c=Aa(e.budget);return{isolated:!0,backend:"transient-unit",unit:a,command:e.probes.systemdRun,args:[...l,"--",e.command,...r],budget:t,...n!=null?{memoryCeiling:n}:{},environment:d,...c!=null?{budgetWarning:c}:{}}}function lv(e,r,t,n,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=om(t,{canRenice:s.nice!=null}),a=t.memory_high!=null||t.memory_max!=null,l=im(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:sm({limits:i,nice:s.nice,command:e.command,args:r}),cwd:e.workspacePath,posix:i,warning:l,budget:t,...n!=null?{memoryCeiling:n}:{},environment:Gt({scope:null,memory_ceiling:n,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 dv(e,r,t,n,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=rm(t),l=av(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...r],cwd:e.workspacePath,job:{name:l,limits:a},budget:t,...n!=null?{memoryCeiling:n}:{},environment:Gt({scope:l,memory_ceiling:n,scope_degradation:null}),...cv(o&&a.note!=null?`${a.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,Aa(e.budget))}}function cv(...e){let r=e.filter(t=>t!=null&&t!=="");return r.length>0?{budgetWarning:r.join("; ")}:{}}function mm(e,r){for(let t of(r.PATH??"").split(sv)){if(!t)continue;let n=am(t,e);if(La(n))return n}return null}function ja(e,r,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||r}async function Ia(e,r){let t=[],n=[];for(let o of e){let s=!1;try{s=await r(o)===!0}catch{s=!1}(s?t:n).push(o)}return{alive:t,dead:n}}var gm=3e4;function fm(e){return e.unit!=null&&e.unit!==""?uv(e.unit):oe(e.pid)}function uv(e){let r=No("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return r.error!=null?!1:r.status===0}var pv="REDSKILLED_UNIT_DISCOVERY",hm="(unowned)";function ym(e){let r=No("systemctl",["--user","show","--property=MainPID","--value",e],{encoding:"utf8"});if(r.error!=null||r.status!==0)return null;let t=Number.parseInt((r.stdout??"").trim(),10);return Number.isInteger(t)&&t>0?t:null}function mv(e=process.env){let r=(e[pv]??"").trim().toLowerCase();return r===""?!0:!["off","false","0","no"].includes(r)}function km(e,r,t=process.env){return mv(t)&&e===r}function bm(e=Co){let r=No("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return r.error!=null||r.status!==0?[]:(r.stdout??"").split(`
|
|
91
|
-
|
|
92
|
-
`),
|
|
93
|
-
`)
|
|
94
|
-
`)
|
|
95
|
-
`)
|
|
84
|
+
`)}var $R=class extends Error{constructor(e,r,t){super(GR(t)),this.request=e,this.headers=r,this.response=t,this.errors=t.errors,this.data=t.data,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}request;headers;response;name="GraphqlResponseError";errors;data},IR=["method","baseUrl","url","headers","request","query","mediaType","operationName"],CR=["query","method","url"],zu=/\/api\/v3\/?$/;function NR(e,r,t){if(t){if(typeof r=="string"&&"query"in t)return Promise.reject(new Error('[@octokit/graphql] "query" cannot be used as variable name'));for(let i in t)if(CR.includes(i))return Promise.reject(new Error(`[@octokit/graphql] "${i}" cannot be used as variable name`))}let n=typeof r=="string"?Object.assign({query:r},t):r,o=Object.keys(n).reduce((i,a)=>IR.includes(a)?(i[a]=n[a],i):(i.variables||(i.variables={}),i.variables[a]=n[a],i),{}),s=n.baseUrl||e.endpoint.DEFAULTS.baseUrl;return zu.test(s)&&(o.url=s.replace(zu,"/api/graphql")),e(o).then(i=>{if(i.data.errors){let a={};for(let l of Object.keys(i.headers))a[l]=i.headers[l];throw new $R(o,a,i.data)}return i.data.data})}function Ui(e,r){let t=e.defaults(r);return Object.assign((o,s)=>NR(t,o,s),{defaults:Ui.bind(null,t),endpoint:t.endpoint})}var uD=Ui(Yt,{headers:{"user-agent":`octokit-graphql.js/${LR} ${sr()}`},method:"POST",url:"/graphql"});function Qu(e){return Ui(e,{method:"POST",url:"/graphql"})}var Bi="(?:[a-zA-Z0-9_-]+)",Yu="\\.",Xu=new RegExp(`^${Bi}${Yu}${Bi}${Yu}${Bi}$`),MR=Xu.test.bind(Xu);async function FR(e){let r=MR(e),t=e.startsWith("v1.")||e.startsWith("ghs_"),n=e.startsWith("ghu_");return{type:"token",token:e,tokenType:r?"app":t?"installation":n?"user-to-server":"oauth"}}function WR(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function UR(e,r,t,n){let o=r.endpoint.merge(t,n);return o.headers.authorization=WR(e),r(o)}var Zu=function(r){if(!r)throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");if(typeof r!="string")throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");return r=r.replace(/^(token|bearer) +/i,""),Object.assign(FR.bind(null,r),{hook:UR.bind(null,r)})};var Hi="7.0.7";var ep=()=>{},BR=console.warn.bind(console),HR=console.error.bind(console);function qR(e={}){return typeof e.debug!="function"&&(e.debug=ep),typeof e.info!="function"&&(e.info=ep),typeof e.warn!="function"&&(e.warn=BR),typeof e.error!="function"&&(e.error=HR),e}var rp=`octokit-core.js/${Hi} ${sr()}`,wo=class{static VERSION=Hi;static defaults(r){return class extends this{constructor(...n){let o=n[0]||{};if(typeof r=="function"){super(r(o));return}super(Object.assign({},r,o,o.userAgent&&r.userAgent?{userAgent:`${o.userAgent} ${r.userAgent}`}:null))}}}static plugins=[];static plugin(...r){let t=this.plugins;return class extends this{static plugins=t.concat(r.filter(o=>!t.includes(o)))}}constructor(r={}){let t=new Eu.Collection,n={baseUrl:Yt.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},r.request,{hook:t.bind(null,"request")}),mediaType:{previews:[],format:""}};if(n.headers["user-agent"]=r.userAgent?`${r.userAgent} ${rp}`:rp,r.baseUrl&&(n.baseUrl=r.baseUrl),r.previews&&(n.mediaType.previews=r.previews),r.timeZone&&(n.headers["time-zone"]=r.timeZone),this.request=Yt.defaults(n),this.graphql=Qu(this.request).defaults(n),this.log=qR(r.log),this.hook=t,r.authStrategy){let{authStrategy:s,...i}=r,a=s(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:i},r.auth));t.wrap("request",a.hook),this.auth=a}else if(!r.auth)this.auth=async()=>({type:"unauthenticated"});else{let s=Zu(r.auth);t.wrap("request",s.hook),this.auth=s}let o=this.constructor;for(let s=0;s<o.plugins.length;++s)Object.assign(this,o.plugins[s](this,r))}request;graphql;log;hook;auth};var tp="6.0.0";function qi(e){e.hook.wrap("request",(r,t)=>{e.log.debug("request",t);let n=Date.now(),o=e.request.endpoint.parse(t),s=o.url.replace(t.baseUrl,"");return r(t).then(i=>{let a=i.headers["x-github-request-id"];return e.log.info(`${o.method} ${s} - ${i.status} with id ${a} in ${Date.now()-n}ms`),i}).catch(i=>{let a=i.response?.headers["x-github-request-id"]||"UNKNOWN";throw e.log.error(`${o.method} ${s} - ${i.status} with id ${a} in ${Date.now()-n}ms`),i})})}qi.VERSION=tp;var VR="0.0.0-development";function KR(e){if(!e.data)return{...e,data:[]};if(!(("total_count"in e.data||"total_commits"in e.data)&&!("url"in e.data)))return e;let t=e.data.incomplete_results,n=e.data.repository_selection,o=e.data.total_count,s=e.data.total_commits;delete e.data.incomplete_results,delete e.data.repository_selection,delete e.data.total_count,delete e.data.total_commits;let i=Object.keys(e.data)[0],a=e.data[i];return e.data=a,typeof t<"u"&&(e.data.incomplete_results=t),typeof n<"u"&&(e.data.repository_selection=n),e.data.total_count=o,e.data.total_commits=s,e}function Vi(e,r,t){let n=typeof r=="function"?r.endpoint(t):e.request.endpoint(r,t),o=typeof r=="function"?r:e.request,s=n.method,i=n.headers,a=n.url;return{[Symbol.asyncIterator]:()=>({async next(){if(!a)return{done:!0};try{let l=await o({method:s,url:a,headers:i}),d=KR(l);if(a=((d.headers.link||"").match(/<([^<>]+)>;\s*rel="next"/)||[])[1],!a&&"total_commits"in d.data){let c=new URL(d.url),u=c.searchParams,m=parseInt(u.get("page")||"1",10),f=parseInt(u.get("per_page")||"250",10);m*f<d.data.total_commits&&(u.set("page",String(m+1)),a=c.toString())}return{value:d}}catch(l){if(l.status!==409)throw l;return a="",{value:{status:200,headers:{},data:[]}}}}})}}function np(e,r,t,n){return typeof t=="function"&&(n=t,t=void 0),op(e,[],Vi(e,r,t)[Symbol.asyncIterator](),n)}function op(e,r,t,n){return t.next().then(o=>{if(o.done)return r;let s=!1;function i(){s=!0}return r=r.concat(n?n(o.value,i):o.value.data),s?r:op(e,r,t,n)})}var PD=Object.assign(np,{iterator:Vi});function Ki(e){return{paginate:Object.assign(np.bind(null,e),{iterator:Vi.bind(null,e)})}}Ki.VERSION=VR;var Ji="17.0.0";var JR={actions:{addCustomLabelsToSelfHostedRunnerForOrg:["POST /orgs/{org}/actions/runners/{runner_id}/labels"],addCustomLabelsToSelfHostedRunnerForRepo:["POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],addRepoAccessToSelfHostedRunnerGroupInOrg:["PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}"],addSelectedRepoToOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],addSelectedRepoToOrgVariable:["PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"],approveWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"],cancelWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"],createEnvironmentVariable:["POST /repos/{owner}/{repo}/environments/{environment_name}/variables"],createHostedRunnerForOrg:["POST /orgs/{org}/actions/hosted-runners"],createOrUpdateEnvironmentSecret:["PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],createOrUpdateOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"],createOrgVariable:["POST /orgs/{org}/actions/variables"],createRegistrationTokenForOrg:["POST /orgs/{org}/actions/runners/registration-token"],createRegistrationTokenForRepo:["POST /repos/{owner}/{repo}/actions/runners/registration-token"],createRemoveTokenForOrg:["POST /orgs/{org}/actions/runners/remove-token"],createRemoveTokenForRepo:["POST /repos/{owner}/{repo}/actions/runners/remove-token"],createRepoVariable:["POST /repos/{owner}/{repo}/actions/variables"],createWorkflowDispatch:["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"],deleteActionsCacheById:["DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}"],deleteActionsCacheByKey:["DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}"],deleteArtifact:["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],deleteCustomImageFromOrg:["DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}"],deleteCustomImageVersionFromOrg:["DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}"],deleteEnvironmentSecret:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],deleteEnvironmentVariable:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],deleteHostedRunnerForOrg:["DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],deleteOrgSecret:["DELETE /orgs/{org}/actions/secrets/{secret_name}"],deleteOrgVariable:["DELETE /orgs/{org}/actions/variables/{name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"],deleteRepoVariable:["DELETE /repos/{owner}/{repo}/actions/variables/{name}"],deleteSelfHostedRunnerFromOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}"],deleteSelfHostedRunnerFromRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"],deleteWorkflowRun:["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],deleteWorkflowRunLogs:["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],disableSelectedRepositoryGithubActionsOrganization:["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"],disableWorkflow:["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"],downloadArtifact:["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"],downloadJobLogsForWorkflowRun:["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"],downloadWorkflowRunAttemptLogs:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"],downloadWorkflowRunLogs:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],enableSelectedRepositoryGithubActionsOrganization:["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"],enableWorkflow:["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"],forceCancelWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel"],generateRunnerJitconfigForOrg:["POST /orgs/{org}/actions/runners/generate-jitconfig"],generateRunnerJitconfigForRepo:["POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig"],getActionsCacheList:["GET /repos/{owner}/{repo}/actions/caches"],getActionsCacheUsage:["GET /repos/{owner}/{repo}/actions/cache/usage"],getActionsCacheUsageByRepoForOrg:["GET /orgs/{org}/actions/cache/usage-by-repository"],getActionsCacheUsageForOrg:["GET /orgs/{org}/actions/cache/usage"],getAllowedActionsOrganization:["GET /orgs/{org}/actions/permissions/selected-actions"],getAllowedActionsRepository:["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"],getArtifact:["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],getCustomImageForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}"],getCustomImageVersionForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}"],getCustomOidcSubClaimForRepo:["GET /repos/{owner}/{repo}/actions/oidc/customization/sub"],getEnvironmentPublicKey:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key"],getEnvironmentSecret:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],getEnvironmentVariable:["GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],getGithubActionsDefaultWorkflowPermissionsOrganization:["GET /orgs/{org}/actions/permissions/workflow"],getGithubActionsDefaultWorkflowPermissionsRepository:["GET /repos/{owner}/{repo}/actions/permissions/workflow"],getGithubActionsPermissionsOrganization:["GET /orgs/{org}/actions/permissions"],getGithubActionsPermissionsRepository:["GET /repos/{owner}/{repo}/actions/permissions"],getHostedRunnerForOrg:["GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],getHostedRunnersGithubOwnedImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/github-owned"],getHostedRunnersLimitsForOrg:["GET /orgs/{org}/actions/hosted-runners/limits"],getHostedRunnersMachineSpecsForOrg:["GET /orgs/{org}/actions/hosted-runners/machine-sizes"],getHostedRunnersPartnerImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/partner"],getHostedRunnersPlatformsForOrg:["GET /orgs/{org}/actions/hosted-runners/platforms"],getJobForWorkflowRun:["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],getOrgPublicKey:["GET /orgs/{org}/actions/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/actions/secrets/{secret_name}"],getOrgVariable:["GET /orgs/{org}/actions/variables/{name}"],getPendingDeploymentsForRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],getRepoPermissions:["GET /repos/{owner}/{repo}/actions/permissions",{},{renamed:["actions","getGithubActionsPermissionsRepository"]}],getRepoPublicKey:["GET /repos/{owner}/{repo}/actions/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],getRepoVariable:["GET /repos/{owner}/{repo}/actions/variables/{name}"],getReviewsForRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"],getSelfHostedRunnerForOrg:["GET /orgs/{org}/actions/runners/{runner_id}"],getSelfHostedRunnerForRepo:["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"],getWorkflow:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],getWorkflowAccessToRepository:["GET /repos/{owner}/{repo}/actions/permissions/access"],getWorkflowRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],getWorkflowRunAttempt:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"],getWorkflowRunUsage:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"],getWorkflowUsage:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"],listArtifactsForRepo:["GET /repos/{owner}/{repo}/actions/artifacts"],listCustomImageVersionsForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions"],listCustomImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom"],listEnvironmentSecrets:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets"],listEnvironmentVariables:["GET /repos/{owner}/{repo}/environments/{environment_name}/variables"],listGithubHostedRunnersInGroupForOrg:["GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners"],listHostedRunnersForOrg:["GET /orgs/{org}/actions/hosted-runners"],listJobsForWorkflowRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"],listJobsForWorkflowRunAttempt:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"],listLabelsForSelfHostedRunnerForOrg:["GET /orgs/{org}/actions/runners/{runner_id}/labels"],listLabelsForSelfHostedRunnerForRepo:["GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],listOrgSecrets:["GET /orgs/{org}/actions/secrets"],listOrgVariables:["GET /orgs/{org}/actions/variables"],listRepoOrganizationSecrets:["GET /repos/{owner}/{repo}/actions/organization-secrets"],listRepoOrganizationVariables:["GET /repos/{owner}/{repo}/actions/organization-variables"],listRepoSecrets:["GET /repos/{owner}/{repo}/actions/secrets"],listRepoVariables:["GET /repos/{owner}/{repo}/actions/variables"],listRepoWorkflows:["GET /repos/{owner}/{repo}/actions/workflows"],listRunnerApplicationsForOrg:["GET /orgs/{org}/actions/runners/downloads"],listRunnerApplicationsForRepo:["GET /repos/{owner}/{repo}/actions/runners/downloads"],listSelectedReposForOrgSecret:["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"],listSelectedReposForOrgVariable:["GET /orgs/{org}/actions/variables/{name}/repositories"],listSelectedRepositoriesEnabledGithubActionsOrganization:["GET /orgs/{org}/actions/permissions/repositories"],listSelfHostedRunnersForOrg:["GET /orgs/{org}/actions/runners"],listSelfHostedRunnersForRepo:["GET /repos/{owner}/{repo}/actions/runners"],listWorkflowRunArtifacts:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"],listWorkflowRuns:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"],listWorkflowRunsForRepo:["GET /repos/{owner}/{repo}/actions/runs"],reRunJobForWorkflowRun:["POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun"],reRunWorkflow:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],reRunWorkflowFailedJobs:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs"],removeAllCustomLabelsFromSelfHostedRunnerForOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}/labels"],removeAllCustomLabelsFromSelfHostedRunnerForRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],removeCustomLabelFromSelfHostedRunnerForOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}"],removeCustomLabelFromSelfHostedRunnerForRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],removeSelectedRepoFromOrgVariable:["DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"],reviewCustomGatesForRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule"],reviewPendingDeploymentsForRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],setAllowedActionsOrganization:["PUT /orgs/{org}/actions/permissions/selected-actions"],setAllowedActionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"],setCustomLabelsForSelfHostedRunnerForOrg:["PUT /orgs/{org}/actions/runners/{runner_id}/labels"],setCustomLabelsForSelfHostedRunnerForRepo:["PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],setCustomOidcSubClaimForRepo:["PUT /repos/{owner}/{repo}/actions/oidc/customization/sub"],setGithubActionsDefaultWorkflowPermissionsOrganization:["PUT /orgs/{org}/actions/permissions/workflow"],setGithubActionsDefaultWorkflowPermissionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions/workflow"],setGithubActionsPermissionsOrganization:["PUT /orgs/{org}/actions/permissions"],setGithubActionsPermissionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"],setSelectedReposForOrgVariable:["PUT /orgs/{org}/actions/variables/{name}/repositories"],setSelectedRepositoriesEnabledGithubActionsOrganization:["PUT /orgs/{org}/actions/permissions/repositories"],setWorkflowAccessToRepository:["PUT /repos/{owner}/{repo}/actions/permissions/access"],updateEnvironmentVariable:["PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],updateHostedRunnerForOrg:["PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],updateOrgVariable:["PATCH /orgs/{org}/actions/variables/{name}"],updateRepoVariable:["PATCH /repos/{owner}/{repo}/actions/variables/{name}"]},activity:{checkRepoIsStarredByAuthenticatedUser:["GET /user/starred/{owner}/{repo}"],deleteRepoSubscription:["DELETE /repos/{owner}/{repo}/subscription"],deleteThreadSubscription:["DELETE /notifications/threads/{thread_id}/subscription"],getFeeds:["GET /feeds"],getRepoSubscription:["GET /repos/{owner}/{repo}/subscription"],getThread:["GET /notifications/threads/{thread_id}"],getThreadSubscriptionForAuthenticatedUser:["GET /notifications/threads/{thread_id}/subscription"],listEventsForAuthenticatedUser:["GET /users/{username}/events"],listNotificationsForAuthenticatedUser:["GET /notifications"],listOrgEventsForAuthenticatedUser:["GET /users/{username}/events/orgs/{org}"],listPublicEvents:["GET /events"],listPublicEventsForRepoNetwork:["GET /networks/{owner}/{repo}/events"],listPublicEventsForUser:["GET /users/{username}/events/public"],listPublicOrgEvents:["GET /orgs/{org}/events"],listReceivedEventsForUser:["GET /users/{username}/received_events"],listReceivedPublicEventsForUser:["GET /users/{username}/received_events/public"],listRepoEvents:["GET /repos/{owner}/{repo}/events"],listRepoNotificationsForAuthenticatedUser:["GET /repos/{owner}/{repo}/notifications"],listReposStarredByAuthenticatedUser:["GET /user/starred"],listReposStarredByUser:["GET /users/{username}/starred"],listReposWatchedByUser:["GET /users/{username}/subscriptions"],listStargazersForRepo:["GET /repos/{owner}/{repo}/stargazers"],listWatchedReposForAuthenticatedUser:["GET /user/subscriptions"],listWatchersForRepo:["GET /repos/{owner}/{repo}/subscribers"],markNotificationsAsRead:["PUT /notifications"],markRepoNotificationsAsRead:["PUT /repos/{owner}/{repo}/notifications"],markThreadAsDone:["DELETE /notifications/threads/{thread_id}"],markThreadAsRead:["PATCH /notifications/threads/{thread_id}"],setRepoSubscription:["PUT /repos/{owner}/{repo}/subscription"],setThreadSubscription:["PUT /notifications/threads/{thread_id}/subscription"],starRepoForAuthenticatedUser:["PUT /user/starred/{owner}/{repo}"],unstarRepoForAuthenticatedUser:["DELETE /user/starred/{owner}/{repo}"]},apps:{addRepoToInstallation:["PUT /user/installations/{installation_id}/repositories/{repository_id}",{},{renamed:["apps","addRepoToInstallationForAuthenticatedUser"]}],addRepoToInstallationForAuthenticatedUser:["PUT /user/installations/{installation_id}/repositories/{repository_id}"],checkToken:["POST /applications/{client_id}/token"],createFromManifest:["POST /app-manifests/{code}/conversions"],createInstallationAccessToken:["POST /app/installations/{installation_id}/access_tokens"],deleteAuthorization:["DELETE /applications/{client_id}/grant"],deleteInstallation:["DELETE /app/installations/{installation_id}"],deleteToken:["DELETE /applications/{client_id}/token"],getAuthenticated:["GET /app"],getBySlug:["GET /apps/{app_slug}"],getInstallation:["GET /app/installations/{installation_id}"],getOrgInstallation:["GET /orgs/{org}/installation"],getRepoInstallation:["GET /repos/{owner}/{repo}/installation"],getSubscriptionPlanForAccount:["GET /marketplace_listing/accounts/{account_id}"],getSubscriptionPlanForAccountStubbed:["GET /marketplace_listing/stubbed/accounts/{account_id}"],getUserInstallation:["GET /users/{username}/installation"],getWebhookConfigForApp:["GET /app/hook/config"],getWebhookDelivery:["GET /app/hook/deliveries/{delivery_id}"],listAccountsForPlan:["GET /marketplace_listing/plans/{plan_id}/accounts"],listAccountsForPlanStubbed:["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"],listInstallationReposForAuthenticatedUser:["GET /user/installations/{installation_id}/repositories"],listInstallationRequestsForAuthenticatedApp:["GET /app/installation-requests"],listInstallations:["GET /app/installations"],listInstallationsForAuthenticatedUser:["GET /user/installations"],listPlans:["GET /marketplace_listing/plans"],listPlansStubbed:["GET /marketplace_listing/stubbed/plans"],listReposAccessibleToInstallation:["GET /installation/repositories"],listSubscriptionsForAuthenticatedUser:["GET /user/marketplace_purchases"],listSubscriptionsForAuthenticatedUserStubbed:["GET /user/marketplace_purchases/stubbed"],listWebhookDeliveries:["GET /app/hook/deliveries"],redeliverWebhookDelivery:["POST /app/hook/deliveries/{delivery_id}/attempts"],removeRepoFromInstallation:["DELETE /user/installations/{installation_id}/repositories/{repository_id}",{},{renamed:["apps","removeRepoFromInstallationForAuthenticatedUser"]}],removeRepoFromInstallationForAuthenticatedUser:["DELETE /user/installations/{installation_id}/repositories/{repository_id}"],resetToken:["PATCH /applications/{client_id}/token"],revokeInstallationAccessToken:["DELETE /installation/token"],scopeToken:["POST /applications/{client_id}/token/scoped"],suspendInstallation:["PUT /app/installations/{installation_id}/suspended"],unsuspendInstallation:["DELETE /app/installations/{installation_id}/suspended"],updateWebhookConfigForApp:["PATCH /app/hook/config"]},billing:{getGithubActionsBillingOrg:["GET /orgs/{org}/settings/billing/actions"],getGithubActionsBillingUser:["GET /users/{username}/settings/billing/actions"],getGithubBillingPremiumRequestUsageReportOrg:["GET /organizations/{org}/settings/billing/premium_request/usage"],getGithubBillingPremiumRequestUsageReportUser:["GET /users/{username}/settings/billing/premium_request/usage"],getGithubBillingUsageReportOrg:["GET /organizations/{org}/settings/billing/usage"],getGithubBillingUsageReportUser:["GET /users/{username}/settings/billing/usage"],getGithubPackagesBillingOrg:["GET /orgs/{org}/settings/billing/packages"],getGithubPackagesBillingUser:["GET /users/{username}/settings/billing/packages"],getSharedStorageBillingOrg:["GET /orgs/{org}/settings/billing/shared-storage"],getSharedStorageBillingUser:["GET /users/{username}/settings/billing/shared-storage"]},campaigns:{createCampaign:["POST /orgs/{org}/campaigns"],deleteCampaign:["DELETE /orgs/{org}/campaigns/{campaign_number}"],getCampaignSummary:["GET /orgs/{org}/campaigns/{campaign_number}"],listOrgCampaigns:["GET /orgs/{org}/campaigns"],updateCampaign:["PATCH /orgs/{org}/campaigns/{campaign_number}"]},checks:{create:["POST /repos/{owner}/{repo}/check-runs"],createSuite:["POST /repos/{owner}/{repo}/check-suites"],get:["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"],getSuite:["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"],listAnnotations:["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"],listForRef:["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"],listForSuite:["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"],listSuitesForRef:["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"],rerequestRun:["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"],rerequestSuite:["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"],setSuitesPreferences:["PATCH /repos/{owner}/{repo}/check-suites/preferences"],update:["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]},codeScanning:{commitAutofix:["POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits"],createAutofix:["POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"],createVariantAnalysis:["POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses"],deleteAnalysis:["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"],deleteCodeqlDatabase:["DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"],getAlert:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}",{},{renamedParameters:{alert_id:"alert_number"}}],getAnalysis:["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"],getAutofix:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"],getCodeqlDatabase:["GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"],getDefaultSetup:["GET /repos/{owner}/{repo}/code-scanning/default-setup"],getSarif:["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],getVariantAnalysis:["GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}"],getVariantAnalysisRepoTask:["GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}"],listAlertInstances:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"],listAlertsForOrg:["GET /orgs/{org}/code-scanning/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/code-scanning/alerts"],listAlertsInstances:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",{},{renamed:["codeScanning","listAlertInstances"]}],listCodeqlDatabases:["GET /repos/{owner}/{repo}/code-scanning/codeql/databases"],listRecentAnalyses:["GET /repos/{owner}/{repo}/code-scanning/analyses"],updateAlert:["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"],updateDefaultSetup:["PATCH /repos/{owner}/{repo}/code-scanning/default-setup"],uploadSarif:["POST /repos/{owner}/{repo}/code-scanning/sarifs"]},codeSecurity:{attachConfiguration:["POST /orgs/{org}/code-security/configurations/{configuration_id}/attach"],attachEnterpriseConfiguration:["POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach"],createConfiguration:["POST /orgs/{org}/code-security/configurations"],createConfigurationForEnterprise:["POST /enterprises/{enterprise}/code-security/configurations"],deleteConfiguration:["DELETE /orgs/{org}/code-security/configurations/{configuration_id}"],deleteConfigurationForEnterprise:["DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}"],detachConfiguration:["DELETE /orgs/{org}/code-security/configurations/detach"],getConfiguration:["GET /orgs/{org}/code-security/configurations/{configuration_id}"],getConfigurationForRepository:["GET /repos/{owner}/{repo}/code-security-configuration"],getConfigurationsForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations"],getConfigurationsForOrg:["GET /orgs/{org}/code-security/configurations"],getDefaultConfigurations:["GET /orgs/{org}/code-security/configurations/defaults"],getDefaultConfigurationsForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations/defaults"],getRepositoriesForConfiguration:["GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories"],getRepositoriesForEnterpriseConfiguration:["GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories"],getSingleConfigurationForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}"],setConfigurationAsDefault:["PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults"],setConfigurationAsDefaultForEnterprise:["PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults"],updateConfiguration:["PATCH /orgs/{org}/code-security/configurations/{configuration_id}"],updateEnterpriseConfiguration:["PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}"]},codesOfConduct:{getAllCodesOfConduct:["GET /codes_of_conduct"],getConductCode:["GET /codes_of_conduct/{key}"]},codespaces:{addRepositoryForSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],addSelectedRepoToOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"],checkPermissionsForDevcontainer:["GET /repos/{owner}/{repo}/codespaces/permissions_check"],codespaceMachinesForAuthenticatedUser:["GET /user/codespaces/{codespace_name}/machines"],createForAuthenticatedUser:["POST /user/codespaces"],createOrUpdateOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],createOrUpdateSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}"],createWithPrForAuthenticatedUser:["POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces"],createWithRepoForAuthenticatedUser:["POST /repos/{owner}/{repo}/codespaces"],deleteForAuthenticatedUser:["DELETE /user/codespaces/{codespace_name}"],deleteFromOrganization:["DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}"],deleteOrgSecret:["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],deleteSecretForAuthenticatedUser:["DELETE /user/codespaces/secrets/{secret_name}"],exportForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/exports"],getCodespacesForUserInOrg:["GET /orgs/{org}/members/{username}/codespaces"],getExportDetailsForAuthenticatedUser:["GET /user/codespaces/{codespace_name}/exports/{export_id}"],getForAuthenticatedUser:["GET /user/codespaces/{codespace_name}"],getOrgPublicKey:["GET /orgs/{org}/codespaces/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/codespaces/secrets/{secret_name}"],getPublicKeyForAuthenticatedUser:["GET /user/codespaces/secrets/public-key"],getRepoPublicKey:["GET /repos/{owner}/{repo}/codespaces/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],getSecretForAuthenticatedUser:["GET /user/codespaces/secrets/{secret_name}"],listDevcontainersInRepositoryForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/devcontainers"],listForAuthenticatedUser:["GET /user/codespaces"],listInOrganization:["GET /orgs/{org}/codespaces",{},{renamedParameters:{org_id:"org"}}],listInRepositoryForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces"],listOrgSecrets:["GET /orgs/{org}/codespaces/secrets"],listRepoSecrets:["GET /repos/{owner}/{repo}/codespaces/secrets"],listRepositoriesForSecretForAuthenticatedUser:["GET /user/codespaces/secrets/{secret_name}/repositories"],listSecretsForAuthenticatedUser:["GET /user/codespaces/secrets"],listSelectedReposForOrgSecret:["GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories"],preFlightWithRepoForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/new"],publishForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/publish"],removeRepositoryForSecretForAuthenticatedUser:["DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"],repoMachinesForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/machines"],setRepositoriesForSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}/repositories"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories"],startForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/start"],stopForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/stop"],stopInOrganization:["POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop"],updateForAuthenticatedUser:["PATCH /user/codespaces/{codespace_name}"]},copilot:{addCopilotSeatsForTeams:["POST /orgs/{org}/copilot/billing/selected_teams"],addCopilotSeatsForUsers:["POST /orgs/{org}/copilot/billing/selected_users"],cancelCopilotSeatAssignmentForTeams:["DELETE /orgs/{org}/copilot/billing/selected_teams"],cancelCopilotSeatAssignmentForUsers:["DELETE /orgs/{org}/copilot/billing/selected_users"],copilotMetricsForOrganization:["GET /orgs/{org}/copilot/metrics"],copilotMetricsForTeam:["GET /orgs/{org}/team/{team_slug}/copilot/metrics"],getCopilotOrganizationDetails:["GET /orgs/{org}/copilot/billing"],getCopilotSeatDetailsForUser:["GET /orgs/{org}/members/{username}/copilot"],listCopilotSeats:["GET /orgs/{org}/copilot/billing/seats"]},credentials:{revoke:["POST /credentials/revoke"]},dependabot:{addSelectedRepoToOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],createOrUpdateOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],deleteOrgSecret:["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],getAlert:["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],getOrgPublicKey:["GET /orgs/{org}/dependabot/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/dependabot/secrets/{secret_name}"],getRepoPublicKey:["GET /repos/{owner}/{repo}/dependabot/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],listAlertsForEnterprise:["GET /enterprises/{enterprise}/dependabot/alerts"],listAlertsForOrg:["GET /orgs/{org}/dependabot/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/dependabot/alerts"],listOrgSecrets:["GET /orgs/{org}/dependabot/secrets"],listRepoSecrets:["GET /repos/{owner}/{repo}/dependabot/secrets"],listSelectedReposForOrgSecret:["GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],repositoryAccessForOrg:["GET /organizations/{org}/dependabot/repository-access"],setRepositoryAccessDefaultLevel:["PUT /organizations/{org}/dependabot/repository-access/default-level"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],updateAlert:["PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],updateRepositoryAccessForOrg:["PATCH /organizations/{org}/dependabot/repository-access"]},dependencyGraph:{createRepositorySnapshot:["POST /repos/{owner}/{repo}/dependency-graph/snapshots"],diffRange:["GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}"],exportSbom:["GET /repos/{owner}/{repo}/dependency-graph/sbom"]},emojis:{get:["GET /emojis"]},enterpriseTeamMemberships:{add:["PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"],bulkAdd:["POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add"],bulkRemove:["POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove"],get:["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"],list:["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships"],remove:["DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"]},enterpriseTeamOrganizations:{add:["PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],bulkAdd:["POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add"],bulkRemove:["POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove"],delete:["DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],getAssignment:["GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],getAssignments:["GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations"]},enterpriseTeams:{create:["POST /enterprises/{enterprise}/teams"],delete:["DELETE /enterprises/{enterprise}/teams/{team_slug}"],get:["GET /enterprises/{enterprise}/teams/{team_slug}"],list:["GET /enterprises/{enterprise}/teams"],update:["PATCH /enterprises/{enterprise}/teams/{team_slug}"]},gists:{checkIsStarred:["GET /gists/{gist_id}/star"],create:["POST /gists"],createComment:["POST /gists/{gist_id}/comments"],delete:["DELETE /gists/{gist_id}"],deleteComment:["DELETE /gists/{gist_id}/comments/{comment_id}"],fork:["POST /gists/{gist_id}/forks"],get:["GET /gists/{gist_id}"],getComment:["GET /gists/{gist_id}/comments/{comment_id}"],getRevision:["GET /gists/{gist_id}/{sha}"],list:["GET /gists"],listComments:["GET /gists/{gist_id}/comments"],listCommits:["GET /gists/{gist_id}/commits"],listForUser:["GET /users/{username}/gists"],listForks:["GET /gists/{gist_id}/forks"],listPublic:["GET /gists/public"],listStarred:["GET /gists/starred"],star:["PUT /gists/{gist_id}/star"],unstar:["DELETE /gists/{gist_id}/star"],update:["PATCH /gists/{gist_id}"],updateComment:["PATCH /gists/{gist_id}/comments/{comment_id}"]},git:{createBlob:["POST /repos/{owner}/{repo}/git/blobs"],createCommit:["POST /repos/{owner}/{repo}/git/commits"],createRef:["POST /repos/{owner}/{repo}/git/refs"],createTag:["POST /repos/{owner}/{repo}/git/tags"],createTree:["POST /repos/{owner}/{repo}/git/trees"],deleteRef:["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],getBlob:["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],getCommit:["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],getRef:["GET /repos/{owner}/{repo}/git/ref/{ref}"],getTag:["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],getTree:["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],listMatchingRefs:["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],updateRef:["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]},gitignore:{getAllTemplates:["GET /gitignore/templates"],getTemplate:["GET /gitignore/templates/{name}"]},hostedCompute:{createNetworkConfigurationForOrg:["POST /orgs/{org}/settings/network-configurations"],deleteNetworkConfigurationFromOrg:["DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}"],getNetworkConfigurationForOrg:["GET /orgs/{org}/settings/network-configurations/{network_configuration_id}"],getNetworkSettingsForOrg:["GET /orgs/{org}/settings/network-settings/{network_settings_id}"],listNetworkConfigurationsForOrg:["GET /orgs/{org}/settings/network-configurations"],updateNetworkConfigurationForOrg:["PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}"]},interactions:{getRestrictionsForAuthenticatedUser:["GET /user/interaction-limits"],getRestrictionsForOrg:["GET /orgs/{org}/interaction-limits"],getRestrictionsForRepo:["GET /repos/{owner}/{repo}/interaction-limits"],getRestrictionsForYourPublicRepos:["GET /user/interaction-limits",{},{renamed:["interactions","getRestrictionsForAuthenticatedUser"]}],removeRestrictionsForAuthenticatedUser:["DELETE /user/interaction-limits"],removeRestrictionsForOrg:["DELETE /orgs/{org}/interaction-limits"],removeRestrictionsForRepo:["DELETE /repos/{owner}/{repo}/interaction-limits"],removeRestrictionsForYourPublicRepos:["DELETE /user/interaction-limits",{},{renamed:["interactions","removeRestrictionsForAuthenticatedUser"]}],setRestrictionsForAuthenticatedUser:["PUT /user/interaction-limits"],setRestrictionsForOrg:["PUT /orgs/{org}/interaction-limits"],setRestrictionsForRepo:["PUT /repos/{owner}/{repo}/interaction-limits"],setRestrictionsForYourPublicRepos:["PUT /user/interaction-limits",{},{renamed:["interactions","setRestrictionsForAuthenticatedUser"]}]},issues:{addAssignees:["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"],addBlockedByDependency:["POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by"],addLabels:["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],addSubIssue:["POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"],checkUserCanBeAssigned:["GET /repos/{owner}/{repo}/assignees/{assignee}"],checkUserCanBeAssignedToIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}"],create:["POST /repos/{owner}/{repo}/issues"],createComment:["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"],createLabel:["POST /repos/{owner}/{repo}/labels"],createMilestone:["POST /repos/{owner}/{repo}/milestones"],deleteComment:["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"],deleteLabel:["DELETE /repos/{owner}/{repo}/labels/{name}"],deleteMilestone:["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"],get:["GET /repos/{owner}/{repo}/issues/{issue_number}"],getComment:["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],getEvent:["GET /repos/{owner}/{repo}/issues/events/{event_id}"],getLabel:["GET /repos/{owner}/{repo}/labels/{name}"],getMilestone:["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],getParent:["GET /repos/{owner}/{repo}/issues/{issue_number}/parent"],list:["GET /issues"],listAssignees:["GET /repos/{owner}/{repo}/assignees"],listComments:["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],listCommentsForRepo:["GET /repos/{owner}/{repo}/issues/comments"],listDependenciesBlockedBy:["GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by"],listDependenciesBlocking:["GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking"],listEvents:["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],listEventsForRepo:["GET /repos/{owner}/{repo}/issues/events"],listEventsForTimeline:["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"],listForAuthenticatedUser:["GET /user/issues"],listForOrg:["GET /orgs/{org}/issues"],listForRepo:["GET /repos/{owner}/{repo}/issues"],listLabelsForMilestone:["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"],listLabelsForRepo:["GET /repos/{owner}/{repo}/labels"],listLabelsOnIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"],listMilestones:["GET /repos/{owner}/{repo}/milestones"],listSubIssues:["GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"],lock:["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],removeAllLabels:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"],removeAssignees:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"],removeDependencyBlockedBy:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}"],removeLabel:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"],removeSubIssue:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue"],reprioritizeSubIssue:["PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority"],setLabels:["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],unlock:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],update:["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],updateComment:["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],updateLabel:["PATCH /repos/{owner}/{repo}/labels/{name}"],updateMilestone:["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"]},licenses:{get:["GET /licenses/{license}"],getAllCommonlyUsed:["GET /licenses"],getForRepo:["GET /repos/{owner}/{repo}/license"]},markdown:{render:["POST /markdown"],renderRaw:["POST /markdown/raw",{headers:{"content-type":"text/plain; charset=utf-8"}}]},meta:{get:["GET /meta"],getAllVersions:["GET /versions"],getOctocat:["GET /octocat"],getZen:["GET /zen"],root:["GET /"]},migrations:{deleteArchiveForAuthenticatedUser:["DELETE /user/migrations/{migration_id}/archive"],deleteArchiveForOrg:["DELETE /orgs/{org}/migrations/{migration_id}/archive"],downloadArchiveForOrg:["GET /orgs/{org}/migrations/{migration_id}/archive"],getArchiveForAuthenticatedUser:["GET /user/migrations/{migration_id}/archive"],getStatusForAuthenticatedUser:["GET /user/migrations/{migration_id}"],getStatusForOrg:["GET /orgs/{org}/migrations/{migration_id}"],listForAuthenticatedUser:["GET /user/migrations"],listForOrg:["GET /orgs/{org}/migrations"],listReposForAuthenticatedUser:["GET /user/migrations/{migration_id}/repositories"],listReposForOrg:["GET /orgs/{org}/migrations/{migration_id}/repositories"],listReposForUser:["GET /user/migrations/{migration_id}/repositories",{},{renamed:["migrations","listReposForAuthenticatedUser"]}],startForAuthenticatedUser:["POST /user/migrations"],startForOrg:["POST /orgs/{org}/migrations"],unlockRepoForAuthenticatedUser:["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"],unlockRepoForOrg:["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"]},oidc:{getOidcCustomSubTemplateForOrg:["GET /orgs/{org}/actions/oidc/customization/sub"],updateOidcCustomSubTemplateForOrg:["PUT /orgs/{org}/actions/oidc/customization/sub"]},orgs:{addSecurityManagerTeam:["PUT /orgs/{org}/security-managers/teams/{team_slug}",{},{deprecated:"octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team"}],assignTeamToOrgRole:["PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"],assignUserToOrgRole:["PUT /orgs/{org}/organization-roles/users/{username}/{role_id}"],blockUser:["PUT /orgs/{org}/blocks/{username}"],cancelInvitation:["DELETE /orgs/{org}/invitations/{invitation_id}"],checkBlockedUser:["GET /orgs/{org}/blocks/{username}"],checkMembershipForUser:["GET /orgs/{org}/members/{username}"],checkPublicMembershipForUser:["GET /orgs/{org}/public_members/{username}"],convertMemberToOutsideCollaborator:["PUT /orgs/{org}/outside_collaborators/{username}"],createArtifactStorageRecord:["POST /orgs/{org}/artifacts/metadata/storage-record"],createInvitation:["POST /orgs/{org}/invitations"],createIssueType:["POST /orgs/{org}/issue-types"],createWebhook:["POST /orgs/{org}/hooks"],customPropertiesForOrgsCreateOrUpdateOrganizationValues:["PATCH /organizations/{org}/org-properties/values"],customPropertiesForOrgsGetOrganizationValues:["GET /organizations/{org}/org-properties/values"],customPropertiesForReposCreateOrUpdateOrganizationDefinition:["PUT /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposCreateOrUpdateOrganizationDefinitions:["PATCH /orgs/{org}/properties/schema"],customPropertiesForReposCreateOrUpdateOrganizationValues:["PATCH /orgs/{org}/properties/values"],customPropertiesForReposDeleteOrganizationDefinition:["DELETE /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposGetOrganizationDefinition:["GET /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposGetOrganizationDefinitions:["GET /orgs/{org}/properties/schema"],customPropertiesForReposGetOrganizationValues:["GET /orgs/{org}/properties/values"],delete:["DELETE /orgs/{org}"],deleteAttestationsBulk:["POST /orgs/{org}/attestations/delete-request"],deleteAttestationsById:["DELETE /orgs/{org}/attestations/{attestation_id}"],deleteAttestationsBySubjectDigest:["DELETE /orgs/{org}/attestations/digest/{subject_digest}"],deleteIssueType:["DELETE /orgs/{org}/issue-types/{issue_type_id}"],deleteWebhook:["DELETE /orgs/{org}/hooks/{hook_id}"],disableSelectedRepositoryImmutableReleasesOrganization:["DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}"],enableSelectedRepositoryImmutableReleasesOrganization:["PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}"],get:["GET /orgs/{org}"],getImmutableReleasesSettings:["GET /orgs/{org}/settings/immutable-releases"],getImmutableReleasesSettingsRepositories:["GET /orgs/{org}/settings/immutable-releases/repositories"],getMembershipForAuthenticatedUser:["GET /user/memberships/orgs/{org}"],getMembershipForUser:["GET /orgs/{org}/memberships/{username}"],getOrgRole:["GET /orgs/{org}/organization-roles/{role_id}"],getOrgRulesetHistory:["GET /orgs/{org}/rulesets/{ruleset_id}/history"],getOrgRulesetVersion:["GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}"],getWebhook:["GET /orgs/{org}/hooks/{hook_id}"],getWebhookConfigForOrg:["GET /orgs/{org}/hooks/{hook_id}/config"],getWebhookDelivery:["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"],list:["GET /organizations"],listAppInstallations:["GET /orgs/{org}/installations"],listArtifactStorageRecords:["GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records"],listAttestationRepositories:["GET /orgs/{org}/attestations/repositories"],listAttestations:["GET /orgs/{org}/attestations/{subject_digest}"],listAttestationsBulk:["POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}"],listBlockedUsers:["GET /orgs/{org}/blocks"],listFailedInvitations:["GET /orgs/{org}/failed_invitations"],listForAuthenticatedUser:["GET /user/orgs"],listForUser:["GET /users/{username}/orgs"],listInvitationTeams:["GET /orgs/{org}/invitations/{invitation_id}/teams"],listIssueTypes:["GET /orgs/{org}/issue-types"],listMembers:["GET /orgs/{org}/members"],listMembershipsForAuthenticatedUser:["GET /user/memberships/orgs"],listOrgRoleTeams:["GET /orgs/{org}/organization-roles/{role_id}/teams"],listOrgRoleUsers:["GET /orgs/{org}/organization-roles/{role_id}/users"],listOrgRoles:["GET /orgs/{org}/organization-roles"],listOrganizationFineGrainedPermissions:["GET /orgs/{org}/organization-fine-grained-permissions"],listOutsideCollaborators:["GET /orgs/{org}/outside_collaborators"],listPatGrantRepositories:["GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories"],listPatGrantRequestRepositories:["GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories"],listPatGrantRequests:["GET /orgs/{org}/personal-access-token-requests"],listPatGrants:["GET /orgs/{org}/personal-access-tokens"],listPendingInvitations:["GET /orgs/{org}/invitations"],listPublicMembers:["GET /orgs/{org}/public_members"],listSecurityManagerTeams:["GET /orgs/{org}/security-managers",{},{deprecated:"octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams"}],listWebhookDeliveries:["GET /orgs/{org}/hooks/{hook_id}/deliveries"],listWebhooks:["GET /orgs/{org}/hooks"],pingWebhook:["POST /orgs/{org}/hooks/{hook_id}/pings"],redeliverWebhookDelivery:["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],removeMember:["DELETE /orgs/{org}/members/{username}"],removeMembershipForUser:["DELETE /orgs/{org}/memberships/{username}"],removeOutsideCollaborator:["DELETE /orgs/{org}/outside_collaborators/{username}"],removePublicMembershipForAuthenticatedUser:["DELETE /orgs/{org}/public_members/{username}"],removeSecurityManagerTeam:["DELETE /orgs/{org}/security-managers/teams/{team_slug}",{},{deprecated:"octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team"}],reviewPatGrantRequest:["POST /orgs/{org}/personal-access-token-requests/{pat_request_id}"],reviewPatGrantRequestsInBulk:["POST /orgs/{org}/personal-access-token-requests"],revokeAllOrgRolesTeam:["DELETE /orgs/{org}/organization-roles/teams/{team_slug}"],revokeAllOrgRolesUser:["DELETE /orgs/{org}/organization-roles/users/{username}"],revokeOrgRoleTeam:["DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"],revokeOrgRoleUser:["DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}"],setImmutableReleasesSettings:["PUT /orgs/{org}/settings/immutable-releases"],setImmutableReleasesSettingsRepositories:["PUT /orgs/{org}/settings/immutable-releases/repositories"],setMembershipForUser:["PUT /orgs/{org}/memberships/{username}"],setPublicMembershipForAuthenticatedUser:["PUT /orgs/{org}/public_members/{username}"],unblockUser:["DELETE /orgs/{org}/blocks/{username}"],update:["PATCH /orgs/{org}"],updateIssueType:["PUT /orgs/{org}/issue-types/{issue_type_id}"],updateMembershipForAuthenticatedUser:["PATCH /user/memberships/orgs/{org}"],updatePatAccess:["POST /orgs/{org}/personal-access-tokens/{pat_id}"],updatePatAccesses:["POST /orgs/{org}/personal-access-tokens"],updateWebhook:["PATCH /orgs/{org}/hooks/{hook_id}"],updateWebhookConfigForOrg:["PATCH /orgs/{org}/hooks/{hook_id}/config"]},packages:{deletePackageForAuthenticatedUser:["DELETE /user/packages/{package_type}/{package_name}"],deletePackageForOrg:["DELETE /orgs/{org}/packages/{package_type}/{package_name}"],deletePackageForUser:["DELETE /users/{username}/packages/{package_type}/{package_name}"],deletePackageVersionForAuthenticatedUser:["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],deletePackageVersionForOrg:["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],deletePackageVersionForUser:["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],getAllPackageVersionsForAPackageOwnedByAnOrg:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions",{},{renamed:["packages","getAllPackageVersionsForPackageOwnedByOrg"]}],getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions",{},{renamed:["packages","getAllPackageVersionsForPackageOwnedByAuthenticatedUser"]}],getAllPackageVersionsForPackageOwnedByAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions"],getAllPackageVersionsForPackageOwnedByOrg:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"],getAllPackageVersionsForPackageOwnedByUser:["GET /users/{username}/packages/{package_type}/{package_name}/versions"],getPackageForAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}"],getPackageForOrganization:["GET /orgs/{org}/packages/{package_type}/{package_name}"],getPackageForUser:["GET /users/{username}/packages/{package_type}/{package_name}"],getPackageVersionForAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],getPackageVersionForOrganization:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],getPackageVersionForUser:["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],listDockerMigrationConflictingPackagesForAuthenticatedUser:["GET /user/docker/conflicts"],listDockerMigrationConflictingPackagesForOrganization:["GET /orgs/{org}/docker/conflicts"],listDockerMigrationConflictingPackagesForUser:["GET /users/{username}/docker/conflicts"],listPackagesForAuthenticatedUser:["GET /user/packages"],listPackagesForOrganization:["GET /orgs/{org}/packages"],listPackagesForUser:["GET /users/{username}/packages"],restorePackageForAuthenticatedUser:["POST /user/packages/{package_type}/{package_name}/restore{?token}"],restorePackageForOrg:["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"],restorePackageForUser:["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"],restorePackageVersionForAuthenticatedUser:["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],restorePackageVersionForOrg:["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],restorePackageVersionForUser:["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"]},privateRegistries:{createOrgPrivateRegistry:["POST /orgs/{org}/private-registries"],deleteOrgPrivateRegistry:["DELETE /orgs/{org}/private-registries/{secret_name}"],getOrgPrivateRegistry:["GET /orgs/{org}/private-registries/{secret_name}"],getOrgPublicKey:["GET /orgs/{org}/private-registries/public-key"],listOrgPrivateRegistries:["GET /orgs/{org}/private-registries"],updateOrgPrivateRegistry:["PATCH /orgs/{org}/private-registries/{secret_name}"]},projects:{addItemForOrg:["POST /orgs/{org}/projectsV2/{project_number}/items"],addItemForUser:["POST /users/{username}/projectsV2/{project_number}/items"],deleteItemForOrg:["DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],deleteItemForUser:["DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}"],getFieldForOrg:["GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}"],getFieldForUser:["GET /users/{username}/projectsV2/{project_number}/fields/{field_id}"],getForOrg:["GET /orgs/{org}/projectsV2/{project_number}"],getForUser:["GET /users/{username}/projectsV2/{project_number}"],getOrgItem:["GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],getUserItem:["GET /users/{username}/projectsV2/{project_number}/items/{item_id}"],listFieldsForOrg:["GET /orgs/{org}/projectsV2/{project_number}/fields"],listFieldsForUser:["GET /users/{username}/projectsV2/{project_number}/fields"],listForOrg:["GET /orgs/{org}/projectsV2"],listForUser:["GET /users/{username}/projectsV2"],listItemsForOrg:["GET /orgs/{org}/projectsV2/{project_number}/items"],listItemsForUser:["GET /users/{username}/projectsV2/{project_number}/items"],updateItemForOrg:["PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],updateItemForUser:["PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}"]},pulls:{checkIfMerged:["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],create:["POST /repos/{owner}/{repo}/pulls"],createReplyForReviewComment:["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"],createReview:["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],createReviewComment:["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"],deletePendingReview:["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],deleteReviewComment:["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"],dismissReview:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"],get:["GET /repos/{owner}/{repo}/pulls/{pull_number}"],getReview:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],getReviewComment:["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],list:["GET /repos/{owner}/{repo}/pulls"],listCommentsForReview:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"],listCommits:["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],listFiles:["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],listRequestedReviewers:["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],listReviewComments:["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"],listReviewCommentsForRepo:["GET /repos/{owner}/{repo}/pulls/comments"],listReviews:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],merge:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],removeRequestedReviewers:["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],requestReviewers:["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],submitReview:["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"],update:["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],updateBranch:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"],updateReview:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],updateReviewComment:["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"]},rateLimit:{get:["GET /rate_limit"]},reactions:{createForCommitComment:["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"],createForIssue:["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"],createForIssueComment:["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],createForPullRequestReviewComment:["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],createForRelease:["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"],createForTeamDiscussionCommentInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],createForTeamDiscussionInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"],deleteForCommitComment:["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"],deleteForIssue:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"],deleteForIssueComment:["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"],deleteForPullRequestComment:["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"],deleteForRelease:["DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}"],deleteForTeamDiscussion:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"],deleteForTeamDiscussionComment:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"],listForCommitComment:["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"],listForIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"],listForIssueComment:["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],listForPullRequestReviewComment:["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],listForRelease:["GET /repos/{owner}/{repo}/releases/{release_id}/reactions"],listForTeamDiscussionCommentInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],listForTeamDiscussionInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"]},repos:{acceptInvitation:["PATCH /user/repository_invitations/{invitation_id}",{},{renamed:["repos","acceptInvitationForAuthenticatedUser"]}],acceptInvitationForAuthenticatedUser:["PATCH /user/repository_invitations/{invitation_id}"],addAppAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],addCollaborator:["PUT /repos/{owner}/{repo}/collaborators/{username}"],addStatusCheckContexts:["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],addTeamAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],addUserAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],cancelPagesDeployment:["POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel"],checkAutomatedSecurityFixes:["GET /repos/{owner}/{repo}/automated-security-fixes"],checkCollaborator:["GET /repos/{owner}/{repo}/collaborators/{username}"],checkImmutableReleases:["GET /repos/{owner}/{repo}/immutable-releases"],checkPrivateVulnerabilityReporting:["GET /repos/{owner}/{repo}/private-vulnerability-reporting"],checkVulnerabilityAlerts:["GET /repos/{owner}/{repo}/vulnerability-alerts"],codeownersErrors:["GET /repos/{owner}/{repo}/codeowners/errors"],compareCommits:["GET /repos/{owner}/{repo}/compare/{base}...{head}"],compareCommitsWithBasehead:["GET /repos/{owner}/{repo}/compare/{basehead}"],createAttestation:["POST /repos/{owner}/{repo}/attestations"],createAutolink:["POST /repos/{owner}/{repo}/autolinks"],createCommitComment:["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"],createCommitSignatureProtection:["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],createCommitStatus:["POST /repos/{owner}/{repo}/statuses/{sha}"],createDeployKey:["POST /repos/{owner}/{repo}/keys"],createDeployment:["POST /repos/{owner}/{repo}/deployments"],createDeploymentBranchPolicy:["POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"],createDeploymentProtectionRule:["POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"],createDeploymentStatus:["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],createDispatchEvent:["POST /repos/{owner}/{repo}/dispatches"],createForAuthenticatedUser:["POST /user/repos"],createFork:["POST /repos/{owner}/{repo}/forks"],createInOrg:["POST /orgs/{org}/repos"],createOrUpdateEnvironment:["PUT /repos/{owner}/{repo}/environments/{environment_name}"],createOrUpdateFileContents:["PUT /repos/{owner}/{repo}/contents/{path}"],createOrgRuleset:["POST /orgs/{org}/rulesets"],createPagesDeployment:["POST /repos/{owner}/{repo}/pages/deployments"],createPagesSite:["POST /repos/{owner}/{repo}/pages"],createRelease:["POST /repos/{owner}/{repo}/releases"],createRepoRuleset:["POST /repos/{owner}/{repo}/rulesets"],createUsingTemplate:["POST /repos/{template_owner}/{template_repo}/generate"],createWebhook:["POST /repos/{owner}/{repo}/hooks"],customPropertiesForReposCreateOrUpdateRepositoryValues:["PATCH /repos/{owner}/{repo}/properties/values"],customPropertiesForReposGetRepositoryValues:["GET /repos/{owner}/{repo}/properties/values"],declineInvitation:["DELETE /user/repository_invitations/{invitation_id}",{},{renamed:["repos","declineInvitationForAuthenticatedUser"]}],declineInvitationForAuthenticatedUser:["DELETE /user/repository_invitations/{invitation_id}"],delete:["DELETE /repos/{owner}/{repo}"],deleteAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],deleteAdminBranchProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],deleteAnEnvironment:["DELETE /repos/{owner}/{repo}/environments/{environment_name}"],deleteAutolink:["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"],deleteBranchProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"],deleteCommitComment:["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],deleteCommitSignatureProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],deleteDeployKey:["DELETE /repos/{owner}/{repo}/keys/{key_id}"],deleteDeployment:["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"],deleteDeploymentBranchPolicy:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],deleteFile:["DELETE /repos/{owner}/{repo}/contents/{path}"],deleteInvitation:["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"],deleteOrgRuleset:["DELETE /orgs/{org}/rulesets/{ruleset_id}"],deletePagesSite:["DELETE /repos/{owner}/{repo}/pages"],deletePullRequestReviewProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],deleteRelease:["DELETE /repos/{owner}/{repo}/releases/{release_id}"],deleteReleaseAsset:["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"],deleteRepoRuleset:["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"],deleteWebhook:["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],disableAutomatedSecurityFixes:["DELETE /repos/{owner}/{repo}/automated-security-fixes"],disableDeploymentProtectionRule:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"],disableImmutableReleases:["DELETE /repos/{owner}/{repo}/immutable-releases"],disablePrivateVulnerabilityReporting:["DELETE /repos/{owner}/{repo}/private-vulnerability-reporting"],disableVulnerabilityAlerts:["DELETE /repos/{owner}/{repo}/vulnerability-alerts"],downloadArchive:["GET /repos/{owner}/{repo}/zipball/{ref}",{},{renamed:["repos","downloadZipballArchive"]}],downloadTarballArchive:["GET /repos/{owner}/{repo}/tarball/{ref}"],downloadZipballArchive:["GET /repos/{owner}/{repo}/zipball/{ref}"],enableAutomatedSecurityFixes:["PUT /repos/{owner}/{repo}/automated-security-fixes"],enableImmutableReleases:["PUT /repos/{owner}/{repo}/immutable-releases"],enablePrivateVulnerabilityReporting:["PUT /repos/{owner}/{repo}/private-vulnerability-reporting"],enableVulnerabilityAlerts:["PUT /repos/{owner}/{repo}/vulnerability-alerts"],generateReleaseNotes:["POST /repos/{owner}/{repo}/releases/generate-notes"],get:["GET /repos/{owner}/{repo}"],getAccessRestrictions:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],getAdminBranchProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],getAllDeploymentProtectionRules:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"],getAllEnvironments:["GET /repos/{owner}/{repo}/environments"],getAllStatusCheckContexts:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"],getAllTopics:["GET /repos/{owner}/{repo}/topics"],getAppsWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"],getAutolink:["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"],getBranch:["GET /repos/{owner}/{repo}/branches/{branch}"],getBranchProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection"],getBranchRules:["GET /repos/{owner}/{repo}/rules/branches/{branch}"],getClones:["GET /repos/{owner}/{repo}/traffic/clones"],getCodeFrequencyStats:["GET /repos/{owner}/{repo}/stats/code_frequency"],getCollaboratorPermissionLevel:["GET /repos/{owner}/{repo}/collaborators/{username}/permission"],getCombinedStatusForRef:["GET /repos/{owner}/{repo}/commits/{ref}/status"],getCommit:["GET /repos/{owner}/{repo}/commits/{ref}"],getCommitActivityStats:["GET /repos/{owner}/{repo}/stats/commit_activity"],getCommitComment:["GET /repos/{owner}/{repo}/comments/{comment_id}"],getCommitSignatureProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],getCommunityProfileMetrics:["GET /repos/{owner}/{repo}/community/profile"],getContent:["GET /repos/{owner}/{repo}/contents/{path}"],getContributorsStats:["GET /repos/{owner}/{repo}/stats/contributors"],getCustomDeploymentProtectionRule:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"],getDeployKey:["GET /repos/{owner}/{repo}/keys/{key_id}"],getDeployment:["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],getDeploymentBranchPolicy:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],getDeploymentStatus:["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"],getEnvironment:["GET /repos/{owner}/{repo}/environments/{environment_name}"],getLatestPagesBuild:["GET /repos/{owner}/{repo}/pages/builds/latest"],getLatestRelease:["GET /repos/{owner}/{repo}/releases/latest"],getOrgRuleSuite:["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"],getOrgRuleSuites:["GET /orgs/{org}/rulesets/rule-suites"],getOrgRuleset:["GET /orgs/{org}/rulesets/{ruleset_id}"],getOrgRulesets:["GET /orgs/{org}/rulesets"],getPages:["GET /repos/{owner}/{repo}/pages"],getPagesBuild:["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],getPagesDeployment:["GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}"],getPagesHealthCheck:["GET /repos/{owner}/{repo}/pages/health"],getParticipationStats:["GET /repos/{owner}/{repo}/stats/participation"],getPullRequestReviewProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],getPunchCardStats:["GET /repos/{owner}/{repo}/stats/punch_card"],getReadme:["GET /repos/{owner}/{repo}/readme"],getReadmeInDirectory:["GET /repos/{owner}/{repo}/readme/{dir}"],getRelease:["GET /repos/{owner}/{repo}/releases/{release_id}"],getReleaseAsset:["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],getReleaseByTag:["GET /repos/{owner}/{repo}/releases/tags/{tag}"],getRepoRuleSuite:["GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}"],getRepoRuleSuites:["GET /repos/{owner}/{repo}/rulesets/rule-suites"],getRepoRuleset:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"],getRepoRulesetHistory:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history"],getRepoRulesetVersion:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}"],getRepoRulesets:["GET /repos/{owner}/{repo}/rulesets"],getStatusChecksProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],getTeamsWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"],getTopPaths:["GET /repos/{owner}/{repo}/traffic/popular/paths"],getTopReferrers:["GET /repos/{owner}/{repo}/traffic/popular/referrers"],getUsersWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"],getViews:["GET /repos/{owner}/{repo}/traffic/views"],getWebhook:["GET /repos/{owner}/{repo}/hooks/{hook_id}"],getWebhookConfigForRepo:["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"],getWebhookDelivery:["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"],listActivities:["GET /repos/{owner}/{repo}/activity"],listAttestations:["GET /repos/{owner}/{repo}/attestations/{subject_digest}"],listAutolinks:["GET /repos/{owner}/{repo}/autolinks"],listBranches:["GET /repos/{owner}/{repo}/branches"],listBranchesForHeadCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"],listCollaborators:["GET /repos/{owner}/{repo}/collaborators"],listCommentsForCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"],listCommitCommentsForRepo:["GET /repos/{owner}/{repo}/comments"],listCommitStatusesForRef:["GET /repos/{owner}/{repo}/commits/{ref}/statuses"],listCommits:["GET /repos/{owner}/{repo}/commits"],listContributors:["GET /repos/{owner}/{repo}/contributors"],listCustomDeploymentRuleIntegrations:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps"],listDeployKeys:["GET /repos/{owner}/{repo}/keys"],listDeploymentBranchPolicies:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"],listDeploymentStatuses:["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],listDeployments:["GET /repos/{owner}/{repo}/deployments"],listForAuthenticatedUser:["GET /user/repos"],listForOrg:["GET /orgs/{org}/repos"],listForUser:["GET /users/{username}/repos"],listForks:["GET /repos/{owner}/{repo}/forks"],listInvitations:["GET /repos/{owner}/{repo}/invitations"],listInvitationsForAuthenticatedUser:["GET /user/repository_invitations"],listLanguages:["GET /repos/{owner}/{repo}/languages"],listPagesBuilds:["GET /repos/{owner}/{repo}/pages/builds"],listPublic:["GET /repositories"],listPullRequestsAssociatedWithCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"],listReleaseAssets:["GET /repos/{owner}/{repo}/releases/{release_id}/assets"],listReleases:["GET /repos/{owner}/{repo}/releases"],listTags:["GET /repos/{owner}/{repo}/tags"],listTeams:["GET /repos/{owner}/{repo}/teams"],listWebhookDeliveries:["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"],listWebhooks:["GET /repos/{owner}/{repo}/hooks"],merge:["POST /repos/{owner}/{repo}/merges"],mergeUpstream:["POST /repos/{owner}/{repo}/merge-upstream"],pingWebhook:["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],redeliverWebhookDelivery:["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],removeAppAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],removeCollaborator:["DELETE /repos/{owner}/{repo}/collaborators/{username}"],removeStatusCheckContexts:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],removeStatusCheckProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],removeTeamAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],removeUserAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],renameBranch:["POST /repos/{owner}/{repo}/branches/{branch}/rename"],replaceAllTopics:["PUT /repos/{owner}/{repo}/topics"],requestPagesBuild:["POST /repos/{owner}/{repo}/pages/builds"],setAdminBranchProtection:["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],setAppAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],setStatusCheckContexts:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],setTeamAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],setUserAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],testPushWebhook:["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],transfer:["POST /repos/{owner}/{repo}/transfer"],update:["PATCH /repos/{owner}/{repo}"],updateBranchProtection:["PUT /repos/{owner}/{repo}/branches/{branch}/protection"],updateCommitComment:["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],updateDeploymentBranchPolicy:["PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],updateInformationAboutPagesSite:["PUT /repos/{owner}/{repo}/pages"],updateInvitation:["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"],updateOrgRuleset:["PUT /orgs/{org}/rulesets/{ruleset_id}"],updatePullRequestReviewProtection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],updateRelease:["PATCH /repos/{owner}/{repo}/releases/{release_id}"],updateReleaseAsset:["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"],updateRepoRuleset:["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"],updateStatusCheckPotection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks",{},{renamed:["repos","updateStatusCheckProtection"]}],updateStatusCheckProtection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],updateWebhook:["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],updateWebhookConfigForRepo:["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"],uploadReleaseAsset:["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}",{baseUrl:"https://uploads.github.com"}]},search:{code:["GET /search/code"],commits:["GET /search/commits"],issuesAndPullRequests:["GET /search/issues"],labels:["GET /search/labels"],repos:["GET /search/repositories"],topics:["GET /search/topics"],users:["GET /search/users"]},secretScanning:{createPushProtectionBypass:["POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses"],getAlert:["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],getScanHistory:["GET /repos/{owner}/{repo}/secret-scanning/scan-history"],listAlertsForOrg:["GET /orgs/{org}/secret-scanning/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/secret-scanning/alerts"],listLocationsForAlert:["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"],listOrgPatternConfigs:["GET /orgs/{org}/secret-scanning/pattern-configurations"],updateAlert:["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],updateOrgPatternConfigs:["PATCH /orgs/{org}/secret-scanning/pattern-configurations"]},securityAdvisories:{createFork:["POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks"],createPrivateVulnerabilityReport:["POST /repos/{owner}/{repo}/security-advisories/reports"],createRepositoryAdvisory:["POST /repos/{owner}/{repo}/security-advisories"],createRepositoryAdvisoryCveRequest:["POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve"],getGlobalAdvisory:["GET /advisories/{ghsa_id}"],getRepositoryAdvisory:["GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}"],listGlobalAdvisories:["GET /advisories"],listOrgRepositoryAdvisories:["GET /orgs/{org}/security-advisories"],listRepositoryAdvisories:["GET /repos/{owner}/{repo}/security-advisories"],updateRepositoryAdvisory:["PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}"]},teams:{addOrUpdateMembershipForUserInOrg:["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"],addOrUpdateRepoPermissionsInOrg:["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],checkPermissionsForRepoInOrg:["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],create:["POST /orgs/{org}/teams"],createDiscussionCommentInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],createDiscussionInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions"],deleteDiscussionCommentInOrg:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],deleteDiscussionInOrg:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],deleteInOrg:["DELETE /orgs/{org}/teams/{team_slug}"],getByName:["GET /orgs/{org}/teams/{team_slug}"],getDiscussionCommentInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],getDiscussionInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],getMembershipForUserInOrg:["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"],list:["GET /orgs/{org}/teams"],listChildInOrg:["GET /orgs/{org}/teams/{team_slug}/teams"],listDiscussionCommentsInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],listDiscussionsInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions"],listForAuthenticatedUser:["GET /user/teams"],listMembersInOrg:["GET /orgs/{org}/teams/{team_slug}/members"],listPendingInvitationsInOrg:["GET /orgs/{org}/teams/{team_slug}/invitations"],listReposInOrg:["GET /orgs/{org}/teams/{team_slug}/repos"],removeMembershipForUserInOrg:["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"],removeRepoInOrg:["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],updateDiscussionCommentInOrg:["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],updateDiscussionInOrg:["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],updateInOrg:["PATCH /orgs/{org}/teams/{team_slug}"]},users:{addEmailForAuthenticated:["POST /user/emails",{},{renamed:["users","addEmailForAuthenticatedUser"]}],addEmailForAuthenticatedUser:["POST /user/emails"],addSocialAccountForAuthenticatedUser:["POST /user/social_accounts"],block:["PUT /user/blocks/{username}"],checkBlocked:["GET /user/blocks/{username}"],checkFollowingForUser:["GET /users/{username}/following/{target_user}"],checkPersonIsFollowedByAuthenticated:["GET /user/following/{username}"],createGpgKeyForAuthenticated:["POST /user/gpg_keys",{},{renamed:["users","createGpgKeyForAuthenticatedUser"]}],createGpgKeyForAuthenticatedUser:["POST /user/gpg_keys"],createPublicSshKeyForAuthenticated:["POST /user/keys",{},{renamed:["users","createPublicSshKeyForAuthenticatedUser"]}],createPublicSshKeyForAuthenticatedUser:["POST /user/keys"],createSshSigningKeyForAuthenticatedUser:["POST /user/ssh_signing_keys"],deleteAttestationsBulk:["POST /users/{username}/attestations/delete-request"],deleteAttestationsById:["DELETE /users/{username}/attestations/{attestation_id}"],deleteAttestationsBySubjectDigest:["DELETE /users/{username}/attestations/digest/{subject_digest}"],deleteEmailForAuthenticated:["DELETE /user/emails",{},{renamed:["users","deleteEmailForAuthenticatedUser"]}],deleteEmailForAuthenticatedUser:["DELETE /user/emails"],deleteGpgKeyForAuthenticated:["DELETE /user/gpg_keys/{gpg_key_id}",{},{renamed:["users","deleteGpgKeyForAuthenticatedUser"]}],deleteGpgKeyForAuthenticatedUser:["DELETE /user/gpg_keys/{gpg_key_id}"],deletePublicSshKeyForAuthenticated:["DELETE /user/keys/{key_id}",{},{renamed:["users","deletePublicSshKeyForAuthenticatedUser"]}],deletePublicSshKeyForAuthenticatedUser:["DELETE /user/keys/{key_id}"],deleteSocialAccountForAuthenticatedUser:["DELETE /user/social_accounts"],deleteSshSigningKeyForAuthenticatedUser:["DELETE /user/ssh_signing_keys/{ssh_signing_key_id}"],follow:["PUT /user/following/{username}"],getAuthenticated:["GET /user"],getById:["GET /user/{account_id}"],getByUsername:["GET /users/{username}"],getContextForUser:["GET /users/{username}/hovercard"],getGpgKeyForAuthenticated:["GET /user/gpg_keys/{gpg_key_id}",{},{renamed:["users","getGpgKeyForAuthenticatedUser"]}],getGpgKeyForAuthenticatedUser:["GET /user/gpg_keys/{gpg_key_id}"],getPublicSshKeyForAuthenticated:["GET /user/keys/{key_id}",{},{renamed:["users","getPublicSshKeyForAuthenticatedUser"]}],getPublicSshKeyForAuthenticatedUser:["GET /user/keys/{key_id}"],getSshSigningKeyForAuthenticatedUser:["GET /user/ssh_signing_keys/{ssh_signing_key_id}"],list:["GET /users"],listAttestations:["GET /users/{username}/attestations/{subject_digest}"],listAttestationsBulk:["POST /users/{username}/attestations/bulk-list{?per_page,before,after}"],listBlockedByAuthenticated:["GET /user/blocks",{},{renamed:["users","listBlockedByAuthenticatedUser"]}],listBlockedByAuthenticatedUser:["GET /user/blocks"],listEmailsForAuthenticated:["GET /user/emails",{},{renamed:["users","listEmailsForAuthenticatedUser"]}],listEmailsForAuthenticatedUser:["GET /user/emails"],listFollowedByAuthenticated:["GET /user/following",{},{renamed:["users","listFollowedByAuthenticatedUser"]}],listFollowedByAuthenticatedUser:["GET /user/following"],listFollowersForAuthenticatedUser:["GET /user/followers"],listFollowersForUser:["GET /users/{username}/followers"],listFollowingForUser:["GET /users/{username}/following"],listGpgKeysForAuthenticated:["GET /user/gpg_keys",{},{renamed:["users","listGpgKeysForAuthenticatedUser"]}],listGpgKeysForAuthenticatedUser:["GET /user/gpg_keys"],listGpgKeysForUser:["GET /users/{username}/gpg_keys"],listPublicEmailsForAuthenticated:["GET /user/public_emails",{},{renamed:["users","listPublicEmailsForAuthenticatedUser"]}],listPublicEmailsForAuthenticatedUser:["GET /user/public_emails"],listPublicKeysForUser:["GET /users/{username}/keys"],listPublicSshKeysForAuthenticated:["GET /user/keys",{},{renamed:["users","listPublicSshKeysForAuthenticatedUser"]}],listPublicSshKeysForAuthenticatedUser:["GET /user/keys"],listSocialAccountsForAuthenticatedUser:["GET /user/social_accounts"],listSocialAccountsForUser:["GET /users/{username}/social_accounts"],listSshSigningKeysForAuthenticatedUser:["GET /user/ssh_signing_keys"],listSshSigningKeysForUser:["GET /users/{username}/ssh_signing_keys"],setPrimaryEmailVisibilityForAuthenticated:["PATCH /user/email/visibility",{},{renamed:["users","setPrimaryEmailVisibilityForAuthenticatedUser"]}],setPrimaryEmailVisibilityForAuthenticatedUser:["PATCH /user/email/visibility"],unblock:["DELETE /user/blocks/{username}"],unfollow:["DELETE /user/following/{username}"],updateAuthenticated:["PATCH /user"]}},sp=JR;var Pr=new Map;for(let[e,r]of Object.entries(sp))for(let[t,n]of Object.entries(r)){let[o,s,i]=n,[a,l]=o.split(/ /),d=Object.assign({method:a,url:l},s);Pr.has(e)||Pr.set(e,new Map),Pr.get(e).set(t,{scope:e,methodName:t,endpointDefaults:d,decorations:i})}var zR={has({scope:e},r){return Pr.get(e).has(r)},getOwnPropertyDescriptor(e,r){return{value:this.get(e,r),configurable:!0,writable:!0,enumerable:!0}},defineProperty(e,r,t){return Object.defineProperty(e.cache,r,t),!0},deleteProperty(e,r){return delete e.cache[r],!0},ownKeys({scope:e}){return[...Pr.get(e).keys()]},set(e,r,t){return e.cache[r]=t},get({octokit:e,scope:r,cache:t},n){if(t[n])return t[n];let o=Pr.get(r).get(n);if(!o)return;let{endpointDefaults:s,decorations:i}=o;return i?t[n]=QR(e,r,n,s,i):t[n]=e.request.defaults(s),t[n]}};function zi(e){let r={};for(let t of Pr.keys())r[t]=new Proxy({octokit:e,scope:t,cache:{}},zR);return r}function QR(e,r,t,n,o){let s=e.request.defaults(n);function i(...a){let l=s.endpoint.merge(...a);if(o.mapToData)return l=Object.assign({},l,{data:l[o.mapToData],[o.mapToData]:void 0}),s(l);if(o.renamed){let[d,c]=o.renamed;e.log.warn(`octokit.${r}.${t}() has been renamed to octokit.${d}.${c}()`)}if(o.deprecated&&e.log.warn(o.deprecated),o.renamedParameters){let d=s.endpoint.merge(...a);for(let[c,u]of Object.entries(o.renamedParameters))c in d&&(e.log.warn(`"${c}" parameter is deprecated for "octokit.${r}.${t}()". Use "${u}" instead`),u in d||(d[u]=d[c]),delete d[c]);return s(d)}return s(...a)}return Object.assign(i,s)}function YR(e){return{rest:zi(e)}}YR.VERSION=Ji;function Qi(e){let r=zi(e);return{...r,rest:r}}Qi.VERSION=Ji;var ip="22.0.1";var ap=wo.plugin(qi,Qi,Ki).defaults({userAgent:`octokit-rest.js/${ip}`});function XR(e){return`r${e}`}function lp(e){if(e.length===0)throw new Error("an aliased single-object query needs at least one read");let r=e[0].kind;if(e.some(s=>s.kind!==r))throw new Error("an aliased single-object query may contain only one object kind");let t={},n=r==="pr"?"pullRequest":"issue";return{query:["query CoalescedSingleObjectReads {",...e.map((s,i)=>{if(!Number.isSafeInteger(s.number)||s.number<=0)throw new Error(`an aliased single-object read needs a positive number, got ${s.number}`);let a=s.selection.trim();if(a==="")throw new Error("an aliased single-object read needs a field selection");let l=XR(i);return t[l]=s,[` ${l}: repository(owner: ${JSON.stringify(s.owner)}, name: ${JSON.stringify(s.repo)}) {`,` object: ${n}(number: ${s.number}) { ${a} }`," }"].join(`
|
|
85
|
+
`)})," rateLimit { cost }","}"].join(`
|
|
86
|
+
`),aliases:t}}function dp(e,r){let t=r!==null&&typeof r=="object"?r:{},n=t.data??t,o=n!==null&&typeof n=="object"?n:{};return Object.entries(e.aliases).map(([s,i])=>{let a=o[s];if(a===null||typeof a!="object")return{read:i,value:null};let l=a.object;return{read:i,value:l!==null&&typeof l=="object"&&!Array.isArray(l)?l:null}})}var ZR=ap.plugin(Ai,yo);function cp(){let e=new Map;return{get:r=>e.get(r),set:(r,t)=>e.set(r,t)}}function up(e){if(e?.outcome!=="asked")return Number.POSITIVE_INFINITY;let r=e.pools.rest,t=e.pools.graphql;return r===null||t===null||t.remaining<=0||t.fraction<=0?Number.POSITIVE_INFINITY:r.remaining<=0||r.fraction<=0?1:!Number.isFinite(r.fraction)||!Number.isFinite(t.fraction)?Number.POSITIVE_INFINITY:Math.max(1,Math.ceil(r.fraction/t.fraction))}var ot=class extends Error{status=401;constructor(r){super("GitHub rejected the host credential; refresh the stored login with `gh auth login` or provide a current host token",r),this.name="GithubCredentialError"}};function Yi(e){let r=e.etags??cp(),t=new ZR({auth:e.token,log:{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},...e.baseUrl?{baseUrl:e.baseUrl}:{},...e.fetchImpl?{request:{fetch:e.fetchImpl}}:{},retry:{doNotRetry:[304,403,429],...e.retryCount===void 0?{}:{retries:e.retryCount}},throttle:e.throttle===!1?{enabled:!1}:{onRateLimit:()=>!1,onSecondaryRateLimit:()=>!1}}),n=async c=>{let u=r.get(c.cacheKey),m={...c.parameters??{}},f=ar(m.headers)?m.headers:{};m.headers={...f,...u?{"if-none-match":u.etag}:{}};try{let h=await t.request(c.route,m),v=h.headers,y=Eo(v,"etag");return y!==void 0&&r.set(c.cacheKey,{etag:y,data:h.data,headers:v}),await e.attribution?.record({operation:c.operation,cost:1,actor:c.actor}),{data:h.data,headers:v,quotaFree:!1}}catch(h){if(Xt(h)===304){if(u===void 0)throw new Error(`GitHub returned 304 for ${JSON.stringify(c.cacheKey)} without a held answer to reuse`,{cause:h});let v=pp(h),y={...u.headers,...v},S=Eo(y,"etag")??u.etag;return r.set(c.cacheKey,{etag:S,data:u.data,headers:y}),await e.attribution?.record({operation:c.operation,cost:0,actor:c.actor}),{data:u.data,headers:y,quotaFree:!0}}throw Xt(h)===401?new ot({cause:h}):h}},o=new Map,s=!1,i=async c=>{let u=c.input,m=u.kind==="pr";try{let f=await n({cacheKey:u.cacheKey,route:m?"GET /repos/{owner}/{repo}/pulls/{pull_number}":"GET /repos/{owner}/{repo}/issues/{issue_number}",parameters:{owner:u.owner,repo:u.repo,...m?{pull_number:u.number}:{issue_number:u.number}},operation:u.operation,actor:u.actor});c.resolve({data:u.project?u.project(f.data,"rest"):f.data,surface:"rest",quotaFree:f.quotaFree})}catch(f){c.reject(f)}},a=async c=>{try{let u=lp(c.map(({input:y})=>y)),m=await t.graphql(u.query),f=dp(u,m),h=rw(m),v=c[0].input;await e.attribution?.record({operation:{key:v.operation.key,budget:"graphql"},cost:h,actor:tw(c.map(({input:y})=>y.actor))}),f.forEach((y,S)=>{let G=c[S];y.value===null?G.reject(new Error(`GitHub returned no ${y.read.kind} #${y.read.number} from the coalesced query`)):G.resolve({data:G.input.project?G.input.project(y.value,"graphql"):y.value,surface:"graphql",quotaFree:!1})})}catch(u){let m=Xt(u)===401?new ot({cause:u}):u;c.forEach(f=>f.reject(m))}},l=async()=>{let c=null;try{c=await e.balance?.()??null}catch{}let u=up(c);s=!1;let m=[...o.values()];o.clear(),await Promise.all(m.map(async f=>{f.length>u?await a(f):await Promise.all(f.map(i))}))};return{conditionalRest:n,singleObject:c=>r.get(c.cacheKey)!==void 0?new Promise((u,m)=>{i({input:c,resolve:u,reject:m})}):new Promise((u,m)=>{let f=o.get(c.kind)??[];f.push({input:c,resolve:u,reject:m}),o.set(c.kind,f),s||(s=!0,setTimeout(()=>void l(),0))}),async conditionalPaginate(c){let u=[],m={},f=0,h=!0,v=1;for(;;){let y=await n({...c,cacheKey:`${c.cacheKey}:page:${v}`,parameters:{...c.parameters??{},per_page:100,page:v}});if(f+=1,h=h&&y.quotaFree,!Array.isArray(y.data))throw new Error(`GitHub returned a non-list body for ${JSON.stringify(c.cacheKey)} page ${v}`);if(u.push(...y.data),m=y.headers,!ew(y.headers))break;v+=1}return{data:u,headers:m,requestCount:f,quotaFree:h}},async graphql(c,u={},m){try{let f=await t.graphql(c,u);return m&&await e.attribution?.record({operation:m.operation,cost:1,actor:m.actor}),f}catch(f){throw Xt(f)===401?new ot({cause:f}):f}}}}function ew(e){let r=Eo(e,"link");return r!==void 0&&/(?:^|,)\s*<[^>]+>;\s*rel="next"(?:\s*;|\s*(?:,|$))/i.test(r)}function Zt(e){let r=Xt(e),t=pp(e);return r===429||r===403&&Eo(t,"x-ratelimit-remaining")==="0"||e instanceof Error&&/secondary rate|rate limit/i.test(e.message)}function Xt(e){if(ar(e))return typeof e.status=="number"?e.status:void 0}function pp(e){return!ar(e)||!ar(e.response)||!ar(e.response.headers)?{}:e.response.headers}function Eo(e,r){let t=e[r]??e[r.toLowerCase()];return typeof t=="string"?t:typeof t=="number"?String(t):void 0}function ar(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rw(e){let r=ar(e)?e:{},t=ar(r.data)?r.data:r,o=(ar(t.rateLimit)?t.rateLimit:{}).cost;if(!Number.isSafeInteger(o)||o<0)throw new Error("GitHub aliased query did not return a non-negative integer rateLimit.cost");return o}function tw(e){let r=[...new Set(e.filter(t=>t!==void 0))].sort();if(r.length!==0)return r.length===1?r[0]:`coalesced:${r.join("+")}`}var gp="rate_limit",fp={rest:"core",graphql:"graphql",search:"search"},Qe=["rest","graphql","search"];function xo(e,r){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:[...Qe],detail:r??"no balance has been asked for yet, so none is known"}}var Zi=15e3,st=.15,So=[{at_or_below_fraction:0,every_ms:Zi,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:st,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"}];var QD=60*6e4,Xi=2;function hp(e,r){let t=mp(e),n=mp(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let a of Qe){let l=fp[a],d=n[l],c=sw(a,l,d);o[a]=c,c==null&&s.push(a)}let i=Qe.length-s.length;return{version:1,origin:"asked",outcome:i>0?"asked":"unanswered",source:"GET /rate_limit",asked_at:r.askedAt,request_count:1,pools:o,unreported_pools:s,detail:i>0?`the token's own answer for ${i} of ${Qe.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function ea(e){try{let r=await e.transport();return hp(r,{askedAt:e.now})}catch(r){let t=r instanceof Error?r.message:String(r);return{...xo(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function ra(e){let r=null;for(let t of Qe){let n=e.pools[t];n!=null&&(r==null||n.fraction<r.fraction)&&(r=n)}return r}function Po(e,r){let t=ra(e);if(t==null)return To(st).every_ms;let n=To(t.fraction);if(t.remaining>0)return n.every_ms;let o=bp(r.now,t.reset_at);return o==null?n.every_ms:Math.max(Zi,Math.min(n.every_ms,o))}function ta(e,r=st){return Math.ceil(e.limit*r)}function yp(e,r,t=st){let n=e.pools[r];return n==null?"unknown":n.remaining<=0?"spent":n.remaining<ta(n,t)?"reserved":"open"}function na(e){let r=e.reservedFraction??st,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:To(r).every_ms*Xi,stale:!1,posture:"unknown",reserved_fraction:r,next_poll_ms:To(r).every_ms,pools:[],unreported_pools:[...Qe],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let n=Po(t,{now:e.now}),o=e.stalenessMs??n*Xi,s=bp(t.asked_at,e.now),i=t.outcome==="asked"&&(s==null||s>o),a=Qe.map(c=>t.pools[c]).filter(c=>c!=null),l=ow(t,r),d=ra(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:r,next_poll_ms:n,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`:nw(l,d,t,r)}}function oa(e){if(!ia(e))return!1;let r=e;return r.version===1&&r.origin==="asked"&&(r.outcome==="asked"||r.outcome==="unanswered")&&(r.asked_at===null||typeof r.asked_at=="string")&&(r.age_ms===null||typeof r.age_ms=="number")&&typeof r.threshold_ms=="number"&&typeof r.stale=="boolean"&&typeof r.posture=="string"&&typeof r.reserved_fraction=="number"&&typeof r.next_poll_ms=="number"&&Array.isArray(r.pools)&&Array.isArray(r.unreported_pools)&&typeof r.reason=="string"}function nw(e,r,t,n){if(r==null)return t.detail;let o=ta(r,n);switch(e){case"spent":return`the ${r.pool} pool is spent and resets at ${r.reset_at}: work is not queued, it is refused`;case"reserved":return`the ${r.pool} pool has ${r.remaining} of ${r.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 ${r.pool} pool is the tightest at ${r.remaining} of ${r.limit}, above the reserved band of ${o}`}}function ow(e,r){let t="unknown";for(let n of Qe){if(e.pools[n]==null)continue;let o=yp(e,n,r);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function To(e){for(let r of So)if(e<=r.at_or_below_fraction)return r;return So[So.length-1]}function sw(e,r,t){if(!ia(t))return null;let n=vo(t.limit),o=vo(t.remaining),s=vo(t.used),i=vo(t.reset);return n==null||n<=0||o==null?null:{pool:e,resource:r,limit:n,remaining:o,used:s??0,reset_at:i==null?"":new Date(i*1e3).toISOString(),fraction:o/n}}function sa(e){let r=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let n=await t(`${r}/${gp}`,{method:"GET",headers:{authorization:`bearer ${e.token}`,accept:"application/vnd.github+json"}});if(!n.ok)throw new Error(`the balance ask was refused with HTTP ${n.status}`);return await n.json()}}function bp(e,r){let t=Date.parse(e),n=Date.parse(r);return!Number.isFinite(t)||!Number.isFinite(n)?null:Math.max(0,n-t)}function vo(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function mp(e){return ia(e)?e:{}}function ia(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vp(e){return{generated_at:e.now,hour:kp("hour",36e5,e),day:kp("day",864e5,e)}}function rn(e,r,t){let n=en(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(a=>{let l=en(r(a));return l==null?!1:n==null||n-l<=o});return i.length<=s?i:i.slice(i.length-s)}function kp(e,r,t){let n=en(t.now),o=n==null?null:n-r,s=e==="hour"?"1h":"24h",i=t.observations.map(u=>({observation:u,at:en(u.observed_at)})).filter(u=>u.at!=null&&wp(u.at,o,n)).sort((u,m)=>u.at-m.at),a=t.outcomes.map(u=>en(u.ts)).filter(u=>u!=null&&wp(u,o,n)),l=_p(i,u=>u.tokens,"tokens",s),d=_p(i,u=>u.tools,"tools",s),c=[];return i.length===0?c.push("worker-vitals"):(l.samples===0&&c.push("worker-vitals.tokens"),d.samples===0&&c.push("worker-vitals.tools")),a.length===0&&c.push("worker-outcomes"),{window:e,window_ms:r,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:l,tools_per_min:d,issues_per_hour:iw(a.length,r,s),runner_share:Rp("runner",i,u=>u.runner,s),model_share:Rp("model",i,u=>u.model,s),unavailable:c}}function _p(e,r,t,n){let o=new Map,s=0;for(let d of e){let c=r(d.observation);if(c==null||!Number.isFinite(c))continue;s+=1;let u=o.get(d.observation.worker_id)??[];u.push({at:d.at,count:c}),o.set(d.observation.worker_id,u)}if(s===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${n}`,samples:0};let i=0,a=null,l=null;for(let d of o.values()){if(d.length<2)continue;for(let m=1;m<d.length;m++){let f=d[m-1],h=d[m];f==null||h==null||(i+=Math.max(0,h.count-f.count))}let c=d[0],u=d[d.length-1];c!=null&&(a=a==null?c.at:Math.min(a,c.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 ${n} 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 iw(e,r,t){return e===0?{value:null,absent_reason:`no Worker outcome was recorded in the last ${t}`,samples:0}:{value:e/(r/36e5),absent_reason:null,samples:e}}function Rp(e,r,t,n){let o=new Map;for(let d of r){let c=t(d.observation);c!=null?o.set(d.observation.worker_id,c):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,c])=>({key:d,worker_count:c,share:c/i})).sort((d,c)=>c.worker_count-d.worker_count||d.key.localeCompare(c.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 ${n}`:`no Worker published a ${e} in the last ${n}`}}function wp(e,r,t){return r==null||t==null?!0:e>=r&&e<=t}function en(e){let r=Date.parse(e);return Number.isFinite(r)?r:null}function Sp(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.generated_at=="string"&&Ep(r.hour)&&Ep(r.day)}function Ep(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.window=="string"&&typeof r.window_ms=="number"&&aa(r.tokens_per_min)&&aa(r.tools_per_min)&&aa(r.issues_per_hour)&&Array.isArray(r.unavailable)}function aa(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return(r.value===null||typeof r.value=="number")&&(r.absent_reason===null||typeof r.absent_reason=="string")&&Number.isInteger(r.samples)}import{execFileSync as aw}from"node:child_process";import{existsSync as lw,readFileSync as Oo,readdirSync as dw}from"node:fs";import{dirname as cw,join as Or}from"node:path";function tn(e){let r=Vt(e),t=[["MemoryMax",r.memory_max],["MemoryHigh",r.memory_high]];for(let[n,o]of t){if(o==null)continue;let s=rt(o);return s==null?null:{name:n,declared:o,bytes:s}}return null}function Tp(e){let r=[],t=[];for(let n of e.workers){let o=tn(n);if(o==null){t.push({worker_id:n.worker_id,reason:(Vt(n).memory_max??Vt(n).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[n.worker_id];if(typeof s!="number"||!Number.isFinite(s)){t.push({worker_id:n.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?.[n.worker_id]==="cgroup"&&o.name==="MemoryMax"){t.push({worker_id:n.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}r.push(uw(n,o,s))}}return{terminations:r,unenforceable:t}}function uw(e,r,t){let n=`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:r.name,budget_declared:r.declared,budget_bytes:r.bytes,observed_rss_bytes:t,workspace_path:e.workspace_path,reason:`redskilled terminated ${n}: its tree RSS of ${t} bytes exceeded its ${r.name} budget of ${r.declared} (${r.bytes} bytes). This is a budget termination, not a stall, and the work in ${JSON.stringify(e.workspace_path)} is handed forward.`}}var pw=4096;function xp(e,r={}){let t=r.platform??process.platform,n={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return n;let o={},s={},i={},a=gw(e,t,r);for(let[u,m]of a){let f=yw(m);f!=null&&(o[u]=f.memoryBytes,f.cpuSeconds!=null&&(s[u]=f.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=_w(t,r);if(d.size===0)return{rss:o,cpu_seconds:s,sources:i};let c=new Map;for(let u of d.values()){let m=c.get(u.ppid);m?m.push(u.pid):c.set(u.ppid,[u.pid])}for(let u of l){if(!d.has(u.pid))continue;let m=0,f=0,h=[u.pid],v=new Set;for(;h.length>0;){let y=h.pop();if(v.has(y))continue;v.add(y);let S=d.get(y);if(S){m+=S.rssBytes,f+=S.cpuSeconds;for(let G of c.get(y)??[])h.push(G)}}o[u.worker_id]=m,s[u.worker_id]=f,i[u.worker_id]="process-tree"}return{rss:o,cpu_seconds:s,sources:i}}var mw="/sys/fs/cgroup";function gw(e,r,t){let n=new Map;if(!(t.cgroupRoot!=null)&&r!=="linux")return n;let s=t.cgroupRoot??mw,i=e.filter(l=>l.unit!=null&&l.unit!=="");if(i.length===0)return n;let a=fw(s,t);for(let l of i)for(let d of a){let c=Or(d,l.unit);if(lw(Or(c,"memory.current"))){n.set(l.worker_id,c);break}}return n}function fw(e,r){let t=r.selfCgroupPath??hw(),n=[],o=a=>{n.includes(a)||n.push(a)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(Or(e,s));let a=cw(s);if(a===s)break;s=a}o(e);let i=r.uid??process.getuid?.();return i!=null&&o(Or(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),n}function hw(){try{for(let e of Oo("/proc/self/cgroup","utf8").split(`
|
|
87
|
+
`))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function yw(e){let r;try{r=Oo(Or(e,"memory.current"),"utf8")}catch{return null}let t=Number(r.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:bw(e)}}function bw(e){let r;try{r=Oo(Or(e,"cpu.stat"),"utf8")}catch{return null}return kw(r)}function kw(e){for(let r of e.split(`
|
|
88
|
+
`)){let[t,n]=r.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(n);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function _w(e,r){return r.procRoot!=null||e==="linux"?Tw(r.procRoot??"/proc"):r.psTable!=null||e==="darwin"?vw(Rw(r.psTable)):new Map}function Rw(e){try{return(e??ww)()}catch{return""}}function ww(){return aw("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Ew=1024;function vw(e){let r=new Map;for(let t of e.split(`
|
|
89
|
+
`)){let n=t.trim().split(/\s+/);if(n.length!==4)continue;let[o,s,i]=n.slice(0,3).map(Number);if(![o,s,i].every(l=>l!=null&&Number.isSafeInteger(l)&&l>=0))continue;let a=Sw(n[3]);a!=null&&r.set(o,{pid:o,ppid:s,rssBytes:i*Ew,cpuSeconds:a})}return r}function Sw(e){let r=e.indexOf("-"),t=r<0?0:Number(e.slice(0,r));if(!Number.isFinite(t)||t<0)return null;let n=e.slice(r+1).split(":"),o=t*86400,s=1;for(let i=n.length-1;i>=0;i--){let a=Number(n[i]);if(!Number.isFinite(a)||a<0||n[i]==="")return null;o+=a*s,s*=60}return o}function Tw(e){let r=new Map,t;try{t=dw(e)}catch{return r}for(let n of t){if(!/^\d+$/.test(n))continue;let o;try{o=Oo(Or(e,n,"stat"),"utf8")}catch{continue}let s=Pw(o);s&&r.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*pw,cpuSeconds:s.cpuTicks/xw})}return r}var xw=100;function Pw(e){let r=e.lastIndexOf(")");if(r<0)return null;let t=Number(e.slice(0,e.indexOf(" "))),n=e.slice(r+1).trim().split(/\s+/),o=Number(n[1]),s=Number(n[11]),i=Number(n[12]),a=Number(n[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 Ow=["api","graphql"],Pj=Si(Ow);var Pp=100,da=6e4,Aw=2*da,Dw=7*24*60*60*1e3,la=class extends Error{constructor(t,n,o){super(`redskilled polls every repository with one host token ${JSON.stringify(o)}, and project ${JSON.stringify(t)} declares its own credential ${JSON.stringify(n)}: 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=n;this.hostTokenRef=o;this.name="RedskilledSplitCredentialError"}};function ca(e,r){for(let t of e)if(t.token_ref!=null&&t.token_ref!==r)throw new la(t.project_label,t.token_ref,r)}function Lp(e,r={now:new Date(0).toISOString()}){Np(e);let t=r.closedWindowMs??Dw,n=Date.parse(r.now);if(!Number.isFinite(n))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(r.now)}`);let o=new Date(n-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:c})=>{let u=JSON.stringify(c.owner),m=JSON.stringify(c.name),f=JSON.stringify(`repo:${c.owner}/${c.name} is:closed closed:>=${o}`);return[` ${l}: repository(owner: ${u}, name: ${m}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${d}: search(query: ${f}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
|
|
90
|
+
`),aliases:s,closed_since:o}}function jw(e,r,t){let n=it(r),o=it(n.data),s=Array.isArray(n.errors)?n.errors.map(it):[],i=Nw(o.rateLimit,s),a=e.aliases.map(({alias:l,search_alias:d,project:c})=>{let u=c.owner+"/"+c.name,m=o[l],f=s.find(h=>Dp(h.path,l)||Dp(h.path,d));if(nn(m)){let h=jp(m.open_pull_requests),v=jp(m.open_issues),y=Mw(o[d]);if(h!=null&&v!=null&&y!=null)return{project_label:c.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:h,open_issues:v,recently_closed:y},detail:`counted ${u} for project ${JSON.stringify(c.project_label)}`}}return i.exhausted||Mp(f)?{project_label:c.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:c.project_label,repository:u,outcome:"unreachable",counts:null,detail:`${u} is not reachable with the host token: ${Ao(f?.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 Lw(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 Gp(e){if(e.projects.length===0)return Lw(e.now);if(ca(e.projects,e.hostTokenRef),e.transport.conditionalList)return await $w(e);let r=Lp(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(r.query);return jw(r,t,{fetchedAt:e.now})}catch(t){let n=t instanceof Error?t.message:String(t),o=/rate limit|secondary rate|429/i.test(n);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: ${n}`}))}}}var Gw={key:"redskilled repository activity poll",budget:"rest"};async function $w(e){Np(e.projects);let r=Date.parse(e.now),t=Number.isFinite(r)?new Date(Math.floor(r/(60*60*1e3))*60*60*1e3).toISOString():e.now,n=Lp(e.projects,{now:t,closedWindowMs:e.closedWindowMs}),o=e.transport.conditionalList,s=[],i=0,a={remaining:null,reset_at:null,exhausted:!1,point_cost:null};for(let l of e.projects){let d=`${l.owner}/${l.name}`,c=[["open-prs","GET /repos/{owner}/{repo}/pulls",{owner:l.owner,repo:l.name,state:"open"}],["open-issues","GET /repos/{owner}/{repo}/issues",{owner:l.owner,repo:l.name,state:"open"}],["recently-closed","GET /repos/{owner}/{repo}/issues",{owner:l.owner,repo:l.name,state:"closed",since:n.closed_since}]],u=[];try{for(let[m,f,h]of c){let v=await o({cacheKey:`activity:${d}:${m}:${JSON.stringify(h)}`,route:f,parameters:h,operation:Gw});i+=v.requestCount;let y=m==="open-prs"?v.data:v.data.filter(S=>!nn(S.pull_request));u.push(m==="recently-closed"?y.filter(S=>Ao(S.closed_at)>=n.closed_since).length:y.length),a=Op(a,Cw(v.headers))}s.push({project_label:l.project_label,repository:d,outcome:"counted",counts:{open_pull_requests:u[0],open_issues:u[1],recently_closed:u[2]},detail:`counted ${d} for project ${JSON.stringify(l.project_label)}`})}catch(m){let f=Zt(m);a=Op(a,{remaining:null,reset_at:null,exhausted:f,point_cost:null}),s.push({project_label:l.project_label,repository:d,outcome:f?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${d} answered: ${m instanceof Error?m.message:String(m)}`})}}return{version:1,fetched_at:e.now,request_count:i,project_count:s.length,rate_limit:a,projects:s}}function $p(e){let r=e.stalenessMs??Aw,t=e.activity;if(t==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:r,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 n=Date.parse(e.now),o=Date.parse(t.fetched_at),s=Number.isFinite(n)&&Number.isFinite(o)?Math.max(0,n-o):null,i=s==null||s>r;return{version:1,fetched_at:t.fetched_at,age_ms:s,threshold_ms:r,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 ${r}ms window`:`fetched ${s}ms ago, within the ${r}ms window`}}function Ip(e){if(!nn(e))return!1;let r=e;return r.version===1&&(r.fetched_at===null||typeof r.fetched_at=="string")&&(r.age_ms===null||typeof r.age_ms=="number")&&typeof r.threshold_ms=="number"&&typeof r.stale=="boolean"&&Number.isInteger(r.request_count)&&nn(r.rate_limit)&&Array.isArray(r.projects)&&typeof r.reason=="string"}function Cp(e){let r=e.endpoint==null?void 0:Iw(e.endpoint),t=Yi({token:e.token,...r?{baseUrl:r}:{},...e.fetchImpl?{fetchImpl:e.fetchImpl}:{},...e.attribution?{attribution:e.attribution}:{},...e.retryCount===void 0?{}:{retryCount:e.retryCount},...e.throttle===void 0?{}:{throttle:e.throttle}}),n=async o=>await t.graphql(o);return n.conditionalList=async o=>await t.conditionalPaginate({cacheKey:o.cacheKey,route:o.route,parameters:o.parameters,operation:o.operation}),n}function Iw(e){let r=new URL(e);return/\/api\/graphql\/?$/.test(r.pathname)?r.pathname=r.pathname.replace(/\/api\/graphql\/?$/,"/api/v3"):r.pathname=r.pathname.replace(/\/graphql\/?$/,""),r.search="",r.hash="",r.toString().replace(/\/$/,"")}function Cw(e){let r=Ap(e,"x-ratelimit-remaining"),t=Ap(e,"x-ratelimit-reset");return{remaining:r,reset_at:t==null?null:new Date(t*1e3).toISOString(),exhausted:r===0,point_cost:null}}function Op(e,r){return{remaining:r.remaining==null?e.remaining:e.remaining==null?r.remaining:Math.min(e.remaining,r.remaining),reset_at:r.reset_at??e.reset_at,exhausted:e.exhausted||r.exhausted,point_cost:null}}function Ap(e,r){let t=e[r];if(typeof t!="string"&&typeof t!="number")return null;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:null}function Np(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>Pp)throw new Error(`redskilled activity fetch spans at most ${Pp} repositories in one query`);let r=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(r.has(t.project_label))throw new Error(`redskilled holds one repository per project, and ${JSON.stringify(t.project_label)} is registered twice`);r.add(t.project_label)}}function Nw(e,r){let t=it(e),n=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=r.some(Mp),i=typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:null;return{remaining:n,reset_at:o,exhausted:s||n===0,point_cost:i}}function Mp(e){if(e==null)return!1;let r=Ao(e.type),t=Ao(e.message);return r==="RATE_LIMITED"||/rate limit/i.test(t)}function Dp(e,r){return Array.isArray(e)&&e.includes(r)}function jp(e){let r=it(e);return Number.isInteger(r.totalCount)?r.totalCount:null}function Mw(e){let r=it(e);return Number.isInteger(r.issueCount)?r.issueCount:null}function it(e){return nn(e)?e:{}}function nn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ao(e){return typeof e=="string"?e:""}var Fw=3e4,Ww=2,Uw=3,Bw=4,Hw=["logs","vitals","display"];function Fp(e,r){if(r===void 0)return e;let t=Hw.filter(o=>r[o]!==!0);if(t.length===0)return e;let n=o=>r[o]===!0;return{...e,workers:e.workers.map(o=>({...o,...n("vitals")?{}:{vitals:qw,budget:{...o.budget,used_bytes:null,used_fraction:null}},...n("logs")?{}:{log:Vw},...n("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var qw={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},Vw={last_line:null,published_at:null,source:null};function Wp(e){let r=e.stalenessMs??Fw,t=lr(e.now),n=e.sampledAt==null?null:lr(e.sampledAt),o=t==null||n==null?null:Math.max(0,t-n),s=o!=null&&o<=r,i=new Set(e.reattachedWorkerIds??[]),a=e.hostState.workers.map(m=>Qw(m,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[m.worker_id],display:e.displays?.[m.worker_id],state:i.has(m.worker_id)?"reattached":"running"})),l=a.filter(m=>m.vitals.rss_bytes==null).map(m=>m.worker_id).sort(),d=a.length-l.length,c=a.reduce((m,f)=>m+(f.vitals.rss_bytes??0),0),u=uo(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:eE({sampledAt:e.sampledAt,ageMs:o,threshold:r,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:c,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:Zw(a),known_projects:Xw(e.hostState),registered_projects:(e.hostState.registrations??[]).map(m=>m.project_label).sort((m,f)=>m.localeCompare(f)),lapsed_projects:(e.hostState.lapsed_registrations??[]).map(m=>({project_label:m.project_label,at:m.at,...m.registered_at==null?{}:{registered_at:m.registered_at},reason:m.detail})),stopped_projects:(e.hostState.stopped_registrations??[]).map(m=>({project_label:m.project_label,at:m.at})),orphaned_projects:(e.hostState.orphaned_registrations??[]).map(m=>m.project_label),workers:a,github_balance:na({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:$p({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:Kw(e.deaths,e.recentDeathLimit??Bw)},engine:zw(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function Kw(e,r){let t=[...e].sort((s,i)=>(lr(i.ts)??0)-(lr(s.ts)??0)),n=t.slice(0,Math.max(0,Math.floor(r))).map(s=>({kind:s.kind,id:s.id,pid:s.pid,ts:s.ts,last_seen:s.last_seen,last_phase:s.last_phase,sender_class:s.sender_class,confidence:s.confidence,signal:s.signal,evidence:s.evidence[0]??null})),o=Jw(t);return{count:t.length,recent:n,latest:n[0]??null,reaped_at:n[0]?.ts??null,...o==null?{}:{boot_loop:o}}}function Jw(e){let r=new Map;for(let n of e){if(n.sender_class!=="boot-refused"||n.uptime_s==null||n.uptime_s>Ww||n.project_label==null||n.project_label===""||lr(n.ts)==null)continue;let o=r.get(n.project_label)??[];o.push(n),r.set(n.project_label,o)}return[...r.entries()].filter(([,n])=>n.length>=Uw).map(([n,o])=>{let s=o[0],i=lr(s.ts),a=Math.min(...o.map(d=>lr(d.ts))),l=s.detail?.trim()||s.evidence[0]?.trim();return l==null||l===""?null:{project_label:n,count:o.length,span_ms:Math.max(0,i-a),latest_refusal:l}}).filter(n=>n!=null).sort((n,o)=>o.count-n.count||o.span_ms-n.span_ms)[0]??null}function zw(e){let r=e.upgrade,t=r?.running_version??e.daemon_version,n=r?.published_version??null,o=r?.newest_published_version??null,s=(r?.newer_published??0)>0,i=(r?.major_held??0)>0;return{running_version:t,published_version:n,newer_published:s,major_held:i,current:n==null&&o==null?null:!s&&!i}}function Qw(e,r){let t=r.rss[e.worker_id],n=typeof t=="number"&&Number.isFinite(t)?t:null,o=tn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=lr(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:r.nowMs==null||i==null?null:Math.max(0,r.nowMs-i),state:r.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:n,sampled_at:n==null?null:r.sampledAt,age_ms:n==null?null:r.ageMs,fresh:n!=null&&r.sampleFresh,rss_source:n==null?null:e.rss_source??null},budget:{name:o?.name??null,declared:o?.declared??s,bytes:o?.bytes??null,used_bytes:n,used_fraction:o==null||o.bytes<=0||n==null?null:n/o.bytes,enforceable:o!=null},log:Yw(r.log),display:r.display?.display??null,display_published_at:r.display?.published_at??null}}function Yw(e){let r={last_line:null,published_at:null,source:null};return e==null||e.line.trim()===""?r:{last_line:e.line,published_at:e.published_at,source:e.source}}function Xw(e){let r=new Set;for(let t of e.registrations??[])r.add(t.project_label);for(let t of e.projects)r.add(t.project_label);for(let t of e.lapsed_registrations??[])r.add(t.project_label);for(let t of e.stopped_registrations??[])r.add(t.project_label);for(let t of e.orphaned_registrations??[])r.add(t.project_label);return[...r].sort((t,n)=>t.localeCompare(n))}function Zw(e){let r=new Map;for(let t of e){let n=r.get(t.project_label)??{workers:0,declared:0,observed:0,measured:0};n.workers+=1,n.declared+=t.budget.bytes??0,n.observed+=t.vitals.rss_bytes??0,n.measured+=t.vitals.rss_bytes==null?0:1,r.set(t.project_label,n)}return[...r.entries()].map(([t,n])=>({project_label:t,worker_count:n.workers,declared_memory_bytes:n.declared,observed_rss_bytes:n.observed,measured_worker_count:n.measured})).sort((t,n)=>t.project_label.localeCompare(n.project_label))}function eE(e){let r={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?{...r,stale:!1,reason:"the host holds no Workers, so there is nothing to measure and nothing to age"}:e.sampledAt==null||e.ageMs==null?{...r,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?{...r,stale:!0,reason:`this answer is stale: its measurement is ${e.ageMs}ms old, past the ${e.threshold}ms staleness window`}:{...r,stale:!1,reason:`measured ${e.ageMs}ms ago, within the ${e.threshold}ms staleness window`}}function lr(e){let r=Date.parse(e);return Number.isFinite(r)?r:null}function ua(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e,t=r.daemon,n=r.staleness,o=r.host;return r.version===1&&typeof r.generated_at=="string"&&t!=null&&typeof t=="object"&&Number.isInteger(t.pid)&&typeof t.daemon_version=="string"&&typeof t.protocol_version=="number"&&n!=null&&typeof n=="object"&&typeof n.stale=="boolean"&&typeof n.threshold_ms=="number"&&Array.isArray(n.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(r.projects)&&Array.isArray(r.workers)&&(r.known_projects===void 0||Array.isArray(r.known_projects)&&r.known_projects.every(s=>typeof s=="string"))&&(r.registered_projects===void 0||Array.isArray(r.registered_projects)&&r.registered_projects.every(s=>typeof s=="string"))&&(r.lapsed_projects===void 0||Array.isArray(r.lapsed_projects)&&r.lapsed_projects.every(rE))&&(r.stopped_projects===void 0||Array.isArray(r.stopped_projects)&&r.stopped_projects.every(tE))&&(r.orphaned_projects===void 0||Array.isArray(r.orphaned_projects)&&r.orphaned_projects.every(s=>typeof s=="string"))&&(r.repository_activity===void 0||Ip(r.repository_activity))&&(r.github_balance===void 0||oa(r.github_balance))&&(r.deaths===void 0||nE(r.deaths))&&(r.engine===void 0||oE(r.engine))&&(r.metrics===void 0||Sp(r.metrics))}function rE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.project_label=="string"&&typeof r.at=="string"&&(r.registered_at===void 0||typeof r.registered_at=="string")&&typeof r.reason=="string"}function tE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.project_label=="string"&&typeof r.at=="string"}function nE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return Number.isInteger(r.count)&&Array.isArray(r.recent)}function oE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.running_version=="string"&&(r.published_version===null||typeof r.published_version=="string")}var Up={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,wait_kind:null,wait_subject:null,wait_pid:null,wait_started_at:null,wait_deadline:null,wait_escalation:null,started_at:null,context:null,eta:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null};function Bp(e,r){let t=e.display?.started_at;if(t!=null&&t!==""){let n=Date.parse(t),o=Date.parse(r);if(Number.isFinite(n)&&Number.isFinite(o))return Math.max(0,o-n)}return e.uptime_ms}var se=e=>`\x1B[${e}m`,on=se("48;2;114;47;55"),pa=se("48;2;88;36;42"),dr=se("38;2;255;255;255"),ma=se("38;2;201;150;158"),sn=se("38;2;255;214;214"),an=se("39"),fe=se("38;2;224;138;148"),ga=se("38;2;240;200;120"),fa=se("38;2;240;110;120"),ha=se("38;2;255;214;214"),ya=se("38;2;146;84;94"),ba=se("38;2;255;95;95"),Fe=se("49"),Oe=se("0"),Do=se("1"),jo=se("22");var sE=/\x1b\[[0-9;]*m/g,iE=/(\x1b\[[0-9;]*m)/,aE=/^\x1b\[[0-9;]*m$/;function Hp(e){return e.replace(sE,"")}function lE(e){return e.slice(2,-1).split(";").every(t=>t===""||Number(t)===0)}function we(e){return[...Hp(e)].length}function me(e,r){if(r<=0)return"";if(we(e)<=r)return e;if(r===1)return"\u2026";let t=r-1,n=0,o=!1,s="";for(let i of e.split(iE))if(i!==""){if(aE.test(i)){s+=i,o=!lE(i);continue}for(let a of i){if(n===t)return`${s}\u2026${o?Oe:""}`;s+=a,n+=1}}return`${s}\u2026${o?Oe:""}`}function ln(e,r){return e+" ".repeat(Math.max(0,r-we(e)))}function ka(e){let r=e.toLowerCase();for(let t of["opus","sonnet","haiku","fable"]){let n=r.indexOf(t);if(n===-1)continue;let s=r.slice(n+t.length).match(/^-(\d+(?:[-.]\d+)*)/)?.[1]?.split(/[-.]/)??[];return/^\d{8}$/.test(s.at(-1)??"")&&s.pop(),s.length===0?t:`${t}-${s.join(".")}`}return e}function Ae(e){if(!Number.isFinite(e)||e<=0)return"0B";let r=["B","K","M","G","T"],t=e,n=0;for(;t>=1024&&n<r.length-1;)t/=1024,n+=1;return`${t>=100||n===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${r[n]}`}function dn(e){if(!Number.isFinite(e)||e<=0)return"0";let r=(t,n)=>{let o=(Math.round(t*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${n}`};return e>=1e9?r(e/1e9,"B"):e>=1e6?r(e/1e6,"M"):e>=1e3?r(e/1e3,"k"):String(Math.round(e))}function cn(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return dn(e);if(e<=0)return"0";let r=(Math.round(e*10)/10).toFixed(1);return r.endsWith(".0")?r.slice(0,-2):r}function cr(e){if(e==null||!Number.isFinite(e)||e<0)return"\u2014";let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let t=Math.floor(r/60);if(t<60)return`${t}m${r%60}s`;let n=Math.floor(t/60);return n<24?`${n}h${t%60}m`:`${Math.floor(n/24)}d${n%24}h`}function at(e){if(e==null)return null;let r=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return r===""?null:r}var un="!unregistered",_a="!lapsed",pn="\u21E1",Ye="\u2020",lt="\u25D0",dt="\u25EF",Ra="\u21B3",wa="redskilled unreachable \u2014 Worker state unknown";function ct(e,r){return r.mode==="global"?e.workers:r.project==null?[]:e.workers.filter(t=>t.project_label===r.project)}function Lo(e,r){return r.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===r.project)}function mn(e,r){return r==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(r)?e.registered_projects==null||e.registered_projects.includes(r)?"matched":e.orphaned_projects?.includes(r)===!0?"orphaned":e.stopped_projects?.some(t=>t.project_label===r)===!0?"stopped":e.lapsed_projects?.some(t=>t.project_label===r)===!0?"lapsed":"name-only":"unregistered"}function Ea(e){let r=[];return e.workers.length>0&&e.workers.length<=e.maxWorkers&&r.push("workers"),e.mode==="global"&&e.projects.length>0&&e.projects.length<=e.maxProjects&&r.push("projects"),r.push("host"),r}var pr=["wid","run","org","iss","bar","phase","elapsed","eta","hb","loc","tks","ctx","tls","rsn","txt"],We={mode:"local",project:null,maxWidth:200,maxRows:16},dE=" ",qp="\u2588",cE="\u25B6",uE="\u2717",pE="\u2591",mE=new Set(["gate","push-pr","merge","cascade"]),gE=new Set(["requeue"]),fE="repair";function gn(e){return e.display?.origin===fE}function ut(e,r=We){let t=mn(e,r.project),n=ct(e,r),o=n.slice(0,Math.max(0,Math.floor(r.maxRows))),s=o.map(u=>Go(u,r,e.generated_at)),i=SE(s),a=o.map((u,m)=>({worker_id:u.worker_id,project_label:u.project_label,mine:r.project!=null&&u.project_label===r.project,cells:s[m],line:me(TE(s[m],i),r.maxWidth)})),l=yE(e,r,n,t),d=n.length-o.length,c=[l.line,...a.map(u=>u.line)];return d>0&&c.push(me(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,r.maxWidth)),c.push(...RE(e,r)),c.push(..._E(e,r)),{version:1,generated_at:e.generated_at,mode:r.mode,project:r.project,columns:pr,header:l,rows:a,lines:c,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Go(e,r,t){let n=e.display??Up,o=gn(e),s=[n.runner,n.model==null?null:ka(n.model),n.effort].filter(l=>!!l).join(" "),i=n.phase!=null&&mE.has(n.phase),a=o||i||n.origin!=null&&gE.has(n.origin);return{wid:r.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:o||s===""?"":`run=${s}`,org:o?"lane=repair":i?"org=landing":n.origin==null?"":`org=${n.origin}`,iss:n.issue==null?"":o?`pr=#${n.issue.replace(/^#/,"")}`:`iss=${n.issue}`,bar:Vp(n),phase:[n.phase,n.step].filter(l=>!!l).join("\xB7"),elapsed:cr(Bp(e,t)),eta:n.eta==null?"":`eta=${cr(n.eta*1e3)}`,hb:hE(n,t)??`hb=${n.heartbeat??"?"}`,loc:a?"":vE(n.added,n.removed),tks:a||n.tokens==null?"":`tks=${dn(n.tokens)}`,ctx:n.context==null?"":`ctx=${dn(n.context)}`,tls:a||n.tools==null?"":`tls=${n.tools}`,rsn:a||n.reasoning==null?"":`rsn=${n.reasoning}`,txt:a||n.text==null?"":`txt=${n.text}`}}function hE(e,r){if(e.wait_kind==null||e.wait_subject==null||e.wait_pid==null||e.wait_pid<=0||e.wait_started_at==null)return null;let t=Date.parse(e.wait_started_at),n=Date.parse(r);return!Number.isFinite(t)||!Number.isFinite(n)?null:`${e.wait_kind}=${e.wait_subject} ${cr(Math.max(0,n-t))}`}function Vp(e){let r=e.phase_total,t=e.phase_index;if(r==null||r<=0||t==null||t<0)return"";let n=Math.min(Math.floor(t),Math.floor(r));if(n>=r)return qp.repeat(Math.floor(r));let o=e.failed?uE:cE;return`${qp.repeat(n)}${o}${pE.repeat(Math.floor(r)-n-1)}`}function yE(e,r,t,n){let o=(e.repository_activity?.projects??[]).find(L=>L.project_label===r.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,interactive_reservation:e.host.ceiling.interactive_reservation??0},a=EE(t),l=o?.repository??r.project,d=e.engine??null,c=d?.running_version??e.daemon.daemon_version,u=e.deaths??null,m=e.metrics??null,f=[bE(l??"host",c,d!=null&&d.current===!1?pn:"")];(n==="unregistered"||n==="name-only")&&f.push(un),n==="lapsed"&&f.push(_a),a!=null&&f.push(`${on}${dr}${a}${Fe}${fe}`);let h=e.workers.filter(gn).length;if(h>0){let L=Math.max(0,e.host.worker_count-h);f.push(`${ur(`workers=${L} coding +`)} ${on}${dr}${h} repairing${Fe}${fe}`)}else f.push(ur(`wrk=${t.length}/${e.host.worker_count}`));let v=i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`;f.push(ur(`${v} reserve=${i.interactive_reservation} interactive`)),f.push(ur(wE(i))),s.open_pull_requests!=null&&f.push(ur(`prs=${s.open_pull_requests}`)),s.recently_closed!=null&&f.push(ur(`cpr=${s.recently_closed}`)),s.open_issues!=null&&f.push(ur(`iss=${s.open_issues}`)),s.stale&&f.push("!counts stale");let y=m==null?null:Kp(m.hour),S=y==null?null:ur(y);if(S!=null&&f.push(S),u!=null&&u.count>0&&u.latest!=null){let L=u.boot_loop,Q=at(L?.latest_refusal);f.push(L==null?`${Ye}${u.count} ${u.latest.sender_class}`:`${Ye}${u.count} boot-refused \xD7${L.count} in ${kE(L.span_ms)}`+(Q==null?"":` \u2014 ${Q}`))}if(e.staleness.stale){let L=e.staleness.age_ms;f.push(L==null?"!unmeasured":`!stale ${Math.round(L/1e3)}s`)}let G=`${f.join(" \xB7 ")}${Oe}`,H=y!=null&&we(G)>r.maxWidth?`${f.filter(L=>L!==S).join(" \xB7 ")}${Oe}`:G;return{repo:l,project:r.project,project_match:n,version:c,engine:d,deaths:u,metrics:m,model:a,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:me(H,r.maxWidth)}}function bE(e,r,t){return`${pa}${dr}${ga}\xBB${dr} ${Do}${e}${jo} ${ma}v${r}${t}${dr}${Fe}${fe}`}function ur(e){return e.replace(/(^|\s)([A-Za-z][A-Za-z0-9/]*=)([^\s]+)/g,(r,t,n,o)=>`${t}${sn}${n}${an}${o}${fe}`)}function kE(e){return cr(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function Kp(e){let r=[];e.tokens_per_min.value!=null&&r.push(`tk/m=${cn(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&r.push(`tl/m=${cn(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&r.push(`iss/h=${cn(e.issues_per_hour.value)}`);let t=e.runner_share.shares[0];return t!=null&&r.push(`${t.key}=${Math.round(t.share*100)}%`),r.length===0?null:r.join(" ")}function _E(e,r){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let n=t.posture==="spent"?dt:lt,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[me(`${n} github budget ${t.posture}${o} \u2014 ${t.reason}`,r.maxWidth)]}function RE(e,r){let t=e.deaths;if(t==null||t.count<=0)return[];let n=t.recent.map(s=>me(`${Ye} ${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}`),r.maxWidth)),o=t.count-t.recent.length;return o>0&&n.push(me(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,r.maxWidth)),n}function wE(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${Ae(e.memory_used_bytes)}`;let r=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${Ae(e.memory_used_bytes)}/${Ae(e.memory_ceiling_bytes)}${r}`}function EE(e){for(let r of e){let t=r.display;if(t==null)continue;let n=[t.runner,t.model,t.effort].filter(o=>!!o);if(n.length>0)return n.join("\xB7")}return null}function vE(e,r){if(e==null&&r==null)return"";let t=[];return e!=null&&e>0&&t.push(`+${e}`),r!=null&&r>0&&t.push(`-${r}`),`loc=${t.length>0?t.join(" "):"0"}`}function SE(e){let r=Object.fromEntries(pr.map(t=>[t,0]));for(let t of e)for(let n of pr)r[n]=Math.max(r[n],we(t[n]));return r}function TE(e,r){let t=pr.filter(o=>r[o]>0);if(t.length===0)return"";let n=t.map((o,s)=>$o(o,ln(e[o],s===t.length-1?we(e[o]):r[o])));return`${Fe}${fe}${n.join(dE)}${Oe}`}function $o(e,r){if(e==="wid")return`${Do}${r}${jo}`;if(e==="org"&&r.trim()==="lane=repair"){let n=r.slice(r.trimEnd().length);return`${on}${dr}${r.trimEnd()}${Fe}${fe}${n}`}if(e==="bar")return r.replace(/█+/g,n=>`${fa}${n}`).replace("\u25B6",`${ha}\u25B6`).replace("\u2717",`${ba}\u2717`).replace(/░+/g,n=>`${ya}${n}`)+fe;let t=r.indexOf("=");return t>0?`${sn}${r.slice(0,t+1)}${an}${r.slice(t+1)}${fe}`:r}function Sa(e){return Object.freeze({none:!0,reason:e})}function fn(){return{tool:"project_start",args:{runner:"claude",target:1},why:"register this project with the host so its queue can drain"}}function va(e,r){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError("repair args must contain only finite JSON numbers");return e}if(r.has(e))throw new TypeError("repair args must not contain cycles");r.add(e);try{if(Array.isArray(e))return Object.freeze(e.map(n=>va(n,r)));let t={};for(let[n,o]of Object.entries(e))t[n]=va(o,r);return Object.freeze(t)}finally{r.delete(e)}}function xE(e){let r=va(e.args,new Set);return Object.freeze({tool:e.tool,args:r,why:e.why})}function Ar(e){if("none"in e.repair)return{prose:`${e.state}; repair: none because ${e.repair.reason}`,repair:"none",repair_reason:e.repair.reason};let r=xE(e.repair);return{prose:`${e.state}; repair: call \`${r.tool}\` with \`${JSON.stringify(r.args)}\` because ${r.why}`,repair:r}}var U={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Dr(e,r=U){let t=mn(e,r.project),n=ct(e,r),o=Lo(e,r),s=LE(e,r.project,t),i=OE(e,r,n,t,s.prose),a=Ea({mode:r.mode,maxWorkers:r.maxWorkers,maxProjects:r.maxProjects,workers:n,projects:o}),l={detail:"host",line:i};for(let f of a){let h=f==="workers"?i:NE(i,PE(f,o),r.separator);if(l={detail:f,line:h},f==="workers"||we(h)<=r.maxWidth)break}let d=me(l.line,r.maxWidth),c=l.detail==="workers"?$E(n,r,e.generated_at):{lines:[],degraded:!1},u=l.detail==="workers"?n.flatMap((f,h)=>{let v=r.verbose?IE(f,r):null;return v==null?[c.lines[h]]:[c.lines[h],v]}):[],m=n.length>0?"workers":"host";return{version:1,line:d,lines:[d,...u],verbose:r.verbose,mode:r.mode,project:r.project,project_match:t,...s.repair===void 0?{}:{repair:s.repair},...s.repair_reason===void 0?{}:{repair_reason:s.repair_reason},detail:l.detail,degraded:l.detail!==m||d!==l.line||c.degraded,stale:e.staleness.stale,generated_at:e.generated_at}}function Oa(e){let r=e.options??U,t=me(wa,r.maxWidth);return{version:1,line:t,lines:[t],verbose:r.verbose,mode:r.mode,project:r.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}function PE(e,r){return e==="projects"?r.map(CE):[]}function OE(e,r,t,n,o){let s=[],i=n!=="matched"&&n!=="name-only";r.mode==="global"?(s.push(`host ${Ta(e.workers,e.host.worker_count)}/${e.host.project_count}p`),s.push(Pa(e,r))):n==="matched"?(s.push(`${r.project} ${Ta(t,t.length)}`),s.push(Pa(e,r)),t.length===0&&s.push("idle")):n==="name-only"?(s.push(`${r.project} ${Ta(t,t.length)}`),s.push(Pa(e,r)),s.push(un)):s.push(o),s.push(Jp(e));let a=AE(e);a!=null&&s.push(a);let l=DE(e);l!=null&&s.push(l),e.staleness.stale&&s.push(zp(e));let d=s.join(" ");return!i||we(d)<=r.maxWidth||a==null&&l==null?d:[a,l,o,Jp(e),e.staleness.stale?zp(e):null].filter(c=>c!=null).join(" ")}function Ta(e,r){let t=e.filter(gn).length;return t===0?`${r}w`:`${Math.max(0,r-t)} coding + ${t} repairing`}function Jp(e){let r=e.engine,t=r?.running_version??e.daemon.daemon_version;return r==null||r.current!==!1?`v${t}`:`v${t}${pn}`}function AE(e){let r=e.github_balance;return r==null?null:r.posture==="spent"?`${dt} quota spent`:r.posture==="reserved"?`${lt} quota band`:null}function DE(e){let r=e.deaths;if(r==null||r.count<=0||r.latest==null)return null;let t=r.boot_loop;if(t!=null){let n=at(t.latest_refusal);return`${Ye}${r.count} boot-refused \xD7${t.count} in ${jE(t.span_ms)}`+(n==null?"":` \u2014 ${n}`)}return`${Ye}${r.count} ${r.latest.sender_class}`}function jE(e){return cr(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function LE(e,r,t){if(t==="unregistered")return Ar({state:`project unknown \u2014 ${r} was never registered on this host`,repair:fn()});if(t==="orphaned")return Ar({state:`project unknown \u2014 ${r} is registered on a daemon this socket does not reach`,repair:Sa("this socket cannot safely replace a registration owned by an unreachable daemon")});if(t==="stopped"){let n=e.stopped_projects?.find(o=>o.project_label===r);return Ar({state:`project unknown \u2014 ${r} was stopped${n==null?"":` at ${xa(n.at)}`}`,repair:fn()})}if(t==="lapsed"){let n=e.lapsed_projects?.find(o=>o.project_label===r);if(n!=null){let o=n.registered_at==null?"":` (registered ${xa(n.registered_at)})`;return Ar({state:`project unknown \u2014 ${r} lapsed at ${xa(n.at)}${o}`,repair:fn()})}return Ar({state:`project unknown \u2014 ${r} lapsed`,repair:fn()})}return t==="unresolved"?Ar({state:"project unknown \u2014 this directory resolved to no project",repair:Sa("the directory must resolve to a project before registration args can be safe")}):{prose:""}}function xa(e){return/^\d{4}-\d{2}-\d{2}T(\d{2}:\d{2}:\d{2})/.exec(e)?.[1]??e}function Pa(e,r){let t=r.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===r.project).reduce((o,s)=>o+s.observed_rss_bytes,0),n=e.host.ceiling.memory_bytes;return r.mode==="global"&&n!=null&&n>0?`${Ae(t)}/${Ae(n)}`:Ae(t)}function zp(e){let r=e.staleness.age_ms;return r==null?"!unmeasured":`!stale ${Math.round(r/1e3)}s`}function GE(e,r,t,n){let o=t.map(s=>$o(s,ln(e[s],r[s])));return me(`${Fe}${fe}${o.join(" ")}${Oe}`,n)}function $E(e,r,t){let n=e.map(a=>Go(a,r,t)),o=pr.filter(a=>n.some(l=>we(l[a])>0)),s=[...o],i=Qp(n,s);for(;s.length>1&&Yp(i,s)>r.maxWidth;)s.pop(),i=Qp(n,s);return{lines:n.map(a=>GE(a,i,s,r.maxWidth)),degraded:s.length<o.length||Yp(i,s)>r.maxWidth}}function Qp(e,r){let t=Object.fromEntries(pr.map(n=>[n,0]));for(let n of e)for(let o of r)t[o]=Math.max(t[o],we(n[o]));return t}function Yp(e,r){return r.reduce((t,n)=>t+e[n],0)+Math.max(0,r.length-1)*2}function IE(e,r){let t=at(e.log.last_line);return t==null?null:me(` ${Ra} ${Xp(e,r.mode)}: ${t}`,r.maxWidth)}function Xp(e,r){return r==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function CE(e){return`${e.project_label} ${e.worker_count}w ${Ae(e.observed_rss_bytes)}`}function NE(e,r,t){return[e,...r].join(t)}var Io=1;async function hn(e,r){return await no(e,r,"redskilled daemon")}function em(e){let r=[...e.workers??[]],t=new Map;for(let n of r)t.set(n.project_label,(t.get(n.project_label)??0)+1);return{version:1,protocol_version:Io,daemon_version:e.daemonVersion,machine_id_hash:e.machineIdHash,session_key_hash:e.sessionKeyHash,pid:e.pid,started_at:e.startedAt,...e.ceiling==null?{}:{ceiling:e.ceiling},...e.scope==null?{}:{scope:e.scope},workers:r,projects:[...t.entries()].map(([n,o])=>({project_label:n,worker_count:o})).sort((n,o)=>n.project_label.localeCompare(o.project_label)),registrations:UE(e),...e.demand==null?{}:{demand:e.demand},...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},...e.stops==null||e.stops.length===0?{}:{stopped_registrations:[...e.stops]},...e.orphanedRegistrations==null||e.orphanedRegistrations.length===0?{}:{orphaned_registrations:[...e.orphanedRegistrations]},birth_latches:[...e.birthLatches??[]],budget_accounting:_c(r,{hostCeilingBytes:e.ceiling?.memory_bytes??e.hostCeilingBytes??null}),upgrade:BE(e)}}function UE(e){let r=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(r),n=e.queue??null,o=new Map(n==null?[]:n.projects.map(s=>[s.project_label,s]));return[...e.registrations??[]].map(s=>{let i=o.get(s.project_label);return{...s,...t?{renewal:tu(s,r)}:{},...n==null||i==null?{}:{last_poll:{at:n.fetched_at,outcome:i.outcome,depth:i.depth,request_count:n.request_count,detail:i.detail}}}}).sort((s,i)=>s.project_label.localeCompare(i.project_label))}function BE(e){let r=e.daemonVersion,t=e.published?.version??null,n=e.published?.majorHold??null;return{running_version:r,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:+(n!==null),major_hold:n}}function rm(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.version===1&&typeof r.protocol_version=="number"&&typeof r.daemon_version=="string"&&typeof r.machine_id_hash=="string"&&typeof r.session_key_hash=="string"&&Number.isInteger(r.pid)&&typeof r.started_at=="string"&&(r.ceiling===void 0||JE(r.ceiling))&&Array.isArray(r.workers)&&Array.isArray(r.projects)&&Rc(r.budget_accounting)&&(r.scope===void 0||Xc(r.scope))&&(r.registrations===void 0||Array.isArray(r.registrations)&&r.registrations.every(zt))&&(r.demand===void 0||Nc(r.demand))&&(r.lapsed_registrations===void 0||Array.isArray(r.lapsed_registrations)&&r.lapsed_registrations.every(qE))&&(r.stopped_registrations===void 0||Array.isArray(r.stopped_registrations)&&r.stopped_registrations.every(VE))&&(r.orphaned_registrations===void 0||Array.isArray(r.orphaned_registrations)&&r.orphaned_registrations.every(KE))&&(r.birth_latches===void 0||Array.isArray(r.birth_latches)&&r.birth_latches.every(HE))&&(r.upgrade===void 0||zE(r.upgrade))}function HE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e,t=r.repair;return r.name==="project-birth-breaker"&&typeof r.project_label=="string"&&(r.state==="open"||r.state==="half-open")&&typeof r.opened_at=="string"&&typeof r.reason=="string"&&typeof r.closes=="string"&&(r.probe_worker_id===null||typeof r.probe_worker_id=="string")&&t!=null&&t.tool==="project_reset"&&typeof t.args=="object"&&t.args!==null&&typeof t.why=="string"}function qE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.project_label=="string"&&(r.registered_at===void 0||typeof r.registered_at=="string")&&typeof r.at=="string"&&typeof r.renew_by=="string"&&Number.isInteger(r.renewals)&&Number.isInteger(r.sustains)&&typeof r.detail=="string"}function VE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.project_label=="string"&&typeof r.registered_at=="string"&&typeof r.at=="string"&&typeof r.detail=="string"}function KE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.project_label=="string"&&(r.registered_at===void 0||typeof r.registered_at=="string")}function JE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e,t=new Set(["flag","environment","home-config","derived-default"]);return(r.memory_bytes===null||typeof r.memory_bytes=="number")&&(r.worker_count===null||typeof r.worker_count=="number")&&(r.validation_count===void 0||Number.isInteger(r.validation_count)&&Number(r.validation_count)>0)&&(r.source==="declared"||r.source==="host-fraction")&&(r.memory_source===void 0||t.has(String(r.memory_source)))&&(r.worker_source===void 0||t.has(String(r.worker_source)))&&(r.validation_source===void 0||t.has(String(r.validation_source)))}function zE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.running_version=="string"&&(r.published_version===null||typeof r.published_version=="string")&&typeof r.published_unknown=="number"&&typeof r.newer_published=="number"&&(r.replacement==="none"||r.replacement==="pending"||r.replacement==="in-progress")&&(r.checked_at===null||typeof r.checked_at=="string")&&(r.newest_published_version===void 0||r.newest_published_version===null||typeof r.newest_published_version=="string")&&(r.major_held===void 0||typeof r.major_held=="number")&&(r.checks===void 0||typeof r.checks=="number")&&(r.hold_reason===void 0||r.hold_reason===null||typeof r.hold_reason=="string")&&(r.major_hold===void 0||r.major_hold===null||QE(r.major_hold))}function QE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.version=="string"&&Number.isInteger(r.running_major)&&Number.isInteger(r.held_major)&&typeof r.reason=="string"&&typeof r.action=="string"&&r.action.trim()!==""}import{randomUUID as YE}from"node:crypto";import{mkdir as XE,readFile as ZE,rename as ev,writeFile as rv}from"node:fs/promises";import{dirname as tv}from"node:path";function tm(e){let r=Promise.resolve(),t=null;async function n(){await r;let s;try{s=await ZE(e,"utf8")}catch(a){if(a.code==="ENOENT")return[];throw a}let i=nv(s);return ov(i)?i.registrations:[]}async function o(s){await XE(tv(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.${YE()}.tmp`,a={version:1,registrations:[...s]};await rv(i,`${J(a,{keyedMapCollapse:!0})}
|
|
91
|
+
`,{encoding:"utf8",mode:384}),await ev(i,e)}return{read:n,replace(s){let i=r.then(()=>o(s));return r=i.then(()=>{t=null},a=>{t=a}),i},async flush(){if(await r,t!=null)throw t}}}function nv(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return ue(r)}catch{return null}}}function ov(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.version===1&&Array.isArray(r.registrations)&&r.registrations.every(zt)}import{spawnSync as Mo}from"node:child_process";import{existsSync as Ga}from"node:fs";import{delimiter as mv,join as pm}from"node:path";import{join as nm}from"node:path";import{existsSync as sv}from"node:fs";import{createRequire as iv}from"node:module";var om="redskilled-job-object.node",jr=100;function pt(e){return{available:!1,reason:e}}function av(e,r,t){return[nm(t,"prebuilds",`${e}-${r}`,om),nm(t,"native","build","Release",om)]}function sm(e={}){let r=e.platform??process.platform,t=e.arch??process.arch;if(r!=="win32")return pt(`Job Object placement is the Windows backend (platform=${r}), so there is no native reach to load here`);let n=e.packageRoot??dv(),o=e.exists??sv,s=av(r,t,n),i=s.find(d=>o(d));if(i==null)return pt(`no Job Object addon was found for ${r}-${t} (looked in ${s.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let a=e.requireFn??iv(import.meta.url),l;try{l=a(i)}catch(d){return pt(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return lv(l)?{available:!0,binding:l}:pt(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function lv(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function dv(){return new URL("..",import.meta.url).pathname}function im(e){let r=e??{},t=[],n=cv(r);n==null&&(r.memory_max??r.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 r.cpu_weight!=null&&(r.cpu_weight<jr?o=Math.max(1,Math.min(100,Math.round(r.cpu_weight))):t.push(`cpu_weight=${r.cpu_weight} is at or above the fair share of ${jr}, and Windows CPU rate control is an absolute cap rather than a share, so no rate limit is set`)),{...n!=null?{memory_limit_bytes:n.bytes,memory_budget_name:n.name,memory_budget_declared:n.declared}:{},...o!=null?{cpu_rate_percent:o}:{},kill_on_close:!0,...t.length>0?{note:t.join("; ")}:{}}}function cv(e){return tn({budget:e})}var Co=5,am=19;function Aa(e){return{available:!1,reason:e}}var uv="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 dm(e,r){let t=e??{},n=[],o;if(!r.canRenice)n.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=Co;else if(t.cpu_weight<jr){let a=Math.round(am*(jr-t.cpu_weight)/jr);o=Math.min(am,Math.max(Co,a))}else o=Co,n.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${jr}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Co}`);let s=lm(t.max_processes);s==null&&t.max_processes!=null&&n.push(`max_processes=${t.max_processes} is not a positive whole number, so no ulimit -u is set`);let i=lm(t.cpu_seconds);return i==null&&t.cpu_seconds!=null&&n.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:uv,...n.length>0?{note:n.join("; ")}:{}}}function cm(e){let{limits:r}=e,t=[];return r.max_processes!=null&&t.push(`ulimit -u ${r.max_processes}`),r.cpu_seconds!=null&&t.push(`ulimit -t ${r.cpu_seconds}`),t.push(r.nice!=null&&e.nice!=null?`exec ${pv(e.nice)} -n ${r.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
|
|
92
|
+
`),e.command,...e.args]}function um(e){let r=[];return e.nice!=null?r.push(`the Worker runs at nice ${e.nice} so it yields to interactive work`):r.push("no priority control was applied"),e.max_processes!=null&&r.push(`its processes are capped at ${e.max_processes}`),e.cpu_seconds!=null&&r.push(`its CPU time is capped at ${e.cpu_seconds} seconds`),`macOS placement applied POSIX limits: ${r.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 Da(e){let r=e??{},t=[r.max_processes!=null?"max_processes":null,r.cpu_seconds!=null?"cpu_seconds":null].filter(n=>n!=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 lm(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function pv(e){return`'${e.replace(/'/g,"'\\''")}'`}var mm="REDSKILLED_PLACEMENT",No="red-worker",ja="/bin/sh";function gm(e=process.env,r=process.platform){let t=Aa(`POSIX rlimit and priority placement is the macOS backend (platform=${r})`);if(r==="win32")return{platform:r,systemdRun:null,userSession:!1,jobObjects:sm({platform:r}),posix:t};let n=pt(`Job Object placement is the Windows backend (platform=${r}), so there is no native reach to load here`);if(r==="darwin")return{platform:r,systemdRun:null,userSession:!1,jobObjects:n,posix:gv(e)};if(r!=="linux")return{platform:r,systemdRun:null,userSession:!1,jobObjects:n,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Ga(pm(o,"systemd","private"));return{platform:r,systemdRun:bm("systemd-run",e),userSession:s,jobObjects:n,posix:t}}function gv(e){return Ga(ja)?{available:!0,shell:ja,nice:bm("nice",e)}:Aa(`no POSIX shell was found at ${ja}, so there is nothing to apply rlimits or priority in`)}function fm(e=process.env){let r=(e[mm]??"").trim().toLowerCase();return r===""?!0:!["off","false","0","no"].includes(r)}function fv(e,r,t=No){return hm(e,r,t).replace(/\.service$/,"")}function hm(e,r,t=No){return`${La(t,"red-worker",24)}-${La(e,"project",32)}-${La(r,"worker",32)}.service`}function ym(e){let r=[...e.args??[]],t={...e.budget??{},...e.budget?.memory_max==null&&e.memoryCeiling?.memory_max!=null?{memory_max:e.memoryCeiling.memory_max}:{}},n=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:r,cwd:e.workspacePath,warning:u,budget:t,...n!=null?{memoryCeiling:n}:{},environment:Mt({scope:null,memory_ceiling:n,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 ${mm}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return yv(e,r,t,n,o,i);if(e.probes.platform==="darwin")return hv(e,r,t,n,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=hm(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=Mt({scope:a,memory_ceiling:n,scope_degradation:null});for(let[u,m]of Object.entries({...e.env??{},...d}))l.push(`--setenv=${u}=${m}`);let c=Da(e.budget);return{isolated:!0,backend:"transient-unit",unit:a,command:e.probes.systemdRun,args:[...l,"--",e.command,...r],budget:t,...n!=null?{memoryCeiling:n}:{},environment:d,...c!=null?{budgetWarning:c}:{}}}function hv(e,r,t,n,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=dm(t,{canRenice:s.nice!=null}),a=t.memory_high!=null||t.memory_max!=null,l=um(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:cm({limits:i,nice:s.nice,command:e.command,args:r}),cwd:e.workspacePath,posix:i,warning:l,budget:t,...n!=null?{memoryCeiling:n}:{},environment:Mt({scope:null,memory_ceiling:n,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 yv(e,r,t,n,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=im(t),l=fv(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...r],cwd:e.workspacePath,job:{name:l,limits:a},budget:t,...n!=null?{memoryCeiling:n}:{},environment:Mt({scope:l,memory_ceiling:n,scope_degradation:null}),...bv(o&&a.note!=null?`${a.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,Da(e.budget))}}function bv(...e){let r=e.filter(t=>t!=null&&t!=="");return r.length>0?{budgetWarning:r.join("; ")}:{}}function bm(e,r){for(let t of(r.PATH??"").split(mv)){if(!t)continue;let n=pm(t,e);if(Ga(n))return n}return null}function La(e,r,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||r}async function $a(e,r){let t=[],n=[];for(let o of e){let s=!1;try{s=await r(o)===!0}catch{s=!1}(s?t:n).push(o)}return{alive:t,dead:n}}var km=3e4;function _m(e){return e.unit!=null&&e.unit!==""?kv(e.unit):oe(e.pid)}function kv(e){let r=Mo("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return r.error!=null?!1:r.status===0}var _v="REDSKILLED_UNIT_DISCOVERY",Rm="(unowned)";function wm(e){let r=Mo("systemctl",["--user","show","--property=MainPID","--value",e],{encoding:"utf8"});if(r.error!=null||r.status!==0)return null;let t=Number.parseInt((r.stdout??"").trim(),10);return Number.isInteger(t)&&t>0?t:null}function Rv(e=process.env){let r=(e[_v]??"").trim().toLowerCase();return r===""?!0:!["off","false","0","no"].includes(r)}function Em(e,r,t=process.env){return Rv(t)&&e===r}function vm(e=No){let r=Mo("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return r.error!=null||r.status!==0?[]:(r.stdout??"").split(`
|
|
93
|
+
`).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function Sm(e){let r=new Set(e.held.map(o=>o.unit).filter(o=>o!=null&&o!=="")),t=new Set,n=[];for(let o of e.units)o===""||r.has(o)||t.has(o)||(t.add(o),n.push({worker_id:o.replace(/\.service$/,""),project_label:Rm,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 n}function Tm(e){return e.project_label.trim()!==""?e:{...e,project_label:Rm,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 xm(e){if(e.unit!=null&&e.unit!==""){let r=Mo("systemctl",["--user","stop",e.unit],{stdio:"ignore"});return r.error==null&&r.status===0}try{return process.kill(e.pid,"SIGTERM"),!0}catch{return!1}}var kn=50,Ca=15e3,kL=2*Ca;function wv(e,r=kn){if(Na(e),!Number.isInteger(r)||r<=0)throw new Error(`redskilled queue discovery needs a whole, positive batch size, not ${JSON.stringify(r)}`);let t=[];for(let n=0;n<e.length;n+=r)t.push(e.slice(n,n+r));return t}function Om(e,r={}){let t=r.batchSize??kn;if(Na(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 n=e.map((i,a)=>({alias:`q${a}`,project:i}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...n.map(({alias:i,project:a})=>` ${i}: search(query: ${JSON.stringify(a.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
|
|
94
|
+
`),aliases:n}}function Am(e,r){let t=bn(r),n=bn(t.data),o=Array.isArray(t.errors)?t.errors.map(bn):[],s=xv(n.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=Ov(n[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 c=o.find(u=>Pv(u.path,a));return s.exhausted||Lm(c)?{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: ${Ia(c?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function Ev(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:kn,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function Dm(e,r,t){return{version:1,fetched_at:r,request_count:0,project_count:e.length,batch_size:kn,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:e.map(n=>({project_label:n.project_label,outcome:"unconfigured",depth:null,detail:`project ${JSON.stringify(n.project_label)} was not counted because this host polls no tracker: ${t}`}))}}async function jm(e){if(e.projects.length===0)return Ev(e.now);if(e.transport.conditionalList)return await Sv(e);let r=e.batchSize??kn,t=wv(e.projects,r),n=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=Om(s,{batchSize:r});try{let a=await e.transport(i.query),l=Am(i,a);n.push(...l.projects),o=yn(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=yn(o,{remaining:null,reset_at:null,exhausted:d});for(let c of s)n.push({project_label:c.project_label,outcome:d?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(c.project_label)} answered: ${l}`})}}return{version:1,fetched_at:e.now,request_count:t.length,project_count:n.length,batch_size:r,rate_limit:o,projects:n}}var vv={key:"redskilled queue poll",budget:"rest"};async function Sv(e){Na(e.projects);let r=e.transport.conditionalList,t=[],n={remaining:null,reset_at:null,exhausted:!1},o=0;for(let s of e.projects)try{if(s.poll==null){let l=Om([s],{batchSize:1}),d=Am(l,await e.transport(l.query));o+=1,t.push(...d.projects),n=yn(n,d.rate_limit);continue}let i=await r({cacheKey:`queue:${s.project_label}:${JSON.stringify(s.poll)}`,route:"GET /repos/{owner}/{repo}/issues",parameters:{owner:s.poll.owner,repo:s.poll.repo,state:"open",labels:s.poll.labels.join(","),...s.poll.creator==null?{}:{creator:s.poll.creator}},operation:vv});o+=i.requestCount;let a=i.data.filter(l=>!Gm(l.pull_request)).length;n=yn(n,Tv(i.headers)),t.push({project_label:s.project_label,outcome:"counted",depth:a,detail:`project ${JSON.stringify(s.project_label)} has ${a} item(s) matching its selector`})}catch(i){let a=Zt(i);n=yn(n,{remaining:null,reset_at:null,exhausted:a}),t.push({project_label:s.project_label,outcome:a?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(s.project_label)} answered: ${i instanceof Error?i.message:String(i)}`})}return{version:1,fetched_at:e.now,request_count:o,project_count:t.length,batch_size:1,rate_limit:n,projects:t}}function Na(e){if(e.length===0)throw new Error("redskilled queue discovery needs at least one registered project");let r=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(r.has(t.project_label))throw new Error(`redskilled holds one selector per project, and ${JSON.stringify(t.project_label)} is registered twice`);r.add(t.project_label)}}function yn(e,r){return{remaining:r.remaining==null?e.remaining:e.remaining==null?r.remaining:Math.min(e.remaining,r.remaining),reset_at:r.reset_at??e.reset_at,exhausted:e.exhausted||r.exhausted}}function Tv(e){let r=Pm(e,"x-ratelimit-remaining"),t=Pm(e,"x-ratelimit-reset");return{remaining:r,reset_at:t==null?null:new Date(t*1e3).toISOString(),exhausted:r===0}}function Pm(e,r){let t=e[r];if(typeof t!="string"&&typeof t!="number")return null;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:null}function xv(e,r){let t=bn(e),n=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null;return{remaining:n,reset_at:o,exhausted:r.some(Lm)||n===0}}function Lm(e){return e==null?!1:Ia(e.type)==="RATE_LIMITED"||/rate limit/i.test(Ia(e.message))}function Pv(e,r){return Array.isArray(e)&&e.includes(r)}function Ov(e){let r=bn(e);return Number.isInteger(r.issueCount)?r.issueCount:null}function bn(e){return Gm(e)?e:{}}function Gm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ia(e){return typeof e=="string"?e:""}function $m(e,r,t){let n=e?.rate_limit;if(n==null)return r;if(n.exhausted){let s=n.reset_at==null?Number.NaN:Date.parse(n.reset_at),i=Number.isFinite(s)?s-t+1e3:r*4;return Math.min(Av,Math.max(r,i))}let o=n.remaining;return o==null?r:o<=Dv?Math.max(r,3e4):o<=jv?Math.max(r,2e4):r}var Av=1e5,Dv=250,jv=1e3;var Lv={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,wait_kind:null,wait_subject:null,wait_pid:null,wait_started_at:null,wait_deadline:null,wait_escalation:null,started_at:null,context:null,eta:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},Gv=["runner","model","effort","origin","issue","phase","step","heartbeat","wait_kind","wait_subject","wait_started_at","wait_deadline","wait_escalation","started_at"],$v=["phase_index","phase_total","wait_pid","context","eta","added","removed","tokens","tools","reasoning","text"];function Im(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let r=e,t={...Lv};for(let n of Gv){let o=r[n];t[n]=typeof o=="string"&&o.trim()!==""?o:null}for(let n of $v){let o=r[n];t[n]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=r.failed===!0,t}import{randomInt as Mv}from"node:crypto";import{spawn as Fv}from"node:child_process";import{appendFileSync as Wv,mkdirSync as Uv}from"node:fs";import{dirname as Bv}from"node:path";import{delimiter as Cm,dirname as Iv}from"node:path";function Cv(e,r=Cm){return(e??"").split(r).map(t=>t.trim()).filter(t=>t!=="")}function Nv(e=process.execPath){let r=(e??"").trim();if(r==="")return null;let t=Iv(r);return t===""||t==="."?null:t}function Nm(e,r=process.execPath,t=Cm){let n=Cv(e,t),o=Nv(r);return o==null?n.join(t):[o,...n.filter(s=>s!==o)].join(t)}var mt=class extends Error{constructor(r){super(r),this.name="RedskilledWorkerSpecError"}},Fo=class extends Error{constructor(t,n){super(t);this.admission=n;this.name="RedskilledAdmissionError"}},Ma="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",Fm=4,Hv=Ma.length**Fm;function Fa(e,r=Mv){let t=new Set(e);for(let n=0;n<Hv;n+=1){let o="h";for(let s=0;s<Fm;s+=1)o+=Ma[r(Ma.length)];if(!t.has(o))return o}throw new mt("redskilled exhausted the host Worker id space")}function qv(e){if(e==null||e.trim()==="")return!1;try{return Uv(Bv(e),{recursive:!0}),!0}catch{return!1}}function Vv(e,r){let t=(n,o)=>{if(n==null)return;let s="",i=a=>{try{Wv(r,ge().push({at:new Date().toISOString(),kind:o,msg:a}),"utf8")}catch{}};n.on("data",a=>{s+=String(a);let l=s.split(`
|
|
95
|
+
`);s=l.pop()??"";for(let d of l)i(d)}),n.on("end",()=>{s!==""&&i(s)})};t(e.stdout,"worker.stdout"),t(e.stderr,"worker.stderr")}function Kv(e){let r=[["project_label",e.project_label],["workspace_path",e.workspace_path],["command",e.command]];for(let[t,n]of r)if(typeof n!="string"||n.trim()==="")throw new mt(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new mt("redskilled worker spec args must be an array")}function Jv(e){if(e==null)throw new Fo("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new Fo(e.reason,e)}function Wm(e){let{spec:r,admission:t}=e;Jv(t),Kv(r);let n=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(r.worker_id??e.workerId)?.trim()||Fa(e.liveWorkerIds??[]),i=e.probes??gm(n),a=e.openLog===!1?!1:qv(r.log_path),l={...r.env??{},PATH:Nm(r.env?.PATH??n.PATH,e.execPath??process.execPath)},d=ym({workerId:s,projectLabel:r.project_label,workspacePath:r.workspace_path,command:r.command,args:r.args,budget:r.budget,...e.memoryCeiling!=null?{memoryCeiling:e.memoryCeiling}:{},target:r.placement,env:l,enabled:e.enabled??fm(n),probes:i,pipeOutput:a}),u=(e.spawnFn??Fv)(d.command,d.args,{...d.cwd!=null?{cwd:d.cwd}:{},detached:!0,stdio:a?["ignore","pipe","pipe"]:"ignore",env:d.backend==="transient-unit"?{...n}:{...n,...l,...d.environment}});if(a&&r.log_path!=null&&Vv(u,r.log_path),u.pid==null)throw u.once("error",()=>{}),new mt(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${s}`);let m=d.job!=null?zv(d,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(y,S)=>{try{m?.job?.close()}catch{}e.onExit?.(s,y,S)}),u.unref();let f=d.job!=null?m?.job!=null:d.isolated,h=[d.warning,m?.warning,d.budgetWarning].filter(y=>y!=null);return{worker:{worker_id:s,project_label:r.project_label,pid:u.pid,started_at:o(),workspace_path:r.workspace_path,...r.log_path!=null?{log_path:r.log_path}:{},isolated:f,...d.unit!=null?{unit:d.unit}:{},...r.budget!=null?{budget:r.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,...m?.job!=null?{job:m.job}:{}}}function zv(e,r,t){let n=e.job;if(n==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(!r.jobObjects.available)return{warning:`Job Object placement unavailable: ${r.jobObjects.reason}. ${o}`};let s;try{s=r.jobObjects.binding.createJobObject({name:n.name,limits:n.limits})}catch(i){return{warning:`Job Object ${JSON.stringify(n.name)} could not be created: ${Mm(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(n.name)}: ${Mm(i)}. ${o}`}}return{job:s}}function Mm(e){return e instanceof Error?e.message:String(e)}import{open as Qv,stat as Yv}from"node:fs/promises";var Xv=16*1024;async function Um(e,r=Xv){let t;try{t=(await Yv(e)).size}catch{return null}if(t<=0)return null;let n=Math.min(r,t),o;try{let s=await Qv(e,"r");try{let i=Buffer.alloc(n);await s.read(i,0,n,t-n),o=i.toString("utf8")}finally{await s.close()}}catch{return null}return Zv(o)}function Zv(e){let r=e.split(`
|
|
96
|
+
`);for(let t=r.length-1;t>=0;t-=1){let n=r[t].replace(/\r$/,"");if(n.trim()!=="")return n}return null}import{spawn as gS}from"node:child_process";import{existsSync as fS,readdirSync as hS}from"node:fs";import{dirname as yS,join as Jm,resolve as bS}from"node:path";var eS="<version>";function mr(e,r=[],t){let n=t&&t.trim().length>0?t.trim():eS;return[`npx -y -p ${Tr}@${n}`,e,...r].join(" ")}function De(e){let r=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return r?{major:Number(r[1]),minor:Number(r[2]),patch:Number(r[3])}:null}function Wa(e,r){let t=De(e),n=De(r);return!t||!n?0:t.major-n.major||t.minor-n.minor||t.patch-n.patch}var ML=4*60*60*1e3;Ke();Ke();import{spawnSync as rS}from"node:child_process";import{mkdir as tS,rm as nS,writeFile as oS}from"node:fs/promises";import{existsSync as sS}from"node:fs";import{homedir as iS}from"node:os";import{dirname as aS,join as Ua}from"node:path";var gt="redskilled.service",Ba="REDSKILLED_SUPERVISED",lS="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function dS(e=process.env){let r=e.XDG_CONFIG_HOME?.trim()||Ua(e.HOME?.trim()||iS(),".config");return Ua(r,"systemd","user")}function Ha(e=process.env){return Ua(dS(e),gt)}function Bm(e,r={}){let t=r.env??process.env,n=ao(r.override??{},r.entryLookup??{}),o=[...n.args,...vr(e,r.idleMs==null?{}:{idleMs:r.idleMs})];return{unitName:gt,unitPath:Ha(t),command:n.command,args:o,text:cS(n.command,o,e)}}function cS(e,r,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${lS}`,"","[Service]","Type=simple",`ExecStart=${[e,...r].map(uS).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Ba}=1"`,`Environment="REDSKILLED_SESSION=${Hm(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
|
|
97
|
+
`)}function uS(e){return/[\s"'\\$%]/.test(e)?`"${Hm(e)}"`:e}function Hm(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function qm(e,r={}){let t=r.writeFile??pS,n=r.run??qa,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(Wo("daemon-reload",n,["systemctl","--user","daemon-reload"])),o.push(Wo("enable",n,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function Vm(e={}){let r=e.removeFile??mS,t=e.run??qa,n=Ha(e.env??process.env),o=[Wo("disable",t,["systemctl","--user","disable","--now",gt])];return await r(n),o.push({step:"remove-unit",ok:!0,detail:n}),o.push(Wo("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:n,installed:!1,steps:o}}function Km(e={}){let r=e.exists??sS,t=e.run??qa,n=Ha(e.env??process.env),o=r(n);return{unitName:gt,unitPath:n,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",gt]).status===0,active:o&&t(["systemctl","--user","is-active",gt]).status===0,floor:"auto-spawn"}}function Wo(e,r,t){let n=r(t),o=(n.stderr??n.stdout??"").trim();return{step:e,argv:t,ok:n.status===0,...o?{detail:o}:{}}}async function pS(e,r){await tS(aS(e),{recursive:!0}),await oS(e,r,{encoding:"utf8",mode:420})}async function mS(e){await nS(e,{force:!0})}function qa(e){let r=rS(e[0],[...e.slice(1)],{encoding:"utf8"});return r.error!=null?{status:null,stderr:r.error.message}:{status:r.status,stdout:r.stdout??"",stderr:r.stderr??""}}var zm=75,Ym=9e5,Qm="redskilled-replacement-entry-unresolved",kS="REDSKILLED_NO_REGISTRY_PROBE",Xm="REDSKILLED_BORN_BY_REPLACEMENT";function Zm(e=process.env){return e[Xm]==="1"}function eg(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function rg(e){let r=e.running.trim();if(_n(r))return null;let t=e.newest?.trim()??"",n=De(t),o=De(r);return n===null||o===null||n.major<=o.major?null:{version:t,running_major:o.major,held_major:n.major,reason:`redskilled ${t} is published and this daemon runs ${r}; 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:_S(n.major,e.supervised)}}function _S(e,r){let t=`install the ${e}.x bundle (update this machine's plugin pin), then `;return r?`${t}re-point the unit and restart it: ${mr("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 tg(e){let r=e.running.trim();if(_n(r))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||De(t)===null?{act:"hold",reason:"published-unknown"}:Wa(t,r)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function _n(e){let r=e.trim();return De(r)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(r)}function ng(e=process.env){return e[Ba]==="1"}var Va=class extends Error{code=Qm;searched;constructor(r,t){super(`${Qm}: the published redskilled bundle ${r} exists on no reachable path and the version-pinned dispatch is disabled
|
|
96
98
|
searched:
|
|
97
99
|
${t.map(n=>` ${n}`).join(`
|
|
98
|
-
`)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function
|
|
99
|
-
`}function wS(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return ue(r)}catch{return null}}}function ES(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;if(r.version!==1||!Number.isInteger(r.pid)||r.pid<=0)return!1;for(let t of["start_time","session_key_hash","machine_id_hash","socket_path","acquired_at","renewed_at"])if(typeof r[t]!="string"||r[t].length===0)return!1;return!0}var _n=3e5,AS=1e4,DS=6e4,jS=15e3,LS=3e4,IS=6e4,Uo=16;function $S(e,r={}){if(e.event!=="worker-death"&&e.event!=="worker-budget-kill")return null;let t=e.event==="worker-budget-kill",n=!t&&r.refusal!=null,o=r.refusal??e.detail??`redskilled observed exit code=${e.exit_code??"null"} signal=${e.signal??"null"}`,s=r.startedAt==null?null:Date.parse(r.startedAt),i=Date.parse(e.ts),a=s!=null&&Number.isFinite(s)&&Number.isFinite(i)?Math.max(0,i-s)/1e3:void 0;return{version:1,ts:e.ts,kind:"worker",id:e.worker_id,pid:e.pid,last_seen:e.ts,last_phase:n?"boot-refused":"unreported",sender_class:t?"teardown":n?"boot-refused":"unknown",confidence:t||n?"high":"none",signal:e.signal,host_boot_changed:!1,evidence:t||n?[o]:[],checked:n?["Worker log tail"]:[`redskilled host event: ${o}`],project_label:e.project_label,...a===void 0?{}:{uptime_s:a},detail:r.refusal??e.detail}}function mg(e){let r=e?.match(/\bsession-error:\s*(.+)$/)?.[1]?.trim();return r==null||r===""?null:r}var Dr=class extends Error{constructor(t,n){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=n;this.name="RedskilledAlreadyRunningError"}},GS="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function fg(e){let{paths:r}=e,t=e.daemonVersion??"0.0.0-dev",n=e.idleMs??_n,o=e.clock??(()=>new Date().toISOString()),s=e.launch??Gm,i=e.ceiling??co();e.repositoryActivity!=null&&da(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??cg(),l=e.leaseStore??ug(r.leasePath,{sessionKeyHash:r.sessionKeyHash,machineIdHash:r.machineIdHash,socketPath:r.socketPath},{clock:o}),d=e.machineOwner??zc(),c={machineIdHash:r.machineIdHash,sessionKeyHash:r.sessionKeyHash,socketPath:r.socketPath},u=e.machineClaimStore??po(r.machineClaimPath,c,{clock:o});await TS(OS(r.socketPath),{recursive:!0,mode:448});let m=await u.claim(d);if(!m.claimed)throw m.claim?.socket_path===r.socketPath?new Dr(r.socketPath):new nr(u.claimPath,m.reason,m.claim);let h=await l.acquire(a);if(!h.acquired)throw await u.release(d).catch(()=>{}),new Dr(r.socketPath,h.lease);let f;try{f=await NS(r.socketPath,async()=>{let[p,y]=await Promise.all([l.read().catch(()=>{}),u.read().catch(()=>{})]);return p!=null&&p.pid!==a.pid&&oe(p.pid)?!0:y!=null&&y.socket_path===r.socketPath&&y.pid!==d.pid&&oe(y.pid)})}catch(p){throw await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),p}let S=o(),_=e.eventLane??Lc(r.eventLanePath),v=e.registrationIntentStore??Yp(r.registrationIntentPath),C=e.liveness??fm,H=e.livenessGraceMs??gm,L=e.stopWorker??wm,Q=e.unitInventory??(()=>km(r.machineClaimPath,uo({machineIdHash:r.machineIdHash}))?bm():[]),ee=e.unitMainPid??ym,le=e.treeSampler??wp,Ye=e.readLogTail??Cm,Lr=e.sampleMs??jS,mt=e.leaseRenewMs??LS,Sn=e.registrationSustainMs??IS,gt=e.publishedVersion??(p=>rg(p)),ft=e.replaceCheckMs??Vm,Tn=e.publishedProbeTimeoutMs??AS,xn=e.localPublishedEvidence??(p=>tg(p,e.replacementIO?.env??process.env)),zo=e.bornByReplacement??Jm(),Pn=e.replaceBootCheckMs??DS,ht=e.supervised??Xm(),yt=e.replacementIO??{},he=e.repositoryActivity,kt=he?.intervalMs??la,pr=e.githubBalance,De=e.queueDiscovery,mr=De?.transport??he?.transport,Ir=De?.unconfiguredReason??GS,Xe=De?.intervalMs??Ga,On=e.demandMs??15e3,An=e.demandBackoffMs??3e4,N=new Map,we=new Set,Ze=new Map,$r=new Map,bt=[],gr=[],fr=e.deaths===void 0?void 0:[...e.deaths],_t=await v.read().catch(()=>[]),hr=Date.parse(S),W=new Map,Y=new Map;for(let p of _t){let y=Date.parse(p.renew_by);!Number.isFinite(hr)||!Number.isFinite(y)||y>=hr?W.set(p.project_label,p):hr-y<=p.renew_within_ms&&Y.set(p.project_label,p)}let Gr=new Set,Rt={},Cr=null,Nr=null,de=null,wt=!1,Mr=0,Et=null,D="none",k=null,g=null,b=null,R=null,w=null,T=null,O=[],$=[],q=new Map((e.orphanedRegistrations??[]).map(p=>[p.project_label,p])),B=null,X={},vt=!1,Be,St,Tt,xt,Pt,Ot,Dn,At,Fr,Wr,ce=!1,Qo=!1,jn=null,ll,Yo=new Promise(p=>{ll=p});function Ur(p){dl(p);let y=Date.parse(p),E=tu(W.values(),y);for(let P of E.lapsed){W.delete(P.project_label);let A=w?.projects.find(I=>I.project_label===P.project_label),j=[...N.values()].some(I=>I.project_label===P.project_label);(A?.outcome==="counted"&&(A.depth??0)>0||j)&&Y.set(P.project_label,P),tf(P,y)}return E.lapsed.length>0&&Br(),E.lapsed}function Br(){let p=new Map(Y);for(let[y,E]of W)p.set(y,E);v.replace([...p.values()]).catch(()=>{})}function tf(p,y){let E=Number.isFinite(y)?new Date(y).toISOString():p.renew_by;O.push({project_label:p.project_label,registered_at:p.registered_at,at:E,renew_by:p.renew_by,renewals:p.renewals,sustains:p.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(p.project_label)}: it stood until ${p.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`}),O.length>Uo&&O.splice(0,O.length-Uo)}function dl(p){if(W.size===0)return;let y=Date.parse(p);if(!Number.isFinite(y))return;let E={};for(let I of N.values())E[I.project_label]=(E[I.project_label]??0)+1;let P=w==null?Number.NaN:Date.parse(w.fetched_at),A=new Map((w?.projects??[]).map(I=>[I.project_label,I])),j=!1;for(let I of[...W.values()]){let Ee=Number.isFinite(P)&&y-P<=I.renew_within_ms?A.get(I.project_label):void 0,G=wi(I,{now:p,...Ee==null?{}:{queue:{outcome:Ee.outcome,depth:Ee.depth}},liveWorkers:E[I.project_label]??0});G.registration!==I&&(W.set(I.project_label,G.registration),j=!0)}j&&Br()}function cl(p){if(Y.size===0)return;let y=Date.parse(p);if(!Number.isFinite(y))return;let E=new Map((w?.projects??[]).map(A=>[A.project_label,A])),P=!1;for(let[A,j]of[...Y]){if(y-Date.parse(j.renew_by)>j.renew_within_ms){Y.delete(A),P=!0;continue}let I=E.get(A),Z=wi(j,{now:p,...I==null?{}:{queue:{outcome:I.outcome,depth:I.depth}},liveWorkers:[...N.values()].filter(Ee=>Ee.project_label===A).length});Z.verdict==="open-work"||Z.verdict==="live-worker"?(W.set(A,Z.registration),Y.delete(A),P=!0):Z.verdict==="drained"&&(Y.delete(A),P=!0)}P&&Br()}function Ln(){let p=o();return Ur(p),zp({now:p,daemonVersion:t,machineIdHash:r.machineIdHash,sessionKeyHash:r.sessionKeyHash,pid:a.pid,startedAt:S,ceiling:i,scope:Qc(u.claimPath,c,d),workers:[...N.values()],registrations:[...W.values()],demand:T,lapses:O,stops:$,orphanedRegistrations:[...q.values()],birthLatches:Fc(X,Date.parse(p)),queue:w,published:{version:Nr,checkedAt:de,newer:wt,replacement:D,newest:k,majorHold:g,checks:Mr,holdReason:Et}})}function In(){return Gp({hostState:Ln(),ceiling:i,rss:Rt,sampledAt:Cr,logLines:Object.fromEntries(Ze),displays:Object.fromEntries($r),now:o(),reattachedWorkerIds:[...we],repositoryActivity:b,githubBalance:R,...fr===void 0?{}:{deaths:fr},metrics:bp({observations:bt,outcomes:gr,now:o()})})}function nf(p,y){bt=Zt([...bt,{worker_id:y,observed_at:p.published_at,tokens:p.display.tokens,tools:p.display.tools,runner:p.display.runner,model:p.display.model}],E=>E.observed_at,{now:o()})}function of(p){gr=Zt([...gr,p],y=>y.ts,{now:o()})}async function Xo(){return he==null||he.projects.length===0?null:(b=await Op({projects:he.projects,hostTokenRef:he.hostTokenRef,transport:he.transport,closedWindowMs:he.closedWindowMs,now:o()}),b)}async function ul(){return pr==null?null:(R=await Zi({transport:pr.transport,now:o()}),R)}function sf(){if(ce||Fr!=null||pr==null)return;let p=()=>{Fr=void 0,ul().catch(()=>{}).then(()=>{if(ce)return;let y=pr.intervalMsOverride??xo(R??af(),{now:o()});Fr=setTimeout(p,y),Fr.unref()})};p()}function af(){return To(o())}function lf(){if(!(mr!=null||De?.armTransport==null))try{let p=De.armTransport();if(p.transport!=null){mr=p.transport;return}p.unconfiguredReason!=null&&(Ir=p.unconfiguredReason)}catch(p){Ir=`this host could not resolve a tracker credential: ${p instanceof Error?p.message:String(p)}`}}async function pl(){let p=o();Ur(p);let y=Date.parse(p);for(let[j,I]of[...Y])Number.isFinite(y)&&y-Date.parse(I.renew_by)>I.renew_within_ms&&Y.delete(j);let P=[...new Map([...Y,...W]).values()].map(j=>({project_label:j.project_label,selector:j.selector,...j.queue_poll==null?{}:{poll:j.queue_poll}})).sort((j,I)=>j.project_label.localeCompare(I.project_label));if(P.length===0)return null;if(lf(),mr==null)return w=Tm(P,p,Ir),w;w=await xm({projects:P,transport:mr,now:p,...De?.batchSize==null?{}:{batchSize:De.batchSize}});let A=o();return cl(A),dl(A),w}async function ml(){let p=o();if(vt)return T??Gc(p);vt=!0;try{await es().catch(()=>{});let y={};for(let G of N.values())y[G.project_label]=(y[G.project_label]??0)+1;let E={};for(let G of w?.projects??[])E[G.project_label]=G.depth;let P=Date.parse(p),A=Number.isFinite(P)?P:0;for(let[G,ye]of Object.entries(X)){if(ye.probeWorkerId==null)continue;let Fn=N.get(ye.probeWorkerId);Fn!=null&&A-Date.parse(Fn.started_at)>=6e4&&(X[G]=mi())}let j=$c({projects:[...W.values()].map(G=>({project_label:G.project_label,selector:G.selector,argv:G.argv,workspace_path:G.workspace_path,target:G.target})),queue:E,live:y,nowMs:A,backoffUntilMs:B,birthHealth:X}),I=[],Z=null;for(let G of j.births){let ye,Fn=Ma(N.keys()),Wn=W.get(G.project_label),Pl=Xc({argv:G.argv,...Wn?.env==null?{}:{env:Wn.env},...Wn?.log_path==null?{}:{log_path:Wn.log_path}},{worker_id:Fn,slot:G.index,workspace_path:G.workspace_path},{project_label:G.project_label});try{ye=Zo(Pl)}catch(ss){Z=ss instanceof Error?ss.message:String(ss),B=(Number.isFinite(P)?P:Date.now())+An;break}I.push({project_label:G.project_label,worker_id:ye.worker.worker_id,pid:ye.worker.pid,warnings:Pl.log_path==null?[...ye.warnings,`project ${JSON.stringify(G.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(ye.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:ye.warnings});let os=X[G.project_label];os?.haltUntilMs!=null&&A>=os.haltUntilMs&&(X[G.project_label]=Mc(os,ye.worker.worker_id))}Z==null&&j.births.length>0&&(B=null);let Ee=new Set(I.map(G=>G.project_label));for(let G of j.intents){if(G.queue_depth==null||G.queue_depth<=0||G.live>=G.target||Ee.has(G.project_label))continue;let ye=Z!=null&&(G.outcome==="asking"||G.outcome==="half-open-probe")?`project ${JSON.stringify(G.project_label)} was birth-eligible but the host refused it: ${Z}`:G.detail;await _.recordDemandRefusal({ts:p,projectLabel:G.project_label,detail:ye}).catch(()=>{})}return T={version:1,at:p,requested:j.births.length,granted:I,shortfall:j.births.length-I.length,refusal:Z,retry_after:B==null?null:new Date(B).toISOString(),projects:j.intents},T}finally{vt=!1}}function df(p){return Or(In(),{...U,mode:p?.mode??U.mode,project:p?.project??U.project,maxWorkers:p?.max_workers??U.maxWorkers,maxProjects:p?.max_projects??U.maxProjects,maxWidth:p?.max_width??U.maxWidth,verbose:p?.verbose??U.verbose})}function cf(p){return lt(In(),{mode:p?.mode??Fe.mode,project:p?.project??Fe.project,maxWidth:p?.max_width??Fe.maxWidth,maxRows:p?.max_rows??Fe.maxRows})}function yr(p,y,E){return su({op:p,sessionProject:y??null,targetProject:E})}async function uf(p){let y=N.get(p.worker_id),E=yr(ou(p.command),p.session_project,y?.project_label??null);if(!E.permitted)throw new Error(E.reason);if(p.command!=="stop")throw new Error(`redskilled does not implement ${p.command}: it owns birth, death and limits, and ${p.command} is a work decision the project's own bundle makes on top of them`);let P=y!=null&&await hf(y,p.detail??"stopped by its own project");return{version:1,command:p.command,worker_id:p.worker_id,applied:P,reach:E,detail:P?`redskilled stopped Worker ${JSON.stringify(p.worker_id)} of project ${JSON.stringify(y.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(p.worker_id)} to stop`}}function $n(p){N.delete(p),we.delete(p),Ze.delete(p),$r.delete(p)}function gl(p){let y=N.get(p.worker_id),E=yr("worker-heartbeat",p.session_project,y?.project_label??null);if(!E.permitted)throw new Error(E.reason);if(typeof p.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:p.worker_id,accepted:!1,reach:E,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(p.worker_id)} to publish a line for`};let P=o();Ze.set(p.worker_id,{line:p.last_log_line,published_at:P,source:"heartbeat"});let A=p.display===void 0?null:Dm(p.display);if(A!=null){let j={display:A,published_at:P};$r.set(p.worker_id,j),nf(j,p.worker_id)}return{version:1,worker_id:p.worker_id,accepted:!0,reach:E,published_at:P,detail:`redskilled stored a line for Worker ${JSON.stringify(p.worker_id)} without reading it`}}async function pf(p,y,E){let P=`exit code=${y??"null"} signal=${E??"null"}`;if(p.unit!=null&&p.unit!==""&&await gf(p)){ff(p,`its launch client ended (${P}) while unit ${JSON.stringify(p.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}let A=p.log_path==null?null:mg(await Ye(p.log_path).catch(()=>null));$n(p.worker_id),He("worker-death",p,A==null?P:`session-error: ${A}`,{exitCode:y,signal:E,refusal:A}),re()}function mf(p,y){if(!Number.isFinite(y)||y<0){X[p]=qt;return}let E=X[p]??qt,P=Nc(E,y,Date.parse(o()));X[p]=P,P.haltUntilMs!=null&&E.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(p)} lost ${P.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(P.haltUntilMs).toISOString()}
|
|
100
|
-
`)}function fl(p,y){let E=yr("project-reset",y,p);if(!E.permitted)throw new Error(E.reason);let P=X[p]?.haltUntilMs!=null||X[p]?.probeWorkerId!=null;return X[p]=mi(),{version:1,project_label:p,latch:"project-birth-breaker",reset:P,reach:E,detail:P?`redskilled cleared project ${JSON.stringify(p)}'s birth breaker; the next demand tick may birth normally`:`redskilled found no open birth breaker for project ${JSON.stringify(p)}; nothing changed`}}async function gf(p){try{return await C(p)===!0}catch{return!1}}function ff(p,y){let E=p.unit==null?null:ee(p.unit);N.set(p.worker_id,{...p,...E!=null&&E>0?{pid:E}:{},warnings:[...p.warnings,y]}),we.add(p.worker_id),re()}function hl(p,y){let E=yr("project-register",y,p.project_label);if(!E.permitted)throw new Error(E.reason);let P=o();Ur(P);let A=Zc(p,{now:P,held:W.get(p.project_label)});return W.set(A.project_label,A),Br(),bl(A.project_label),re(),{version:1,registration:A,reach:E,detail:`redskilled holds a registration for project ${JSON.stringify(A.project_label)} at a target of ${A.target} until ${A.renew_by}, and has read neither its selector nor its argv`}}function yl(p,y={}){let E=yr("project-renew",y.sessionProject,p);if(!E.permitted)throw new Error(E.reason);let P=o();Ur(P);let A=W.get(p);if(A==null){if(q.has(p))throw new Sr(p,{kind:"orphaned"});let I=[...$].reverse().find(Ee=>Ee.project_label===p);if(I!=null)throw new Sr(p,{kind:"stopped",at:I.at});let Z=[...O].reverse().find(Ee=>Ee.project_label===p);throw Z!=null?new Sr(p,{kind:"lapsed",at:Z.at,...Z.registered_at==null?{}:{registered_at:Z.registered_at}}):new Sr(p)}let j=eu(A,{now:P,...y.renewWithinMs==null?{}:{renew_within_ms:y.renewWithinMs},...y.launch==null?{}:{launch:y.launch}});return W.set(j.project_label,j),Br(),re(),{version:1,registration:j,reach:E,detail:`redskilled renewed the registration for project ${JSON.stringify(j.project_label)}, which now stands until ${j.renew_by} after renewal ${j.renewals}`+(y.launch==null?"":`, carrying launch revision ${j.launch_revision} for its next Worker`)}}function kl(p,y){let E=yr("project-deregister",y,p);if(!E.permitted)throw new Error(E.reason);let P=W.get(p)??Y.get(p),A=W.delete(p),j=Y.delete(p),I=A||j;if(P!=null){let Z=`redskilled released the registration for project ${JSON.stringify(p)}`;bl(p),$.push({project_label:p,registered_at:P.registered_at,at:o(),detail:Z}),$.length>Uo&&$.splice(0,$.length-Uo)}return I&&Br(),{version:1,project_label:p,released:I,reach:E,detail:I?`redskilled released the registration for project ${JSON.stringify(p)}`:`redskilled held no registration for project ${JSON.stringify(p)}, so there was nothing to release`}}function bl(p){Y.delete(p);for(let y=O.length-1;y>=0;y-=1)O[y].project_label===p&&O.splice(y,1);for(let y=$.length-1;y>=0;y-=1)$[y].project_label===p&&$.splice(y,1);q.delete(p)}async function hf(p,y){try{await L(p)}catch{}return $n(p.worker_id),He("worker-death",p,y),re(),!0}function _l(p){return Pc({ceiling:i,workers:[...N.values()],budget:p.budget,projectLabel:p.project_label,...p.reservation==null?{}:{reservation:p.reservation}})}function Zo(p){let y=Oc({ceiling:i,workers:[...N.values()],budget:p.budget}),E=s({spec:p,admission:_l(p),memoryCeiling:y,liveWorkerIds:N.keys(),clock:o,onExit:(P,A,j)=>{let I=N.get(P);if(I==null){re();return}pf(I,A,j).catch(()=>{})}});return N.set(E.worker.worker_id,E.worker),He("worker-birth",E.worker,null),re(),E}function He(p,y,E,P={}){if(ce)return;let A=o();(p==="worker-death"||p==="worker-budget-kill")&&(of({worker_id:y.worker_id,ts:A,outcome:p}),Rl({version:1,ts:A,event:p,worker_id:y.worker_id,project_label:y.project_label,pid:y.pid,workspace_path:y.workspace_path,log_path:y.log_path??null,isolated:y.isolated,unit:y.unit??null,memory_high:y.budget?.memory_high??null,memory_max:y.budget?.memory_max??null,cpu_weight:y.budget?.cpu_weight??null,detail:E,reason:null,exit_code:P.exitCode??null,signal:P.signal??null},{startedAt:y.started_at,...P.refusal==null?{}:{refusal:P.refusal}}),mf(y.project_label,Date.parse(A)-Date.parse(y.started_at))),_.record({event:p,worker:y,ts:A,detail:E,...P.exitCode!==void 0?{exitCode:P.exitCode}:{},...P.signal!==void 0?{signal:P.signal}:{}}).catch(()=>{})}function Rl(p,y={}){let E=$S(p,y);if(E==null)return;let P=[E,...(fr??[]).filter(A=>A.kind!==E.kind||A.id!==E.id||A.ts!==E.ts)].sort((A,j)=>Date.parse(A.ts)-Date.parse(j.ts));fr=Zt(P,A=>A.ts,{now:o()})}async function es(){let p=Date.parse(o()),y=[...N.values()].filter(P=>{if(we.has(P.worker_id))return!0;let A=Date.parse(P.started_at);return!Number.isFinite(A)||p-A>=H});if(y.length===0)return[];let{dead:E}=await Ia(y,C);for(let P of E)$n(P.worker_id),He("worker-death",P,"the host no longer confirms this Worker");return E.length>0&&re(),E}async function wl(p,y){let E=N.get(p);if(!E)return!1;try{await L(E)}catch{}return $n(p),He("worker-budget-kill",E,y),re(),!0}async function El(){let p=[...N.values()];if(p.length===0)return[];let y;try{y=await le(p)}catch{return[]}let E=y.rss;Rt=E,Cr=o(),yf(y.cpu_seconds,Cr);let{terminations:P}=Rp({workers:p,rss:E}),A=[];for(let j of P)await wl(j.worker_id,j.reason)&&A.push(j);return A}function yf(p,y){for(let[E,P]of Object.entries(p)){if(typeof P!="number"||!Number.isFinite(P))continue;let A=N.get(E);A&&N.set(E,{...A,cpu:{cpu_seconds:P,sampled_at:y}})}}async function kf(){try{return Tn<=0?await gt(t):await new Promise(p=>{let y=setTimeout(()=>p(rs()),Tn);y.unref(),gt(t).then(E=>{clearTimeout(y),p(E)},()=>{clearTimeout(y),p(rs())})})}catch{return rs()}}function rs(){try{return xn(t)}catch{return null}}async function vl(){if(kn(t))return Mr+=1,de=o(),Et="local-build",{act:"hold",reason:"local-build"};let p=zm(await kf()),y=p.version;Nr=y,k=p.newest??null,de=o(),g=Qm({running:t,newest:k,supervised:ht});let E=Ym({running:t,published:y,supervised:ht});return wt=E.act==="replace",Mr+=1,Et=E.act==="hold"?E.reason:null,D!=="in-progress"&&(D=E.act==="replace"?"pending":"none"),E}async function Gn(){let p=await vl();if(p.act!=="replace"||D==="in-progress")return p;let y=Zm(p,yt);return D="in-progress",await _.flush().catch(()=>{}),await v.flush().catch(()=>{}),await Nn({reason:"replaced"}),eg(y,r,{...n==null?{}:{idleMs:n},io:yt}),p}function bf(){ce||Ot!=null||ft<=0||(!zo&&Pn>0&&(Dn=setTimeout(()=>{Gn().catch(()=>{})},Pn),Dn.unref()),Ot=setInterval(()=>{Gn().catch(()=>{})},ft),Ot.unref())}async function Sl(){return await l.renew(a).catch(()=>null)}function _f(){ce||Tt!=null||mt<=0||(Tt=setInterval(()=>{Sl()},mt),Tt.unref())}function Rf(){ce||xt!=null||Sn<=0||(xt=setInterval(()=>{Ur(o())},Sn),xt.unref())}function wf(){ce||St!=null||Lr<=0||(St=setInterval(()=>{El().catch(()=>{})},Lr),St.unref())}function Ef(){ce||At!=null||he==null||he.projects.length===0||kt<=0||(Xo().catch(()=>{}),At=setInterval(()=>{Xo().catch(()=>{})},kt),At.unref())}function vf(){if(ce||Wr!=null||Xe<=0)return;let p=y=>{Wr=setTimeout(()=>{Wr=void 0,pl().catch(()=>{}).finally(()=>{if(ce)return;let E=Date.parse(o());p(Am(w,Xe,Number.isFinite(E)?E:Date.now()))})},y),Wr.unref()};p(Xe)}function Sf(){ce||Pt!=null||On<=0||(Pt=setInterval(()=>{ml().catch(()=>{})},On),Pt.unref())}function re(){ce||(Be&&clearTimeout(Be),Be=setTimeout(()=>{es().catch(()=>{}).then(()=>Tl())},n),Be.unref())}function Tl(){return N.size>0?(re(),"held-by-workers"):(Ur(o()),W.size>0?(re(),"held-by-registrations"):(Tf(),"exited"))}async function Tf(){if(!kn(t)){if((await Gn().catch(()=>null))?.act==="replace"||Qo||ce)return;if(N.size>0||W.size>0){re();return}}await Nn({reason:"idle"})}function Cn(p){return Uc({reason:p,socketPath:r.socketPath,daemonVersion:t,pid:a.pid,workers:[...N.values()],projects:[...W.keys()]})}function xl(p){if(jn!=null)return jn;let y=p.reason??"requested",E=p.note?.trim();return jn=_.recordDaemonStop({ts:o(),pid:a.pid,socketPath:r.socketPath,reason:y,detail:E==null||E===""?Cn(y).detail:`${Cn(y).detail} \u2014 ${E}`,...p.signal==null?{}:{signal:p.signal}}).catch(()=>{}),jn}async function Nn(p={}){if(Qo)return await Yo;Qo=!0,await xl(p),ce=!0,Be&&clearTimeout(Be),St&&clearInterval(St),Tt&&clearInterval(Tt),xt&&clearInterval(xt),Ot&&clearInterval(Ot),Dn&&clearTimeout(Dn),At&&clearInterval(At),Fr&&clearTimeout(Fr),Wr&&clearTimeout(Wr),Pt&&clearInterval(Pt),await _.flush().catch(()=>{}),await v.flush().catch(()=>{}),f.close();for(let y of Gr)y.destroy();return await new Promise(y=>f.once("close",()=>y())),await gg(r.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),ll(),await Yo}let ts=await _.read().catch(()=>[]),Mn=new Map;for(let p of ts){if(p.event==="worker-birth"){Mn.set(p.worker_id,p.ts);continue}let y=mg(p.detail);Rl(p,{...Mn.get(p.worker_id)==null?{}:{startedAt:Mn.get(p.worker_id)},...y==null?{}:{refusal:y}}),(p.event==="worker-death"||p.event==="worker-budget-kill")&&Mn.delete(p.worker_id)}gr=Zt(ts.filter(p=>p.event==="worker-death"||p.event==="worker-budget-kill").map(p=>({worker_id:p.worker_id,ts:p.ts,outcome:p.event})),p=>p.ts,{now:o()});let xf=Ic(ts),ns=await Ia(xf,C);for(let p of ns.alive){let y=Rm(p),E=y.unit==null||oe(y.pid)?null:ee(y.unit);N.set(y.worker_id,E!=null&&E>0?{...y,pid:E}:y),we.add(y.worker_id)}for(let p of ns.dead)He("worker-death",p,"the Worker ended while no daemon was watching");let Pf=_m({units:await Promise.resolve(Q()).catch(()=>[]),held:[...N.values()],mainPid:ee,now:S});for(let p of Pf)N.set(p.worker_id,p),we.add(p.worker_id),He("worker-birth",p,"adopted from an active unit with no birth on this lane");cl(o());for(let p of ns.alive){if(p.log_path==null||Ze.has(p.worker_id))continue;let y=await Ye(p.log_path).catch(()=>null);y==null||y.trim()===""||Ze.set(p.worker_id,{line:y,published_at:o(),source:"rehydrated"})}f.on("connection",p=>{Gr.add(p),p.once("close",()=>Gr.delete(p)),re(),MS(p,async(y,E)=>{re();let P=await Of(y);E(P),y.op==="shutdown"&&setImmediate(()=>void Nn({reason:"requested"}))})});async function Of(p){try{if(p.op==="ping")return{id:p.id,ok:!0,value:{pong:!0,protocol_version:$o,daemon_version:t,pid:a.pid}};if(p.op==="host-state")return{id:p.id,ok:!0,value:Ln()};if(p.op==="statusline-payload")return{id:p.id,ok:!0,value:$p(In(),p.extras)};if(p.op==="statusline-string")return{id:p.id,ok:!0,value:df(p.render)};if(p.op==="statusline-dashboard")return{id:p.id,ok:!0,value:cf(p.dashboard)};if(p.op==="worker-heartbeat")return{id:p.id,ok:!0,value:gl(p.heartbeat)};if(p.op==="project-register"){let E=hl(p.registration,p.session_project);return await v.flush(),{id:p.id,ok:!0,value:E}}if(p.op==="project-renew"){let E=yl(p.project_label,{...p.session_project==null?{}:{sessionProject:p.session_project},...p.renew_within_ms==null?{}:{renewWithinMs:p.renew_within_ms},...p.launch==null?{}:{launch:p.launch}});return await v.flush(),{id:p.id,ok:!0,value:E}}if(p.op==="project-deregister"){let E=kl(p.project_label,p.session_project);return await v.flush(),{id:p.id,ok:!0,value:E}}if(p.op==="project-reset")return{id:p.id,ok:!0,value:fl(p.project_label,p.session_project)};if(p.op==="worker-command")return{id:p.id,ok:!0,value:await uf(p.command)};if(p.op==="worker-start"){let E=yr("worker-start",p.session_project,p.spec.project_label);if(!E.permitted)return{id:p.id,ok:!1,error:E.reason};let P=Zo(p.spec);return await _.flush().catch(()=>{}),{id:p.id,ok:!0,value:{worker:P.worker,admission:P.admission,warnings:P.warnings}}}if(p.op==="shutdown"){let E=Cn("requested");return await xl({reason:"requested",...p.detail==null?{}:{note:p.detail}}),{id:p.id,ok:!0,value:E}}let y=p;return{id:y.id??Bo(),ok:!1,error:`unsupported redskilled op: ${y.op??"unknown"}`}}catch(y){return{id:p.id??Bo(),ok:!1,error:y instanceof Error?y.message:String(y)}}}return re(),wf(),_f(),Rf(),bf(),Ef(),sf(),vf(),Sf(),{socketPath:r.socketPath,lease:h.lease,startedAt:S,closed:Yo,startWorker:Zo,admit:_l,ceiling:()=>i,killWorkerOverBudget:wl,sampleMemoryBudgets:El,renewLease:Sl,pollRepositoryActivity:Xo,pollGithubBalance:ul,githubBalance:()=>R,pollQueueDiscovery:pl,queueDiscovery:()=>w,driveDemand:ml,demand:()=>T,sweepWorkerLiveness:es,publishWorkerHeartbeat:gl,reattached:()=>[...we].map(p=>N.get(p)).filter(p=>p!=null),flushEvents:()=>_.flush(),trackWorker(p){N.set(p.worker_id,p),He("worker-birth",p,null),re()},releaseWorker(p){let y=N.get(p),E=N.delete(p);return we.delete(p),Ze.delete(p),$r.delete(p),y&&He("worker-death",y,"released by the daemon"),re(),E},workerCount:()=>N.size,registerProject:hl,renewProject:yl,resetProjectBirthBreaker:fl,deregisterProject:kl,registrations:()=>Ln().registrations??[],hostState:Ln,statuslinePayload:In,evaluateIdle:Tl,observePublishedVersion:vl,checkForReplacement:Gn,stopReport:Cn,stop:Nn}}async function CS(e,r=250){return await new Promise(t=>{let n=xS(e),o=!1,s=a=>{o||(o=!0,clearTimeout(i),n.destroy(),t(a))},i=setTimeout(()=>s("unknown"),r);i.unref?.(),n.once("connect",()=>s("owned")),n.once("error",a=>{s(a.code==="ECONNREFUSED"||a.code==="ENOENT"?"unowned":"unknown")})})}async function NS(e,r){for(let t=0;t<2;t++){let n=PS();try{return await new Promise((o,s)=>{n.once("error",s),n.listen(e,()=>{n.off("error",s),o()})}),n}catch(o){if(n.close(),o.code!=="EADDRINUSE")throw o;if(await CS(e)!=="unowned")throw new Dr(e);if(await r?.())throw new Dr(e);await gg(e,{force:!0})}}throw new Dr(e)}async function We(e,r=250){try{return(await ro({socketPath:e,timeoutMs:r},{id:Bo(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function MS(e,r){oc(e,(t,n)=>r(t,n),(t,n,o)=>{o({id:n?.id??Bo(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function za(e){let r=e.socketPath,t=FS(e);return e.answers?{version:1,kind:"answering",socket_path:r,holder:t,reason:`a redskilled daemon answered on ${JSON.stringify(r)}`,repair:"nothing to repair"}:t!=null?{version:1,kind:"held-unresponsive",socket_path:r,holder:t,reason:`redskilled pid ${t.pid} is alive and has held ${JSON.stringify(r)} since ${t.acquired_at}${t.uptime_ms==null?"":` (up ${hg(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 \`${ur("red-skills-redskilled",["stop"])}\` and let the next client start a fresh one.`}:{version:1,kind:"absent",socket_path:r,holder:null,reason:`nothing answered on ${JSON.stringify(r)} and no live process holds its lease`,repair:`Install and start one with \`${ur("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function Qa(e){return`${e.reason} ${e.repair}`}function FS(e){let r=e.lease;return r==null||e.holderAlive!==!0||r.socket_path!==e.socketPath?null:{pid:r.pid,socket_path:r.socket_path,acquired_at:r.acquired_at,renewed_at:r.renewed_at,uptime_ms:WS(r.acquired_at,e.now??new Date().toISOString())}}function WS(e,r){let t=Date.parse(e),n=Date.parse(r);return!Number.isFinite(t)||!Number.isFinite(n)?null:Math.max(0,n-t)}function hg(e){let r=Math.floor(e/1e3),t=Math.floor(r/3600),n=Math.floor(r%3600/60),o=r%60;return t>0?`${t}h${String(n).padStart(2,"0")}m`:n>0?`${n}m${String(o).padStart(2,"0")}s`:`${o}s`}Ve();var bg=1e4,jr=class extends Error{constructor(t,n,o){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${n instanceof Error?n.message:String(n)}${o!=null&&o.kind==="held-unresponsive"?`. ${Qa(o)}`:""}`);this.socketPath=t;this.cause=n;this.presence=o;this.name="RedskilledUnreachableError"}},Ya=class extends jr{constructor(t,n,o){super(t,o,n);this.presence=n;this.name="RedskilledDaemonHeldError"}},Ho=class extends Error{constructor(t){super(t);this.refusal=t;this.name="RedskilledRequestRefusedError"}};async function qo(e,r={}){let t=r.answers??await We(e.socketPath),n=await bn(e.leasePath).catch(()=>{});return za({socketPath:e.socketPath,answers:t,lease:n,holderAlive:n!=null&&oe(n.pid)})}async function Xa(e,r={}){try{return await qS(e,r)}catch(t){if(t instanceof nr||t instanceof jr)throw t;let n=await qo(e).catch(()=>{});throw new jr(e.socketPath,t,n)}}async function qS(e,r){if(await BS(HS(e.socketPath),{recursive:!0,mode:448}),await We(e.socketPath))return"already-running";await JS(e);let t=await KS(e,r);if(t!=null)return t;let n=await ic(e.lockPath,{...r.spawnLockMaxAgeMs==null?{}:{maxAgeMs:r.spawnLockMaxAgeMs},onReap:r.onSpawnLockReaped??VS});if(!n.acquired)return await yg(e,r,void 0,n),"joined";try{if(await We(e.socketPath))return"already-running";let o=await QS(e,r);return await yg(e,r,o),"spawned"}finally{await ac(n)}}function VS(e){process.stderr.write(`redskilled: reaped the spawn lock ${JSON.stringify(e.lockPath)} (${e.reason}, ${Math.round(e.ageMs/1e3)}s old, holder ${e.holder==null?"unnamed":`pid ${e.holder.pid}`}) and went on to spawn
|
|
101
|
-
`)}async function
|
|
102
|
-
`)}import{chmod as
|
|
100
|
+
`)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function RS(e,r={}){let t=r.env??process.env,n=r.exists??fS,o=r.execPath??process.execPath,s=r.callerEntry===void 0?process.argv[1]:r.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[Jm(io(t),i),"bundle-cache"]];s&&l.push([Jm(yS(bS(s)),i),"caller-sibling-bundle"]);for(let[d,c]of l)if(a.push(d),n(d))return{command:o,args:[d],version:e,source:c,searched:a};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new Va(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 og(e,r={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=r.resolveEntry??(n=>RS(n,r.env==null?{}:{env:r.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function sg(e,r,t={}){let n=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(n.exit??ES)(zm),{...e,exitCode:zm};let o=[...e.entry.args,...vr(r,t.idleMs==null?{}:{idleMs:t.idleMs})];return(n.spawnSuccessor??wS(n.env))(e.entry,o),e}function wS(e){return(r,t)=>{let n=gS(r.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[Xm]:"1"}});n.on("error",()=>{}),n.unref()}}function ES(e){process.exitCode=e,process.exit(e)}async function ig(e,r=process.env,t=vS){let n=lg(r),o=dg(e,r);if(r[kS]==="1")return{version:o,newest:n};let s=De(e)===null?"0.0.0":e;try{let i=await gc({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??n}}catch{return{version:o,newest:n}}}function ag(e,r=process.env,t){let n=t??Ka;return{version:dg(e,r,n),newest:lg(r,n)}}function lg(e=process.env,r=Ka){return ug(cg(e,r))}function dg(e,r=process.env,t=Ka){let n=De(e.trim())?.major;return n===void 0?null:ug(cg(r,t).filter(o=>De(o)?.major===n))}function cg(e,r){let t=[];for(let n of r(io(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(n)?.[1];!o||De(o)===null||t.push(o)}return t}function ug(e){let r=null;for(let t of e)(r===null||Wa(t,r)>0)&&(r=t);return r}function Ka(e){try{return hS(e)}catch{return[]}}async function vS(e){let r=await fetch(e,{headers:{accept:"application/json"}});if(!r.ok)throw new Error(`registry read failed with HTTP ${r.status}`);return await r.text()}import{mkdir as SS,readFile as TS,rename as xS,rm as Ja,writeFile as pg}from"node:fs/promises";import{randomUUID as PS}from"node:crypto";import{dirname as OS}from"node:path";var Uo=class extends Error{constructor(r){super(`redskilled lease ${JSON.stringify(r)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function Rn(e){let r;try{r=await TS(e,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}let t=AS(r);return DS(t)?t:void 0}var mg;function fg(){return mg??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},mg}function hg(e,r,t={}){let n=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??oe;async function s(){return await Rn(e)}async function i(l){let d=`${e}.${l.pid}.${PS()}.tmp`;await pg(d,gg(l),{encoding:"utf8",mode:384}),await xS(d,e)}function a(l,d){return{version:1,pid:l.pid,start_time:l.startTime,session_key_hash:r.sessionKeyHash,machine_id_hash:r.machineIdHash,socket_path:r.socketPath,acquired_at:d,renewed_at:d}}return{read:s,async acquire(l){await SS(OS(e),{recursive:!0,mode:448});let d=!1;for(;;){let c=n(),u=a(l,c);try{return await pg(e,gg(u),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:u}}catch(f){if(f.code!=="EEXIST")throw f}let m=await s();if(!m){await Ja(e,{force:!0}),d=!0;continue}if(za(m,l))return{acquired:!0,reaped:d,lease:m};if(await o(m.pid))return{acquired:!1,lease:m};await Ja(e,{force:!0}),d=!0}},async renew(l){let d=await s();if(!d||!za(d,l))throw new Uo(e);let c={...d,renewed_at:n()};return await i(c),c},async release(l){let d=await s();if(!d)return!1;if(!za(d,l))throw new Uo(e);return await Ja(e,{force:!0}),!0}}}function za(e,r){return e.pid===r.pid&&e.start_time===r.startTime}function gg(e){return`${J(e,{keyedMapCollapse:!0})}
|
|
101
|
+
`}function AS(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return ue(r)}catch{return null}}}function DS(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;if(r.version!==1||!Number.isInteger(r.pid)||r.pid<=0)return!1;for(let t of["start_time","session_key_hash","machine_id_hash","socket_path","acquired_at","renewed_at"])if(typeof r[t]!="string"||r[t].length===0)return!1;return!0}var wn=3e5,NS=1e4,MS=6e4,FS=15e3,WS=3e4,US=6e4,Bo=16;function BS(e,r={}){if(e.event!=="worker-death"&&e.event!=="worker-budget-kill")return null;let t=e.event==="worker-budget-kill",n=!t&&r.refusal!=null,o=r.refusal??e.detail??`redskilled observed exit code=${e.exit_code??"null"} signal=${e.signal??"null"}`,s=r.startedAt==null?null:Date.parse(r.startedAt),i=Date.parse(e.ts),a=s!=null&&Number.isFinite(s)&&Number.isFinite(i)?Math.max(0,i-s)/1e3:void 0;return{version:1,ts:e.ts,kind:"worker",id:e.worker_id,pid:e.pid,last_seen:e.ts,last_phase:n?"boot-refused":"unreported",sender_class:t?"teardown":n?"boot-refused":"unknown",confidence:t||n?"high":"none",signal:e.signal,host_boot_changed:!1,evidence:t||n?[o]:[],checked:n?["Worker log tail"]:[`redskilled host event: ${o}`],project_label:e.project_label,...a===void 0?{}:{uptime_s:a},detail:r.refusal??e.detail}}function bg(e){let r=e?.match(/\bsession-error:\s*(.+)$/)?.[1]?.trim();return r==null||r===""?null:r}var Lr=class extends Error{constructor(t,n){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=n;this.name="RedskilledAlreadyRunningError"}},HS="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function _g(e){let{paths:r}=e,t=e.daemonVersion??"0.0.0-dev",n=e.idleMs??wn,o=e.clock??(()=>new Date().toISOString()),s=e.launch??Wm,i=e.ceiling??po();e.repositoryActivity!=null&&ca(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??fg(),l=e.leaseStore??hg(r.leasePath,{sessionKeyHash:r.sessionKeyHash,machineIdHash:r.machineIdHash,socketPath:r.socketPath},{clock:o}),d=e.machineOwner??Qc(),c={machineIdHash:r.machineIdHash,sessionKeyHash:r.sessionKeyHash,socketPath:r.socketPath},u=e.machineClaimStore??go(r.machineClaimPath,c,{clock:o});await GS(CS(r.socketPath),{recursive:!0,mode:448});let m=await u.claim(d);if(!m.claimed)throw m.claim?.socket_path===r.socketPath?new Lr(r.socketPath):new or(u.claimPath,m.reason,m.claim);let f=await l.acquire(a);if(!f.acquired)throw await u.release(d).catch(()=>{}),new Lr(r.socketPath,f.lease);let h;try{h=await VS(r.socketPath,async()=>{let[p,b]=await Promise.all([l.read().catch(()=>{}),u.read().catch(()=>{})]);return p!=null&&p.pid!==a.pid&&oe(p.pid)?!0:b!=null&&b.socket_path===r.socketPath&&b.pid!==d.pid&&oe(b.pid)})}catch(p){throw await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),p}let v=o(),y=e.eventLane??Gc(r.eventLanePath),S=e.registrationIntentStore??tm(r.registrationIntentPath),G=e.liveness??_m,H=e.livenessGraceMs??km,L=e.stopWorker??xm,Q=e.unitInventory??(()=>Em(r.machineClaimPath,mo({machineIdHash:r.machineIdHash}))?vm():[]),ee=e.unitMainPid??wm,le=e.treeSampler??xp,Xe=e.readLogTail??Um,$r=e.sampleMs??FS,ht=e.leaseRenewMs??WS,xn=e.registrationSustainMs??US,yt=e.publishedVersion??(p=>ig(p)),bt=e.replaceCheckMs??Ym,Pn=e.publishedProbeTimeoutMs??NS,On=e.localPublishedEvidence??(p=>ag(p,e.replacementIO?.env??process.env)),Qo=e.bornByReplacement??Zm(),An=e.replaceBootCheckMs??MS,kt=e.supervised??ng(),_t=e.replacementIO??{},he=e.repositoryActivity,Rt=he?.intervalMs??da,gr=e.githubBalance,je=e.queueDiscovery,fr=je?.transport??he?.transport,Ir=je?.unconfiguredReason??HS,Ze=je?.intervalMs??Ca,Dn=e.demandMs??15e3,jn=e.demandBackoffMs??3e4,N=new Map,Ee=new Set,er=new Map,Cr=new Map,wt=[],hr=[],yr=e.deaths===void 0?void 0:[...e.deaths],Et=await S.read().catch(()=>[]),br=Date.parse(v),W=new Map,Y=new Map;for(let p of Et){let b=Date.parse(p.renew_by);!Number.isFinite(br)||!Number.isFinite(b)||b>=br?W.set(p.project_label,p):br-b<=p.renew_within_ms&&Y.set(p.project_label,p)}let Nr=new Set,vt={},Mr=null,Fr=null,de=null,St=!1,Wr=0,Tt=null,D="none",k=null,g=null,_=null,R=null,w=null,T=null,O=[],I=[],q=new Map((e.orphanedRegistrations??[]).map(p=>[p.project_label,p])),B=null,X={},xt=!1,He,Pt,Ot,At,Dt,jt,Ln,Lt,Ur,Br,ce=!1,Yo=!1,Gn=null,dl,Xo=new Promise(p=>{dl=p});function Hr(p){cl(p);let b=Date.parse(p),E=nu(W.values(),b);for(let P of E.lapsed){W.delete(P.project_label);let A=w?.projects.find($=>$.project_label===P.project_label),j=[...N.values()].some($=>$.project_label===P.project_label);(A?.outcome==="counted"&&(A.depth??0)>0||j)&&Y.set(P.project_label,P),lf(P,b)}return E.lapsed.length>0&&qr(),E.lapsed}function qr(){let p=new Map(Y);for(let[b,E]of W)p.set(b,E);S.replace([...p.values()]).catch(()=>{})}function lf(p,b){let E=Number.isFinite(b)?new Date(b).toISOString():p.renew_by;O.push({project_label:p.project_label,registered_at:p.registered_at,at:E,renew_by:p.renew_by,renewals:p.renewals,sustains:p.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(p.project_label)}: it stood until ${p.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`}),O.length>Bo&&O.splice(0,O.length-Bo)}function cl(p){if(W.size===0)return;let b=Date.parse(p);if(!Number.isFinite(b))return;let E={};for(let $ of N.values())E[$.project_label]=(E[$.project_label]??0)+1;let P=w==null?Number.NaN:Date.parse(w.fetched_at),A=new Map((w?.projects??[]).map($=>[$.project_label,$])),j=!1;for(let $ of[...W.values()]){let ve=Number.isFinite(P)&&b-P<=$.renew_within_ms?A.get($.project_label):void 0,C=Ei($,{now:p,...ve==null?{}:{queue:{outcome:ve.outcome,depth:ve.depth}},liveWorkers:E[$.project_label]??0});C.registration!==$&&(W.set($.project_label,C.registration),j=!0)}j&&qr()}function ul(p){if(Y.size===0)return;let b=Date.parse(p);if(!Number.isFinite(b))return;let E=new Map((w?.projects??[]).map(A=>[A.project_label,A])),P=!1;for(let[A,j]of[...Y]){if(b-Date.parse(j.renew_by)>j.renew_within_ms){Y.delete(A),P=!0;continue}let $=E.get(A),Z=Ei(j,{now:p,...$==null?{}:{queue:{outcome:$.outcome,depth:$.depth}},liveWorkers:[...N.values()].filter(ve=>ve.project_label===A).length});Z.verdict==="open-work"||Z.verdict==="live-worker"?(W.set(A,Z.registration),Y.delete(A),P=!0):Z.verdict==="drained"&&(Y.delete(A),P=!0)}P&&qr()}function $n(){let p=o();return Hr(p),em({now:p,daemonVersion:t,machineIdHash:r.machineIdHash,sessionKeyHash:r.sessionKeyHash,pid:a.pid,startedAt:v,ceiling:i,scope:Yc(u.claimPath,c,d),workers:[...N.values()],registrations:[...W.values()],demand:T,lapses:O,stops:I,orphanedRegistrations:[...q.values()],birthLatches:Wc(X,Date.parse(p)),queue:w,published:{version:Fr,checkedAt:de,newer:St,replacement:D,newest:k,majorHold:g,checks:Wr,holdReason:Tt}})}function In(){return Wp({hostState:$n(),ceiling:i,rss:vt,sampledAt:Mr,logLines:Object.fromEntries(er),displays:Object.fromEntries(Cr),now:o(),reattachedWorkerIds:[...Ee],repositoryActivity:_,githubBalance:R,...yr===void 0?{}:{deaths:yr},metrics:vp({observations:wt,outcomes:hr,now:o()})})}function df(p,b){wt=rn([...wt,{worker_id:b,observed_at:p.published_at,tokens:p.display.tokens,tools:p.display.tools,runner:p.display.runner,model:p.display.model}],E=>E.observed_at,{now:o()})}function cf(p){hr=rn([...hr,p],b=>b.ts,{now:o()})}async function Zo(){return he==null||he.projects.length===0?null:(_=await Gp({projects:he.projects,hostTokenRef:he.hostTokenRef,transport:he.transport,closedWindowMs:he.closedWindowMs,now:o()}),_)}async function pl(){return gr==null?null:(R=await ea({transport:gr.transport,now:o()}),R)}function uf(){if(ce||Ur!=null||gr==null)return;let p=()=>{Ur=void 0,pl().catch(()=>{}).then(()=>{if(ce)return;let b=gr.intervalMsOverride??Po(R??pf(),{now:o()});Ur=setTimeout(p,b),Ur.unref()})};p()}function pf(){return xo(o())}function mf(){if(!(fr!=null||je?.armTransport==null))try{let p=je.armTransport();if(p.transport!=null){fr=p.transport;return}p.unconfiguredReason!=null&&(Ir=p.unconfiguredReason)}catch(p){Ir=`this host could not resolve a tracker credential: ${p instanceof Error?p.message:String(p)}`}}async function ml(){let p=o();Hr(p);let b=Date.parse(p);for(let[j,$]of[...Y])Number.isFinite(b)&&b-Date.parse($.renew_by)>$.renew_within_ms&&Y.delete(j);let P=[...new Map([...Y,...W]).values()].map(j=>({project_label:j.project_label,selector:j.selector,...j.queue_poll==null?{}:{poll:j.queue_poll}})).sort((j,$)=>j.project_label.localeCompare($.project_label));if(P.length===0)return null;if(mf(),fr==null)return w=Dm(P,p,Ir),w;w=await jm({projects:P,transport:fr,now:p,...je?.batchSize==null?{}:{batchSize:je.batchSize}});let A=o();return ul(A),cl(A),w}async function gl(){let p=o();if(xt)return T??Cc(p);xt=!0;try{await rs().catch(()=>{});let b={};for(let C of N.values())b[C.project_label]=(b[C.project_label]??0)+1;let E={};for(let C of w?.projects??[])E[C.project_label]=C.depth;let P=Date.parse(p),A=Number.isFinite(P)?P:0;for(let[C,ye]of Object.entries(X)){if(ye.probeWorkerId==null)continue;let Un=N.get(ye.probeWorkerId);Un!=null&&A-Date.parse(Un.started_at)>=6e4&&(X[C]=gi())}let j=Ic({projects:[...W.values()].map(C=>({project_label:C.project_label,selector:C.selector,argv:C.argv,workspace_path:C.workspace_path,target:C.target})),queue:E,live:b,nowMs:A,backoffUntilMs:B,birthHealth:X}),$=[],Z=null;for(let C of j.births){let ye,Un=Fa(N.keys()),Bn=W.get(C.project_label),Ol=Zc({argv:C.argv,...Bn?.env==null?{}:{env:Bn.env},...Bn?.log_path==null?{}:{log_path:Bn.log_path}},{worker_id:Un,slot:C.index,workspace_path:C.workspace_path},{project_label:C.project_label});try{ye=es(Ol)}catch(is){Z=is instanceof Error?is.message:String(is),B=(Number.isFinite(P)?P:Date.now())+jn;break}$.push({project_label:C.project_label,worker_id:ye.worker.worker_id,pid:ye.worker.pid,warnings:Ol.log_path==null?[...ye.warnings,`project ${JSON.stringify(C.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(ye.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:ye.warnings});let ss=X[C.project_label];ss?.haltUntilMs!=null&&A>=ss.haltUntilMs&&(X[C.project_label]=Fc(ss,ye.worker.worker_id))}Z==null&&j.births.length>0&&(B=null);let ve=new Set($.map(C=>C.project_label));for(let C of j.intents){if(C.queue_depth==null||C.queue_depth<=0||C.live>=C.target||ve.has(C.project_label))continue;let ye=Z!=null&&(C.outcome==="asking"||C.outcome==="half-open-probe")?`project ${JSON.stringify(C.project_label)} was birth-eligible but the host refused it: ${Z}`:C.detail;await y.recordDemandRefusal({ts:p,projectLabel:C.project_label,detail:ye}).catch(()=>{})}return T={version:1,at:p,requested:j.births.length,granted:$,shortfall:j.births.length-$.length,refusal:Z,retry_after:B==null?null:new Date(B).toISOString(),projects:j.intents},T}finally{xt=!1}}function gf(p){return Dr(In(),{...U,mode:p?.mode??U.mode,project:p?.project??U.project,maxWorkers:p?.max_workers??U.maxWorkers,maxProjects:p?.max_projects??U.maxProjects,maxWidth:p?.max_width??U.maxWidth,verbose:p?.verbose??U.verbose})}function ff(p){return ut(In(),{mode:p?.mode??We.mode,project:p?.project??We.project,maxWidth:p?.max_width??We.maxWidth,maxRows:p?.max_rows??We.maxRows})}function kr(p,b,E){return iu({op:p,sessionProject:b??null,targetProject:E})}async function hf(p){let b=N.get(p.worker_id),E=kr(su(p.command),p.session_project,b?.project_label??null);if(!E.permitted)throw new Error(E.reason);if(p.command!=="stop")throw new Error(`redskilled does not implement ${p.command}: it owns birth, death and limits, and ${p.command} is a work decision the project's own bundle makes on top of them`);let P=b!=null&&await Rf(b,p.detail??"stopped by its own project");return{version:1,command:p.command,worker_id:p.worker_id,applied:P,reach:E,detail:P?`redskilled stopped Worker ${JSON.stringify(p.worker_id)} of project ${JSON.stringify(b.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(p.worker_id)} to stop`}}function Cn(p){N.delete(p),Ee.delete(p),er.delete(p),Cr.delete(p)}function fl(p){let b=N.get(p.worker_id),E=kr("worker-heartbeat",p.session_project,b?.project_label??null);if(!E.permitted)throw new Error(E.reason);if(typeof p.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(b==null)return{version:1,worker_id:p.worker_id,accepted:!1,reach:E,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(p.worker_id)} to publish a line for`};let P=o();er.set(p.worker_id,{line:p.last_log_line,published_at:P,source:"heartbeat"});let A=p.display===void 0?null:Im(p.display);if(A!=null){let j={display:A,published_at:P};Cr.set(p.worker_id,j),df(j,p.worker_id)}return{version:1,worker_id:p.worker_id,accepted:!0,reach:E,published_at:P,detail:`redskilled stored a line for Worker ${JSON.stringify(p.worker_id)} without reading it`}}async function yf(p,b,E){let P=`exit code=${b??"null"} signal=${E??"null"}`;if(p.unit!=null&&p.unit!==""&&await kf(p)){_f(p,`its launch client ended (${P}) while unit ${JSON.stringify(p.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}let A=p.log_path==null?null:bg(await Xe(p.log_path).catch(()=>null));Cn(p.worker_id),qe("worker-death",p,A==null?P:`session-error: ${A}`,{exitCode:b,signal:E,refusal:A}),re()}function bf(p,b){if(!Number.isFinite(b)||b<0){X[p]=Jt;return}let E=X[p]??Jt,P=Mc(E,b,Date.parse(o()));X[p]=P,P.haltUntilMs!=null&&E.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(p)} lost ${P.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(P.haltUntilMs).toISOString()}
|
|
102
|
+
`)}function hl(p,b){let E=kr("project-reset",b,p);if(!E.permitted)throw new Error(E.reason);let P=X[p]?.haltUntilMs!=null||X[p]?.probeWorkerId!=null;return X[p]=gi(),{version:1,project_label:p,latch:"project-birth-breaker",reset:P,reach:E,detail:P?`redskilled cleared project ${JSON.stringify(p)}'s birth breaker; the next demand tick may birth normally`:`redskilled found no open birth breaker for project ${JSON.stringify(p)}; nothing changed`}}async function kf(p){try{return await G(p)===!0}catch{return!1}}function _f(p,b){let E=p.unit==null?null:ee(p.unit);N.set(p.worker_id,{...p,...E!=null&&E>0?{pid:E}:{},warnings:[...p.warnings,b]}),Ee.add(p.worker_id),re()}function yl(p,b){let E=kr("project-register",b,p.project_label);if(!E.permitted)throw new Error(E.reason);let P=o();Hr(P);let A=eu(p,{now:P,held:W.get(p.project_label)});return W.set(A.project_label,A),qr(),_l(A.project_label),re(),{version:1,registration:A,reach:E,detail:`redskilled holds a registration for project ${JSON.stringify(A.project_label)} at a target of ${A.target} until ${A.renew_by}, and has read neither its selector nor its argv`}}function bl(p,b={}){let E=kr("project-renew",b.sessionProject,p);if(!E.permitted)throw new Error(E.reason);let P=o();Hr(P);let A=W.get(p);if(A==null){if(q.has(p))throw new xr(p,{kind:"orphaned"});let $=[...I].reverse().find(ve=>ve.project_label===p);if($!=null)throw new xr(p,{kind:"stopped",at:$.at});let Z=[...O].reverse().find(ve=>ve.project_label===p);throw Z!=null?new xr(p,{kind:"lapsed",at:Z.at,...Z.registered_at==null?{}:{registered_at:Z.registered_at}}):new xr(p)}let j=ru(A,{now:P,...b.renewWithinMs==null?{}:{renew_within_ms:b.renewWithinMs},...b.launch==null?{}:{launch:b.launch}});return W.set(j.project_label,j),qr(),re(),{version:1,registration:j,reach:E,detail:`redskilled renewed the registration for project ${JSON.stringify(j.project_label)}, which now stands until ${j.renew_by} after renewal ${j.renewals}`+(b.launch==null?"":`, carrying launch revision ${j.launch_revision} for its next Worker`)}}function kl(p,b){let E=kr("project-deregister",b,p);if(!E.permitted)throw new Error(E.reason);let P=W.get(p)??Y.get(p),A=W.delete(p),j=Y.delete(p),$=A||j;if(P!=null){let Z=`redskilled released the registration for project ${JSON.stringify(p)}`;_l(p),I.push({project_label:p,registered_at:P.registered_at,at:o(),detail:Z}),I.length>Bo&&I.splice(0,I.length-Bo)}return $&&qr(),{version:1,project_label:p,released:$,reach:E,detail:$?`redskilled released the registration for project ${JSON.stringify(p)}`:`redskilled held no registration for project ${JSON.stringify(p)}, so there was nothing to release`}}function _l(p){Y.delete(p);for(let b=O.length-1;b>=0;b-=1)O[b].project_label===p&&O.splice(b,1);for(let b=I.length-1;b>=0;b-=1)I[b].project_label===p&&I.splice(b,1);q.delete(p)}async function Rf(p,b){try{await L(p)}catch{}return Cn(p.worker_id),qe("worker-death",p,b),re(),!0}function Rl(p){return Oc({ceiling:i,workers:[...N.values()],budget:p.budget,projectLabel:p.project_label,...p.reservation==null?{}:{reservation:p.reservation}})}function es(p){let b=Ac({ceiling:i,workers:[...N.values()],budget:p.budget}),E=s({spec:p,admission:Rl(p),memoryCeiling:b,liveWorkerIds:N.keys(),clock:o,onExit:(P,A,j)=>{let $=N.get(P);if($==null){re();return}yf($,A,j).catch(()=>{})}});return N.set(E.worker.worker_id,E.worker),qe("worker-birth",E.worker,null),re(),E}function qe(p,b,E,P={}){if(ce)return;let A=o();(p==="worker-death"||p==="worker-budget-kill")&&(cf({worker_id:b.worker_id,ts:A,outcome:p}),wl({version:1,ts:A,event:p,worker_id:b.worker_id,project_label:b.project_label,pid:b.pid,workspace_path:b.workspace_path,log_path:b.log_path??null,isolated:b.isolated,unit:b.unit??null,memory_high:b.budget?.memory_high??null,memory_max:b.budget?.memory_max??null,cpu_weight:b.budget?.cpu_weight??null,detail:E,reason:null,exit_code:P.exitCode??null,signal:P.signal??null},{startedAt:b.started_at,...P.refusal==null?{}:{refusal:P.refusal}}),bf(b.project_label,Date.parse(A)-Date.parse(b.started_at))),y.record({event:p,worker:b,ts:A,detail:E,...P.exitCode!==void 0?{exitCode:P.exitCode}:{},...P.signal!==void 0?{signal:P.signal}:{}}).catch(()=>{})}function wl(p,b={}){let E=BS(p,b);if(E==null)return;let P=[E,...(yr??[]).filter(A=>A.kind!==E.kind||A.id!==E.id||A.ts!==E.ts)].sort((A,j)=>Date.parse(A.ts)-Date.parse(j.ts));yr=rn(P,A=>A.ts,{now:o()})}async function rs(){let p=Date.parse(o()),b=[...N.values()].filter(P=>{if(Ee.has(P.worker_id))return!0;let A=Date.parse(P.started_at);return!Number.isFinite(A)||p-A>=H});if(b.length===0)return[];let{dead:E}=await $a(b,G);for(let P of E)Cn(P.worker_id),qe("worker-death",P,"the host no longer confirms this Worker");return E.length>0&&re(),E}async function El(p,b){let E=N.get(p);if(!E)return!1;try{await L(E)}catch{}return Cn(p),qe("worker-budget-kill",E,b),re(),!0}async function vl(){let p=[...N.values()];if(p.length===0)return[];let b;try{b=await le(p)}catch{return[]}let E=b.rss;vt=E,Mr=o(),wf(b.cpu_seconds,Mr);let{terminations:P}=Tp({workers:p,rss:E}),A=[];for(let j of P)await El(j.worker_id,j.reason)&&A.push(j);return A}function wf(p,b){for(let[E,P]of Object.entries(p)){if(typeof P!="number"||!Number.isFinite(P))continue;let A=N.get(E);A&&N.set(E,{...A,cpu:{cpu_seconds:P,sampled_at:b}})}}async function Ef(){try{return Pn<=0?await yt(t):await new Promise(p=>{let b=setTimeout(()=>p(ts()),Pn);b.unref(),yt(t).then(E=>{clearTimeout(b),p(E)},()=>{clearTimeout(b),p(ts())})})}catch{return ts()}}function ts(){try{return On(t)}catch{return null}}async function Sl(){if(_n(t))return Wr+=1,de=o(),Tt="local-build",{act:"hold",reason:"local-build"};let p=eg(await Ef()),b=p.version;Fr=b,k=p.newest??null,de=o(),g=rg({running:t,newest:k,supervised:kt});let E=tg({running:t,published:b,supervised:kt});return St=E.act==="replace",Wr+=1,Tt=E.act==="hold"?E.reason:null,D!=="in-progress"&&(D=E.act==="replace"?"pending":"none"),E}async function Nn(){let p=await Sl();if(p.act!=="replace"||D==="in-progress")return p;let b=og(p,_t);return D="in-progress",await y.flush().catch(()=>{}),await S.flush().catch(()=>{}),await Fn({reason:"replaced"}),sg(b,r,{...n==null?{}:{idleMs:n},io:_t}),p}function vf(){ce||jt!=null||bt<=0||(!Qo&&An>0&&(Ln=setTimeout(()=>{Nn().catch(()=>{})},An),Ln.unref()),jt=setInterval(()=>{Nn().catch(()=>{})},bt),jt.unref())}async function Tl(){return await l.renew(a).catch(()=>null)}function Sf(){ce||Ot!=null||ht<=0||(Ot=setInterval(()=>{Tl()},ht),Ot.unref())}function Tf(){ce||At!=null||xn<=0||(At=setInterval(()=>{Hr(o())},xn),At.unref())}function xf(){ce||Pt!=null||$r<=0||(Pt=setInterval(()=>{vl().catch(()=>{})},$r),Pt.unref())}function Pf(){ce||Lt!=null||he==null||he.projects.length===0||Rt<=0||(Zo().catch(()=>{}),Lt=setInterval(()=>{Zo().catch(()=>{})},Rt),Lt.unref())}function Of(){if(ce||Br!=null||Ze<=0)return;let p=b=>{Br=setTimeout(()=>{Br=void 0,ml().catch(()=>{}).finally(()=>{if(ce)return;let E=Date.parse(o());p($m(w,Ze,Number.isFinite(E)?E:Date.now()))})},b),Br.unref()};p(Ze)}function Af(){ce||Dt!=null||Dn<=0||(Dt=setInterval(()=>{gl().catch(()=>{})},Dn),Dt.unref())}function re(){ce||(He&&clearTimeout(He),He=setTimeout(()=>{rs().catch(()=>{}).then(()=>xl())},n),He.unref())}function xl(){return N.size>0?(re(),"held-by-workers"):(Hr(o()),W.size>0?(re(),"held-by-registrations"):(Df(),"exited"))}async function Df(){if(!_n(t)){if((await Nn().catch(()=>null))?.act==="replace"||Yo||ce)return;if(N.size>0||W.size>0){re();return}}await Fn({reason:"idle"})}function Mn(p){return Bc({reason:p,socketPath:r.socketPath,daemonVersion:t,pid:a.pid,workers:[...N.values()],projects:[...W.keys()]})}function Pl(p){if(Gn!=null)return Gn;let b=p.reason??"requested",E=p.note?.trim();return Gn=y.recordDaemonStop({ts:o(),pid:a.pid,socketPath:r.socketPath,reason:b,detail:E==null||E===""?Mn(b).detail:`${Mn(b).detail} \u2014 ${E}`,...p.signal==null?{}:{signal:p.signal}}).catch(()=>{}),Gn}async function Fn(p={}){if(Yo)return await Xo;Yo=!0,await Pl(p),ce=!0,He&&clearTimeout(He),Pt&&clearInterval(Pt),Ot&&clearInterval(Ot),At&&clearInterval(At),jt&&clearInterval(jt),Ln&&clearTimeout(Ln),Lt&&clearInterval(Lt),Ur&&clearTimeout(Ur),Br&&clearTimeout(Br),Dt&&clearInterval(Dt),await y.flush().catch(()=>{}),await S.flush().catch(()=>{}),h.close();for(let b of Nr)b.destroy();return await new Promise(b=>h.once("close",()=>b())),await kg(r.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),dl(),await Xo}let ns=await y.read().catch(()=>[]),Wn=new Map;for(let p of ns){if(p.event==="worker-birth"){Wn.set(p.worker_id,p.ts);continue}let b=bg(p.detail);wl(p,{...Wn.get(p.worker_id)==null?{}:{startedAt:Wn.get(p.worker_id)},...b==null?{}:{refusal:b}}),(p.event==="worker-death"||p.event==="worker-budget-kill")&&Wn.delete(p.worker_id)}hr=rn(ns.filter(p=>p.event==="worker-death"||p.event==="worker-budget-kill").map(p=>({worker_id:p.worker_id,ts:p.ts,outcome:p.event})),p=>p.ts,{now:o()});let jf=$c(ns),os=await $a(jf,G);for(let p of os.alive){let b=Tm(p),E=b.unit==null||oe(b.pid)?null:ee(b.unit);N.set(b.worker_id,E!=null&&E>0?{...b,pid:E}:b),Ee.add(b.worker_id)}for(let p of os.dead)qe("worker-death",p,"the Worker ended while no daemon was watching");let Lf=Sm({units:await Promise.resolve(Q()).catch(()=>[]),held:[...N.values()],mainPid:ee,now:v});for(let p of Lf)N.set(p.worker_id,p),Ee.add(p.worker_id),qe("worker-birth",p,"adopted from an active unit with no birth on this lane");ul(o());for(let p of os.alive){if(p.log_path==null||er.has(p.worker_id))continue;let b=await Xe(p.log_path).catch(()=>null);b==null||b.trim()===""||er.set(p.worker_id,{line:b,published_at:o(),source:"rehydrated"})}h.on("connection",p=>{Nr.add(p),p.once("close",()=>Nr.delete(p)),re(),KS(p,async(b,E)=>{re();let P=await Gf(b);E(P),b.op==="shutdown"&&setImmediate(()=>void Fn({reason:"requested"}))})});async function Gf(p){try{if(p.op==="ping")return{id:p.id,ok:!0,value:{pong:!0,protocol_version:Io,daemon_version:t,pid:a.pid}};if(p.op==="host-state")return{id:p.id,ok:!0,value:$n()};if(p.op==="statusline-payload")return{id:p.id,ok:!0,value:Fp(In(),p.extras)};if(p.op==="statusline-string")return{id:p.id,ok:!0,value:gf(p.render)};if(p.op==="statusline-dashboard")return{id:p.id,ok:!0,value:ff(p.dashboard)};if(p.op==="worker-heartbeat")return{id:p.id,ok:!0,value:fl(p.heartbeat)};if(p.op==="project-register"){let E=yl(p.registration,p.session_project);return await S.flush(),{id:p.id,ok:!0,value:E}}if(p.op==="project-renew"){let E=bl(p.project_label,{...p.session_project==null?{}:{sessionProject:p.session_project},...p.renew_within_ms==null?{}:{renewWithinMs:p.renew_within_ms},...p.launch==null?{}:{launch:p.launch}});return await S.flush(),{id:p.id,ok:!0,value:E}}if(p.op==="project-deregister"){let E=kl(p.project_label,p.session_project);return await S.flush(),{id:p.id,ok:!0,value:E}}if(p.op==="project-reset")return{id:p.id,ok:!0,value:hl(p.project_label,p.session_project)};if(p.op==="worker-command")return{id:p.id,ok:!0,value:await hf(p.command)};if(p.op==="worker-start"){let E=kr("worker-start",p.session_project,p.spec.project_label);if(!E.permitted)return{id:p.id,ok:!1,error:E.reason};let P=es(p.spec);return await y.flush().catch(()=>{}),{id:p.id,ok:!0,value:{worker:P.worker,admission:P.admission,warnings:P.warnings}}}if(p.op==="shutdown"){let E=Mn("requested");return await Pl({reason:"requested",...p.detail==null?{}:{note:p.detail}}),{id:p.id,ok:!0,value:E}}let b=p;return{id:b.id??Ho(),ok:!1,error:`unsupported redskilled op: ${b.op??"unknown"}`}}catch(b){return{id:p.id??Ho(),ok:!1,error:b instanceof Error?b.message:String(b)}}}return re(),xf(),Sf(),Tf(),vf(),Pf(),uf(),Of(),Af(),{socketPath:r.socketPath,lease:f.lease,startedAt:v,closed:Xo,startWorker:es,admit:Rl,ceiling:()=>i,killWorkerOverBudget:El,sampleMemoryBudgets:vl,renewLease:Tl,pollRepositoryActivity:Zo,pollGithubBalance:pl,githubBalance:()=>R,pollQueueDiscovery:ml,queueDiscovery:()=>w,driveDemand:gl,demand:()=>T,sweepWorkerLiveness:rs,publishWorkerHeartbeat:fl,reattached:()=>[...Ee].map(p=>N.get(p)).filter(p=>p!=null),flushEvents:()=>y.flush(),trackWorker(p){N.set(p.worker_id,p),qe("worker-birth",p,null),re()},releaseWorker(p){let b=N.get(p),E=N.delete(p);return Ee.delete(p),er.delete(p),Cr.delete(p),b&&qe("worker-death",b,"released by the daemon"),re(),E},workerCount:()=>N.size,registerProject:yl,renewProject:bl,resetProjectBirthBreaker:hl,deregisterProject:kl,registrations:()=>$n().registrations??[],hostState:$n,statuslinePayload:In,evaluateIdle:xl,observePublishedVersion:Sl,checkForReplacement:Nn,stopReport:Mn,stop:Fn}}async function qS(e,r=250){return await new Promise(t=>{let n=$S(e),o=!1,s=a=>{o||(o=!0,clearTimeout(i),n.destroy(),t(a))},i=setTimeout(()=>s("unknown"),r);i.unref?.(),n.once("connect",()=>s("owned")),n.once("error",a=>{s(a.code==="ECONNREFUSED"||a.code==="ENOENT"?"unowned":"unknown")})})}async function VS(e,r){for(let t=0;t<2;t++){let n=IS();try{return await new Promise((o,s)=>{n.once("error",s),n.listen(e,()=>{n.off("error",s),o()})}),n}catch(o){if(n.close(),o.code!=="EADDRINUSE")throw o;if(await qS(e)!=="unowned")throw new Lr(e);if(await r?.())throw new Lr(e);await kg(e,{force:!0})}}throw new Lr(e)}async function Ue(e,r=250){try{return(await no({socketPath:e,timeoutMs:r},{id:Ho(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function KS(e,r){sc(e,(t,n)=>r(t,n),(t,n,o)=>{o({id:n?.id??Ho(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function Qa(e){let r=e.socketPath,t=JS(e);return e.answers?{version:1,kind:"answering",socket_path:r,holder:t,reason:`a redskilled daemon answered on ${JSON.stringify(r)}`,repair:"nothing to repair"}:t!=null?{version:1,kind:"held-unresponsive",socket_path:r,holder:t,reason:`redskilled pid ${t.pid} is alive and has held ${JSON.stringify(r)} since ${t.acquired_at}${t.uptime_ms==null?"":` (up ${Rg(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 \`${mr("red-skills-redskilled",["stop"])}\` and let the next client start a fresh one.`}:{version:1,kind:"absent",socket_path:r,holder:null,reason:`nothing answered on ${JSON.stringify(r)} and no live process holds its lease`,repair:`Install and start one with \`${mr("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function Ya(e){return`${e.reason} ${e.repair}`}function JS(e){let r=e.lease;return r==null||e.holderAlive!==!0||r.socket_path!==e.socketPath?null:{pid:r.pid,socket_path:r.socket_path,acquired_at:r.acquired_at,renewed_at:r.renewed_at,uptime_ms:zS(r.acquired_at,e.now??new Date().toISOString())}}function zS(e,r){let t=Date.parse(e),n=Date.parse(r);return!Number.isFinite(t)||!Number.isFinite(n)?null:Math.max(0,n-t)}function Rg(e){let r=Math.floor(e/1e3),t=Math.floor(r/3600),n=Math.floor(r%3600/60),o=r%60;return t>0?`${t}h${String(n).padStart(2,"0")}m`:n>0?`${n}m${String(o).padStart(2,"0")}s`:`${o}s`}Ke();var vg=1e4,Gr=class extends Error{constructor(t,n,o){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${n instanceof Error?n.message:String(n)}${o!=null&&o.kind==="held-unresponsive"?`. ${Ya(o)}`:""}`);this.socketPath=t;this.cause=n;this.presence=o;this.name="RedskilledUnreachableError"}},Xa=class extends Gr{constructor(t,n,o){super(t,o,n);this.presence=n;this.name="RedskilledDaemonHeldError"}},qo=class extends Error{constructor(t){super(t);this.refusal=t;this.name="RedskilledRequestRefusedError"}};async function Vo(e,r={}){let t=r.answers??await Ue(e.socketPath),n=await Rn(e.leasePath).catch(()=>{});return Qa({socketPath:e.socketPath,answers:t,lease:n,holderAlive:n!=null&&oe(n.pid)})}async function Za(e,r={}){try{return await ZS(e,r)}catch(t){if(t instanceof or||t instanceof Gr)throw t;let n=await Vo(e).catch(()=>{});throw new Gr(e.socketPath,t,n)}}async function ZS(e,r){if(await YS(XS(e.socketPath),{recursive:!0,mode:448}),await Ue(e.socketPath))return"already-running";await tT(e);let t=await rT(e,r);if(t!=null)return t;let n=await ac(e.lockPath,{...r.spawnLockMaxAgeMs==null?{}:{maxAgeMs:r.spawnLockMaxAgeMs},onReap:r.onSpawnLockReaped??eT});if(!n.acquired)return await wg(e,r,void 0,n),"joined";try{if(await Ue(e.socketPath))return"already-running";let o=await oT(e,r);return await wg(e,r,o),"spawned"}finally{await lc(n)}}function eT(e){process.stderr.write(`redskilled: reaped the spawn lock ${JSON.stringify(e.lockPath)} (${e.reason}, ${Math.round(e.ageMs/1e3)}s old, holder ${e.holder==null?"unnamed":`pid ${e.holder.pid}`}) and went on to spawn
|
|
103
|
+
`)}async function rT(e,r){let t=await Vo(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let n=r.readyTimeoutMs??vg,o=Date.now()+n;for(;;){if(await Ue(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(i=>setTimeout(i,25))}let s=await Vo(e).catch(()=>{});if(s==null||s.kind!=="held-unresponsive")return null;throw new Xa(e.socketPath,s,new Error(`it did not answer a ping within ${n}ms, and no second daemon was spawned because pid ${s.holder?.pid??"unknown"} still holds this socket`))}async function tT(e){let t=await go(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&oe(t.pid))throw new or(e.machineClaimPath,"held",t)}async function Sg(e,r,t={}){await Za(e,t);let n;try{n=await hn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...r,id:Eg()})}catch(o){throw new Gr(e.socketPath,o,await Vo(e).catch(()=>{}))}if(!n.ok)throw new qo(n.error);return n.value}async function Tg(e,r={},t={}){if(!await Ue(e.socketPath))return Hc(e.socketPath);let n;try{n=await hn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Eg(),op:"shutdown",...r.detail==null?{}:{detail:r.detail}})}catch(i){throw new Gr(e.socketPath,i)}if(!n.ok)throw new qo(n.error);if(!fi(n.value))throw new Error("redskilled daemon returned a malformed stop report");let o=n.value;return await nT(e.socketPath,r.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 nT(e,r){let t=Date.now()+r;for(;;){if(!await Ue(e))return!0;if(Date.now()>=t)return!1;await new Promise(n=>setTimeout(n,25))}}async function xg(e,r={}){let t=await Sg(e,{op:"host-state"},r);if(!rm(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Pg(e,r={},t){let n=await Sg(e,{op:"statusline-payload",...r.sessionProject!=null?{session_project:r.sessionProject}:{},...t==null?{}:{extras:t}},r);if(!ua(n))throw new Error("redskilled daemon returned a malformed statusline payload");return n}async function Og(e,r=U,t={}){let n=await Pg(e,t,{vitals:!0,logs:r.verbose,display:!0});return Dr(n,r)}async function Ag(e,r={},t={}){let n=await Pg(e,t,{vitals:!0,logs:!0,display:!0});return ut(n,{...We,...r})}async function wg(e,r,t,n){let o=Date.now()+(r.readyTimeoutMs??vg);for(;;){if(await Ue(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()>=o){if(n!=null)throw new Error(`no redskilled daemon answered on ${JSON.stringify(e.socketPath)} within the ready window, and ${dc(n)}`);let s=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)}${s}`)}await new Promise(s=>setTimeout(s,25))}}async function oT(e,r){let t=r.serverCommand??(r.serverArgs!=null?process.execPath:void 0),n=await kc({...t!=null?{serverCommand:t}:{},serverArgs:r.serverArgs},r.entryLookup??{}),o={entry:n},s=[...n.args,...vr(e,r.idleMs==null?{}:{idleMs:r.idleMs})],i=QS(n.command,s,{detached:!0,stdio:"ignore",env:{...r.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}Ke();import{readFile as sT}from"node:fs/promises";import{homedir as iT,totalmem as aT}from"node:os";import{join as lT}from"node:path";var dT="REDSKILLED_IDLE_MS",cT=".red/config.yaml";async function jg(e=iT()){let r=lT(e,cT),t;try{t=await sT(r,"utf8")}catch(n){return n.code==="ENOENT"?{}:(el(`redskilled: cannot read host config ${JSON.stringify(r)}; using environment and defaults instead: ${Dg(n)}`),{})}try{let n=pT(t);return{...Ko(n,"plugins.dev.redskilled.worker_ceiling","workerCeiling"),...Ko(n,"plugins.dev.redskilled.memory_ceiling","memoryCeiling"),...Ko(n,"plugins.dev.redskilled.validation_ceiling","validationCeiling"),...Ko(n,"plugins.dev.redskilled.idle_ms","idleMs")}}catch(n){return el(`redskilled: malformed host config ${JSON.stringify(r)}; using environment and defaults instead: ${Dg(n)}`),{}}}function Lg(e={}){let r=e.env??process.env,t=e.config??{},n=po(r,e.totalMemoryBytes??aT(),{flags:e.flags,config:t,...e.availableParallelism==null?{}:{availableParallelism:e.availableParallelism}}),o=uT(e.flags?.idleMs==null?void 0:String(e.flags.idleMs),r[dT],t.idleMs);if(o==null)return{ceiling:n,idleMs:wn,idleMsSource:"derived-default"};let s=Number(o.value);return Number.isSafeInteger(s)&&s>0?{ceiling:n,idleMs:s,idleMsSource:o.source}:(el(`redskilled: ${fT(o.source)} idle_ms=${JSON.stringify(o.value)} is not a positive integer; using the default ${wn}ms instead.`),{ceiling:n,idleMs:wn,idleMsSource:"derived-default"})}function uT(e,r,t){if(e!==void 0)return{value:e.trim(),source:"flag"};if(r!==void 0)return{value:r.trim(),source:"environment"};if(t!==void 0)return{value:t.trim(),source:"home-config"}}function Ko(e,r,t){let n=e[r];return n===void 0?{}:{[t]:n}}function pT(e){let r={},t=[];for(let[n,o]of e.split(/\r?\n/).entries()){let s=mT(o);if(s.trim()==="")continue;let i=s.match(/^ */)?.[0].length??0;if(i%2!==0||/\t/.test(s.slice(0,i)))throw new Error(`line ${n+1} has unsupported indentation`);let a=/^([A-Za-z_][A-Za-z0-9_-]*):(?:\s*(.*))?$/.exec(s.slice(i).trimEnd());if(a==null)throw new Error(`line ${n+1} is not a mapping entry`);let l=i/2;if(l>t.length)throw new Error(`line ${n+1} skips a mapping level`);t.splice(l);let d=a[1],c=a[2]??"";if(c===""){t.push(d);continue}r[[...t,d].join(".")]=gT(c.trim())}return r}function mT(e){let r;for(let t=0;t<e.length;t+=1){let n=e[t];if(r==null&&(n==="'"||n==='"'))r=n;else if(r===n)r=void 0;else if(r==null&&n==="#"&&(t===0||/\s/.test(e[t-1])))return e.slice(0,t).trimEnd()}if(r!=null)throw new Error("unclosed quoted scalar");return e}function gT(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function fT(e){return e==="flag"?"serve flag":e==="environment"?"environment":e==="home-config"?"home config":"derived default"}function Dg(e){return e instanceof Error?e.message:String(e)}function el(e){process.stderr.write(`${e}
|
|
104
|
+
`)}import{chmod as Fg,mkdir as Ug,readFile as Bg,stat as TT,writeFile as Hg}from"node:fs/promises";import{homedir as nl}from"node:os";import{dirname as qg,join as Jo}from"node:path";import{join as hT}from"node:path";var Gg=["local","tmp","host"],yT="local",En="plugins.dev.workspace.target";var rl=class extends Error{constructor(r){super(r),this.name="WorkspaceConfigError"}};function Ig(e){let r=et(e,En),t=_T(r??"").trim();return t===""?void 0:t}function Cg(e){let r=(e??"").trim();if(r==="")return{kind:"preset",preset:yT};let t=Gg.find(n=>n===r.toLowerCase());if(t)return{kind:"preset",preset:t};if(r.startsWith("/")||r==="~"||r.startsWith("~/"))return{kind:"custom",parentDir:r};throw new rl(`${En}: unknown workspace target ${JSON.stringify(r)}. Use one of the presets (${Gg.join(", ")}) or an absolute parent directory for Workers.`)}function Ng(e,r){return e.kind==="preset"?e.preset==="host":kT(bT(e.parentDir,r),Ce(r))}function bT(e,r){return e==="~"?$g(r):e.startsWith("~/")?hT(r,e.slice(2)):$g(e)}function kT(e,r){return e===r?!0:r==="/"?e.startsWith("/"):e.startsWith(`${r}/`)}function $g(e){let r=e.trim();return r.length>1?r.replace(/\/+$/,""):r}function _T(e){let r=e.trim(),t=/^(["'])(.*)\1$/.exec(r);return t?t[2]:r}Ke();import{createHash as RT}from"node:crypto";import{hostname as wT}from"node:os";import{join as vn}from"node:path";var ft="redskilled.sock",ET="REDSKILLED_SESSION";function vT(e={}){let r=e.env??process.env,t=r[ET]?.trim();if(t)return t;let n=r.XDG_RUNTIME_DIR?.trim();return n||`uid:${e.uid??(typeof process.getuid=="function"?process.getuid():"nouid")}`}function ST(e={}){return Mg(e.host??wT())}function Be(e={}){let r=vT(e),t=e.runtimeDir??oo({key:`redskilled:${r}`,socketFileName:ft,env:e.env,uid:e.uid}),n=ST(e),o=e.homeDir??e.env?.HOME??(e.runtimeDir==null?process.env.HOME:e.runtimeDir)??t;return{sessionKey:r,sessionKeyHash:Mg(r),machineIdHash:n,runtimeDir:t,socketPath:vn(t,ft),lockPath:vn(t,"redskilled.spawn.lock"),leasePath:vn(t,"redskilled.lease.toon"),eventLanePath:vn(Ce(o),Lc),registrationIntentPath:vn(t,"redskilled.registrations.toon"),machineClaimPath:e.machineClaimPath??mo({env:e.env,machineIdHash:n,platform:e.platform})}}function Mg(e){return RT("sha256").update(e).digest("hex").slice(0,12)}var tl=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${mr("red-skills-redskilled",["provision"])}\` directly`,xT=`# Host-scoped redskilled policy. This file is never read from a repository.
|
|
103
105
|
plugins:
|
|
104
106
|
dev:
|
|
105
107
|
redskilled:
|
|
@@ -107,8 +109,8 @@ plugins:
|
|
|
107
109
|
# memory_ceiling: 8G
|
|
108
110
|
# validation_ceiling: 2
|
|
109
111
|
# idle_ms: 300000
|
|
110
|
-
`;async function
|
|
111
|
-
`)}async function
|
|
112
|
+
`;async function Vg(e=nl()){let r=Ce(e),t=Jo(qg(r),"config.yaml"),n=await sl(r),o=!1,s=!1;n===void 0?(await Ug(r,{recursive:!0,mode:Ve}),await Fg(r,Ve),o=!0):n!==Ve&&(await Fg(r,Ve),s=!0);let i=!1;try{await Hg(t,xT,{encoding:"utf8",flag:"wx",mode:384}),i=!0}catch(a){if(a.code!=="EEXIST")throw a}return{path:r,created:o,tightened:s,mode:Ve,configPath:t,configCreated:i}}var Kg={needed:!1,declaredBy:`no ${En} in view`};async function ol(e={}){let r=e.homeDir??nl(),t=e.declaredTarget?.trim();if(t)return Wg(t,r,"stated on the command line");let n=e.projectRoot?.trim();if(!n)return Kg;let o=Jo(n,".red","config.yaml"),s=await Bg(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=Ig(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Wg(i,r,o)}function Wg(e,r,t){let n=`${En}: ${e} (${t})`;try{return{needed:Ng(Cg(e),r),declaredBy:n}}catch{return{needed:!1,declaredBy:`${n} \u2014 off-contract, so it names no lane under the home`}}}function Jg(e){let r=[PT(e),OT(e),AT(e),DT(e)],t=r.filter(o=>o.verdict!=="ok");return{verdict:t.some(o=>o.verdict==="missing")?"missing":t.length>0?"degraded":"ok",rows:r,findings:t}}function PT(e){let r=e.homeNeed??Kg;if(!e.homePresent)return r.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${r.declaredBy}`,fix:tl}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${r.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??Ve;return t!==Ve?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${Ve.toString(8)}`,fix:`${tl} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function OT(e){return Me(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 \`${mr("red-skills-redskilled",["provision"])}\``}}function AT(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:`${tl} \u2014 it starts the daemon and waits for the socket`}}function DT(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 zg(e={}){let r=e.env??process.env,t=e.homeDir??nl(),n=e.paths??Be({env:r}),o=Ce(t),[s,i,a]=await Promise.all([sl(o),Ue(n.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):ol({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:a,entry:nr(e.entryOverride??{},{env:r,...e.entryLookup}),socketPath:n.socketPath,reachable:i,supervisorUnit:await LT(GT(e,r,t),r)}}var jT="redskilled.service";function Qg(e){return Jo(e,"systemd","user",jT)}function Yg(e){let r=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${r}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
|
|
113
|
+
`)}async function Xg(e){let r=Qg(e.configHome);return await sl(r)!==void 0?{path:r,status:"already-present"}:(await Ug(qg(r),{recursive:!0}),await Hg(r,e.unit,"utf8"),{path:r,status:"installed"})}async function LT(e,r){if(process.platform!=="linux")return"unsupported";try{return await Bg(Qg(e),"utf8"),"installed"}catch{return r.XDG_RUNTIME_DIR?"absent":"unsupported"}}function GT(e,r,t){return e.configHome??r.XDG_CONFIG_HOME?.trim()??Jo(t,".config")}async function sl(e){try{return(await TT(e)).mode&511}catch{return}}import{readdir as ef,rm as $T,stat as IT}from"node:fs/promises";import{dirname as CT,join as il}from"node:path";var NT=5*6e4,MT="redskilled.";function FT(e={}){let r=e.env??process.env,t=i=>CT(oo({key:"redskilled:reclaim-probe",socketFileName:ft,env:i,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:n,...o}=r,s=[t(r),t(o)];return[...new Set(s)]}async function rf(e={}){let r=e.roots??FT(e),t=e.graceMs??NT,n=e.now??Date.now,o=e.isPidAlive??oe,s=e.answers??HT,i=e.dryRun===!0,a=[];for(let l of r){let d;try{d=(await ef(l,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name)}catch{continue}for(let c of d.sort())a.push(await WT(il(l,c),{graceMs:t,now:n,pidAlive:o,answers:s,dryRun:i}))}return{roots:r,scanned:a.length,reclaimed:a.filter(l=>l.verdict==="reclaimed").length,dryRun:i,entries:a}}async function WT(e,r){let t;try{t=(await ef(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:tf(i),removed:[]}}let n=t.filter(i=>i.startsWith(MT));if(t.length>0&&n.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await UT(il(e,"redskilled.lease.toon"));if(o!==void 0)return await r.pidAlive(o.pid)?{dir:e,verdict:"live",reason:`lease pid ${o.pid} is alive`,removed:[]}:await Zg(e,t,`lease pid ${o.pid} is dead`,r);if(t.includes(ft)&&await r.answers(il(e,ft)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await BT(e,r.now);return s!==void 0&&s<r.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(s/1e3)}s ago`,removed:[]}:await Zg(e,t,t.length===0?"empty and stale":"no lease and stale",r)}async function Zg(e,r,t,n){if(n.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:r};try{await $T(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:tf(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:r}}async function UT(e){try{return await Rn(e)}catch{return}}async function BT(e,r){try{return Math.max(0,r()-(await IT(e)).mtimeMs)}catch{return}}async function HT(e){try{return(await hn({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function tf(e){return e instanceof Error?e.message:String(e)}var qT="plugins.dev.statusline",VT="dev.statusline";function KT(e){let r=[],t=a=>{for(let l of[qT,VT]){let d=`${l}.${a}`,c=et(e,d)?.trim();if(c!=null&&c!=="")return{key:d,value:c}}},n=t("mode"),o={};n!=null&&(n.value==="local"||n.value==="global"?o.mode=n.value:r.push({...n,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):r.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":r.push({...i,reason:"expected `true` or `false`"})),{config:o,warnings:r}}var JT={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 al(e){let{values:r,positionals:t}=tr(e,JT),n=[],o={},s=r.mode??t.find(a=>a==="global"||a==="local");s!=null&&(s==="local"||s==="global"?o.mode=s:n.push({key:"--mode",value:s,reason:"expected `local` or `global`"})),r.project!=null&&(o.project=r.project),r.verbose!==void 0&&(o.verbose=r.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=r[a.flag];if(l==null)continue;let d=Number(l);Number.isInteger(d)&&d>=0?a.assign(d):n.push({key:`--${a.flag}`,value:l,reason:"expected a whole number of zero or more"})}return{flags:o,warnings:n}}function ll(e={}){let r=e.configText==null?{config:{},warnings:[]}:KT(e.configText),t=e.flags??{};return{options:{...U,mode:t.mode??r.config.mode??U.mode,project:t.project!==void 0?t.project:e.project??U.project,maxWorkers:t.maxWorkers??r.config.maxWorkers??U.maxWorkers,maxProjects:t.maxProjects??r.config.maxProjects??U.maxProjects,maxWidth:t.maxWidth??r.config.maxWidth??U.maxWidth,verbose:t.verbose??r.config.verbose??U.verbose},warnings:r.warnings}}var QT=`Usage: redskilled <command> [options]
|
|
112
114
|
|
|
113
115
|
Commands:
|
|
114
116
|
host-state (default) print the host's state as JSON
|
|
@@ -122,7 +124,7 @@ Commands:
|
|
|
122
124
|
|
|
123
125
|
Run \`redskilled <command> --help\` for a command's own usage.
|
|
124
126
|
\`--version\` (\`-v\`) prints the build stamp; both answer offline.
|
|
125
|
-
`,
|
|
127
|
+
`,YT={serve:`Usage: redskilled serve [options]
|
|
126
128
|
|
|
127
129
|
Runs the daemon in this process. Every path is a flag and none is derived
|
|
128
130
|
(ADR 0130 rule 3); what is absent falls back to the session derivation.
|
|
@@ -207,28 +209,28 @@ Reports every session runtime dir it looked at and why it kept or removed it.
|
|
|
207
209
|
|
|
208
210
|
--dry-run the same report with nothing removed
|
|
209
211
|
--grace-ms <n> how long a dir must be idle before it is reclaimed
|
|
210
|
-
`};function
|
|
211
|
-
`:`${
|
|
212
|
-
`),0}if(
|
|
213
|
-
`);let m=
|
|
214
|
-
`),0}var
|
|
215
|
-
`),0}function
|
|
216
|
-
`),o.running&&!o.stopped?1:0}async function
|
|
217
|
-
`),0;if(o==="install"){let s=await
|
|
218
|
-
`),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await
|
|
219
|
-
`),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function
|
|
220
|
-
`);let a;try{a=await
|
|
221
|
-
`),a=
|
|
212
|
+
`};function XT(e){return e==="--help"||e==="-h"||e==="help"}var ZT={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},"worker-ceiling":{kind:"value",coerce:e=>e},"memory-ceiling":{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)}},of="REDSKILLED_HOST_TOKEN";function Tn(){try{let r=zT("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return r===""?null:r}catch{return null}}function sf(e=process.env,r=Tn){let t=(e[of]??e.GITHUB_TOKEN??e.GH_TOKEN??"").trim();if(t!=="")return{token:t,source:"env"};let n=(r()??"").trim();return n!==""?{token:n,source:"tracker-cli"}:null}function ex(e,r=process.env,t=Tn,n){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...nf(e,r,t,n),armTransport:()=>nf(e,r,t,n)}}function rx(e,r=process.env,t=Tn){let n=sf(r,t);if(n==null)return null;let o=r.GITHUB_API_URL;return{transport:sa({token:n.token,...o?{origin:o}:{}})}}function nf(e,r=process.env,t=Tn,n){let o=sf(r,t);if(o==null)return{unconfiguredReason:`no credential names a tracker for this host: ${of}, GITHUB_TOKEN and GH_TOKEN are all unset in the daemon's environment and \`gh auth token\` returned nothing \u2014 so no queue depth is asked for, and no depth is invented either`};let s=e["queue-endpoint"]??r.GITHUB_GRAPHQL_URL;return{transport:Cp({token:o.token,...s?{endpoint:s}:{},...n?{attribution:n}:{}})}}async function tx(e){if(e[0]==="--version"||e[0]==="-v"){let o=Ps("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
|
|
213
|
+
`:`${gd(o)}
|
|
214
|
+
`),0}if(XT(e[0]))return process.stdout.write(QT),0;let{command:r,args:t}=bd(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},dashboard:{},"github-spend":{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(YT[r]),0;if(r==="serve"){let{values:o}=tr(t,ZT),s=await jg(Sn()),i=Lg({flags:{...o["worker-ceiling"]==null?{}:{workerCeiling:o["worker-ceiling"]},...o["memory-ceiling"]==null?{}:{memoryCeiling:o["memory-ceiling"]},...o["idle-ms"]==null?{}:{idleMs:o["idle-ms"]}},config:s}),a=zo(Ce(Sn()),"state"),l=ho({path:zo(a,"github","spend.toonl")}),d=ex(o,process.env,Tn,l),c=rx(o),u=Nd({stateRoot:a});process.stderr.write(`${Md(u)}
|
|
215
|
+
`);let m=Ld({lanePath:Ft(a),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),f=await _g({paths:fx(o),idleMs:i.idleMs,ceiling:i.ceiling,daemonVersion:o["daemon-version"]??Ps("redskilled").version,deaths:u.attributions,queueDiscovery:d,...c==null?{}:{githubBalance:c},...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let h of["SIGTERM","SIGINT"])process.once(h,()=>void f.stop({reason:"signal",signal:h}).catch(()=>{}));return await f.closed,m.phase("closed"),0}if(r==="stop")return await ax(t);if(r==="statusline")return await dx(t);if(r==="dashboard")return await yx(t);if(r==="github-spend")return await ox(t);if(r==="unit")return await lx(t);if(r==="provision")return await ux(t);if(r==="reclaim")return await mx(t);let n=await xg(Be());return process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
216
|
+
`),0}var nx={pool:{kind:"value",coerce:e=>e},hours:{kind:"value",coerce:e=>Number(e)}};async function ox(e,r={}){let{values:t}=tr(e,nx,{unknownFlags:"error"}),n=t.hours??1;if(!Number.isFinite(n)||n<=0)throw new Error(`redskilled github-spend --hours must be a positive number; received ${String(n)}`);let o=t.pool??"graphql",s=o==="all"?void 0:sx(o),i=(r.now??(()=>new Date().toISOString()))(),a=Date.parse(i);if(!Number.isFinite(a))throw new Error(`redskilled github-spend clock returned an invalid instant: ${i}`);let l=new Date(a-n*60*60*1e3).toISOString(),c=await(r.ledger??ho({path:zo(Ce(r.homeDir??Sn()),"state","github","spend.toonl")})).report({from:l,to:i,...s===void 0?{}:{pool:s}});return(r.write??(u=>process.stdout.write(u)))(`${J({version:c.version,origin:c.origin,window:{from:c.window.from,to:c.window.to},pool:c.pool,total_count:c.total_count,total_cost:c.total_cost,operations:c.operations.map(u=>({operation_key:u.operation_key,pool:u.pool,...u.actor===void 0?{}:{actor:u.actor},count:u.count,cost:u.cost})),unreadable_records:c.unreadable_records})}
|
|
217
|
+
`),0}function sx(e){if(e==="graphql"||e==="rest"||e==="search")return e;throw new Error(`redskilled github-spend --pool must be graphql, rest, search or all; received ${JSON.stringify(e)}`)}var ix={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function ax(e,r={}){let t=r.write??(s=>process.stdout.write(s)),{values:n}=tr(e,ix),o=await Tg(r.paths??Be(),{...n.reason==null?{}:{detail:n.reason},...Number.isFinite(n["settle-timeout-ms"])?{settleTimeoutMs:n["settle-timeout-ms"]}:{}},r.client??{});return t(`${J({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})}
|
|
218
|
+
`),o.running&&!o.stopped?1:0}async function lx(e,r={}){let t=r.write??(s=>process.stdout.write(s)),n=r.paths??Be(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(Km(r.unitIO??{}),null,2)}
|
|
219
|
+
`),0;if(o==="install"){let s=await qm(Bm(n),r.unitIO??{});return t(`${JSON.stringify(s,null,2)}
|
|
220
|
+
`),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await Vm(r.unitIO??{}),null,2)}
|
|
221
|
+
`),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function dx(e,r={}){let t=r.write??(l=>process.stdout.write(l)),n=r.warn??(l=>process.stderr.write(l)),o=al(e),s=af(r.cwd??process.cwd()),i=ll({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let l of[...i.warnings,...o.warnings])n(`redskilled statusline: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
|
|
222
|
+
`);let a;try{a=await Og(r.paths??Be(),i.options,{...r.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(l){n(`redskilled statusline: ${l instanceof Error?l.message:String(l)}
|
|
223
|
+
`),a=Oa({options:i.options,generated_at:(r.now??(()=>new Date().toISOString()))()})}return t(`${a.lines.join(`
|
|
222
224
|
`)}
|
|
223
|
-
`),0}var
|
|
224
|
-
`),u.verdict==="ok"?0:1}var
|
|
225
|
-
`),o.entries.some(s=>s.verdict==="failed")?1:0}function
|
|
226
|
-
`),process.exitCode=1});async function
|
|
227
|
-
`);try{let a=await
|
|
225
|
+
`),0}var cx={"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 ux(e,r={}){let t=r.write??(m=>process.stdout.write(m)),{values:n}=tr(e,cx),o=r.paths??Be(),s=r.homeDir??Sn(),i=await ol({homeDir:s,declaredTarget:n.workspace,projectRoot:n.project??r.projectRoot??process.cwd()}),a=n.check||!i.needed?void 0:await Vg(s),l;if(!n.check&&!n["no-start"])try{await Za(o,r.client??{})}catch(m){l=m instanceof Error?m.message:String(m)}let d=await zg({paths:o,homeNeed:i,...r.homeDir==null?{}:{homeDir:r.homeDir},...r.configHome==null?{}:{configHome:r.configHome},...r.client?.serverCommand==null?{}:{entryOverride:{serverCommand:r.client.serverCommand,serverArgs:r.client.serverArgs}}}),c=n["install-unit"]&&Me(d.entry)?await Xg({configHome:r.configHome??gx(),unit:Yg({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=Jg(d);return t(`${J({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},...c==null?{}:{unit:{path:c.path,status:c.status}},checks:u.rows.map(m=>({check:m.check,verdict:m.verdict,evidence:m.evidence})),fixes:u.findings.map(m=>({check:m.check,fix:m.fix}))})}
|
|
226
|
+
`),u.verdict==="ok"?0:1}var px={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function mx(e,r={}){let t=r.write??(s=>process.stdout.write(s)),{values:n}=tr(e,px),o=await rf({...r.options??{},dryRun:n["dry-run"]===!0,...Number.isFinite(n["grace-ms"])?{graceMs:n["grace-ms"]}:{}});return t(`${J({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]}))})}
|
|
227
|
+
`),o.entries.some(s=>s.verdict==="failed")?1:0}function gx(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:zo(Sn(),".config")}function af(e){let r=Ks(e);return r.configText==null?{label:null}:{configText:r.configText,label:Kd(e)}}function fx(e){let r=Be();return{...r,socketPath:e.socket??r.socketPath,leasePath:e.lease??r.leasePath,eventLanePath:e.events??r.eventLanePath,sessionKeyHash:e["session-key-hash"]??r.sessionKeyHash,machineIdHash:e["machine-id-hash"]??r.machineIdHash,machineClaimPath:e["machine-claim"]??r.machineClaimPath}}var hx=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;hx&&tx(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
|
|
228
|
+
`),process.exitCode=1});async function yx(e,r={}){let t=r.write??(a=>process.stdout.write(a)),n=r.warn??(a=>process.stderr.write(a)),o=al(e),s=af(r.cwd??process.cwd()),i=ll({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let a of[...i.warnings,...o.warnings])n(`redskilled dashboard: ignoring ${a.key}=${a.value} \u2014 ${a.reason}
|
|
229
|
+
`);try{let a=await Ag(r.paths??Be(),{...i.options.project==null?{}:{project:i.options.project},mode:i.options.mode,...i.options.maxWidth==null?{}:{maxWidth:i.options.maxWidth}},{...r.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}});t(`${a.lines.join(`
|
|
228
230
|
`)}
|
|
229
231
|
`)}catch(a){n(`redskilled dashboard: ${a instanceof Error?a.message:String(a)}
|
|
230
232
|
`),t(`redskilled unreachable \u2014 the host was not asked, so its Workers are unknown
|
|
231
|
-
`)}return 0}export{
|
|
233
|
+
`)}return 0}export{of as REDSKILLED_HOST_TOKEN_ENV,QT as REDSKILLED_USAGE,nf as armRedskilledQueueTransport,sf as resolveRedskilledHostToken,rx as resolveServeGithubBalance,ex as resolveServeQueueDiscovery,yx as runDashboard,ox as runGithubSpend,ux as runProvision,mx as runReclaim,tx as runRedskilledCli,dx as runStatusline,ax as runStop,lx as runUnit};
|
|
232
234
|
/*! Bundled license information:
|
|
233
235
|
|
|
234
236
|
content-type/dist/index.js:
|