@reddb-io/red-skills 3.5.0 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brain.bundle.min.mjs +1 -1
- package/dist/castle-mcp.bundle.min.mjs +376 -376
- package/dist/code-nav.bundle.min.mjs +1 -1
- package/dist/dev.bundle.min.mjs +740 -736
- package/dist/memory.bundle.min.mjs +1 -1
- package/dist/redskilled.bundle.min.mjs +88 -87
- package/dist/rsp.bundle.min.mjs +114 -114
- 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 Af=Object.create;var is=Object.defineProperty;var Df=Object.getOwnPropertyDescriptor;var jf=Object.getOwnPropertyNames;var Lf=Object.getPrototypeOf,If=Object.prototype.hasOwnProperty;var $f=(e,r)=>()=>(e&&(r=e(e=0)),r);var Ol=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),Gf=(e,r)=>{for(var t in r)is(e,t,{get:r[t],enumerable:!0})},Cf=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of jf(r))!If.call(e,o)&&o!==t&&is(e,o,{get:()=>r[o],enumerable:!(n=Df(r,o))||n.enumerable});return e};var as=(e,r,t)=>(t=e!=null?Af(Lf(e)):{},Cf(r||!e||!e.__esModule?is(t,"default",{value:e,enumerable:!0}):t,e));var uc={};Gf(uc,{REDSKILLED_BIN_ENV:()=>ei,REDSKILLED_BUNDLE_ASSET:()=>Ce,REDSKILLED_ENTRY_UNRESOLVED:()=>Ft,RedskilledDaemonEntryError:()=>Wt,isRedskilledEntryPath:()=>ti,isResolvedRedskilledEntry:()=>Ne,redskilledBundleCacheRoot:()=>oo,redskilledServeArgv:()=>wr,requireRedskilledEntry:()=>so,resolveRedskilledEntry:()=>tr});import{existsSync as Wk,readdirSync as Uk}from"node:fs";import{homedir as Bk}from"node:os";import{basename as Zs,dirname as Xs,join as _e,resolve as no}from"node:path";function Ne(e){return"command"in e}function wr(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 oo(e=process.env){return cc(e)}function tr(e={},r={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=r.env??process.env,n=r.exists??Wk,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[ei];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(i&&ti(i))return a(no(i),"caller-entry");let d=[];for(let[c,u]of Kk(i,r.rootDir,t,r.listDir??Qk))if(d.push(c),n(c))return a(c,u);return{diagnostic:Ft,searched:d,...i?{callerEntry:no(i)}:{}}}function so(e={},r={}){let t=tr(e,r);if(Ne(t))return t;throw new Wt(t)}function ti(e){let r=Zs(e);return r===Ce||ri.test(r)||r==="red-skills-redskilled"||r==="red-skills-redskilled.mjs"?!0:r!=="cli.js"&&r!=="cli.mjs"&&r!=="cli.ts"?!1:Vk(no(e))}function Vk(e){let r=Xs(e);for(let t=0;t<4;t++){if(Zs(r)==="redskilled")return!0;let n=Xs(r);if(n===r)return!1;r=n}return!1}function*Kk(e,r,t,n){if(e){let s=Xs(no(e));yield[_e(s,Ce),"caller-sibling-bundle"];let i=Hk.exec(Zs(e));i&&(yield[_e(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[_e(s,"..","dist",Ce),"caller-sibling-bundle"]}for(let s of qk){let i=t[s];i&&(yield[_e(i,"dist",Ce),"plugin-root-bundle"],yield[_e(i,"..","..","dist",Ce),"plugin-root-bundle"])}r&&(yield[_e(r,"dist",Ce),"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=cc(t);yield[_e(o,Ce),"bundle-cache"];for(let s of Jk(o,n))yield[_e(o,s),"bundle-cache"]}function cc(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let r=e.XDG_CACHE_HOME||_e(e.HOME||Bk(),".cache");return _e(r,"red-skills","bundles")}function Jk(e,r){return r(e).filter(t=>ri.test(t)).sort((t,n)=>zk(dc(n),dc(t)))}function dc(e){return ri.exec(e)?.[1]??""}function zk(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 Qk(e){try{return Uk(e)}catch{return[]}}var Ce,Ft,ei,Wt,Hk,ri,qk,Ve=$f(()=>{"use strict";Ce="redskilled.bundle.min.mjs",Ft="redskilled-daemon-entry-unresolved",ei="REDSKILLED_BIN";Wt=class extends Error{code=Ft;searched;callerEntry;constructor(r){super(`${Ft}: no published ${Ce} 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)}};Gk=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Hs=/^redskilled-(.+)\.bundle\.min\.mjs$/,$k=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});var yi=wl((fi,hi)=>{(function(e,r){typeof fi=="object"&&typeof hi<"u"?hi.exports=r():typeof define=="function"&&define.amd?define(r):e.Bottleneck=r()})(fi,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(G){return T=G,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,v,_,S,j,B;j=10,_=5,B=o,v=f,S=class{constructor(k,g,b,R,w,T,O,G){this.task=k,this.args=g,this.rejectOnDrop=w,this.Events=T,this._states=O,this.Promise=G,this.options=B.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,H)=>{this._resolve=q,this._reject=H}),this.retryCount=0}_sanitizePriority(k){var g;return g=~~k!==k?_:k,g<0?0:g>j-1?j-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,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(G){return w=G,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 v(`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 M=S,oe,Z,le;le=o,oe=f,Z=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 oe(`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 Je=Z,Pr,dt;Pr=f,dt=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 Pr(`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 kn=dt,ct,ut;ct=i,ut=class{constructor(k,g){this.schedule=this.schedule.bind(this),this.name=k,this.Promise=g,this._running=0,this._queue=new ct}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(G){return b=G,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 bn=ut,_n="2.19.5",No={version:_n},Rn=Object.freeze({version:_n,default:No}),pt=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),mt=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),ge=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),gt,ar,Oe,lr,Or,ze;ze=o,gt=l,lr=pt,Oe=mt,Or=ge,ar=function(){class D{constructor(g={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=g,ze.load(this.limiterOptions,this.defaults,this),this.Events=new gt(this),this.instances={},this.Bottleneck=Ir,this._startAutoCleanup(),this.sharedConnection=this.connection!=null,this.connection==null&&(this.limiterOptions.datastore==="redis"?this.connection=new lr(Object.assign({},this.limiterOptions,{Events:this.Events})):this.limiterOptions.datastore==="ioredis"&&(this.connection=new Oe(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",...Or.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,G,q,H;if(this.connection==null)return this.Promise.resolve(this.keys());for(O=[],g=null,H=`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,G=R.length;w<G;w++)T=R[w],O.push(T.slice(H,-b));return O}_startAutoCleanup(){var g;return clearInterval(this.interval),typeof(g=this.interval=setInterval(async()=>{var b,R,w,T,O,G;O=Date.now(),w=this.instances,T=[];for(R in w){G=w[R];try{await G._store.__groupCheck__(O)?T.push(this.deleteKey(R)):T.push(void 0)}catch(q){b=q,T.push(G.Events.trigger("error",b))}}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 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 wn=ar,En,C,be;be=o,C=l,En=function(){class D{constructor(g={}){this.options=g,be.load(this.options,this.defaults,this),this.Events=new C(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 Qe=En,Ar=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),ft=r(Rn),dr,cr,ht,ur,W,Q,Dr,yt,jr,Lr,de,kt=[].splice;Q=10,cr=5,de=o,Dr=m,ur=M,W=Je,yt=Ar,ht=l,jr=kn,Lr=bn,dr=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 Dr(Q),this._scheduled={},this._states=new jr(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new ht(this),this._submitLock=new Lr("submit",this.Promise),this._registerLock=new Lr("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 yt(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(G){return T=G,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:G,wait:q,reservoir:H})=>{var Y;return this.Events.trigger("debug",`Drained ${T.id}`,{success:G,args:b,options:T}),G?(O.shift(),Y=this.empty(),Y&&this.Events.trigger("empty"),H===0&&this.Events.trigger("depleted",Y),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,G)=>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:Q-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,G,q;({args:b,options:T}=g);try{({reachedHWM:O,blocked:R,strategy:q}=await this._store.__submit__(this.queued(),T.weight))}catch(H){return w=H,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&&(G=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,G?.doDrop(),G==null||q===D.prototype.strategy.OVERFLOW)?(G==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,G,q;return typeof g[0]=="function"?(O=g,[R,...g]=O,[b]=kt.call(g,-1),T=de.load({},this.jobDefaults)):(G=g,[T,R,...g]=G,[b]=kt.call(g,-1),T=de.load(T,this.jobDefaults)),q=(...H)=>new this.Promise(function(Y,_t){return R(...H,function(...Me){return(Me[0]!=null?_t:Y)(Me)})}),w=new ur(q,g,T,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),w.promise.then(function(H){return typeof b=="function"?b(...H):void 0}).catch(function(H){return Array.isArray(H)?typeof b=="function"?b(...H):void 0:typeof b=="function"?b(H):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 ur(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=ht,D.version=D.prototype.version=ft.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=wn,D.RedisConnection=D.prototype.RedisConnection=pt,D.IORedisConnection=D.prototype.IORedisConnection=mt,D.Batcher=D.prototype.Batcher=Qe,D.prototype.jobDefaults={priority:cr,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 Ir=dr,bt=Ir;return bt})});var Pu=wl(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.format=eR;co.parse=rR;var Y_=/^[\u0009\u0020-\u007e\u0080-\u00ff]*$/,Eu=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,X_=/[\\"]/g,Z_=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,vu=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function eR(e){let{type:r,parameters:t}=e;if(!r||!Z_.test(r))throw new TypeError(`Invalid type: ${r}`);let n=r;if(t)for(let o of Object.keys(t)){if(!Eu.test(o))throw new TypeError(`Invalid parameter name: ${o}`);n+=`; ${o}=${sR(t[o])}`}return n}function rR(e,r){let t=e.length,n=Ei(e,0,t),o=n;n=wi(e,n,t);let s=vi(e,o,n),i=e.slice(o,s).toLowerCase(),a=r?.parameters===!1?new vu:oR(e,n,t);return{type:i,parameters:a}}var Su=32,Tu=9,xu=59,tR=61,wu=34,nR=92;function oR(e,r,t){let n=new vu;e:for(;r<t;){r=Ei(e,r+1,t);let o=r;for(;r<t;){let s=e.charCodeAt(r);if(s===xu)continue e;if(s===tR){let i=vi(e,o,r),a=e.slice(o,i).toLowerCase();if(r=Ei(e,r+1,t),r<t&&e.charCodeAt(r)===wu){r++;let d="";for(;r<t;){let c=e.charCodeAt(r++);if(c===wu){r=wi(e,r,t),n[a]===void 0&&(n[a]=d);break}if(c===nR&&r<t){d+=e[r++];continue}d+=String.fromCharCode(c)}continue e}let l=r;if(r=wi(e,r,t),n[a]===void 0){let d=vi(e,l,r);n[a]=e.slice(l,d)}continue e}r++}}return n}function wi(e,r,t){for(;r<t&&e.charCodeAt(r)!==xu;)r++;return r}function Ei(e,r,t){for(;r<t;){let n=e.charCodeAt(r);if(n!==Su&&n!==Tu)break;r++}return r}function vi(e,r,t){for(;t>r;){let n=e.charCodeAt(t-1);if(n!==Su&&n!==Tu)break;t--}return t}function sR(e){if(Eu.test(e))return e;if(Y_.test(e))return`"${e.replace(X_,"\\$&")}"`;throw new TypeError(`Invalid parameter value: ${e}`)}});import{execFileSync as $T}from"node:child_process";import{homedir as hn}from"node:os";import{join as Co}from"node:path";var Mr=class extends Error{constructor(r,t){super(r===0?t:`line ${r}: ${t}`),this.name="ToonError",this.line=r,this.reason=t}},mr=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 Mr(e,r)}function N(e,r){return new mr(e,r)}function Fr(e){return e instanceof mr?e:e instanceof Mr?new mr(e.line,e.reason):new mr(0,String(e&&e.message?e.message:e))}var El=["type","kind","event"],gr="|",vl=new Set(["order","discriminator","rows","common"]);var V=",";function Gn(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: ",
|
|
10
|
-
`),e.push(" discriminator: ",
|
|
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 je(e){return x(e,"invalid quoted string")}function ke(e,r){if(e==="")return"";if(e.startsWith('"'))return Il(e,r);if(e.includes('"'))throw je(r);return e==="true"?!0:e==="false"?!1:e==="null"?null:Nf(e)?Number(e):e}function ve(e,r){let t=e.trim();if(t.startsWith('"'))return[Il(t,r),!0];if(t.includes('"')||/\s/.test(t))throw x(r,"expected non-empty field name");return[t,!1]}var jl=/["\\\u0000-\u0008\u000a-\u001f]/g;function Il(e,r){if(e.charCodeAt(0)!==34)throw je(r);let t="",n=1;for(;n<e.length;){jl.lastIndex=n;let o=jl.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(n,o.index);throw je(r)}if(o[0]!=="\\")throw je(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 je(r);let a=Number.parseInt(i,16);if(a>=55296&&a<=57343)throw je(r);t+=String.fromCharCode(a),n+=4;break}default:throw je(r)}}throw je(r)}function $l(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 je(t);r=o+2;continue}if(n===-1)throw je(t);return n+1}}function Se(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=$l(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=$l(e,o+1,t)}return-1}function Nf(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Mf(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Ff(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 Le(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 Ff(e);if(typeof e=="string")return Uf(e,r);throw x(0,"not a primitive")}function Wf(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function te(e){return Wf(e)?e:Bn(e)}function Uf(e,r){return ls(e,r)?Bn(e):e}function ls(e,r){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Mf(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(r)||e.startsWith("-")}var Ll=/["\\\u0000-\u001f]/g;function Bn(e){let r='"',t=0;Ll.lastIndex=0;let n;for(;(n=Ll.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 Te(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 Gl(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 Cl(e,r){let t=[],n=!1;return Un(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);Ie(l,i,r),t.push({number:i,depth:l,content:o.slice(a),blankBefore:n}),n=!1}),t}function Ie(e,r,t){if(t.maxDepth!==0&&e>t.maxDepth)throw x(r,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function Lt(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,Ie(n,r,t)):i==="}"&&(n=Math.max(0,n-1)))}}function Fl(e){if(!K(e)||Object.keys(e).length===0)return e;let r={};for(let[t,n]of Object.entries(e)){let o=Bf(n,1);if(o===void 0)return e;Te(r,t,o)}return r}function Bf(e,r){if(!K(e)||!Hf(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 Wl(r);let l=new Map;for(let[u,m]of Object.entries(e))if(!Dl.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 h=l.get(u);if(h===void 0)throw ds(r);let f=d.get(u)??0,S=h[f];if(S===void 0)throw ds(r);return d.set(u,f+1),Vf(n,u,a[m],S,r)});for(let[u,m]of l)if((d.get(u)??0)!==m.length)throw ds(r);return c}function Hf(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=>Qf(c,t));if(a.some(c=>c===""))throw ne(t);let l=zf(i,t),d=a.length*l;if(!Number.isSafeInteger(d))throw ne(t);if(d!==r)throw Wl(t);return Array.from({length:d},(c,u)=>a[u%a.length])}function Vf(e,r,t,n,o){let s={};Te(s,e,r);for(let[i,a]of Object.entries(t??{})){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw ne(o);Te(s,i,a)}for(let[i,a]of Object.entries(Kf(n,o))){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw ne(o);Te(s,i,a)}return s}function Kf(e,r){let t={};for(let[n,o]of Object.entries(e))Jf(t,n.split("."),o,r);return Hn(t,r)}function Jf(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 Hn(e,r){return Array.isArray(e)?e.map(t=>Hn(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 Hn(e[String(n)],r)}):Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Hn(n,r)])):e}function zf(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 Qf(e,r){try{return decodeURIComponent(e)}catch{throw ne(r)}}function Nl(e){return encodeURIComponent(e)}function ne(e){return x(e,"invalid cyclic array wire")}function Wl(e){return x(e,"cyclic array length mismatch")}function ds(e){return x(e,"cyclic array group length mismatch")}function Ul(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=Yf(s);if(i===void 0)return;t.push([o,i])}let n=[];for(let[o,s]of t)rh(n,o,s);return n.join("")}function Yf(e){if(!Array.isArray(e)||e.length===0||!e.every(K))return;let r=Xf(e);if(r===void 0)return;let t=e.map(a=>a[r]),n=Zf(t);if(n===void 0)return;let o=eh(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)&&!cs(u,c,d))return;s.get(l).push(d)}let i=[];for(let a of n.cycle){let l=s.get(a),d=nh(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 Xf(e){return Al.find(r=>e.every(t=>typeof t[r]=="string"))}function Zf(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(Nl).join(","),s=`cycle(${t.map(Nl).join(",")})*${n}`;if(s.length<=o.length*.4)return{cycle:t,encoded:s,repeats:n}}}function eh(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(!th(s)||!e.every(i=>Object.prototype.hasOwnProperty.call(i,s))||!e.every(i=>Le(i[s])))break;t.push(s)}return t}function rh(e,r,t){e.push(te(r),`:
|
|
9
|
+
`),e.push(" order: ",ae(t.order.encoded,br),`
|
|
10
|
+
`),e.push(" discriminator: ",ae(t.discriminator,br),`
|
|
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=>
|
|
14
|
-
`)}function Kf(e){return e!==""&&es(e)}function Zo(e,r,t,n=new Set){if(!es(r))return!1;if(De(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)=>Zo(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(".")&&Zo(i,`${r}.${s}`,t,n));return n.delete(e),o}return!1}function Jf(e){let r=Object.keys(e[0]??{});if(e.every(t=>zf(Object.keys(t),r)))return r.every(es)?r:void 0}function zf(e,r){return e.length===r.length&&e.every((t,n)=>t===r[n])}function es(e){return e.split(".").every(r=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(r))}function Wr(e,r){let t=e[r]??e[e.length-1];return x(t===void 0?1:t.number,"array length mismatch")}function Nn(e,r){if(r===-1)throw x(0,"array header missing colon");let t=e.slice(0,r),n=se(t,"[",0);if(n===-1)throw x(0,"invalid array header");let o,s;try{[o,s]=Re(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=Yf(m.slice(1,-1),u),h=ts(f)}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:h,fieldTree:f}}function $l(e){let r=se(e,"{",0);if(r===-1||!e.endsWith("}"))throw x(0,"invalid keyed map header");let t,n;try{[t,n]=Re(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=Qf(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 Qf(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]=Re(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 v=e.slice(f,o);if(!Cl(v,t))throw x(0,"invalid array header");o+=1,n.push({path:[...l,m],listDelimiter:v})}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(Nl(n[l].path,n[d].path)||At(n[l].path,n[d].path)||At(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 Yf(e,r){if(r!==V&&e.includes(V)&&(e.includes("[")||e.includes("{")))return rs(e,V,r);try{return rs(e,r,r)}catch(t){if(r!==V&&t.reason!=="duplicate key")return rs(e,V,r);throw t}}function rs(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]=Re(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 v=e.slice(f,n);n+=1;let _=Xf(v);if(_!==void 0){if(_.delimiter!==t)throw x(0,"invalid array header");h.fixedLength=_.len,h.fixedDelimiter=_.delimiter}else if(Cl(v,t))h.listDelimiter=v;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=ts(i);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(Nl(a[l].path,a[d].path)||At(a[l].path,a[d].path)||At(a[d].path,a[l].path))throw x(0,"duplicate key");return i}function Xf(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 ts(e,r=[]){return e.flatMap(t=>{let n=[...r,t.key];return t.children!==void 0?ts(t.children,n):[{path:n,listDelimiter:t.listDelimiter}]})}function Mn(e,r,t){return e.listDelimiter===void 0?he(r,t):we(r,e.listDelimiter,t).map(n=>he(n,t))}function Cl(e,r){return e.length===1&&e!==r&&!/[ \t\r\n"[\]{}:]/.test(e)}function Nl(e,r){return e.length===r.length&&At(e,r)}function At(e,r){return r.every((t,n)=>e[n]===t)}function Fn(e,r){return x(r,e.reason??String(e.message))}function ue(e,r){let t=Ol(r),n=Al(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("[")){Ot(o.content,o.number,t);let d;try{d=Nn(o.content,se(o.content,":",o.number))}catch(c){if(t.strict)throw Fn(c,o.number);d=void 0}if(d!==void 0)return rh(d,n,t)}if(s&&se(o.content,":",o.number)===-1)return he(o.content.trim(),o.number);let i={index:0},a=os(n,i,0,t),l=n[i.index];if(l!==void 0)throw x(l.number,"expected end of document");return t.cyclicDiscriminatedArrays?Ll(a):a}function os(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}=Zf(e,r,t,n);ql(o,i,a,l,n,s.number)}return o}function Zf(e,r,t,n){let o=e[r.index],s=o.content,i=se(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=se(a,"[",o.number),c=se(a,"{",o.number);if(c!==-1&&(d===-1||c<d)){Ot(a,o.number,n);let f;try{f=$l(a)}catch(_){if(n.strict)throw Fn(_,o.number);r.index+=1;let S=ns(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=eh(f,e,r,t+1,n);return{key:f.key,quoted:f.keyQuoted,value:v}}if(d!==-1){Ot(a,o.number,n);let f;try{f=Nn(a,i)}catch(_){if(n.strict)throw Fn(_,o.number);r.index+=1;let S=ns(e,r,t,l,o.number,n);return{key:a.trim(),quoted:!1,value:S}}if(f.key===""&&!f.keyQuoted)throw x(o.number,"expected non-empty field name");let v=ss(f,l,e,r,t,n);return{key:f.key,quoted:f.keyQuoted,value:v}}let[u,m]=Re(a,o.number);if(u===""&&!m)throw x(o.number,"expected non-empty field name");r.index+=1;let h=ns(e,r,t,l,o.number,n);return{key:u,quoted:m,value:h}}function ns(e,r,t,n,o,s){let i=n.trim();if(i==="[]")return[];if(i!=="")return he(i,o);let a=e[r.index];return a!==void 0&&a.depth>t?os(e,r,t+1,s):{}}function eh(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=se(i.content,":",i.number);if(a===-1)throw x(i.number,"expected `key: value`");let[l,d]=Re(i.content.slice(0,a),i.number);if(l===""&&!d)throw x(i.number,"expected non-empty field name");let c=we(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)=>{Br(u,m.path,Mn(m,c[h],i.number),o,i.number)}),ql(s,l,d,u,o,i.number),t.index+=1}return s}function rh(e,r,t){let n=r[0],o=se(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=ss(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 ss(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 th(e,e.fields,t,n,o+1,s)}if(a!==""){let l=we(a,e.delimiter,i).map(d=>he(d,i));if(l.length!==e.len)throw x(i,"array length mismatch");return l}return dh(e,t,n,o+1,s)}function th(e,r,t,n,o,s){if(e.fieldTree!==void 0&&ah(e.fieldTree))return nh(e,t,n,o,s);let i=[];for(;i.length<e.len;){let l=t[n.index];if(l===void 0)throw Wr(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(!Ur(l.content,e.delimiter,l.number))break;let d=we(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)=>{Br(c,u.path,Mn(u,d[m],l.number),s,l.number)}),i.push(c),n.index+=1}if(i.length!==e.len)throw Wr(t,n.index);let a=t[n.index];if(a!==void 0&&a.depth>=o&&Ur(a.content,e.delimiter,a.number))throw x(a.number,"array length mismatch");return i}function nh(e,r,t,n,o){return Ml(e.len,e.fieldTree,e.delimiter,r,t,n,o,!0)}function Ml(e,r,t,n,o,s,i,a){let l=[],d=Wl(e,r,t,n,o.index,s,i);for(;l.length<e;){let u=n[o.index];if(u===void 0)throw Wr(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(!Ur(u.content,t,u.number))break;let m=we(u.content,t,u.number),h={cellIndex:0,nextIndex:o.index+1,flatWidth:Wn(r),childTableFields:d},f=Fl(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(ih(r,f,a)),o.index=h.nextIndex}if(l.length!==e)throw Wr(n,o.index);let c=n[o.index];if(c!==void 0&&c.depth>=s&&Ur(c.content,t,c.number))throw x(c.number,"array length mismatch");return l}function Fl(e,r,t,n,o,s,i,a){let l={};return e.forEach((d,c)=>{let u=e.slice(c+1),m=oh(d,u,r,t,n,o,s,i,a);Br(l,[d.key],m,a,t)}),l}function oh(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=>he(u,n));return s.cellIndex+=e.fixedLength,c}if(e.children!==void 0){let c=Wn(e.children),u=t[s.cellIndex],m=Bl(u),h=t.length-s.cellIndex-1,f=o[s.nextIndex],v=f!==void 0&&f.depth===i,_=s.childTableFields===void 0?void 0:s.childTableFields.has(e);if(_===void 0?m!==void 0&&(v||t.length!==s.flatWidth&&h<c+lh(r)):_){if(m===void 0)throw x(n,"array row length mismatch");return s.cellIndex+=1,Ml(m,e.children,a,o,{get index(){return s.nextIndex},set index(j){s.nextIndex=j}},i,l,!1)}return Fl(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,Mn(e,d,n)}function Wl(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=Ul(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 Ul(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||!Ur(m.content,n,m.number))return;let h=we(m.content,n,m.number),f=sh(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&&Ur(c.content,n,c.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function sh(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=Bl(t[l]);if(m===void 0)return;l+=1;let h=Wl(m,u.children,n,o,d,i,a);if(h===void 0)return;let f=Ul(m,u.children,h,n,o,d,i,a);if(f===void 0)return;d=f.nextIndex,c+=m+f.consumedChildRows}else l+=Wn(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:c}}function ih(e,r,t){return t&&e.length===1&&e[0].fixedLength!==void 0?r[e[0].key]:r}function Bl(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function ah(e){return e.some(r=>r.fixedLength!==void 0||r.children!==void 0)}function Wn(e){return e.reduce((r,t)=>r+Hl(t),0)}function Hl(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?Wn(e.children):1}function lh(e){return e.reduce((r,t)=>t.children!==void 0?r+1:r+Hl(t),0)}function Ur(e,r,t){let n=se(e,":",t);if(n===-1)return!0;let o=se(e,r,t);return o===-1?!1:o<n}function dh(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 Wr(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(ch(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 ch(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=se(s,":",o.number);Ot(s,o.number,n);let a;try{a=Nn(s,i)}catch{a=void 0}if(a!==void 0){let l=s.slice(i+1);return ss(a,l,e,r,t,n)}}if(se(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 os(i,{index:0},t+1,n)}return r.index+=1,he(s,o.number)}function ql(e,r,t,n,o,s){if(o.expandPaths&&!t&&r.includes(".")){let i=r.split(".");if(i.every(uh)){Br(e,i,n,o,s);return}}Br(e,[r],n,o,s)}function Br(e,r,t,n,o){je(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");Ee(e,s,t);return}if(i&&!K(e[s])){if(n.strict)throw x(o,"path expansion conflict");Ee(e,s,{})}else i||Ee(e,s,{});Br(e[s],r.slice(1),t,n,o)}function uh(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=Gl(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?ds(s,void 0,e,0,!1,o):K(e)?Vl(s,e,0,o):s.push(ie(e,n)),s.join("")}function Hr(e,r){e.push(" ".repeat(r*2))}function Vl(e,r,t,n){je(t,0,n);for(let[o,s]of Object.entries(r))Hr(e,t),as(e,o,s,t,n)}function as(e,r,t,n,o){if(je(n,0,o),Array.isArray(t)){ds(e,r,t,n,!1,o);return}if(K(t)){let s=o.keyedMapCollapse?mh(t,o,n+1):void 0;if(s!==void 0){e.push(re(r),"{",cs(o.delimiter),s.fields.map(i=>ms(i,o.delimiter)).join(o.delimiter),`}:
|
|
15
|
-
`);for(let[i,a]of Object.entries(t)){
|
|
16
|
-
`),e.push(...l)}return}e.push(
|
|
17
|
-
`),
|
|
18
|
-
`)}function
|
|
12
|
+
`),t.common.length>0&&Ml(e,"common",t.common,t.commonRows);for(let n of t.groups)Ml(e,n.label,n.fields,n.rows)}function Ml(e,r,t,n){e.push(" ",te(r),"[",String(n.length),br,"]{",t.map(te).join(br),`}:
|
|
13
|
+
`);for(let o of n)e.push(" ",t.map(s=>ae(o[s],br)).join(br),`
|
|
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)){zr(e,n+1);let l=[];e.push(te(i),": ",s.paths.map(d=>Ss(Es(a,d.path),d,o.delimiter,o,l,n+2)).join(o.delimiter),`
|
|
16
|
+
`),e.push(...l)}return}e.push(te(r),`:
|
|
17
|
+
`),Zl(e,t,n+1,o);return}e.push(te(r),": ",ae(t,o.delimiter),`
|
|
18
|
+
`)}function _s(e,r,t,n,o,s){if(Ie(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("- "),
|
|
27
|
-
`)}function
|
|
28
|
-
`),e.push(...i)}}function
|
|
29
|
-
`}function
|
|
30
|
-
`}function
|
|
31
|
-
`,f=()=>
|
|
32
|
-
`;return
|
|
33
|
-
`},end(){return u?"":(u=!0,h())}}}function
|
|
21
|
+
`);return}if(t.every(Le)){ys(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:ed(t,s,n+1);if(i!==void 0){ys(e,r,t.length,i.fields,s.delimiter),e.push(`
|
|
23
|
+
`);for(let a of t){zr(e,n+1);let l=[];e.push(i.paths.map(d=>Ss(Es(a,d.path),d,s.delimiter,s,l,n+2)).join(s.delimiter)),e.push(`
|
|
24
|
+
`),e.push(...l)}return}ys(e,r,t.length,void 0,s.delimiter),e.push(`
|
|
25
|
+
`);for(let a of t)zr(e,n+1),Rh(e,a,n+1,s)}function Rh(e,r,t,n){if(Ie(t,0,n),Array.isArray(r)){e.push("- "),_s(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))zr(e,t+1),ks(e,s,i,t+1,n);return}e.push("- ",ae(r,n.delimiter),`
|
|
27
|
+
`)}function ys(e,r,t,n,o){r!==void 0&&e.push(te(r)),e.push("[",String(t),Rs(o),"]"),n!==void 0&&e.push("{",n.map(s=>vs(s,o)).join(o),"}"),e.push(":")}function Rs(e){return e===V?"":e}function ed(e,r,t){let n=Eh(e,r);if(n!==void 0)return n;let o=bs(e.map(s=>({value:s})),r,t);return o===void 0?void 0:{fields:o,paths:ws(o)}}function wh(e,r,t){let n=Object.values(e);if(!(n.length<2))return ed(n,r,t)}function bs(e,r,t){Ie(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})=>Le(l)))continue;if(r.primitiveArrayColumns&&i.every(({value:l})=>Array.isArray(l)&&l.every(Le))){s.listDelimiter=";";continue}if(r.objectArrayColumns&&i.every(({value:l})=>Array.isArray(l))){let l=rd(i.map(({value:c})=>c));if(l!==void 0){s.fixedLength=l.fixedLength,s.fixedDelimiter=r.delimiter;continue}let d=bs(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=bs(i,r,t+1);if(a===void 0)return;s.children=a}return o}}function Eh(e,r){if(!r.objectArrayColumns)return;let t=rd(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:r.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function rd(e){let r=e[0]?.length;if(!(!Number.isInteger(r)||r===0)&&e.every(t=>Array.isArray(t)&&t.length===r&&t.every(Le)))return{fixedLength:r}}function ws(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}]:ws(t.children,n)})}function Es(e,r){let t=e;for(let n of r)t=t[n];return t}function vs(e,r){return e.listDelimiter!==void 0?`${te(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${te(e.key)}[${e.fixedLength}${Rs(r)}]`:e.children===void 0?te(e.key):`${te(e.key)}{${e.children.map(t=>vs(t,r)).join(r)}}`}function Ss(e,r,t,n,o,s){return r.childFields!==void 0?(vh(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=>Sh(i,t,r.listDelimiter)).join(r.listDelimiter)}function vh(e,r,t,n,o){for(let s of r){zr(e,o);let i=[];e.push(ws(t).map(a=>Ss(Es(s,a.path),a,n.delimiter,n,i,o+1)).join(n.delimiter)),e.push(`
|
|
28
|
+
`),e.push(...i)}}function Sh(e,r,t){return typeof e!="string"?ae(e,r):ls(e,r)||e.includes(t)?Bn(e):e}var dd=[V,"|"," "];var cd=8,ud=/^[A-Za-z0-9_-]+$/,aP=new TextEncoder,lP=new TextDecoder;function Oh(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 pd(e,r){if(!ud.test(e))throw M(r,"invalid tag")}function Ah(e,r){let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t);if(!ud.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 Dh(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(!dd.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),pd(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=Se(c,a,r).map(m=>ve(m,r)[0])}catch(m){throw qr(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 jh(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 td(e,r,t,n){let o;try{o=Se(e,r,n)}catch(s){throw qr(s)}if(o.length!==t)throw M(n,"row arity mismatch");for(let s of o)try{ke(s,n)}catch(i){throw qr(i)}return o}function Lh(e,r,t){let n={};return e.forEach((o,s)=>{try{Te(n,o,ke(r[s],t))}catch(i){throw qr(i)}}),n}function Ih(e,r,t){if(e.startsWith("- "))throw M(r,"reserved line prefix");let n=Oh(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=Dh(e,r);if(o!==null)return o.continuation?(jh(t,o,r),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=Ah(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:td(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:td(e,t.delimiter,t.fields.length,r)}}function $h(e,r={}){let t=[],n=new Map,o=[],s=[],i=null,a=!1,l=!1;function d(h,f){let S=s.at(-1);if(S!==void 0&&S.lane===h.lane&&S.delimiter===h.delimiter&&S.fieldText===h.fieldText){S.rows.push(f);return}s.push({lane:h.lane,delimiter:h.delimiter,fields:h.fields,fieldText:h.fieldText,rows:[f]})}function c(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function u(h,f,S){let _=n.get(h);if(_===void 0){if(n.size>=cd)throw M(S,"too many tagged lanes");_={segments:[],current:null},n.set(h,_),t.push(h)}else _.current!==null&&_.segments.push(_.current);_.current={lane:h,delimiter:f.delimiter,fields:f.fields,fieldText:f.fieldText,rows:[]},_.delimiter=f.delimiter,_.fields=f.fields,_.fieldText=f.fieldText}if(Un(e).forEach((h,f)=>{let S=f+1;if(h==="")return;let _=i===null?{taggedLanes:n}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:n},v=Ih(h,S,_);if(v.kind==="trailer"){c(),i=null;return}if(v.kind!=="continuation"){if(v.kind==="tag-header"){l=!0,u(v.header.tag,v.header,S);return}if(v.kind==="header"){c(),a||(t.push(null),a=!0),i={lane:null,delimiter:v.header.delimiter,fields:v.header.fields,fieldText:v.header.fieldText,rows:[]};return}if(v.kind==="tagged-row"){l=!0;let C=n.get(v.tag).current;C.rows.push(v.cells),d(C,v.cells);return}if(i===null)throw M(S,"row before header");i.rows.push(v.cells),d(i,v.cells)}}),!l)return c(),r.preserveInterleaving===!0,o;let m=[];c();for(let h of t){if(h===null){m.push(...o);continue}let f=n.get(h);m.push(...f.segments),f.current!==null&&m.push(f.current)}return r.preserveInterleaving===!0?s:m}function $e(e){return $h(e).flatMap(r=>r.rows.map(t=>Lh(r.fields,t,0)))}function Gh(e){if(!dd.includes(e))throw M(0,"invalid header delimiter")}function nd(e,r,t=!1){return`[${`${t?"~":""}${e===V?"":e}`}]{${r}}:
|
|
29
|
+
`}function od(e,r){return`[]<${e}>{${r}}:
|
|
30
|
+
`}function Ts(e,r){return r.map(te).join(e)}function Ch(e){if(!Array.isArray(e)||e.length===0)throw M(0,"TOONL header requires fields");return e.map(r=>{let t;try{[t]=ve(String(r),0)}catch(n){throw qr(n)}if(t==="")throw M(0,"TOONL header requires fields");return t})}function sd(e,r){return e!==null&&e.length===r.length&&e.every((t,n)=>t===r[n])}function id(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw M(0,"TOONL continuation cadence must be positive")}function Nh(e,r,t){return e.continuationEveryRows!==void 0&&r>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function ad(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=>!Le(e[t])))throw M(0,"TOONL rows must be flat objects");return r}function Mh(e){return JSON.stringify([...e].sort())}function ld(e,r){let t=Mh(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}={}){Gh(e),id(t),id(n);let o=null,s="",i=new Map,a=0,l=0,d=0,c=new Map,u=!1,m={continuationEveryRows:t,continuationEveryBytes:n},h=()=>o===null||!r?"":`[=${a}]
|
|
31
|
+
`,f=()=>Nh(m,l,d)?(l=0,d=0,nd(e,s,!0)):"",S=_=>{pd(_,0);let v=c.get(_);if(v===void 0){if(c.size>=cd)throw M(0,"too many tagged lanes");v={fields:null,fieldsByShape:new Map},c.set(_,v)}return v};return{push(_){if(u)throw M(0,"TOONL encoder is closed");let v=ld(ad(_),i),C="";(o===null||o.length!==v.length||o.some((Q,ee)=>Q!==v[ee]))&&(C+=h(),o=v,s=Ts(e,o),a=0,l=0,d=0,C+=nd(e,s));let H=o.map(Q=>ae(_[Q],e));C+=f();let L=`${H.join(e)}
|
|
32
|
+
`;return C+=L,a+=1,l+=1,d+=L.length,C},declareLane(_,v){if(u)throw M(0,"TOONL encoder is closed");let C=Ch(v),H=Ts(V,C),L=S(_);return sd(L.fields,C)?"":(L.fields=C,od(_,H))},pushTagged(_,v){if(u)throw M(0,"TOONL encoder is closed");let C=S(_),H=ld(ad(v),C.fieldsByShape),L=Ts(V,H),Q=H.map(le=>ae(v[le],V)),ee="";return sd(C.fields,H)||(C.fields=H,ee+=od(_,L)),`${ee}${_}:${Q.join(V)}
|
|
33
|
+
`},end(){return u?"":(u=!0,h())}}}function xs(e){let r={app:e,version:Fh(Qr("__RED_BUILD_VERSION__",()=>"3.6.0")??"0.0.0-dev"),gitSha:Qr("__RED_BUILD_GIT_SHA__",()=>"dd8922efad583c6a2a7b6a4963ba4f3f5334eaac")??"unknown",buildTime:Qr("__RED_BUILD_TIME__",()=>"2026-08-05T04:59:15Z")??"unknown",bundleAsset:Qr("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=Qr("__REDDB_SDK_VERSION__",()=>""),n=Qr("__REDDB_BINARY_TAG__",()=>"");return t&&(r.reddbSdkVersion=t),n&&(r.reddbBinaryTag=n),r}function Fh(e){return e.startsWith("v")?e.slice(1):e}function md(e){return`${e.app} ${e.version} ${e.gitSha}`}function Qr(e,r){try{let t=r();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var gd={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Wh=/^[a-z][a-z0-9+.-]*:\/\//i;function Uh(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 Bh(e=gd){return Object.entries(e).map(([r,t])=>Uh(r,t)).sort((r,t)=>t.separator.length-r.separator.length)}function Hh(e){return/^-\d+(\.\d+)?$/.test(e)}function $t(e){return!(!e||e.startsWith("-")&&!Hh(e))}function zn(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 fd(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=>fd(t.trim())):e}function _r(e,r){switch(r){case"boolean":return qh(e);case"number":return Vh(e);case"array":return e.split(",").map(t=>zn(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 Vh(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 er(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Kh(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 Jh(e){let r=[],t=Qh(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=Yh(e.options);r.push(...n)}return r}function zh(e,r){let t=Jh(e);return Kh(t,r)}function Qh(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 Yh(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=S=>{u.includes(S)||u.push(S)};c.short&&m(`-${c.short}`),m(`--${d}`);for(let S of c.aliases??[])S.length===1?m(`-${S}`):m(`--${S}`);let h=u.join(", "),f=c.type&&c.type!=="boolean"?`<${c.type}>`:void 0;n.push({flags:h,type:f,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 hd(e){let r=oy(e.options??{},e.autoShort??!1),t=Bh(e.separators??gd);return{schema:e,parse(n){return Xh(n,e,r,t)},help(){return zh(e,e.formatter)}}}function Xh(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 h=[];for(;l<e.length;){let f=e[l];h.push(m.type?_r(f,m.type):f),l++}o.positional[m.name]=h,i++}else{let h=m.type?_r(c,m.type):c;o.positional[m.name]=h,i++,l++}}else r.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(c)),l++;continue}if(c.startsWith("--")){l=ty(c,l,e,o,t,r);continue}if(c.startsWith("-")&&c.length>1&&!dy(c)){l=ny(c,l,e,o,t,r);continue}let u=Zh(c,n);if(u){let{key:m,value:h,config:f}=u,S=o,_=S[f.to]??(S[f.to]={});_[m]=f.typed?fd(h):er(h),l++;continue}if(i<a.length){let m=a[i];if(m.variadic){let f=[];for(;l<e.length&&!e[l].startsWith("-");){let S=e[l];f.push(m.type?_r(S,m.type):S),l++}o.positional[m.name]=f,i++;continue}let h=m.type?_r(c,m.type):c;o.positional[m.name]=h,i++}else r.allowUnknown!==!1?o.rest.push(c):o.errors.push(`Unexpected positional argument: ${c}`);l++}return iy(o,r,t),ay(o,r,a),ly(o,r,t),o}function Zh(e,r){if(Wh.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(ey(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(ry(o,s,t))return{key:o,value:s,config:t}}}return null}function ey(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function ry(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 ty(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 Qn(d,c,r+1,n,o,s)}let a=o.get(i);if(a){if(a.type!=="boolean"){let l=t[r+1];return $t(l)?Qn(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 ny(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=Ps(l,o);return c?Qn(c.name,d,r+1,n,o,s):(s.strict?n.errors.push(`Unknown option: -${l}`):s.allowUnknown!==!1&&(n.options[l]=zn(er(d))),r+1)}if(i.length===1){let a=Ps(i,o);if(a){if(a.type!=="boolean"){let l=t[r+1];return $t(l)?Qn(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($t(l))return n.options[i]=zn(er(l)),r+2;n.options[i]=!0}return r+1}for(let a of i){let l=Ps(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 Qn(e,r,t,n,o,s){let i=o.get(e);if(i){if(i.choices){let l=i.type?_r(er(r),i.type):er(r);if(!i.choices.includes(l))return n.errors.push(`Invalid value for '${e}': '${r}'. Allowed: ${i.choices.join(", ")}`),t}let a=i.type?_r(er(r),i.type):er(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]=zn(er(r)));return t}function oy(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=sy(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 sy(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 Ps(e,r){for(let t of r.values())if(t.short===e||t.aliases.includes(e))return t}function iy(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?_r(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 ay(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 ly(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 dy(e){return/^-\d+(\.\d+)?$/.test(e)}var Os=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 cy(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 uy(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&&$t(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 rr(e,r,t={}){let o=hd({options:cy(r),separators:{},allowUnknown:!0}).parse([...e]),s={},i=uy(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 Os(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 As=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 yd(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 As(t,Object.keys(r.commands))}let o=r.keepArgvOnDefault??!0;return{command:r.default,args:o?[...e]:n}}import{appendFileSync as wy,mkdirSync as Ey,readFileSync as xd,statSync as vy}from"node:fs";import{dirname as Od,join as Sy}from"node:path";var kd="RED_WORKER_SCOPE",bd="RED_WORKER_MEMORY_CEILING",_d="RED_WORKER_SCOPE_DEGRADATION",js={scope:null,memory_ceiling:null,scope_degradation:null};function Ls(e){return{scope:Ds(e[kd]),memory_ceiling:Ds(e[bd]),scope_degradation:Ds(e[_d])}}function Gt(e){let r={};return e.scope!=null&&e.scope!==""&&(r[kd]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(r[bd]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(r[_d]=e.scope_degradation),r}function Ds(e){let r=(e??"").trim();return r===""?null:r}import{mkdirSync as gy,readdirSync as fy,readFileSync as vd,rmSync as hy,writeFileSync as yy}from"node:fs";import{basename as ky,join as Yr}from"node:path";import{isAbsolute as WP,join as Yn,resolve as UP}from"node:path";function py(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var Rd="deaths",wd="deaths.toonl";function Xn(e){return Yn(py(e),Rd)}function Ct(e){return Yn(Xn(e),wd)}var Nt="live",Ed="attributions.toonl";function Zn(e){return Yn(Xn(e),Nt)}function Is(e){return Yn(Xn(e),Ed)}var Gs=Yr("sys","kernel","random","boot_id"),Sd=1;function Cs(e,r={}){let t=r.procRoot??"/proc",n=e.pid??process.pid;return{version:Sd,ts:(r.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:n,ppid:e.ppid??process.ppid,boot_id:Td(Yr(t,Gs)),cgroup:by(t,n),last_phase:e.last_phase}}function Td(e){try{let r=vd(e,"utf8").trim();return r===""?null:r}catch{return null}}function by(e,r){let t=Td(Yr(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 Ns(e){let r=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${r}-${e.pid}.toon`}function Ms(e,r){let t=Yr(e,Ns(r));try{return gy(e,{recursive:!0,mode:448}),yy(t,ge({trailer:!1}).push(Ry(r)),{encoding:"utf8",mode:384}),t}catch{return null}}function Rr(e,r){try{hy(Yr(e,Ns(r)),{force:!0})}catch{}}function Fs(e,r){let t;try{t=fy(e)}catch{return[]}let n=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=Yr(e,o);try{let a=$e(vd(s,"utf8"))[0];if(a===void 0)throw new Error("anchor holds no record");n.push(_y(a))}catch(i){r?.(ky(s),i instanceof Error?i.message:String(i))}}return n}function _y(e){let r=e.kind;if(r!=="launcher"&&r!=="worker"&&r!=="daemon")throw new Error(`presence anchor has unknown kind ${String(r)}`);return{version:$s(e.version),ts:String(e.ts),kind:r,id:String(e.id),pid:$s(e.pid),ppid:$s(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 $s(e){return typeof e=="number"?e:Number(e)}function Ry(e){return{...e}}var Ty=1,xy=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Py(e){return typeof e=="string"&&xy.has(e)}var Oy="startup";function Ay(e,r){return{...e.scope??js,version:Ty,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 Dy(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 Us={mkdir(e){Ey(e,{recursive:!0,mode:448})},endsClean(e){let r;try{r=vy(e).size}catch{return!0}if(r===0)return!0;try{return xd(e,"utf8").endsWith(`
|
|
43
|
+
`)}catch{return!0}},append(e,r){wy(e,r,{encoding:"utf8",mode:384})},read(e){return xd(e,"utf8")}};function jy(e){let r={};for(let[t,n]of Object.entries(e))r[t]=n;return r}function Ly(e,r,t=Us){let n=ge({trailer:!1}).push(jy(r));return t.mkdir(Od(e)),t.endsClean(e)||t.append(e,`
|
|
44
|
+
`),t.append(e,n),r}function Ad(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===""?[]:$e(r).map(Iy)}function Iy(e){let r=e.exit_path;if(!Py(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:be(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:be(e.pid),exit_path:r,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:be(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:be(e.uptime_s),rss_kb:be(e.rss_kb),max_rss_kb:be(e.max_rss_kb),user_cpu_us:be(e.user_cpu_us),system_cpu_us:be(e.system_cpu_us),minor_page_faults:be(e.minor_page_faults),major_page_faults:be(e.major_page_faults),voluntary_ctx_switches:be(e.voluntary_ctx_switches),involuntary_ctx_switches:be(e.involuntary_ctx_switches)}}function be(e){return typeof e=="number"?e:Number(e)}function Dd(e,r=Us){let t;try{t=r.read(e)}catch(n){if(n.code==="ENOENT")return[];throw n}return Ad(t)}var $y=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],Ws=null;function jd(e){let r=e.host??process,t=e.io??Us,n=e.clock??(()=>new Date().toISOString()),o=r.pid,s=e.scope??Ls(process.env),i=e.phase??Oy,a=null,l=e.presenceDir===void 0?Sy(Od(e.lanePath),Nt):e.presenceDir,d=null,c=()=>{l!==null&&(d=Cs({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),Ms(l,d))},u=_=>{if(!a){try{a=Ly(e.lanePath,Ay({ts:n(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,..._},Dy(r)),t)}catch{}l!==null&&d!==null&&Rr(l,d)}},m={signal(_){u({exit_path:"signal",signal:_})},exit(_){u({exit_path:"exit",exit_code:_})},uncaughtException(_){u({exit_path:"uncaught-exception",detail:Pd(_)})},unhandledRejection(_){u({exit_path:"unhandled-rejection",detail:Pd(_)})}},f=[...(e.signals??$y).map(_=>{let v=()=>{if(m.signal(_),!(r.listenerCount?.(_)!==1||!r.kill)){r.off(_,v);try{r.kill(o,_)}catch{}}};return[_,v]}),["uncaughtException",(..._)=>m.uncaughtException(_[0])],["unhandledRejection",(..._)=>m.unhandledRejection(_[0])],["exit",(..._)=>m.exit(typeof _[0]=="number"?_[0]:null)]];for(let[_,v]of f)r.on(_,v);let S={lanePath:e.lanePath,phase(_){i=_,a||c()},currentPhase:()=>i,written:()=>a,uninstall(){for(let[_,v]of f)r.off(_,v);l!==null&&d!==null&&Rr(l,d),Ws===S&&(Ws=null)},handlers:m};return e.setActive!==!1&&(Ws=S),c(),S}function Pd(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Gy,readdirSync as Cy,readFileSync as eo,statSync as Ny,writeFileSync as My}from"node:fs";import{join as Gd}from"node:path";var Fy=1,Wy=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],Uy=512*1024;function By(e={}){let r=e.procRoot??"/proc",t=e.journalPaths??Wy,n=[],o=Gd(r,Gs),s=null;try{let l=eo(o,"utf8").trim();s=l===""?null:l,n.push({source:o,result:s?"read":"empty",detail:s})}catch(l){n.push({source:o,result:Bs(l),detail:null})}let i=new Set;try{for(let l of Cy(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:Bs(l),detail:null})}let a=[];for(let l of t)try{let c=Hy(l,e.tailBytes??Uy).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:Bs(d),detail:null})}return{boot_id:s,live_pids:i,journal:a,probes:n}}function Bs(e){return e.code==="ENOENT"?"absent":"unreadable"}function Hy(e,r){let t=Ny(e).size,n=eo(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+)/,Vy=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,Ky=/Killed (\/\S*) due to memory pressure/,Jy=/\bopid=(\d+)\b/,Ld=/\bsig=(\d+)\b/,zy=/\buid=(\d+)\b/,Qy=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,Yy={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function Xy(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,h,f)=>({version:Fy,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:h,host_boot_changed:o,evidence:f,checked:s}),a=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],l=r.journal.find(u=>Id(u,e.pid,qy)||Id(u,e.pid,Vy));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=Ky.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(Jy.exec(u)?.[1])===e.pid&&Ld.test(u));if(d!==void 0){let u=Number(Ld.exec(d)?.[1]),m=zy.exec(d)?.[1];return i("user-signal",o?"medium":"high",Yy[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=>Qy.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 Id(e,r,t){return Number(t.exec(e)?.[1])===r}var Zy=" | ";function $d(e){return e.map(r=>r.replace(/[|\n\r]+/g," ").trim()).join(Zy)}function ek(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:$d(e.evidence),checked:$d(e.checked)}}function rk(e){let r=ge({trailer:!1});return e.map(t=>r.push(ek(t))).join("")}function Cd(e){let r=Zn(e.stateRoot),t=Is(e.stateRoot),n=e.now??(()=>new Date().toISOString()),o=e.evidence??By({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=Fs(r,u=>s.push(u)),a=Dd(Ct(e.stateRoot)),l=[],d=[],c=[];for(let u of i){if(o.live_pids.has(u.pid)){d.push(u);continue}if(a.find(h=>h.pid===u.pid&&h.id===u.id)!==void 0){c.push(u),Rr(r,u);continue}l.push(Xy(u,o,a,n())),Rr(r,u)}return l.length>0&&tk(t,l),{attributions:l,alive:d,self_recorded:c,skipped:s,laneText:()=>{try{return eo(t,"utf8")}catch{return""}}}}function Nd(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 tk(e,r){try{Gy(Gd(e,".."),{recursive:!0,mode:448});let t=nk(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
|
+
`;My(e,`${t}${n}${rk(r)}`,{encoding:"utf8",mode:384})}catch{}}function nk(e){try{return eo(e,"utf8")}catch{return""}}import{join as ok}from"node:path";var sk=[".red","redskilled"],qe=448;function Ge(e){return ok(e,...sk)}import{execFileSync as bk}from"node:child_process";import{readFileSync as _k}from"node:fs";import{dirname as qd,join as Rk}from"node:path";import{existsSync as ik,readFileSync as bO}from"node:fs";import{dirname as ak,join as lk}from"node:path";function Md(e,r){let t=e;for(let n=0;n<16;n++){let o=lk(t,r);if(ik(o))return o;let s=ak(t);if(s===t)break;t=s}return null}function dk(e){let r=e.indexOf(" #");return(r>=0?e.slice(0,r):e).trim()}function Xr(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 dk(d)}}import{createHash as ck}from"node:crypto";var uk="project.name";function Wd(e){let r=Xr(e,uk)?.trim();return r===void 0||r===""?void 0:r}var pk=8,Ud="project";function Bd(e){let r=yk(e.gitCommonDir),t=(e.declaredName??"").trim(),n=t!==""?{name:t,source:"declared"}:mk(e.remoteUrl)??{name:gk(e.checkoutPath,r),source:"basename"},o=hk(r??Hs(e.checkoutPath));return{name:n.name,slug:`${fk(n.name)}-${o}`,hash:o,source:n.source}}function Hd(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 mk(e){let r=Hd(e);return r===void 0?void 0:{name:r,source:"remote"}}function gk(e,r){let t=r===void 0?"":Fd(kk(r));if(t!=="")return t;let n=Fd(Hs(e));return n===""?Ud:n}function fk(e){let t=e.split("/").map(n=>n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(n=>n!=="").join("--");return t===""?Ud:t}function hk(e){return ck("sha256").update(e).digest("hex").slice(0,pk)}function yk(e){let r=Hs(e??"");return r===""?void 0:r}function Hs(e){let r=e.trim().replace(/\\/g,"/");return r.length>1?r.replace(/\/+$/,""):r}function Fd(e){let r=e.split("/").filter(t=>t!=="");return r[r.length-1]??""}function kk(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var wk=2e3;function Vd(e){return Ek(e).name}function Ek(e){let r=Vs(e),t=qs(e,["rev-parse","--absolute-git-dir"])??qs(e,["rev-parse","--git-common-dir"]),n=qs(e,["remote","get-url","origin"]);return Bd({checkoutPath:r.root??e,...t!==void 0?{gitCommonDir:t}:{},...n!==void 0?{remoteUrl:n}:{},...r.name!==void 0?{declaredName:r.name}:{}})}function Vs(e){let r=Md(e,Rk(".red","config.yaml"));if(r==null)return{};let t;try{t=_k(r,"utf8")}catch{return{}}let n=Wd(t),o=qd(qd(r));return{...n===void 0?{}:{name:n},configText:t,root:o}}function qs(e,r){try{let t=bk("git",[...r],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:wk}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as kg}from"node:crypto";import{spawn as US}from"node:child_process";import{mkdir as BS}from"node:fs/promises";import{dirname as HS}from"node:path";import{createHash as Tk}from"node:crypto";import{constants as Ys}from"node:fs";import{mkdir as rc,open as xk,readFile as Pk,rm as tc,stat as Ok}from"node:fs/promises";import{createConnection as Ak}from"node:net";import{tmpdir as Dk}from"node:os";import{dirname as nc,join as Mt}from"node:path";var vk="toon";function zd(e){return e.trimStart().startsWith("{")?"json":"toon"}function Js(e){let r=0;for(;e[r]===`
|
|
51
|
+
`||e[r]==="\r";)r+=1;let t=e.slice(r);if(t==="")return null;let n=zd(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 zs(e){let r=zd(e)==="json"?Ks:Kd,t=r===Ks?Kd:Ks;try{return r(e)}catch(n){try{return t(e)}catch{throw n}}}function Ks(e){return JSON.parse(e)}function Kd(e){return ue(e)}function Qs(e,r){if(r==="toon"){let t=Sk(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(Xd))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 Ak(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 _k(e)).mtimeMs)}catch{return null}}function ne(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}var Dk="/tmp";function zn(e){let r=e.env??process.env,t=yk("sha256").update(e.key).digest("hex").slice(0,20),n=l=>Gt(l,e.socketFileName).length<Ek,o=r.XDG_RUNTIME_DIR;if(o){let l=Gt(o,"red-skills",t);if(n(l))return l}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=Gt(`red-skills-${s}`,t),a=Gt(wk(),i);return n(a)||process.platform==="win32"?a:Gt(Dk,i)}Ue();import{homedir as eb}from"node:os";import{join as Xs}from"node:path";import{spawnSync as rb}from"node:child_process";import{createHash as tb}from"node:crypto";import{existsSync as nb,readdirSync as ob}from"node:fs";import{mkdir as dc,readFile as sb,rename as ib,writeFile as ab}from"node:fs/promises";import{dirname as lb}from"node:path";var br="@reddb-io/red-skills",Uk="https://registry.npmjs.org",Bk="canary",kr=class extends Error{kind;cause;constructor(r,t,n){super(t),this.name="BundleFetchError",this.kind=r,this.cause=n}},Hk=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;function Ks(e){return typeof e=="string"&&Hk.test(e.trim())}function sc(e){return`${e}-.bundle.min.mjs`}var qk=".unversioned";function Vk(e,r,t="stable"){if(t==="canary")return`${e}-canary.bundle.min.mjs`;if(!Ks(r))throw new kr("invalid-version",`refusing to key the ${e} bundle cache on ${JSON.stringify(r??"")}: it would mint ${sc(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 Zn(e){let{plugin:r,version:t,cacheDir:n,channel:o}=e;return Nt(n,Vk(r,t,o))}function Kk(e){return e==="dev"?["rsp","redskilled"]:[]}function Jk(e){return`${e}.bundle.min.mjs`}function zk(e){return Nt("dist",Jk(e))}function Qk(e,r="stable"){return`${br}@${r==="canary"?Bk:e}`}function Js(e=br){return`${Uk}/${e.replace("/","%2F")}`}async function zs(e,r){let{plugin:t,version:n,cacheDir:o,channel:s="stable"}=r,i=Zn({plugin:t,version:n,cacheDir:o,channel:s}),a=Kk(t),l=a.map(m=>Zn({plugin:m,version:n,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await Xk(e,l))return i;let d=Qk(n,s),c=Nt(o,`.staging-${t}-${s==="canary"?"canary":n}`),u;try{u=await e.materialize(d,c)}catch(m){throw lc(m,d)}for(let m of[t,...a]){let h=zk(m),f=Nt(u,h);if(!await e.exists(f))throw new kr("bundle-missing",`npm package ${d} has no ${h}`);let v=m===t?i:Zn({plugin:m,version:n,cacheDir:o,channel:s});await e.writeFile(v,await e.readFile(f))}return await Yk(e,o,[t,...a]),i}async function Yk(e,r,t){if(e.rename)for(let n of t){let o=Nt(r,sc(n));try{if(!await e.exists(o))continue;await e.rename(o,`${o}${qk}`)}catch{}}}async function Xk(e,r){for(let t of r)if(!await e.exists(t))return!1;return!0}async function ic(e,r,t=br){let n;try{n=await e.fetchText(Js(t))}catch(s){throw lc(s,t)}let o=Qs(n);return{sameMajor:Zk(o,r),newest:Ys(o)}}function Qs(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 Zk(e,r){let t=Vs(r);if(t===null)return null;let n=null;for(let o of e)Vs(o)===t&&(n===null||ac(o,n)>0)&&(n=o);return n}function Ys(e){let r=null;for(let t of e){let n=String(t).trim();Vs(n)===null||/^\d+\.\d+\.\d+[-+]/.test(n)||(r===null||ac(n,r)>0)&&(r=n)}return r}function Vs(e){let r=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return r?Number(r[1]):null}function ac(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 lc(e,r){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new kr("npm-unavailable",`npm is unavailable while resolving ${r}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new kr("package-missing",`npm could not resolve ${r}: ${t}`,e):new kr("network",`failed to resolve ${r}: ${t}`,e)}function Nt(e,r){return e.endsWith("/")?`${e}${r}`:`${e}/${r}`}Ue();var cc={async materialize(e,r){await dc(r,{recursive:!0});let t=rb("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 Xs(r,"node_modules",...br.split("/"))},async readFile(e){return new Uint8Array(await sb(e))},async writeFile(e,r){await dc(lb(e),{recursive:!0}),await ab(e,r)},async exists(e){return nb(e)},sha256(e){return tb("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 ib(e,r)}},db="redskilled";function cb(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let r=e.XDG_CACHE_HOME||Xs(e.HOME||eb(),".cache");return Xs(r,"red-skills","bundles")}var ub=/^([a-z0-9-]+)-(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?)\.bundle\.min\.mjs$/;async function pb(e,r){if(Ks(e.version))return e.version.trim();let t=e.listCacheDir??fb,n=mb(t(r),"dev");if(n)return n;try{let s=await(e.bundleIO??cc).fetchText(Js());return Ys(Qs(s))}catch{return null}}function mb(e,r){let t=null;for(let n of e){let o=ub.exec(n);if(!o||o[1]!==r)continue;let s=o[2];(t===null||gb(s,t)>0)&&(t=s)}return t}function gb(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 fb(e){try{return ob(e)}catch{return[]}}async function hb(e={},r={},t={}){let n=er(e,r);if(Ge(n))return n;let o=t.env??r.env??process.env,s=cb(o),i=await pb(t,s);if(i===null)return n;try{await zs(t.bundleIO??cc,{plugin:db,version:i,cacheDir:s})}catch{return n}return er(e,r)}async function uc(e={},r={},t={}){let n=await hb(e,r,t);if(Ge(n))return n;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(Ue(),oc));throw new o(n)}import{randomUUID as jo}from"node:crypto";import{mkdir as RS,rm as sg}from"node:fs/promises";import{connect as wS,createServer as ES}from"node:net";import{dirname as vS}from"node:path";import{availableParallelism as gc,totalmem as kb}from"node:os";function Mt(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 pc(e,r={}){let t=0,n=0,o=0,s=[],i=[];for(let d of e){let c=Mt(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=Jr(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:yb(e.length,n,a,l)}}function yb(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 Jr(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 mc(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 fc="REDSKILLED_MEMORY_CEILING",ei="REDSKILLED_WORKER_CEILING",bc="REDSKILLED_VALIDATION_CEILING",hc="REDSKILLED_INTERACTIVE_RESERVATION",Ft=1,yc=.7,bb=2*1024**3,_b=2;function _c(e){let r=e?.memory_max??e?.memory_high;if(r!=null)return Jr(r)}function ro(e){let r=0,t=[];for(let n of e){let o=_c(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 Rc(e){let{ceiling:r}=e,t=ro(e.workers),n=_c(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??Ft),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 wc(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=ro(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 (${ei} 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 to(e=process.env,r=kb(),t={}){let n=Zs(t.flags?.memoryCeiling,e[fc],t.config?.memoryCeiling),o=Zs(t.flags?.workerCeiling,e[ei],t.config?.workerCeiling),s=Zs(t.flags?.validationCeiling,e[bc],t.config?.validationCeiling),i=n?.value??"",a=o?.value??"",l=(e[hc]??"").trim(),d=Ec(a),c=l===""?Ft:Eb(l),u=o?.source??"derived-default";if(a!==""&&d===null&&!Rb(a)&&(eo(`redskilled: ${ri(o)} ${ei}=${JSON.stringify(a)} is not a positive integer; this host admits an unbounded number of Workers instead.`),u="derived-default"),i!==""){let m=wb(i,r);if(m!==void 0)return kc({memory_bytes:m,worker_count:d,interactive_reservation:c??Ft,source:"declared",memory_source:n.source,worker_source:u},s,t.availableParallelism??gc());eo(`redskilled: ${ri(n)} ${fc}=${JSON.stringify(i)} is not a memory ceiling this host can read; using ${yc*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return l!==""&&c===void 0&&eo(`redskilled: ${hc}=${JSON.stringify(l)} is not a non-negative integer; using the default reservation of ${Ft} Worker(s) instead.`),kc({memory_bytes:Math.floor(r*yc),worker_count:d,interactive_reservation:c??Ft,memory_source:"derived-default",worker_source:u,source:"host-fraction"},s,t.availableParallelism??gc())}function kc(e,r,t){if(r!==void 0){let i=Ec(r.value);if(i!==null)return{...e,validation_count:i,validation_source:r.source};eo(`redskilled: ${ri(r)} ${bc}=${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)/_b)),o=e.memory_bytes==null?Number.POSITIVE_INFINITY:Math.max(1,Math.floor(e.memory_bytes/bb)),s=e.worker_count??Number.POSITIVE_INFINITY;return{...e,validation_count:Math.max(1,Math.min(n,o,s)),validation_source:"derived-default"}}function Zs(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 ri(e){return e.source==="flag"?"serve flag":e.source==="environment"?"environment":e.source==="home-config"?"home config":"derived default"}function Rb(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var eo=e=>process.stderr.write(`${e}
|
|
62
|
-
`);function
|
|
63
|
-
`);return r.pop(),r.length===0?[]
|
|
59
|
+
`}function Sk(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 Qd(e,r){return!Jd(e)||!Jd(r)||r.ok!==!1?!1:typeof e.id=="string"&&typeof r.id=="string"&&r.id!==e.id}function Jd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Yd=new Set;function Xd(e){return Yd.has(e)?"json":vk}function Zd(e){Yd.add(e)}var jk=108;async function ro(e,r,t="resident server"){let n=e.wire,o=n??Xd(e.socketPath),s=await ec(e,r,t,o);return n||o==="json"||!Qd(r,s)?s:(Zd(e.socketPath),await ec(e,r,t,"json"))}async function ec(e,r,t,n){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let a=Ak(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(Qs(r,n))}),a.on("data",m=>{d+=m.toString("utf8");let h=Js(d);h&&(d=h.rest,u(()=>{try{s(zs(h.frame))}catch(f){i(f)}}),a.end())}),a.on("error",m=>u(()=>i(m))),a.on("close",()=>{l||u(()=>i(new Error(`${t} closed without response`)))})})}function oc(e,r,t){let n="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{n+=o;let s=Js(n);if(!s)return;n=s.rest,e.pause();let i=a=>{if(!(e.destroyed||!e.writable))try{e.write(Qs(a,s.dialect))}catch{}};(async()=>{let a;try{a=zs(s.frame),await r(a,i)}catch(l){t(l,a,i)}finally{e.end()}})()})}async function Lk(e){await rc(nc(e),{recursive:!0,mode:448});try{return await xk(e,Ys.O_CREAT|Ys.O_EXCL|Ys.O_RDWR)}catch(r){if(r.code!=="EEXIST")throw r;return null}}var Ik=6e4,sc="resident-spawn-lock v1",$k=3;async function ic(e,r={}){let t=r.maxAgeMs??Ik,n=r.now??Date.now,o=r.pid??process.pid,s=r.isPidAlive??oe;await rc(nc(e),{recursive:!0,mode:448});let i=[];for(let a=0;;a+=1){let l=await Lk(e);if(l)return await l.writeFile(`${sc} pid=${o} taken=${new Date(n()).toISOString()}
|
|
60
|
+
`).catch(()=>{}),{acquired:!0,lockPath:e,handle:l,reaped:i};let d=await Ck(e),c=await Mk(e,d,n());if(a>=$k||c==null)return{acquired:!1,lockPath:e,holder:d,ageMs:c};let u=Gk(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 tc(e,{force:!0}),i.push(m),r.onReap?.(m)}}async function ac(e){await e.handle.close().catch(()=>{}),await tc(e.lockPath,{force:!0})}function Gk(e,r,t,n){return e==null?r>t?"unattributed":null:n(e.pid)?r>t?"aged-out":null:"holder-dead"}function lc(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 Ck(e){try{return Nk(await Pk(e,"utf8"))}catch{return null}}function Nk(e){let r=e.split(`
|
|
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 Db(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)):Zr(e)??void 0}function Ac(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 jb(e){let r=Number(e);return Number.isSafeInteger(r)&&r>=0?r:void 0}import{appendFile as Lb,mkdir as Ib,open as $b,readFile as Gb,stat as Cb,truncate as Dc}from"node:fs/promises";import{dirname as Nb}from"node:path";var jc="redskilled.log.toonl";function Mb(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 Fb="daemon:";function Wb(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${Fb}${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 Ub(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 Lc(e){let r=ge({trailer:!1}),t=Promise.resolve();async function n(o){let s=t.then(async()=>{await Ib(Nb(e),{recursive:!0,mode:448}),await Bb(e),await Lb(e,r.push(Kb(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>n(Mb(o)),recordDemandRefusal:o=>n(Ub(o)),recordDaemonStop:o=>n(Wb(o)),read:()=>Hb(e),flush:async()=>{await t}}}async function Bb(e){let r;try{r=(await Cb(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(r===0)return;let t=64*1024,n=await $b(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 Dc(e,s-i+l+1);return}}await Dc(e,0)}finally{await n.close()}}async function Hb(e){let r;try{r=await Gb(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return qb(r)}function qb(e){let r=e.split(`
|
|
63
|
+
`);return r.pop(),r.length===0?[]:$e(`${r.join(`
|
|
64
64
|
`)}
|
|
65
|
-
`).filter(Mb).map(Fb)}function xc(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,Cb(t)):r.delete(t.worker_id));return[...r.values()]}function Cb(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 Nb(e){return{...e}}function Mb(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 Fb(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:Be(e.project_label)??"",pid:Number(e.pid??0),workspace_path:Be(e.workspace_path)??"",log_path:Be(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:Be(e.unit),memory_high:Be(e.memory_high),memory_max:Be(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:Be(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:Be(e.signal),reason:Be(e.reason)}}function Be(e){return e==null||e===""?null:String(e)}function Pc(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,v=f?1:h;o.push({...c,outcome:f?"half-open-probe":"asking",wanted:v,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;_<v;_+=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 Oc(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function Ac(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 Wt={shortLifeStreak:0,haltUntilMs:null,openedAtMs:null,probeWorkerId:null};function Dc(e,r,t){if(r>=6e4)return Wt;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 jc(e,r){return e.haltUntilMs==null?e:{...e,probeWorkerId:r}}function ti(){return Wt}function Wb(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 Lc(e,r){return Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>Wb(t,n,r)).filter(t=>t!=null)}function Gc(e){let r=e.workers.map(Ub),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:Hb({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:r.length,projects:t.length,surviving:n.length})}}function $c(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 Ub(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 Bb(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 Hb(e){let r=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Bb(e.reason)}`;return e.held===0?`${r}; it holds no Workers, so nothing survives the stop`:`${r}; it holds ${Ic(e.held,"Worker")} across ${Ic(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 Ic(e,r){return`${e} ${r}${e===1?"":"s"}`}function ni(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 qb,mkdir as Vb,readFile as Kb,rm as Jb,writeFile as zb}from"node:fs/promises";import{dirname as Cc,join as Wc}from"node:path";import{tmpdir as Nc}from"node:os";var Qb="redskilled.machine.claim.toon",Yb="REDSKILLED_MACHINE_DIR",Xb=8,rr=class extends Error{constructor(t,n,o){super(e_(t,n,o));this.claimPath=t;this.reason=n;this.claim=o;this.name="RedskilledMachineHeldError"}},Mc;function Uc(){return Mc??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},Mc}function Zb(e={machineIdHash:"unknown"}){let r=e.env??process.env,t=r[Yb]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?r.PROGRAMDATA?.trim()||Nc():Nc();return Wc(o,`redskilled-${e.machineIdHash}`)}function no(e){return Wc(Zb(e),Qb)}function oo(e,r,t={}){let n=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??ne;async function s(){let l;try{l=await Kb(e,"utf8")}catch(c){if(c.code==="ENOENT"||oi(c))return;throw c}let d=t_(l);return n_(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 Jb(e,{force:!0}),!0}catch(l){if(oi(l))return!1;throw l}}return{claimPath:e,read:s,async claim(l){await Vb(Cc(e),{recursive:!0,mode:1023})!=null&&await qb(Cc(e),1023).catch(()=>{});let c=!1;for(let u=0;u<Xb;u+=1){let m=i(l,n());try{return await zb(e,r_(m),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:c,claim:m}}catch(f){if(f.code!=="EEXIST"){if(oi(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(Fc(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||!Fc(d,l,r.socketPath)?!1:await a()}}}function Bc(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 Hc(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 e_(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 oi(e){let r=e?.code;return r==="EACCES"||r==="EPERM"||r==="EROFS"}function Fc(e,r,t){return e.pid===r.pid&&e.start_time===r.startTime&&e.socket_path===t}function r_(e){return`${J(e,{keyedMapCollapse:!0})}
|
|
66
|
-
`}function t_(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return ue(r)}catch{return null}}}function n_(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 o_=["worker_id","slot","workspace_path","log_path"],si=class extends Error{constructor(t,n){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${n}: the facts a birth supplies are ${o_.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},s_=/\{\{([a-z_]+)\}\}/g;function i_(e,r){let t=(i,a)=>i.replace(s_,(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 si(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 qc(e,r,t){let n=i_(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 ii(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 ai(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 li(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 a_=3e5,l_=.5,ci=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 Vc(e,r){if(r.held!=null)throw new ci(r.held);let t=di(e.project_label,"a project label"),n=di(e.selector,"a selector"),o=u_(e.queue_poll,t),s=ii(e.argv,t),i=li(e.env,t),a=ai(e.log_path,t),l=di(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??a_;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 _r=class extends Error{constructor(t,n={kind:"never"}){super(d_(t,n));this.projectLabel=t;this.absence=n;this.name="RedskilledProjectUnregisteredError"}};function d_(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 Kc(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:ii(r.launch.argv,e.project_label),env:li(r.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=r.launch==null?e.log_path:ai(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 ui(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 c_(e,r){let t=Date.parse(e.renew_by);return Number.isFinite(t)?r>=t:!1}function Jc(e,r){let t=Date.parse(e.renewed_at??e.registered_at),n=s=>Number.isFinite(s)&&r-s<=e.renew_within_ms*l_;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 zc(e,r){let t=[],n=[];for(let o of e)(c_(o,r)?n:t).push(o);return{standing:t,lapsed:n}}function Ut(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||Qc(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||p_(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 u_(e,r){if(e!==void 0){if(!Qc(e))throw new Error(`redskilled needs a complete queue poll plan for project ${JSON.stringify(r)} when one is stated`);return e}}function Qc(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 p_(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(r=>typeof r=="string")}function di(e,r){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${r} to register a project, not ${JSON.stringify(e)}`);return e}var m_={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 Yc(e){return`worker-${e}`}function Xc(e){let r=m_[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 Zc(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??Zc(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 eu=[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")],g_=new Map(eu.map(e=>[e.key,e]));function ru(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 pi(e){let r=ru(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 so=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(r){let t=pi(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 tu(e){return g_.get(pi(e))??null}function nu(e){let r=tu(e);if(!r)throw new so(e);return r}function mi(e){return nu(e).surface}import{appendFile as f_,mkdir as h_,readFile as y_}from"node:fs/promises";import{dirname as k_}from"node:path";function io(e){let r=e.now??(()=>new Date().toISOString()),t=Promise.resolve();return{record(n){let o=b_(n.operation,n.cost,n.observedAt??r(),n.actor),s=ve().push(R_(o));return t=t.then(async()=>{await h_(k_(e.path),{recursive:!0}),await f_(e.path,s,"utf8")}),t},async report(n){await t;let o=gi(n.from,"report window start"),s=gi(n.to,"report window end");if(s<=o)throw new Error("GitHub attribution report window end must be after its start");let i=await __(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 b_(e,r,t,n){if(gi(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 __(e){let r;try{r=await y_(e,"utf8")}catch(s){if(v_(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(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=$e(`${i}
|
|
68
68
|
${a}
|
|
69
|
-
`)[0]}catch{n+=1,s+=1;continue}if(!
|
|
69
|
+
`)[0]}catch{n+=1,s+=1;continue}if(!D_(l)){n+=1,s+=1;continue}t.push(l),s+=1}return{observations:t,unreadable:n}}function A_(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 D_(e){return j_(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 Si(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 j_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function L_(e){return e instanceof Error&&"code"in e}var pu=as(Pi(),1);var Je=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 I_="0.0.0-development";function $_(e){return e.request!==void 0}async function uu(e,r,t,n){if(!$_(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 G_(e,r,t,n){let o=new pu.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(C_.bind(null,e,r,t),n)}async function C_(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 Je(o.data.errors[0].message,500,{request:n,response:o});return uu(e,r,s,n)}return o}function Oi(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",uu.bind(null,t,n)),e.hook.wrap("request",G_.bind(null,t,n))),n}Oi.VERSION=I_;var gu=as(Pi(),1),N_="0.0.0-development",Ai=()=>Promise.resolve();function M_(e,r,t){return e.retryLimiter.schedule(F_,e,r,t)}async function F_(e,r,t){let{pathname:n}=new URL(t.url,"http://github.test"),o=W_(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,Ai),s&&e.triggersNotification(n)&&await e.notifications.key(e.id).schedule(d,Ai),i&&await e.search.key(e.id).schedule(d,Ai);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 W_(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 U_=["/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 B_(e){let t=`^(?:${e.map(n=>n.split("/").map(o=>o.startsWith("{")?"(?:.+?)":o).join("/")).map(n=>`(?:${n})`).join("|")})[^/]*$`;return new RegExp(t,"i")}var mu=B_(U_),fu=mu.test.bind(mu),xe={},H_=function(e,r){xe.global=new e.Group({id:"octokit-global",maxConcurrent:10,...r}),xe.auth=new e.Group({id:"octokit-auth",maxConcurrent:1,...r}),xe.search=new e.Group({id:"octokit-search",maxConcurrent:1,minTime:2e3,...r}),xe.write=new e.Group({id:"octokit-write",maxConcurrent:1,minTime:1e3,...r}),xe.notifications=new e.Group({id:"octokit-notifications",maxConcurrent:1,minTime:3e3,...r})};function fo(e,r){let{enabled:t=!0,Bottleneck:n=gu.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:fu,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,29 +76,30 @@ ${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 _=f.val[f.index],
|
|
81
|
-
`+n.repeat(u)+
|
|
82
|
-
`+n.repeat(u)),c.push(f.isArray?"]":"}"),h.delete(f.val),m.pop())}return c.join("")},
|
|
79
|
+
`);let d=!1,c=()=>{if(d)return;d=!0,xe.global==null&&H_(n,a),l.global=l.global??xe.global,l.auth=l.auth??xe.auth,l.search=l.search??xe.search,l.write=l.write??xe.write,l.notifications=l.notifications??xe.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",h=>e.log.warn("Error in throttling-plugin limit handler",h)),l.retryLimiter.on("failed",async function(h,f){let[S,_,v]=f.args,{pathname:C}=new URL(v.url,"http://github.test");if(!(C.startsWith("/graphql")&&h.status!==401||h.status===403||h.status===429))return;let L=~~_.retryCount;_.retryCount=L,v.request.retryCount=L;let{wantRetry:Q,retryAfter:ee=0}=await async function(){if(/\bsecondary rate\b/i.test(h.message)){let le=Number(h.response.headers["retry-after"])||S.fallbackSecondaryRateRetryAfter;return{wantRetry:await m.trigger("secondary-limit",le,v,e,L),retryAfter:le}}if(h.response.headers!=null&&h.response.headers["x-ratelimit-remaining"]==="0"||(h.response.data?.errors??[]).some(le=>le.type==="RATE_LIMITED")){let le=new Date(~~h.response.headers["x-ratelimit-reset"]*1e3).getTime(),Ye=Math.max(Math.ceil((le-Date.now())/1e3)+1,0);return{wantRetry:await m.trigger("rate-limit",Ye,v,e,L),retryAfter:Ye}}return{}}();if(Q)return _.retryCount++,ee*S.retryAfterBaseValue})};return e.hook.wrap("request",(u,m)=>(c(),M_(l,u,m))),{}}fo.VERSION=N_;fo.triggersNotification=fu;function or(){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 ho(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)=>ho.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 hu(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 yu(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 ku=Function.bind,bu=ku.bind(ku);function _u(e,r,t){let n=bu(yu,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]=bu(hu,null).apply(null,s)})}function q_(){let e=Symbol("Singular"),r={registry:{}},t=ho.bind(null,r,e);return _u(t,r,e),t}function V_(){let e={registry:{}},r=ho.bind(null,e);return _u(r,e),r}var Ru={Singular:q_,Collection:V_};var K_="0.0.0-development",J_=`octokit-endpoint.js/${K_} ${or()}`,z_={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":J_},mediaType:{format:""}};function Q_(e){return e?Object.keys(e).reduce((r,t)=>(r[t.toLowerCase()]=e[t],r),{}):{}}function Y_(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 vu(e,r){let t=Object.assign({},e);return Object.keys(r).forEach(n=>{Y_(r[n])?n in e?t[n]=vu(e[n],r[n]):Object.assign(t,{[n]:r[n]}):Object.assign(t,{[n]:r[n]})}),t}function wu(e){for(let r in e)e[r]===void 0&&delete e[r];return e}function ji(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=Q_(t.headers),wu(t),wu(t.headers);let n=vu(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 X_(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 Z_=/\{[^{}}]+\}/g;function eR(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function rR(e){let r=e.match(Z_);return r?r.map(eR).reduce((t,n)=>t.concat(n),[]):[]}function Eu(e,r){let t={__proto__:null};for(let n of Object.keys(e))r.indexOf(n)===-1&&(t[n]=e[n]);return t}function Su(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 rt(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(r){return"%"+r.charCodeAt(0).toString(16).toUpperCase()})}function Kt(e,r,t){return r=e==="+"||e==="#"?Su(r):rt(r),t?rt(t)+"="+r:r}function et(e){return e!=null}function Di(e){return e===";"||e==="&"||e==="?"}function tR(e,r,t,n){var o=e[t],s=[];if(et(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(Kt(r,o,Di(r)?t:""));else if(n==="*")Array.isArray(o)?o.filter(et).forEach(function(i){s.push(Kt(r,i,Di(r)?t:""))}):Object.keys(o).forEach(function(i){et(o[i])&&s.push(Kt(r,o[i],i))});else{let i=[];Array.isArray(o)?o.filter(et).forEach(function(a){i.push(Kt(r,a))}):Object.keys(o).forEach(function(a){et(o[a])&&(i.push(rt(a)),i.push(Kt(r,o[a].toString())))}),Di(r)?s.push(rt(t)+"="+i.join(",")):i.length!==0&&s.push(i.join(","))}else r===";"?et(o)&&s.push(rt(t)):o===""&&(r==="&"||r==="?")?s.push(rt(t)+"="):o===""&&s.push("");return s}function nR(e){return{expand:oR.bind(null,e)}}function oR(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(tR(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 Su(s)}),e==="/"?e:e.replace(/\/$/,"")}function Tu(e){let r=e.method.toUpperCase(),t=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),n=Object.assign({},e.headers),o,s=Eu(e,["method","baseUrl","url","headers","request","mediaType"]),i=rR(t);t=nR(t).expand(s),/^http/.test(t)||(t=e.baseUrl+t);let a=Object.keys(e).filter(c=>i.includes(c)).concat("baseUrl"),l=Eu(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=X_(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 sR(e,r,t){return Tu(ji(e,r,t))}function xu(e,r){let t=ji(e,r),n=sR.bind(null,t);return Object.assign(n,{DEFAULTS:t,defaults:xu.bind(null,t),merge:ji.bind(null,t),parse:Tu})}var Pu=xu(null,z_);var Vu=as($u(),1);var fR=/^-?\d+$/,bo=/^-?\d+n+$/,sr=JSON.stringify,Gi=JSON.parse,Fu=/^-?\d+n$/,Gu=/([\[:])?"(-?\d+)n"($|\s*[,\}\]])/g,Cu=/([\[:])?("-?\d+n+)n("$|"\s*[,\}\]])/g,Ci=e=>e===void 0||typeof e=="function"||typeof e=="symbol",Ni=e=>e!==null&&typeof e=="object"&&e.constructor&&e.constructor.name==="RawJSON",hR=(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=(f,S,_)=>(_!==null&&typeof _=="object"&&typeof _.toJSON=="function"&&(_=_.toJSON(S)),typeof _=="string"&&bo.test(_)?_+"n":typeof _=="bigint"?"rawJSON"in JSON?JSON.rawJSON(_.toString()):_.toString()+"n":(o&&(_=r.call(f,S,_)),_!==null&&typeof _=="object"&&(_ instanceof Number||_ instanceof String||_ instanceof Boolean)&&(_=_.valueOf()),_)),a=i({"":e},"",e);if(Ci(a))return;let l=a===null||typeof a!="object",d=Ni(a);if(l||d)return sr(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}],h=new WeakSet([a]);for(;m.length>0;){let f=m[m.length-1];f.index===0&&(c.push(f.isArray?"[":"{"),u++);let S=!1;if(f.isArray)if(f.index<f.val.length){f.first||c.push(","),n&&c.push(`
|
|
80
|
+
`+n.repeat(u));let _=f.val[f.index],v=i(f.val,String(f.index),_);if(Ci(v))c.push("null"),f.first=!1,f.index++;else{let C=v!==null&&typeof v=="object",H=Ni(v);if(C&&!H){if(h.has(v))throw new TypeError("Converting circular structure to JSON");h.add(v),m.push({parent:f.val,key:String(f.index),val:v,isArray:Array.isArray(v),keys:Array.isArray(v)?null:Object.keys(v),index:0,first:!0}),f.first=!1,f.index++}else c.push(sr(v)),f.first=!1,f.index++}}else S=!0;else{for(;f.index<f.keys.length;){let v=f.keys[f.index++];if(s&&!s.has(v))continue;let H=f.val[v],L=i(f.val,v,H);if(Ci(L))continue;f.first||c.push(","),n?c.push(`
|
|
81
|
+
`+n.repeat(u)+sr(v)+": "):c.push(sr(v)+":");let Q=L!==null&&typeof L=="object",ee=Ni(L);if(Q&&!ee){if(h.has(L))throw new TypeError("Converting circular structure to JSON");h.add(L),m.push({parent:f.val,key:v,val:L,isArray:Array.isArray(L),keys:Array.isArray(L)?null:Object.keys(L),index:0,first:!0}),f.first=!1;break}else c.push(sr(L)),f.first=!1}f.index>=f.keys.length&&m[m.length-1]===f&&(S=!0)}S&&(u--,!f.first&&n&&c.push(`
|
|
82
|
+
`+n.repeat(u)),c.push(f.isArray?"]":"}"),h.delete(f.val),m.pop())}return c.join("")},Wu=(e,r,t)=>{try{return"rawJSON"in JSON?sr(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?sr(e,(a,l)=>typeof l=="string"&&bo.test(l)||typeof l=="bigint"?l.toString()+"n":typeof r=="function"?r(a,l):(Array.isArray(r)&&r.includes(a),l),t).replace(Gu,"$1$2$3").replace(Cu,"$1$2$3"):sr(e,r,t)}catch(n){if(n instanceof RangeError){let o=hR(e,r,t);return o===void 0?void 0:"rawJSON"in JSON?o:o.replace(Gu,"$1$2$3").replace(Cu,"$1$2$3")}throw n}},ko=new Map,yR=()=>{let e=JSON.parse.toString();if(ko.has(e))return ko.get(e);try{let r=JSON.parse("1",(t,n,o)=>!!o?.source&&o.source==="1");return ko.set(e,r),r}catch{return ko.set(e,!1),!1}},kR=(e,r,t,n)=>typeof r=="string"&&Fu.test(r)?BigInt(r.slice(0,-1)):typeof r=="string"&&bo.test(r)?r.slice(0,-1):typeof n=="function"?n(e,r,t):r,bR=(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&&fR.test(o.source);return a&&l?BigInt(o.source):typeof r=="function"?r(t,n,o):n}),Uu=Number.MAX_SAFE_INTEGER.toString(),Nu=Uu.length,_R=/"(?:\\.|[^"])*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g,RR=/^"-?\d+n+"$/,wR=(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"&&(Fu.test(a)?a=BigInt(a.slice(0,-1)):bo.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[""]},Mu=e=>e.replace(_R,(r,t,n,o)=>{let s=r[0]==='"';if(s&&RR.test(r))return r.substring(0,r.length-1)+'n"';let a=n||o,l=t&&(t.length<Nu||t.length===Nu&&t<=Uu);return s||a||l?r:'"'+r+'n"'}),Bu=(e,r)=>{if(!e)return Gi(e,r);try{if(yR())return bR(e,r);let t=Mu(e);return Gi(t,(n,o,s)=>kR(n,o,s,r))}catch(t){if(t instanceof RangeError){let n=Mu(e),o=Gi(n);return wR(o,r)}throw t}};var ER="10.0.13",vR={headers:{"user-agent":`octokit-request.js/${ER} ${or()}`}};function SR(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 Hu=()=>"";async function qu(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=SR(e.body)||Array.isArray(e.body)?Wu(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 h=new Je(m,500,{request:e});throw h.cause=u,h}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 Je(i.statusText,a,{response:c,request:e})}if(a===304)throw c.data=await Mi(i),new Je("Not modified",a,{response:c,request:e});if(a>=400)throw c.data=await Mi(i),new Je(xR(c.data),a,{response:c,request:e});return c.data=n?await Mi(i):i.body,c}async function Mi(e){let r=e.headers.get("content-type");if(!r)return e.text().catch(Hu);let t=(0,Vu.parse)(r);if(TR(t)){let n="";try{return n=await e.text(),Bu(n)}catch{return n}}else return t.type.startsWith("text/")||t.parameters.charset?.toLowerCase()==="utf-8"&&t.type!=="application/octet-stream"?e.text().catch(Hu):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function TR(e){return e.type==="application/json"||e.type==="application/scim+json"}function xR(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 Fi(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 qu(t.parse(i));let a=(l,d)=>qu(t.parse(t.merge(l,d)));return Object.assign(a,{endpoint:t,defaults:Fi.bind(null,t)}),i.request.hook(a,i)},{endpoint:t,defaults:Fi.bind(null,t)})}var Jt=Fi(Pu,vR);var PR="0.0.0-development";function OR(e){return`Request failed due to following response errors:
|
|
83
83
|
`+e.errors.map(r=>` - ${r.message}`).join(`
|
|
84
|
-
`)}var RR=class extends Error{constructor(e,r,t){super(_R(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},wR=["method","baseUrl","url","headers","request","query","mediaType","operationName"],ER=["query","method","url"],Fu=/\/api\/v3\/?$/;function vR(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(ER.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)=>wR.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 Fu.test(s)&&(o.url=s.replace(Fu,"/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 RR(o,a,i.data)}return i.data.data})}function Ai(e,r){let t=e.defaults(r);return Object.assign((o,s)=>vR(t,o,s),{defaults:Ai.bind(null,t),endpoint:t.endpoint})}var XA=Ai(Ht,{headers:{"user-agent":`octokit-graphql.js/${bR} ${tr()}`},method:"POST",url:"/graphql"});function Wu(e){return Ai(e,{method:"POST",url:"/graphql"})}var Di="(?:[a-zA-Z0-9_-]+)",Uu="\\.",Bu=new RegExp(`^${Di}${Uu}${Di}${Uu}${Di}$`),SR=Bu.test.bind(Bu);async function TR(e){let r=SR(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 xR(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function PR(e,r,t,n){let o=r.endpoint.merge(t,n);return o.headers.authorization=xR(e),r(o)}var Hu=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(TR.bind(null,r),{hook:PR.bind(null,r)})};var ji="7.0.7";var qu=()=>{},OR=console.warn.bind(console),AR=console.error.bind(console);function DR(e={}){return typeof e.debug!="function"&&(e.debug=qu),typeof e.info!="function"&&(e.info=qu),typeof e.warn!="function"&&(e.warn=OR),typeof e.error!="function"&&(e.error=AR),e}var Vu=`octokit-core.js/${ji} ${tr()}`,mo=class{static VERSION=ji;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 gu.Collection,n={baseUrl:Ht.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} ${Vu}`:Vu,r.baseUrl&&(n.baseUrl=r.baseUrl),r.previews&&(n.mediaType.previews=r.previews),r.timeZone&&(n.headers["time-zone"]=r.timeZone),this.request=Ht.defaults(n),this.graphql=Wu(this.request).defaults(n),this.log=DR(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=Hu(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 Ku="6.0.0";function Li(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})})}Li.VERSION=Ku;var jR="0.0.0-development";function LR(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 Ii(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=LR(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 Ju(e,r,t,n){return typeof t=="function"&&(n=t,t=void 0),zu(e,[],Ii(e,r,t)[Symbol.asyncIterator](),n)}function zu(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:zu(e,r,t,n)})}var fD=Object.assign(Ju,{iterator:Ii});function Gi(e){return{paginate:Object.assign(Ju.bind(null,e),{iterator:Ii.bind(null,e)})}}Gi.VERSION=jR;var $i="17.0.0";var IR={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"]}},Qu=IR;var Rr=new Map;for(let[e,r]of Object.entries(Qu))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);Rr.has(e)||Rr.set(e,new Map),Rr.get(e).set(t,{scope:e,methodName:t,endpointDefaults:d,decorations:i})}var GR={has({scope:e},r){return Rr.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[...Rr.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=Rr.get(r).get(n);if(!o)return;let{endpointDefaults:s,decorations:i}=o;return i?t[n]=$R(e,r,n,s,i):t[n]=e.request.defaults(s),t[n]}};function Ci(e){let r={};for(let t of Rr.keys())r[t]=new Proxy({octokit:e,scope:t,cache:{}},GR);return r}function $R(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 CR(e){return{rest:Ci(e)}}CR.VERSION=$i;function Ni(e){let r=Ci(e);return{...r,rest:r}}Ni.VERSION=$i;var Yu="22.0.1";var Xu=mo.plugin(Li,Ni,Gi).defaults({userAgent:`octokit-rest.js/${Yu}`});var NR=Xu.plugin(ki,ao);function Zu(){let e=new Map;return{get:r=>e.get(r),set:(r,t)=>e.set(r,t)}}var Vt=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 Mi(e){let r=e.etags??Zu(),t=new NR({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=qt(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=fo(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(go(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=ep(l),c={...s.headers,...d},u=fo(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 go(l)===401?new Vt({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,!MR(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 go(i)===401?new Vt({cause:i}):i}}}}function MR(e){let r=fo(e,"link");return r!==void 0&&/(?:^|,)\s*<[^>]+>;\s*rel="next"(?:\s*;|\s*(?:,|$))/i.test(r)}function Kt(e){let r=go(e),t=ep(e);return r===429||r===403&&fo(t,"x-ratelimit-remaining")==="0"||e instanceof Error&&/secondary rate|rate limit/i.test(e.message)}function go(e){if(qt(e))return typeof e.status=="number"?e.status:void 0}function ep(e){return!qt(e)||!qt(e.response)||!qt(e.response.headers)?{}:e.response.headers}function fo(e,r){let t=e[r]??e[r.toLowerCase()];return typeof t=="string"?t:typeof t=="number"?String(t):void 0}function qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var tp="rate_limit",np={rest:"core",graphql:"graphql",search:"search"},qe=["rest","graphql","search"];function bo(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 Wi=15e3,Yr=.15,yo=[{at_or_below_fraction:0,every_ms:Wi,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:Yr,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"}],Fi=2;function op(e,r){let t=rp(e),n=rp(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let a of qe){let l=np[a],d=n[l],c=UR(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 Ui(e){try{let r=await e.transport();return op(r,{askedAt:e.now})}catch(r){let t=r instanceof Error?r.message:String(r);return{...bo(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function Bi(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 _o(e,r){let t=Bi(e);if(t==null)return ko(Yr).every_ms;let n=ko(t.fraction);if(t.remaining>0)return n.every_ms;let o=ip(r.now,t.reset_at);return o==null?n.every_ms:Math.max(Wi,Math.min(n.every_ms,o))}function Hi(e,r=Yr){return Math.ceil(e.limit*r)}function sp(e,r,t=Yr){let n=e.pools[r];return n==null?"unknown":n.remaining<=0?"spent":n.remaining<Hi(n,t)?"reserved":"open"}function qi(e){let r=e.reservedFraction??Yr,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:ko(r).every_ms*Fi,stale:!1,posture:"unknown",reserved_fraction:r,next_poll_ms:ko(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=_o(t,{now:e.now}),o=e.stalenessMs??n*Fi,s=ip(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=WR(t,r),d=Bi(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`:FR(l,d,t,r)}}function Vi(e){if(!Ji(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 FR(e,r,t,n){if(r==null)return t.detail;let o=Hi(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 WR(e,r){let t="unknown";for(let n of qe){if(e.pools[n]==null)continue;let o=sp(e,n,r);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function ko(e){for(let r of yo)if(e<=r.at_or_below_fraction)return r;return yo[yo.length-1]}function UR(e,r,t){if(!Ji(t))return null;let n=ho(t.limit),o=ho(t.remaining),s=ho(t.used),i=ho(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 Ki(e){let r=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let n=await t(`${r}/${tp}`,{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 ip(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 ho(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function rp(e){return Ji(e)?e:{}}function Ji(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pp(e){return{generated_at:e.now,hour:ap("hour",36e5,e),day:ap("day",864e5,e)}}function zt(e,r,t){let n=Jt(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(a=>{let l=Jt(r(a));return l==null?!1:n==null||n-l<=o});return i.length<=s?i:i.slice(i.length-s)}function ap(e,r,t){let n=Jt(t.now),o=n==null?null:n-r,s=e==="hour"?"1h":"24h",i=t.observations.map(u=>({observation:u,at:Jt(u.observed_at)})).filter(u=>u.at!=null&&cp(u.at,o,n)).sort((u,m)=>u.at-m.at),a=t.outcomes.map(u=>Jt(u.ts)).filter(u=>u!=null&&cp(u,o,n)),l=lp(i,u=>u.tokens,"tokens",s),d=lp(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:BR(a.length,r,s),runner_share:dp("runner",i,u=>u.runner,s),model_share:dp("model",i,u=>u.model,s),unavailable:c}}function lp(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 BR(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 dp(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 cp(e,r,t){return r==null||t==null?!0:e>=r&&e<=t}function Jt(e){let r=Date.parse(e);return Number.isFinite(r)?r:null}function mp(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.generated_at=="string"&&up(r.hour)&&up(r.day)}function up(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"&&zi(r.tokens_per_min)&&zi(r.tools_per_min)&&zi(r.issues_per_hour)&&Array.isArray(r.unavailable)}function zi(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 HR}from"node:child_process";import{existsSync as qR,readFileSync as Ro,readdirSync as VR}from"node:fs";import{dirname as KR,join as wr}from"node:path";function Qt(e){let r=Mt(e),t=[["MemoryMax",r.memory_max],["MemoryHigh",r.memory_high]];for(let[n,o]of t){if(o==null)continue;let s=Jr(o);return s==null?null:{name:n,declared:o,bytes:s}}return null}function gp(e){let r=[],t=[];for(let n of e.workers){let o=Qt(n);if(o==null){t.push({worker_id:n.worker_id,reason:(Mt(n).memory_max??Mt(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(JR(n,o,s))}}return{terminations:r,unenforceable:t}}function JR(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 zR=4096;function fp(e,r={}){let t=r.platform??process.platform,n={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return n;let o={},s={},i={},a=YR(e,t,r);for(let[u,m]of a){let h=ew(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=nw(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],v=new Set;for(;f.length>0;){let _=f.pop();if(v.has(_))continue;v.add(_);let S=d.get(_);if(S){m+=S.rssBytes,h+=S.cpuSeconds;for(let j of c.get(_)??[])f.push(j)}}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 QR="/sys/fs/cgroup";function YR(e,r,t){let n=new Map;if(!(t.cgroupRoot!=null)&&r!=="linux")return n;let s=t.cgroupRoot??QR,i=e.filter(l=>l.unit!=null&&l.unit!=="");if(i.length===0)return n;let a=XR(s,t);for(let l of i)for(let d of a){let c=wr(d,l.unit);if(qR(wr(c,"memory.current"))){n.set(l.worker_id,c);break}}return n}function XR(e,r){let t=r.selfCgroupPath??ZR(),n=[],o=a=>{n.includes(a)||n.push(a)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(wr(e,s));let a=KR(s);if(a===s)break;s=a}o(e);let i=r.uid??process.getuid?.();return i!=null&&o(wr(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),n}function ZR(){try{for(let e of Ro("/proc/self/cgroup","utf8").split(`
|
|
85
|
-
`))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function
|
|
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
|
|
87
|
-
`)){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=
|
|
88
|
-
`),aliases:s,closed_since:o}}function fw(e,r,t){let n=Xr(r),o=Xr(n.data),s=Array.isArray(n.errors)?n.errors.map(Xr):[],i=Rw(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=>bp(f.path,l)||bp(f.path,d));if(Yt(m)){let f=_p(m.open_pull_requests),v=_p(m.open_issues),_=ww(o[d]);if(f!=null&&v!=null&&_!=null)return{project_label:c.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:f,open_issues:v,recently_closed:_},detail:`counted ${u} for project ${JSON.stringify(c.project_label)}`}}return i.exhausted||xp(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: ${wo(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 hw(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 wp(e){if(e.projects.length===0)return hw(e.now);if(Xi(e.projects,e.hostTokenRef),e.transport.conditionalList)return await kw(e);let r=Rp(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(r.query);return fw(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 yw={key:"redskilled repository activity poll",budget:"rest"};async function kw(e){Tp(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=Rp(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 v=await o({cacheKey:`activity:${d}:${m}:${JSON.stringify(f)}`,route:h,parameters:f,operation:yw});i+=v.requestCount;let _=m==="open-prs"?v.data:v.data.filter(S=>!Yt(S.pull_request));u.push(m==="recently-closed"?_.filter(S=>wo(S.closed_at)>=n.closed_since).length:_.length),a=yp(a,_w(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 h=Kt(m);a=yp(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 Ep(e){let r=e.stalenessMs??mw,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 vp(e){if(!Yt(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)&&Yt(r.rate_limit)&&Array.isArray(r.projects)&&typeof r.reason=="string"}function Sp(e){let r=e.endpoint==null?void 0:bw(e.endpoint),t=Mi({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 bw(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 _w(e){let r=kp(e,"x-ratelimit-remaining"),t=kp(e,"x-ratelimit-reset");return{remaining:r,reset_at:t==null?null:new Date(t*1e3).toISOString(),exhausted:r===0,point_cost:null}}function yp(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 kp(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 Tp(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>hp)throw new Error(`redskilled activity fetch spans at most ${hp} 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 Rw(e,r){let t=Xr(e),n=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=r.some(xp),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 xp(e){if(e==null)return!1;let r=wo(e.type),t=wo(e.message);return r==="RATE_LIMITED"||/rate limit/i.test(t)}function bp(e,r){return Array.isArray(e)&&e.includes(r)}function _p(e){let r=Xr(e);return Number.isInteger(r.totalCount)?r.totalCount:null}function ww(e){let r=Xr(e);return Number.isInteger(r.issueCount)?r.issueCount:null}function Xr(e){return Yt(e)?e:{}}function Yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wo(e){return typeof e=="string"?e:""}var Ew=3e4,vw=2,Sw=3,Tw=4,xw=["logs","vitals","display"];function Pp(e,r){if(r===void 0)return e;let t=xw.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:Pw,budget:{...o.budget,used_bytes:null,used_fraction:null}},...n("logs")?{}:{log:Ow},...n("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var Pw={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},Ow={last_line:null,published_at:null,source:null};function Op(e){let r=e.stalenessMs??Ew,t=or(e.now),n=e.sampledAt==null?null:or(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=>Lw(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=ro(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:Cw({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:$w(a),known_projects:Gw(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:qi({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:Ep({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:Aw(e.deaths,e.recentDeathLimit??Tw)},engine:jw(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function Aw(e,r){let t=[...e].sort((s,i)=>(or(i.ts)??0)-(or(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=Dw(t);return{count:t.length,recent:n,latest:n[0]??null,reaped_at:n[0]?.ts??null,...o==null?{}:{boot_loop:o}}}function Dw(e){let r=new Map;for(let n of e){if(n.sender_class!=="boot-refused"||n.uptime_s==null||n.uptime_s>vw||n.project_label==null||n.project_label===""||or(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>=Sw).map(([n,o])=>{let s=o[0],i=or(s.ts),a=Math.min(...o.map(d=>or(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 jw(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 Lw(e,r){let t=r.rss[e.worker_id],n=typeof t=="number"&&Number.isFinite(t)?t:null,o=Qt(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=or(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:Iw(r.log),display:r.display?.display??null,display_published_at:r.display?.published_at??null}}function Iw(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 Gw(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 $w(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 Cw(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 or(e){let r=Date.parse(e);return Number.isFinite(r)?r:null}function Zi(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(Nw))&&(r.stopped_projects===void 0||Array.isArray(r.stopped_projects)&&r.stopped_projects.every(Mw))&&(r.orphaned_projects===void 0||Array.isArray(r.orphaned_projects)&&r.orphaned_projects.every(s=>typeof s=="string"))&&(r.repository_activity===void 0||vp(r.repository_activity))&&(r.github_balance===void 0||Vi(r.github_balance))&&(r.deaths===void 0||Fw(r.deaths))&&(r.engine===void 0||Ww(r.engine))&&(r.metrics===void 0||mp(r.metrics))}function Nw(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 Mw(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 Fw(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 Ww(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 Ap={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 ea(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 ae=e=>`\x1B[${e}m`,Uw=ae("48;2;114;47;55"),Bw=ae("48;2;88;36;42"),Hw=ae("38;2;255;255;255"),qw=ae("38;2;201;150;158"),ra=ae("38;2;255;214;214"),ta=ae("39"),Xt=ae("38;2;224;138;148"),na=ae("38;2;240;110;120"),oa=ae("38;2;255;214;214"),sa=ae("38;2;146;84;94"),ia=ae("38;2;255;95;95"),aa=ae("49"),Zr=ae("0"),la=ae("1"),da=ae("22");var Vw=/\x1b\[[0-9;]*m/g,Kw=/(\x1b\[[0-9;]*m)/,Jw=/^\x1b\[[0-9;]*m$/;function Dp(e){return e.replace(Vw,"")}function zw(e){return e.slice(2,-1).split(";").every(t=>t===""||Number(t)===0)}function Te(e){return[...Dp(e)].length}function me(e,r){if(r<=0)return"";if(Te(e)<=r)return e;if(r===1)return"\u2026";let t=r-1,n=0,o=!1,s="";for(let i of e.split(Kw))if(i!==""){if(Jw.test(i)){s+=i,o=!zw(i);continue}for(let a of i){if(n===t)return`${s}\u2026${o?Zr:""}`;s+=a,n+=1}}return`${s}\u2026${o?Zr:""}`}function Zt(e,r){return e+" ".repeat(Math.max(0,r-Te(e)))}function ca(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 xe(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 en(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 rn(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return en(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 Ve(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 et(e){if(e==null)return null;let r=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return r===""?null:r}var tn="!unregistered",ua="!lapsed",nn="\u21E1",Ke="\u2020",rt="\u25D0",tt="\u25EF",pa="\u21B3",ma="redskilled unreachable \u2014 Worker state unknown";function nt(e,r){return r.mode==="global"?e.workers:r.project==null?[]:e.workers.filter(t=>t.project_label===r.project)}function Eo(e,r){return r.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===r.project)}function on(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 ga(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 sr=["wid","run","org","iss","bar","phase","elapsed","eta","hb","loc","tks","ctx","tls","rsn","txt"],$e={mode:"local",project:null,maxWidth:200,maxRows:16},Qw=" ",jp="\u2588",Yw="\u25B6",Xw="\u2717",Zw="\u2591",eE=new Set(["gate","push-pr","merge","cascade"]),rE=new Set(["requeue"]);function ot(e,r=$e){let t=on(e,r.project),n=nt(e,r),o=n.slice(0,Math.max(0,Math.floor(r.maxRows))),s=o.map(u=>fa(u,r,e.generated_at)),i=cE(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(uE(s[m],i),r.maxWidth)})),l=nE(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(...iE(e,r)),c.push(...sE(e,r)),{version:1,generated_at:e.generated_at,mode:r.mode,project:r.project,columns:sr,header:l,rows:a,lines:c,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function fa(e,r,t){let n=e.display??Ap,o=[n.runner,n.model==null?null:ca(n.model),n.effort].filter(a=>!!a).join(" "),s=n.phase!=null&&eE.has(n.phase),i=s||n.origin!=null&&rE.has(n.origin);return{wid:r.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:o===""?"":`run=${o}`,org:s?"org=landing":n.origin==null?"":`org=${n.origin}`,iss:n.issue==null?"":`iss=${n.issue}`,bar:Lp(n),phase:[n.phase,n.step].filter(a=>!!a).join("\xB7"),elapsed:Ve(ea(e,t)),eta:n.eta==null?"":`eta=${Ve(n.eta*1e3)}`,hb:tE(n,t)??`hb=${n.heartbeat??"?"}`,loc:i?"":dE(n.added,n.removed),tks:i||n.tokens==null?"":`tks=${en(n.tokens)}`,ctx:n.context==null?"":`ctx=${en(n.context)}`,tls:i||n.tools==null?"":`tls=${n.tools}`,rsn:i||n.reasoning==null?"":`rsn=${n.reasoning}`,txt:i||n.text==null?"":`txt=${n.text}`}}function tE(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} ${Ve(Math.max(0,n-t))}`}function Lp(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 jp.repeat(Math.floor(r));let o=e.failed?Xw:Yw;return`${jp.repeat(n)}${o}${Zw.repeat(Math.floor(r)-n-1)}`}function nE(e,r,t,n){let o=(e.repository_activity?.projects??[]).find(j=>j.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=lE(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=[`\xBB ${l??"host"} v${c}${d!=null&&d.current===!1?nn:""}`];(n==="unregistered"||n==="name-only")&&h.push(tn),n==="lapsed"&&h.push(ua),a!=null&&h.push(a),h.push(`wrk=${t.length}/${e.host.worker_count}`);let f=i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`;h.push(`${f} reserve=${i.interactive_reservation} interactive`),h.push(aE(i)),s.open_pull_requests!=null&&h.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&h.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&h.push(`iss=${s.open_issues}`),s.stale&&h.push("!counts stale");let v=m==null?null:Ip(m.hour);if(v!=null&&h.push(v),u!=null&&u.count>0&&u.latest!=null){let j=u.boot_loop,B=et(j?.latest_refusal);h.push(j==null?`${Ke}${u.count} ${u.latest.sender_class}`:`${Ke}${u.count} boot-refused \xD7${j.count} in ${oE(j.span_ms)}`+(B==null?"":` \u2014 ${B}`))}if(e.staleness.stale){let j=e.staleness.age_ms;h.push(j==null?"!unmeasured":`!stale ${Math.round(j/1e3)}s`)}let _=h.join(" \xB7 "),S=v!=null&&Te(_)>r.maxWidth?h.filter(j=>j!==v).join(" \xB7 "):_;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(S,r.maxWidth)}}function oE(e){return Ve(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function Ip(e){let r=[];e.tokens_per_min.value!=null&&r.push(`tk/m=${rn(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&r.push(`tl/m=${rn(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&r.push(`iss/h=${rn(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 sE(e,r){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let n=t.posture==="spent"?tt:rt,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 iE(e,r){let t=e.deaths;if(t==null||t.count<=0)return[];let n=t.recent.map(s=>me(`${Ke} ${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 aE(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${xe(e.memory_used_bytes)}`;let r=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${xe(e.memory_used_bytes)}/${xe(e.memory_ceiling_bytes)}${r}`}function lE(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 dE(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 cE(e){let r=Object.fromEntries(sr.map(t=>[t,0]));for(let t of e)for(let n of sr)r[n]=Math.max(r[n],Te(t[n]));return r}function uE(e,r){return sr.filter(n=>r[n]>0).map(n=>Zt(e[n],r[n])).join(Qw).replace(/\s+$/,"")}function ya(e){return Object.freeze({none:!0,reason:e})}function sn(){return{tool:"project_start",args:{runner:"claude",target:1},why:"register this project with the host so its queue can drain"}}function ha(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=>ha(n,r)));let t={};for(let[n,o]of Object.entries(e))t[n]=ha(o,r);return Object.freeze(t)}finally{r.delete(e)}}function pE(e){let r=ha(e.args,new Set);return Object.freeze({tool:e.tool,args:r,why:e.why})}function Er(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=pE(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 vr(e,r=U){let t=on(e,r.project),n=nt(e,r),o=Eo(e,r),s=kE(e,r.project,t),i=gE(e,r,n,t,s.prose),a=ga({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:vE(i,mE(h,o),r.separator);if(l={detail:h,line:f},h==="workers"||Te(f)<=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((h,f)=>{let v=r.verbose?wE(h,r):null;return v==null?[c.lines[f]]:[c.lines[f],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 _a(e){let r=e.options??U,t=me(ma,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 mE(e,r){return e==="projects"?r.map(EE):[]}function gE(e,r,t,n,o){let s=[],i=n!=="matched"&&n!=="name-only";r.mode==="global"?(s.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),s.push(ba(e,r))):n==="matched"?(s.push(`${r.project} ${t.length}w`),s.push(ba(e,r)),t.length===0&&s.push("idle")):n==="name-only"?(s.push(`${r.project} ${t.length}w`),s.push(ba(e,r)),s.push(tn)):s.push(o),s.push(Gp(e));let a=fE(e);a!=null&&s.push(a);let l=hE(e);l!=null&&s.push(l),e.staleness.stale&&s.push($p(e));let d=s.join(" ");return!i||Te(d)<=r.maxWidth||a==null&&l==null?d:[a,l,o,Gp(e),e.staleness.stale?$p(e):null].filter(c=>c!=null).join(" ")}function Gp(e){let r=e.engine,t=r?.running_version??e.daemon.daemon_version;return r==null||r.current!==!1?`v${t}`:`v${t}${nn}`}function fE(e){let r=e.github_balance;return r==null?null:r.posture==="spent"?`${tt} quota spent`:r.posture==="reserved"?`${rt} quota band`:null}function hE(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=et(t.latest_refusal);return`${Ke}${r.count} boot-refused \xD7${t.count} in ${yE(t.span_ms)}`+(n==null?"":` \u2014 ${n}`)}return`${Ke}${r.count} ${r.latest.sender_class}`}function yE(e){return Ve(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function kE(e,r,t){if(t==="unregistered")return Er({state:`project unknown \u2014 ${r} was never registered on this host`,repair:sn()});if(t==="orphaned")return Er({state:`project unknown \u2014 ${r} is registered on a daemon this socket does not reach`,repair:ya("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 Er({state:`project unknown \u2014 ${r} was stopped${n==null?"":` at ${ka(n.at)}`}`,repair:sn()})}if(t==="lapsed"){let n=e.lapsed_projects?.find(o=>o.project_label===r);if(n!=null){let o=n.registered_at==null?"":` (registered ${ka(n.registered_at)})`;return Er({state:`project unknown \u2014 ${r} lapsed at ${ka(n.at)}${o}`,repair:sn()})}return Er({state:`project unknown \u2014 ${r} lapsed`,repair:sn()})}return t==="unresolved"?Er({state:"project unknown \u2014 this directory resolved to no project",repair:ya("the directory must resolve to a project before registration args can be safe")}):{prose:""}}function ka(e){return/^\d{4}-\d{2}-\d{2}T(\d{2}:\d{2}:\d{2})/.exec(e)?.[1]??e}function ba(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?`${xe(t)}/${xe(n)}`:xe(t)}function $p(e){let r=e.staleness.age_ms;return r==null?"!unmeasured":`!stale ${Math.round(r/1e3)}s`}function bE(e,r,t,n){let o=t.map(s=>RE(s,Zt(e[s],r[s])));return me(`${aa}${Xt}${o.join(" ")}${Zr}`,n)}function _E(e,r,t){let n=e.map(a=>fa(a,r,t)),o=sr.filter(a=>n.some(l=>Te(l[a])>0)),s=[...o],i=Cp(n,s);for(;s.length>1&&Np(i,s)>r.maxWidth;)s.pop(),i=Cp(n,s);return{lines:n.map(a=>bE(a,i,s,r.maxWidth)),degraded:s.length<o.length||Np(i,s)>r.maxWidth}}function Cp(e,r){let t=Object.fromEntries(sr.map(n=>[n,0]));for(let n of e)for(let o of r)t[o]=Math.max(t[o],Te(n[o]));return t}function Np(e,r){return r.reduce((t,n)=>t+e[n],0)+Math.max(0,r.length-1)*2}function RE(e,r){if(e==="wid")return`${la}${r}${da}`;if(e==="bar")return r.replace(/█+/g,n=>`${na}${n}`).replace("\u25B6",`${oa}\u25B6`).replace("\u2717",`${ia}\u2717`).replace(/░+/g,n=>`${sa}${n}`)+Xt;let t=r.indexOf("=");return t>0?`${ra}${r.slice(0,t+1)}${ta}${r.slice(t+1)}${Xt}`:r}function wE(e,r){let t=et(e.log.last_line);return t==null?null:me(` ${pa} ${Ra(e,r.mode)}: ${t}`,r.maxWidth)}function Ra(e,r){return r==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function EE(e){return`${e.project_label} ${e.worker_count}w ${xe(e.observed_rss_bytes)}`}function vE(e,r,t){return[e,...r].join(t)}var vo=1;async function an(e,r){return await Jn(e,r,"redskilled daemon")}function Fp(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:vo,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:PE(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:pc(r,{hostCeilingBytes:e.ceiling?.memory_bytes??e.hostCeilingBytes??null}),upgrade:OE(e)}}function PE(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:Jc(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 OE(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 Wp(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||IE(r.ceiling))&&Array.isArray(r.workers)&&Array.isArray(r.projects)&&mc(r.budget_accounting)&&(r.scope===void 0||Hc(r.scope))&&(r.registrations===void 0||Array.isArray(r.registrations)&&r.registrations.every(Ut))&&(r.demand===void 0||Ac(r.demand))&&(r.lapsed_registrations===void 0||Array.isArray(r.lapsed_registrations)&&r.lapsed_registrations.every(DE))&&(r.stopped_registrations===void 0||Array.isArray(r.stopped_registrations)&&r.stopped_registrations.every(jE))&&(r.orphaned_registrations===void 0||Array.isArray(r.orphaned_registrations)&&r.orphaned_registrations.every(LE))&&(r.birth_latches===void 0||Array.isArray(r.birth_latches)&&r.birth_latches.every(AE))&&(r.upgrade===void 0||GE(r.upgrade))}function AE(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 DE(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 jE(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 LE(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 IE(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 GE(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||$E(r.major_hold))}function $E(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 CE}from"node:crypto";import{mkdir as NE,readFile as ME,rename as FE,writeFile as WE}from"node:fs/promises";import{dirname as UE}from"node:path";function Up(e){let r=Promise.resolve(),t=null;async function n(){await r;let s;try{s=await ME(e,"utf8")}catch(a){if(a.code==="ENOENT")return[];throw a}let i=BE(s);return HE(i)?i.registrations:[]}async function o(s){await NE(UE(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.${CE()}.tmp`,a={version:1,registrations:[...s]};await WE(i,`${J(a,{keyedMapCollapse:!0})}
|
|
89
|
-
`,{encoding:"utf8",mode:384}),await
|
|
90
|
-
`),e.command,...e.args]}function
|
|
91
|
-
`).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function
|
|
92
|
-
`),aliases:n}}function hm(e,r){let t=dn(r),n=dn(t.data),o=Array.isArray(t.errors)?t.errors.map(dn):[],s=mv(n.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=fv(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=>gv(u.path,a));return s.exhausted||bm(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: ${Pa(c?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function dv(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:cn,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function ym(e,r,t){return{version:1,fetched_at:r,request_count:0,project_count:e.length,batch_size:cn,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 km(e){if(e.projects.length===0)return dv(e.now);if(e.transport.conditionalList)return await uv(e);let r=e.batchSize??cn,t=lv(e.projects,r),n=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=fm(s,{batchSize:r});try{let a=await e.transport(i.query),l=hm(i,a);n.push(...l.projects),o=ln(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=ln(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 cv={key:"redskilled queue poll",budget:"rest"};async function uv(e){Aa(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=fm([s],{batchSize:1}),d=hm(l,await e.transport(l.query));o+=1,t.push(...d.projects),n=ln(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:cv});o+=i.requestCount;let a=i.data.filter(l=>!_m(l.pull_request)).length;n=ln(n,pv(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=Kt(i);n=ln(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 Aa(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 ln(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 pv(e){let r=gm(e,"x-ratelimit-remaining"),t=gm(e,"x-ratelimit-reset");return{remaining:r,reset_at:t==null?null:new Date(t*1e3).toISOString(),exhausted:r===0}}function gm(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 mv(e,r){let t=dn(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(bm)||n===0}}function bm(e){return e==null?!1:Pa(e.type)==="RATE_LIMITED"||/rate limit/i.test(Pa(e.message))}function gv(e,r){return Array.isArray(e)&&e.includes(r)}function fv(e){let r=dn(e);return Number.isInteger(r.issueCount)?r.issueCount:null}function dn(e){return _m(e)?e:{}}function _m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pa(e){return typeof e=="string"?e:""}function Rm(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(hv,Math.max(r,i))}let o=n.remaining;return o==null?r:o<=yv?Math.max(r,3e4):o<=kv?Math.max(r,2e4):r}var hv=1e5,yv=250,kv=1e3;var bv={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},_v=["runner","model","effort","origin","issue","phase","step","heartbeat","wait_kind","wait_subject","wait_started_at","wait_deadline","wait_escalation","started_at"],Rv=["phase_index","phase_total","wait_pid","context","eta","added","removed","tokens","tools","reasoning","text"];function wm(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let r=e,t={...bv};for(let n of _v){let o=r[n];t[n]=typeof o=="string"&&o.trim()!==""?o:null}for(let n of Rv){let o=r[n];t[n]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=r.failed===!0,t}import{randomInt as Sv}from"node:crypto";import{spawn as Tv}from"node:child_process";import{closeSync as xv,mkdirSync as Pv,openSync as Ov}from"node:fs";import{dirname as Av}from"node:path";import{delimiter as Em,dirname as wv}from"node:path";function Ev(e,r=Em){return(e??"").split(r).map(t=>t.trim()).filter(t=>t!=="")}function vv(e=process.execPath){let r=(e??"").trim();if(r==="")return null;let t=wv(r);return t===""||t==="."?null:t}function vm(e,r=process.execPath,t=Em){let n=Ev(e,t),o=vv(r);return o==null?n.join(t):[o,...n.filter(s=>s!==o)].join(t)}var it=class extends Error{constructor(r){super(r),this.name="RedskilledWorkerSpecError"}},Po=class extends Error{constructor(t,n){super(t);this.admission=n;this.name="RedskilledAdmissionError"}},Da="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",Tm=4,Dv=Da.length**Tm;function ja(e,r=Sv){let t=new Set(e);for(let n=0;n<Dv;n+=1){let o="h";for(let s=0;s<Tm;s+=1)o+=Da[r(Da.length)];if(!t.has(o))return o}throw new it("redskilled exhausted the host Worker id space")}function jv(e){if(e==null||e.trim()==="")return null;try{return Pv(Av(e),{recursive:!0}),Ov(e,"a")}catch{return null}}function Lv(e){try{xv(e)}catch{}}function Iv(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 it(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new it("redskilled worker spec args must be an array")}function Gv(e){if(e==null)throw new Po("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new Po(e.reason,e)}function xm(e){let{spec:r,admission:t}=e;Gv(t),Iv(r);let n=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(r.worker_id??e.workerId)?.trim()||ja(e.liveWorkerIds??[]),i=e.probes??em(n),a=e.openLog===!1?null:jv(r.log_path),l={...r.env??{},PATH:vm(r.env?.PATH??n.PATH,e.execPath??process.execPath)},d=nm({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??rm(n),probes:i,pipeOutput:a!==null}),u=(e.spawnFn??Tv)(d.command,d.args,{...d.cwd!=null?{cwd:d.cwd}:{},detached:!0,stdio:a===null?"ignore":["ignore",a,a],env:d.backend==="transient-unit"?{...n}:{...n,...l,...d.environment}});if(a!==null&&Lv(a),u.pid==null)throw u.once("error",()=>{}),new it(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${s}`);let m=d.job!=null?$v(d,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(_,S)=>{try{m?.job?.close()}catch{}e.onExit?.(s,_,S)}),u.unref();let h=d.job!=null?m?.job!=null:d.isolated,f=[d.warning,m?.warning,d.budgetWarning].filter(_=>_!=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:h,...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:f},admission:t,warnings:f,plan:d,child:u,...m?.job!=null?{job:m.job}:{}}}function $v(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: ${Sm(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)}: ${Sm(i)}. ${o}`}}return{job:s}}function Sm(e){return e instanceof Error?e.message:String(e)}import{open as Cv,stat as Nv}from"node:fs/promises";var Mv=16*1024;async function Pm(e,r=Mv){let t;try{t=(await Nv(e)).size}catch{return null}if(t<=0)return null;let n=Math.min(r,t),o;try{let s=await Cv(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 Fv(o)}function Fv(e){let r=e.split(`
|
|
93
|
-
`);for(let
|
|
94
|
-
`)
|
|
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
|
+
`))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function dw(e){let r;try{r=Po(xr(e,"memory.current"),"utf8")}catch{return null}let t=Number(r.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:cw(e)}}function cw(e){let r;try{r=Po(xr(e,"cpu.stat"),"utf8")}catch{return null}return uw(r)}function uw(e){for(let r of e.split(`
|
|
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
|
+
`)){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=yw(n[3]);a!=null&&r.set(o,{pid:o,ppid:s,rssBytes:i*fw,cpuSeconds:a})}return r}function yw(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 kw(e){let r=new Map,t;try{t=rw(e)}catch{return r}for(let n of t){if(!/^\d+$/.test(n))continue;let o;try{o=Po(xr(e,n,"stat"),"utf8")}catch{continue}let s=_w(o);s&&r.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*ow,cpuSeconds:s.cpuTicks/bw})}return r}var bw=100;function _w(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 Rw=["api","graphql"],fj=vi(Rw);var Ep=100,la=6e4,ww=2*la,Ew=7*24*60*60*1e3,aa=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 da(e,r){for(let t of e)if(t.token_ref!=null&&t.token_ref!==r)throw new aa(t.project_label,t.token_ref,r)}function Pp(e,r={now:new Date(0).toISOString()}){Lp(e);let t=r.closedWindowMs??Ew,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),h=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: ${h}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
|
|
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
|
+
`,{encoding:"utf8",mode:384}),await VE(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 zE(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return ue(r)}catch{return null}}}function QE(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(Vt)}import{spawnSync as No}from"node:child_process";import{existsSync as La}from"node:fs";import{delimiter as sv,join as am}from"node:path";import{join as Xp}from"node:path";import{existsSync as YE}from"node:fs";import{createRequire as XE}from"node:module";var Zp="redskilled-job-object.node",Ar=100;function dt(e){return{available:!1,reason:e}}function ZE(e,r,t){return[Xp(t,"prebuilds",`${e}-${r}`,Zp),Xp(t,"native","build","Release",Zp)]}function em(e={}){let r=e.platform??process.platform,t=e.arch??process.arch;if(r!=="win32")return dt(`Job Object placement is the Windows backend (platform=${r}), so there is no native reach to load here`);let n=e.packageRoot??rv(),o=e.exists??YE,s=ZE(r,t,n),i=s.find(d=>o(d));if(i==null)return dt(`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??XE(import.meta.url),l;try{l=a(i)}catch(d){return dt(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return ev(l)?{available:!0,binding:l}:dt(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function ev(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function rv(){return new URL("..",import.meta.url).pathname}function rm(e){let r=e??{},t=[],n=tv(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<Ar?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 ${Ar}, 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 tv(e){return en({budget:e})}var Go=5,tm=19;function Oa(e){return{available:!1,reason:e}}var nv="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 om(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=Go;else if(t.cpu_weight<Ar){let a=Math.round(tm*(Ar-t.cpu_weight)/Ar);o=Math.min(tm,Math.max(Go,a))}else o=Go,n.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${Ar}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Go}`);let s=nm(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=nm(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:nv,...n.length>0?{note:n.join("; ")}:{}}}function sm(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 ${ov(e.nice)} -n ${r.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
|
|
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
|
+
`).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function _m(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:hm,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 Rm(e){return e.project_label.trim()!==""?e:{...e,project_label:hm,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 wm(e){if(e.unit!=null&&e.unit!==""){let r=No("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 yn=50,Ga=15e3,i0=2*Ga;function gv(e,r=yn){if(Ca(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 vm(e,r={}){let t=r.batchSize??yn;if(Ca(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(`
|
|
92
|
+
`),aliases:n}}function Sm(e,r){let t=hn(r),n=hn(t.data),o=Array.isArray(t.errors)?t.errors.map(hn):[],s=bv(n.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=Rv(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=>_v(u.path,a));return s.exhausted||Pm(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: ${$a(c?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function fv(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:yn,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function Tm(e,r,t){return{version:1,fetched_at:r,request_count:0,project_count:e.length,batch_size:yn,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 xm(e){if(e.projects.length===0)return fv(e.now);if(e.transport.conditionalList)return await yv(e);let r=e.batchSize??yn,t=gv(e.projects,r),n=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=vm(s,{batchSize:r});try{let a=await e.transport(i.query),l=Sm(i,a);n.push(...l.projects),o=fn(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=fn(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 hv={key:"redskilled queue poll",budget:"rest"};async function yv(e){Ca(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=vm([s],{batchSize:1}),d=Sm(l,await e.transport(l.query));o+=1,t.push(...d.projects),n=fn(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:hv});o+=i.requestCount;let a=i.data.filter(l=>!Om(l.pull_request)).length;n=fn(n,kv(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=Yt(i);n=fn(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 Ca(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 fn(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 kv(e){let r=Em(e,"x-ratelimit-remaining"),t=Em(e,"x-ratelimit-reset");return{remaining:r,reset_at:t==null?null:new Date(t*1e3).toISOString(),exhausted:r===0}}function Em(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 bv(e,r){let t=hn(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(Pm)||n===0}}function Pm(e){return e==null?!1:$a(e.type)==="RATE_LIMITED"||/rate limit/i.test($a(e.message))}function _v(e,r){return Array.isArray(e)&&e.includes(r)}function Rv(e){let r=hn(e);return Number.isInteger(r.issueCount)?r.issueCount:null}function hn(e){return Om(e)?e:{}}function Om(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $a(e){return typeof e=="string"?e:""}function Am(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(wv,Math.max(r,i))}let o=n.remaining;return o==null?r:o<=Ev?Math.max(r,3e4):o<=vv?Math.max(r,2e4):r}var wv=1e5,Ev=250,vv=1e3;var Sv={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},Tv=["runner","model","effort","origin","issue","phase","step","heartbeat","wait_kind","wait_subject","wait_started_at","wait_deadline","wait_escalation","started_at"],xv=["phase_index","phase_total","wait_pid","context","eta","added","removed","tokens","tools","reasoning","text"];function Dm(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let r=e,t={...Sv};for(let n of Tv){let o=r[n];t[n]=typeof o=="string"&&o.trim()!==""?o:null}for(let n of xv){let o=r[n];t[n]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=r.failed===!0,t}import{randomInt as Dv}from"node:crypto";import{spawn as jv}from"node:child_process";import{appendFileSync as Lv,mkdirSync as Iv}from"node:fs";import{dirname as $v}from"node:path";import{delimiter as jm,dirname as Pv}from"node:path";function Ov(e,r=jm){return(e??"").split(r).map(t=>t.trim()).filter(t=>t!=="")}function Av(e=process.execPath){let r=(e??"").trim();if(r==="")return null;let t=Pv(r);return t===""||t==="."?null:t}function Lm(e,r=process.execPath,t=jm){let n=Ov(e,t),o=Av(r);return o==null?n.join(t):[o,...n.filter(s=>s!==o)].join(t)}var ct=class extends Error{constructor(r){super(r),this.name="RedskilledWorkerSpecError"}},Mo=class extends Error{constructor(t,n){super(t);this.admission=n;this.name="RedskilledAdmissionError"}},Na="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",$m=4,Gv=Na.length**$m;function Ma(e,r=Dv){let t=new Set(e);for(let n=0;n<Gv;n+=1){let o="h";for(let s=0;s<$m;s+=1)o+=Na[r(Na.length)];if(!t.has(o))return o}throw new ct("redskilled exhausted the host Worker id space")}function Cv(e){if(e==null||e.trim()==="")return!1;try{return Iv($v(e),{recursive:!0}),!0}catch{return!1}}function Nv(e,r){let t=(n,o)=>{if(n==null)return;let s="",i=a=>{try{Lv(r,ge().push({at:new Date().toISOString(),kind:o,msg:a}),"utf8")}catch{}};n.on("data",a=>{s+=String(a);let l=s.split(`
|
|
93
|
+
`);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 Mv(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 ct(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new ct("redskilled worker spec args must be an array")}function Fv(e){if(e==null)throw new Mo("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new Mo(e.reason,e)}function Gm(e){let{spec:r,admission:t}=e;Fv(t),Mv(r);let n=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(r.worker_id??e.workerId)?.trim()||Ma(e.liveWorkerIds??[]),i=e.probes??dm(n),a=e.openLog===!1?!1:Cv(r.log_path),l={...r.env??{},PATH:Lm(r.env?.PATH??n.PATH,e.execPath??process.execPath)},d=pm({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??cm(n),probes:i,pipeOutput:a}),u=(e.spawnFn??jv)(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&&Nv(u,r.log_path),u.pid==null)throw u.once("error",()=>{}),new ct(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${s}`);let m=d.job!=null?Wv(d,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(_,v)=>{try{m?.job?.close()}catch{}e.onExit?.(s,_,v)}),u.unref();let h=d.job!=null?m?.job!=null:d.isolated,f=[d.warning,m?.warning,d.budgetWarning].filter(_=>_!=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:h,...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:f},admission:t,warnings:f,plan:d,child:u,...m?.job!=null?{job:m.job}:{}}}function Wv(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: ${Im(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)}: ${Im(i)}. ${o}`}}return{job:s}}function Im(e){return e instanceof Error?e.message:String(e)}import{open as Uv,stat as Bv}from"node:fs/promises";var Hv=16*1024;async function Cm(e,r=Hv){let t;try{t=(await Bv(e)).size}catch{return null}if(t<=0)return null;let n=Math.min(r,t),o;try{let s=await Uv(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 qv(o)}function qv(e){let r=e.split(`
|
|
94
|
+
`);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 iS}from"node:child_process";import{existsSync as aS,readdirSync as lS}from"node:fs";import{dirname as dS,join as Bm,resolve as cS}from"node:path";var Vv="<version>";function ur(e,r=[],t){let n=t&&t.trim().length>0?t.trim():Vv;return[`npx -y -p ${vr}@${n}`,e,...r].join(" ")}function Ae(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 Fa(e,r){let t=Ae(e),n=Ae(r);return!t||!n?0:t.major-n.major||t.minor-n.minor||t.patch-n.patch}var T0=4*60*60*1e3;Ve();Ve();import{spawnSync as Kv}from"node:child_process";import{mkdir as Jv,rm as zv,writeFile as Qv}from"node:fs/promises";import{existsSync as Yv}from"node:fs";import{homedir as Xv}from"node:os";import{dirname as Zv,join as Wa}from"node:path";var ut="redskilled.service",Ua="REDSKILLED_SUPERVISED",eS="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function rS(e=process.env){let r=e.XDG_CONFIG_HOME?.trim()||Wa(e.HOME?.trim()||Xv(),".config");return Wa(r,"systemd","user")}function Ba(e=process.env){return Wa(rS(e),ut)}function Nm(e,r={}){let t=r.env??process.env,n=so(r.override??{},r.entryLookup??{}),o=[...n.args,...wr(e,r.idleMs==null?{}:{idleMs:r.idleMs})];return{unitName:ut,unitPath:Ba(t),command:n.command,args:o,text:tS(n.command,o,e)}}function tS(e,r,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${eS}`,"","[Service]","Type=simple",`ExecStart=${[e,...r].map(nS).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Ua}=1"`,`Environment="REDSKILLED_SESSION=${Mm(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
|
|
95
|
+
`)}function nS(e){return/[\s"'\\$%]/.test(e)?`"${Mm(e)}"`:e}function Mm(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function Fm(e,r={}){let t=r.writeFile??oS,n=r.run??Ha,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(Fo("daemon-reload",n,["systemctl","--user","daemon-reload"])),o.push(Fo("enable",n,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function Wm(e={}){let r=e.removeFile??sS,t=e.run??Ha,n=Ba(e.env??process.env),o=[Fo("disable",t,["systemctl","--user","disable","--now",ut])];return await r(n),o.push({step:"remove-unit",ok:!0,detail:n}),o.push(Fo("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:n,installed:!1,steps:o}}function Um(e={}){let r=e.exists??Yv,t=e.run??Ha,n=Ba(e.env??process.env),o=r(n);return{unitName:ut,unitPath:n,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",ut]).status===0,active:o&&t(["systemctl","--user","is-active",ut]).status===0,floor:"auto-spawn"}}function Fo(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 oS(e,r){await Jv(Zv(e),{recursive:!0}),await Qv(e,r,{encoding:"utf8",mode:420})}async function sS(e){await zv(e,{force:!0})}function Ha(e){let r=Kv(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 Hm=75,Vm=9e5,qm="redskilled-replacement-entry-unresolved",uS="REDSKILLED_NO_REGISTRY_PROBE",Km="REDSKILLED_BORN_BY_REPLACEMENT";function Jm(e=process.env){return e[Km]==="1"}function zm(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function Qm(e){let r=e.running.trim();if(kn(r))return null;let t=e.newest?.trim()??"",n=Ae(t),o=Ae(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:pS(n.major,e.supervised)}}function pS(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: ${ur("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 Ym(e){let r=e.running.trim();if(kn(r))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||Ae(t)===null?{act:"hold",reason:"published-unknown"}:Fa(t,r)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function kn(e){let r=e.trim();return Ae(r)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(r)}function Xm(e=process.env){return e[Ua]==="1"}var qa=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
|
|
95
96
|
searched:
|
|
96
97
|
${t.map(n=>` ${n}`).join(`
|
|
97
|
-
`)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function
|
|
98
|
-
`}function yS(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return ue(r)}catch{return null}}}function kS(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 mn=3e5,SS=1e4,TS=6e4,xS=15e3,PS=3e4,OS=6e4,Do=16;function AS(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 og(e){let r=e?.match(/\bsession-error:\s*(.+)$/)?.[1]?.trim();return r==null||r===""?null:r}var Tr=class extends Error{constructor(t,n){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=n;this.name="RedskilledAlreadyRunningError"}},DS="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function ig(e){let{paths:r}=e,t=e.daemonVersion??"0.0.0-dev",n=e.idleMs??mn,o=e.clock??(()=>new Date().toISOString()),s=e.launch??xm,i=e.ceiling??to();e.repositoryActivity!=null&&Xi(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??rg(),l=e.leaseStore??tg(r.leasePath,{sessionKeyHash:r.sessionKeyHash,machineIdHash:r.machineIdHash,socketPath:r.socketPath},{clock:o}),d=e.machineOwner??Uc(),c={machineIdHash:r.machineIdHash,sessionKeyHash:r.sessionKeyHash,socketPath:r.socketPath},u=e.machineClaimStore??oo(r.machineClaimPath,c,{clock:o});await RS(vS(r.socketPath),{recursive:!0,mode:448});let m=await u.claim(d);if(!m.claimed)throw m.claim?.socket_path===r.socketPath?new Tr(r.socketPath):new rr(u.claimPath,m.reason,m.claim);let h=await l.acquire(a);if(!h.acquired)throw await u.release(d).catch(()=>{}),new Tr(r.socketPath,h.lease);let f;try{f=await LS(r.socketPath,async()=>{let[p,y]=await Promise.all([l.read().catch(()=>{}),u.read().catch(()=>{})]);return p!=null&&p.pid!==a.pid&&ne(p.pid)?!0:y!=null&&y.socket_path===r.socketPath&&y.pid!==d.pid&&ne(y.pid)})}catch(p){throw await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),p}let v=o(),_=e.eventLane??Tc(r.eventLanePath),S=e.registrationIntentStore??Up(r.registrationIntentPath),j=e.liveness??im,B=e.livenessGraceMs??sm,M=e.stopWorker??mm,oe=e.unitInventory??(()=>dm(r.machineClaimPath,no({machineIdHash:r.machineIdHash}))?cm():[]),Z=e.unitMainPid??lm,le=e.treeSampler??fp,Je=e.readLogTail??Pm,Pr=e.sampleMs??xS,dt=e.leaseRenewMs??PS,kn=e.registrationSustainMs??OS,ct=e.publishedVersion??(p=>Vm(p)),ut=e.replaceCheckMs??Cm,bn=e.publishedProbeTimeoutMs??SS,_n=e.localPublishedEvidence??(p=>Km(p,e.replacementIO?.env??process.env)),No=e.bornByReplacement??Mm(),Rn=e.replaceBootCheckMs??TS,pt=e.supervised??Bm(),mt=e.replacementIO??{},ge=e.repositoryActivity,gt=ge?.intervalMs??Yi,ar=e.githubBalance,Oe=e.queueDiscovery,lr=Oe?.transport??ge?.transport,Or=Oe?.unconfiguredReason??DS,ze=Oe?.intervalMs??Oa,wn=e.demandMs??15e3,En=e.demandBackoffMs??3e4,C=new Map,be=new Set,Qe=new Map,Ar=new Map,ft=[],dr=[],cr=e.deaths===void 0?void 0:[...e.deaths],ht=await S.read().catch(()=>[]),ur=Date.parse(v),W=new Map,Q=new Map;for(let p of ht){let y=Date.parse(p.renew_by);!Number.isFinite(ur)||!Number.isFinite(y)||y>=ur?W.set(p.project_label,p):ur-y<=p.renew_within_ms&&Q.set(p.project_label,p)}let Dr=new Set,yt={},jr=null,Lr=null,de=null,kt=!1,Ir=0,bt=null,D="none",k=null,g=null,b=null,R=null,w=null,T=null,O=[],G=[],q=new Map((e.orphanedRegistrations??[]).map(p=>[p.project_label,p])),H=null,Y={},_t=!1,Me,Rt,wt,Et,vt,St,vn,Tt,Gr,$r,ce=!1,Mo=!1,Sn=null,rl,Fo=new Promise(p=>{rl=p});function Cr(p){tl(p);let y=Date.parse(p),E=zc(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),L=[...C.values()].some(I=>I.project_label===P.project_label);(A?.outcome==="counted"&&(A.depth??0)>0||L)&&Q.set(P.project_label,P),Kg(P,y)}return E.lapsed.length>0&&Nr(),E.lapsed}function Nr(){let p=new Map(Q);for(let[y,E]of W)p.set(y,E);S.replace([...p.values()]).catch(()=>{})}function Kg(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>Do&&O.splice(0,O.length-Do)}function tl(p){if(W.size===0)return;let y=Date.parse(p);if(!Number.isFinite(y))return;let E={};for(let I of C.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])),L=!1;for(let I of[...W.values()]){let _e=Number.isFinite(P)&&y-P<=I.renew_within_ms?A.get(I.project_label):void 0,$=ui(I,{now:p,..._e==null?{}:{queue:{outcome:_e.outcome,depth:_e.depth}},liveWorkers:E[I.project_label]??0});$.registration!==I&&(W.set(I.project_label,$.registration),L=!0)}L&&Nr()}function nl(p){if(Q.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,L]of[...Q]){if(y-Date.parse(L.renew_by)>L.renew_within_ms){Q.delete(A),P=!0;continue}let I=E.get(A),X=ui(L,{now:p,...I==null?{}:{queue:{outcome:I.outcome,depth:I.depth}},liveWorkers:[...C.values()].filter(_e=>_e.project_label===A).length});X.verdict==="open-work"||X.verdict==="live-worker"?(W.set(A,X.registration),Q.delete(A),P=!0):X.verdict==="drained"&&(Q.delete(A),P=!0)}P&&Nr()}function Tn(){let p=o();return Cr(p),Fp({now:p,daemonVersion:t,machineIdHash:r.machineIdHash,sessionKeyHash:r.sessionKeyHash,pid:a.pid,startedAt:v,ceiling:i,scope:Bc(u.claimPath,c,d),workers:[...C.values()],registrations:[...W.values()],demand:T,lapses:O,stops:G,orphanedRegistrations:[...q.values()],birthLatches:Lc(Y,Date.parse(p)),queue:w,published:{version:Lr,checkedAt:de,newer:kt,replacement:D,newest:k,majorHold:g,checks:Ir,holdReason:bt}})}function xn(){return Op({hostState:Tn(),ceiling:i,rss:yt,sampledAt:jr,logLines:Object.fromEntries(Qe),displays:Object.fromEntries(Ar),now:o(),reattachedWorkerIds:[...be],repositoryActivity:b,githubBalance:R,...cr===void 0?{}:{deaths:cr},metrics:pp({observations:ft,outcomes:dr,now:o()})})}function Jg(p,y){ft=zt([...ft,{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 zg(p){dr=zt([...dr,p],y=>y.ts,{now:o()})}async function Wo(){return ge==null||ge.projects.length===0?null:(b=await wp({projects:ge.projects,hostTokenRef:ge.hostTokenRef,transport:ge.transport,closedWindowMs:ge.closedWindowMs,now:o()}),b)}async function ol(){return ar==null?null:(R=await Ui({transport:ar.transport,now:o()}),R)}function Qg(){if(ce||Gr!=null||ar==null)return;let p=()=>{Gr=void 0,ol().catch(()=>{}).then(()=>{if(ce)return;let y=ar.intervalMsOverride??_o(R??Yg(),{now:o()});Gr=setTimeout(p,y),Gr.unref()})};p()}function Yg(){return bo(o())}function Xg(){if(!(lr!=null||Oe?.armTransport==null))try{let p=Oe.armTransport();if(p.transport!=null){lr=p.transport;return}p.unconfiguredReason!=null&&(Or=p.unconfiguredReason)}catch(p){Or=`this host could not resolve a tracker credential: ${p instanceof Error?p.message:String(p)}`}}async function sl(){let p=o();Cr(p);let y=Date.parse(p);for(let[L,I]of[...Q])Number.isFinite(y)&&y-Date.parse(I.renew_by)>I.renew_within_ms&&Q.delete(L);let P=[...new Map([...Q,...W]).values()].map(L=>({project_label:L.project_label,selector:L.selector,...L.queue_poll==null?{}:{poll:L.queue_poll}})).sort((L,I)=>L.project_label.localeCompare(I.project_label));if(P.length===0)return null;if(Xg(),lr==null)return w=ym(P,p,Or),w;w=await km({projects:P,transport:lr,now:p,...Oe?.batchSize==null?{}:{batchSize:Oe.batchSize}});let A=o();return nl(A),tl(A),w}async function il(){let p=o();if(_t)return T??Oc(p);_t=!0;try{await Bo().catch(()=>{});let y={};for(let $ of C.values())y[$.project_label]=(y[$.project_label]??0)+1;let E={};for(let $ of w?.projects??[])E[$.project_label]=$.depth;let P=Date.parse(p),A=Number.isFinite(P)?P:0;for(let[$,fe]of Object.entries(Y)){if(fe.probeWorkerId==null)continue;let Ln=C.get(fe.probeWorkerId);Ln!=null&&A-Date.parse(Ln.started_at)>=6e4&&(Y[$]=ti())}let L=Pc({projects:[...W.values()].map($=>({project_label:$.project_label,selector:$.selector,argv:$.argv,workspace_path:$.workspace_path,target:$.target})),queue:E,live:y,nowMs:A,backoffUntilMs:H,birthHealth:Y}),I=[],X=null;for(let $ of L.births){let fe,Ln=ja(C.keys()),In=W.get($.project_label),Rl=qc({argv:$.argv,...In?.env==null?{}:{env:In.env},...In?.log_path==null?{}:{log_path:In.log_path}},{worker_id:Ln,slot:$.index,workspace_path:$.workspace_path},{project_label:$.project_label});try{fe=Uo(Rl)}catch(Jo){X=Jo instanceof Error?Jo.message:String(Jo),H=(Number.isFinite(P)?P:Date.now())+En;break}I.push({project_label:$.project_label,worker_id:fe.worker.worker_id,pid:fe.worker.pid,warnings:Rl.log_path==null?[...fe.warnings,`project ${JSON.stringify($.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(fe.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:fe.warnings});let Ko=Y[$.project_label];Ko?.haltUntilMs!=null&&A>=Ko.haltUntilMs&&(Y[$.project_label]=jc(Ko,fe.worker.worker_id))}X==null&&L.births.length>0&&(H=null);let _e=new Set(I.map($=>$.project_label));for(let $ of L.intents){if($.queue_depth==null||$.queue_depth<=0||$.live>=$.target||_e.has($.project_label))continue;let fe=X!=null&&($.outcome==="asking"||$.outcome==="half-open-probe")?`project ${JSON.stringify($.project_label)} was birth-eligible but the host refused it: ${X}`:$.detail;await _.recordDemandRefusal({ts:p,projectLabel:$.project_label,detail:fe}).catch(()=>{})}return T={version:1,at:p,requested:L.births.length,granted:I,shortfall:L.births.length-I.length,refusal:X,retry_after:H==null?null:new Date(H).toISOString(),projects:L.intents},T}finally{_t=!1}}function Zg(p){return vr(xn(),{...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 ef(p){return ot(xn(),{mode:p?.mode??$e.mode,project:p?.project??$e.project,maxWidth:p?.max_width??$e.maxWidth,maxRows:p?.max_rows??$e.maxRows})}function pr(p,y,E){return Xc({op:p,sessionProject:y??null,targetProject:E})}async function rf(p){let y=C.get(p.worker_id),E=pr(Yc(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 af(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 Pn(p){C.delete(p),be.delete(p),Qe.delete(p),Ar.delete(p)}function al(p){let y=C.get(p.worker_id),E=pr("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();Qe.set(p.worker_id,{line:p.last_log_line,published_at:P,source:"heartbeat"});let A=p.display===void 0?null:wm(p.display);if(A!=null){let L={display:A,published_at:P};Ar.set(p.worker_id,L),Jg(L,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 tf(p,y,E){let P=`exit code=${y??"null"} signal=${E??"null"}`;if(p.unit!=null&&p.unit!==""&&await of(p)){sf(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:og(await Je(p.log_path).catch(()=>null));Pn(p.worker_id),Fe("worker-death",p,A==null?P:`session-error: ${A}`,{exitCode:y,signal:E,refusal:A}),ee()}function nf(p,y){if(!Number.isFinite(y)||y<0){Y[p]=Wt;return}let E=Y[p]??Wt,P=Dc(E,y,Date.parse(o()));Y[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()}
|
|
99
|
-
`)}function ll(p,y){let E=pr("project-reset",y,p);if(!E.permitted)throw new Error(E.reason);let P=Y[p]?.haltUntilMs!=null||Y[p]?.probeWorkerId!=null;return Y[p]=ti(),{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 of(p){try{return await j(p)===!0}catch{return!1}}function sf(p,y){let E=p.unit==null?null:Z(p.unit);C.set(p.worker_id,{...p,...E!=null&&E>0?{pid:E}:{},warnings:[...p.warnings,y]}),be.add(p.worker_id),ee()}function dl(p,y){let E=pr("project-register",y,p.project_label);if(!E.permitted)throw new Error(E.reason);let P=o();Cr(P);let A=Vc(p,{now:P,held:W.get(p.project_label)});return W.set(A.project_label,A),Nr(),pl(A.project_label),ee(),{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 cl(p,y={}){let E=pr("project-renew",y.sessionProject,p);if(!E.permitted)throw new Error(E.reason);let P=o();Cr(P);let A=W.get(p);if(A==null){if(q.has(p))throw new _r(p,{kind:"orphaned"});let I=[...G].reverse().find(_e=>_e.project_label===p);if(I!=null)throw new _r(p,{kind:"stopped",at:I.at});let X=[...O].reverse().find(_e=>_e.project_label===p);throw X!=null?new _r(p,{kind:"lapsed",at:X.at,...X.registered_at==null?{}:{registered_at:X.registered_at}}):new _r(p)}let L=Kc(A,{now:P,...y.renewWithinMs==null?{}:{renew_within_ms:y.renewWithinMs},...y.launch==null?{}:{launch:y.launch}});return W.set(L.project_label,L),Nr(),ee(),{version:1,registration:L,reach:E,detail:`redskilled renewed the registration for project ${JSON.stringify(L.project_label)}, which now stands until ${L.renew_by} after renewal ${L.renewals}`+(y.launch==null?"":`, carrying launch revision ${L.launch_revision} for its next Worker`)}}function ul(p,y){let E=pr("project-deregister",y,p);if(!E.permitted)throw new Error(E.reason);let P=W.get(p)??Q.get(p),A=W.delete(p),L=Q.delete(p),I=A||L;if(P!=null){let X=`redskilled released the registration for project ${JSON.stringify(p)}`;pl(p),G.push({project_label:p,registered_at:P.registered_at,at:o(),detail:X}),G.length>Do&&G.splice(0,G.length-Do)}return I&&Nr(),{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 pl(p){Q.delete(p);for(let y=O.length-1;y>=0;y-=1)O[y].project_label===p&&O.splice(y,1);for(let y=G.length-1;y>=0;y-=1)G[y].project_label===p&&G.splice(y,1);q.delete(p)}async function af(p,y){try{await M(p)}catch{}return Pn(p.worker_id),Fe("worker-death",p,y),ee(),!0}function ml(p){return Rc({ceiling:i,workers:[...C.values()],budget:p.budget,projectLabel:p.project_label,...p.reservation==null?{}:{reservation:p.reservation}})}function Uo(p){let y=wc({ceiling:i,workers:[...C.values()],budget:p.budget}),E=s({spec:p,admission:ml(p),memoryCeiling:y,liveWorkerIds:C.keys(),clock:o,onExit:(P,A,L)=>{let I=C.get(P);if(I==null){ee();return}tf(I,A,L).catch(()=>{})}});return C.set(E.worker.worker_id,E.worker),Fe("worker-birth",E.worker,null),ee(),E}function Fe(p,y,E,P={}){if(ce)return;let A=o();(p==="worker-death"||p==="worker-budget-kill")&&(zg({worker_id:y.worker_id,ts:A,outcome:p}),gl({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}}),nf(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 gl(p,y={}){let E=AS(p,y);if(E==null)return;let P=[E,...(cr??[]).filter(A=>A.kind!==E.kind||A.id!==E.id||A.ts!==E.ts)].sort((A,L)=>Date.parse(A.ts)-Date.parse(L.ts));cr=zt(P,A=>A.ts,{now:o()})}async function Bo(){let p=Date.parse(o()),y=[...C.values()].filter(P=>{if(be.has(P.worker_id))return!0;let A=Date.parse(P.started_at);return!Number.isFinite(A)||p-A>=B});if(y.length===0)return[];let{dead:E}=await xa(y,j);for(let P of E)Pn(P.worker_id),Fe("worker-death",P,"the host no longer confirms this Worker");return E.length>0&&ee(),E}async function fl(p,y){let E=C.get(p);if(!E)return!1;try{await M(E)}catch{}return Pn(p),Fe("worker-budget-kill",E,y),ee(),!0}async function hl(){let p=[...C.values()];if(p.length===0)return[];let y;try{y=await le(p)}catch{return[]}let E=y.rss;yt=E,jr=o(),lf(y.cpu_seconds,jr);let{terminations:P}=gp({workers:p,rss:E}),A=[];for(let L of P)await fl(L.worker_id,L.reason)&&A.push(L);return A}function lf(p,y){for(let[E,P]of Object.entries(p)){if(typeof P!="number"||!Number.isFinite(P))continue;let A=C.get(E);A&&C.set(E,{...A,cpu:{cpu_seconds:P,sampled_at:y}})}}async function df(){try{return bn<=0?await ct(t):await new Promise(p=>{let y=setTimeout(()=>p(Ho()),bn);y.unref(),ct(t).then(E=>{clearTimeout(y),p(E)},()=>{clearTimeout(y),p(Ho())})})}catch{return Ho()}}function Ho(){try{return _n(t)}catch{return null}}async function yl(){if(un(t))return Ir+=1,de=o(),bt="local-build",{act:"hold",reason:"local-build"};let p=Fm(await df()),y=p.version;Lr=y,k=p.newest??null,de=o(),g=Wm({running:t,newest:k,supervised:pt});let E=Um({running:t,published:y,supervised:pt});return kt=E.act==="replace",Ir+=1,bt=E.act==="hold"?E.reason:null,D!=="in-progress"&&(D=E.act==="replace"?"pending":"none"),E}async function On(){let p=await yl();if(p.act!=="replace"||D==="in-progress")return p;let y=Hm(p,mt);return D="in-progress",await _.flush().catch(()=>{}),await S.flush().catch(()=>{}),await Dn({reason:"replaced"}),qm(y,r,{...n==null?{}:{idleMs:n},io:mt}),p}function cf(){ce||St!=null||ut<=0||(!No&&Rn>0&&(vn=setTimeout(()=>{On().catch(()=>{})},Rn),vn.unref()),St=setInterval(()=>{On().catch(()=>{})},ut),St.unref())}async function kl(){return await l.renew(a).catch(()=>null)}function uf(){ce||wt!=null||dt<=0||(wt=setInterval(()=>{kl()},dt),wt.unref())}function pf(){ce||Et!=null||kn<=0||(Et=setInterval(()=>{Cr(o())},kn),Et.unref())}function mf(){ce||Rt!=null||Pr<=0||(Rt=setInterval(()=>{hl().catch(()=>{})},Pr),Rt.unref())}function gf(){ce||Tt!=null||ge==null||ge.projects.length===0||gt<=0||(Wo().catch(()=>{}),Tt=setInterval(()=>{Wo().catch(()=>{})},gt),Tt.unref())}function ff(){if(ce||$r!=null||ze<=0)return;let p=y=>{$r=setTimeout(()=>{$r=void 0,sl().catch(()=>{}).finally(()=>{if(ce)return;let E=Date.parse(o());p(Rm(w,ze,Number.isFinite(E)?E:Date.now()))})},y),$r.unref()};p(ze)}function hf(){ce||vt!=null||wn<=0||(vt=setInterval(()=>{il().catch(()=>{})},wn),vt.unref())}function ee(){ce||(Me&&clearTimeout(Me),Me=setTimeout(()=>{Bo().catch(()=>{}).then(()=>bl())},n),Me.unref())}function bl(){return C.size>0?(ee(),"held-by-workers"):(Cr(o()),W.size>0?(ee(),"held-by-registrations"):(yf(),"exited"))}async function yf(){if(!un(t)){if((await On().catch(()=>null))?.act==="replace"||Mo||ce)return;if(C.size>0||W.size>0){ee();return}}await Dn({reason:"idle"})}function An(p){return Gc({reason:p,socketPath:r.socketPath,daemonVersion:t,pid:a.pid,workers:[...C.values()],projects:[...W.keys()]})}function _l(p){if(Sn!=null)return Sn;let y=p.reason??"requested",E=p.note?.trim();return Sn=_.recordDaemonStop({ts:o(),pid:a.pid,socketPath:r.socketPath,reason:y,detail:E==null||E===""?An(y).detail:`${An(y).detail} \u2014 ${E}`,...p.signal==null?{}:{signal:p.signal}}).catch(()=>{}),Sn}async function Dn(p={}){if(Mo)return await Fo;Mo=!0,await _l(p),ce=!0,Me&&clearTimeout(Me),Rt&&clearInterval(Rt),wt&&clearInterval(wt),Et&&clearInterval(Et),St&&clearInterval(St),vn&&clearTimeout(vn),Tt&&clearInterval(Tt),Gr&&clearTimeout(Gr),$r&&clearTimeout($r),vt&&clearInterval(vt),await _.flush().catch(()=>{}),await S.flush().catch(()=>{}),f.close();for(let y of Dr)y.destroy();return await new Promise(y=>f.once("close",()=>y())),await sg(r.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),rl(),await Fo}let qo=await _.read().catch(()=>[]),jn=new Map;for(let p of qo){if(p.event==="worker-birth"){jn.set(p.worker_id,p.ts);continue}let y=og(p.detail);gl(p,{...jn.get(p.worker_id)==null?{}:{startedAt:jn.get(p.worker_id)},...y==null?{}:{refusal:y}}),(p.event==="worker-death"||p.event==="worker-budget-kill")&&jn.delete(p.worker_id)}dr=zt(qo.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 kf=xc(qo),Vo=await xa(kf,j);for(let p of Vo.alive){let y=pm(p),E=y.unit==null||ne(y.pid)?null:Z(y.unit);C.set(y.worker_id,E!=null&&E>0?{...y,pid:E}:y),be.add(y.worker_id)}for(let p of Vo.dead)Fe("worker-death",p,"the Worker ended while no daemon was watching");let bf=um({units:await Promise.resolve(oe()).catch(()=>[]),held:[...C.values()],mainPid:Z,now:v});for(let p of bf)C.set(p.worker_id,p),be.add(p.worker_id),Fe("worker-birth",p,"adopted from an active unit with no birth on this lane");nl(o());for(let p of Vo.alive){if(p.log_path==null||Qe.has(p.worker_id))continue;let y=await Je(p.log_path).catch(()=>null);y==null||y.trim()===""||Qe.set(p.worker_id,{line:y,published_at:o(),source:"rehydrated"})}f.on("connection",p=>{Dr.add(p),p.once("close",()=>Dr.delete(p)),ee(),IS(p,async(y,E)=>{ee();let P=await _f(y);E(P),y.op==="shutdown"&&setImmediate(()=>void Dn({reason:"requested"}))})});async function _f(p){try{if(p.op==="ping")return{id:p.id,ok:!0,value:{pong:!0,protocol_version:vo,daemon_version:t,pid:a.pid}};if(p.op==="host-state")return{id:p.id,ok:!0,value:Tn()};if(p.op==="statusline-payload")return{id:p.id,ok:!0,value:Pp(xn(),p.extras)};if(p.op==="statusline-string")return{id:p.id,ok:!0,value:Zg(p.render)};if(p.op==="statusline-dashboard")return{id:p.id,ok:!0,value:ef(p.dashboard)};if(p.op==="worker-heartbeat")return{id:p.id,ok:!0,value:al(p.heartbeat)};if(p.op==="project-register"){let E=dl(p.registration,p.session_project);return await S.flush(),{id:p.id,ok:!0,value:E}}if(p.op==="project-renew"){let E=cl(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=ul(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:ll(p.project_label,p.session_project)};if(p.op==="worker-command")return{id:p.id,ok:!0,value:await rf(p.command)};if(p.op==="worker-start"){let E=pr("worker-start",p.session_project,p.spec.project_label);if(!E.permitted)return{id:p.id,ok:!1,error:E.reason};let P=Uo(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=An("requested");return await _l({reason:"requested",...p.detail==null?{}:{note:p.detail}}),{id:p.id,ok:!0,value:E}}let y=p;return{id:y.id??jo(),ok:!1,error:`unsupported redskilled op: ${y.op??"unknown"}`}}catch(y){return{id:p.id??jo(),ok:!1,error:y instanceof Error?y.message:String(y)}}}return ee(),mf(),uf(),pf(),cf(),gf(),Qg(),ff(),hf(),{socketPath:r.socketPath,lease:h.lease,startedAt:v,closed:Fo,startWorker:Uo,admit:ml,ceiling:()=>i,killWorkerOverBudget:fl,sampleMemoryBudgets:hl,renewLease:kl,pollRepositoryActivity:Wo,pollGithubBalance:ol,githubBalance:()=>R,pollQueueDiscovery:sl,queueDiscovery:()=>w,driveDemand:il,demand:()=>T,sweepWorkerLiveness:Bo,publishWorkerHeartbeat:al,reattached:()=>[...be].map(p=>C.get(p)).filter(p=>p!=null),flushEvents:()=>_.flush(),trackWorker(p){C.set(p.worker_id,p),Fe("worker-birth",p,null),ee()},releaseWorker(p){let y=C.get(p),E=C.delete(p);return be.delete(p),Qe.delete(p),Ar.delete(p),y&&Fe("worker-death",y,"released by the daemon"),ee(),E},workerCount:()=>C.size,registerProject:dl,renewProject:cl,resetProjectBirthBreaker:ll,deregisterProject:ul,registrations:()=>Tn().registrations??[],hostState:Tn,statuslinePayload:xn,evaluateIdle:bl,observePublishedVersion:yl,checkForReplacement:On,stopReport:An,stop:Dn}}async function jS(e,r=250){return await new Promise(t=>{let n=wS(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 LS(e,r){for(let t=0;t<2;t++){let n=ES();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 jS(e)!=="unowned")throw new Tr(e);if(await r?.())throw new Tr(e);await sg(e,{force:!0})}}throw new Tr(e)}async function Ce(e,r=250){try{return(await Jn({socketPath:e,timeoutMs:r},{id:jo(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function IS(e,r){Yd(e,(t,n)=>r(t,n),(t,n,o)=>{o({id:n?.id??jo(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function Ua(e){let r=e.socketPath,t=GS(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 ${ag(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 \`${ir("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 \`${ir("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function Ba(e){return`${e.reason} ${e.repair}`}function GS(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:$S(r.acquired_at,e.now??new Date().toISOString())}}function $S(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 ag(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`}Ue();var cg=1e4,xr=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"?`. ${Ba(o)}`:""}`);this.socketPath=t;this.cause=n;this.presence=o;this.name="RedskilledUnreachableError"}},Ha=class extends xr{constructor(t,n,o){super(t,o,n);this.presence=n;this.name="RedskilledDaemonHeldError"}},Lo=class extends Error{constructor(t){super(t);this.refusal=t;this.name="RedskilledRequestRefusedError"}};async function Io(e,r={}){let t=r.answers??await Ce(e.socketPath),n=await pn(e.leasePath).catch(()=>{});return Ua({socketPath:e.socketPath,answers:t,lease:n,holderAlive:n!=null&&ne(n.pid)})}async function qa(e,r={}){try{return await FS(e,r)}catch(t){if(t instanceof rr||t instanceof xr)throw t;let n=await Io(e).catch(()=>{});throw new xr(e.socketPath,t,n)}}async function FS(e,r){if(await NS(MS(e.socketPath),{recursive:!0,mode:448}),await Ce(e.socketPath))return"already-running";await BS(e);let t=await US(e,r);if(t!=null)return t;let n=await Zd(e.lockPath,{...r.spawnLockMaxAgeMs==null?{}:{maxAgeMs:r.spawnLockMaxAgeMs},onReap:r.onSpawnLockReaped??WS});if(!n.acquired)return await lg(e,r,void 0,n),"joined";try{if(await Ce(e.socketPath))return"already-running";let o=await qS(e,r);return await lg(e,r,o),"spawned"}finally{await ec(n)}}function WS(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
|
|
100
|
-
`)}async function
|
|
101
|
-
`)}import{chmod as
|
|
98
|
+
`)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function mS(e,r={}){let t=r.env??process.env,n=r.exists??aS,o=r.execPath??process.execPath,s=r.callerEntry===void 0?process.argv[1]:r.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[Bm(oo(t),i),"bundle-cache"]];s&&l.push([Bm(dS(cS(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 qa(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 Zm(e,r={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=r.resolveEntry??(n=>mS(n,r.env==null?{}:{env:r.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function eg(e,r,t={}){let n=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(n.exit??fS)(Hm),{...e,exitCode:Hm};let o=[...e.entry.args,...wr(r,t.idleMs==null?{}:{idleMs:t.idleMs})];return(n.spawnSuccessor??gS(n.env))(e.entry,o),e}function gS(e){return(r,t)=>{let n=iS(r.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[Km]:"1"}});n.on("error",()=>{}),n.unref()}}function fS(e){process.exitCode=e,process.exit(e)}async function rg(e,r=process.env,t=hS){let n=ng(r),o=og(e,r);if(r[uS]==="1")return{version:o,newest:n};let s=Ae(e)===null?"0.0.0":e;try{let i=await mc({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??n}}catch{return{version:o,newest:n}}}function tg(e,r=process.env,t){let n=t??Va;return{version:og(e,r,n),newest:ng(r,n)}}function ng(e=process.env,r=Va){return ig(sg(e,r))}function og(e,r=process.env,t=Va){let n=Ae(e.trim())?.major;return n===void 0?null:ig(sg(r,t).filter(o=>Ae(o)?.major===n))}function sg(e,r){let t=[];for(let n of r(oo(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(n)?.[1];!o||Ae(o)===null||t.push(o)}return t}function ig(e){let r=null;for(let t of e)(r===null||Fa(t,r)>0)&&(r=t);return r}function Va(e){try{return lS(e)}catch{return[]}}async function hS(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 yS,readFile as kS,rename as bS,rm as Ka,writeFile as ag}from"node:fs/promises";import{randomUUID as _S}from"node:crypto";import{dirname as RS}from"node:path";var Wo=class extends Error{constructor(r){super(`redskilled lease ${JSON.stringify(r)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function bn(e){let r;try{r=await kS(e,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}let t=wS(r);return ES(t)?t:void 0}var lg;function cg(){return lg??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},lg}function ug(e,r,t={}){let n=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??oe;async function s(){return await bn(e)}async function i(l){let d=`${e}.${l.pid}.${_S()}.tmp`;await ag(d,dg(l),{encoding:"utf8",mode:384}),await bS(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 yS(RS(e),{recursive:!0,mode:448});let d=!1;for(;;){let c=n(),u=a(l,c);try{return await ag(e,dg(u),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:u}}catch(h){if(h.code!=="EEXIST")throw h}let m=await s();if(!m){await Ka(e,{force:!0}),d=!0;continue}if(Ja(m,l))return{acquired:!0,reaped:d,lease:m};if(await o(m.pid))return{acquired:!1,lease:m};await Ka(e,{force:!0}),d=!0}},async renew(l){let d=await s();if(!d||!Ja(d,l))throw new Wo(e);let c={...d,renewed_at:n()};return await i(c),c},async release(l){let d=await s();if(!d)return!1;if(!Ja(d,l))throw new Wo(e);return await Ka(e,{force:!0}),!0}}}function Ja(e,r){return e.pid===r.pid&&e.start_time===r.startTime}function dg(e){return`${J(e,{keyedMapCollapse:!0})}
|
|
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 KS(e,r){let t=await qo(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let n=r.readyTimeoutMs??bg,o=Date.now()+n;for(;;){if(await We(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(i=>setTimeout(i,25))}let s=await qo(e).catch(()=>{});if(s==null||s.kind!=="held-unresponsive")return null;throw new Ya(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 JS(e){let t=await po(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 nr(e.machineClaimPath,"held",t)}async function _g(e,r,t={}){await Xa(e,t);let n;try{n=await gn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...r,id:kg()})}catch(o){throw new jr(e.socketPath,o,await qo(e).catch(()=>{}))}if(!n.ok)throw new Ho(n.error);return n.value}async function Rg(e,r={},t={}){if(!await We(e.socketPath))return Bc(e.socketPath);let n;try{n=await gn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:kg(),op:"shutdown",...r.detail==null?{}:{detail:r.detail}})}catch(i){throw new jr(e.socketPath,i)}if(!n.ok)throw new Ho(n.error);if(!gi(n.value))throw new Error("redskilled daemon returned a malformed stop report");let o=n.value;return await zS(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 zS(e,r){let t=Date.now()+r;for(;;){if(!await We(e))return!0;if(Date.now()>=t)return!1;await new Promise(n=>setTimeout(n,25))}}async function wg(e,r={}){let t=await _g(e,{op:"host-state"},r);if(!Qp(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Eg(e,r={},t){let n=await _g(e,{op:"statusline-payload",...r.sessionProject!=null?{session_project:r.sessionProject}:{},...t==null?{}:{extras:t}},r);if(!ca(n))throw new Error("redskilled daemon returned a malformed statusline payload");return n}async function vg(e,r=U,t={}){let n=await Eg(e,t,{vitals:!0,logs:r.verbose,display:!0});return Or(n,r)}async function Sg(e,r={},t={}){let n=await Eg(e,t,{vitals:!0,logs:!0,display:!0});return lt(n,{...Fe,...r})}async function yg(e,r,t,n){let o=Date.now()+(r.readyTimeoutMs??bg);for(;;){if(await We(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 ${lc(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 QS(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,...wr(e,r.idleMs==null?{}:{idleMs:r.idleMs})],i=US(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}Ve();import{readFile as YS}from"node:fs/promises";import{homedir as XS,totalmem as ZS}from"node:os";import{join as eT}from"node:path";var rT="REDSKILLED_IDLE_MS",tT=".red/config.yaml";async function xg(e=XS()){let r=eT(e,tT),t;try{t=await YS(r,"utf8")}catch(n){return n.code==="ENOENT"?{}:(Za(`redskilled: cannot read host config ${JSON.stringify(r)}; using environment and defaults instead: ${Tg(n)}`),{})}try{let n=oT(t);return{...Vo(n,"plugins.dev.redskilled.worker_ceiling","workerCeiling"),...Vo(n,"plugins.dev.redskilled.memory_ceiling","memoryCeiling"),...Vo(n,"plugins.dev.redskilled.validation_ceiling","validationCeiling"),...Vo(n,"plugins.dev.redskilled.idle_ms","idleMs")}}catch(n){return Za(`redskilled: malformed host config ${JSON.stringify(r)}; using environment and defaults instead: ${Tg(n)}`),{}}}function Pg(e={}){let r=e.env??process.env,t=e.config??{},n=co(r,e.totalMemoryBytes??ZS(),{flags:e.flags,config:t,...e.availableParallelism==null?{}:{availableParallelism:e.availableParallelism}}),o=nT(e.flags?.idleMs==null?void 0:String(e.flags.idleMs),r[rT],t.idleMs);if(o==null)return{ceiling:n,idleMs:_n,idleMsSource:"derived-default"};let s=Number(o.value);return Number.isSafeInteger(s)&&s>0?{ceiling:n,idleMs:s,idleMsSource:o.source}:(Za(`redskilled: ${aT(o.source)} idle_ms=${JSON.stringify(o.value)} is not a positive integer; using the default ${_n}ms instead.`),{ceiling:n,idleMs:_n,idleMsSource:"derived-default"})}function nT(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 Vo(e,r,t){let n=e[r];return n===void 0?{}:{[t]:n}}function oT(e){let r={},t=[];for(let[n,o]of e.split(/\r?\n/).entries()){let s=sT(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(".")]=iT(c.trim())}return r}function sT(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 iT(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function aT(e){return e==="flag"?"serve flag":e==="environment"?"environment":e==="home-config"?"home config":"derived default"}function Tg(e){return e instanceof Error?e.message:String(e)}function Za(e){process.stderr.write(`${e}
|
|
102
|
+
`)}import{chmod as $g,mkdir as Cg,readFile as Ng,stat as kT,writeFile as Mg}from"node:fs/promises";import{homedir as tl}from"node:os";import{dirname as Fg,join as Ko}from"node:path";import{join as lT}from"node:path";var Og=["local","tmp","host"],dT="local",Rn="plugins.dev.workspace.target";var el=class extends Error{constructor(r){super(r),this.name="WorkspaceConfigError"}};function Dg(e){let r=Xr(e,Rn),t=pT(r??"").trim();return t===""?void 0:t}function jg(e){let r=(e??"").trim();if(r==="")return{kind:"preset",preset:dT};let t=Og.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 el(`${Rn}: unknown workspace target ${JSON.stringify(r)}. Use one of the presets (${Og.join(", ")}) or an absolute parent directory for Workers.`)}function Lg(e,r){return e.kind==="preset"?e.preset==="host":uT(cT(e.parentDir,r),Ge(r))}function cT(e,r){return e==="~"?Ag(r):e.startsWith("~/")?lT(r,e.slice(2)):Ag(e)}function uT(e,r){return e===r?!0:r==="/"?e.startsWith("/"):e.startsWith(`${r}/`)}function Ag(e){let r=e.trim();return r.length>1?r.replace(/\/+$/,""):r}function pT(e){let r=e.trim(),t=/^(["'])(.*)\1$/.exec(r);return t?t[2]:r}Ve();import{createHash as mT}from"node:crypto";import{hostname as gT}from"node:os";import{join as wn}from"node:path";var pt="redskilled.sock",fT="REDSKILLED_SESSION";function hT(e={}){let r=e.env??process.env,t=r[fT]?.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 yT(e={}){return Ig(e.host??gT())}function Ue(e={}){let r=hT(e),t=e.runtimeDir??to({key:`redskilled:${r}`,socketFileName:pt,env:e.env,uid:e.uid}),n=yT(e),o=e.homeDir??e.env?.HOME??(e.runtimeDir==null?process.env.HOME:e.runtimeDir)??t;return{sessionKey:r,sessionKeyHash:Ig(r),machineIdHash:n,runtimeDir:t,socketPath:wn(t,pt),lockPath:wn(t,"redskilled.spawn.lock"),leasePath:wn(t,"redskilled.lease.toon"),eventLanePath:wn(Ge(o),jc),registrationIntentPath:wn(t,"redskilled.registrations.toon"),machineClaimPath:e.machineClaimPath??uo({env:e.env,machineIdHash:n,platform:e.platform})}}function Ig(e){return mT("sha256").update(e).digest("hex").slice(0,12)}var rl=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${ur("red-skills-redskilled",["provision"])}\` directly`,bT=`# Host-scoped redskilled policy. This file is never read from a repository.
|
|
102
103
|
plugins:
|
|
103
104
|
dev:
|
|
104
105
|
redskilled:
|
|
@@ -106,8 +107,8 @@ plugins:
|
|
|
106
107
|
# memory_ceiling: 8G
|
|
107
108
|
# validation_ceiling: 2
|
|
108
109
|
# idle_ms: 300000
|
|
109
|
-
`;async function
|
|
110
|
-
`)}async function
|
|
110
|
+
`;async function Wg(e=tl()){let r=Ge(e),t=Ko(Fg(r),"config.yaml"),n=await ol(r),o=!1,s=!1;n===void 0?(await Cg(r,{recursive:!0,mode:qe}),await $g(r,qe),o=!0):n!==qe&&(await $g(r,qe),s=!0);let i=!1;try{await Mg(t,bT,{encoding:"utf8",flag:"wx",mode:384}),i=!0}catch(a){if(a.code!=="EEXIST")throw a}return{path:r,created:o,tightened:s,mode:qe,configPath:t,configCreated:i}}var Ug={needed:!1,declaredBy:`no ${Rn} in view`};async function nl(e={}){let r=e.homeDir??tl(),t=e.declaredTarget?.trim();if(t)return Gg(t,r,"stated on the command line");let n=e.projectRoot?.trim();if(!n)return Ug;let o=Ko(n,".red","config.yaml"),s=await Ng(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=Dg(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Gg(i,r,o)}function Gg(e,r,t){let n=`${Rn}: ${e} (${t})`;try{return{needed:Lg(jg(e),r),declaredBy:n}}catch{return{needed:!1,declaredBy:`${n} \u2014 off-contract, so it names no lane under the home`}}}function Bg(e){let r=[_T(e),RT(e),wT(e),ET(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 _T(e){let r=e.homeNeed??Ug;if(!e.homePresent)return r.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${r.declaredBy}`,fix:rl}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${r.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??qe;return t!==qe?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${qe.toString(8)}`,fix:`${rl} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function RT(e){return Ne(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 \`${ur("red-skills-redskilled",["provision"])}\``}}function wT(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:`${rl} \u2014 it starts the daemon and waits for the socket`}}function ET(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 Hg(e={}){let r=e.env??process.env,t=e.homeDir??tl(),n=e.paths??Ue({env:r}),o=Ge(t),[s,i,a]=await Promise.all([ol(o),We(n.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):nl({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:a,entry:tr(e.entryOverride??{},{env:r,...e.entryLookup}),socketPath:n.socketPath,reachable:i,supervisorUnit:await ST(TT(e,r,t),r)}}var vT="redskilled.service";function qg(e){return Ko(e,"systemd","user",vT)}function Vg(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(`
|
|
111
|
+
`)}async function Kg(e){let r=qg(e.configHome);return await ol(r)!==void 0?{path:r,status:"already-present"}:(await Cg(Fg(r),{recursive:!0}),await Mg(r,e.unit,"utf8"),{path:r,status:"installed"})}async function ST(e,r){if(process.platform!=="linux")return"unsupported";try{return await Ng(qg(e),"utf8"),"installed"}catch{return r.XDG_RUNTIME_DIR?"absent":"unsupported"}}function TT(e,r,t){return e.configHome??r.XDG_CONFIG_HOME?.trim()??Ko(t,".config")}async function ol(e){try{return(await kT(e)).mode&511}catch{return}}import{readdir as zg,rm as xT,stat as PT}from"node:fs/promises";import{dirname as OT,join as sl}from"node:path";var AT=5*6e4,DT="redskilled.";function jT(e={}){let r=e.env??process.env,t=i=>OT(to({key:"redskilled:reclaim-probe",socketFileName:pt,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 Qg(e={}){let r=e.roots??jT(e),t=e.graceMs??AT,n=e.now??Date.now,o=e.isPidAlive??oe,s=e.answers??GT,i=e.dryRun===!0,a=[];for(let l of r){let d;try{d=(await zg(l,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name)}catch{continue}for(let c of d.sort())a.push(await LT(sl(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 LT(e,r){let t;try{t=(await zg(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:Yg(i),removed:[]}}let n=t.filter(i=>i.startsWith(DT));if(t.length>0&&n.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await IT(sl(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 Jg(e,t,`lease pid ${o.pid} is dead`,r);if(t.includes(pt)&&await r.answers(sl(e,pt)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await $T(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 Jg(e,t,t.length===0?"empty and stale":"no lease and stale",r)}async function Jg(e,r,t,n){if(n.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:r};try{await xT(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:Yg(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:r}}async function IT(e){try{return await bn(e)}catch{return}}async function $T(e,r){try{return Math.max(0,r()-(await PT(e)).mtimeMs)}catch{return}}async function GT(e){try{return(await gn({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function Yg(e){return e instanceof Error?e.message:String(e)}var CT="plugins.dev.statusline",NT="dev.statusline";function MT(e){let r=[],t=a=>{for(let l of[CT,NT]){let d=`${l}.${a}`,c=Xr(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 FT={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 il(e){let{values:r,positionals:t}=rr(e,FT),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 al(e={}){let r=e.configText==null?{config:{},warnings:[]}:MT(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 UT=`Usage: redskilled <command> [options]
|
|
111
112
|
|
|
112
113
|
Commands:
|
|
113
114
|
host-state (default) print the host's state as JSON
|
|
@@ -121,7 +122,7 @@ Commands:
|
|
|
121
122
|
|
|
122
123
|
Run \`redskilled <command> --help\` for a command's own usage.
|
|
123
124
|
\`--version\` (\`-v\`) prints the build stamp; both answer offline.
|
|
124
|
-
`,
|
|
125
|
+
`,BT={serve:`Usage: redskilled serve [options]
|
|
125
126
|
|
|
126
127
|
Runs the daemon in this process. Every path is a flag and none is derived
|
|
127
128
|
(ADR 0130 rule 3); what is absent falls back to the session derivation.
|
|
@@ -206,28 +207,28 @@ Reports every session runtime dir it looked at and why it kept or removed it.
|
|
|
206
207
|
|
|
207
208
|
--dry-run the same report with nothing removed
|
|
208
209
|
--grace-ms <n> how long a dir must be idle before it is reclaimed
|
|
209
|
-
`};function
|
|
210
|
-
`:`${
|
|
211
|
-
`),0}if(
|
|
212
|
-
`);let m=
|
|
213
|
-
`),0}var
|
|
214
|
-
`),0}function
|
|
215
|
-
`),o.running&&!o.stopped?1:0}async function
|
|
216
|
-
`),0;if(o==="install"){let s=await
|
|
217
|
-
`),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await
|
|
218
|
-
`),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function
|
|
219
|
-
`);let a;try{a=await
|
|
220
|
-
`),a=
|
|
210
|
+
`};function HT(e){return e==="--help"||e==="-h"||e==="help"}var qT={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)}},Zg="REDSKILLED_HOST_TOKEN";function vn(){try{let r=WT("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return r===""?null:r}catch{return null}}function ef(e=process.env,r=vn){let t=(e[Zg]??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 VT(e,r=process.env,t=vn,n){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...Xg(e,r,t,n),armTransport:()=>Xg(e,r,t,n)}}function KT(e,r=process.env,t=vn){let n=ef(r,t);if(n==null)return null;let o=r.GITHUB_API_URL;return{transport:oa({token:n.token,...o?{origin:o}:{}})}}function Xg(e,r=process.env,t=vn,n){let o=ef(r,t);if(o==null)return{unconfiguredReason:`no credential names a tracker for this host: ${Zg}, 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:jp({token:o.token,...s?{endpoint:s}:{},...n?{attribution:n}:{}})}}async function JT(e){if(e[0]==="--version"||e[0]==="-v"){let o=xs("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
|
|
211
|
+
`:`${md(o)}
|
|
212
|
+
`),0}if(HT(e[0]))return process.stdout.write(UT),0;let{command:r,args:t}=yd(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(BT[r]),0;if(r==="serve"){let{values:o}=rr(t,qT),s=await xg(En()),i=Pg({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=Jo(Ge(En()),"state"),l=go({path:Jo(a,"github","spend.toonl")}),d=VT(o,process.env,vn,l),c=KT(o),u=Cd({stateRoot:a});process.stderr.write(`${Nd(u)}
|
|
213
|
+
`);let m=jd({lanePath:Ct(a),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),h=await fg({paths:ax(o),idleMs:i.idleMs,ceiling:i.ceiling,daemonVersion:o["daemon-version"]??xs("redskilled").version,deaths:u.attributions,queueDiscovery:d,...c==null?{}:{githubBalance:c},...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let f of["SIGTERM","SIGINT"])process.once(f,()=>void h.stop({reason:"signal",signal:f}).catch(()=>{}));return await h.closed,m.phase("closed"),0}if(r==="stop")return await ZT(t);if(r==="statusline")return await rx(t);if(r==="dashboard")return await dx(t);if(r==="github-spend")return await QT(t);if(r==="unit")return await ex(t);if(r==="provision")return await nx(t);if(r==="reclaim")return await sx(t);let n=await wg(Ue());return process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
214
|
+
`),0}var zT={pool:{kind:"value",coerce:e=>e},hours:{kind:"value",coerce:e=>Number(e)}};async function QT(e,r={}){let{values:t}=rr(e,zT,{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:YT(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??go({path:Jo(Ge(r.homeDir??En()),"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})}
|
|
215
|
+
`),0}function YT(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 XT={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function ZT(e,r={}){let t=r.write??(s=>process.stdout.write(s)),{values:n}=rr(e,XT),o=await Rg(r.paths??Ue(),{...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})}
|
|
216
|
+
`),o.running&&!o.stopped?1:0}async function ex(e,r={}){let t=r.write??(s=>process.stdout.write(s)),n=r.paths??Ue(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(Um(r.unitIO??{}),null,2)}
|
|
217
|
+
`),0;if(o==="install"){let s=await Fm(Nm(n),r.unitIO??{});return t(`${JSON.stringify(s,null,2)}
|
|
218
|
+
`),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await Wm(r.unitIO??{}),null,2)}
|
|
219
|
+
`),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function rx(e,r={}){let t=r.write??(l=>process.stdout.write(l)),n=r.warn??(l=>process.stderr.write(l)),o=il(e),s=rf(r.cwd??process.cwd()),i=al({...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}
|
|
220
|
+
`);let a;try{a=await vg(r.paths??Ue(),i.options,{...r.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(l){n(`redskilled statusline: ${l instanceof Error?l.message:String(l)}
|
|
221
|
+
`),a=Pa({options:i.options,generated_at:(r.now??(()=>new Date().toISOString()))()})}return t(`${a.lines.join(`
|
|
221
222
|
`)}
|
|
222
|
-
`),0}var
|
|
223
|
-
`),u.verdict==="ok"?0:1}var
|
|
224
|
-
`),o.entries.some(s=>s.verdict==="failed")?1:0}function
|
|
225
|
-
`),process.exitCode=1});async function
|
|
226
|
-
`);try{let a=await
|
|
223
|
+
`),0}var tx={"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 nx(e,r={}){let t=r.write??(m=>process.stdout.write(m)),{values:n}=rr(e,tx),o=r.paths??Ue(),s=r.homeDir??En(),i=await nl({homeDir:s,declaredTarget:n.workspace,projectRoot:n.project??r.projectRoot??process.cwd()}),a=n.check||!i.needed?void 0:await Wg(s),l;if(!n.check&&!n["no-start"])try{await Xa(o,r.client??{})}catch(m){l=m instanceof Error?m.message:String(m)}let d=await Hg({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"]&&Ne(d.entry)?await Kg({configHome:r.configHome??ix(),unit:Vg({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=Bg(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}))})}
|
|
224
|
+
`),u.verdict==="ok"?0:1}var ox={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function sx(e,r={}){let t=r.write??(s=>process.stdout.write(s)),{values:n}=rr(e,ox),o=await Qg({...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]}))})}
|
|
225
|
+
`),o.entries.some(s=>s.verdict==="failed")?1:0}function ix(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:Jo(En(),".config")}function rf(e){let r=Vs(e);return r.configText==null?{label:null}:{configText:r.configText,label:Vd(e)}}function ax(e){let r=Ue();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 lx=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;lx&&JT(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
|
|
226
|
+
`),process.exitCode=1});async function dx(e,r={}){let t=r.write??(a=>process.stdout.write(a)),n=r.warn??(a=>process.stderr.write(a)),o=il(e),s=rf(r.cwd??process.cwd()),i=al({...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}
|
|
227
|
+
`);try{let a=await Sg(r.paths??Ue(),{...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(`
|
|
227
228
|
`)}
|
|
228
229
|
`)}catch(a){n(`redskilled dashboard: ${a instanceof Error?a.message:String(a)}
|
|
229
230
|
`),t(`redskilled unreachable \u2014 the host was not asked, so its Workers are unknown
|
|
230
|
-
`)}return 0}export{
|
|
231
|
+
`)}return 0}export{Zg as REDSKILLED_HOST_TOKEN_ENV,UT as REDSKILLED_USAGE,Xg as armRedskilledQueueTransport,ef as resolveRedskilledHostToken,KT as resolveServeGithubBalance,VT as resolveServeQueueDiscovery,dx as runDashboard,QT as runGithubSpend,nx as runProvision,sx as runReclaim,JT as runRedskilledCli,rx as runStatusline,ZT as runStop,ex as runUnit};
|
|
231
232
|
/*! Bundled license information:
|
|
232
233
|
|
|
233
234
|
content-type/dist/index.js:
|