@reddb-io/red-skills 3.9.0 → 3.10.1
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/README.md +4 -5
- package/dist/brain.bundle.min.mjs +1 -1
- package/dist/castle-mcp.bundle.min.mjs +376 -370
- package/dist/code-nav.bundle.min.mjs +1 -1
- package/dist/dev.bundle.min.mjs +663 -659
- package/dist/memory.bundle.min.mjs +1 -1
- package/dist/redskilled.bundle.min.mjs +87 -87
- package/dist/rsp.bundle.min.mjs +1 -1
- 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 ih=Object.create;var Ss=Object.defineProperty;var ah=Object.getOwnPropertyDescriptor;var lh=Object.getOwnPropertyNames;var dh=Object.getPrototypeOf,ch=Object.prototype.hasOwnProperty;var uh=(e,r)=>()=>(e&&(r=e(e=0)),r);var zl=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),ph=(e,r)=>{for(var t in r)Ss(e,t,{get:r[t],enumerable:!0})},mh=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of lh(r))!ch.call(e,o)&&o!==t&&Ss(e,o,{get:()=>r[o],enumerable:!(n=ah(r,o))||n.enumerable});return e};var Ts=(e,r,t)=>(t=e!=null?ih(dh(e)):{},mh(r||!e||!e.__esModule?Ss(t,"default",{value:e,enumerable:!0}):t,e));var Dc={};ph(Dc,{REDSKILLED_BIN_ENV:()=>bi,REDSKILLED_BUNDLE_ASSET:()=>Be,REDSKILLED_ENTRY_UNRESOLVED:()=>Zt,RedskilledDaemonEntryError:()=>en,isRedskilledEntryPath:()=>Ri,isResolvedRedskilledEntry:()=>He,redskilledBundleCacheRoot:()=>wo,redskilledServeArgv:()=>jr,requireRedskilledEntry:()=>Eo,resolveRedskilledEntry:()=>cr});import{existsSync as yb,readdirSync as kb}from"node:fs";import{homedir as bb}from"node:os";import{basename as ki,dirname as yi,join as Se,resolve as Ro}from"node:path";function He(e){return"command"in e}function jr(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 wo(e=process.env){return Ac(e)}function cr(e={},r={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=r.env??process.env,n=r.exists??yb,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[bi];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(i&&Ri(i))return a(Ro(i),"caller-entry");let d=[];for(let[c,u]of Eb(i,r.rootDir,t,r.listDir??Tb))if(d.push(c),n(c))return a(c,u);return{diagnostic:Zt,searched:d,...i?{callerEntry:Ro(i)}:{}}}function Eo(e={},r={}){let t=cr(e,r);if(He(t))return t;throw new en(t)}function Ri(e){let r=ki(e);return r===Be||_i.test(r)||r==="red-skills-redskilled"||r==="red-skills-redskilled.mjs"?!0:r!=="cli.js"&&r!=="cli.mjs"&&r!=="cli.ts"?!1:wb(Ro(e))}function wb(e){let r=yi(e);for(let t=0;t<4;t++){if(ki(r)==="redskilled")return!0;let n=yi(r);if(n===r)return!1;r=n}return!1}function*Eb(e,r,t,n){if(e){let s=yi(Ro(e));yield[Se(s,Be),"caller-sibling-bundle"];let i=_b.exec(ki(e));i&&(yield[Se(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[Se(s,"..","dist",Be),"caller-sibling-bundle"]}for(let s of Rb){let i=t[s];i&&(yield[Se(i,"dist",Be),"plugin-root-bundle"],yield[Se(i,"..","..","dist",Be),"plugin-root-bundle"])}r&&(yield[Se(r,"dist",Be),"repo-bundle"],yield[Se(r,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[Se(r,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=Ac(t);yield[Se(o,Be),"bundle-cache"];for(let s of vb(o,n))yield[Se(o,s),"bundle-cache"]}function Ac(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let r=e.XDG_CACHE_HOME||Se(e.HOME||bb(),".cache");return Se(r,"red-skills","bundles")}function vb(e,r){return r(e).filter(t=>_i.test(t)).sort((t,n)=>Sb(Oc(n),Oc(t)))}function Oc(e){return _i.exec(e)?.[1]??""}function Sb(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 Tb(e){try{return kb(e)}catch{return[]}}var Be,Zt,bi,en,_b,_i,Rb,rr=uh(()=>{"use strict";Be="redskilled.bundle.min.mjs",Zt="redskilled-daemon-entry-unresolved",bi="REDSKILLED_BIN";en=class extends Error{code=Zt;searched;callerEntry;constructor(r){super(`${Zt}: no published ${Be} 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)}};kb=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,bi=/^redskilled-(.+)\.bundle\.min\.mjs$/,bb=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});var qi=Jl((Bi,Hi)=>{(function(e,r){typeof Bi=="object"&&typeof Hi<"u"?Hi.exports=r():typeof define=="function"&&define.amd?define(r):e.Bottleneck=r()})(Bi,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,b,g={}){var _,R,E;for(_ in b)E=b[_],g[_]=(R=D[_])!=null?R:E;return g},n=function(D,b,g={}){var _,R;for(_ in D)R=D[_],b[_]!==void 0&&(g[_]=R);return g},o={load:t,overwrite:n},s;s=class{constructor(b,g){this.incr=b,this.decr=g,this._first=null,this._last=null,this.length=0}push(b){var g;this.length++,typeof this.incr=="function"&&this.incr(),g={value:b,prev:this._last,next:null},this._last!=null?(this._last.next=g,this._last=g):this._first=this._last=g}shift(){var b;if(this._first!=null)return this.length--,typeof this.decr=="function"&&this.decr(),b=this._first.value,(this._first=this._first.next)!=null?this._first.prev=null:this._last=null,b}first(){if(this._first!=null)return this._first.value}getArray(){var b,g,_;for(b=this._first,_=[];b!=null;)_.push((g=b,b=b.next,g.value));return _}forEachShift(b){var g;for(g=this.shift();g!=null;)b(g),g=this.shift()}debug(){var b,g,_,R,E;for(b=this._first,E=[];b!=null;)E.push((g=b,b=b.next,{value:g.value,prev:(_=g.prev)!=null?_.value:void 0,next:(R=g.next)!=null?R.value:void 0}));return E}};var i=s,a;a=class{constructor(b){if(this.instance=b,this._events={},this.instance.on!=null||this.instance.once!=null||this.instance.removeAllListeners!=null)throw new Error("An Emitter already exists for this object");this.instance.on=(g,_)=>this._addListener(g,"many",_),this.instance.once=(g,_)=>this._addListener(g,"once",_),this.instance.removeAllListeners=(g=null)=>g!=null?delete this._events[g]:this._events={}}_addListener(b,g,_){var R;return(R=this._events)[b]==null&&(R[b]=[]),this._events[b].push({cb:_,status:g}),this.instance}listenerCount(b){return this._events[b]!=null?this._events[b].length:0}async trigger(b,...g){var _,R;try{return b!=="debug"&&this.trigger("debug",`Event triggered: ${b}`,g),this._events[b]==null?void 0:(this._events[b]=this._events[b].filter(function(E){return E.status!=="none"}),R=this._events[b].map(async E=>{var x,A;if(E.status!=="none"){E.status==="once"&&(E.status="none");try{return A=typeof E.cb=="function"?E.cb(...g):void 0,typeof A?.then=="function"?await A:A}catch(N){return x=N,this.trigger("error",x),null}}}),(await Promise.all(R)).find(function(E){return E!=null}))}catch(E){return _=E,this.trigger("error",_),null}}};var l=a,d,c,u;d=i,c=l,u=class{constructor(b){var g;this.Events=new c(this),this._length=0,this._lists=function(){var _,R,E;for(E=[],g=_=1,R=b;1<=R?_<=R:_>=R;g=1<=R?++_:--_)E.push(new d(()=>this.incr(),()=>this.decr()));return E}.call(this)}incr(){if(this._length++===0)return this.Events.trigger("leftzero")}decr(){if(--this._length===0)return this.Events.trigger("zero")}push(b){return this._lists[b.options.priority].push(b)}queued(b){return b!=null?this._lists[b].length:this._length}shiftAll(b){return this._lists.forEach(function(g){return g.forEachShift(b)})}getFirst(b=this._lists){var g,_,R;for(g=0,_=b.length;g<_;g++)if(R=b[g],R.length>0)return R;return[]}shiftLastFrom(b){return this.getFirst(this._lists.slice(b).reverse()).shift()}};var m=u,f;f=class extends Error{};var h=f,v,k,T,$,U;$=10,k=5,U=o,v=h,T=class{constructor(b,g,_,R,E,x,A,N){this.task=b,this.args=g,this.rejectOnDrop=E,this.Events=x,this._states=A,this.Promise=N,this.options=U.load(_,R),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===R.id&&(this.options.id=`${this.options.id}-${this._randomIndex()}`),this.promise=new this.Promise((V,z)=>{this._resolve=V,this._reject=z}),this.retryCount=0}_sanitizePriority(b){var g;return g=~~b!==b?k:b,g<0?0:g>$-1?$-1:g}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:b,message:g="This job has been dropped by Bottleneck"}={}){return this._states.remove(this.options.id)?(this.rejectOnDrop&&this._reject(b??new v(g)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0):!1}_assertStatus(b){var g;if(g=this._states.jobStatus(this.options.id),!(g===b||b==="DONE"&&g===null))throw new v(`Invalid job status ${g}, expected ${b}. 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(b,g){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:b,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(b,g,_,R){var E,x,A;this.retryCount===0?(this._assertStatus("RUNNING"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),x={args:this.args,options:this.options,retryCount:this.retryCount},this.Events.trigger("executing",x);try{if(A=await(b!=null?b.schedule(this.options,this.task,...this.args):this.task(...this.args)),g())return this.doDone(x),await R(this.options,x),this._assertStatus("DONE"),this._resolve(A)}catch(N){return E=N,this._onFailure(E,x,g,_,R)}}doExpire(b,g,_){var R,E;return this._states.jobStatus(this.options.id==="RUNNING")&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),E={args:this.args,options:this.options,retryCount:this.retryCount},R=new v(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(R,E,b,g,_)}async _onFailure(b,g,_,R,E){var x,A;if(_())return x=await this.Events.trigger("failed",b,g),x!=null?(A=~~x,this.Events.trigger("retry",`Retrying ${this.options.id} after ${A} ms`,g),this.retryCount++,R(A)):(this.doDone(g),await E(this.options,g),this._assertStatus("DONE"),this._reject(b))}doDone(b){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",b)}};var G=T,H,ee,q;q=o,H=h,ee=class{constructor(b,g,_){this.instance=b,this.storeOptions=g,this.clientId=this.instance._randomIndex(),q.load(_,_,this),this._nextRequest=this._lastReservoirRefresh=this._lastReservoirIncrease=Date.now(),this._running=0,this._done=0,this._unblockTime=0,this.ready=this.Promise.resolve(),this.clients={},this._startHeartbeat()}_startHeartbeat(){var b;return this.heartbeat==null&&(this.storeOptions.reservoirRefreshInterval!=null&&this.storeOptions.reservoirRefreshAmount!=null||this.storeOptions.reservoirIncreaseInterval!=null&&this.storeOptions.reservoirIncreaseAmount!=null)?typeof(b=this.heartbeat=setInterval(()=>{var g,_,R,E,x;if(E=Date.now(),this.storeOptions.reservoirRefreshInterval!=null&&E>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=E,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),this.storeOptions.reservoirIncreaseInterval!=null&&E>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval&&({reservoirIncreaseAmount:g,reservoirIncreaseMaximum:R,reservoir:x}=this.storeOptions,this._lastReservoirIncrease=E,_=R!=null?Math.min(g,R-x):g,_>0))return this.storeOptions.reservoir+=_,this.instance._drainAll(this.computeCapacity())},this.heartbeatInterval)).unref=="function"?b.unref():void 0:clearInterval(this.heartbeat)}async __publish__(b){return await this.yieldLoop(),this.instance.Events.trigger("message",b.toString())}async __disconnect__(b){return await this.yieldLoop(),clearInterval(this.heartbeat),this.Promise.resolve()}yieldLoop(b=0){return new this.Promise(function(g,_){return setTimeout(g,b)})}computePenalty(){var b;return(b=this.storeOptions.penalty)!=null?b:15*this.storeOptions.minTime||5e3}async __updateSettings__(b){return await this.yieldLoop(),q.overwrite(b,b,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__(b){return await this.yieldLoop(),this._nextRequest+this.timeout<b}computeCapacity(){var b,g;return{maxConcurrent:b,reservoir:g}=this.storeOptions,b!=null&&g!=null?Math.min(b-this._running,g):b!=null?b-this._running:g??null}conditionsCheck(b){var g;return g=this.computeCapacity(),g==null||b<=g}async __incrementReservoir__(b){var g;return await this.yieldLoop(),g=this.storeOptions.reservoir+=b,this.instance._drainAll(this.computeCapacity()),g}async __currentReservoir__(){return await this.yieldLoop(),this.storeOptions.reservoir}isBlocked(b){return this._unblockTime>=b}check(b,g){return this.conditionsCheck(b)&&this._nextRequest-g<=0}async __check__(b){var g;return await this.yieldLoop(),g=Date.now(),this.check(b,g)}async __register__(b,g,_){var R,E;return await this.yieldLoop(),R=Date.now(),this.conditionsCheck(g)?(this._running+=g,this.storeOptions.reservoir!=null&&(this.storeOptions.reservoir-=g),E=Math.max(this._nextRequest-R,0),this._nextRequest=R+E+this.storeOptions.minTime,{success:!0,wait:E,reservoir:this.storeOptions.reservoir}):{success:!1}}strategyIsBlock(){return this.storeOptions.strategy===3}async __submit__(b,g){var _,R,E;if(await this.yieldLoop(),this.storeOptions.maxConcurrent!=null&&g>this.storeOptions.maxConcurrent)throw new H(`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(),E=this.storeOptions.highWater!=null&&b===this.storeOptions.highWater&&!this.check(g,R),_=this.strategyIsBlock()&&(E||this.isBlocked(R)),_&&(this._unblockTime=R+this.computePenalty(),this._nextRequest=this._unblockTime+this.storeOptions.minTime,this.instance._dropAllQueued()),{reachedHWM:E,blocked:_,strategy:this.storeOptions.strategy}}async __free__(b,g){return await this.yieldLoop(),this._running-=g,this._done+=g,this.instance._drainAll(this.computeCapacity()),{running:this._running}}};var he=ee,wr,Cn;wr=h,Cn=class{constructor(b){this.status=b,this._jobs={},this.counts=this.status.map(function(){return 0})}next(b){var g,_;if(g=this._jobs[b],_=g+1,g!=null&&_<this.status.length)return this.counts[g]--,this.counts[_]++,this._jobs[b]++;if(g!=null)return this.counts[g]--,delete this._jobs[b]}start(b){var g;return g=0,this._jobs[b]=g,this.counts[g]++}remove(b){var g;return g=this._jobs[b],g!=null&&(this.counts[g]--,delete this._jobs[b]),g!=null}jobStatus(b){var g;return(g=this.status[this._jobs[b]])!=null?g:null}statusJobs(b){var g,_,R,E,x;if(b!=null){if(_=this.status.indexOf(b),_<0)throw new wr(`status must be one of ${this.status.join(", ")}`);R=this._jobs,E=[];for(g in R)x=R[g],x===_&&E.push(g);return E}else return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce((b,g,_)=>(b[this.status[_]]=g,b),{})}};var Nn=Cn,Mn,Br;Mn=i,Br=class{constructor(b,g){this.schedule=this.schedule.bind(this),this.name=b,this.Promise=g,this._running=0,this._queue=new Mn}isEmpty(){return this._queue.length===0}async _tryToRun(){var b,g,_,R,E,x,A;if(this._running<1&&this._queue.length>0)return this._running++,{task:A,args:b,resolve:E,reject:R}=this._queue.shift(),g=await async function(){try{return x=await A(...b),function(){return E(x)}}catch(N){return _=N,function(){return R(_)}}}(),this._running--,this._tryToRun(),g()}schedule(b,...g){var _,R,E;return E=R=null,_=new this.Promise(function(x,A){return E=x,R=A}),this._queue.push({task:b,args:g,resolve:E,reject:R}),this._tryToRun(),_}};var ps=Br,vt="2.19.5",Fn={version:vt},Wn=Object.freeze({version:vt,default:Fn}),St=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Tt=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Un=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),xt,Bn,Hn,Pt,Ot,Er;Er=o,xt=l,Pt=St,Hn=Tt,Ot=Un,Bn=function(){class D{constructor(g={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=g,Er.load(this.limiterOptions,this.defaults,this),this.Events=new xt(this),this.instances={},this.Bottleneck=W,this._startAutoCleanup(),this.sharedConnection=this.connection!=null,this.connection==null&&(this.limiterOptions.datastore==="redis"?this.connection=new Pt(Object.assign({},this.limiterOptions,{Events:this.Events})):this.limiterOptions.datastore==="ioredis"&&(this.connection=new Hn(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(g=""){var _;return(_=this.instances[g])!=null?_:(()=>{var R;return R=this.instances[g]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${g}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",R,g),R})()}async deleteKey(g=""){var _,R;return R=this.instances[g],this.connection&&(_=await this.connection.__runCommand__(["del",...Ot.allKeys(`${this.id}-${g}`)])),R!=null&&(delete this.instances[g],await R.disconnect()),R!=null||_>0}limiters(){var g,_,R,E;_=this.instances,R=[];for(g in _)E=_[g],R.push({key:g,limiter:E});return R}keys(){return Object.keys(this.instances)}async clusterKeys(){var g,_,R,E,x,A,N,V,z;if(this.connection==null)return this.Promise.resolve(this.keys());for(A=[],g=null,z=`b_${this.id}-`.length,_=9;g!==0;)for([V,R]=await this.connection.__runCommand__(["scan",g??0,"match",`b_${this.id}-*_settings`,"count",1e4]),g=~~V,E=0,N=R.length;E<N;E++)x=R[E],A.push(x.slice(z,-_));return A}_startAutoCleanup(){var g;return clearInterval(this.interval),typeof(g=this.interval=setInterval(async()=>{var _,R,E,x,A,N;A=Date.now(),E=this.instances,x=[];for(R in E){N=E[R];try{await N._store.__groupCheck__(A)?x.push(this.deleteKey(R)):x.push(void 0)}catch(V){_=V,x.push(N.Events.trigger("error",_))}}return x},this.timeout/2)).unref=="function"?g.unref():void 0}updateSettings(g={}){if(Er.overwrite(g,this.defaults,this),Er.overwrite(g,g,this.limiterOptions),g.timeout!=null)return this._startAutoCleanup()}disconnect(g=!0){var _;if(!this.sharedConnection)return(_=this.connection)!=null?_.disconnect(g):void 0}}return D.prototype.defaults={timeout:1e3*60*5,connection:null,Promise,id:"group-key"},D}.call(e);var be=Bn,At,vr,$e;$e=o,vr=l,At=function(){class D{constructor(g={}){this.options=g,$e.load(this.options,this.defaults,this),this.Events=new vr(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise((g,_)=>this._resolve=g)}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(g){var _;return this._arr.push(g),_=this._promise,this._arr.length===this.maxSize?this._flush():this.maxTime!=null&&this._arr.length===1&&(this._timeout=setTimeout(()=>this._flush(),this.maxTime)),_}}return D.prototype.defaults={maxTime:null,maxSize:null,Promise},D}.call(e);var Hr=At,Dt=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),jt=r(Wn),Lt,qn,C,sr,Pe,Ce,ir,qr,Sr,ar,_e,Vr=[].splice;Ce=10,qn=5,_e=o,ir=m,sr=G,Pe=he,qr=Dt,C=l,Sr=Nn,ar=ps,Lt=function(){class D{constructor(g={},..._){var R,E;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(g,_),_e.load(g,this.instanceDefaults,this),this._queues=new ir(Ce),this._scheduled={},this._states=new Sr(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new C(this),this._submitLock=new ar("submit",this.Promise),this._registerLock=new ar("register",this.Promise),E=_e.load(g,this.storeDefaults,{}),this._store=function(){if(this.datastore==="redis"||this.datastore==="ioredis"||this.connection!=null)return R=_e.load(g,this.redisStoreDefaults,{}),new qr(this,E,R);if(this.datastore==="local")return R=_e.load(g,this.localStoreDefaults,{}),new Pe(this,E,R);throw new D.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}.call(this),this._queues.on("leftzero",()=>{var x;return(x=this._store.heartbeat)!=null&&typeof x.ref=="function"?x.ref():void 0}),this._queues.on("zero",()=>{var x;return(x=this._store.heartbeat)!=null&&typeof x.unref=="function"?x.unref():void 0})}_validateOptions(g,_){if(!(g!=null&&typeof g=="object"&&_.length===0))throw new D.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.")}ready(){return this._store.ready}clients(){return this._store.clients}channel(){return`b_${this.id}`}channel_client(){return`b_${this.id}_${this._store.clientId}`}publish(g){return this._store.__publish__(g)}disconnect(g=!0){return this._store.__disconnect__(g)}chain(g){return this._limiter=g,this}queued(g){return this._queues.queued(g)}clusterQueued(){return this._store.__queued__()}empty(){return this.queued()===0&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(g){return this._states.jobStatus(g)}jobs(g){return this._states.statusJobs(g)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(g=1){return this._store.__check__(g)}_clearGlobalState(g){return this._scheduled[g]!=null?(clearTimeout(this._scheduled[g].expiration),delete this._scheduled[g],!0):!1}async _free(g,_,R,E){var x,A;try{if({running:A}=await this._store.__free__(g,R.weight),this.Events.trigger("debug",`Freed ${R.id}`,E),A===0&&this.empty())return this.Events.trigger("idle")}catch(N){return x=N,this.Events.trigger("error",x)}}_run(g,_,R){var E,x,A;return _.doRun(),E=this._clearGlobalState.bind(this,g),A=this._run.bind(this,g,_),x=this._free.bind(this,g,_),this._scheduled[g]={timeout:setTimeout(()=>_.doExecute(this._limiter,E,A,x),R),expiration:_.options.expiration!=null?setTimeout(function(){return _.doExpire(E,A,x)},R+_.options.expiration):void 0,job:_}}_drainOne(g){return this._registerLock.schedule(()=>{var _,R,E,x,A;return this.queued()===0?this.Promise.resolve(null):(A=this._queues.getFirst(),{options:x,args:_}=E=A.first(),g!=null&&x.weight>g?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${x.id}`,{args:_,options:x}),R=this._randomIndex(),this._store.__register__(R,x.weight,x.expiration).then(({success:N,wait:V,reservoir:z})=>{var Qe;return this.Events.trigger("debug",`Drained ${x.id}`,{success:N,args:_,options:x}),N?(A.shift(),Qe=this.empty(),Qe&&this.Events.trigger("empty"),z===0&&this.Events.trigger("depleted",Qe),this._run(R,E,V),this.Promise.resolve(x.weight)):this.Promise.resolve(null)})))})}_drainAll(g,_=0){return this._drainOne(g).then(R=>{var E;return R!=null?(E=g!=null?g-R:g,this._drainAll(E,_+R)):this.Promise.resolve(_)}).catch(R=>this.Events.trigger("error",R))}_dropAllQueued(g){return this._queues.shiftAll(function(_){return _.doDrop({message:g})})}stop(g={}){var _,R;return g=_e.load(g,this.stopDefaults),R=E=>{var x;return x=()=>{var A;return A=this._states.counts,A[0]+A[1]+A[2]+A[3]===E},new this.Promise((A,N)=>x()?A():this.on("done",()=>{if(x())return this.removeAllListeners("done"),A()}))},_=g.dropWaitingJobs?(this._run=function(E,x){return x.doDrop({message:g.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule(()=>this._submitLock.schedule(()=>{var E,x,A;x=this._scheduled;for(E in x)A=x[E],this.jobStatus(A.job.options.id)==="RUNNING"&&(clearTimeout(A.timeout),clearTimeout(A.expiration),A.job.doDrop({message:g.dropErrorMessage}));return this._dropAllQueued(g.dropErrorMessage),R(0)}))):this.schedule({priority:Ce-1,weight:0},()=>R(1)),this._receive=function(E){return E._reject(new D.prototype.BottleneckError(g.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new D.prototype.BottleneckError("stop() has already been called")),_}async _addToQueue(g){var _,R,E,x,A,N,V;({args:_,options:x}=g);try{({reachedHWM:A,blocked:R,strategy:V}=await this._store.__submit__(this.queued(),x.weight))}catch(z){return E=z,this.Events.trigger("debug",`Could not queue ${x.id}`,{args:_,options:x,error:E}),g.doDrop({error:E}),!1}return R?(g.doDrop(),!0):A&&(N=V===D.prototype.strategy.LEAK?this._queues.shiftLastFrom(x.priority):V===D.prototype.strategy.OVERFLOW_PRIORITY?this._queues.shiftLastFrom(x.priority+1):V===D.prototype.strategy.OVERFLOW?g:void 0,N?.doDrop(),N==null||V===D.prototype.strategy.OVERFLOW)?(N==null&&g.doDrop(),A):(g.doQueue(A,R),this._queues.push(g),await this._drainAll(),A)}_receive(g){return this._states.jobStatus(g.options.id)!=null?(g._reject(new D.prototype.BottleneckError(`A job with the same id already exists (id=${g.options.id})`)),!1):(g.doReceive(),this._submitLock.schedule(this._addToQueue,g))}submit(...g){var _,R,E,x,A,N,V;return typeof g[0]=="function"?(A=g,[R,...g]=A,[_]=Vr.call(g,-1),x=_e.load({},this.jobDefaults)):(N=g,[x,R,...g]=N,[_]=Vr.call(g,-1),x=_e.load(x,this.jobDefaults)),V=(...z)=>new this.Promise(function(Qe,Tr){return R(...z,function(...se){return(se[0]!=null?Tr:Qe)(se)})}),E=new sr(V,g,x,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),E.promise.then(function(z){return typeof _=="function"?_(...z):void 0}).catch(function(z){return Array.isArray(z)?typeof _=="function"?_(...z):void 0:typeof _=="function"?_(z):void 0}),this._receive(E)}schedule(...g){var _,R,E;return typeof g[0]=="function"?([E,...g]=g,R={}):[R,E,...g]=g,_=new sr(E,g,R,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(_),_.promise}wrap(g){var _,R;return _=this.schedule.bind(this),R=function(...E){return _(g.bind(this),...E)},R.withOptions=function(E,...x){return _(E,g,...x)},R}async updateSettings(g={}){return await this._store.__updateSettings__(_e.overwrite(g,this.storeDefaults)),_e.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=C,D.version=D.prototype.version=jt.version,D.strategy=D.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},D.BottleneckError=D.prototype.BottleneckError=h,D.Group=D.prototype.Group=be,D.RedisConnection=D.prototype.RedisConnection=St,D.IORedisConnection=D.prototype.IORedisConnection=Tt,D.Batcher=D.prototype.Batcher=Hr,D.prototype.jobDefaults={priority:qn,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 W=Lt,oe=W;return oe})});var rp=Jl(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.format=MR;Io.parse=FR;var $R=/^[\u0009\u0020-\u007e\u0080-\u00ff]*$/,Qu=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,CR=/[\\"]/g,NR=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,Yu=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function MR(e){let{type:r,parameters:t}=e;if(!r||!NR.test(r))throw new TypeError(`Invalid type: ${r}`);let n=r;if(t)for(let o of Object.keys(t)){if(!Qu.test(o))throw new TypeError(`Invalid parameter name: ${o}`);n+=`; ${o}=${HR(t[o])}`}return n}function FR(e,r){let t=e.length,n=Yi(e,0,t),o=n;n=Qi(e,n,t);let s=Xi(e,o,n),i=e.slice(o,s).toLowerCase(),a=r?.parameters===!1?new Yu:BR(e,n,t);return{type:i,parameters:a}}var Xu=32,Zu=9,ep=59,WR=61,zu=34,UR=92;function BR(e,r,t){let n=new Yu;e:for(;r<t;){r=Yi(e,r+1,t);let o=r;for(;r<t;){let s=e.charCodeAt(r);if(s===ep)continue e;if(s===WR){let i=Xi(e,o,r),a=e.slice(o,i).toLowerCase();if(r=Yi(e,r+1,t),r<t&&e.charCodeAt(r)===zu){r++;let d="";for(;r<t;){let c=e.charCodeAt(r++);if(c===zu){r=Qi(e,r,t),n[a]===void 0&&(n[a]=d);break}if(c===UR&&r<t){d+=e[r++];continue}d+=String.fromCharCode(c)}continue e}let l=r;if(r=Qi(e,r,t),n[a]===void 0){let d=Xi(e,l,r);n[a]=e.slice(l,d)}continue e}r++}}return n}function Qi(e,r,t){for(;r<t&&e.charCodeAt(r)!==ep;)r++;return r}function Yi(e,r,t){for(;r<t;){let n=e.charCodeAt(r);if(n!==Xu&&n!==Zu)break;r++}return r}function Xi(e,r,t){for(;t>r;){let n=e.charCodeAt(t-1);if(n!==Xu&&n!==Zu)break;t--}return t}function HR(e){if(Qu.test(e))return e;if($R.test(e))return`"${e.replace(CR,"\\$&")}"`;throw new TypeError(`Invalid parameter value: ${e}`)}});import{execFileSync as Rx}from"node:child_process";import{homedir as In}from"node:os";import{join as us}from"node:path";var et=class extends Error{constructor(r,t){super(r===0?t:`line ${r}: ${t}`),this.name="ToonError",this.line=r,this.reason=t}},Pr=class extends Error{constructor(r,t){super(r===0?t:`line ${r}: ${t}`),this.name="ToonlError",this.line=r,this.reason=t}};function P(e,r){return new et(e,r)}function M(e,r){return new Pr(e,r)}function rt(e){return e instanceof Pr?e:e instanceof et?new Pr(e.line,e.reason):new Pr(0,String(e&&e.message?e.message:e))}var zl=["type","kind","event"],Or="|",Ql=new Set(["order","discriminator","rows","common"]);var K=",";function so(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 Ne(e){return P(e,"invalid quoted string")}function Ee(e,r){if(e==="")return"";if(e.startsWith('"'))return
|
|
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 Ne(r);let a=Number.parseInt(i,16);if(a>=55296&&a<=57343)throw Ne(r);t+=String.fromCharCode(a),n+=4;break}default:throw Ne(r)}}throw Ne(r)}function
|
|
6
|
+
`)}`),this.name="RedskilledDaemonEntryError",this.searched=r.searched,r.callerEntry!=null&&(this.callerEntry=r.callerEntry)}};_b=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,_i=/^redskilled-(.+)\.bundle\.min\.mjs$/,Rb=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});var qi=zl((Bi,Hi)=>{(function(e,r){typeof Bi=="object"&&typeof Hi<"u"?Hi.exports=r():typeof define=="function"&&define.amd?define(r):e.Bottleneck=r()})(Bi,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,b,g={}){var _,R,E;for(_ in b)E=b[_],g[_]=(R=D[_])!=null?R:E;return g},n=function(D,b,g={}){var _,R;for(_ in D)R=D[_],b[_]!==void 0&&(g[_]=R);return g},o={load:t,overwrite:n},s;s=class{constructor(b,g){this.incr=b,this.decr=g,this._first=null,this._last=null,this.length=0}push(b){var g;this.length++,typeof this.incr=="function"&&this.incr(),g={value:b,prev:this._last,next:null},this._last!=null?(this._last.next=g,this._last=g):this._first=this._last=g}shift(){var b;if(this._first!=null)return this.length--,typeof this.decr=="function"&&this.decr(),b=this._first.value,(this._first=this._first.next)!=null?this._first.prev=null:this._last=null,b}first(){if(this._first!=null)return this._first.value}getArray(){var b,g,_;for(b=this._first,_=[];b!=null;)_.push((g=b,b=b.next,g.value));return _}forEachShift(b){var g;for(g=this.shift();g!=null;)b(g),g=this.shift()}debug(){var b,g,_,R,E;for(b=this._first,E=[];b!=null;)E.push((g=b,b=b.next,{value:g.value,prev:(_=g.prev)!=null?_.value:void 0,next:(R=g.next)!=null?R.value:void 0}));return E}};var i=s,a;a=class{constructor(b){if(this.instance=b,this._events={},this.instance.on!=null||this.instance.once!=null||this.instance.removeAllListeners!=null)throw new Error("An Emitter already exists for this object");this.instance.on=(g,_)=>this._addListener(g,"many",_),this.instance.once=(g,_)=>this._addListener(g,"once",_),this.instance.removeAllListeners=(g=null)=>g!=null?delete this._events[g]:this._events={}}_addListener(b,g,_){var R;return(R=this._events)[b]==null&&(R[b]=[]),this._events[b].push({cb:_,status:g}),this.instance}listenerCount(b){return this._events[b]!=null?this._events[b].length:0}async trigger(b,...g){var _,R;try{return b!=="debug"&&this.trigger("debug",`Event triggered: ${b}`,g),this._events[b]==null?void 0:(this._events[b]=this._events[b].filter(function(E){return E.status!=="none"}),R=this._events[b].map(async E=>{var x,A;if(E.status!=="none"){E.status==="once"&&(E.status="none");try{return A=typeof E.cb=="function"?E.cb(...g):void 0,typeof A?.then=="function"?await A:A}catch(N){return x=N,this.trigger("error",x),null}}}),(await Promise.all(R)).find(function(E){return E!=null}))}catch(E){return _=E,this.trigger("error",_),null}}};var l=a,d,c,u;d=i,c=l,u=class{constructor(b){var g;this.Events=new c(this),this._length=0,this._lists=function(){var _,R,E;for(E=[],g=_=1,R=b;1<=R?_<=R:_>=R;g=1<=R?++_:--_)E.push(new d(()=>this.incr(),()=>this.decr()));return E}.call(this)}incr(){if(this._length++===0)return this.Events.trigger("leftzero")}decr(){if(--this._length===0)return this.Events.trigger("zero")}push(b){return this._lists[b.options.priority].push(b)}queued(b){return b!=null?this._lists[b].length:this._length}shiftAll(b){return this._lists.forEach(function(g){return g.forEachShift(b)})}getFirst(b=this._lists){var g,_,R;for(g=0,_=b.length;g<_;g++)if(R=b[g],R.length>0)return R;return[]}shiftLastFrom(b){return this.getFirst(this._lists.slice(b).reverse()).shift()}};var m=u,f;f=class extends Error{};var h=f,v,k,T,I,F;I=10,k=5,F=o,v=h,T=class{constructor(b,g,_,R,E,x,A,N){this.task=b,this.args=g,this.rejectOnDrop=E,this.Events=x,this._states=A,this.Promise=N,this.options=F.load(_,R),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===R.id&&(this.options.id=`${this.options.id}-${this._randomIndex()}`),this.promise=new this.Promise((V,z)=>{this._resolve=V,this._reject=z}),this.retryCount=0}_sanitizePriority(b){var g;return g=~~b!==b?k:b,g<0?0:g>I-1?I-1:g}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:b,message:g="This job has been dropped by Bottleneck"}={}){return this._states.remove(this.options.id)?(this.rejectOnDrop&&this._reject(b??new v(g)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0):!1}_assertStatus(b){var g;if(g=this._states.jobStatus(this.options.id),!(g===b||b==="DONE"&&g===null))throw new v(`Invalid job status ${g}, expected ${b}. 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(b,g){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:b,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(b,g,_,R){var E,x,A;this.retryCount===0?(this._assertStatus("RUNNING"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),x={args:this.args,options:this.options,retryCount:this.retryCount},this.Events.trigger("executing",x);try{if(A=await(b!=null?b.schedule(this.options,this.task,...this.args):this.task(...this.args)),g())return this.doDone(x),await R(this.options,x),this._assertStatus("DONE"),this._resolve(A)}catch(N){return E=N,this._onFailure(E,x,g,_,R)}}doExpire(b,g,_){var R,E;return this._states.jobStatus(this.options.id==="RUNNING")&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),E={args:this.args,options:this.options,retryCount:this.retryCount},R=new v(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(R,E,b,g,_)}async _onFailure(b,g,_,R,E){var x,A;if(_())return x=await this.Events.trigger("failed",b,g),x!=null?(A=~~x,this.Events.trigger("retry",`Retrying ${this.options.id} after ${A} ms`,g),this.retryCount++,R(A)):(this.doDone(g),await E(this.options,g),this._assertStatus("DONE"),this._reject(b))}doDone(b){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",b)}};var G=T,H,ee,q;q=o,H=h,ee=class{constructor(b,g,_){this.instance=b,this.storeOptions=g,this.clientId=this.instance._randomIndex(),q.load(_,_,this),this._nextRequest=this._lastReservoirRefresh=this._lastReservoirIncrease=Date.now(),this._running=0,this._done=0,this._unblockTime=0,this.ready=this.Promise.resolve(),this.clients={},this._startHeartbeat()}_startHeartbeat(){var b;return this.heartbeat==null&&(this.storeOptions.reservoirRefreshInterval!=null&&this.storeOptions.reservoirRefreshAmount!=null||this.storeOptions.reservoirIncreaseInterval!=null&&this.storeOptions.reservoirIncreaseAmount!=null)?typeof(b=this.heartbeat=setInterval(()=>{var g,_,R,E,x;if(E=Date.now(),this.storeOptions.reservoirRefreshInterval!=null&&E>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=E,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),this.storeOptions.reservoirIncreaseInterval!=null&&E>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval&&({reservoirIncreaseAmount:g,reservoirIncreaseMaximum:R,reservoir:x}=this.storeOptions,this._lastReservoirIncrease=E,_=R!=null?Math.min(g,R-x):g,_>0))return this.storeOptions.reservoir+=_,this.instance._drainAll(this.computeCapacity())},this.heartbeatInterval)).unref=="function"?b.unref():void 0:clearInterval(this.heartbeat)}async __publish__(b){return await this.yieldLoop(),this.instance.Events.trigger("message",b.toString())}async __disconnect__(b){return await this.yieldLoop(),clearInterval(this.heartbeat),this.Promise.resolve()}yieldLoop(b=0){return new this.Promise(function(g,_){return setTimeout(g,b)})}computePenalty(){var b;return(b=this.storeOptions.penalty)!=null?b:15*this.storeOptions.minTime||5e3}async __updateSettings__(b){return await this.yieldLoop(),q.overwrite(b,b,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__(b){return await this.yieldLoop(),this._nextRequest+this.timeout<b}computeCapacity(){var b,g;return{maxConcurrent:b,reservoir:g}=this.storeOptions,b!=null&&g!=null?Math.min(b-this._running,g):b!=null?b-this._running:g??null}conditionsCheck(b){var g;return g=this.computeCapacity(),g==null||b<=g}async __incrementReservoir__(b){var g;return await this.yieldLoop(),g=this.storeOptions.reservoir+=b,this.instance._drainAll(this.computeCapacity()),g}async __currentReservoir__(){return await this.yieldLoop(),this.storeOptions.reservoir}isBlocked(b){return this._unblockTime>=b}check(b,g){return this.conditionsCheck(b)&&this._nextRequest-g<=0}async __check__(b){var g;return await this.yieldLoop(),g=Date.now(),this.check(b,g)}async __register__(b,g,_){var R,E;return await this.yieldLoop(),R=Date.now(),this.conditionsCheck(g)?(this._running+=g,this.storeOptions.reservoir!=null&&(this.storeOptions.reservoir-=g),E=Math.max(this._nextRequest-R,0),this._nextRequest=R+E+this.storeOptions.minTime,{success:!0,wait:E,reservoir:this.storeOptions.reservoir}):{success:!1}}strategyIsBlock(){return this.storeOptions.strategy===3}async __submit__(b,g){var _,R,E;if(await this.yieldLoop(),this.storeOptions.maxConcurrent!=null&&g>this.storeOptions.maxConcurrent)throw new H(`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(),E=this.storeOptions.highWater!=null&&b===this.storeOptions.highWater&&!this.check(g,R),_=this.strategyIsBlock()&&(E||this.isBlocked(R)),_&&(this._unblockTime=R+this.computePenalty(),this._nextRequest=this._unblockTime+this.storeOptions.minTime,this.instance._dropAllQueued()),{reachedHWM:E,blocked:_,strategy:this.storeOptions.strategy}}async __free__(b,g){return await this.yieldLoop(),this._running-=g,this._done+=g,this.instance._drainAll(this.computeCapacity()),{running:this._running}}};var he=ee,wr,Cn;wr=h,Cn=class{constructor(b){this.status=b,this._jobs={},this.counts=this.status.map(function(){return 0})}next(b){var g,_;if(g=this._jobs[b],_=g+1,g!=null&&_<this.status.length)return this.counts[g]--,this.counts[_]++,this._jobs[b]++;if(g!=null)return this.counts[g]--,delete this._jobs[b]}start(b){var g;return g=0,this._jobs[b]=g,this.counts[g]++}remove(b){var g;return g=this._jobs[b],g!=null&&(this.counts[g]--,delete this._jobs[b]),g!=null}jobStatus(b){var g;return(g=this.status[this._jobs[b]])!=null?g:null}statusJobs(b){var g,_,R,E,x;if(b!=null){if(_=this.status.indexOf(b),_<0)throw new wr(`status must be one of ${this.status.join(", ")}`);R=this._jobs,E=[];for(g in R)x=R[g],x===_&&E.push(g);return E}else return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce((b,g,_)=>(b[this.status[_]]=g,b),{})}};var Nn=Cn,Mn,Br;Mn=i,Br=class{constructor(b,g){this.schedule=this.schedule.bind(this),this.name=b,this.Promise=g,this._running=0,this._queue=new Mn}isEmpty(){return this._queue.length===0}async _tryToRun(){var b,g,_,R,E,x,A;if(this._running<1&&this._queue.length>0)return this._running++,{task:A,args:b,resolve:E,reject:R}=this._queue.shift(),g=await async function(){try{return x=await A(...b),function(){return E(x)}}catch(N){return _=N,function(){return R(_)}}}(),this._running--,this._tryToRun(),g()}schedule(b,...g){var _,R,E;return E=R=null,_=new this.Promise(function(x,A){return E=x,R=A}),this._queue.push({task:b,args:g,resolve:E,reject:R}),this._tryToRun(),_}};var ms=Br,vt="2.19.5",Fn={version:vt},Wn=Object.freeze({version:vt,default:Fn}),St=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Tt=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Un=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),xt,Bn,Hn,Pt,Ot,Er;Er=o,xt=l,Pt=St,Hn=Tt,Ot=Un,Bn=function(){class D{constructor(g={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=g,Er.load(this.limiterOptions,this.defaults,this),this.Events=new xt(this),this.instances={},this.Bottleneck=U,this._startAutoCleanup(),this.sharedConnection=this.connection!=null,this.connection==null&&(this.limiterOptions.datastore==="redis"?this.connection=new Pt(Object.assign({},this.limiterOptions,{Events:this.Events})):this.limiterOptions.datastore==="ioredis"&&(this.connection=new Hn(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(g=""){var _;return(_=this.instances[g])!=null?_:(()=>{var R;return R=this.instances[g]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${g}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",R,g),R})()}async deleteKey(g=""){var _,R;return R=this.instances[g],this.connection&&(_=await this.connection.__runCommand__(["del",...Ot.allKeys(`${this.id}-${g}`)])),R!=null&&(delete this.instances[g],await R.disconnect()),R!=null||_>0}limiters(){var g,_,R,E;_=this.instances,R=[];for(g in _)E=_[g],R.push({key:g,limiter:E});return R}keys(){return Object.keys(this.instances)}async clusterKeys(){var g,_,R,E,x,A,N,V,z;if(this.connection==null)return this.Promise.resolve(this.keys());for(A=[],g=null,z=`b_${this.id}-`.length,_=9;g!==0;)for([V,R]=await this.connection.__runCommand__(["scan",g??0,"match",`b_${this.id}-*_settings`,"count",1e4]),g=~~V,E=0,N=R.length;E<N;E++)x=R[E],A.push(x.slice(z,-_));return A}_startAutoCleanup(){var g;return clearInterval(this.interval),typeof(g=this.interval=setInterval(async()=>{var _,R,E,x,A,N;A=Date.now(),E=this.instances,x=[];for(R in E){N=E[R];try{await N._store.__groupCheck__(A)?x.push(this.deleteKey(R)):x.push(void 0)}catch(V){_=V,x.push(N.Events.trigger("error",_))}}return x},this.timeout/2)).unref=="function"?g.unref():void 0}updateSettings(g={}){if(Er.overwrite(g,this.defaults,this),Er.overwrite(g,g,this.limiterOptions),g.timeout!=null)return this._startAutoCleanup()}disconnect(g=!0){var _;if(!this.sharedConnection)return(_=this.connection)!=null?_.disconnect(g):void 0}}return D.prototype.defaults={timeout:1e3*60*5,connection:null,Promise,id:"group-key"},D}.call(e);var be=Bn,At,vr,$e;$e=o,vr=l,At=function(){class D{constructor(g={}){this.options=g,$e.load(this.options,this.defaults,this),this.Events=new vr(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise((g,_)=>this._resolve=g)}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(g){var _;return this._arr.push(g),_=this._promise,this._arr.length===this.maxSize?this._flush():this.maxTime!=null&&this._arr.length===1&&(this._timeout=setTimeout(()=>this._flush(),this.maxTime)),_}}return D.prototype.defaults={maxTime:null,maxSize:null,Promise},D}.call(e);var Hr=At,Dt=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),jt=r(Wn),Lt,qn,C,sr,Pe,Ce,ir,qr,Sr,ar,_e,Vr=[].splice;Ce=10,qn=5,_e=o,ir=m,sr=G,Pe=he,qr=Dt,C=l,Sr=Nn,ar=ms,Lt=function(){class D{constructor(g={},..._){var R,E;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(g,_),_e.load(g,this.instanceDefaults,this),this._queues=new ir(Ce),this._scheduled={},this._states=new Sr(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new C(this),this._submitLock=new ar("submit",this.Promise),this._registerLock=new ar("register",this.Promise),E=_e.load(g,this.storeDefaults,{}),this._store=function(){if(this.datastore==="redis"||this.datastore==="ioredis"||this.connection!=null)return R=_e.load(g,this.redisStoreDefaults,{}),new qr(this,E,R);if(this.datastore==="local")return R=_e.load(g,this.localStoreDefaults,{}),new Pe(this,E,R);throw new D.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}.call(this),this._queues.on("leftzero",()=>{var x;return(x=this._store.heartbeat)!=null&&typeof x.ref=="function"?x.ref():void 0}),this._queues.on("zero",()=>{var x;return(x=this._store.heartbeat)!=null&&typeof x.unref=="function"?x.unref():void 0})}_validateOptions(g,_){if(!(g!=null&&typeof g=="object"&&_.length===0))throw new D.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.")}ready(){return this._store.ready}clients(){return this._store.clients}channel(){return`b_${this.id}`}channel_client(){return`b_${this.id}_${this._store.clientId}`}publish(g){return this._store.__publish__(g)}disconnect(g=!0){return this._store.__disconnect__(g)}chain(g){return this._limiter=g,this}queued(g){return this._queues.queued(g)}clusterQueued(){return this._store.__queued__()}empty(){return this.queued()===0&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(g){return this._states.jobStatus(g)}jobs(g){return this._states.statusJobs(g)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(g=1){return this._store.__check__(g)}_clearGlobalState(g){return this._scheduled[g]!=null?(clearTimeout(this._scheduled[g].expiration),delete this._scheduled[g],!0):!1}async _free(g,_,R,E){var x,A;try{if({running:A}=await this._store.__free__(g,R.weight),this.Events.trigger("debug",`Freed ${R.id}`,E),A===0&&this.empty())return this.Events.trigger("idle")}catch(N){return x=N,this.Events.trigger("error",x)}}_run(g,_,R){var E,x,A;return _.doRun(),E=this._clearGlobalState.bind(this,g),A=this._run.bind(this,g,_),x=this._free.bind(this,g,_),this._scheduled[g]={timeout:setTimeout(()=>_.doExecute(this._limiter,E,A,x),R),expiration:_.options.expiration!=null?setTimeout(function(){return _.doExpire(E,A,x)},R+_.options.expiration):void 0,job:_}}_drainOne(g){return this._registerLock.schedule(()=>{var _,R,E,x,A;return this.queued()===0?this.Promise.resolve(null):(A=this._queues.getFirst(),{options:x,args:_}=E=A.first(),g!=null&&x.weight>g?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${x.id}`,{args:_,options:x}),R=this._randomIndex(),this._store.__register__(R,x.weight,x.expiration).then(({success:N,wait:V,reservoir:z})=>{var Qe;return this.Events.trigger("debug",`Drained ${x.id}`,{success:N,args:_,options:x}),N?(A.shift(),Qe=this.empty(),Qe&&this.Events.trigger("empty"),z===0&&this.Events.trigger("depleted",Qe),this._run(R,E,V),this.Promise.resolve(x.weight)):this.Promise.resolve(null)})))})}_drainAll(g,_=0){return this._drainOne(g).then(R=>{var E;return R!=null?(E=g!=null?g-R:g,this._drainAll(E,_+R)):this.Promise.resolve(_)}).catch(R=>this.Events.trigger("error",R))}_dropAllQueued(g){return this._queues.shiftAll(function(_){return _.doDrop({message:g})})}stop(g={}){var _,R;return g=_e.load(g,this.stopDefaults),R=E=>{var x;return x=()=>{var A;return A=this._states.counts,A[0]+A[1]+A[2]+A[3]===E},new this.Promise((A,N)=>x()?A():this.on("done",()=>{if(x())return this.removeAllListeners("done"),A()}))},_=g.dropWaitingJobs?(this._run=function(E,x){return x.doDrop({message:g.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule(()=>this._submitLock.schedule(()=>{var E,x,A;x=this._scheduled;for(E in x)A=x[E],this.jobStatus(A.job.options.id)==="RUNNING"&&(clearTimeout(A.timeout),clearTimeout(A.expiration),A.job.doDrop({message:g.dropErrorMessage}));return this._dropAllQueued(g.dropErrorMessage),R(0)}))):this.schedule({priority:Ce-1,weight:0},()=>R(1)),this._receive=function(E){return E._reject(new D.prototype.BottleneckError(g.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new D.prototype.BottleneckError("stop() has already been called")),_}async _addToQueue(g){var _,R,E,x,A,N,V;({args:_,options:x}=g);try{({reachedHWM:A,blocked:R,strategy:V}=await this._store.__submit__(this.queued(),x.weight))}catch(z){return E=z,this.Events.trigger("debug",`Could not queue ${x.id}`,{args:_,options:x,error:E}),g.doDrop({error:E}),!1}return R?(g.doDrop(),!0):A&&(N=V===D.prototype.strategy.LEAK?this._queues.shiftLastFrom(x.priority):V===D.prototype.strategy.OVERFLOW_PRIORITY?this._queues.shiftLastFrom(x.priority+1):V===D.prototype.strategy.OVERFLOW?g:void 0,N?.doDrop(),N==null||V===D.prototype.strategy.OVERFLOW)?(N==null&&g.doDrop(),A):(g.doQueue(A,R),this._queues.push(g),await this._drainAll(),A)}_receive(g){return this._states.jobStatus(g.options.id)!=null?(g._reject(new D.prototype.BottleneckError(`A job with the same id already exists (id=${g.options.id})`)),!1):(g.doReceive(),this._submitLock.schedule(this._addToQueue,g))}submit(...g){var _,R,E,x,A,N,V;return typeof g[0]=="function"?(A=g,[R,...g]=A,[_]=Vr.call(g,-1),x=_e.load({},this.jobDefaults)):(N=g,[x,R,...g]=N,[_]=Vr.call(g,-1),x=_e.load(x,this.jobDefaults)),V=(...z)=>new this.Promise(function(Qe,Tr){return R(...z,function(...se){return(se[0]!=null?Tr:Qe)(se)})}),E=new sr(V,g,x,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),E.promise.then(function(z){return typeof _=="function"?_(...z):void 0}).catch(function(z){return Array.isArray(z)?typeof _=="function"?_(...z):void 0:typeof _=="function"?_(z):void 0}),this._receive(E)}schedule(...g){var _,R,E;return typeof g[0]=="function"?([E,...g]=g,R={}):[R,E,...g]=g,_=new sr(E,g,R,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(_),_.promise}wrap(g){var _,R;return _=this.schedule.bind(this),R=function(...E){return _(g.bind(this),...E)},R.withOptions=function(E,...x){return _(E,g,...x)},R}async updateSettings(g={}){return await this._store.__updateSettings__(_e.overwrite(g,this.storeDefaults)),_e.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=C,D.version=D.prototype.version=jt.version,D.strategy=D.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},D.BottleneckError=D.prototype.BottleneckError=h,D.Group=D.prototype.Group=be,D.RedisConnection=D.prototype.RedisConnection=St,D.IORedisConnection=D.prototype.IORedisConnection=Tt,D.Batcher=D.prototype.Batcher=Hr,D.prototype.jobDefaults={priority:qn,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 U=Lt,oe=U;return oe})});var op=zl($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.format=FR;$o.parse=WR;var CR=/^[\u0009\u0020-\u007e\u0080-\u00ff]*$/,Zu=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,NR=/[\\"]/g,MR=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,ep=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function FR(e){let{type:r,parameters:t}=e;if(!r||!MR.test(r))throw new TypeError(`Invalid type: ${r}`);let n=r;if(t)for(let o of Object.keys(t)){if(!Zu.test(o))throw new TypeError(`Invalid parameter name: ${o}`);n+=`; ${o}=${qR(t[o])}`}return n}function WR(e,r){let t=e.length,n=Yi(e,0,t),o=n;n=Qi(e,n,t);let s=Xi(e,o,n),i=e.slice(o,s).toLowerCase(),a=r?.parameters===!1?new ep:HR(e,n,t);return{type:i,parameters:a}}var rp=32,tp=9,np=59,UR=61,Xu=34,BR=92;function HR(e,r,t){let n=new ep;e:for(;r<t;){r=Yi(e,r+1,t);let o=r;for(;r<t;){let s=e.charCodeAt(r);if(s===np)continue e;if(s===UR){let i=Xi(e,o,r),a=e.slice(o,i).toLowerCase();if(r=Yi(e,r+1,t),r<t&&e.charCodeAt(r)===Xu){r++;let d="";for(;r<t;){let c=e.charCodeAt(r++);if(c===Xu){r=Qi(e,r,t),n[a]===void 0&&(n[a]=d);break}if(c===BR&&r<t){d+=e[r++];continue}d+=String.fromCharCode(c)}continue e}let l=r;if(r=Qi(e,r,t),n[a]===void 0){let d=Xi(e,l,r);n[a]=e.slice(l,d)}continue e}r++}}return n}function Qi(e,r,t){for(;r<t&&e.charCodeAt(r)!==np;)r++;return r}function Yi(e,r,t){for(;r<t;){let n=e.charCodeAt(r);if(n!==rp&&n!==tp)break;r++}return r}function Xi(e,r,t){for(;t>r;){let n=e.charCodeAt(t-1);if(n!==rp&&n!==tp)break;t--}return t}function qR(e){if(Zu.test(e))return e;if(CR.test(e))return`"${e.replace(NR,"\\$&")}"`;throw new TypeError(`Invalid parameter value: ${e}`)}});import{execFileSync as wx}from"node:child_process";import{homedir as In}from"node:os";import{join as ps}from"node:path";var et=class extends Error{constructor(r,t){super(r===0?t:`line ${r}: ${t}`),this.name="ToonError",this.line=r,this.reason=t}},Pr=class extends Error{constructor(r,t){super(r===0?t:`line ${r}: ${t}`),this.name="ToonlError",this.line=r,this.reason=t}};function P(e,r){return new et(e,r)}function M(e,r){return new Pr(e,r)}function rt(e){return e instanceof Pr?e:e instanceof et?new Pr(e.line,e.reason):new Pr(0,String(e&&e.message?e.message:e))}var Ql=["type","kind","event"],Or="|",Yl=new Set(["order","discriminator","rows","common"]);var K=",";function so(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 Ne(e){return P(e,"invalid quoted string")}function Ee(e,r){if(e==="")return"";if(e.startsWith('"'))return ed(e,r);if(e.includes('"'))throw Ne(r);return e==="true"?!0:e==="false"?!1:e==="null"?null:gh(e)?Number(e):e}function Oe(e,r){let t=e.trim();if(t.startsWith('"'))return[ed(t,r),!0];if(t.includes('"')||/\s/.test(t))throw P(r,"expected non-empty field name");return[t,!1]}var Xl=/["\\\u0000-\u0008\u000a-\u001f]/g;function ed(e,r){if(e.charCodeAt(0)!==34)throw Ne(r);let t="",n=1;for(;n<e.length;){Xl.lastIndex=n;let o=Xl.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(n,o.index);throw Ne(r)}if(o[0]!=="\\")throw Ne(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 Ne(r);let a=Number.parseInt(i,16);if(a>=55296&&a<=57343)throw Ne(r);t+=String.fromCharCode(a),n+=4;break}default:throw Ne(r)}}throw Ne(r)}function rd(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 Ne(t);r=o+2;continue}if(n===-1)throw Ne(t);return n+1}}function Ae(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=rd(e,i+1,t);else break}return n.push(e.slice(o).trim()),n}function de(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=rd(e,o+1,t)}return-1}function gh(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function fh(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function hh(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw P(0,"number is not representable in TOON");return String(e)}function Me(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function ce(e,r){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return hh(e);if(typeof e=="string")return kh(e,r);throw P(0,"not a primitive")}function yh(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function te(e){return yh(e)?e:io(e)}function kh(e,r){return xs(e,r)?io(e):e}function xs(e,r){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||fh(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(r)||e.startsWith("-")}var Zl=/["\\\u0000-\u001f]/g;function io(e){let r='"',t=0;Zl.lastIndex=0;let n;for(;(n=Zl.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 De(e,r,t){Object.defineProperty(e,r,{value:t,writable:!0,enumerable:!0,configurable:!0})}function Y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function td(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 nd(e,r){let t=[],n=!1;return so(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 P(i,"invalid indentation");if(r.strict&&a%r.indent!==0)throw P(i,"invalid indentation");let l=Math.floor(a/r.indent);Fe(l,i,r),t.push({number:i,depth:l,content:o.slice(a),blankBefore:n}),n=!1}),t}function Fe(e,r,t){if(t.maxDepth!==0&&e>t.maxDepth)throw P(r,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function Vt(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,Fe(n,r,t)):i==="}"&&(n=Math.max(0,n-1)))}}function id(e){if(!Y(e)||Object.keys(e).length===0)return e;let r={};for(let[t,n]of Object.entries(e)){let o=bh(n,1);if(o===void 0)return e;De(r,t,o)}return r}function bh(e,r){if(!Y(e)||!_h(e))return;let{order:t,discriminator:n,rows:o}=e;if(typeof t!="string"||typeof n!="string"||!Number.isSafeInteger(o)||o<0)throw ie(r);let s=Rh(t,o,r),i=e.common,a=i===void 0?Array.from({length:o},()=>({})):i;if(!Array.isArray(a)||a.length!==o||!a.every(Y))throw ad(r);let l=new Map;for(let[u,m]of Object.entries(e))if(!Yl.has(u)){if(!Array.isArray(m)||!m.every(Y))throw ie(r);l.set(u,m)}if(l.size===0)throw ie(r);let d=new Map,c=s.map((u,m)=>{let f=l.get(u);if(f===void 0)throw Ps(r);let h=d.get(u)??0,v=f[h];if(v===void 0)throw Ps(r);return d.set(u,h+1),wh(n,u,a[m],v,r)});for(let[u,m]of l)if((d.get(u)??0)!==m.length)throw Ps(r);return c}function _h(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function Rh(e,r,t){if(!e.startsWith("cycle("))throw ie(t);let n=e.slice(6),o=n.indexOf(")*");if(o===-1)throw ie(t);let s=n.slice(0,o),i=n.slice(o+2);if(s===""||i.includes("+tail("))throw ie(t);let a=s.split(",").map(c=>Th(c,t));if(a.some(c=>c===""))throw ie(t);let l=Sh(i,t),d=a.length*l;if(!Number.isSafeInteger(d))throw ie(t);if(d!==r)throw ad(t);return Array.from({length:d},(c,u)=>a[u%a.length])}function wh(e,r,t,n,o){let s={};De(s,e,r);for(let[i,a]of Object.entries(t??{})){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw ie(o);De(s,i,a)}for(let[i,a]of Object.entries(Eh(n,o))){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw ie(o);De(s,i,a)}return s}function Eh(e,r){let t={};for(let[n,o]of Object.entries(e))vh(t,n.split("."),o,r);return ao(t,r)}function vh(e,r,t,n){if(r.some(s=>s===""))throw ie(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],!Y(o))throw ie(n)}}function ao(e,r){return Array.isArray(e)?e.map(t=>ao(t,r)):Y(e)?Number.isSafeInteger(e.length)&&e.length>=0?Array.from({length:e.length},(t,n)=>{if(!Object.prototype.hasOwnProperty.call(e,String(n)))throw ie(r);return ao(e[String(n)],r)}):Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ao(n,r)])):e}function Sh(e,r){if(e===""||e.length>1&&e.startsWith("0")||!/^[0-9]+$/.test(e))throw ie(r);let t=Number(e);if(!Number.isSafeInteger(t))throw ie(r);return t}function Th(e,r){try{return decodeURIComponent(e)}catch{throw ie(r)}}function od(e){return encodeURIComponent(e)}function ie(e){return P(e,"invalid cyclic array wire")}function ad(e){return P(e,"cyclic array length mismatch")}function Ps(e){return P(e,"cyclic array group length mismatch")}function ld(e){if(!Y(e))return;let r=Object.entries(e);if(r.length===0)return;let t=[];for(let[o,s]of r){let i=xh(s);if(i===void 0)return;t.push([o,i])}let n=[];for(let[o,s]of t)Dh(n,o,s);return n.join("")}function xh(e){if(!Array.isArray(e)||e.length===0||!e.every(Y))return;let r=Ph(e);if(r===void 0)return;let t=e.map(a=>a[r]),n=Oh(t);if(n===void 0)return;let o=Ah(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)&&!Os(u,c,d))return;s.get(l).push(d)}let i=[];for(let a of n.cycle){let l=s.get(a),d=Lh(l);if(d===void 0||d.length===0)return;i.push({fields:d,label:a,rows:l})}return{common:o,commonRows:e.map(a=>Object.fromEntries(o.map(l=>[l,a[l]]))),discriminator:r,groups:i,order:n,rows:e}}function Ph(e){return Ql.find(r=>e.every(t=>typeof t[r]=="string"))}function Oh(e){if(!(e.length<12))for(let r=2;r<=Math.min(8,Math.floor(e.length/3));r+=1){if(e.length%r!==0)continue;let t=e.slice(0,r);if(new Set(t).size<2||!e.every((i,a)=>i===t[a%r]))continue;let n=e.length/r;if(n<3)continue;let o=e.map(od).join(","),s=`cycle(${t.map(od).join(",")})*${n}`;if(s.length<=o.length*.4)return{cycle:t,encoded:s,repeats:n}}}function Ah(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(!jh(s)||!e.every(i=>Object.prototype.hasOwnProperty.call(i,s))||!e.every(i=>Me(i[s])))break;t.push(s)}return t}function Dh(e,r,t){e.push(te(r),`:
|
|
9
9
|
`),e.push(" order: ",ce(t.order.encoded,Or),`
|
|
10
10
|
`),e.push(" discriminator: ",ce(t.discriminator,Or),`
|
|
11
11
|
`),e.push(" rows: ",String(t.rows.length),`
|
|
12
|
-
`),t.common.length>0&&
|
|
12
|
+
`),t.common.length>0&&sd(e,"common",t.common,t.commonRows);for(let n of t.groups)sd(e,n.label,n.fields,n.rows)}function sd(e,r,t,n){e.push(" ",te(r),"[",String(n.length),Or,"]{",t.map(te).join(Or),`}:
|
|
13
13
|
`);for(let o of n)e.push(" ",t.map(s=>ce(o[s],Or)).join(Or),`
|
|
14
|
-
`)}function Ah(e){return e!==""&&Os(e)}function Ps(e,r,t,n=new Set){if(!Os(r))return!1;if(Me(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)=>Ps(s,`${r}.${i}`,t,n));return n.delete(e),o}if(Y(e)){if(n.has(e))return!1;n.add(e);let o=Object.entries(e).every(([s,i])=>!s.includes(".")&&Ps(i,`${r}.${s}`,t,n));return n.delete(e),o}return!1}function Dh(e){let r=Object.keys(e[0]??{});if(e.every(t=>jh(Object.keys(t),r)))return r.every(Os)?r:void 0}function jh(e,r){return e.length===r.length&&e.every((t,n)=>t===r[n])}function Os(e){return e.split(".").every(r=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(r))}function tt(e,r){let t=e[r]??e[e.length-1];return P(t===void 0?1:t.number,"array length mismatch")}function lo(e,r){if(r===-1)throw P(0,"array header missing colon");let t=e.slice(0,r),n=de(t,"[",0);if(n===-1)throw P(0,"invalid array header");let o,s;try{[o,s]=Oe(t.slice(0,n),0)}catch{throw P(0,"invalid array header")}let i=t.slice(n+1),a=i.indexOf("]");if(a===-1)throw P(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 P(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 P(0,"invalid array header")}let m=i.slice(a+1),f,h;if(m==="")f=void 0,h=void 0;else if(m.startsWith("{")&&m.endsWith("}")&&m.length>=2)try{h=Gh(m.slice(1,-1),u),f=Ds(h)}catch(v){throw P(0,v.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw P(0,"invalid array header");return{key:o,keyQuoted:s,len:c,delimiter:u,fields:f,fieldTree:h}}function ld(e){let r=de(e,"{",0);if(r===-1||!e.endsWith("}"))throw P(0,"invalid keyed map header");let t,n;try{[t,n]=Oe(e.slice(0,r),0)}catch{throw P(0,"invalid keyed map header")}if(t===""&&!n)throw P(0,"expected non-empty field name");let o=e.slice(r+1,-1),s=K;(o.startsWith("|")||o.startsWith(" "))&&(s=o[0],o=o.slice(1));let i;try{i=Lh(o,s,s)}catch(a){throw P(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:n,delimiter:s,fields:i}}function Lh(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 P(0,"invalid array header");let u=o;for(;o<e.length;){let h=e[o];if(h==='"'){i();continue}if(h===r||h==="{"||h==="}"||h==="[")break;o+=1}let[m,f]=Oe(e.slice(u,o),0);if(m===""&&!f)throw P(0,"invalid array header");if(c+=1,e[o]==="["){o+=1;let h=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw P(0,"invalid array header");let v=e.slice(h,o);if(!dd(v,t))throw P(0,"invalid array header");o+=1,n.push({path:[...l,m],listDelimiter:v})}else if(e[o]==="{"){o+=1;let h=n.length;if(s([...l,m],!0),e[o]!=="}"||n.length===h)throw P(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 P(0,"invalid array header");continue}if(d?e[o]==="}":o===e.length)break;throw P(0,"invalid array header")}if(c===0)throw P(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 P(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(cd(n[l].path,n[d].path)||Kt(n[l].path,n[d].path)||Kt(n[d].path,n[l].path))throw P(0,"duplicate key");for(let l of n){let c=l.path.join("\0");if(a.has(c))throw P(0,"duplicate key");a.add(c)}return n}function Gh(e,r){if(r!==K&&e.includes(K)&&(e.includes("[")||e.includes("{")))return As(e,K,r);try{return As(e,r,r)}catch(t){if(r!==K&&t.reason!=="duplicate key")return As(e,K,r);throw t}}function As(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 P(0,"invalid array header");let c=n;for(;n<e.length;){let h=e[n];if(h==='"'){s();continue}if(h===r||h==="{"||h==="}"||h==="[")break;n+=1}let[u,m]=Oe(e.slice(c,n),0);if(u===""&&!m)throw P(0,"invalid array header");let f={key:u};if(e[n]==="["){n+=1;let h=n;for(;n<e.length&&e[n]!=="]";)n+=1;if(n>=e.length)throw P(0,"invalid array header");let v=e.slice(h,n);n+=1;let k=Ih(v);if(k!==void 0){if(k.delimiter!==t)throw P(0,"invalid array header");f.fixedLength=k.len,f.fixedDelimiter=k.delimiter}else if(dd(v,t))f.listDelimiter=v;else throw P(0,"invalid array header")}else if(e[n]==="{"){if(n+=1,f.children=o(!0),e[n]!=="}"||f.children.length===0)throw P(0,"invalid array header");n+=1}if(d.push(f),e[n]===r){if(n+=1,n>=e.length||e[n]==="}")throw P(0,"invalid array header");continue}if(l?e[n]==="}":n===e.length)break;throw P(0,"invalid array header")}if(d.length===0)throw P(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 P(0,"invalid array header");let a=Ds(i);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(cd(a[l].path,a[d].path)||Kt(a[l].path,a[d].path)||Kt(a[d].path,a[l].path))throw P(0,"duplicate key");return i}function Ih(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=K;break;case" ":n=" ";break;case"|":n="|";break;default:return}return{len:Number.parseInt(r,10),delimiter:n}}function Ds(e,r=[]){return e.flatMap(t=>{let n=[...r,t.key];return t.children!==void 0?Ds(t.children,n):[{path:n,listDelimiter:t.listDelimiter}]})}function co(e,r,t){return e.listDelimiter===void 0?Ee(r,t):Ae(r,e.listDelimiter,t).map(n=>Ee(n,t))}function dd(e,r){return e.length===1&&e!==r&&!/[ \t\r\n"[\]{}:]/.test(e)}function cd(e,r){return e.length===r.length&&Kt(e,r)}function Kt(e,r){return r.every((t,n)=>e[n]===t)}function uo(e,r){return P(r,e.reason??String(e.message))}function me(e,r){let t=rd(r),n=td(e,t),o=n[0];if(o===void 0)return{};if(o.depth!==0)throw P(o.number,"invalid indentation");let s=n.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){Vt(o.content,o.number,t);let d;try{d=lo(o.content,de(o.content,":",o.number))}catch(c){if(t.strict)throw uo(c,o.number);d=void 0}if(d!==void 0)return Nh(d,n,t)}if(s&&de(o.content,":",o.number)===-1)return Ee(o.content.trim(),o.number);let i={index:0},a=Ls(n,i,0,t),l=n[i.index];if(l!==void 0)throw P(l.number,"expected end of document");return t.cyclicDiscriminatedArrays?sd(a):a}function Ls(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 P(s.number,"invalid indentation");let{key:i,quoted:a,value:l}=$h(e,r,t,n);yd(o,i,a,l,n,s.number)}return o}function $h(e,r,t,n){let o=e[r.index],s=o.content,i=de(s,":",o.number);if(i===-1)throw P(o.number,"expected `key: value`");let a=s.slice(0,i),l=s.slice(i+1),d=de(a,"[",o.number),c=de(a,"{",o.number);if(c!==-1&&(d===-1||c<d)){Vt(a,o.number,n);let h;try{h=ld(a)}catch(k){if(n.strict)throw uo(k,o.number);r.index+=1;let T=js(e,r,t,l,o.number,n);return{key:a.trim(),quoted:!1,value:T}}if(l.trim()!=="")throw P(o.number,"expected keyed map rows");let v=Ch(h,e,r,t+1,n);return{key:h.key,quoted:h.keyQuoted,value:v}}if(d!==-1){Vt(a,o.number,n);let h;try{h=lo(a,i)}catch(k){if(n.strict)throw uo(k,o.number);r.index+=1;let T=js(e,r,t,l,o.number,n);return{key:a.trim(),quoted:!1,value:T}}if(h.key===""&&!h.keyQuoted)throw P(o.number,"expected non-empty field name");let v=Gs(h,l,e,r,t,n);return{key:h.key,quoted:h.keyQuoted,value:v}}let[u,m]=Oe(a,o.number);if(u===""&&!m)throw P(o.number,"expected non-empty field name");r.index+=1;let f=js(e,r,t,l,o.number,n);return{key:u,quoted:m,value:f}}function js(e,r,t,n,o,s){let i=n.trim();if(i==="[]")return[];if(i!=="")return Ee(i,o);let a=e[r.index];return a!==void 0&&a.depth>t?Ls(e,r,t+1,s):{}}function Ch(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 P(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw P(i.number,"blank line inside keyed map");let a=de(i.content,":",i.number);if(a===-1)throw P(i.number,"expected `key: value`");let[l,d]=Oe(i.content.slice(0,a),i.number);if(l===""&&!d)throw P(i.number,"expected non-empty field name");let c=Ae(i.content.slice(a+1).trim(),e.delimiter,i.number);if(c.length!==e.fields.length)throw P(i.number,"keyed map row length mismatch");let u={};e.fields.forEach((m,f)=>{ot(u,m.path,co(m,c[f],i.number),o,i.number)}),yd(s,l,d,u,o,i.number),t.index+=1}return s}function Nh(e,r,t){let n=r[0],o=de(n.content,":",n.number);if(o===-1)throw P(n.number,"expected `key: value`");let s=n.content.slice(o+1),i={index:0},a=Gs(e,s,r,i,0,t),l=r[i.index];if(l!==void 0)throw P(l.number,"expected end of document");return a}function Gs(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 P(i,"expected tabular rows");return Mh(e,e.fields,t,n,o+1,s)}if(a!==""){let l=Ae(a,e.delimiter,i).map(d=>Ee(d,i));if(l.length!==e.len)throw P(i,"array length mismatch");return l}return Vh(e,t,n,o+1,s)}function Mh(e,r,t,n,o,s){if(e.fieldTree!==void 0&&Hh(e.fieldTree))return Fh(e,t,n,o,s);let i=[];for(;i.length<e.len;){let l=t[n.index];if(l===void 0)throw tt(t,n.index);if(l.depth<o)break;if(l.depth>o)throw P(l.number,"invalid indentation");if(l.blankBefore&&s.strict)throw P(l.number,"blank line inside array");if(!nt(l.content,e.delimiter,l.number))break;let d=Ae(l.content,e.delimiter,l.number);if(d.length!==r.length)throw P(l.number,"array row length mismatch");let c={};r.forEach((u,m)=>{ot(c,u.path,co(u,d[m],l.number),s,l.number)}),i.push(c),n.index+=1}if(i.length!==e.len)throw tt(t,n.index);let a=t[n.index];if(a!==void 0&&a.depth>=o&&nt(a.content,e.delimiter,a.number))throw P(a.number,"array length mismatch");return i}function Fh(e,r,t,n,o){return ud(e.len,e.fieldTree,e.delimiter,r,t,n,o,!0)}function ud(e,r,t,n,o,s,i,a){let l=[],d=md(e,r,t,n,o.index,s,i);for(;l.length<e;){let u=n[o.index];if(u===void 0)throw tt(n,o.index);if(u.depth<s)break;if(u.depth>s)throw P(u.number,"invalid indentation");if(u.blankBefore&&i.strict)throw P(u.number,"blank line inside array");if(!nt(u.content,t,u.number))break;let m=Ae(u.content,t,u.number),f={cellIndex:0,nextIndex:o.index+1,flatWidth:po(r),childTableFields:d},h=pd(r,m,u.number,n,f,s+1,t,i);if(f.cellIndex!==m.length)throw P(u.number,"array row length mismatch");l.push(Bh(r,h,a)),o.index=f.nextIndex}if(l.length!==e)throw tt(n,o.index);let c=n[o.index];if(c!==void 0&&c.depth>=s&&nt(c.content,t,c.number))throw P(c.number,"array length mismatch");return l}function pd(e,r,t,n,o,s,i,a){let l={};return e.forEach((d,c)=>{let u=e.slice(c+1),m=Wh(d,u,r,t,n,o,s,i,a);ot(l,[d.key],m,a,t)}),l}function Wh(e,r,t,n,o,s,i,a,l){if(e.fixedLength!==void 0){if(s.cellIndex+e.fixedLength>t.length)throw P(n,"array row length mismatch");let c=t.slice(s.cellIndex,s.cellIndex+e.fixedLength).map(u=>Ee(u,n));return s.cellIndex+=e.fixedLength,c}if(e.children!==void 0){let c=po(e.children),u=t[s.cellIndex],m=fd(u),f=t.length-s.cellIndex-1,h=o[s.nextIndex],v=h!==void 0&&h.depth===i,k=s.childTableFields===void 0?void 0:s.childTableFields.has(e);if(k===void 0?m!==void 0&&(v||t.length!==s.flatWidth&&f<c+qh(r)):k){if(m===void 0)throw P(n,"array row length mismatch");return s.cellIndex+=1,ud(m,e.children,a,o,{get index(){return s.nextIndex},set index($){s.nextIndex=$}},i,l,!1)}return pd(e.children,t,n,o,s,i,a,l)}let d=t[s.cellIndex];if(d===void 0)throw P(n,"array row length mismatch");return s.cellIndex+=1,co(e,d,n)}function md(e,r,t,n,o,s,i){let a=r.filter(c=>c.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let l,d=1<<a.length;for(let c=0;c<d;c+=1){let u=new Set;a.forEach((f,h)=>{c&1<<h&&u.add(f)});let m=gd(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 gd(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||!nt(m.content,n,m.number))return;let f=Ae(m.content,n,m.number),h=Uh(r,t,f,n,o,l+1,i+1,a);if(h===void 0||o[h.nextIndex]?.depth>i)return;d+=h.consumedChildRows,l=h.nextIndex}let c=o[l];if(c!==void 0&&c.depth>=i&&nt(c.content,n,c.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function Uh(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=fd(t[l]);if(m===void 0)return;l+=1;let f=md(m,u.children,n,o,d,i,a);if(f===void 0)return;let h=gd(m,u.children,f,n,o,d,i,a);if(h===void 0)return;d=h.nextIndex,c+=m+h.consumedChildRows}else l+=po(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:c}}function Bh(e,r,t){return t&&e.length===1&&e[0].fixedLength!==void 0?r[e[0].key]:r}function fd(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 po(e){return e.reduce((r,t)=>r+hd(t),0)}function hd(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?po(e.children):1}function qh(e){return e.reduce((r,t)=>t.children!==void 0?r+1:r+hd(t),0)}function nt(e,r,t){let n=de(e,":",t);if(n===-1)return!0;let o=de(e,r,t);return o===-1?!1:o<n}function Vh(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 tt(r,t.index);if(a.depth>n)throw P(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw P(a.number,"blank line inside array");s.push(Kh(r,t,n,o))}let i=r[t.index];if(i!==void 0&&i.depth>=n)throw P(i.number,"array length mismatch");return s}function Kh(e,r,t,n){let o=e[r.index];if(!o.content.startsWith("-"))throw P(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return r.index+=1,{};if(s.startsWith("[")){let i=de(s,":",o.number);Vt(s,o.number,n);let a;try{a=lo(s,i)}catch{a=void 0}if(a!==void 0){let l=s.slice(i+1);return Gs(a,l,e,r,t,n)}}if(de(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 Ls(i,{index:0},t+1,n)}return r.index+=1,Ee(s,o.number)}function yd(e,r,t,n,o,s){if(o.expandPaths&&!t&&r.includes(".")){let i=r.split(".");if(i.every(Jh)){ot(e,i,n,o,s);return}}ot(e,[r],n,o,s)}function ot(e,r,t,n,o){Fe(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 P(o,"duplicate key");De(e,s,t);return}if(i&&!Y(e[s])){if(n.strict)throw P(o,"path expansion conflict");De(e,s,{})}else i||De(e,s,{});ot(e[s],r.slice(1),t,n,o)}function Jh(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function X(e,r={}){let t=r.maxDepth??1e3,n=r.delimiter??K;if(![K,"|"," "].includes(n))throw P(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=ad(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?Ns(s,void 0,e,0,!1,o):Y(e)?kd(s,e,0,o):s.push(ce(e,n)),s.join("")}function st(e,r){e.push(" ".repeat(r*2))}function kd(e,r,t,n){Fe(t,0,n);for(let[o,s]of Object.entries(r))st(e,t),$s(e,o,s,t,n)}function $s(e,r,t,n,o){if(Fe(n,0,o),Array.isArray(t)){Ns(e,r,t,n,!1,o);return}if(Y(t)){let s=o.keyedMapCollapse?Qh(t,o,n+1):void 0;if(s!==void 0){e.push(te(r),"{",Ms(o.delimiter),s.fields.map(i=>Us(i,o.delimiter)).join(o.delimiter),`}:
|
|
15
|
-
`);for(let[i,a]of Object.entries(t)){st(e,n+1);let l=[];e.push(te(i),": ",s.paths.map(d=>
|
|
14
|
+
`)}function jh(e){return e!==""&&As(e)}function Os(e,r,t,n=new Set){if(!As(r))return!1;if(Me(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)=>Os(s,`${r}.${i}`,t,n));return n.delete(e),o}if(Y(e)){if(n.has(e))return!1;n.add(e);let o=Object.entries(e).every(([s,i])=>!s.includes(".")&&Os(i,`${r}.${s}`,t,n));return n.delete(e),o}return!1}function Lh(e){let r=Object.keys(e[0]??{});if(e.every(t=>Gh(Object.keys(t),r)))return r.every(As)?r:void 0}function Gh(e,r){return e.length===r.length&&e.every((t,n)=>t===r[n])}function As(e){return e.split(".").every(r=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(r))}function tt(e,r){let t=e[r]??e[e.length-1];return P(t===void 0?1:t.number,"array length mismatch")}function lo(e,r){if(r===-1)throw P(0,"array header missing colon");let t=e.slice(0,r),n=de(t,"[",0);if(n===-1)throw P(0,"invalid array header");let o,s;try{[o,s]=Oe(t.slice(0,n),0)}catch{throw P(0,"invalid array header")}let i=t.slice(n+1),a=i.indexOf("]");if(a===-1)throw P(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 P(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 P(0,"invalid array header")}let m=i.slice(a+1),f,h;if(m==="")f=void 0,h=void 0;else if(m.startsWith("{")&&m.endsWith("}")&&m.length>=2)try{h=$h(m.slice(1,-1),u),f=js(h)}catch(v){throw P(0,v.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw P(0,"invalid array header");return{key:o,keyQuoted:s,len:c,delimiter:u,fields:f,fieldTree:h}}function dd(e){let r=de(e,"{",0);if(r===-1||!e.endsWith("}"))throw P(0,"invalid keyed map header");let t,n;try{[t,n]=Oe(e.slice(0,r),0)}catch{throw P(0,"invalid keyed map header")}if(t===""&&!n)throw P(0,"expected non-empty field name");let o=e.slice(r+1,-1),s=K;(o.startsWith("|")||o.startsWith(" "))&&(s=o[0],o=o.slice(1));let i;try{i=Ih(o,s,s)}catch(a){throw P(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:n,delimiter:s,fields:i}}function Ih(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 P(0,"invalid array header");let u=o;for(;o<e.length;){let h=e[o];if(h==='"'){i();continue}if(h===r||h==="{"||h==="}"||h==="[")break;o+=1}let[m,f]=Oe(e.slice(u,o),0);if(m===""&&!f)throw P(0,"invalid array header");if(c+=1,e[o]==="["){o+=1;let h=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw P(0,"invalid array header");let v=e.slice(h,o);if(!cd(v,t))throw P(0,"invalid array header");o+=1,n.push({path:[...l,m],listDelimiter:v})}else if(e[o]==="{"){o+=1;let h=n.length;if(s([...l,m],!0),e[o]!=="}"||n.length===h)throw P(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 P(0,"invalid array header");continue}if(d?e[o]==="}":o===e.length)break;throw P(0,"invalid array header")}if(c===0)throw P(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 P(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(ud(n[l].path,n[d].path)||Kt(n[l].path,n[d].path)||Kt(n[d].path,n[l].path))throw P(0,"duplicate key");for(let l of n){let c=l.path.join("\0");if(a.has(c))throw P(0,"duplicate key");a.add(c)}return n}function $h(e,r){if(r!==K&&e.includes(K)&&(e.includes("[")||e.includes("{")))return Ds(e,K,r);try{return Ds(e,r,r)}catch(t){if(r!==K&&t.reason!=="duplicate key")return Ds(e,K,r);throw t}}function Ds(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 P(0,"invalid array header");let c=n;for(;n<e.length;){let h=e[n];if(h==='"'){s();continue}if(h===r||h==="{"||h==="}"||h==="[")break;n+=1}let[u,m]=Oe(e.slice(c,n),0);if(u===""&&!m)throw P(0,"invalid array header");let f={key:u};if(e[n]==="["){n+=1;let h=n;for(;n<e.length&&e[n]!=="]";)n+=1;if(n>=e.length)throw P(0,"invalid array header");let v=e.slice(h,n);n+=1;let k=Ch(v);if(k!==void 0){if(k.delimiter!==t)throw P(0,"invalid array header");f.fixedLength=k.len,f.fixedDelimiter=k.delimiter}else if(cd(v,t))f.listDelimiter=v;else throw P(0,"invalid array header")}else if(e[n]==="{"){if(n+=1,f.children=o(!0),e[n]!=="}"||f.children.length===0)throw P(0,"invalid array header");n+=1}if(d.push(f),e[n]===r){if(n+=1,n>=e.length||e[n]==="}")throw P(0,"invalid array header");continue}if(l?e[n]==="}":n===e.length)break;throw P(0,"invalid array header")}if(d.length===0)throw P(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 P(0,"invalid array header");let a=js(i);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(ud(a[l].path,a[d].path)||Kt(a[l].path,a[d].path)||Kt(a[d].path,a[l].path))throw P(0,"duplicate key");return i}function Ch(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=K;break;case" ":n=" ";break;case"|":n="|";break;default:return}return{len:Number.parseInt(r,10),delimiter:n}}function js(e,r=[]){return e.flatMap(t=>{let n=[...r,t.key];return t.children!==void 0?js(t.children,n):[{path:n,listDelimiter:t.listDelimiter}]})}function co(e,r,t){return e.listDelimiter===void 0?Ee(r,t):Ae(r,e.listDelimiter,t).map(n=>Ee(n,t))}function cd(e,r){return e.length===1&&e!==r&&!/[ \t\r\n"[\]{}:]/.test(e)}function ud(e,r){return e.length===r.length&&Kt(e,r)}function Kt(e,r){return r.every((t,n)=>e[n]===t)}function uo(e,r){return P(r,e.reason??String(e.message))}function me(e,r){let t=td(r),n=nd(e,t),o=n[0];if(o===void 0)return{};if(o.depth!==0)throw P(o.number,"invalid indentation");let s=n.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){Vt(o.content,o.number,t);let d;try{d=lo(o.content,de(o.content,":",o.number))}catch(c){if(t.strict)throw uo(c,o.number);d=void 0}if(d!==void 0)return Fh(d,n,t)}if(s&&de(o.content,":",o.number)===-1)return Ee(o.content.trim(),o.number);let i={index:0},a=Gs(n,i,0,t),l=n[i.index];if(l!==void 0)throw P(l.number,"expected end of document");return t.cyclicDiscriminatedArrays?id(a):a}function Gs(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 P(s.number,"invalid indentation");let{key:i,quoted:a,value:l}=Nh(e,r,t,n);kd(o,i,a,l,n,s.number)}return o}function Nh(e,r,t,n){let o=e[r.index],s=o.content,i=de(s,":",o.number);if(i===-1)throw P(o.number,"expected `key: value`");let a=s.slice(0,i),l=s.slice(i+1),d=de(a,"[",o.number),c=de(a,"{",o.number);if(c!==-1&&(d===-1||c<d)){Vt(a,o.number,n);let h;try{h=dd(a)}catch(k){if(n.strict)throw uo(k,o.number);r.index+=1;let T=Ls(e,r,t,l,o.number,n);return{key:a.trim(),quoted:!1,value:T}}if(l.trim()!=="")throw P(o.number,"expected keyed map rows");let v=Mh(h,e,r,t+1,n);return{key:h.key,quoted:h.keyQuoted,value:v}}if(d!==-1){Vt(a,o.number,n);let h;try{h=lo(a,i)}catch(k){if(n.strict)throw uo(k,o.number);r.index+=1;let T=Ls(e,r,t,l,o.number,n);return{key:a.trim(),quoted:!1,value:T}}if(h.key===""&&!h.keyQuoted)throw P(o.number,"expected non-empty field name");let v=Is(h,l,e,r,t,n);return{key:h.key,quoted:h.keyQuoted,value:v}}let[u,m]=Oe(a,o.number);if(u===""&&!m)throw P(o.number,"expected non-empty field name");r.index+=1;let f=Ls(e,r,t,l,o.number,n);return{key:u,quoted:m,value:f}}function Ls(e,r,t,n,o,s){let i=n.trim();if(i==="[]")return[];if(i!=="")return Ee(i,o);let a=e[r.index];return a!==void 0&&a.depth>t?Gs(e,r,t+1,s):{}}function Mh(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 P(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw P(i.number,"blank line inside keyed map");let a=de(i.content,":",i.number);if(a===-1)throw P(i.number,"expected `key: value`");let[l,d]=Oe(i.content.slice(0,a),i.number);if(l===""&&!d)throw P(i.number,"expected non-empty field name");let c=Ae(i.content.slice(a+1).trim(),e.delimiter,i.number);if(c.length!==e.fields.length)throw P(i.number,"keyed map row length mismatch");let u={};e.fields.forEach((m,f)=>{ot(u,m.path,co(m,c[f],i.number),o,i.number)}),kd(s,l,d,u,o,i.number),t.index+=1}return s}function Fh(e,r,t){let n=r[0],o=de(n.content,":",n.number);if(o===-1)throw P(n.number,"expected `key: value`");let s=n.content.slice(o+1),i={index:0},a=Is(e,s,r,i,0,t),l=r[i.index];if(l!==void 0)throw P(l.number,"expected end of document");return a}function Is(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 P(i,"expected tabular rows");return Wh(e,e.fields,t,n,o+1,s)}if(a!==""){let l=Ae(a,e.delimiter,i).map(d=>Ee(d,i));if(l.length!==e.len)throw P(i,"array length mismatch");return l}return Jh(e,t,n,o+1,s)}function Wh(e,r,t,n,o,s){if(e.fieldTree!==void 0&&Vh(e.fieldTree))return Uh(e,t,n,o,s);let i=[];for(;i.length<e.len;){let l=t[n.index];if(l===void 0)throw tt(t,n.index);if(l.depth<o)break;if(l.depth>o)throw P(l.number,"invalid indentation");if(l.blankBefore&&s.strict)throw P(l.number,"blank line inside array");if(!nt(l.content,e.delimiter,l.number))break;let d=Ae(l.content,e.delimiter,l.number);if(d.length!==r.length)throw P(l.number,"array row length mismatch");let c={};r.forEach((u,m)=>{ot(c,u.path,co(u,d[m],l.number),s,l.number)}),i.push(c),n.index+=1}if(i.length!==e.len)throw tt(t,n.index);let a=t[n.index];if(a!==void 0&&a.depth>=o&&nt(a.content,e.delimiter,a.number))throw P(a.number,"array length mismatch");return i}function Uh(e,r,t,n,o){return pd(e.len,e.fieldTree,e.delimiter,r,t,n,o,!0)}function pd(e,r,t,n,o,s,i,a){let l=[],d=gd(e,r,t,n,o.index,s,i);for(;l.length<e;){let u=n[o.index];if(u===void 0)throw tt(n,o.index);if(u.depth<s)break;if(u.depth>s)throw P(u.number,"invalid indentation");if(u.blankBefore&&i.strict)throw P(u.number,"blank line inside array");if(!nt(u.content,t,u.number))break;let m=Ae(u.content,t,u.number),f={cellIndex:0,nextIndex:o.index+1,flatWidth:po(r),childTableFields:d},h=md(r,m,u.number,n,f,s+1,t,i);if(f.cellIndex!==m.length)throw P(u.number,"array row length mismatch");l.push(qh(r,h,a)),o.index=f.nextIndex}if(l.length!==e)throw tt(n,o.index);let c=n[o.index];if(c!==void 0&&c.depth>=s&&nt(c.content,t,c.number))throw P(c.number,"array length mismatch");return l}function md(e,r,t,n,o,s,i,a){let l={};return e.forEach((d,c)=>{let u=e.slice(c+1),m=Bh(d,u,r,t,n,o,s,i,a);ot(l,[d.key],m,a,t)}),l}function Bh(e,r,t,n,o,s,i,a,l){if(e.fixedLength!==void 0){if(s.cellIndex+e.fixedLength>t.length)throw P(n,"array row length mismatch");let c=t.slice(s.cellIndex,s.cellIndex+e.fixedLength).map(u=>Ee(u,n));return s.cellIndex+=e.fixedLength,c}if(e.children!==void 0){let c=po(e.children),u=t[s.cellIndex],m=hd(u),f=t.length-s.cellIndex-1,h=o[s.nextIndex],v=h!==void 0&&h.depth===i,k=s.childTableFields===void 0?void 0:s.childTableFields.has(e);if(k===void 0?m!==void 0&&(v||t.length!==s.flatWidth&&f<c+Kh(r)):k){if(m===void 0)throw P(n,"array row length mismatch");return s.cellIndex+=1,pd(m,e.children,a,o,{get index(){return s.nextIndex},set index(I){s.nextIndex=I}},i,l,!1)}return md(e.children,t,n,o,s,i,a,l)}let d=t[s.cellIndex];if(d===void 0)throw P(n,"array row length mismatch");return s.cellIndex+=1,co(e,d,n)}function gd(e,r,t,n,o,s,i){let a=r.filter(c=>c.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let l,d=1<<a.length;for(let c=0;c<d;c+=1){let u=new Set;a.forEach((f,h)=>{c&1<<h&&u.add(f)});let m=fd(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 fd(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||!nt(m.content,n,m.number))return;let f=Ae(m.content,n,m.number),h=Hh(r,t,f,n,o,l+1,i+1,a);if(h===void 0||o[h.nextIndex]?.depth>i)return;d+=h.consumedChildRows,l=h.nextIndex}let c=o[l];if(c!==void 0&&c.depth>=i&&nt(c.content,n,c.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function Hh(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=hd(t[l]);if(m===void 0)return;l+=1;let f=gd(m,u.children,n,o,d,i,a);if(f===void 0)return;let h=fd(m,u.children,f,n,o,d,i,a);if(h===void 0)return;d=h.nextIndex,c+=m+h.consumedChildRows}else l+=po(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:c}}function qh(e,r,t){return t&&e.length===1&&e[0].fixedLength!==void 0?r[e[0].key]:r}function hd(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function Vh(e){return e.some(r=>r.fixedLength!==void 0||r.children!==void 0)}function po(e){return e.reduce((r,t)=>r+yd(t),0)}function yd(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?po(e.children):1}function Kh(e){return e.reduce((r,t)=>t.children!==void 0?r+1:r+yd(t),0)}function nt(e,r,t){let n=de(e,":",t);if(n===-1)return!0;let o=de(e,r,t);return o===-1?!1:o<n}function Jh(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 tt(r,t.index);if(a.depth>n)throw P(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw P(a.number,"blank line inside array");s.push(zh(r,t,n,o))}let i=r[t.index];if(i!==void 0&&i.depth>=n)throw P(i.number,"array length mismatch");return s}function zh(e,r,t,n){let o=e[r.index];if(!o.content.startsWith("-"))throw P(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return r.index+=1,{};if(s.startsWith("[")){let i=de(s,":",o.number);Vt(s,o.number,n);let a;try{a=lo(s,i)}catch{a=void 0}if(a!==void 0){let l=s.slice(i+1);return Is(a,l,e,r,t,n)}}if(de(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 Gs(i,{index:0},t+1,n)}return r.index+=1,Ee(s,o.number)}function kd(e,r,t,n,o,s){if(o.expandPaths&&!t&&r.includes(".")){let i=r.split(".");if(i.every(Qh)){ot(e,i,n,o,s);return}}ot(e,[r],n,o,s)}function ot(e,r,t,n,o){Fe(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 P(o,"duplicate key");De(e,s,t);return}if(i&&!Y(e[s])){if(n.strict)throw P(o,"path expansion conflict");De(e,s,{})}else i||De(e,s,{});ot(e[s],r.slice(1),t,n,o)}function Qh(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function X(e,r={}){let t=r.maxDepth??1e3,n=r.delimiter??K;if(![K,"|"," "].includes(n))throw P(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=ld(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?Ms(s,void 0,e,0,!1,o):Y(e)?bd(s,e,0,o):s.push(ce(e,n)),s.join("")}function st(e,r){e.push(" ".repeat(r*2))}function bd(e,r,t,n){Fe(t,0,n);for(let[o,s]of Object.entries(r))st(e,t),Cs(e,o,s,t,n)}function Cs(e,r,t,n,o){if(Fe(n,0,o),Array.isArray(t)){Ms(e,r,t,n,!1,o);return}if(Y(t)){let s=o.keyedMapCollapse?Xh(t,o,n+1):void 0;if(s!==void 0){e.push(te(r),"{",Fs(o.delimiter),s.fields.map(i=>Bs(i,o.delimiter)).join(o.delimiter),`}:
|
|
15
|
+
`);for(let[i,a]of Object.entries(t)){st(e,n+1);let l=[];e.push(te(i),": ",s.paths.map(d=>Hs(Us(a,d.path),d,o.delimiter,o,l,n+2)).join(o.delimiter),`
|
|
16
16
|
`),e.push(...l)}return}e.push(te(r),`:
|
|
17
|
-
`),
|
|
18
|
-
`)}function
|
|
17
|
+
`),bd(e,t,n+1,o);return}e.push(te(r),": ",ce(t,o.delimiter),`
|
|
18
|
+
`)}function Ms(e,r,t,n,o,s){if(Fe(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(Me)){
|
|
22
|
-
`);return}let i=o?void 0:
|
|
23
|
-
`);for(let a of t){st(e,n+1);let l=[];e.push(i.paths.map(d=>
|
|
24
|
-
`),e.push(...l)}return}
|
|
25
|
-
`);for(let a of t)st(e,n+1),
|
|
26
|
-
`);return}e.push("- ")
|
|
27
|
-
`)}function
|
|
28
|
-
`),e.push(...i)}}function
|
|
29
|
-
`}function
|
|
30
|
-
`}function
|
|
31
|
-
`,h=()=>
|
|
32
|
-
`;return
|
|
33
|
-
`},end(){return u?"":(u=!0,f())}}}function
|
|
34
|
-
`),
|
|
35
|
-
`)),e.positional&&e.positional.length>0){r.push(
|
|
36
|
-
`));for(let n of e.positional)if(n.description){let o=n.variadic?`${n.name}...`:n.name;r.push(
|
|
37
|
-
`),
|
|
38
|
-
`))}r.push(
|
|
39
|
-
`))}if(e.options&&Object.keys(e.options).length>0){r.push(
|
|
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
|
|
21
|
+
`);return}if(t.every(Me)){$s(e,r,t.length,void 0,s.delimiter),e.push(" "),e.push(t.map(a=>ce(a,s.delimiter)).join(s.delimiter)),e.push(`
|
|
22
|
+
`);return}let i=o?void 0:_d(t,s,n+1);if(i!==void 0){$s(e,r,t.length,i.fields,s.delimiter),e.push(`
|
|
23
|
+
`);for(let a of t){st(e,n+1);let l=[];e.push(i.paths.map(d=>Hs(Us(a,d.path),d,s.delimiter,s,l,n+2)).join(s.delimiter)),e.push(`
|
|
24
|
+
`),e.push(...l)}return}$s(e,r,t.length,void 0,s.delimiter),e.push(`
|
|
25
|
+
`);for(let a of t)st(e,n+1),Yh(e,a,n+1,s)}function Yh(e,r,t,n){if(Fe(t,0,n),Array.isArray(r)){e.push("- "),Ms(e,void 0,r,t,!0,n);return}if(Y(r)){let o=Object.entries(r);if(o.length===0){e.push(`-
|
|
26
|
+
`);return}e.push("- "),Cs(e,o[0][0],o[0][1],t+1,n);for(let[s,i]of o.slice(1))st(e,t+1),Cs(e,s,i,t+1,n);return}e.push("- ",ce(r,n.delimiter),`
|
|
27
|
+
`)}function $s(e,r,t,n,o){r!==void 0&&e.push(te(r)),e.push("[",String(t),Fs(o),"]"),n!==void 0&&e.push("{",n.map(s=>Bs(s,o)).join(o),"}"),e.push(":")}function Fs(e){return e===K?"":e}function _d(e,r,t){let n=Zh(e,r);if(n!==void 0)return n;let o=Ns(e.map(s=>({value:s})),r,t);return o===void 0?void 0:{fields:o,paths:Ws(o)}}function Xh(e,r,t){let n=Object.values(e);if(!(n.length<2))return _d(n,r,t)}function Ns(e,r,t){Fe(t,0,r);let n=e[0]?.value;if(!Y(n))return;let o=Object.keys(n).map(s=>({key:s}));if(o.length!==0){for(let{value:s}of e)if(!Y(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})=>Me(l)))continue;if(r.primitiveArrayColumns&&i.every(({value:l})=>Array.isArray(l)&&l.every(Me))){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=Ns(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=Ns(i,r,t+1);if(a===void 0)return;s.children=a}return o}}function Zh(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(Me)))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 Us(e,r){let t=e;for(let n of r)t=t[n];return t}function Bs(e,r){return e.listDelimiter!==void 0?`${te(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${te(e.key)}[${e.fixedLength}${Fs(r)}]`:e.children===void 0?te(e.key):`${te(e.key)}{${e.children.map(t=>Bs(t,r)).join(r)}}`}function Hs(e,r,t,n,o,s){return r.childFields!==void 0?(ey(o,e,r.childFields,n,s),String(e.length)):r.fixedLength!==void 0?e.map(i=>ce(i,t)).join(t):r.listDelimiter===void 0?ce(e,t):e.map(i=>ry(i,t,r.listDelimiter)).join(r.listDelimiter)}function ey(e,r,t,n,o){for(let s of r){st(e,o);let i=[];e.push(Ws(t).map(a=>Hs(Us(s,a.path),a,n.delimiter,n,i,o+1)).join(n.delimiter)),e.push(`
|
|
28
|
+
`),e.push(...i)}}function ry(e,r,t){return typeof e!="string"?ce(e,r):xs(e,r)||e.includes(t)?io(e):e}var Od=[K,"|"," "];var Ad=8,Dd=/^[A-Za-z0-9_-]+$/,UP=new TextEncoder,BP=new TextDecoder;function sy(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 jd(e,r){if(!Dd.test(e))throw M(r,"invalid tag")}function iy(e,r){let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t);if(!Dd.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 ay(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(!Od.includes(i)&&i!=="")throw M(r,"invalid header delimiter");let a=i===""?K: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),jd(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=Ae(c,a,r).map(m=>Oe(m,r)[0])}catch(m){throw rt(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 ly(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 wd(e,r,t,n){let o;try{o=Ae(e,r,n)}catch(s){throw rt(s)}if(o.length!==t)throw M(n,"row arity mismatch");for(let s of o)try{Ee(s,n)}catch(i){throw rt(i)}return o}function dy(e,r,t){let n={};return e.forEach((o,s)=>{try{De(n,o,Ee(r[s],t))}catch(i){throw rt(i)}}),n}function cy(e,r,t){if(e.startsWith("- "))throw M(r,"reserved line prefix");let n=sy(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=ay(e,r);if(o!==null)return o.continuation?(ly(t,o,r),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=iy(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:wd(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:wd(e,t.delimiter,t.fields.length,r)}}function uy(e,r={}){let t=[],n=new Map,o=[],s=[],i=null,a=!1,l=!1;function d(f,h){let v=s.at(-1);if(v!==void 0&&v.lane===f.lane&&v.delimiter===f.delimiter&&v.fieldText===f.fieldText){v.rows.push(h);return}s.push({lane:f.lane,delimiter:f.delimiter,fields:f.fields,fieldText:f.fieldText,rows:[h]})}function c(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function u(f,h,v){let k=n.get(f);if(k===void 0){if(n.size>=Ad)throw M(v,"too many tagged lanes");k={segments:[],current:null},n.set(f,k),t.push(f)}else k.current!==null&&k.segments.push(k.current);k.current={lane:f,delimiter:h.delimiter,fields:h.fields,fieldText:h.fieldText,rows:[]},k.delimiter=h.delimiter,k.fields=h.fields,k.fieldText=h.fieldText}if(so(e).forEach((f,h)=>{let v=h+1;if(f==="")return;let k=i===null?{taggedLanes:n}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:n},T=cy(f,v,k);if(T.kind==="trailer"){c(),i=null;return}if(T.kind!=="continuation"){if(T.kind==="tag-header"){l=!0,u(T.header.tag,T.header,v);return}if(T.kind==="header"){c(),a||(t.push(null),a=!0),i={lane:null,delimiter:T.header.delimiter,fields:T.header.fields,fieldText:T.header.fieldText,rows:[]};return}if(T.kind==="tagged-row"){l=!0;let I=n.get(T.tag).current;I.rows.push(T.cells),d(I,T.cells);return}if(i===null)throw M(v,"row before header");i.rows.push(T.cells),d(i,T.cells)}}),!l)return c(),r.preserveInterleaving===!0,o;let m=[];c();for(let f of t){if(f===null){m.push(...o);continue}let h=n.get(f);m.push(...h.segments),h.current!==null&&m.push(h.current)}return r.preserveInterleaving===!0?s:m}function We(e){return uy(e).flatMap(r=>r.rows.map(t=>dy(r.fields,t,0)))}function py(e){if(!Od.includes(e))throw M(0,"invalid header delimiter")}function Ed(e,r,t=!1){return`[${`${t?"~":""}${e===K?"":e}`}]{${r}}:
|
|
29
|
+
`}function vd(e,r){return`[]<${e}>{${r}}:
|
|
30
|
+
`}function qs(e,r){return r.map(te).join(e)}function my(e){if(!Array.isArray(e)||e.length===0)throw M(0,"TOONL header requires fields");return e.map(r=>{let t;try{[t]=Oe(String(r),0)}catch(n){throw rt(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 Td(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw M(0,"TOONL continuation cadence must be positive")}function gy(e,r,t){return e.continuationEveryRows!==void 0&&r>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function xd(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=>!Me(e[t])))throw M(0,"TOONL rows must be flat objects");return r}function fy(e){return JSON.stringify([...e].sort())}function Pd(e,r){let t=fy(e),n=r.get(t);return n!==void 0?n:(r.set(t,e),e)}function ye({delimiter:e=K,trailer:r=!0,continuationEveryRows:t,continuationEveryBytes:n}={}){py(e),Td(t),Td(n);let o=null,s="",i=new Map,a=0,l=0,d=0,c=new Map,u=!1,m={continuationEveryRows:t,continuationEveryBytes:n},f=()=>o===null||!r?"":`[=${a}]
|
|
31
|
+
`,h=()=>gy(m,l,d)?(l=0,d=0,Ed(e,s,!0)):"",v=k=>{jd(k,0);let T=c.get(k);if(T===void 0){if(c.size>=Ad)throw M(0,"too many tagged lanes");T={fields:null,fieldsByShape:new Map},c.set(k,T)}return T};return{push(k){if(u)throw M(0,"TOONL encoder is closed");let T=Pd(xd(k),i),I="";(o===null||o.length!==T.length||o.some((H,ee)=>H!==T[ee]))&&(I+=f(),o=T,s=qs(e,o),a=0,l=0,d=0,I+=Ed(e,s));let F=o.map(H=>ce(k[H],e));I+=h();let G=`${F.join(e)}
|
|
32
|
+
`;return I+=G,a+=1,l+=1,d+=G.length,I},declareLane(k,T){if(u)throw M(0,"TOONL encoder is closed");let I=my(T),F=qs(K,I),G=v(k);return Sd(G.fields,I)?"":(G.fields=I,vd(k,F))},pushTagged(k,T){if(u)throw M(0,"TOONL encoder is closed");let I=v(k),F=Pd(xd(T),I.fieldsByShape),G=qs(K,F),H=F.map(q=>ce(T[q],K)),ee="";return Sd(I.fields,F)||(I.fields=F,ee+=vd(k,G)),`${ee}${k}:${H.join(K)}
|
|
33
|
+
`},end(){return u?"":(u=!0,f())}}}function Vs(e){let r={app:e,version:hy(it("__RED_BUILD_VERSION__",()=>"3.10.1")??"0.0.0-dev"),gitSha:it("__RED_BUILD_GIT_SHA__",()=>"49c48d93eb60833362eced33096f90dc78f6bfe1")??"unknown",buildTime:it("__RED_BUILD_TIME__",()=>"2026-08-07T04:47:29-03:00")??"unknown",bundleAsset:it("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=it("__REDDB_SDK_VERSION__",()=>""),n=it("__REDDB_BINARY_TAG__",()=>"");return t&&(r.reddbSdkVersion=t),n&&(r.reddbBinaryTag=n),r}function hy(e){return e.startsWith("v")?e.slice(1):e}function Ld(e){return`${e.app} ${e.version} ${e.gitSha}`}function it(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"},yy=/^[a-z][a-z0-9+.-]*:\/\//i;function ky(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 by(e=Gd){return Object.entries(e).map(([r,t])=>ky(r,t)).sort((r,t)=>t.separator.length-r.separator.length)}function _y(e){return/^-\d+(\.\d+)?$/.test(e)}function Jt(e){return!(!e||e.startsWith("-")&&!_y(e))}function mo(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 Id(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=>Id(t.trim())):e}function Ar(e,r){switch(r){case"boolean":return Ry(e);case"number":return wy(e);case"array":return e.split(",").map(t=>mo(t.trim()));case"string":default:return e}}function Ry(e){let r=e.toLowerCase().trim();return r==="true"||r==="yes"||r==="1"||r==="on"}function wy(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 lr(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Ey(e,r={}){return e.map(t=>{let n=r[t.type];return n?n(t.value):t.value}).join("")}function W(e,r){return{type:e,value:r}}function vy(e){let r=[],t=Ty(e);if(r.push(W("section-header","Usage:"),W("text"," "),W("usage-text",t),W("newline",`
|
|
34
|
+
`),W("newline",`
|
|
35
|
+
`)),e.positional&&e.positional.length>0){r.push(W("section-header","Arguments:"),W("newline",`
|
|
36
|
+
`));for(let n of e.positional)if(n.description){let o=n.variadic?`${n.name}...`:n.name;r.push(W("indent"," "),W("positional-name",`<${o}>`)),n.required||r.push(W("positional-optional"," (optional)")),r.push(W("newline",`
|
|
37
|
+
`),W("indent"," "),W("option-description",n.description),W("newline",`
|
|
38
|
+
`))}r.push(W("newline",`
|
|
39
|
+
`))}if(e.options&&Object.keys(e.options).length>0){r.push(W("section-header","Options:"),W("newline",`
|
|
40
|
+
`));let n=xy(e.options);r.push(...n)}return r}function Sy(e,r){let t=vy(e);return Ey(t,r)}function Ty(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 xy(e,r=!1){let t=[],n=[],o=r?"global-option-flag":"option-flag",s=r?"global-option-type":"option-type",i=r?"global-option-default":"option-default",a=r?"global-option-description":"option-description";for(let[d,c]of Object.entries(e)){if(c.hidden)continue;let u=[],m=v=>{u.includes(v)||u.push(v)};c.short&&m(`-${c.short}`),m(`--${d}`);for(let v of c.aliases??[])v.length===1?m(`-${v}`):m(`--${v}`);let f=u.join(", "),h=c.type&&c.type!=="boolean"?`<${c.type}>`:void 0;n.push({flags:f,type:h,desc:c.description??"",default:c.default!==void 0?String(c.default):void 0})}let l=Math.max(...n.map(d=>d.flags.length+(d.type?d.type.length+1:0)),20);for(let d of n){let c=d.flags.length+(d.type?d.type.length+1:0),u=" ".repeat(l-c+2);t.push(W("indent"," ")),t.push(W(o,d.flags)),d.type&&(t.push(W("text"," ")),t.push(W(s,d.type))),t.push(W("text",u)),t.push(W(a,d.desc)),d.default!==void 0&&(t.push(W("text"," ")),t.push(W(i,`(default: ${d.default})`))),t.push(W("newline",`
|
|
41
|
+
`))}return t}function $d(e){let r=Gy(e.options??{},e.autoShort??!1),t=by(e.separators??Gd);return{schema:e,parse(n){return Py(n,e,r,t)},help(){return Sy(e,e.formatter)}}}function Py(e,r,t,n){let o={positional:{},options:{},errors:[],rest:[]},s=new Set(n.map(c=>c.to));for(let c of s)o[c]={};let i=0,a=r.positional??[],l=0,d=!1;for(;l<e.length;){let c=e[l];if(r.stopEarly&&i>0){o.rest=e.slice(l);break}if(c==="--"&&!d){d=!0,l++;continue}if(d){if(i<a.length){let m=a[i];if(m.variadic){let f=[];for(;l<e.length;){let h=e[l];f.push(m.type?Ar(h,m.type):h),l++}o.positional[m.name]=f,i++}else{let f=m.type?Ar(c,m.type):c;o.positional[m.name]=f,i++,l++}}else r.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(c)),l++;continue}if(c.startsWith("--")){l=jy(c,l,e,o,t,r);continue}if(c.startsWith("-")&&c.length>1&&!My(c)){l=Ly(c,l,e,o,t,r);continue}let u=Oy(c,n);if(u){let{key:m,value:f,config:h}=u,v=o,k=v[h.to]??(v[h.to]={});k[m]=h.typed?Id(f):lr(f),l++;continue}if(i<a.length){let m=a[i];if(m.variadic){let h=[];for(;l<e.length&&!e[l].startsWith("-");){let v=e[l];h.push(m.type?Ar(v,m.type):v),l++}o.positional[m.name]=h,i++;continue}let f=m.type?Ar(c,m.type):c;o.positional[m.name]=f,i++}else r.allowUnknown!==!1?o.rest.push(c):o.errors.push(`Unexpected positional argument: ${c}`);l++}return $y(o,r,t),Cy(o,r,a),Ny(o,r,t),o}function Oy(e,r){if(yy.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(Ay(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(Dy(o,s,t))return{key:o,value:s,config:t}}}return null}function Ay(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function Dy(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 jy(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 go(d,c,r+1,n,o,s)}let a=o.get(i);if(a){if(a.type!=="boolean"){let l=t[r+1];return Jt(l)?go(a.name,l,r+2,n,o,s):(n.errors.push(`Option --${i} requires a value`),r+1)}return n.options[a.name]=!0,r+1}return s.strict?n.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(n.options[i]=!0),r+1}function Ly(e,r,t,n,o,s){let i=e.slice(1);if(i.includes("=")){let a=i.indexOf("="),l=i.slice(0,a),d=i.slice(a+1),c=Ks(l,o);return c?go(c.name,d,r+1,n,o,s):(s.strict?n.errors.push(`Unknown option: -${l}`):s.allowUnknown!==!1&&(n.options[l]=mo(lr(d))),r+1)}if(i.length===1){let a=Ks(i,o);if(a){if(a.type!=="boolean"){let l=t[r+1];return Jt(l)?go(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(Jt(l))return n.options[i]=mo(lr(l)),r+2;n.options[i]=!0}return r+1}for(let a of i){let l=Ks(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 go(e,r,t,n,o,s){let i=o.get(e);if(i){if(i.choices){let l=i.type?Ar(lr(r),i.type):lr(r);if(!i.choices.includes(l))return n.errors.push(`Invalid value for '${e}': '${r}'. Allowed: ${i.choices.join(", ")}`),t}let a=i.type?Ar(lr(r),i.type):lr(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]=mo(lr(r)));return t}function Gy(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=Iy(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 Iy(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 Ks(e,r){for(let t of r.values())if(t.short===e||t.aliases.includes(e))return t}function $y(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?Ar(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 Cy(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 Ny(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 My(e){return/^-\d+(\.\d+)?$/.test(e)}var Js=class extends Error{flag;known;constructor(r,t){super(`unknown flag '${r}'; expected one of: ${t.join(", ")}`),this.name="UnknownFlagError",this.flag=r,this.known=t}};function Fy(e){let r={};for(let[t,n]of Object.entries(e))r[t]={type:n.kind==="boolean"?"boolean":"string",...t.length===1?{short:t}:{},...n.aliases===void 0?{}:{aliases:n.aliases}};return r}function Wy(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&&Jt(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 dr(e,r,t={}){let o=$d({options:Fy(r),separators:{},allowUnknown:!0}).parse([...e]),s={},i=Wy(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 Js(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 zs=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 Cd(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 zs(t,Object.keys(r.commands))}let o=r.keepArgvOnDefault??!0;return{command:r.default,args:o?[...e]:n}}import{appendFileSync as Xy,mkdirSync as Zy,readFileSync as Kd,statSync as ek}from"node:fs";import{dirname as zd,join as rk}from"node:path";var Nd="RED_WORKER_SCOPE",Md="RED_WORKER_MEMORY_CEILING",Fd="RED_WORKER_SCOPE_DEGRADATION",Ys={scope:null,memory_ceiling:null,scope_degradation:null};function Xs(e){return{scope:Qs(e[Nd]),memory_ceiling:Qs(e[Md]),scope_degradation:Qs(e[Fd])}}function zt(e){let r={};return e.scope!=null&&e.scope!==""&&(r[Nd]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(r[Md]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(r[Fd]=e.scope_degradation),r}function Qs(e){let r=(e??"").trim();return r===""?null:r}import{mkdirSync as Hy,readdirSync as qy,readFileSync as Hd,rmSync as Vy,writeFileSync as Ky}from"node:fs";import{basename as Jy,join as at}from"node:path";import{isAbsolute as wO,join as fo,resolve as EO}from"node:path";function Uy(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var Wd="deaths",Ud="deaths.toonl";function ho(e){return fo(Uy(e),Wd)}function Qt(e){return fo(ho(e),Ud)}var Yt="live",Bd="attributions.toonl";function yo(e){return fo(ho(e),Yt)}function Zs(e){return fo(ho(e),Bd)}var ri=at("sys","kernel","random","boot_id"),qd=1;function ti(e,r={}){let t=r.procRoot??"/proc",n=e.pid??process.pid;return{version:qd,ts:(r.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:n,ppid:e.ppid??process.ppid,boot_id:Vd(at(t,ri)),cgroup:zy(t,n),last_phase:e.last_phase}}function Vd(e){try{let r=Hd(e,"utf8").trim();return r===""?null:r}catch{return null}}function zy(e,r){let t=Vd(at(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 ni(e){let r=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${r}-${e.pid}.toon`}function oi(e,r){let t=at(e,ni(r));try{return Hy(e,{recursive:!0,mode:448}),Ky(t,ye({trailer:!1}).push(Yy(r)),{encoding:"utf8",mode:384}),t}catch{return null}}function Dr(e,r){try{Vy(at(e,ni(r)),{force:!0})}catch{}}function si(e,r){let t;try{t=qy(e)}catch{return[]}let n=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=at(e,o);try{let a=We(Hd(s,"utf8"))[0];if(a===void 0)throw new Error("anchor holds no record");n.push(Qy(a))}catch(i){r?.(Jy(s),i instanceof Error?i.message:String(i))}}return n}function Qy(e){let r=e.kind;if(r!=="launcher"&&r!=="worker"&&r!=="daemon")throw new Error(`presence anchor has unknown kind ${String(r)}`);return{version:ei(e.version),ts:String(e.ts),kind:r,id:String(e.id),pid:ei(e.pid),ppid:ei(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 ei(e){return typeof e=="number"?e:Number(e)}function Yy(e){return{...e}}var tk=1,nk=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function ok(e){return typeof e=="string"&&nk.has(e)}var sk="startup";function ik(e,r){return{...e.scope??Ys,version:tk,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 ak(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 ai={mkdir(e){Zy(e,{recursive:!0,mode:448})},endsClean(e){let r;try{r=ek(e).size}catch{return!0}if(r===0)return!0;try{return Kd(e,"utf8").endsWith(`
|
|
43
|
+
`)}catch{return!0}},append(e,r){Xy(e,r,{encoding:"utf8",mode:384})},read(e){return Kd(e,"utf8")}};function lk(e){let r={};for(let[t,n]of Object.entries(e))r[t]=n;return r}function dk(e,r,t=ai){let n=ye({trailer:!1}).push(lk(r));return t.mkdir(zd(e)),t.endsClean(e)||t.append(e,`
|
|
44
|
+
`),t.append(e,n),r}function Qd(e){let r=e.endsWith(`
|
|
45
45
|
`)?e:e.slice(0,e.lastIndexOf(`
|
|
46
|
-
`)+1);return r===""?[]:We(r).map(
|
|
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===""?[]:We(r).map(ck)}function ck(e){let r=e.exit_path;if(!ok(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:ve(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:ve(e.pid),exit_path:r,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:ve(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:ve(e.uptime_s),rss_kb:ve(e.rss_kb),max_rss_kb:ve(e.max_rss_kb),user_cpu_us:ve(e.user_cpu_us),system_cpu_us:ve(e.system_cpu_us),minor_page_faults:ve(e.minor_page_faults),major_page_faults:ve(e.major_page_faults),voluntary_ctx_switches:ve(e.voluntary_ctx_switches),involuntary_ctx_switches:ve(e.involuntary_ctx_switches)}}function ve(e){return typeof e=="number"?e:Number(e)}function Yd(e,r=ai){let t;try{t=r.read(e)}catch(n){if(n.code==="ENOENT")return[];throw n}return Qd(t)}var uk=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],ii=null;function Xd(e){let r=e.host??process,t=e.io??ai,n=e.clock??(()=>new Date().toISOString()),o=r.pid,s=e.scope??Xs(process.env),i=e.phase??sk,a=null,l=e.presenceDir===void 0?rk(zd(e.lanePath),Yt):e.presenceDir,d=null,c=()=>{l!==null&&(d=ti({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),oi(l,d))},u=k=>{if(!a){try{a=dk(e.lanePath,ik({ts:n(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...k},ak(r)),t)}catch{}l!==null&&d!==null&&Dr(l,d)}},m={signal(k){u({exit_path:"signal",signal:k})},exit(k){u({exit_path:"exit",exit_code:k})},uncaughtException(k){u({exit_path:"uncaught-exception",detail:Jd(k)})},unhandledRejection(k){u({exit_path:"unhandled-rejection",detail:Jd(k)})}},h=[...(e.signals??uk).map(k=>{let T=()=>{if(m.signal(k),!(r.listenerCount?.(k)!==1||!r.kill)){r.off(k,T);try{r.kill(o,k)}catch{}}};return[k,T]}),["uncaughtException",(...k)=>m.uncaughtException(k[0])],["unhandledRejection",(...k)=>m.unhandledRejection(k[0])],["exit",(...k)=>m.exit(typeof k[0]=="number"?k[0]:null)]];for(let[k,T]of h)r.on(k,T);let v={lanePath:e.lanePath,phase(k){i=k,a||c()},currentPhase:()=>i,written:()=>a,uninstall(){for(let[k,T]of h)r.off(k,T);l!==null&&d!==null&&Dr(l,d),ii===v&&(ii=null)},handlers:m};return e.setActive!==!1&&(ii=v),c(),v}function Jd(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as pk,readdirSync as mk,readFileSync as ko,statSync as gk,writeFileSync as fk}from"node:fs";import{join as tc}from"node:path";var hk=1,yk=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],kk=512*1024;function bk(e={}){let r=e.procRoot??"/proc",t=e.journalPaths??yk,n=[],o=tc(r,ri),s=null;try{let l=ko(o,"utf8").trim();s=l===""?null:l,n.push({source:o,result:s?"read":"empty",detail:s})}catch(l){n.push({source:o,result:li(l),detail:null})}let i=new Set;try{for(let l of mk(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:li(l),detail:null})}let a=[];for(let l of t)try{let c=_k(l,e.tailBytes??kk).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:li(d),detail:null})}return{boot_id:s,live_pids:i,journal:a,probes:n}}function li(e){return e.code==="ENOENT"?"absent":"unreadable"}function _k(e,r){let t=gk(e).size,n=ko(e,"utf8");return t<=r?n:n.slice(n.length-r)}var Rk=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,wk=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,Ek=/Killed (\/\S*) due to memory pressure/,vk=/\bopid=(\d+)\b/,Zd=/\bsig=(\d+)\b/,Sk=/\buid=(\d+)\b/,Tk=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,xk={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function Pk(e,r,t,n){let o=e.boot_id!==null&&r.boot_id!==null&&e.boot_id!==r.boot_id,s=[...r.probes.map(u=>`${u.source}: ${u.result}${u.detail?` (${u.detail})`:""}`),`boot id: anchored under ${e.boot_id??"unknown"}, host now ${r.boot_id??"unknown"} (${o?"changed":"same"})`,`parent account: ppid ${e.ppid}`,`cgroup: ${e.cgroup??"unknown"}`],i=(u,m,f,h)=>({version:hk,ts:n,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:u,confidence:m,signal:f,host_boot_changed:o,evidence:h,checked:s}),a=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],l=r.journal.find(u=>ec(u,e.pid,Rk)||ec(u,e.pid,wk));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=Ek.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(vk.exec(u)?.[1])===e.pid&&Zd.test(u));if(d!==void 0){let u=Number(Zd.exec(d)?.[1]),m=Sk.exec(d)?.[1];return i("user-signal",o?"medium":"high",xk[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=>Tk.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 ec(e,r,t){return Number(t.exec(e)?.[1])===r}var Ok=" | ";function rc(e){return e.map(r=>r.replace(/[|\n\r]+/g," ").trim()).join(Ok)}function Ak(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:rc(e.evidence),checked:rc(e.checked)}}function Dk(e){let r=ye({trailer:!1});return e.map(t=>r.push(Ak(t))).join("")}function nc(e){let r=yo(e.stateRoot),t=Zs(e.stateRoot),n=e.now??(()=>new Date().toISOString()),o=e.evidence??bk({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=si(r,u=>s.push(u)),a=Yd(Qt(e.stateRoot)),l=[],d=[],c=[];for(let u of i){if(o.live_pids.has(u.pid)){d.push(u);continue}if(a.find(f=>f.pid===u.pid&&f.id===u.id)!==void 0){c.push(u),Dr(r,u);continue}l.push(Pk(u,o,a,n())),Dr(r,u)}return l.length>0&&jk(t,l),{attributions:l,alive:d,self_recorded:c,skipped:s,laneText:()=>{try{return ko(t,"utf8")}catch{return""}}}}function oc(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 jk(e,r){try{pk(tc(e,".."),{recursive:!0,mode:448});let t=Lk(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
|
+
`;fk(e,`${t}${n}${Dk(r)}`,{encoding:"utf8",mode:384})}catch{}}function Lk(e){try{return ko(e,"utf8")}catch{return""}}import{join as Gk}from"node:path";var Ik=[".red","redskilled"],er=448;function Ue(e){return Gk(e,...Ik)}import{execFileSync as zk}from"node:child_process";import{readFileSync as Qk}from"node:fs";import{dirname as uc,join as Yk}from"node:path";import{existsSync as $k,readFileSync as eA}from"node:fs";import{dirname as Ck,join as Nk}from"node:path";function sc(e,r){let t=e;for(let n=0;n<16;n++){let o=Nk(t,r);if($k(o))return o;let s=Ck(t);if(s===t)break;t=s}return null}function Mk(e){let r=e.indexOf(" #");return(r>=0?e.slice(0,r):e).trim()}function lt(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 Mk(d)}}import{createHash as Fk}from"node:crypto";var Wk="project.name";function ac(e){let r=lt(e,Wk)?.trim();return r===void 0||r===""?void 0:r}var Uk=8,lc="project";function dc(e){let r=Kk(e.gitCommonDir),t=(e.declaredName??"").trim(),n=t!==""?{name:t,source:"declared"}:Bk(e.remoteUrl)??{name:Hk(e.checkoutPath,r),source:"basename"},o=Vk(r??di(e.checkoutPath));return{name:n.name,slug:`${qk(n.name)}-${o}`,hash:o,source:n.source}}function cc(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 Bk(e){let r=cc(e);return r===void 0?void 0:{name:r,source:"remote"}}function Hk(e,r){let t=r===void 0?"":ic(Jk(r));if(t!=="")return t;let n=ic(di(e));return n===""?lc:n}function qk(e){let t=e.split("/").map(n=>n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(n=>n!=="").join("--");return t===""?lc:t}function Vk(e){return Fk("sha256").update(e).digest("hex").slice(0,Uk)}function Kk(e){let r=di(e??"");return r===""?void 0:r}function di(e){let r=e.trim().replace(/\\/g,"/");return r.length>1?r.replace(/\/+$/,""):r}function ic(e){let r=e.split("/").filter(t=>t!=="");return r[r.length-1]??""}function Jk(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var Xk=2e3;function pc(e){return Zk(e).name}function Zk(e){let r=ui(e),t=ci(e,["rev-parse","--absolute-git-dir"])??ci(e,["rev-parse","--git-common-dir"]),n=ci(e,["remote","get-url","origin"]);return dc({checkoutPath:r.root??e,...t!==void 0?{gitCommonDir:t}:{},...n!==void 0?{remoteUrl:n}:{},...r.name!==void 0?{declaredName:r.name}:{}})}function ui(e){let r=sc(e,Yk(".red","config.yaml"));if(r==null)return{};let t;try{t=Qk(r,"utf8")}catch{return{}}let n=ac(t),o=uc(uc(r));return{...n===void 0?{}:{name:n},configText:t,root:o}}function ci(e,r){try{let t=zk("git",[...r],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Xk}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as Kg}from"node:crypto";import{spawn as ET}from"node:child_process";import{mkdir as vT}from"node:fs/promises";import{dirname as ST}from"node:path";import{createHash as tb}from"node:crypto";import{constants as hi}from"node:fs";import{mkdir as Rc,open as nb,readFile as ob,rm as wc,stat as sb}from"node:fs/promises";import{createConnection as ib}from"node:net";import{tmpdir as ab}from"node:os";import{dirname as Ec,join as Xt}from"node:path";var eb="toon";function fc(e){return e.trimStart().startsWith("{")?"json":"toon"}function mi(e){let r=0;for(;e[r]===`
|
|
51
|
+
`||e[r]==="\r";)r+=1;let t=e.slice(r);if(t==="")return null;let n=fc(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 gi(e){let r=fc(e)==="json"?pi:mc,t=r===pi?mc:pi;try{return r(e)}catch(n){try{return t(e)}catch{throw n}}}function pi(e){return JSON.parse(e)}function mc(e){return me(e)}function fi(e,r){if(r==="toon"){let t=rb(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(vc))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 mb(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 nb(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 gb="/tmp";function _o(e){let r=e.env??process.env,t=eb("sha256").update(e.key).digest("hex").slice(0,20),n=l=>Xt(l,e.socketFileName).length<ib,o=r.XDG_RUNTIME_DIR;if(o){let l=Xt(o,"red-skills",t);if(n(l))return l}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=Xt(`red-skills-${s}`,t),a=Xt(sb(),i);return n(a)||process.platform==="win32"?a:Xt(gb,i)}rr();import{homedir as Cb}from"node:os";import{join as xi}from"node:path";import{spawnSync as Nb}from"node:child_process";import{createHash as Mb}from"node:crypto";import{existsSync as Fb,readdirSync as Wb}from"node:fs";import{mkdir as Ic,readFile as Ub,rename as Bb,writeFile as Hb}from"node:fs/promises";import{dirname as qb}from"node:path";var Gr="@reddb-io/red-skills",Sb="https://registry.npmjs.org",Tb="canary",Lr=class extends Error{kind;cause;constructor(r,t,n){super(t),this.name="BundleFetchError",this.kind=r,this.cause=n}},xb=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;function wi(e){return typeof e=="string"&&xb.test(e.trim())}function Dc(e){return`${e}-.bundle.min.mjs`}var Pb=".unversioned";function Ob(e,r,t="stable"){if(t==="canary")return`${e}-canary.bundle.min.mjs`;if(!wi(r))throw new Lr("invalid-version",`refusing to key the ${e} bundle cache on ${JSON.stringify(r??"")}: it would mint ${Dc(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 vo(e){let{plugin:r,version:t,cacheDir:n,channel:o}=e;return rn(n,Ob(r,t,o))}function Ab(e){return e==="dev"?["rsp","redskilled"]:[]}function Db(e){return`${e}.bundle.min.mjs`}function jb(e){return rn("dist",Db(e))}function Lb(e,r="stable"){return`${Gr}@${r==="canary"?Tb:e}`}function Ei(e=Gr){return`${Sb}/${e.replace("/","%2F")}`}async function vi(e,r){let{plugin:t,version:n,cacheDir:o,channel:s="stable"}=r,i=vo({plugin:t,version:n,cacheDir:o,channel:s}),a=Ab(t),l=a.map(m=>vo({plugin:m,version:n,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await Ib(e,l))return i;let d=Lb(n,s),c=rn(o,`.staging-${t}-${s==="canary"?"canary":n}`),u;try{u=await e.materialize(d,c)}catch(m){throw Gc(m,d)}for(let m of[t,...a]){let f=jb(m),h=rn(u,f);if(!await e.exists(h))throw new Lr("bundle-missing",`npm package ${d} has no ${f}`);let v=m===t?i:vo({plugin:m,version:n,cacheDir:o,channel:s});await e.writeFile(v,await e.readFile(h))}return await Gb(e,o,[t,...a]),i}async function Gb(e,r,t){if(e.rename)for(let n of t){let o=rn(r,Dc(n));try{if(!await e.exists(o))continue;await e.rename(o,`${o}${Pb}`)}catch{}}}async function Ib(e,r){for(let t of r)if(!await e.exists(t))return!1;return!0}async function jc(e,r,t=Gr){let n;try{n=await e.fetchText(Ei(t))}catch(s){throw Gc(s,t)}let o=Si(n);return{sameMajor:$b(o,r),newest:Ti(o)}}function Si(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 $b(e,r){let t=Ri(r);if(t===null)return null;let n=null;for(let o of e)Ri(o)===t&&(n===null||Lc(o,n)>0)&&(n=o);return n}function Ti(e){let r=null;for(let t of e){let n=String(t).trim();Ri(n)===null||/^\d+\.\d+\.\d+[-+]/.test(n)||(r===null||Lc(n,r)>0)&&(r=n)}return r}function Ri(e){let r=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return r?Number(r[1]):null}function Lc(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 Gc(e,r){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Lr("npm-unavailable",`npm is unavailable while resolving ${r}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Lr("package-missing",`npm could not resolve ${r}: ${t}`,e):new Lr("network",`failed to resolve ${r}: ${t}`,e)}function rn(e,r){return e.endsWith("/")?`${e}${r}`:`${e}/${r}`}rr();var $c={async materialize(e,r){await Ic(r,{recursive:!0});let t=Nb("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 xi(r,"node_modules",...Gr.split("/"))},async readFile(e){return new Uint8Array(await Ub(e))},async writeFile(e,r){await Ic(qb(e),{recursive:!0}),await Hb(e,r)},async exists(e){return Fb(e)},sha256(e){return Mb("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 Bb(e,r)}},Vb="redskilled";function Kb(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let r=e.XDG_CACHE_HOME||xi(e.HOME||Cb(),".cache");return xi(r,"red-skills","bundles")}var Jb=/^([a-z0-9-]+)-(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?)\.bundle\.min\.mjs$/;async function zb(e,r){if(wi(e.version))return e.version.trim();let t=e.listCacheDir??Xb,n=Qb(t(r),"dev");if(n)return n;try{let s=await(e.bundleIO??$c).fetchText(Ei());return Ti(Si(s))}catch{return null}}function Qb(e,r){let t=null;for(let n of e){let o=Jb.exec(n);if(!o||o[1]!==r)continue;let s=o[2];(t===null||Yb(s,t)>0)&&(t=s)}return t}function Yb(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 Xb(e){try{return Wb(e)}catch{return[]}}async function Zb(e={},r={},t={}){let n=cr(e,r);if(He(n))return n;let o=t.env??r.env??process.env,s=Kb(o),i=await zb(t,s);if(i===null)return n;try{await vi(t.bundleIO??$c,{plugin:Vb,version:i,cacheDir:s})}catch{return n}return cr(e,r)}async function Cc(e={},r={},t={}){let n=await Zb(e,r,t);if(He(n))return n;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(rr(),Ac));throw new o(n)}import{randomUUID as is}from"node:crypto";import{mkdir as aT,rm as Mg}from"node:fs/promises";import{connect as lT,createServer as dT}from"node:net";import{dirname as cT}from"node:path";import{availableParallelism as Fc,totalmem as r_}from"node:os";function tn(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 Nc(e,r={}){let t=0,n=0,o=0,s=[],i=[];for(let d of e){let c=tn(d),u=!1;for(let[m,f]of[[c.memory_high,h=>t+=h],[c.memory_max,h=>n+=h]]){if(m==null)continue;let h=dt(m);h==null?u=!0:f(h)}c.cpu_weight!=null&&(o+=c.cpu_weight),u&&s.push(d.worker_id),d.isolated||i.push(d.worker_id)}let a=r.hostCeilingBytes??null,l=a==null?0:Math.max(0,n-a);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:n,cpu_weight_total:o,unaccounted_workers:s.sort(),unisolated_workers:i.sort(),memory_ceiling_bytes:a,over_committed_bytes:l,over_commitment_reason:l===0?null:e_(e.length,n,a,l)}}function e_(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 dt(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 Wc="REDSKILLED_MEMORY_CEILING",Oi="REDSKILLED_WORKER_CEILING",qc="REDSKILLED_VALIDATION_CEILING",Uc="REDSKILLED_INTERACTIVE_RESERVATION",nn=1,Bc=.7,t_=2*1024**3,n_=2;function Vc(e){let r=e?.memory_max??e?.memory_high;if(r!=null)return dt(r)}function To(e){let r=0,t=[];for(let n of e){let o=Vc(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 Kc(e){let{ceiling:r}=e,t=To(e.workers),n=Vc(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??nn),l=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",d=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,c=(f,h)=>({version:1,admitted:!1,verdict:f,reason:h,ceiling:r,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}),u=r.worker_count==null?0:i-r.worker_count;if(u>0){if(e.reservation!=="interactive")return c("refused-over-worker-ceiling",`redskilled refused this Worker${l}: it would be Worker ${i} past a host ceiling of ${r.worker_count} Worker(s); ${a} extra slot(s) are reserved for interactive dispatches, and ${d}`);if(u>a)return c("refused-over-interactive-reservation",`redskilled refused this interactive Worker${l}: reserved slot ${u}/${a} is outside the bounded interactive reservation above the host ceiling of ${r.worker_count} Worker(s), and ${d}`)}if(r.memory_bytes!=null&&n===null)return c("refused-unaccountable-budget",`redskilled refused this Worker${l}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${r.memory_bytes} bytes, and ${d}`);if(r.memory_bytes!=null&&s>r.memory_bytes)return c("refused-over-memory-ceiling",`redskilled refused this Worker${l}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${r.memory_bytes} bytes, and ${d}`);let m=e.reservation==="interactive"&&u>0;return{version:1,admitted:!0,verdict:m?"admitted-interactive-reservation":"admitted",reason:m?`redskilled admitted this interactive Worker${l} into reserved interactive slot ${u}/${a} above the host ceiling of ${r.worker_count} Worker(s): ${s} bytes of declared Worker memory against a host ceiling of ${r.memory_bytes??"unbounded"} bytes, and ${d}`:`redskilled admitted this Worker${l}: ${s} bytes of declared Worker memory against a host ceiling of ${r.memory_bytes??"unbounded"} bytes, and ${d}`,ceiling:r,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function Jc(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=To(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 (${Oi} 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 xo(e=process.env,r=r_(),t={}){let n=Pi(t.flags?.memoryCeiling,e[Wc],t.config?.memoryCeiling),o=Pi(t.flags?.workerCeiling,e[Oi],t.config?.workerCeiling),s=Pi(t.flags?.validationCeiling,e[qc],t.config?.validationCeiling),i=n?.value??"",a=o?.value??"",l=(e[Uc]??"").trim(),d=zc(a),c=l===""?nn:i_(l),u=o?.source??"derived-default";if(a!==""&&d===null&&!o_(a)&&(So(`redskilled: ${Ai(o)} ${Oi}=${JSON.stringify(a)} is not a positive integer; this host admits an unbounded number of Workers instead.`),u="derived-default"),i!==""){let m=s_(i,r);if(m!==void 0)return Hc({memory_bytes:m,worker_count:d,interactive_reservation:c??nn,source:"declared",memory_source:n.source,worker_source:u},s,t.availableParallelism??Fc());So(`redskilled: ${Ai(n)} ${Wc}=${JSON.stringify(i)} is not a memory ceiling this host can read; using ${Bc*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return l!==""&&c===void 0&&So(`redskilled: ${Uc}=${JSON.stringify(l)} is not a non-negative integer; using the default reservation of ${nn} Worker(s) instead.`),Hc({memory_bytes:Math.floor(r*Bc),worker_count:d,interactive_reservation:c??nn,memory_source:"derived-default",worker_source:u,source:"host-fraction"},s,t.availableParallelism??Fc())}function Hc(e,r,t){if(r!==void 0){let i=zc(r.value);if(i!==null)return{...e,validation_count:i,validation_source:r.source};So(`redskilled: ${Ai(r)} ${qc}=${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)/n_)),o=e.memory_bytes==null?Number.POSITIVE_INFINITY:Math.max(1,Math.floor(e.memory_bytes/t_)),s=e.worker_count??Number.POSITIVE_INFINITY;return{...e,validation_count:Math.max(1,Math.min(n,o,s)),validation_source:"derived-default"}}function Pi(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 Ai(e){return e.source==="flag"?"serve flag":e.source==="environment"?"environment":e.source==="home-config"?"home config":"derived default"}function o_(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var So=e=>process.stderr.write(`${e}
|
|
62
|
-
`);function
|
|
59
|
+
`}function rb(e){try{let r=JSON.stringify(e);if(r===void 0)return null;let t=X(JSON.parse(r));return t.trim()===""?null:t}catch{return null}}function hc(e,r){return!gc(e)||!gc(r)||r.ok!==!1?!1:typeof e.id=="string"&&typeof r.id=="string"&&r.id!==e.id}function gc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var yc=new Set;function kc(e){return yc.has(e)?"json":eb}function bc(e){yc.add(e)}var lb=108;async function bo(e,r,t="resident server"){let n=e.wire,o=n??kc(e.socketPath),s=await _c(e,r,t,o);return n||o==="json"||!hc(r,s)?s:(bc(e.socketPath),await _c(e,r,t,"json"))}async function _c(e,r,t,n){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let a=ib(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(fi(r,n))}),a.on("data",m=>{d+=m.toString("utf8");let f=mi(d);f&&(d=f.rest,u(()=>{try{s(gi(f.frame))}catch(h){i(h)}}),a.end())}),a.on("error",m=>u(()=>i(m))),a.on("close",()=>{l||u(()=>i(new Error(`${t} closed without response`)))})})}function vc(e,r,t){let n="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{n+=o;let s=mi(n);if(!s)return;n=s.rest,e.pause();let i=a=>{if(!(e.destroyed||!e.writable))try{e.write(fi(a,s.dialect))}catch{}};(async()=>{let a;try{a=gi(s.frame),await r(a,i)}catch(l){t(l,a,i)}finally{e.end()}})()})}async function db(e){await Rc(Ec(e),{recursive:!0,mode:448});try{return await nb(e,hi.O_CREAT|hi.O_EXCL|hi.O_RDWR)}catch(r){if(r.code!=="EEXIST")throw r;return null}}var cb=6e4,Sc="resident-spawn-lock v1",ub=3;async function Tc(e,r={}){let t=r.maxAgeMs??cb,n=r.now??Date.now,o=r.pid??process.pid,s=r.isPidAlive??ne;await Rc(Ec(e),{recursive:!0,mode:448});let i=[];for(let a=0;;a+=1){let l=await db(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 mb(e),c=await fb(e,d,n());if(a>=ub||c==null)return{acquired:!1,lockPath:e,holder:d,ageMs:c};let u=pb(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 wc(e,{force:!0}),i.push(m),r.onReap?.(m)}}async function xc(e){await e.handle.close().catch(()=>{}),await wc(e.lockPath,{force:!0})}function pb(e,r,t,n){return e==null?r>t?"unattributed":null:n(e.pid)?r>t?"aged-out":null:"holder-dead"}function Pc(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 mb(e){try{return gb(await ob(e,"utf8"))}catch{return null}}function gb(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 fb(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 sb(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 hb="/tmp";function _o(e){let r=e.env??process.env,t=tb("sha256").update(e.key).digest("hex").slice(0,20),n=l=>Xt(l,e.socketFileName).length<lb,o=r.XDG_RUNTIME_DIR;if(o){let l=Xt(o,"red-skills",t);if(n(l))return l}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=Xt(`red-skills-${s}`,t),a=Xt(ab(),i);return n(a)||process.platform==="win32"?a:Xt(hb,i)}rr();import{homedir as Mb}from"node:os";import{join as Pi}from"node:path";import{spawnSync as Fb}from"node:child_process";import{createHash as Wb}from"node:crypto";import{existsSync as Ub,readdirSync as Bb}from"node:fs";import{mkdir as $c,readFile as Hb,rename as qb,writeFile as Vb}from"node:fs/promises";import{dirname as Kb}from"node:path";var Gr="@reddb-io/red-skills",xb="https://registry.npmjs.org",Pb="canary",Lr=class extends Error{kind;cause;constructor(r,t,n){super(t),this.name="BundleFetchError",this.kind=r,this.cause=n}},Ob=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;function Ei(e){return typeof e=="string"&&Ob.test(e.trim())}function jc(e){return`${e}-.bundle.min.mjs`}var Ab=".unversioned";function Db(e,r,t="stable"){if(t==="canary")return`${e}-canary.bundle.min.mjs`;if(!Ei(r))throw new Lr("invalid-version",`refusing to key the ${e} bundle cache on ${JSON.stringify(r??"")}: it would mint ${jc(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 vo(e){let{plugin:r,version:t,cacheDir:n,channel:o}=e;return rn(n,Db(r,t,o))}function jb(e){return e==="dev"?["rsp","redskilled"]:[]}function Lb(e){return`${e}.bundle.min.mjs`}function Gb(e){return rn("dist",Lb(e))}function Ib(e,r="stable"){return`${Gr}@${r==="canary"?Pb:e}`}function vi(e=Gr){return`${xb}/${e.replace("/","%2F")}`}async function Si(e,r){let{plugin:t,version:n,cacheDir:o,channel:s="stable"}=r,i=vo({plugin:t,version:n,cacheDir:o,channel:s}),a=jb(t),l=a.map(m=>vo({plugin:m,version:n,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await Cb(e,l))return i;let d=Ib(n,s),c=rn(o,`.staging-${t}-${s==="canary"?"canary":n}`),u;try{u=await e.materialize(d,c)}catch(m){throw Ic(m,d)}for(let m of[t,...a]){let f=Gb(m),h=rn(u,f);if(!await e.exists(h))throw new Lr("bundle-missing",`npm package ${d} has no ${f}`);let v=m===t?i:vo({plugin:m,version:n,cacheDir:o,channel:s});await e.writeFile(v,await e.readFile(h))}return await $b(e,o,[t,...a]),i}async function $b(e,r,t){if(e.rename)for(let n of t){let o=rn(r,jc(n));try{if(!await e.exists(o))continue;await e.rename(o,`${o}${Ab}`)}catch{}}}async function Cb(e,r){for(let t of r)if(!await e.exists(t))return!1;return!0}async function Lc(e,r,t=Gr){let n;try{n=await e.fetchText(vi(t))}catch(s){throw Ic(s,t)}let o=Ti(n);return{sameMajor:Nb(o,r),newest:xi(o)}}function Ti(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 Nb(e,r){let t=wi(r);if(t===null)return null;let n=null;for(let o of e)wi(o)===t&&(n===null||Gc(o,n)>0)&&(n=o);return n}function xi(e){let r=null;for(let t of e){let n=String(t).trim();wi(n)===null||/^\d+\.\d+\.\d+[-+]/.test(n)||(r===null||Gc(n,r)>0)&&(r=n)}return r}function wi(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 Ic(e,r){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Lr("npm-unavailable",`npm is unavailable while resolving ${r}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Lr("package-missing",`npm could not resolve ${r}: ${t}`,e):new Lr("network",`failed to resolve ${r}: ${t}`,e)}function rn(e,r){return e.endsWith("/")?`${e}${r}`:`${e}/${r}`}rr();var Cc={async materialize(e,r){await $c(r,{recursive:!0});let t=Fb("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 Pi(r,"node_modules",...Gr.split("/"))},async readFile(e){return new Uint8Array(await Hb(e))},async writeFile(e,r){await $c(Kb(e),{recursive:!0}),await Vb(e,r)},async exists(e){return Ub(e)},sha256(e){return Wb("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 qb(e,r)}},Jb="redskilled";function zb(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let r=e.XDG_CACHE_HOME||Pi(e.HOME||Mb(),".cache");return Pi(r,"red-skills","bundles")}var Qb=/^([a-z0-9-]+)-(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?)\.bundle\.min\.mjs$/;async function Yb(e,r){if(Ei(e.version))return e.version.trim();let t=e.listCacheDir??e_,n=Xb(t(r),"dev");if(n)return n;try{let s=await(e.bundleIO??Cc).fetchText(vi());return xi(Ti(s))}catch{return null}}function Xb(e,r){let t=null;for(let n of e){let o=Qb.exec(n);if(!o||o[1]!==r)continue;let s=o[2];(t===null||Zb(s,t)>0)&&(t=s)}return t}function Zb(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 e_(e){try{return Bb(e)}catch{return[]}}async function r_(e={},r={},t={}){let n=cr(e,r);if(He(n))return n;let o=t.env??r.env??process.env,s=zb(o),i=await Yb(t,s);if(i===null)return n;try{await Si(t.bundleIO??Cc,{plugin:Jb,version:i,cacheDir:s})}catch{return n}return cr(e,r)}async function Nc(e={},r={},t={}){let n=await r_(e,r,t);if(He(n))return n;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(rr(),Dc));throw new o(n)}import{randomUUID as as}from"node:crypto";import{mkdir as lT,rm as Wg}from"node:fs/promises";import{connect as dT,createServer as cT}from"node:net";import{dirname as uT}from"node:path";import{availableParallelism as Wc,totalmem as n_}from"node:os";function tn(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 Mc(e,r={}){let t=0,n=0,o=0,s=[],i=[];for(let d of e){let c=tn(d),u=!1;for(let[m,f]of[[c.memory_high,h=>t+=h],[c.memory_max,h=>n+=h]]){if(m==null)continue;let h=dt(m);h==null?u=!0:f(h)}c.cpu_weight!=null&&(o+=c.cpu_weight),u&&s.push(d.worker_id),d.isolated||i.push(d.worker_id)}let a=r.hostCeilingBytes??null,l=a==null?0:Math.max(0,n-a);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:n,cpu_weight_total:o,unaccounted_workers:s.sort(),unisolated_workers:i.sort(),memory_ceiling_bytes:a,over_committed_bytes:l,over_commitment_reason:l===0?null:t_(e.length,n,a,l)}}function t_(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 dt(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 Fc(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 Uc="REDSKILLED_MEMORY_CEILING",Ai="REDSKILLED_WORKER_CEILING",Vc="REDSKILLED_VALIDATION_CEILING",Bc="REDSKILLED_INTERACTIVE_RESERVATION",nn=1,Hc=.7,o_=2*1024**3,s_=2;function Kc(e){let r=e?.memory_max??e?.memory_high;if(r!=null)return dt(r)}function To(e){let r=0,t=[];for(let n of e){let o=Kc(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 Jc(e){let{ceiling:r}=e,t=To(e.workers),n=Kc(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??nn),l=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",d=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,c=(f,h)=>({version:1,admitted:!1,verdict:f,reason:h,ceiling:r,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}),u=r.worker_count==null?0:i-r.worker_count;if(u>0){if(e.reservation!=="interactive")return c("refused-over-worker-ceiling",`redskilled refused this Worker${l}: it would be Worker ${i} past a host ceiling of ${r.worker_count} Worker(s); ${a} extra slot(s) are reserved for interactive dispatches, and ${d}`);if(u>a)return c("refused-over-interactive-reservation",`redskilled refused this interactive Worker${l}: reserved slot ${u}/${a} is outside the bounded interactive reservation above the host ceiling of ${r.worker_count} Worker(s), and ${d}`)}if(r.memory_bytes!=null&&n===null)return c("refused-unaccountable-budget",`redskilled refused this Worker${l}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${r.memory_bytes} bytes, and ${d}`);if(r.memory_bytes!=null&&s>r.memory_bytes)return c("refused-over-memory-ceiling",`redskilled refused this Worker${l}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${r.memory_bytes} bytes, and ${d}`);let m=e.reservation==="interactive"&&u>0;return{version:1,admitted:!0,verdict:m?"admitted-interactive-reservation":"admitted",reason:m?`redskilled admitted this interactive Worker${l} into reserved interactive slot ${u}/${a} above the host ceiling of ${r.worker_count} Worker(s): ${s} bytes of declared Worker memory against a host ceiling of ${r.memory_bytes??"unbounded"} bytes, and ${d}`:`redskilled admitted this Worker${l}: ${s} bytes of declared Worker memory against a host ceiling of ${r.memory_bytes??"unbounded"} bytes, and ${d}`,ceiling:r,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function zc(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=To(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 (${Ai} 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 xo(e=process.env,r=n_(),t={}){let n=Oi(t.flags?.memoryCeiling,e[Uc],t.config?.memoryCeiling),o=Oi(t.flags?.workerCeiling,e[Ai],t.config?.workerCeiling),s=Oi(t.flags?.validationCeiling,e[Vc],t.config?.validationCeiling),i=n?.value??"",a=o?.value??"",l=(e[Bc]??"").trim(),d=Qc(a),c=l===""?nn:l_(l),u=o?.source??"derived-default";if(a!==""&&d===null&&!i_(a)&&(So(`redskilled: ${Di(o)} ${Ai}=${JSON.stringify(a)} is not a positive integer; this host admits an unbounded number of Workers instead.`),u="derived-default"),i!==""){let m=a_(i,r);if(m!==void 0)return qc({memory_bytes:m,worker_count:d,interactive_reservation:c??nn,source:"declared",memory_source:n.source,worker_source:u},s,t.availableParallelism??Wc());So(`redskilled: ${Di(n)} ${Uc}=${JSON.stringify(i)} is not a memory ceiling this host can read; using ${Hc*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return l!==""&&c===void 0&&So(`redskilled: ${Bc}=${JSON.stringify(l)} is not a non-negative integer; using the default reservation of ${nn} Worker(s) instead.`),qc({memory_bytes:Math.floor(r*Hc),worker_count:d,interactive_reservation:c??nn,memory_source:"derived-default",worker_source:u,source:"host-fraction"},s,t.availableParallelism??Wc())}function qc(e,r,t){if(r!==void 0){let i=Qc(r.value);if(i!==null)return{...e,validation_count:i,validation_source:r.source};So(`redskilled: ${Di(r)} ${Vc}=${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)/s_)),o=e.memory_bytes==null?Number.POSITIVE_INFINITY:Math.max(1,Math.floor(e.memory_bytes/o_)),s=e.worker_count??Number.POSITIVE_INFINITY;return{...e,validation_count:Math.max(1,Math.min(n,o,s)),validation_source:"derived-default"}}function Oi(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 Di(e){return e.source==="flag"?"serve flag":e.source==="environment"?"environment":e.source==="home-config"?"home config":"derived default"}function i_(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var So=e=>process.stderr.write(`${e}
|
|
62
|
+
`);function a_(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)):dt(e)??void 0}function Qc(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 l_(e){let r=Number(e);return Number.isSafeInteger(r)&&r>=0?r:void 0}import{appendFile as d_,mkdir as c_,open as u_,readFile as p_,stat as m_,truncate as Yc}from"node:fs/promises";import{dirname as g_}from"node:path";var f_=["worker-birth","worker-activity","worker-drift","worker-heal","worker-death","worker-budget-kill"],h_=["demand-refusal","daemon-stop"],Xc="redskilled.log.toonl";function Po(e){let r=e.worker.budget??{},t="kind"in e?e.kind:e.event;return{version:1,ts:e.ts,kind:t,event:t,worker_id:e.worker.worker_id,project_label:e.worker.project_label,pid:e.worker.pid,workspace_path:e.worker.workspace_path,fork_sha:e.worker.fork_sha??null,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,admission_verdict:"admissionVerdict"in e?e.admissionVerdict??null:null,phase:"phase"in e?e.phase??null:null,step:"step"in e?e.step??null:null,base_head_sha:"baseHeadSha"in e?e.baseHeadSha??null:null,base_commits_ahead:"baseCommitsAhead"in e?e.baseCommitsAhead??null:null,heal_kind:"healKind"in e?e.healKind??null:null,detail:e.detail??null,exit_code:e.exitCode??null,signal:e.signal??null,reason:"reason"in e?e.reason??null:null}}var y_="daemon:";function k_(e){return{version:1,ts:e.ts,kind:"daemon-stop",event:"daemon-stop",worker_id:`${y_}${e.pid}`,project_label:"",pid:e.pid,workspace_path:e.socketPath,fork_sha:null,log_path:null,isolated:!1,unit:null,memory_high:null,memory_max:null,cpu_weight:null,admission_verdict:null,phase:null,step:null,base_head_sha:null,base_commits_ahead:null,heal_kind:null,detail:e.detail,exit_code:null,signal:e.signal??null,reason:e.reason}}function b_(e){return{version:1,ts:e.ts,kind:"demand-refusal",event:"demand-refusal",worker_id:`demand:${e.projectLabel}`,project_label:e.projectLabel,pid:0,workspace_path:"",fork_sha:null,log_path:null,isolated:!1,unit:null,memory_high:null,memory_max:null,cpu_weight:null,admission_verdict:null,phase:null,step:null,base_head_sha:null,base_commits_ahead:null,heal_kind:null,detail:e.detail,exit_code:null,signal:null,reason:null}}function Zc(e){let r=ye({trailer:!1}),t=Promise.resolve();async function n(o){let s=t.then(async()=>{await c_(g_(e),{recursive:!0,mode:448}),await __(e),await d_(e,r.push(v_(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>n(Po(o)),recordWorker:o=>n(Po(o)),recordDemandRefusal:o=>n(b_(o)),recordDaemonStop:o=>n(k_(o)),read:()=>R_(e),flush:async()=>{await t}}}async function __(e){let r;try{r=(await m_(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(r===0)return;let t=64*1024,n=await u_(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 Yc(e,s-i+l+1);return}}await Yc(e,0)}finally{await n.close()}}async function R_(e){let r;try{r=await p_(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return w_(r)}function w_(e){let r=e.split(`
|
|
63
63
|
`);return r.pop(),r.length===0?[]:We(`${r.join(`
|
|
64
64
|
`)}
|
|
65
|
-
`).filter(E_).map(v_)}function Zc(e){let r=new Map;for(let t of e)t.kind==="daemon-stop"||t.kind==="demand-refusal"||(t.kind==="worker-birth"?r.set(t.worker_id,R_(t)):(t.kind==="worker-death"||t.kind==="worker-budget-kill")&&r.delete(t.worker_id));return[...r.values()]}function R_(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.fork_sha!=null?{fork_sha:e.fork_sha}:{},...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 w_(e){return{...e}}function E_(e){let r=e.kind??e.event;return e.version===1&&typeof e.ts=="string"&&typeof e.worker_id=="string"&&[...m_,...g_].includes(r)}function v_(e){let r=e.kind??e.event;return{version:1,ts:String(e.ts),kind:r,event:r,worker_id:String(e.worker_id),project_label:ue(e.project_label)??"",pid:Number(e.pid??0),workspace_path:ue(e.workspace_path)??"",fork_sha:ue(e.fork_sha),log_path:ue(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:ue(e.unit),memory_high:ue(e.memory_high),memory_max:ue(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),admission_verdict:ue(e.admission_verdict),phase:ue(e.phase),step:ue(e.step),base_head_sha:ue(e.base_head_sha),base_commits_ahead:e.base_commits_ahead==null||e.base_commits_ahead===""?null:Number(e.base_commits_ahead),heal_kind:ue(e.heal_kind),detail:ue(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:ue(e.signal),reason:ue(e.reason)}}function ue(e){return e==null||e===""?null:String(e)}function eu(e){let r=[...e.projects].sort((i,a)=>i.project_label.localeCompare(a.project_label)),t=e.backoffUntilMs??null,n=t!=null&&e.nowMs<t,o=[],s=[];for(let i of r){let a=Math.max(0,e.live[i.project_label]??0),l=Object.prototype.hasOwnProperty.call(e.queue,i.project_label),d=l?e.queue[i.project_label]??null:null,c={project_label:i.project_label,queue_depth:d,target:i.target,live:a};if(n){o.push({...c,outcome:"backing-off",wanted:0,detail:`the host refused a Worker, so no project is asked for one again before ${new Date(t).toISOString()}`});continue}let u=e.birthHealth?.[i.project_label],m=u?.haltUntilMs??e.birthHaltUntilMs?.[i.project_label];if(m!=null&&e.nowMs<m){o.push({...c,outcome:"birth-halted",wanted:0,detail:`project ${JSON.stringify(i.project_label)} lost 3 Workers in a row inside 60000ms of birth, so it is not asked for another before ${new Date(m).toISOString()} \u2014 a Worker that cannot survive boot will not survive the next one either, and every birth spends host quota shared with every project`});continue}if(u?.probeWorkerId!=null){o.push({...c,outcome:"half-open-probe",wanted:0,detail:`project ${JSON.stringify(i.project_label)} is half-open and probe Worker ${JSON.stringify(u.probeWorkerId)} has not yet survived 60000ms, so no second birth is admitted`});continue}if(d==null){o.push({...c,outcome:"queue-unknown",wanted:0,detail:l?`the last poll produced no depth for project ${JSON.stringify(i.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(i.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...c,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(i.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,i.target),d)-a);if(f===0){o.push({...c,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(i.project_label)} holds ${a} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for none`});continue}let h=u?.haltUntilMs!=null&&e.nowMs>=u.haltUntilMs,v=h?1:f;o.push({...c,outcome:h?"half-open-probe":"asking",wanted:v,detail:h?`project ${JSON.stringify(i.project_label)} finished its birth-breaker cooldown, so exactly one probe Worker is admitted before the remaining ${Math.max(0,f-1)} birth(s)`:`project ${JSON.stringify(i.project_label)} holds ${a} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for ${f} more`});for(let k=0;k<v;k+=1)(s[k]??(s[k]=[])).push({project_label:i.project_label,index:a+k,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function ru(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function tu(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 on={shortLifeStreak:0,haltUntilMs:null,openedAtMs:null,probeWorkerId:null};function nu(e,r,t){if(r>=6e4)return on;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 ou(e,r){return e.haltUntilMs==null?e:{...e,probeWorkerId:r}}function Di(){return on}function S_(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 su(e,r){return Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>S_(t,n,r)).filter(t=>t!=null)}function au(e){let r=e.workers.map(T_),t=[...new Set([...r.map(o=>o.project_label),...e.projects??[]])].filter(o=>o!=="").sort(),n=r.filter(o=>o.survives).map(o=>o.worker_id);return{version:1,running:!0,stopped:!0,reason:e.reason,socket_path:e.socketPath,daemon_version:e.daemonVersion,pid:e.pid,holding:{workers:r,projects:t},surviving:n,detail:P_({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:r.length,projects:t.length,surviving:n.length})}}function lu(e){return{version:1,running:!1,stopped:!1,reason:"not-running",socket_path:e,daemon_version:null,pid:null,holding:{workers:[],projects:[]},surviving:[],detail:`no redskilled daemon is answering on ${JSON.stringify(e)}, so there was nothing to stop`}}function T_(e){return{worker_id:e.worker_id,project_label:e.project_label,pid:e.pid,unit:e.unit??null,isolated:e.isolated,survives:!0}}function x_(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 P_(e){let r=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${x_(e.reason)}`;return e.held===0?`${r}; it holds no Workers, so nothing survives the stop`:`${r}; it holds ${iu(e.held,"Worker")} across ${iu(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 iu(e,r){return`${e} ${r}${e===1?"":"s"}`}function ji(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 O_,mkdir as A_,readFile as D_,rm as j_,writeFile as L_}from"node:fs/promises";import{dirname as du,join as mu}from"node:path";import{tmpdir as cu}from"node:os";var G_="redskilled.machine.claim.toon",I_="REDSKILLED_MACHINE_DIR",$_=8,ur=class extends Error{constructor(t,n,o){super(N_(t,n,o));this.claimPath=t;this.reason=n;this.claim=o;this.name="RedskilledMachineHeldError"}},uu;function gu(){return uu??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},uu}function C_(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()||cu():cu();return mu(o,`redskilled-${e.machineIdHash}`)}function Oo(e){return mu(C_(e),G_)}function Ao(e,r,t={}){let n=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??ne;async function s(){let l;try{l=await D_(e,"utf8")}catch(c){if(c.code==="ENOENT"||Li(c))return;throw c}let d=F_(l);return W_(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 j_(e,{force:!0}),!0}catch(l){if(Li(l))return!1;throw l}}return{claimPath:e,read:s,async claim(l){await A_(du(e),{recursive:!0,mode:1023})!=null&&await O_(du(e),1023).catch(()=>{});let c=!1;for(let u=0;u<$_;u+=1){let m=i(l,n());try{return await L_(e,M_(m),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:c,claim:m}}catch(h){if(h.code!=="EEXIST"){if(Li(h))return{claimed:!1,reason:"stale-claim-not-reapable"};throw h}}let f=await s();if(!f){if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable"};c=!0;continue}if(pu(f,l,r.socketPath))return{claimed:!0,reaped:c,claim:f};if(await o(f.pid))return{claimed:!1,reason:"held",claim:f};if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable",claim:f};c=!0}return{claimed:!1,reason:"contended"}},async release(l){let d=await s();return!d||!pu(d,l,r.socketPath)?!1:await a()}}}function fu(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 hu(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 N_(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 Li(e){let r=e?.code;return r==="EACCES"||r==="EPERM"||r==="EROFS"}function pu(e,r,t){return e.pid===r.pid&&e.start_time===r.startTime&&e.socket_path===t}function M_(e){return`${X(e,{keyedMapCollapse:!0})}
|
|
66
|
-
`}function F_(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return me(r)}catch{return null}}}function W_(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 U_=["worker_id","slot","workspace_path","log_path"],Gi=class extends Error{constructor(t,n){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${n}: the facts a birth supplies are ${U_.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},B_=/\{\{([a-z_]+)\}\}/g;function H_(e,r){let t=(i,a)=>i.replace(B_,(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 Gi(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 yu(e,r,t){let n=H_(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 $i(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 Ci(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 q_=3e5,V_=.5,Ni=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 ku(e,r){if(r.held!=null)throw new Ni(r.held);let t=sn(e.project_label,"a project label"),n=sn(e.selector,"a selector"),o=Q_(e.queue_poll,t),s=Ii(e.argv,t),i=Ci(e.env,t),a=$i(e.log_path,t),l=sn(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`),d=e.trunk==null?void 0:{remote:sn(e.trunk.remote,`a trunk remote for project ${JSON.stringify(t)}`),branch:sn(e.trunk.branch,`a trunk branch 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 c=e.renew_within_ms??q_;if(!Number.isFinite(c)||c<=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 u=Date.parse(r.now);if(!Number.isFinite(u))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,...d==null?{}:{trunk:d},env:i,...a==null?{}:{log_path:a},target:e.target,registered_at:new Date(u).toISOString(),renew_within_ms:c,renew_by:new Date(u+c).toISOString(),renewed_at:new Date(u).toISOString(),renewals:0,session_renewals:0,launch_revision:0}}var Ir=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 bu(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:Ci(r.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=r.launch==null?e.log_path:$i(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 Mi(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 J_(e,r){let t=Date.parse(e.renew_by);return Number.isFinite(t)?r>=t:!1}function _u(e,r){let t=Date.parse(e.renewed_at??e.registered_at),n=s=>Number.isFinite(s)&&r-s<=e.renew_within_ms*V_;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 Ru(e,r){let t=[],n=[];for(let o of e)(J_(o,r)?n:t).push(o);return{standing:t,lapsed:n}}function an(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||wu(r.queue_poll))&&Array.isArray(r.argv)&&r.argv.every(t=>typeof t=="string")&&typeof r.workspace_path=="string"&&(r.trunk===void 0||z_(r.trunk))&&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||Y_(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 z_(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.remote=="string"&&r.remote.trim()!==""&&typeof r.branch=="string"&&r.branch.trim()!==""}function Q_(e,r){if(e!==void 0){if(!wu(e))throw new Error(`redskilled needs a complete queue poll plan for project ${JSON.stringify(r)} when one is stated`);return e}}function wu(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 Y_(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(r=>typeof r=="string")}function sn(e,r){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${r} to register a project, not ${JSON.stringify(e)}`);return e}var X_={ping:"host-read","host-state":"host-read","statusline-payload":"host-read",shutdown:"daemon-life","worker-start":"project-write","worker-stop":"project-write","worker-recycle":"project-write","worker-steer":"project-write","worker-heartbeat":"project-write","project-register":"project-write","project-renew":"project-write","project-reset":"project-write","project-deregister":"project-write"};function Eu(e){return`worker-${e}`}function vu(e){let r=X_[e.op]??"project-write",t=e.sessionProject??null,n=e.targetProject??null,o={version:1,op:e.op,reach:r,session_project:t,target_project:n};return r==="host-read"?{...o,permitted:!0,verdict:"permitted-host-read",reason:`redskilled permitted ${e.op}: a session reads the whole host, whichever project it was started in`}:r==="daemon-life"?{...o,permitted:!0,verdict:"permitted-daemon-life",reason:`redskilled permitted ${e.op}: it acts on the daemon's own process, not on any project's Workers`}:t==null||t===""?{...o,permitted:!0,verdict:"permitted-unattributed",reason:`redskilled permitted ${e.op}: the session named no project of its own, so there is nothing to refuse it against`}:n!=null&&n===t?{...o,permitted:!0,verdict:"permitted-own-project",reason:`redskilled permitted ${e.op}: the target belongs to project ${JSON.stringify(t)}, which is this session's own`}:{...o,permitted:!1,verdict:"refused-cross-project",reason:`redskilled refused ${e.op} from a session in project ${JSON.stringify(t)}: ${n==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(n)}`}. A session reads the whole host and writes only its own project.`}}function Su(e){return e==="single-object"?"rest":"graphql"}function Tu(e,r){return e==="stable-poll"?"rest":Su(r)}function Te(e){return{none:e}}function Z(e,r,t,n,o,s,i){let a=typeof o=="string"?{fallback:o}:{fallback:null,noFallbackBecause:o.none};return{key:e,kind:"read",cardinality:r,volatility:t,surface:i??Tu(t,r),budget:n,...a,...i?{only:i}:{},why:s}}function ge(e,r,t,n){return{key:e,kind:"write",cardinality:"single-object",surface:r,budget:t,fallback:null,noFallbackBecause:"a mutation has one observed GitHub API method",why:n}}var xu=[Z("issue view","single-object","stable-poll","rest","graphql","one issue by number, repeatedly polled while usually unchanged; REST answers in one request"),Z("pr view","single-object","stable-poll","rest","graphql","one pull request by number, polled per Worker per iteration"),Z("repo view","single-object","stable-poll","rest","graphql","one repository's own metadata, repeatedly read while usually unchanged"),Z("run view","single-object","stable-poll","rest",Te("Actions runs have no GraphQL resource"),"one Actions run repeatedly polled to terminal"),Z("release view","single-object","stable-poll","rest",Te("release lookup has no GraphQL client method"),"one release by tag, repeatedly checked while usually absent or unchanged"),Z("pr diff","single-object","one-shot","rest",Te("the complete diff is exposed as a REST media type"),"one pull request's diff, read once for review"),Z("issue list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged issue collection; REST can make an unchanged poll free"),Z("pr list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged pull-request collection; REST can make an unchanged poll free"),Z("pr checks","multi-node","stable-poll","rest","graphql","check contexts are repeatedly polled while awaiting terminal state"),Z("release list","multi-node","stable-poll","rest",Te("Releases has no GraphQL collection client method"),"release waits poll a usually-unchanged list"),Z("run list","multi-node","stable-poll","rest",Te("Actions has no GraphQL collection client method"),"run waits poll a usually-unchanged list"),Z("label list","multi-node","one-shot","graphql","rest","a label connection loaded once for the current operation"),Z("issue list (search)","multi-node","stable-poll","search",Te("search is ineligible for diverted traffic"),"queue discovery polls usually-unchanged search results through the 30/min search connection"),Z("pr list (search)","multi-node","stable-poll","search",Te("search is ineligible for diverted traffic"),"PR discovery polls usually-unchanged search results through the 30/min search connection"),Z("search issues","multi-repository","one-shot","search",Te("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),Z("search prs","multi-repository","one-shot","search",Te("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),Z("search repos","multi-repository","one-shot","search",Te("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),Z("api graphql","multi-node","one-shot","graphql",Te("the caller explicitly chose GraphQL"),"the caller supplies one explicit GraphQL query rather than a routed poll"),Z("api rest","single-object","one-shot","rest",Te("the caller explicitly chose REST"),"the caller supplies one explicit REST path rather than a routed poll"),ge("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),ge("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),ge("issue close","graphql","graphql","gh closes with the closeIssue mutation"),ge("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),ge("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),ge("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),ge("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),ge("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),ge("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),ge("pr close","graphql","graphql","gh closes with a GraphQL mutation"),ge("pr edit","graphql","graphql","gh edits with GraphQL mutations"),ge("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),ge("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),ge("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],Z_=new Map(xu.map(e=>[e.key,e]));function Pu(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 Fi(e){let r=Pu(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 Do=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(r){let t=Fi(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 Ou(e){return Z_.get(Fi(e))??null}function Au(e){let r=Ou(e);if(!r)throw new Do(e);return r}function Wi(e){return Au(e).surface}import{appendFile as eR,mkdir as rR,readFile as tR}from"node:fs/promises";import{dirname as nR}from"node:path";function jo(e){let r=e.now??(()=>new Date().toISOString()),t=Promise.resolve();return{record(n){let o=oR(n.operation,n.cost,n.observedAt??r(),n.actor),s=ye().push(iR(o));return t=t.then(async()=>{await rR(nR(e.path),{recursive:!0}),await eR(e.path,s,"utf8")}),t},async report(n){await t;let o=Ui(n.from,"report window start"),s=Ui(n.to,"report window end");if(s<=o)throw new Error("GitHub attribution report window end must be after its start");let i=await sR(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 oR(e,r,t,n){if(Ui(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 sR(e){let r;try{r=await tR(e,"utf8")}catch(s){if(dR(s)&&s.code==="ENOENT")return{observations:[],unreadable:0};throw s}let t=[],n=0,o=r.split(`
|
|
65
|
+
`).filter(S_).map(T_)}function eu(e){let r=new Map;for(let t of e)t.kind==="daemon-stop"||t.kind==="demand-refusal"||(t.kind==="worker-birth"?r.set(t.worker_id,E_(t)):(t.kind==="worker-death"||t.kind==="worker-budget-kill")&&r.delete(t.worker_id));return[...r.values()]}function E_(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.fork_sha!=null?{fork_sha:e.fork_sha}:{},...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 v_(e){return{...e}}function S_(e){let r=e.kind??e.event;return e.version===1&&typeof e.ts=="string"&&typeof e.worker_id=="string"&&[...f_,...h_].includes(r)}function T_(e){let r=e.kind??e.event;return{version:1,ts:String(e.ts),kind:r,event:r,worker_id:String(e.worker_id),project_label:ue(e.project_label)??"",pid:Number(e.pid??0),workspace_path:ue(e.workspace_path)??"",fork_sha:ue(e.fork_sha),log_path:ue(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:ue(e.unit),memory_high:ue(e.memory_high),memory_max:ue(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),admission_verdict:ue(e.admission_verdict),phase:ue(e.phase),step:ue(e.step),base_head_sha:ue(e.base_head_sha),base_commits_ahead:e.base_commits_ahead==null||e.base_commits_ahead===""?null:Number(e.base_commits_ahead),heal_kind:ue(e.heal_kind),detail:ue(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:ue(e.signal),reason:ue(e.reason)}}function ue(e){return e==null||e===""?null:String(e)}function ru(e){let r=[...e.projects].sort((i,a)=>i.project_label.localeCompare(a.project_label)),t=e.backoffUntilMs??null,n=t!=null&&e.nowMs<t,o=[],s=[];for(let i of r){let a=Math.max(0,e.live[i.project_label]??0),l=Object.prototype.hasOwnProperty.call(e.queue,i.project_label),d=l?e.queue[i.project_label]??null:null,c={project_label:i.project_label,queue_depth:d,target:i.target,live:a};if(n){o.push({...c,outcome:"backing-off",wanted:0,detail:`the host refused a Worker, so no project is asked for one again before ${new Date(t).toISOString()}`});continue}let u=e.birthHealth?.[i.project_label],m=u?.haltUntilMs??e.birthHaltUntilMs?.[i.project_label];if(m!=null&&e.nowMs<m){o.push({...c,outcome:"birth-halted",wanted:0,detail:`project ${JSON.stringify(i.project_label)} lost 3 Workers in a row inside 60000ms of birth, so it is not asked for another before ${new Date(m).toISOString()} \u2014 a Worker that cannot survive boot will not survive the next one either, and every birth spends host quota shared with every project`});continue}if(u?.probeWorkerId!=null){o.push({...c,outcome:"half-open-probe",wanted:0,detail:`project ${JSON.stringify(i.project_label)} is half-open and probe Worker ${JSON.stringify(u.probeWorkerId)} has not yet survived 60000ms, so no second birth is admitted`});continue}if(d==null){o.push({...c,outcome:"queue-unknown",wanted:0,detail:l?`the last poll produced no depth for project ${JSON.stringify(i.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(i.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...c,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(i.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,i.target),d)-a);if(f===0){o.push({...c,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(i.project_label)} holds ${a} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for none`});continue}let h=u?.haltUntilMs!=null&&e.nowMs>=u.haltUntilMs,v=h?1:f;o.push({...c,outcome:h?"half-open-probe":"asking",wanted:v,detail:h?`project ${JSON.stringify(i.project_label)} finished its birth-breaker cooldown, so exactly one probe Worker is admitted before the remaining ${Math.max(0,f-1)} birth(s)`:`project ${JSON.stringify(i.project_label)} holds ${a} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for ${f} more`});for(let k=0;k<v;k+=1)(s[k]??(s[k]=[])).push({project_label:i.project_label,index:a+k,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function tu(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function nu(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 on={shortLifeStreak:0,haltUntilMs:null,openedAtMs:null,probeWorkerId:null};function ou(e,r,t){if(r>=6e4)return on;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 su(e,r){return e.haltUntilMs==null?e:{...e,probeWorkerId:r}}function ji(){return on}function x_(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 iu(e,r){return Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>x_(t,n,r)).filter(t=>t!=null)}function lu(e){let r=e.workers.map(P_),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:A_({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:r.length,projects:t.length,surviving:n.length})}}function du(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 P_(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 O_(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 A_(e){let r=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${O_(e.reason)}`;return e.held===0?`${r}; it holds no Workers, so nothing survives the stop`:`${r}; it holds ${au(e.held,"Worker")} across ${au(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 au(e,r){return`${e} ${r}${e===1?"":"s"}`}function Li(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 D_,mkdir as j_,readFile as L_,rm as G_,writeFile as I_}from"node:fs/promises";import{dirname as cu,join as gu}from"node:path";import{tmpdir as uu}from"node:os";var $_="redskilled.machine.claim.toon",C_="REDSKILLED_MACHINE_DIR",N_=8,ur=class extends Error{constructor(t,n,o){super(F_(t,n,o));this.claimPath=t;this.reason=n;this.claim=o;this.name="RedskilledMachineHeldError"}},pu;function fu(){return pu??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},pu}function M_(e={machineIdHash:"unknown"}){let r=e.env??process.env,t=r[C_]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?r.PROGRAMDATA?.trim()||uu():uu();return gu(o,`redskilled-${e.machineIdHash}`)}function Oo(e){return gu(M_(e),$_)}function Ao(e,r,t={}){let n=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??ne;async function s(){let l;try{l=await L_(e,"utf8")}catch(c){if(c.code==="ENOENT"||Gi(c))return;throw c}let d=U_(l);return B_(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 G_(e,{force:!0}),!0}catch(l){if(Gi(l))return!1;throw l}}return{claimPath:e,read:s,async claim(l){await j_(cu(e),{recursive:!0,mode:1023})!=null&&await D_(cu(e),1023).catch(()=>{});let c=!1;for(let u=0;u<N_;u+=1){let m=i(l,n());try{return await I_(e,W_(m),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:c,claim:m}}catch(h){if(h.code!=="EEXIST"){if(Gi(h))return{claimed:!1,reason:"stale-claim-not-reapable"};throw h}}let f=await s();if(!f){if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable"};c=!0;continue}if(mu(f,l,r.socketPath))return{claimed:!0,reaped:c,claim:f};if(await o(f.pid))return{claimed:!1,reason:"held",claim:f};if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable",claim:f};c=!0}return{claimed:!1,reason:"contended"}},async release(l){let d=await s();return!d||!mu(d,l,r.socketPath)?!1:await a()}}}function hu(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 yu(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 F_(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 Gi(e){let r=e?.code;return r==="EACCES"||r==="EPERM"||r==="EROFS"}function mu(e,r,t){return e.pid===r.pid&&e.start_time===r.startTime&&e.socket_path===t}function W_(e){return`${X(e,{keyedMapCollapse:!0})}
|
|
66
|
+
`}function U_(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return me(r)}catch{return null}}}function B_(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 H_=["worker_id","slot","workspace_path","log_path"],Do=class extends Error{constructor(t,n){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${n}: the facts a birth supplies are ${H_.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},ku=/\{\{([a-z_]+)\}\}/g;function q_(e,r){let t=(i,a)=>i.replace(ku,(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 Do(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 bu(e,r){if(!(e==null||e.trim()===""))return e.replace(ku,(t,n)=>{switch(n){case"worker_id":return r.worker_id;case"workspace_path":return r.workspace_path;default:throw new Do(n,"the log path")}})}function _u(e,r,t){let n=q_(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 $i(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 Ci(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 V_=3e5,K_=.5,Ni=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 Ru(e,r){if(r.held!=null)throw new Ni(r.held);let t=sn(e.project_label,"a project label"),n=sn(e.selector,"a selector"),o=Y_(e.queue_poll,t),s=Ii(e.argv,t),i=Ci(e.env,t),a=$i(e.log_path,t),l=sn(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`),d=e.trunk==null?void 0:{remote:sn(e.trunk.remote,`a trunk remote for project ${JSON.stringify(t)}`),branch:sn(e.trunk.branch,`a trunk branch 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 c=e.renew_within_ms??V_;if(!Number.isFinite(c)||c<=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 u=Date.parse(r.now);if(!Number.isFinite(u))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,...d==null?{}:{trunk:d},env:i,...a==null?{}:{log_path:a},target:e.target,registered_at:new Date(u).toISOString(),renew_within_ms:c,renew_by:new Date(u+c).toISOString(),renewed_at:new Date(u).toISOString(),renewals:0,session_renewals:0,launch_revision:0}}var Ir=class extends Error{constructor(t,n={kind:"never"}){super(J_(t,n));this.projectLabel=t;this.absence=n;this.name="RedskilledProjectUnregisteredError"}};function J_(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 wu(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:Ci(r.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=r.launch==null?e.log_path:$i(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 Mi(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 z_(e,r){let t=Date.parse(e.renew_by);return Number.isFinite(t)?r>=t:!1}function Eu(e,r){let t=Date.parse(e.renewed_at??e.registered_at),n=s=>Number.isFinite(s)&&r-s<=e.renew_within_ms*K_;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 vu(e,r){let t=[],n=[];for(let o of e)(z_(o,r)?n:t).push(o);return{standing:t,lapsed:n}}function an(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||Su(r.queue_poll))&&Array.isArray(r.argv)&&r.argv.every(t=>typeof t=="string")&&typeof r.workspace_path=="string"&&(r.trunk===void 0||Q_(r.trunk))&&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||X_(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 Q_(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.remote=="string"&&r.remote.trim()!==""&&typeof r.branch=="string"&&r.branch.trim()!==""}function Y_(e,r){if(e!==void 0){if(!Su(e))throw new Error(`redskilled needs a complete queue poll plan for project ${JSON.stringify(r)} when one is stated`);return e}}function Su(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 X_(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(r=>typeof r=="string")}function sn(e,r){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${r} to register a project, not ${JSON.stringify(e)}`);return e}var Z_={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 Tu(e){return`worker-${e}`}function xu(e){let r=Z_[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 Pu(e){return e==="single-object"?"rest":"graphql"}function Ou(e,r){return e==="stable-poll"?"rest":Pu(r)}function Te(e){return{none:e}}function Z(e,r,t,n,o,s,i){let a=typeof o=="string"?{fallback:o}:{fallback:null,noFallbackBecause:o.none};return{key:e,kind:"read",cardinality:r,volatility:t,surface:i??Ou(t,r),budget:n,...a,...i?{only:i}:{},why:s}}function ge(e,r,t,n){return{key:e,kind:"write",cardinality:"single-object",surface:r,budget:t,fallback:null,noFallbackBecause:"a mutation has one observed GitHub API method",why:n}}var Au=[Z("issue view","single-object","stable-poll","rest","graphql","one issue by number, repeatedly polled while usually unchanged; REST answers in one request"),Z("pr view","single-object","stable-poll","rest","graphql","one pull request by number, polled per Worker per iteration"),Z("repo view","single-object","stable-poll","rest","graphql","one repository's own metadata, repeatedly read while usually unchanged"),Z("run view","single-object","stable-poll","rest",Te("Actions runs have no GraphQL resource"),"one Actions run repeatedly polled to terminal"),Z("release view","single-object","stable-poll","rest",Te("release lookup has no GraphQL client method"),"one release by tag, repeatedly checked while usually absent or unchanged"),Z("pr diff","single-object","one-shot","rest",Te("the complete diff is exposed as a REST media type"),"one pull request's diff, read once for review"),Z("issue list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged issue collection; REST can make an unchanged poll free"),Z("pr list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged pull-request collection; REST can make an unchanged poll free"),Z("pr checks","multi-node","stable-poll","rest","graphql","check contexts are repeatedly polled while awaiting terminal state"),Z("release list","multi-node","stable-poll","rest",Te("Releases has no GraphQL collection client method"),"release waits poll a usually-unchanged list"),Z("run list","multi-node","stable-poll","rest",Te("Actions has no GraphQL collection client method"),"run waits poll a usually-unchanged list"),Z("label list","multi-node","one-shot","graphql","rest","a label connection loaded once for the current operation"),Z("issue list (search)","multi-node","stable-poll","search",Te("search is ineligible for diverted traffic"),"queue discovery polls usually-unchanged search results through the 30/min search connection"),Z("pr list (search)","multi-node","stable-poll","search",Te("search is ineligible for diverted traffic"),"PR discovery polls usually-unchanged search results through the 30/min search connection"),Z("search issues","multi-repository","one-shot","search",Te("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),Z("search prs","multi-repository","one-shot","search",Te("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),Z("search repos","multi-repository","one-shot","search",Te("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),Z("api graphql","multi-node","one-shot","graphql",Te("the caller explicitly chose GraphQL"),"the caller supplies one explicit GraphQL query rather than a routed poll"),Z("api rest","single-object","one-shot","rest",Te("the caller explicitly chose REST"),"the caller supplies one explicit REST path rather than a routed poll"),ge("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),ge("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),ge("issue close","graphql","graphql","gh closes with the closeIssue mutation"),ge("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),ge("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),ge("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),ge("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),ge("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),ge("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),ge("pr close","graphql","graphql","gh closes with a GraphQL mutation"),ge("pr edit","graphql","graphql","gh edits with GraphQL mutations"),ge("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),ge("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),ge("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],eR=new Map(Au.map(e=>[e.key,e]));function Du(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 Fi(e){let r=Du(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 jo=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(r){let t=Fi(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 ju(e){return eR.get(Fi(e))??null}function Lu(e){let r=ju(e);if(!r)throw new jo(e);return r}function Wi(e){return Lu(e).surface}import{appendFile as rR,mkdir as tR,readFile as nR}from"node:fs/promises";import{dirname as oR}from"node:path";function Lo(e){let r=e.now??(()=>new Date().toISOString()),t=Promise.resolve();return{record(n){let o=sR(n.operation,n.cost,n.observedAt??r(),n.actor),s=ye().push(aR(o));return t=t.then(async()=>{await tR(oR(e.path),{recursive:!0}),await rR(e.path,s,"utf8")}),t},async report(n){await t;let o=Ui(n.from,"report window start"),s=Ui(n.to,"report window end");if(s<=o)throw new Error("GitHub attribution report window end must be after its start");let i=await iR(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 sR(e,r,t,n){if(Ui(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 iR(e){let r;try{r=await nR(e,"utf8")}catch(s){if(cR(s)&&s.code==="ENOENT")return{observations:[],unreadable:0};throw s}let t=[],n=0,o=r.split(`
|
|
67
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=We(`${i}
|
|
68
68
|
${a}
|
|
69
|
-
`)[0]}catch{n+=1,s+=1;continue}if(!
|
|
69
|
+
`)[0]}catch{n+=1,s+=1;continue}if(!lR(l)){n+=1,s+=1;continue}t.push(l),s+=1}return{observations:t,unreadable:n}}function aR(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 lR(e){return dR(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 Ui(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 dR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cR(e){return e instanceof Error&&"code"in e}var Iu=Ts(qi(),1);var tr=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 uR="0.0.0-development";function pR(e){return e.request!==void 0}async function Gu(e,r,t,n){if(!pR(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 mR(e,r,t,n){let o=new Iu.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(gR.bind(null,e,r,t),n)}async function gR(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 tr(o.data.errors[0].message,500,{request:n,response:o});return Gu(e,r,s,n)}return o}function Vi(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",Gu.bind(null,t,n)),e.hook.wrap("request",mR.bind(null,t,n))),n}Vi.VERSION=uR;var Cu=Ts(qi(),1),fR="0.0.0-development",Ki=()=>Promise.resolve();function hR(e,r,t){return e.retryLimiter.schedule(yR,e,r,t)}async function yR(e,r,t){let{pathname:n}=new URL(t.url,"http://github.test"),o=kR(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,Ki),s&&e.triggersNotification(n)&&await e.notifications.key(e.id).schedule(d,Ki),i&&await e.search.key(e.id).schedule(d,Ki);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 kR(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 bR=["/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 _R(e){let t=`^(?:${e.map(n=>n.split("/").map(o=>o.startsWith("{")?"(?:.+?)":o).join("/")).map(n=>`(?:${n})`).join("|")})[^/]*$`;return new RegExp(t,"i")}var $u=_R(bR),Nu=$u.test.bind($u),je={},RR=function(e,r){je.global=new e.Group({id:"octokit-global",maxConcurrent:10,...r}),je.auth=new e.Group({id:"octokit-auth",maxConcurrent:1,...r}),je.search=new e.Group({id:"octokit-search",maxConcurrent:1,minTime:2e3,...r}),je.write=new e.Group({id:"octokit-write",maxConcurrent:1,minTime:1e3,...r}),je.notifications=new e.Group({id:"octokit-notifications",maxConcurrent:1,minTime:3e3,...r})};function Go(e,r){let{enabled:t=!0,Bottleneck:n=Cu.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:Nu,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,32 +76,32 @@ ${a}
|
|
|
76
76
|
onRateLimit: (retryAfter, options) => {/* ... */}
|
|
77
77
|
}
|
|
78
78
|
})
|
|
79
|
-
`);let d=!1,c=()=>{if(d)return;d=!0,je.global==null&&
|
|
80
|
-
`+n.repeat(u));let k=h.val[h.index],T=i(h.val,String(h.index),k);if(ea(T))c.push("null"),h.first=!1,h.index++;else{let
|
|
79
|
+
`);let d=!1,c=()=>{if(d)return;d=!0,je.global==null&&RR(n,a),l.global=l.global??je.global,l.auth=l.auth??je.auth,l.search=l.search??je.search,l.write=l.write??je.write,l.notifications=l.notifications??je.notifications,l.retryLimiter=l.retryLimiter??new n;let u={},m=new n.Events(u);u.on("secondary-limit",l.onSecondaryRateLimit),u.on("rate-limit",l.onRateLimit),u.on("error",f=>e.log.warn("Error in throttling-plugin limit handler",f)),l.retryLimiter.on("failed",async function(f,h){let[v,k,T]=h.args,{pathname:I}=new URL(T.url,"http://github.test");if(!(I.startsWith("/graphql")&&f.status!==401||f.status===403||f.status===429))return;let G=~~k.retryCount;k.retryCount=G,T.request.retryCount=G;let{wantRetry:H,retryAfter:ee=0}=await async function(){if(/\bsecondary rate\b/i.test(f.message)){let q=Number(f.response.headers["retry-after"])||v.fallbackSecondaryRateRetryAfter;return{wantRetry:await m.trigger("secondary-limit",q,T,e,G),retryAfter:q}}if(f.response.headers!=null&&f.response.headers["x-ratelimit-remaining"]==="0"||(f.response.data?.errors??[]).some(q=>q.type==="RATE_LIMITED")){let q=new Date(~~f.response.headers["x-ratelimit-reset"]*1e3).getTime(),he=Math.max(Math.ceil((q-Date.now())/1e3)+1,0);return{wantRetry:await m.trigger("rate-limit",he,T,e,G),retryAfter:he}}return{}}();if(H)return k.retryCount++,ee*v.retryAfterBaseValue})};return e.hook.wrap("request",(u,m)=>(c(),hR(l,u,m))),{}}Go.VERSION=fR;Go.triggersNotification=Nu;function pr(){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 Io(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)=>Io.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 Mu(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 Fu(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 Wu=Function.bind,Uu=Wu.bind(Wu);function Bu(e,r,t){let n=Uu(Fu,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]=Uu(Mu,null).apply(null,s)})}function wR(){let e=Symbol("Singular"),r={registry:{}},t=Io.bind(null,r,e);return Bu(t,r,e),t}function ER(){let e={registry:{}},r=Io.bind(null,e);return Bu(r,e),r}var Hu={Singular:wR,Collection:ER};var vR="0.0.0-development",SR=`octokit-endpoint.js/${vR} ${pr()}`,TR={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":SR},mediaType:{format:""}};function xR(e){return e?Object.keys(e).reduce((r,t)=>(r[t.toLowerCase()]=e[t],r),{}):{}}function PR(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 Ku(e,r){let t=Object.assign({},e);return Object.keys(r).forEach(n=>{PR(r[n])?n in e?t[n]=Ku(e[n],r[n]):Object.assign(t,{[n]:r[n]}):Object.assign(t,{[n]:r[n]})}),t}function qu(e){for(let r in e)e[r]===void 0&&delete e[r];return e}function zi(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=xR(t.headers),qu(t),qu(t.headers);let n=Ku(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 OR(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 AR=/\{[^{}}]+\}/g;function DR(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function jR(e){let r=e.match(AR);return r?r.map(DR).reduce((t,n)=>t.concat(n),[]):[]}function Vu(e,r){let t={__proto__:null};for(let n of Object.keys(e))r.indexOf(n)===-1&&(t[n]=e[n]);return t}function Ju(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 ut(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(r){return"%"+r.charCodeAt(0).toString(16).toUpperCase()})}function ln(e,r,t){return r=e==="+"||e==="#"?Ju(r):ut(r),t?ut(t)+"="+r:r}function ct(e){return e!=null}function Ji(e){return e===";"||e==="&"||e==="?"}function LR(e,r,t,n){var o=e[t],s=[];if(ct(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(ln(r,o,Ji(r)?t:""));else if(n==="*")Array.isArray(o)?o.filter(ct).forEach(function(i){s.push(ln(r,i,Ji(r)?t:""))}):Object.keys(o).forEach(function(i){ct(o[i])&&s.push(ln(r,o[i],i))});else{let i=[];Array.isArray(o)?o.filter(ct).forEach(function(a){i.push(ln(r,a))}):Object.keys(o).forEach(function(a){ct(o[a])&&(i.push(ut(a)),i.push(ln(r,o[a].toString())))}),Ji(r)?s.push(ut(t)+"="+i.join(",")):i.length!==0&&s.push(i.join(","))}else r===";"?ct(o)&&s.push(ut(t)):o===""&&(r==="&"||r==="?")?s.push(ut(t)+"="):o===""&&s.push("");return s}function GR(e){return{expand:IR.bind(null,e)}}function IR(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(LR(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 Ju(s)}),e==="/"?e:e.replace(/\/$/,"")}function zu(e){let r=e.method.toUpperCase(),t=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),n=Object.assign({},e.headers),o,s=Vu(e,["method","baseUrl","url","headers","request","mediaType"]),i=jR(t);t=GR(t).expand(s),/^http/.test(t)||(t=e.baseUrl+t);let a=Object.keys(e).filter(c=>i.includes(c)).concat("baseUrl"),l=Vu(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=OR(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 $R(e,r,t){return zu(zi(e,r,t))}function Qu(e,r){let t=zi(e,r),n=$R.bind(null,t);return Object.assign(n,{DEFAULTS:t,defaults:Qu.bind(null,t),merge:zi.bind(null,t),parse:zu})}var Yu=Qu(null,TR);var fp=Ts(op(),1);var VR=/^-?\d+$/,No=/^-?\d+n+$/,mr=JSON.stringify,Zi=JSON.parse,dp=/^-?\d+n$/,sp=/([\[:])?"(-?\d+)n"($|\s*[,\}\]])/g,ip=/([\[:])?("-?\d+n+)n("$|"\s*[,\}\]])/g,ea=e=>e===void 0||typeof e=="function"||typeof e=="symbol",ra=e=>e!==null&&typeof e=="object"&&e.constructor&&e.constructor.name==="RawJSON",KR=(e,r,t)=>{let n="";typeof t=="number"?n=" ".repeat(Math.min(10,Math.max(0,Math.floor(t)))):typeof t=="string"&&(n=t.slice(0,10));let o=typeof r=="function",s=Array.isArray(r)?new Set(r.map(String)):null,i=(h,v,k)=>(k!==null&&typeof k=="object"&&typeof k.toJSON=="function"&&(k=k.toJSON(v)),typeof k=="string"&&No.test(k)?k+"n":typeof k=="bigint"?"rawJSON"in JSON?JSON.rawJSON(k.toString()):k.toString()+"n":(o&&(k=r.call(h,v,k)),k!==null&&typeof k=="object"&&(k instanceof Number||k instanceof String||k instanceof Boolean)&&(k=k.valueOf()),k)),a=i({"":e},"",e);if(ea(a))return;let l=a===null||typeof a!="object",d=ra(a);if(l||d)return mr(a);let c=[],u=0,m=[{parent:{"":a},key:"",val:a,isArray:Array.isArray(a),keys:Array.isArray(a)?null:Object.keys(a),index:0,first:!0}],f=new WeakSet([a]);for(;m.length>0;){let h=m[m.length-1];h.index===0&&(c.push(h.isArray?"[":"{"),u++);let v=!1;if(h.isArray)if(h.index<h.val.length){h.first||c.push(","),n&&c.push(`
|
|
80
|
+
`+n.repeat(u));let k=h.val[h.index],T=i(h.val,String(h.index),k);if(ea(T))c.push("null"),h.first=!1,h.index++;else{let I=T!==null&&typeof T=="object",F=ra(T);if(I&&!F){if(f.has(T))throw new TypeError("Converting circular structure to JSON");f.add(T),m.push({parent:h.val,key:String(h.index),val:T,isArray:Array.isArray(T),keys:Array.isArray(T)?null:Object.keys(T),index:0,first:!0}),h.first=!1,h.index++}else c.push(mr(T)),h.first=!1,h.index++}}else v=!0;else{for(;h.index<h.keys.length;){let T=h.keys[h.index++];if(s&&!s.has(T))continue;let F=h.val[T],G=i(h.val,T,F);if(ea(G))continue;h.first||c.push(","),n?c.push(`
|
|
81
81
|
`+n.repeat(u)+mr(T)+": "):c.push(mr(T)+":");let H=G!==null&&typeof G=="object",ee=ra(G);if(H&&!ee){if(f.has(G))throw new TypeError("Converting circular structure to JSON");f.add(G),m.push({parent:h.val,key:T,val:G,isArray:Array.isArray(G),keys:Array.isArray(G)?null:Object.keys(G),index:0,first:!0}),h.first=!1;break}else c.push(mr(G)),h.first=!1}h.index>=h.keys.length&&m[m.length-1]===h&&(v=!0)}v&&(u--,!h.first&&n&&c.push(`
|
|
82
|
-
`+n.repeat(u)),c.push(h.isArray?"]":"}"),f.delete(h.val),m.pop())}return c.join("")},
|
|
82
|
+
`+n.repeat(u)),c.push(h.isArray?"]":"}"),f.delete(h.val),m.pop())}return c.join("")},cp=(e,r,t)=>{try{return"rawJSON"in JSON?mr(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?mr(e,(a,l)=>typeof l=="string"&&No.test(l)||typeof l=="bigint"?l.toString()+"n":typeof r=="function"?r(a,l):(Array.isArray(r)&&r.includes(a),l),t).replace(sp,"$1$2$3").replace(ip,"$1$2$3"):mr(e,r,t)}catch(n){if(n instanceof RangeError){let o=KR(e,r,t);return o===void 0?void 0:"rawJSON"in JSON?o:o.replace(sp,"$1$2$3").replace(ip,"$1$2$3")}throw n}},Co=new Map,JR=()=>{let e=JSON.parse.toString();if(Co.has(e))return Co.get(e);try{let r=JSON.parse("1",(t,n,o)=>!!o?.source&&o.source==="1");return Co.set(e,r),r}catch{return Co.set(e,!1),!1}},zR=(e,r,t,n)=>typeof r=="string"&&dp.test(r)?BigInt(r.slice(0,-1)):typeof r=="string"&&No.test(r)?r.slice(0,-1):typeof n=="function"?n(e,r,t):r,QR=(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&&VR.test(o.source);return a&&l?BigInt(o.source):typeof r=="function"?r(t,n,o):n}),up=Number.MAX_SAFE_INTEGER.toString(),ap=up.length,YR=/"(?:\\.|[^"])*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g,XR=/^"-?\d+n+"$/,ZR=(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"&&(dp.test(a)?a=BigInt(a.slice(0,-1)):No.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[""]},lp=e=>e.replace(YR,(r,t,n,o)=>{let s=r[0]==='"';if(s&&XR.test(r))return r.substring(0,r.length-1)+'n"';let a=n||o,l=t&&(t.length<ap||t.length===ap&&t<=up);return s||a||l?r:'"'+r+'n"'}),pp=(e,r)=>{if(!e)return Zi(e,r);try{if(JR())return QR(e,r);let t=lp(e);return Zi(t,(n,o,s)=>zR(n,o,s,r))}catch(t){if(t instanceof RangeError){let n=lp(e),o=Zi(n);return ZR(o,r)}throw t}};var ew="10.0.13",rw={headers:{"user-agent":`octokit-request.js/${ew} ${pr()}`}};function tw(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 mp=()=>"";async function gp(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=tw(e.body)||Array.isArray(e.body)?cp(e.body):e.body,s=Object.fromEntries(Object.entries(e.headers).map(([u,m])=>[u,String(m)])),i;try{i=await r(e.url,{method:e.method,body:o,redirect:e.request?.redirect,headers:s,signal:e.request?.signal,...e.body&&{duplex:"half"}})}catch(u){let m="Unknown Error";if(u instanceof Error){if(u.name==="AbortError")throw u.status=500,u;m=u.message,u.name==="TypeError"&&"cause"in u&&(u.cause instanceof Error?m=u.cause.message:typeof u.cause=="string"&&(m=u.cause))}let f=new tr(m,500,{request:e});throw f.cause=u,f}let a=i.status,l=i.url,d={};for(let[u,m]of i.headers)d[u]=m;let c={url:l,status:a,headers:d,data:""};if("deprecation"in d){let u=d.link&&d.link.match(/<([^<>]+)>; rel="deprecation"/),m=u&&u.pop();t.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${d.sunset}${m?`. See ${m}`:""}`)}if(a===204||a===205)return c;if(e.method==="HEAD"){if(a<400)return c;throw new tr(i.statusText,a,{response:c,request:e})}if(a===304)throw c.data=await ta(i),new tr("Not modified",a,{response:c,request:e});if(a>=400)throw c.data=await ta(i),new tr(ow(c.data),a,{response:c,request:e});return c.data=n?await ta(i):i.body,c}async function ta(e){let r=e.headers.get("content-type");if(!r)return e.text().catch(mp);let t=(0,fp.parse)(r);if(nw(t)){let n="";try{return n=await e.text(),pp(n)}catch{return n}}else return t.type.startsWith("text/")||t.parameters.charset?.toLowerCase()==="utf-8"&&t.type!=="application/octet-stream"?e.text().catch(mp):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function nw(e){return e.type==="application/json"||e.type==="application/scim+json"}function ow(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 na(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 gp(t.parse(i));let a=(l,d)=>gp(t.parse(t.merge(l,d)));return Object.assign(a,{endpoint:t,defaults:na.bind(null,t)}),i.request.hook(a,i)},{endpoint:t,defaults:na.bind(null,t)})}var dn=na(Yu,rw);var sw="0.0.0-development";function iw(e){return`Request failed due to following response errors:
|
|
83
83
|
`+e.errors.map(r=>` - ${r.message}`).join(`
|
|
84
|
-
`)}var iw=class extends Error{constructor(e,r,t){super(sw(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},aw=["method","baseUrl","url","headers","request","query","mediaType","operationName"],lw=["query","method","url"],mp=/\/api\/v3\/?$/;function dw(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(lw.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)=>aw.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 mp.test(s)&&(o.url=s.replace(mp,"/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 iw(o,a,i.data)}return i.data.data})}function oa(e,r){let t=e.defaults(r);return Object.assign((o,s)=>dw(t,o,s),{defaults:oa.bind(null,t),endpoint:t.endpoint})}var CD=oa(dn,{headers:{"user-agent":`octokit-graphql.js/${ow} ${pr()}`},method:"POST",url:"/graphql"});function gp(e){return oa(e,{method:"POST",url:"/graphql"})}var sa="(?:[a-zA-Z0-9_-]+)",fp="\\.",hp=new RegExp(`^${sa}${fp}${sa}${fp}${sa}$`),cw=hp.test.bind(hp);async function uw(e){let r=cw(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 pw(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function mw(e,r,t,n){let o=r.endpoint.merge(t,n);return o.headers.authorization=pw(e),r(o)}var yp=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(uw.bind(null,r),{hook:mw.bind(null,r)})};var ia="7.0.7";var kp=()=>{},gw=console.warn.bind(console),fw=console.error.bind(console);function hw(e={}){return typeof e.debug!="function"&&(e.debug=kp),typeof e.info!="function"&&(e.info=kp),typeof e.warn!="function"&&(e.warn=gw),typeof e.error!="function"&&(e.error=fw),e}var bp=`octokit-core.js/${ia} ${pr()}`,No=class{static VERSION=ia;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 Wu.Collection,n={baseUrl:dn.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} ${bp}`:bp,r.baseUrl&&(n.baseUrl=r.baseUrl),r.previews&&(n.mediaType.previews=r.previews),r.timeZone&&(n.headers["time-zone"]=r.timeZone),this.request=dn.defaults(n),this.graphql=gp(this.request).defaults(n),this.log=hw(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=yp(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 _p="6.0.0";function aa(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})})}aa.VERSION=_p;var yw="0.0.0-development";function kw(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 la(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=kw(l);if(a=((d.headers.link||"").match(/<([^<>]+)>;\s*rel="next"/)||[])[1],!a&&"total_commits"in d.data){let c=new URL(d.url),u=c.searchParams,m=parseInt(u.get("page")||"1",10),f=parseInt(u.get("per_page")||"250",10);m*f<d.data.total_commits&&(u.set("page",String(m+1)),a=c.toString())}return{value:d}}catch(l){if(l.status!==409)throw l;return a="",{value:{status:200,headers:{},data:[]}}}}})}}function Rp(e,r,t,n){return typeof t=="function"&&(n=t,t=void 0),wp(e,[],la(e,r,t)[Symbol.asyncIterator](),n)}function wp(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:wp(e,r,t,n)})}var ej=Object.assign(Rp,{iterator:la});function da(e){return{paginate:Object.assign(Rp.bind(null,e),{iterator:la.bind(null,e)})}}da.VERSION=yw;var ca="17.0.0";var bw={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"]}},Ep=bw;var $r=new Map;for(let[e,r]of Object.entries(Ep))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);$r.has(e)||$r.set(e,new Map),$r.get(e).set(t,{scope:e,methodName:t,endpointDefaults:d,decorations:i})}var _w={has({scope:e},r){return $r.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[...$r.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=$r.get(r).get(n);if(!o)return;let{endpointDefaults:s,decorations:i}=o;return i?t[n]=Rw(e,r,n,s,i):t[n]=e.request.defaults(s),t[n]}};function ua(e){let r={};for(let t of $r.keys())r[t]=new Proxy({octokit:e,scope:t,cache:{}},_w);return r}function Rw(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 ww(e){return{rest:ua(e)}}ww.VERSION=ca;function pa(e){let r=ua(e);return{...r,rest:r}}pa.VERSION=ca;var vp="22.0.1";var Sp=No.plugin(aa,pa,da).defaults({userAgent:`octokit-rest.js/${vp}`});function Ew(e){return`r${e}`}function Tp(e){if(e.length===0)throw new Error("an aliased single-object query needs at least one read");let r=e[0].kind;if(e.some(s=>s.kind!==r))throw new Error("an aliased single-object query may contain only one object kind");let t={},n=r==="pr"?"pullRequest":"issue";return{query:["query CoalescedSingleObjectReads {",...e.map((s,i)=>{if(!Number.isSafeInteger(s.number)||s.number<=0)throw new Error(`an aliased single-object read needs a positive number, got ${s.number}`);let a=s.selection.trim();if(a==="")throw new Error("an aliased single-object read needs a field selection");let l=Ew(i);return t[l]=s,[` ${l}: repository(owner: ${JSON.stringify(s.owner)}, name: ${JSON.stringify(s.repo)}) {`,` object: ${n}(number: ${s.number}) { ${a} }`," }"].join(`
|
|
84
|
+
`)}var aw=class extends Error{constructor(e,r,t){super(iw(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},lw=["method","baseUrl","url","headers","request","query","mediaType","operationName"],dw=["query","method","url"],hp=/\/api\/v3\/?$/;function cw(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(dw.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)=>lw.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 hp.test(s)&&(o.url=s.replace(hp,"/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 aw(o,a,i.data)}return i.data.data})}function oa(e,r){let t=e.defaults(r);return Object.assign((o,s)=>cw(t,o,s),{defaults:oa.bind(null,t),endpoint:t.endpoint})}var ND=oa(dn,{headers:{"user-agent":`octokit-graphql.js/${sw} ${pr()}`},method:"POST",url:"/graphql"});function yp(e){return oa(e,{method:"POST",url:"/graphql"})}var sa="(?:[a-zA-Z0-9_-]+)",kp="\\.",bp=new RegExp(`^${sa}${kp}${sa}${kp}${sa}$`),uw=bp.test.bind(bp);async function pw(e){let r=uw(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 mw(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function gw(e,r,t,n){let o=r.endpoint.merge(t,n);return o.headers.authorization=mw(e),r(o)}var _p=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(pw.bind(null,r),{hook:gw.bind(null,r)})};var ia="7.0.7";var Rp=()=>{},fw=console.warn.bind(console),hw=console.error.bind(console);function yw(e={}){return typeof e.debug!="function"&&(e.debug=Rp),typeof e.info!="function"&&(e.info=Rp),typeof e.warn!="function"&&(e.warn=fw),typeof e.error!="function"&&(e.error=hw),e}var wp=`octokit-core.js/${ia} ${pr()}`,Mo=class{static VERSION=ia;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 Hu.Collection,n={baseUrl:dn.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} ${wp}`:wp,r.baseUrl&&(n.baseUrl=r.baseUrl),r.previews&&(n.mediaType.previews=r.previews),r.timeZone&&(n.headers["time-zone"]=r.timeZone),this.request=dn.defaults(n),this.graphql=yp(this.request).defaults(n),this.log=yw(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=_p(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 aa(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})})}aa.VERSION=Ep;var kw="0.0.0-development";function bw(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 la(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=bw(l);if(a=((d.headers.link||"").match(/<([^<>]+)>;\s*rel="next"/)||[])[1],!a&&"total_commits"in d.data){let c=new URL(d.url),u=c.searchParams,m=parseInt(u.get("page")||"1",10),f=parseInt(u.get("per_page")||"250",10);m*f<d.data.total_commits&&(u.set("page",String(m+1)),a=c.toString())}return{value:d}}catch(l){if(l.status!==409)throw l;return a="",{value:{status:200,headers:{},data:[]}}}}})}}function vp(e,r,t,n){return typeof t=="function"&&(n=t,t=void 0),Sp(e,[],la(e,r,t)[Symbol.asyncIterator](),n)}function Sp(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:Sp(e,r,t,n)})}var rj=Object.assign(vp,{iterator:la});function da(e){return{paginate:Object.assign(vp.bind(null,e),{iterator:la.bind(null,e)})}}da.VERSION=kw;var ca="17.0.0";var _w={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"]}},Tp=_w;var $r=new Map;for(let[e,r]of Object.entries(Tp))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);$r.has(e)||$r.set(e,new Map),$r.get(e).set(t,{scope:e,methodName:t,endpointDefaults:d,decorations:i})}var Rw={has({scope:e},r){return $r.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[...$r.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=$r.get(r).get(n);if(!o)return;let{endpointDefaults:s,decorations:i}=o;return i?t[n]=ww(e,r,n,s,i):t[n]=e.request.defaults(s),t[n]}};function ua(e){let r={};for(let t of $r.keys())r[t]=new Proxy({octokit:e,scope:t,cache:{}},Rw);return r}function ww(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 Ew(e){return{rest:ua(e)}}Ew.VERSION=ca;function pa(e){let r=ua(e);return{...r,rest:r}}pa.VERSION=ca;var xp="22.0.1";var Pp=Mo.plugin(aa,pa,da).defaults({userAgent:`octokit-rest.js/${xp}`});function vw(e){return`r${e}`}function Op(e){if(e.length===0)throw new Error("an aliased single-object query needs at least one read");let r=e[0].kind;if(e.some(s=>s.kind!==r))throw new Error("an aliased single-object query may contain only one object kind");let t={},n=r==="pr"?"pullRequest":"issue";return{query:["query CoalescedSingleObjectReads {",...e.map((s,i)=>{if(!Number.isSafeInteger(s.number)||s.number<=0)throw new Error(`an aliased single-object read needs a positive number, got ${s.number}`);let a=s.selection.trim();if(a==="")throw new Error("an aliased single-object read needs a field selection");let l=vw(i);return t[l]=s,[` ${l}: repository(owner: ${JSON.stringify(s.owner)}, name: ${JSON.stringify(s.repo)}) {`,` object: ${n}(number: ${s.number}) { ${a} }`," }"].join(`
|
|
85
85
|
`)})," rateLimit { cost }","}"].join(`
|
|
86
|
-
`),aliases:t}}function xp(e,r){let t=r!==null&&typeof r=="object"?r:{},n=t.data??t,o=n!==null&&typeof n=="object"?n:{};return Object.entries(e.aliases).map(([s,i])=>{let a=o[s];if(a===null||typeof a!="object")return{read:i,value:null};let l=a.object;return{read:i,value:l!==null&&typeof l=="object"&&!Array.isArray(l)?l:null}})}var vw=Sp.plugin(Vi,Lo);function Pp(){let e=new Map;return{get:r=>e.get(r),set:(r,t)=>e.set(r,t)}}function Op(e){if(e?.outcome!=="asked")return Number.POSITIVE_INFINITY;let r=e.pools.rest,t=e.pools.graphql;return r===null||t===null||t.remaining<=0||t.fraction<=0?Number.POSITIVE_INFINITY:r.remaining<=0||r.fraction<=0?1:!Number.isFinite(r.fraction)||!Number.isFinite(t.fraction)?Number.POSITIVE_INFINITY:Math.max(1,Math.ceil(r.fraction/t.fraction))}var pt=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 ma(e){let r=e.etags??Pp(),t=new vw({auth:e.token,log:{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},...e.baseUrl?{baseUrl:e.baseUrl}:{},...e.fetchImpl?{request:{fetch:e.fetchImpl}}:{},retry:{doNotRetry:[304,403,429],...e.retryCount===void 0?{}:{retries:e.retryCount}},throttle:e.throttle===!1?{enabled:!1}:{onRateLimit:()=>!1,onSecondaryRateLimit:()=>!1}}),n=async c=>{let u=r.get(c.cacheKey),m={...c.parameters??{}},f=gr(m.headers)?m.headers:{};m.headers={...f,...u?{"if-none-match":u.etag}:{}};try{let h=await t.request(c.route,m),v=h.headers,k=Mo(v,"etag");return k!==void 0&&r.set(c.cacheKey,{etag:k,data:h.data,headers:v}),await e.attribution?.record({operation:c.operation,cost:1,actor:c.actor}),{data:h.data,headers:v,quotaFree:!1}}catch(h){if(cn(h)===304){if(u===void 0)throw new Error(`GitHub returned 304 for ${JSON.stringify(c.cacheKey)} without a held answer to reuse`,{cause:h});let v=Ap(h),k={...u.headers,...v},T=Mo(k,"etag")??u.etag;return r.set(c.cacheKey,{etag:T,data:u.data,headers:k}),await e.attribution?.record({operation:c.operation,cost:0,actor:c.actor}),{data:u.data,headers:k,quotaFree:!0}}throw cn(h)===401?new pt({cause:h}):h}},o=new Map,s=!1,i=async c=>{let u=c.input,m=u.kind==="pr";try{let f=await n({cacheKey:u.cacheKey,route:m?"GET /repos/{owner}/{repo}/pulls/{pull_number}":"GET /repos/{owner}/{repo}/issues/{issue_number}",parameters:{owner:u.owner,repo:u.repo,...m?{pull_number:u.number}:{issue_number:u.number}},operation:u.operation,actor:u.actor});c.resolve({data:u.project?u.project(f.data,"rest"):f.data,surface:"rest",quotaFree:f.quotaFree})}catch(f){c.reject(f)}},a=async c=>{try{let u=Tp(c.map(({input:k})=>k)),m=await t.graphql(u.query),f=xp(u,m),h=Tw(m),v=c[0].input;await e.attribution?.record({operation:{key:v.operation.key,budget:"graphql"},cost:h,actor:xw(c.map(({input:k})=>k.actor))}),f.forEach((k,T)=>{let $=c[T];k.value===null?$.reject(new Error(`GitHub returned no ${k.read.kind} #${k.read.number} from the coalesced query`)):$.resolve({data:$.input.project?$.input.project(k.value,"graphql"):k.value,surface:"graphql",quotaFree:!1})})}catch(u){let m=cn(u)===401?new pt({cause:u}):u;c.forEach(f=>f.reject(m))}},l=async()=>{let c=null;try{c=await e.balance?.()??null}catch{}let u=Op(c);s=!1;let m=[...o.values()];o.clear(),await Promise.all(m.map(async f=>{f.length>u?await a(f):await Promise.all(f.map(i))}))};return{conditionalRest:n,singleObject:c=>r.get(c.cacheKey)!==void 0?new Promise((u,m)=>{i({input:c,resolve:u,reject:m})}):new Promise((u,m)=>{let f=o.get(c.kind)??[];f.push({input:c,resolve:u,reject:m}),o.set(c.kind,f),s||(s=!0,setTimeout(()=>void l(),0))}),async conditionalPaginate(c){let u=[],m={},f=0,h=!0,v=1;for(;;){let k=await n({...c,cacheKey:`${c.cacheKey}:page:${v}`,parameters:{...c.parameters??{},per_page:100,page:v}});if(f+=1,h=h&&k.quotaFree,!Array.isArray(k.data))throw new Error(`GitHub returned a non-list body for ${JSON.stringify(c.cacheKey)} page ${v}`);if(u.push(...k.data),m=k.headers,!Sw(k.headers))break;v+=1}return{data:u,headers:m,requestCount:f,quotaFree:h}},async graphql(c,u={},m){try{let f=await t.graphql(c,u);return m&&await e.attribution?.record({operation:m.operation,cost:1,actor:m.actor}),f}catch(f){throw cn(f)===401?new pt({cause:f}):f}}}}function Sw(e){let r=Mo(e,"link");return r!==void 0&&/(?:^|,)\s*<[^>]+>;\s*rel="next"(?:\s*;|\s*(?:,|$))/i.test(r)}function un(e){let r=cn(e),t=Ap(e);return r===429||r===403&&Mo(t,"x-ratelimit-remaining")==="0"||e instanceof Error&&/secondary rate|rate limit/i.test(e.message)}function cn(e){if(gr(e))return typeof e.status=="number"?e.status:void 0}function Ap(e){return!gr(e)||!gr(e.response)||!gr(e.response.headers)?{}:e.response.headers}function Mo(e,r){let t=e[r]??e[r.toLowerCase()];return typeof t=="string"?t:typeof t=="number"?String(t):void 0}function gr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tw(e){let r=gr(e)?e:{},t=gr(r.data)?r.data:r,o=(gr(t.rateLimit)?t.rateLimit:{}).cost;if(!Number.isSafeInteger(o)||o<0)throw new Error("GitHub aliased query did not return a non-negative integer rateLimit.cost");return o}function xw(e){let r=[...new Set(e.filter(t=>t!==void 0))].sort();if(r.length!==0)return r.length===1?r[0]:`coalesced:${r.join("+")}`}var jp="rate_limit",Lp={rest:"core",graphql:"graphql",search:"search"},nr=["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:[...nr],detail:r??"no balance has been asked for yet, so none is known"}}var fa=15e3,mt=.15,Wo=[{at_or_below_fraction:0,every_ms:fa,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:mt,every_ms:3e4,why:"inside the reserved band: the posture can change between two calls"},{at_or_below_fraction:.5,every_ms:12e4,why:"below half: tightening, because the band is now reachable inside one window"},{at_or_below_fraction:1,every_ms:6e5,why:"above half: rare, because nothing this balance decides is anywhere close"}];var wj=60*6e4,ga=2;function Gp(e,r){let t=Dp(e),n=Dp(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let a of nr){let l=Lp[a],d=n[l],c=Aw(a,l,d);o[a]=c,c==null&&s.push(a)}let i=nr.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 ${nr.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function ha(e){try{let r=await e.transport();return Gp(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 ya(e){let r=null;for(let t of nr){let n=e.pools[t];n!=null&&(r==null||n.fraction<r.fraction)&&(r=n)}return r}function Ho(e,r){let t=ya(e);if(t==null)return Uo(mt).every_ms;let n=Uo(t.fraction);if(t.remaining>0)return n.every_ms;let o=$p(r.now,t.reset_at);return o==null?n.every_ms:Math.max(fa,Math.min(n.every_ms,o))}function ka(e,r=mt){return Math.ceil(e.limit*r)}function Ip(e,r,t=mt){let n=e.pools[r];return n==null?"unknown":n.remaining<=0?"spent":n.remaining<ka(n,t)?"reserved":"open"}function ba(e){let r=e.reservedFraction??mt,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:Uo(r).every_ms*ga,stale:!1,posture:"unknown",reserved_fraction:r,next_poll_ms:Uo(r).every_ms,pools:[],unreported_pools:[...nr],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let n=Ho(t,{now:e.now}),o=e.stalenessMs??n*ga,s=$p(t.asked_at,e.now),i=t.outcome==="asked"&&(s==null||s>o),a=nr.map(c=>t.pools[c]).filter(c=>c!=null),l=Ow(t,r),d=ya(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`:Pw(l,d,t,r)}}function _a(e){if(!wa(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 Pw(e,r,t,n){if(r==null)return t.detail;let o=ka(r,n);switch(e){case"spent":return`the ${r.pool} pool is spent and resets at ${r.reset_at}: work is not queued, it is refused`;case"reserved":return`the ${r.pool} pool has ${r.remaining} of ${r.limit} left, inside the reserved band of ${o}: convenience reads are refused and the claim, a landing and a closing comment still pass`;default:return`the ${r.pool} pool is the tightest at ${r.remaining} of ${r.limit}, above the reserved band of ${o}`}}function Ow(e,r){let t="unknown";for(let n of nr){if(e.pools[n]==null)continue;let o=Ip(e,n,r);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function Uo(e){for(let r of Wo)if(e<=r.at_or_below_fraction)return r;return Wo[Wo.length-1]}function Aw(e,r,t){if(!wa(t))return null;let n=Fo(t.limit),o=Fo(t.remaining),s=Fo(t.used),i=Fo(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 Ra(e){let r=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let n=await t(`${r}/${jp}`,{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 $p(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 Fo(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function Dp(e){return wa(e)?e:{}}function wa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Up(e){return{generated_at:e.now,hour:Cp("hour",36e5,e),day:Cp("day",864e5,e)}}function mn(e,r,t){let n=pn(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(a=>{let l=pn(r(a));return l==null?!1:n==null||n-l<=o});return i.length<=s?i:i.slice(i.length-s)}function Cp(e,r,t){let n=pn(t.now),o=n==null?null:n-r,s=e==="hour"?"1h":"24h",i=t.observations.map(u=>({observation:u,at:pn(u.observed_at)})).filter(u=>u.at!=null&&Fp(u.at,o,n)).sort((u,m)=>u.at-m.at),a=t.outcomes.map(u=>pn(u.ts)).filter(u=>u!=null&&Fp(u,o,n)),l=Np(i,u=>u.tokens,"tokens",s),d=Np(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:Dw(a.length,r,s),runner_share:Mp("runner",i,u=>u.runner,s),model_share:Mp("model",i,u=>u.model,s),unavailable:c}}function Np(e,r,t,n){let o=new Map,s=0;for(let d of e){let c=r(d.observation);if(c==null||!Number.isFinite(c))continue;s+=1;let u=o.get(d.observation.worker_id)??[];u.push({at:d.at,count:c}),o.set(d.observation.worker_id,u)}if(s===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${n}`,samples:0};let i=0,a=null,l=null;for(let d of o.values()){if(d.length<2)continue;for(let m=1;m<d.length;m++){let f=d[m-1],h=d[m];f==null||h==null||(i+=Math.max(0,h.count-f.count))}let c=d[0],u=d[d.length-1];c!=null&&(a=a==null?c.at:Math.min(a,c.at)),u!=null&&(l=l==null?u.at:Math.max(l,u.at))}return a==null||l==null||l<=a?{value:null,absent_reason:`the last ${n} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:s}:{value:i/((l-a)/6e4),absent_reason:null,samples:s}}function Dw(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 Mp(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 Fp(e,r,t){return r==null||t==null?!0:e>=r&&e<=t}function pn(e){let r=Date.parse(e);return Number.isFinite(r)?r:null}function Bp(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.generated_at=="string"&&Wp(r.hour)&&Wp(r.day)}function Wp(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"&&Ea(r.tokens_per_min)&&Ea(r.tools_per_min)&&Ea(r.issues_per_hour)&&Array.isArray(r.unavailable)}function Ea(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 jw}from"node:child_process";import{existsSync as Lw,readFileSync as qo,readdirSync as Gw}from"node:fs";import{dirname as Iw,join as Cr}from"node:path";function gn(e){let r=tn(e),t=[["MemoryMax",r.memory_max],["MemoryHigh",r.memory_high]];for(let[n,o]of t){if(o==null)continue;let s=dt(o);return s==null?null:{name:n,declared:o,bytes:s}}return null}function Hp(e){let r=[],t=[];for(let n of e.workers){let o=gn(n);if(o==null){t.push({worker_id:n.worker_id,reason:(tn(n).memory_max??tn(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($w(n,o,s))}}return{terminations:r,unenforceable:t}}function $w(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 Cw=4096;function qp(e,r={}){let t=r.platform??process.platform,n={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return n;let o={},s={},i={},a=Mw(e,t,r);for(let[u,m]of a){let f=Uw(m);f!=null&&(o[u]=f.memoryBytes,f.cpuSeconds!=null&&(s[u]=f.cpuSeconds),i[u]="cgroup")}let l=e.filter(u=>i[u.worker_id]==null);if(l.length===0)return{rss:o,cpu_seconds:s,sources:i};let d=qw(t,r);if(d.size===0)return{rss:o,cpu_seconds:s,sources:i};let c=new Map;for(let u of d.values()){let m=c.get(u.ppid);m?m.push(u.pid):c.set(u.ppid,[u.pid])}for(let u of l){if(!d.has(u.pid))continue;let m=0,f=0,h=[u.pid],v=new Set;for(;h.length>0;){let k=h.pop();if(v.has(k))continue;v.add(k);let T=d.get(k);if(T){m+=T.rssBytes,f+=T.cpuSeconds;for(let $ of c.get(k)??[])h.push($)}}o[u.worker_id]=m,s[u.worker_id]=f,i[u.worker_id]="process-tree"}return{rss:o,cpu_seconds:s,sources:i}}var Nw="/sys/fs/cgroup";function Mw(e,r,t){let n=new Map;if(!(t.cgroupRoot!=null)&&r!=="linux")return n;let s=t.cgroupRoot??Nw,i=e.filter(l=>l.unit!=null&&l.unit!=="");if(i.length===0)return n;let a=Fw(s,t);for(let l of i)for(let d of a){let c=Cr(d,l.unit);if(Lw(Cr(c,"memory.current"))){n.set(l.worker_id,c);break}}return n}function Fw(e,r){let t=r.selfCgroupPath??Ww(),n=[],o=a=>{n.includes(a)||n.push(a)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(Cr(e,s));let a=Iw(s);if(a===s)break;s=a}o(e);let i=r.uid??process.getuid?.();return i!=null&&o(Cr(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),n}function Ww(){try{for(let e of qo("/proc/self/cgroup","utf8").split(`
|
|
87
|
-
`))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function
|
|
88
|
-
`)){let[t,n]=r.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(n);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function
|
|
89
|
-
`)){let n=t.trim().split(/\s+/);if(n.length!==4)continue;let[o,s,i]=n.slice(0,3).map(Number);if(![o,s,i].every(l=>l!=null&&Number.isSafeInteger(l)&&l>=0))continue;let a=
|
|
90
|
-
`),aliases:s,closed_since:o}}function nE(e,r,t){let n=gt(r),o=gt(n.data),s=Array.isArray(n.errors)?n.errors.map(gt):[],i=dE(o.rateLimit,s),a=e.aliases.map(({alias:l,search_alias:d,project:c})=>{let u=c.owner+"/"+c.name,m=o[l],f=s.find(h=>zp(h.path,l)||zp(h.path,d));if(fn(m)){let h=Qp(m.open_pull_requests),v=Qp(m.open_issues),k=cE(o[d]);if(h!=null&&v!=null&&k!=null)return{project_label:c.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:h,open_issues:v,recently_closed:k},detail:`counted ${u} for project ${JSON.stringify(c.project_label)}`}}return i.exhausted||nm(f)?{project_label:c.project_label,repository:u,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${u} answered, so this project has no counts rather than zero counts${i.reset_at==null?"":`; the quota resets at ${i.reset_at}`}`}:{project_label:c.project_label,repository:u,outcome:"unreachable",counts:null,detail:`${u} is not reachable with the host token: ${Vo(f?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:a.length,rate_limit:i,projects:a}}function oE(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 Xp(e){if(e.projects.length===0)return oE(e.now);if(Ta(e.projects,e.hostTokenRef),e.transport.conditionalList)return await iE(e);let r=Yp(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(r.query);return nE(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 sE={key:"redskilled repository activity poll",budget:"rest"};async function iE(e){tm(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=Yp(e.projects,{now:t,closedWindowMs:e.closedWindowMs}),o=e.transport.conditionalList,s=[],i=0,a={remaining:null,reset_at:null,exhausted:!1,point_cost:null};for(let l of e.projects){let d=`${l.owner}/${l.name}`,c=[["open-prs","GET /repos/{owner}/{repo}/pulls",{owner:l.owner,repo:l.name,state:"open"}],["open-issues","GET /repos/{owner}/{repo}/issues",{owner:l.owner,repo:l.name,state:"open"}],["recently-closed","GET /repos/{owner}/{repo}/issues",{owner:l.owner,repo:l.name,state:"closed",since:n.closed_since}]],u=[];try{for(let[m,f,h]of c){let v=await o({cacheKey:`activity:${d}:${m}:${JSON.stringify(h)}`,route:f,parameters:h,operation:sE});i+=v.requestCount;let k=m==="open-prs"?v.data:v.data.filter(T=>!fn(T.pull_request));u.push(m==="recently-closed"?k.filter(T=>Vo(T.closed_at)>=n.closed_since).length:k.length),a=Kp(a,lE(v.headers))}s.push({project_label:l.project_label,repository:d,outcome:"counted",counts:{open_pull_requests:u[0],open_issues:u[1],recently_closed:u[2]},detail:`counted ${d} for project ${JSON.stringify(l.project_label)}`})}catch(m){let f=un(m);a=Kp(a,{remaining:null,reset_at:null,exhausted:f,point_cost:null}),s.push({project_label:l.project_label,repository:d,outcome:f?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${d} answered: ${m instanceof Error?m.message:String(m)}`})}}return{version:1,fetched_at:e.now,request_count:i,project_count:s.length,rate_limit:a,projects:s}}function Zp(e){let r=e.stalenessMs??rE,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 em(e){if(!fn(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)&&fn(r.rate_limit)&&Array.isArray(r.projects)&&typeof r.reason=="string"}function rm(e){let r=e.endpoint==null?void 0:aE(e.endpoint),t=ma({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 aE(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 lE(e){let r=Jp(e,"x-ratelimit-remaining"),t=Jp(e,"x-ratelimit-reset");return{remaining:r,reset_at:t==null?null:new Date(t*1e3).toISOString(),exhausted:r===0,point_cost:null}}function Kp(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 Jp(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 tm(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>Vp)throw new Error(`redskilled activity fetch spans at most ${Vp} 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 dE(e,r){let t=gt(e),n=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=r.some(nm),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 nm(e){if(e==null)return!1;let r=Vo(e.type),t=Vo(e.message);return r==="RATE_LIMITED"||/rate limit/i.test(t)}function zp(e,r){return Array.isArray(e)&&e.includes(r)}function Qp(e){let r=gt(e);return Number.isInteger(r.totalCount)?r.totalCount:null}function cE(e){let r=gt(e);return Number.isInteger(r.issueCount)?r.issueCount:null}function gt(e){return fn(e)?e:{}}function fn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vo(e){return typeof e=="string"?e:""}var uE=3e4,pE=2,mE=3,gE=4,fE=["logs","vitals","display"];function om(e,r){if(r===void 0)return e;let t=fE.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:hE,budget:{...o.budget,used_bytes:null,used_fraction:null}},...n("logs")?{}:{log:yE},...n("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var hE={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},yE={last_line:null,published_at:null,source:null};function sm(e){let r=e.stalenessMs??uE,t=fr(e.now),n=e.sampledAt==null?null:fr(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=>RE(m,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[m.worker_id],display:e.displays?.[m.worker_id],state:i.has(m.worker_id)?"reattached":"running"})),l=a.filter(m=>m.vitals.rss_bytes==null).map(m=>m.worker_id).sort(),d=a.length-l.length,c=a.reduce((m,f)=>m+(f.vitals.rss_bytes??0),0),u=To(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:SE({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:vE(a),known_projects:EE(e.hostState),registered_projects:(e.hostState.registrations??[]).map(m=>m.project_label).sort((m,f)=>m.localeCompare(f)),lapsed_projects:(e.hostState.lapsed_registrations??[]).map(m=>({project_label:m.project_label,at:m.at,...m.registered_at==null?{}:{registered_at:m.registered_at},reason:m.detail})),stopped_projects:(e.hostState.stopped_registrations??[]).map(m=>({project_label:m.project_label,at:m.at})),orphaned_projects:(e.hostState.orphaned_registrations??[]).map(m=>m.project_label),workers:a,github_balance:ba({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:Zp({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:kE(e.deaths,e.recentDeathLimit??gE)},engine:_E(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function kE(e,r){let t=[...e].sort((s,i)=>(fr(i.ts)??0)-(fr(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=bE(t);return{count:t.length,recent:n,latest:n[0]??null,reaped_at:n[0]?.ts??null,...o==null?{}:{boot_loop:o}}}function bE(e){let r=new Map;for(let n of e){if(n.sender_class!=="boot-refused"||n.uptime_s==null||n.uptime_s>pE||n.project_label==null||n.project_label===""||fr(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>=mE).map(([n,o])=>{let s=o[0],i=fr(s.ts),a=Math.min(...o.map(d=>fr(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 _E(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 RE(e,r){let t=r.rss[e.worker_id],n=typeof t=="number"&&Number.isFinite(t)?t:null,o=gn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=fr(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,...e.base_commits_ahead==null?{}:{base_commits_ahead:e.base_commits_ahead},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:wE(r.log),display:r.display?.display??null,display_published_at:r.display?.published_at??null}}function wE(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 EE(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 vE(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 SE(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 fr(e){let r=Date.parse(e);return Number.isFinite(r)?r:null}function xa(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(TE))&&(r.stopped_projects===void 0||Array.isArray(r.stopped_projects)&&r.stopped_projects.every(xE))&&(r.orphaned_projects===void 0||Array.isArray(r.orphaned_projects)&&r.orphaned_projects.every(s=>typeof s=="string"))&&(r.repository_activity===void 0||em(r.repository_activity))&&(r.github_balance===void 0||_a(r.github_balance))&&(r.deaths===void 0||PE(r.deaths))&&(r.engine===void 0||OE(r.engine))&&(r.metrics===void 0||Bp(r.metrics))}function TE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.project_label=="string"&&typeof r.at=="string"&&(r.registered_at===void 0||typeof r.registered_at=="string")&&typeof r.reason=="string"}function xE(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 PE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return Number.isInteger(r.count)&&Array.isArray(r.recent)}function OE(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.running_version=="string"&&(r.published_version===null||typeof r.published_version=="string")}var im={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 am(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`,hn=ae("48;2;114;47;55"),Pa=ae("48;2;88;36;42"),hr=ae("38;2;255;255;255"),Oa=ae("38;2;201;150;158"),yn=ae("38;2;255;214;214"),kn=ae("39"),ke=ae("38;2;224;138;148"),Aa=ae("38;2;240;200;120"),Da=ae("38;2;240;110;120"),ja=ae("38;2;255;214;214"),La=ae("38;2;146;84;94"),Ga=ae("38;2;255;95;95"),qe=ae("49"),Le=ae("0"),Ko=ae("1"),Jo=ae("22");var AE=/\x1b\[[0-9;]*m/g,DE=/(\x1b\[[0-9;]*m)/,jE=/^\x1b\[[0-9;]*m$/;function lm(e){return e.replace(AE,"")}function LE(e){return e.slice(2,-1).split(";").every(t=>t===""||Number(t)===0)}function xe(e){return[...lm(e)].length}function fe(e,r){if(r<=0)return"";if(xe(e)<=r)return e;if(r===1)return"\u2026";let t=r-1,n=0,o=!1,s="";for(let i of e.split(DE))if(i!==""){if(jE.test(i)){s+=i,o=!LE(i);continue}for(let a of i){if(n===t)return`${s}\u2026${o?Le:""}`;s+=a,n+=1}}return`${s}\u2026${o?Le:""}`}function bn(e,r){return e+" ".repeat(Math.max(0,r-xe(e)))}function Ia(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 Ge(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 _n(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 _n(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 yr(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 ft(e){if(e==null)return null;let r=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return r===""?null:r}var wn="!unregistered",$a="!lapsed",En="\u21E1",or="\u2020",ht="\u25D0",yt="\u25EF",Ca="\u21B3",Na="redskilled unreachable \u2014 Worker state unknown";function kt(e,r){return r.mode==="global"?e.workers:r.project==null?[]:e.workers.filter(t=>t.project_label===r.project)}function zo(e,r){return r.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===r.project)}function vn(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 Ma(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 br=["wid","run","org","iss","bar","phase","base","elapsed","eta","hb","loc","tks","ctx","tls","rsn","txt"],Ve={mode:"local",project:null,maxWidth:200,maxRows:16},GE=" ",dm="\u2588",IE="\u25B6",$E="\u2717",CE="\u2591",NE=new Set(["gate","push-pr","merge","cascade"]),ME=new Set(["requeue"]),FE="repair";function Sn(e){return e.display?.origin===FE}function bt(e,r=Ve){let t=vn(e,r.project),n=kt(e,r),o=n.slice(0,Math.max(0,Math.floor(r.maxRows))),s=o.map(u=>Qo(u,r,e.generated_at)),i=QE(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:fe(YE(s[m],i),r.maxWidth)})),l=UE(e,r,n,t),d=n.length-o.length,c=[l.line,...a.map(u=>u.line)];return d>0&&c.push(fe(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,r.maxWidth)),c.push(...VE(e,r)),c.push(...qE(e,r)),{version:1,generated_at:e.generated_at,mode:r.mode,project:r.project,columns:br,header:l,rows:a,lines:c,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Qo(e,r,t){let n=e.display??im,o=Sn(e),s=[n.runner,n.model==null?null:Ia(n.model),n.effort].filter(l=>!!l).join(" "),i=n.phase!=null&&NE.has(n.phase),a=o||i||n.origin!=null&&ME.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:cm(n),phase:[n.phase,n.step].filter(l=>!!l).join("\xB7"),base:e.base_commits_ahead==null?"":`base +${e.base_commits_ahead}`,elapsed:yr(am(e,t)),eta:n.eta==null?"":`eta=${yr(n.eta*1e3)}`,hb:WE(n,t)??`hb=${n.heartbeat??"?"}`,loc:a?"":zE(n.added,n.removed),tks:a||n.tokens==null?"":`tks=${_n(n.tokens)}`,ctx:n.context==null?"":`ctx=${_n(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 WE(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} ${yr(Math.max(0,n-t))}`}function cm(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 dm.repeat(Math.floor(r));let o=e.failed?$E:IE;return`${dm.repeat(n)}${o}${CE.repeat(Math.floor(r)-n-1)}`}function UE(e,r,t,n){let o=(e.repository_activity?.projects??[]).find(G=>G.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=JE(t),l=o?.repository??r.project,d=e.engine??null,c=d?.running_version??e.daemon.daemon_version,u=e.deaths??null,m=e.metrics??null,f=[BE(l??"host",c,d!=null&&d.current===!1?En:"")];(n==="unregistered"||n==="name-only")&&f.push(wn),n==="lapsed"&&f.push($a),a!=null&&f.push(`${hn}${hr}${a}${qe}${ke}`);let h=e.workers.filter(Sn).length;if(h>0){let G=Math.max(0,e.host.worker_count-h);f.push(`${kr(`workers=${G} coding +`)} ${hn}${hr}${h} repairing${qe}${ke}`)}else f.push(kr(`wrk=${t.length}/${e.host.worker_count}`));let v=i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`;f.push(kr(`${v} reserve=${i.interactive_reservation} interactive`)),f.push(kr(KE(i))),s.open_pull_requests!=null&&f.push(kr(`prs=${s.open_pull_requests}`)),s.recently_closed!=null&&f.push(kr(`cpr=${s.recently_closed}`)),s.open_issues!=null&&f.push(kr(`iss=${s.open_issues}`)),s.stale&&f.push("!counts stale");let k=m==null?null:um(m.hour),T=k==null?null:kr(k);if(T!=null&&f.push(T),u!=null&&u.count>0&&u.latest!=null){let G=u.boot_loop,H=ft(G?.latest_refusal);f.push(G==null?`${or}${u.count} ${u.latest.sender_class}`:`${or}${u.count} boot-refused \xD7${G.count} in ${HE(G.span_ms)}`+(H==null?"":` \u2014 ${H}`))}if(e.staleness.stale){let G=e.staleness.age_ms;f.push(G==null?"!unmeasured":`!stale ${Math.round(G/1e3)}s`)}let $=`${f.join(" \xB7 ")}${Le}`,U=k!=null&&xe($)>r.maxWidth?`${f.filter(G=>G!==T).join(" \xB7 ")}${Le}`:$;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:fe(U,r.maxWidth)}}function BE(e,r,t){return`${Pa}${hr}${Aa}\xBB${hr} ${Ko}${e}${Jo} ${Oa}v${r}${t}${hr}${qe}${ke}`}function kr(e){return e.replace(/(^|\s)([A-Za-z][A-Za-z0-9/]*=)([^\s]+)/g,(r,t,n,o)=>`${t}${yn}${n}${kn}${o}${ke}`)}function HE(e){return yr(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function um(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 qE(e,r){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let n=t.posture==="spent"?yt:ht,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[fe(`${n} github budget ${t.posture}${o} \u2014 ${t.reason}`,r.maxWidth)]}function VE(e,r){let t=e.deaths;if(t==null||t.count<=0)return[];let n=t.recent.map(s=>fe(`${or} ${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(fe(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,r.maxWidth)),n}function KE(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${Ge(e.memory_used_bytes)}`;let r=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${Ge(e.memory_used_bytes)}/${Ge(e.memory_ceiling_bytes)}${r}`}function JE(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 zE(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 QE(e){let r=Object.fromEntries(br.map(t=>[t,0]));for(let t of e)for(let n of br)r[n]=Math.max(r[n],xe(t[n]));return r}function YE(e,r){let t=br.filter(o=>r[o]>0);if(t.length===0)return"";let n=t.map((o,s)=>Yo(o,bn(e[o],s===t.length-1?xe(e[o]):r[o])));return`${qe}${ke}${n.join(GE)}${Le}`}function Yo(e,r){if(e==="wid")return`${Ko}${r}${Jo}`;if(e==="org"&&r.trim()==="lane=repair"){let n=r.slice(r.trimEnd().length);return`${hn}${hr}${r.trimEnd()}${qe}${ke}${n}`}if(e==="bar")return r.replace(/█+/g,n=>`${Da}${n}`).replace("\u25B6",`${ja}\u25B6`).replace("\u2717",`${Ga}\u2717`).replace(/░+/g,n=>`${La}${n}`)+ke;let t=r.indexOf("=");return t>0?`${yn}${r.slice(0,t+1)}${kn}${r.slice(t+1)}${ke}`:r}function Wa(e){return Object.freeze({none:!0,reason:e})}function Tn(){return{tool:"project_start",args:{runner:"claude",target:1},why:"register this project with the host so its queue can drain"}}function Fa(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=>Fa(n,r)));let t={};for(let[n,o]of Object.entries(e))t[n]=Fa(o,r);return Object.freeze(t)}finally{r.delete(e)}}function XE(e){let r=Fa(e.args,new Set);return Object.freeze({tool:e.tool,args:r,why:e.why})}function Nr(e){if("none"in e.repair)return{prose:`${e.state}; repair: none because ${e.repair.reason}`,repair:"none",repair_reason:e.repair.reason};let r=XE(e.repair);return{prose:`${e.state}; repair: call \`${r.tool}\` with \`${JSON.stringify(r.args)}\` because ${r.why}`,repair:r}}var B={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Mr(e,r=B){let t=vn(e,r.project),n=kt(e,r),o=zo(e,r),s=ov(e,r.project,t),i=ev(e,r,n,t,s.prose),a=Ma({mode:r.mode,maxWorkers:r.maxWorkers,maxProjects:r.maxProjects,workers:n,projects:o}),l={detail:"host",line:i};for(let f of a){let h=f==="workers"?i:dv(i,ZE(f,o),r.separator);if(l={detail:f,line:h},f==="workers"||xe(h)<=r.maxWidth)break}let d=fe(l.line,r.maxWidth),c=l.detail==="workers"?iv(n,r,e.generated_at):{lines:[],degraded:!1},u=l.detail==="workers"?n.flatMap((f,h)=>{let v=r.verbose?av(f,r):null;return v==null?[c.lines[h]]:[c.lines[h],v]}):[],m=n.length>0?"workers":"host";return{version:1,line:d,lines:[d,...u],verbose:r.verbose,mode:r.mode,project:r.project,project_match:t,...s.repair===void 0?{}:{repair:s.repair},...s.repair_reason===void 0?{}:{repair_reason:s.repair_reason},detail:l.detail,degraded:l.detail!==m||d!==l.line||c.degraded,stale:e.staleness.stale,generated_at:e.generated_at}}function qa(e){let r=e.options??B,t=fe(Na,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 ZE(e,r){return e==="projects"?r.map(lv):[]}function ev(e,r,t,n,o){let s=[],i=n!=="matched"&&n!=="name-only";r.mode==="global"?(s.push(`host ${Ua(e.workers,e.host.worker_count)}/${e.host.project_count}p`),s.push(Ha(e,r))):n==="matched"?(s.push(`${r.project} ${Ua(t,t.length)}`),s.push(Ha(e,r)),t.length===0&&s.push("idle")):n==="name-only"?(s.push(`${r.project} ${Ua(t,t.length)}`),s.push(Ha(e,r)),s.push(wn)):s.push(o),s.push(pm(e));let a=rv(e);a!=null&&s.push(a);let l=tv(e);l!=null&&s.push(l),e.staleness.stale&&s.push(mm(e));let d=s.join(" ");return!i||xe(d)<=r.maxWidth||a==null&&l==null?d:[a,l,o,pm(e),e.staleness.stale?mm(e):null].filter(c=>c!=null).join(" ")}function Ua(e,r){let t=e.filter(Sn).length;return t===0?`${r}w`:`${Math.max(0,r-t)} coding + ${t} repairing`}function pm(e){let r=e.engine,t=r?.running_version??e.daemon.daemon_version;return r==null||r.current!==!1?`v${t}`:`v${t}${En}`}function rv(e){let r=e.github_balance;return r==null?null:r.posture==="spent"?`${yt} quota spent`:r.posture==="reserved"?`${ht} quota band`:null}function tv(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=ft(t.latest_refusal);return`${or}${r.count} boot-refused \xD7${t.count} in ${nv(t.span_ms)}`+(n==null?"":` \u2014 ${n}`)}return`${or}${r.count} ${r.latest.sender_class}`}function nv(e){return yr(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function ov(e,r,t){if(t==="unregistered")return Nr({state:`project unknown \u2014 ${r} was never registered on this host`,repair:Tn()});if(t==="orphaned")return Nr({state:`project unknown \u2014 ${r} is registered on a daemon this socket does not reach`,repair:Wa("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 Nr({state:`project unknown \u2014 ${r} was stopped${n==null?"":` at ${Ba(n.at)}`}`,repair:Tn()})}if(t==="lapsed"){let n=e.lapsed_projects?.find(o=>o.project_label===r);if(n!=null){let o=n.registered_at==null?"":` (registered ${Ba(n.registered_at)})`;return Nr({state:`project unknown \u2014 ${r} lapsed at ${Ba(n.at)}${o}`,repair:Tn()})}return Nr({state:`project unknown \u2014 ${r} lapsed`,repair:Tn()})}return t==="unresolved"?Nr({state:"project unknown \u2014 this directory resolved to no project",repair:Wa("the directory must resolve to a project before registration args can be safe")}):{prose:""}}function Ba(e){return/^\d{4}-\d{2}-\d{2}T(\d{2}:\d{2}:\d{2})/.exec(e)?.[1]??e}function Ha(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?`${Ge(t)}/${Ge(n)}`:Ge(t)}function mm(e){let r=e.staleness.age_ms;return r==null?"!unmeasured":`!stale ${Math.round(r/1e3)}s`}function sv(e,r,t,n){let o=t.map(s=>Yo(s,bn(e[s],r[s])));return fe(`${qe}${ke}${o.join(" ")}${Le}`,n)}function iv(e,r,t){let n=e.map(a=>Qo(a,r,t)),o=br.filter(a=>n.some(l=>xe(l[a])>0)),s=[...o],i=gm(n,s);for(;s.length>1&&fm(i,s)>r.maxWidth;)s.pop(),i=gm(n,s);return{lines:n.map(a=>sv(a,i,s,r.maxWidth)),degraded:s.length<o.length||fm(i,s)>r.maxWidth}}function gm(e,r){let t=Object.fromEntries(br.map(n=>[n,0]));for(let n of e)for(let o of r)t[o]=Math.max(t[o],xe(n[o]));return t}function fm(e,r){return r.reduce((t,n)=>t+e[n],0)+Math.max(0,r.length-1)*2}function av(e,r){let t=ft(e.log.last_line);return t==null?null:fe(` ${Ca} ${hm(e,r.mode)}: ${t}`,r.maxWidth)}function hm(e,r){return r==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function lv(e){return`${e.project_label} ${e.worker_count}w ${Ge(e.observed_rss_bytes)}`}function dv(e,r,t){return[e,...r].join(t)}var Xo=1;async function xn(e,r){return await bo(e,r,"redskilled daemon")}function km(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:Xo,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:mv(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:Nc(r,{hostCeilingBytes:e.ceiling?.memory_bytes??e.hostCeilingBytes??null}),upgrade:gv(e)}}function mv(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:_u(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 gv(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 bm(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||bv(r.ceiling))&&Array.isArray(r.workers)&&Array.isArray(r.projects)&&Mc(r.budget_accounting)&&(r.scope===void 0||hu(r.scope))&&(r.registrations===void 0||Array.isArray(r.registrations)&&r.registrations.every(an))&&(r.demand===void 0||tu(r.demand))&&(r.lapsed_registrations===void 0||Array.isArray(r.lapsed_registrations)&&r.lapsed_registrations.every(hv))&&(r.stopped_registrations===void 0||Array.isArray(r.stopped_registrations)&&r.stopped_registrations.every(yv))&&(r.orphaned_registrations===void 0||Array.isArray(r.orphaned_registrations)&&r.orphaned_registrations.every(kv))&&(r.birth_latches===void 0||Array.isArray(r.birth_latches)&&r.birth_latches.every(fv))&&(r.upgrade===void 0||_v(r.upgrade))}function fv(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 hv(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 yv(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 kv(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 bv(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 _v(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||Rv(r.major_hold))}function Rv(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 wv}from"node:crypto";import{mkdir as Ev,readFile as vv,rename as Sv,writeFile as Tv}from"node:fs/promises";import{dirname as xv}from"node:path";function _m(e){let r=Promise.resolve(),t=null;async function n(){await r;let s;try{s=await vv(e,"utf8")}catch(a){if(a.code==="ENOENT")return[];throw a}let i=Pv(s);return Ov(i)?i.registrations:[]}async function o(s){await Ev(xv(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.${wv()}.tmp`,a={version:1,registrations:[...s]};await Tv(i,`${X(a,{keyedMapCollapse:!0})}
|
|
91
|
-
`,{encoding:"utf8",mode:384}),await
|
|
92
|
-
`),e.command,...e.args]}function
|
|
93
|
-
`).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function
|
|
94
|
-
`),aliases:n}}function
|
|
95
|
-
`);s=l.pop()??"";for(let d of l)i(d)}),n.on("end",()=>{s!==""&&i(s)})};t(e.stdout,"worker.stdout"),t(e.stderr,"worker.stderr")}function
|
|
96
|
-
`);for(let t=r.length-1;t>=0;t-=1){let n=r[t].replace(/\r$/,"");if(n.trim()!=="")return n}return null}import{spawn as
|
|
97
|
-
`)}function
|
|
86
|
+
`),aliases:t}}function Ap(e,r){let t=r!==null&&typeof r=="object"?r:{},n=t.data??t,o=n!==null&&typeof n=="object"?n:{};return Object.entries(e.aliases).map(([s,i])=>{let a=o[s];if(a===null||typeof a!="object")return{read:i,value:null};let l=a.object;return{read:i,value:l!==null&&typeof l=="object"&&!Array.isArray(l)?l:null}})}var Sw=Pp.plugin(Vi,Go);function Dp(){let e=new Map;return{get:r=>e.get(r),set:(r,t)=>e.set(r,t)}}function jp(e){if(e?.outcome!=="asked")return Number.POSITIVE_INFINITY;let r=e.pools.rest,t=e.pools.graphql;return r===null||t===null||t.remaining<=0||t.fraction<=0?Number.POSITIVE_INFINITY:r.remaining<=0||r.fraction<=0?1:!Number.isFinite(r.fraction)||!Number.isFinite(t.fraction)?Number.POSITIVE_INFINITY:Math.max(1,Math.ceil(r.fraction/t.fraction))}var pt=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 ma(e){let r=e.etags??Dp(),t=new Sw({auth:e.token,log:{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},...e.baseUrl?{baseUrl:e.baseUrl}:{},...e.fetchImpl?{request:{fetch:e.fetchImpl}}:{},retry:{doNotRetry:[304,403,429],...e.retryCount===void 0?{}:{retries:e.retryCount}},throttle:e.throttle===!1?{enabled:!1}:{onRateLimit:()=>!1,onSecondaryRateLimit:()=>!1}}),n=async c=>{let u=r.get(c.cacheKey),m={...c.parameters??{}},f=gr(m.headers)?m.headers:{};m.headers={...f,...u?{"if-none-match":u.etag}:{}};try{let h=await t.request(c.route,m),v=h.headers,k=Fo(v,"etag");return k!==void 0&&r.set(c.cacheKey,{etag:k,data:h.data,headers:v}),await e.attribution?.record({operation:c.operation,cost:1,actor:c.actor}),{data:h.data,headers:v,quotaFree:!1}}catch(h){if(cn(h)===304){if(u===void 0)throw new Error(`GitHub returned 304 for ${JSON.stringify(c.cacheKey)} without a held answer to reuse`,{cause:h});let v=Lp(h),k={...u.headers,...v},T=Fo(k,"etag")??u.etag;return r.set(c.cacheKey,{etag:T,data:u.data,headers:k}),await e.attribution?.record({operation:c.operation,cost:0,actor:c.actor}),{data:u.data,headers:k,quotaFree:!0}}throw cn(h)===401?new pt({cause:h}):h}},o=new Map,s=!1,i=async c=>{let u=c.input,m=u.kind==="pr";try{let f=await n({cacheKey:u.cacheKey,route:m?"GET /repos/{owner}/{repo}/pulls/{pull_number}":"GET /repos/{owner}/{repo}/issues/{issue_number}",parameters:{owner:u.owner,repo:u.repo,...m?{pull_number:u.number}:{issue_number:u.number}},operation:u.operation,actor:u.actor});c.resolve({data:u.project?u.project(f.data,"rest"):f.data,surface:"rest",quotaFree:f.quotaFree})}catch(f){c.reject(f)}},a=async c=>{try{let u=Op(c.map(({input:k})=>k)),m=await t.graphql(u.query),f=Ap(u,m),h=xw(m),v=c[0].input;await e.attribution?.record({operation:{key:v.operation.key,budget:"graphql"},cost:h,actor:Pw(c.map(({input:k})=>k.actor))}),f.forEach((k,T)=>{let I=c[T];k.value===null?I.reject(new Error(`GitHub returned no ${k.read.kind} #${k.read.number} from the coalesced query`)):I.resolve({data:I.input.project?I.input.project(k.value,"graphql"):k.value,surface:"graphql",quotaFree:!1})})}catch(u){let m=cn(u)===401?new pt({cause:u}):u;c.forEach(f=>f.reject(m))}},l=async()=>{let c=null;try{c=await e.balance?.()??null}catch{}let u=jp(c);s=!1;let m=[...o.values()];o.clear(),await Promise.all(m.map(async f=>{f.length>u?await a(f):await Promise.all(f.map(i))}))};return{conditionalRest:n,singleObject:c=>r.get(c.cacheKey)!==void 0?new Promise((u,m)=>{i({input:c,resolve:u,reject:m})}):new Promise((u,m)=>{let f=o.get(c.kind)??[];f.push({input:c,resolve:u,reject:m}),o.set(c.kind,f),s||(s=!0,setTimeout(()=>void l(),0))}),async conditionalPaginate(c){let u=[],m={},f=0,h=!0,v=1;for(;;){let k=await n({...c,cacheKey:`${c.cacheKey}:page:${v}`,parameters:{...c.parameters??{},per_page:100,page:v}});if(f+=1,h=h&&k.quotaFree,!Array.isArray(k.data))throw new Error(`GitHub returned a non-list body for ${JSON.stringify(c.cacheKey)} page ${v}`);if(u.push(...k.data),m=k.headers,!Tw(k.headers))break;v+=1}return{data:u,headers:m,requestCount:f,quotaFree:h}},async graphql(c,u={},m){try{let f=await t.graphql(c,u);return m&&await e.attribution?.record({operation:m.operation,cost:1,actor:m.actor}),f}catch(f){throw cn(f)===401?new pt({cause:f}):f}}}}function Tw(e){let r=Fo(e,"link");return r!==void 0&&/(?:^|,)\s*<[^>]+>;\s*rel="next"(?:\s*;|\s*(?:,|$))/i.test(r)}function un(e){let r=cn(e),t=Lp(e);return r===429||r===403&&Fo(t,"x-ratelimit-remaining")==="0"||e instanceof Error&&/secondary rate|rate limit/i.test(e.message)}function cn(e){if(gr(e))return typeof e.status=="number"?e.status:void 0}function Lp(e){return!gr(e)||!gr(e.response)||!gr(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 gr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xw(e){let r=gr(e)?e:{},t=gr(r.data)?r.data:r,o=(gr(t.rateLimit)?t.rateLimit:{}).cost;if(!Number.isSafeInteger(o)||o<0)throw new Error("GitHub aliased query did not return a non-negative integer rateLimit.cost");return o}function Pw(e){let r=[...new Set(e.filter(t=>t!==void 0))].sort();if(r.length!==0)return r.length===1?r[0]:`coalesced:${r.join("+")}`}var Ip="rate_limit",$p={rest:"core",graphql:"graphql",search:"search"},nr=["rest","graphql","search"];function Ho(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:[...nr],detail:r??"no balance has been asked for yet, so none is known"}}var fa=15e3,mt=.15,Uo=[{at_or_below_fraction:0,every_ms:fa,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:mt,every_ms:3e4,why:"inside the reserved band: the posture can change between two calls"},{at_or_below_fraction:.5,every_ms:12e4,why:"below half: tightening, because the band is now reachable inside one window"},{at_or_below_fraction:1,every_ms:6e5,why:"above half: rare, because nothing this balance decides is anywhere close"}];var Ej=60*6e4,ga=2;function Cp(e,r){let t=Gp(e),n=Gp(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let a of nr){let l=$p[a],d=n[l],c=Dw(a,l,d);o[a]=c,c==null&&s.push(a)}let i=nr.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 ${nr.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function ha(e){try{let r=await e.transport();return Cp(r,{askedAt:e.now})}catch(r){let t=r instanceof Error?r.message:String(r);return{...Ho(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function ya(e){let r=null;for(let t of nr){let n=e.pools[t];n!=null&&(r==null||n.fraction<r.fraction)&&(r=n)}return r}function qo(e,r){let t=ya(e);if(t==null)return Bo(mt).every_ms;let n=Bo(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(fa,Math.min(n.every_ms,o))}function ka(e,r=mt){return Math.ceil(e.limit*r)}function Np(e,r,t=mt){let n=e.pools[r];return n==null?"unknown":n.remaining<=0?"spent":n.remaining<ka(n,t)?"reserved":"open"}function ba(e){let r=e.reservedFraction??mt,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:Bo(r).every_ms*ga,stale:!1,posture:"unknown",reserved_fraction:r,next_poll_ms:Bo(r).every_ms,pools:[],unreported_pools:[...nr],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let n=qo(t,{now:e.now}),o=e.stalenessMs??n*ga,s=Mp(t.asked_at,e.now),i=t.outcome==="asked"&&(s==null||s>o),a=nr.map(c=>t.pools[c]).filter(c=>c!=null),l=Aw(t,r),d=ya(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`:Ow(l,d,t,r)}}function _a(e){if(!wa(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 Ow(e,r,t,n){if(r==null)return t.detail;let o=ka(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 Aw(e,r){let t="unknown";for(let n of nr){if(e.pools[n]==null)continue;let o=Np(e,n,r);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function Bo(e){for(let r of Uo)if(e<=r.at_or_below_fraction)return r;return Uo[Uo.length-1]}function Dw(e,r,t){if(!wa(t))return null;let n=Wo(t.limit),o=Wo(t.remaining),s=Wo(t.used),i=Wo(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 Ra(e){let r=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let n=await t(`${r}/${Ip}`,{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 Wo(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function Gp(e){return wa(e)?e:{}}function wa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qp(e){return{generated_at:e.now,hour:Fp("hour",36e5,e),day:Fp("day",864e5,e)}}function mn(e,r,t){let n=pn(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(a=>{let l=pn(r(a));return l==null?!1:n==null||n-l<=o});return i.length<=s?i:i.slice(i.length-s)}function Fp(e,r,t){let n=pn(t.now),o=n==null?null:n-r,s=e==="hour"?"1h":"24h",i=t.observations.map(u=>({observation:u,at:pn(u.observed_at)})).filter(u=>u.at!=null&&Bp(u.at,o,n)).sort((u,m)=>u.at-m.at),a=t.outcomes.map(u=>pn(u.ts)).filter(u=>u!=null&&Bp(u,o,n)),l=Wp(i,u=>u.tokens,"tokens",s),d=Wp(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:jw(a.length,r,s),runner_share:Up("runner",i,u=>u.runner,s),model_share:Up("model",i,u=>u.model,s),unavailable:c}}function Wp(e,r,t,n){let o=new Map,s=0;for(let d of e){let c=r(d.observation);if(c==null||!Number.isFinite(c))continue;s+=1;let u=o.get(d.observation.worker_id)??[];u.push({at:d.at,count:c}),o.set(d.observation.worker_id,u)}if(s===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${n}`,samples:0};let i=0,a=null,l=null;for(let d of o.values()){if(d.length<2)continue;for(let m=1;m<d.length;m++){let f=d[m-1],h=d[m];f==null||h==null||(i+=Math.max(0,h.count-f.count))}let c=d[0],u=d[d.length-1];c!=null&&(a=a==null?c.at:Math.min(a,c.at)),u!=null&&(l=l==null?u.at:Math.max(l,u.at))}return a==null||l==null||l<=a?{value:null,absent_reason:`the last ${n} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:s}:{value:i/((l-a)/6e4),absent_reason:null,samples:s}}function jw(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 Up(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 Bp(e,r,t){return r==null||t==null?!0:e>=r&&e<=t}function pn(e){let r=Date.parse(e);return Number.isFinite(r)?r:null}function Vp(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.generated_at=="string"&&Hp(r.hour)&&Hp(r.day)}function Hp(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"&&Ea(r.tokens_per_min)&&Ea(r.tools_per_min)&&Ea(r.issues_per_hour)&&Array.isArray(r.unavailable)}function Ea(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 Lw}from"node:child_process";import{existsSync as Gw,readFileSync as Vo,readdirSync as Iw}from"node:fs";import{dirname as $w,join as Cr}from"node:path";function gn(e){let r=tn(e),t=[["MemoryMax",r.memory_max],["MemoryHigh",r.memory_high]];for(let[n,o]of t){if(o==null)continue;let s=dt(o);return s==null?null:{name:n,declared:o,bytes:s}}return null}function Kp(e){let r=[],t=[];for(let n of e.workers){let o=gn(n);if(o==null){t.push({worker_id:n.worker_id,reason:(tn(n).memory_max??tn(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(Cw(n,o,s))}}return{terminations:r,unenforceable:t}}function Cw(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 Nw=4096;function Jp(e,r={}){let t=r.platform??process.platform,n={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return n;let o={},s={},i={},a=Fw(e,t,r);for(let[u,m]of a){let f=Bw(m);f!=null&&(o[u]=f.memoryBytes,f.cpuSeconds!=null&&(s[u]=f.cpuSeconds),i[u]="cgroup")}let l=e.filter(u=>i[u.worker_id]==null);if(l.length===0)return{rss:o,cpu_seconds:s,sources:i};let d=Vw(t,r);if(d.size===0)return{rss:o,cpu_seconds:s,sources:i};let c=new Map;for(let u of d.values()){let m=c.get(u.ppid);m?m.push(u.pid):c.set(u.ppid,[u.pid])}for(let u of l){if(!d.has(u.pid))continue;let m=0,f=0,h=[u.pid],v=new Set;for(;h.length>0;){let k=h.pop();if(v.has(k))continue;v.add(k);let T=d.get(k);if(T){m+=T.rssBytes,f+=T.cpuSeconds;for(let I of c.get(k)??[])h.push(I)}}o[u.worker_id]=m,s[u.worker_id]=f,i[u.worker_id]="process-tree"}return{rss:o,cpu_seconds:s,sources:i}}var Mw="/sys/fs/cgroup";function Fw(e,r,t){let n=new Map;if(!(t.cgroupRoot!=null)&&r!=="linux")return n;let s=t.cgroupRoot??Mw,i=e.filter(l=>l.unit!=null&&l.unit!=="");if(i.length===0)return n;let a=Ww(s,t);for(let l of i)for(let d of a){let c=Cr(d,l.unit);if(Gw(Cr(c,"memory.current"))){n.set(l.worker_id,c);break}}return n}function Ww(e,r){let t=r.selfCgroupPath??Uw(),n=[],o=a=>{n.includes(a)||n.push(a)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(Cr(e,s));let a=$w(s);if(a===s)break;s=a}o(e);let i=r.uid??process.getuid?.();return i!=null&&o(Cr(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),n}function Uw(){try{for(let e of Vo("/proc/self/cgroup","utf8").split(`
|
|
87
|
+
`))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function Bw(e){let r;try{r=Vo(Cr(e,"memory.current"),"utf8")}catch{return null}let t=Number(r.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:Hw(e)}}function Hw(e){let r;try{r=Vo(Cr(e,"cpu.stat"),"utf8")}catch{return null}return qw(r)}function qw(e){for(let r of e.split(`
|
|
88
|
+
`)){let[t,n]=r.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(n);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function Vw(e,r){return r.procRoot!=null||e==="linux"?Xw(r.procRoot??"/proc"):r.psTable!=null||e==="darwin"?Qw(Kw(r.psTable)):new Map}function Kw(e){try{return(e??Jw)()}catch{return""}}function Jw(){return Lw("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var zw=1024;function Qw(e){let r=new Map;for(let t of e.split(`
|
|
89
|
+
`)){let n=t.trim().split(/\s+/);if(n.length!==4)continue;let[o,s,i]=n.slice(0,3).map(Number);if(![o,s,i].every(l=>l!=null&&Number.isSafeInteger(l)&&l>=0))continue;let a=Yw(n[3]);a!=null&&r.set(o,{pid:o,ppid:s,rssBytes:i*zw,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 Xw(e){let r=new Map,t;try{t=Iw(e)}catch{return r}for(let n of t){if(!/^\d+$/.test(n))continue;let o;try{o=Vo(Cr(e,n,"stat"),"utf8")}catch{continue}let s=eE(o);s&&r.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*Nw,cpuSeconds:s.cpuTicks/Zw})}return r}var Zw=100;function eE(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 rE=["api","graphql"],r0=Wi(rE);var zp=100,Sa=6e4,tE=2*Sa,nE=7*24*60*60*1e3,va=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 Ta(e,r){for(let t of e)if(t.token_ref!=null&&t.token_ref!==r)throw new va(t.project_label,t.token_ref,r)}function em(e,r={now:new Date(0).toISOString()}){sm(e);let t=r.closedWindowMs??nE,n=Date.parse(r.now);if(!Number.isFinite(n))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(r.now)}`);let o=new Date(n-Math.max(0,t)).toISOString(),s=e.map((l,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:l}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { cost remaining resetAt }",...s.flatMap(({alias:l,search_alias:d,project:c})=>{let u=JSON.stringify(c.owner),m=JSON.stringify(c.name),f=JSON.stringify(`repo:${c.owner}/${c.name} is:closed closed:>=${o}`);return[` ${l}: repository(owner: ${u}, name: ${m}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${d}: search(query: ${f}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
|
|
90
|
+
`),aliases:s,closed_since:o}}function oE(e,r,t){let n=gt(r),o=gt(n.data),s=Array.isArray(n.errors)?n.errors.map(gt):[],i=cE(o.rateLimit,s),a=e.aliases.map(({alias:l,search_alias:d,project:c})=>{let u=c.owner+"/"+c.name,m=o[l],f=s.find(h=>Xp(h.path,l)||Xp(h.path,d));if(fn(m)){let h=Zp(m.open_pull_requests),v=Zp(m.open_issues),k=uE(o[d]);if(h!=null&&v!=null&&k!=null)return{project_label:c.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:h,open_issues:v,recently_closed:k},detail:`counted ${u} for project ${JSON.stringify(c.project_label)}`}}return i.exhausted||im(f)?{project_label:c.project_label,repository:u,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${u} answered, so this project has no counts rather than zero counts${i.reset_at==null?"":`; the quota resets at ${i.reset_at}`}`}:{project_label:c.project_label,repository:u,outcome:"unreachable",counts:null,detail:`${u} is not reachable with the host token: ${Ko(f?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:a.length,rate_limit:i,projects:a}}function sE(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 rm(e){if(e.projects.length===0)return sE(e.now);if(Ta(e.projects,e.hostTokenRef),e.transport.conditionalList)return await aE(e);let r=em(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(r.query);return oE(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 iE={key:"redskilled repository activity poll",budget:"rest"};async function aE(e){sm(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=em(e.projects,{now:t,closedWindowMs:e.closedWindowMs}),o=e.transport.conditionalList,s=[],i=0,a={remaining:null,reset_at:null,exhausted:!1,point_cost:null};for(let l of e.projects){let d=`${l.owner}/${l.name}`,c=[["open-prs","GET /repos/{owner}/{repo}/pulls",{owner:l.owner,repo:l.name,state:"open"}],["open-issues","GET /repos/{owner}/{repo}/issues",{owner:l.owner,repo:l.name,state:"open"}],["recently-closed","GET /repos/{owner}/{repo}/issues",{owner:l.owner,repo:l.name,state:"closed",since:n.closed_since}]],u=[];try{for(let[m,f,h]of c){let v=await o({cacheKey:`activity:${d}:${m}:${JSON.stringify(h)}`,route:f,parameters:h,operation:iE});i+=v.requestCount;let k=m==="open-prs"?v.data:v.data.filter(T=>!fn(T.pull_request));u.push(m==="recently-closed"?k.filter(T=>Ko(T.closed_at)>=n.closed_since).length:k.length),a=Qp(a,dE(v.headers))}s.push({project_label:l.project_label,repository:d,outcome:"counted",counts:{open_pull_requests:u[0],open_issues:u[1],recently_closed:u[2]},detail:`counted ${d} for project ${JSON.stringify(l.project_label)}`})}catch(m){let f=un(m);a=Qp(a,{remaining:null,reset_at:null,exhausted:f,point_cost:null}),s.push({project_label:l.project_label,repository:d,outcome:f?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${d} answered: ${m instanceof Error?m.message:String(m)}`})}}return{version:1,fetched_at:e.now,request_count:i,project_count:s.length,rate_limit:a,projects:s}}function tm(e){let r=e.stalenessMs??tE,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 nm(e){if(!fn(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)&&fn(r.rate_limit)&&Array.isArray(r.projects)&&typeof r.reason=="string"}function om(e){let r=e.endpoint==null?void 0:lE(e.endpoint),t=ma({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 lE(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 dE(e){let r=Yp(e,"x-ratelimit-remaining"),t=Yp(e,"x-ratelimit-reset");return{remaining:r,reset_at:t==null?null:new Date(t*1e3).toISOString(),exhausted:r===0,point_cost:null}}function Qp(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 Yp(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 sm(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>zp)throw new Error(`redskilled activity fetch spans at most ${zp} 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 cE(e,r){let t=gt(e),n=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=r.some(im),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 im(e){if(e==null)return!1;let r=Ko(e.type),t=Ko(e.message);return r==="RATE_LIMITED"||/rate limit/i.test(t)}function Xp(e,r){return Array.isArray(e)&&e.includes(r)}function Zp(e){let r=gt(e);return Number.isInteger(r.totalCount)?r.totalCount:null}function uE(e){let r=gt(e);return Number.isInteger(r.issueCount)?r.issueCount:null}function gt(e){return fn(e)?e:{}}function fn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ko(e){return typeof e=="string"?e:""}var pE=3e4,mE=2,gE=3,fE=4,hE=["logs","vitals","display"];function am(e,r){if(r===void 0)return e;let t=hE.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:yE,budget:{...o.budget,used_bytes:null,used_fraction:null}},...n("logs")?{}:{log:kE},...n("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var yE={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},kE={last_line:null,published_at:null,source:null};function lm(e){let r=e.stalenessMs??pE,t=fr(e.now),n=e.sampledAt==null?null:fr(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=>wE(m,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[m.worker_id],display:e.displays?.[m.worker_id],state:i.has(m.worker_id)?"reattached":"running"})),l=a.filter(m=>m.vitals.rss_bytes==null).map(m=>m.worker_id).sort(),d=a.length-l.length,c=a.reduce((m,f)=>m+(f.vitals.rss_bytes??0),0),u=To(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:TE({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:SE(a),known_projects:vE(e.hostState),registered_projects:(e.hostState.registrations??[]).map(m=>m.project_label).sort((m,f)=>m.localeCompare(f)),lapsed_projects:(e.hostState.lapsed_registrations??[]).map(m=>({project_label:m.project_label,at:m.at,...m.registered_at==null?{}:{registered_at:m.registered_at},reason:m.detail})),stopped_projects:(e.hostState.stopped_registrations??[]).map(m=>({project_label:m.project_label,at:m.at})),orphaned_projects:(e.hostState.orphaned_registrations??[]).map(m=>m.project_label),workers:a,github_balance:ba({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:tm({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:bE(e.deaths,e.recentDeathLimit??fE)},engine:RE(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function bE(e,r){let t=[...e].sort((s,i)=>(fr(i.ts)??0)-(fr(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=_E(t);return{count:t.length,recent:n,latest:n[0]??null,reaped_at:n[0]?.ts??null,...o==null?{}:{boot_loop:o}}}function _E(e){let r=new Map;for(let n of e){if(n.sender_class!=="boot-refused"||n.uptime_s==null||n.uptime_s>mE||n.project_label==null||n.project_label===""||fr(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>=gE).map(([n,o])=>{let s=o[0],i=fr(s.ts),a=Math.min(...o.map(d=>fr(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 RE(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 wE(e,r){let t=r.rss[e.worker_id],n=typeof t=="number"&&Number.isFinite(t)?t:null,o=gn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=fr(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,...e.base_commits_ahead==null?{}:{base_commits_ahead:e.base_commits_ahead},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:EE(r.log),display:r.display?.display??null,display_published_at:r.display?.published_at??null}}function EE(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 vE(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 SE(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 TE(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 fr(e){let r=Date.parse(e);return Number.isFinite(r)?r:null}function xa(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(xE))&&(r.stopped_projects===void 0||Array.isArray(r.stopped_projects)&&r.stopped_projects.every(PE))&&(r.orphaned_projects===void 0||Array.isArray(r.orphaned_projects)&&r.orphaned_projects.every(s=>typeof s=="string"))&&(r.repository_activity===void 0||nm(r.repository_activity))&&(r.github_balance===void 0||_a(r.github_balance))&&(r.deaths===void 0||OE(r.deaths))&&(r.engine===void 0||AE(r.engine))&&(r.metrics===void 0||Vp(r.metrics))}function xE(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 PE(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 OE(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 AE(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 dm={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 cm(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`,hn=ae("48;2;114;47;55"),Pa=ae("48;2;88;36;42"),hr=ae("38;2;255;255;255"),Oa=ae("38;2;201;150;158"),yn=ae("38;2;255;214;214"),kn=ae("39"),ke=ae("38;2;224;138;148"),Aa=ae("38;2;240;200;120"),Da=ae("38;2;240;110;120"),ja=ae("38;2;255;214;214"),La=ae("38;2;146;84;94"),Ga=ae("38;2;255;95;95"),qe=ae("49"),Le=ae("0"),Jo=ae("1"),zo=ae("22");var DE=/\x1b\[[0-9;]*m/g,jE=/(\x1b\[[0-9;]*m)/,LE=/^\x1b\[[0-9;]*m$/;function um(e){return e.replace(DE,"")}function GE(e){return e.slice(2,-1).split(";").every(t=>t===""||Number(t)===0)}function xe(e){return[...um(e)].length}function fe(e,r){if(r<=0)return"";if(xe(e)<=r)return e;if(r===1)return"\u2026";let t=r-1,n=0,o=!1,s="";for(let i of e.split(jE))if(i!==""){if(LE.test(i)){s+=i,o=!GE(i);continue}for(let a of i){if(n===t)return`${s}\u2026${o?Le:""}`;s+=a,n+=1}}return`${s}\u2026${o?Le:""}`}function bn(e,r){return e+" ".repeat(Math.max(0,r-xe(e)))}function Ia(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 Ge(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 _n(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 _n(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 yr(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 ft(e){if(e==null)return null;let r=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return r===""?null:r}var wn="!unregistered",$a="!lapsed",En="\u21E1",or="\u2020",ht="\u25D0",yt="\u25EF",Ca="\u21B3",Na="redskilled unreachable \u2014 Worker state unknown";function kt(e,r){return r.mode==="global"?e.workers:r.project==null?[]:e.workers.filter(t=>t.project_label===r.project)}function Qo(e,r){return r.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===r.project)}function vn(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 Ma(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 br=["wid","run","org","iss","bar","phase","base","elapsed","eta","hb","loc","tks","ctx","tls","rsn","txt"],Ve={mode:"local",project:null,maxWidth:200,maxRows:16},IE=" ",pm="\u2588",$E="\u25B6",CE="\u2717",NE="\u2591",ME=new Set(["gate","push-pr","merge","cascade"]),FE=new Set(["requeue"]),WE="repair";function Sn(e){return e.display?.origin===WE}function bt(e,r=Ve){let t=vn(e,r.project),n=kt(e,r),o=n.slice(0,Math.max(0,Math.floor(r.maxRows))),s=o.map(u=>Yo(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:fe(XE(s[m],i),r.maxWidth)})),l=BE(e,r,n,t),d=n.length-o.length,c=[l.line,...a.map(u=>u.line)];return d>0&&c.push(fe(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,r.maxWidth)),c.push(...KE(e,r)),c.push(...VE(e,r)),{version:1,generated_at:e.generated_at,mode:r.mode,project:r.project,columns:br,header:l,rows:a,lines:c,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Yo(e,r,t){let n=e.display??dm,o=Sn(e),s=[n.runner,n.model==null?null:Ia(n.model),n.effort].filter(l=>!!l).join(" "),i=n.phase!=null&&ME.has(n.phase),a=o||i||n.origin!=null&&FE.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:mm(n),phase:[n.phase,n.step].filter(l=>!!l).join("\xB7"),base:e.base_commits_ahead==null?"":`base +${e.base_commits_ahead}`,elapsed:yr(cm(e,t)),eta:n.eta==null?"":`eta=${yr(n.eta*1e3)}`,hb:UE(n,t)??`hb=${n.heartbeat??"?"}`,loc:a?"":QE(n.added,n.removed),tks:a||n.tokens==null?"":`tks=${_n(n.tokens)}`,ctx:n.context==null?"":`ctx=${_n(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 UE(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} ${yr(Math.max(0,n-t))}`}function mm(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 pm.repeat(Math.floor(r));let o=e.failed?CE:$E;return`${pm.repeat(n)}${o}${NE.repeat(Math.floor(r)-n-1)}`}function BE(e,r,t,n){let o=(e.repository_activity?.projects??[]).find(G=>G.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=zE(t),l=o?.repository??r.project,d=e.engine??null,c=d?.running_version??e.daemon.daemon_version,u=e.deaths??null,m=e.metrics??null,f=[HE(l??"host",c,d!=null&&d.current===!1?En:"")];(n==="unregistered"||n==="name-only")&&f.push(wn),n==="lapsed"&&f.push($a),a!=null&&f.push(`${hn}${hr}${a}${qe}${ke}`);let h=e.workers.filter(Sn).length;if(h>0){let G=Math.max(0,e.host.worker_count-h);f.push(`${kr(`workers=${G} coding +`)} ${hn}${hr}${h} repairing${qe}${ke}`)}else f.push(kr(`wrk=${t.length}/${e.host.worker_count}`));let v=i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`;f.push(kr(`${v} reserve=${i.interactive_reservation} interactive`)),f.push(kr(JE(i))),s.open_pull_requests!=null&&f.push(kr(`prs=${s.open_pull_requests}`)),s.recently_closed!=null&&f.push(kr(`cpr=${s.recently_closed}`)),s.open_issues!=null&&f.push(kr(`iss=${s.open_issues}`)),s.stale&&f.push("!counts stale");let k=m==null?null:gm(m.hour),T=k==null?null:kr(k);if(T!=null&&f.push(T),u!=null&&u.count>0&&u.latest!=null){let G=u.boot_loop,H=ft(G?.latest_refusal);f.push(G==null?`${or}${u.count} ${u.latest.sender_class}`:`${or}${u.count} boot-refused \xD7${G.count} in ${qE(G.span_ms)}`+(H==null?"":` \u2014 ${H}`))}if(e.staleness.stale){let G=e.staleness.age_ms;f.push(G==null?"!unmeasured":`!stale ${Math.round(G/1e3)}s`)}let I=`${f.join(" \xB7 ")}${Le}`,F=k!=null&&xe(I)>r.maxWidth?`${f.filter(G=>G!==T).join(" \xB7 ")}${Le}`:I;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:fe(F,r.maxWidth)}}function HE(e,r,t){return`${Pa}${hr}${Aa}\xBB${hr} ${Jo}${e}${zo} ${Oa}v${r}${t}${hr}${qe}${ke}`}function kr(e){return e.replace(/(^|\s)([A-Za-z][A-Za-z0-9/]*=)([^\s]+)/g,(r,t,n,o)=>`${t}${yn}${n}${kn}${o}${ke}`)}function qE(e){return yr(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function gm(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 VE(e,r){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let n=t.posture==="spent"?yt:ht,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[fe(`${n} github budget ${t.posture}${o} \u2014 ${t.reason}`,r.maxWidth)]}function KE(e,r){let t=e.deaths;if(t==null||t.count<=0)return[];let n=t.recent.map(s=>fe(`${or} ${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(fe(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,r.maxWidth)),n}function JE(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${Ge(e.memory_used_bytes)}`;let r=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${Ge(e.memory_used_bytes)}/${Ge(e.memory_ceiling_bytes)}${r}`}function zE(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 QE(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(br.map(t=>[t,0]));for(let t of e)for(let n of br)r[n]=Math.max(r[n],xe(t[n]));return r}function XE(e,r){let t=br.filter(o=>r[o]>0);if(t.length===0)return"";let n=t.map((o,s)=>Xo(o,bn(e[o],s===t.length-1?xe(e[o]):r[o])));return`${qe}${ke}${n.join(IE)}${Le}`}function Xo(e,r){if(e==="wid")return`${Jo}${r}${zo}`;if(e==="org"&&r.trim()==="lane=repair"){let n=r.slice(r.trimEnd().length);return`${hn}${hr}${r.trimEnd()}${qe}${ke}${n}`}if(e==="bar")return r.replace(/█+/g,n=>`${Da}${n}`).replace("\u25B6",`${ja}\u25B6`).replace("\u2717",`${Ga}\u2717`).replace(/░+/g,n=>`${La}${n}`)+ke;let t=r.indexOf("=");return t>0?`${yn}${r.slice(0,t+1)}${kn}${r.slice(t+1)}${ke}`:r}function Wa(e){return Object.freeze({none:!0,reason:e})}function Tn(){return{tool:"project_start",args:{runner:"claude",target:1},why:"register this project with the host so its queue can drain"}}function Fa(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=>Fa(n,r)));let t={};for(let[n,o]of Object.entries(e))t[n]=Fa(o,r);return Object.freeze(t)}finally{r.delete(e)}}function ZE(e){let r=Fa(e.args,new Set);return Object.freeze({tool:e.tool,args:r,why:e.why})}function Nr(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=ZE(e.repair);return{prose:`${e.state}; repair: call \`${r.tool}\` with \`${JSON.stringify(r.args)}\` because ${r.why}`,repair:r}}var B={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Mr(e,r=B){let t=vn(e,r.project),n=kt(e,r),o=Qo(e,r),s=sv(e,r.project,t),i=rv(e,r,n,t,s.prose),a=Ma({mode:r.mode,maxWorkers:r.maxWorkers,maxProjects:r.maxProjects,workers:n,projects:o}),l={detail:"host",line:i};for(let f of a){let h=f==="workers"?i:cv(i,ev(f,o),r.separator);if(l={detail:f,line:h},f==="workers"||xe(h)<=r.maxWidth)break}let d=fe(l.line,r.maxWidth),c=l.detail==="workers"?av(n,r,e.generated_at):{lines:[],degraded:!1},u=l.detail==="workers"?n.flatMap((f,h)=>{let v=r.verbose?lv(f,r):null;return v==null?[c.lines[h]]:[c.lines[h],v]}):[],m=n.length>0?"workers":"host";return{version:1,line:d,lines:[d,...u],verbose:r.verbose,mode:r.mode,project:r.project,project_match:t,...s.repair===void 0?{}:{repair:s.repair},...s.repair_reason===void 0?{}:{repair_reason:s.repair_reason},detail:l.detail,degraded:l.detail!==m||d!==l.line||c.degraded,stale:e.staleness.stale,generated_at:e.generated_at}}function qa(e){let r=e.options??B,t=fe(Na,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 ev(e,r){return e==="projects"?r.map(dv):[]}function rv(e,r,t,n,o){let s=[],i=n!=="matched"&&n!=="name-only";r.mode==="global"?(s.push(`host ${Ua(e.workers,e.host.worker_count)}/${e.host.project_count}p`),s.push(Ha(e,r))):n==="matched"?(s.push(`${r.project} ${Ua(t,t.length)}`),s.push(Ha(e,r)),t.length===0&&s.push("idle")):n==="name-only"?(s.push(`${r.project} ${Ua(t,t.length)}`),s.push(Ha(e,r)),s.push(wn)):s.push(o),s.push(fm(e));let a=tv(e);a!=null&&s.push(a);let l=nv(e);l!=null&&s.push(l),e.staleness.stale&&s.push(hm(e));let d=s.join(" ");return!i||xe(d)<=r.maxWidth||a==null&&l==null?d:[a,l,o,fm(e),e.staleness.stale?hm(e):null].filter(c=>c!=null).join(" ")}function Ua(e,r){let t=e.filter(Sn).length;return t===0?`${r}w`:`${Math.max(0,r-t)} coding + ${t} repairing`}function fm(e){let r=e.engine,t=r?.running_version??e.daemon.daemon_version;return r==null||r.current!==!1?`v${t}`:`v${t}${En}`}function tv(e){let r=e.github_balance;return r==null?null:r.posture==="spent"?`${yt} quota spent`:r.posture==="reserved"?`${ht} quota band`:null}function nv(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=ft(t.latest_refusal);return`${or}${r.count} boot-refused \xD7${t.count} in ${ov(t.span_ms)}`+(n==null?"":` \u2014 ${n}`)}return`${or}${r.count} ${r.latest.sender_class}`}function ov(e){return yr(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function sv(e,r,t){if(t==="unregistered")return Nr({state:`project unknown \u2014 ${r} was never registered on this host`,repair:Tn()});if(t==="orphaned")return Nr({state:`project unknown \u2014 ${r} is registered on a daemon this socket does not reach`,repair:Wa("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 Nr({state:`project unknown \u2014 ${r} was stopped${n==null?"":` at ${Ba(n.at)}`}`,repair:Tn()})}if(t==="lapsed"){let n=e.lapsed_projects?.find(o=>o.project_label===r);if(n!=null){let o=n.registered_at==null?"":` (registered ${Ba(n.registered_at)})`;return Nr({state:`project unknown \u2014 ${r} lapsed at ${Ba(n.at)}${o}`,repair:Tn()})}return Nr({state:`project unknown \u2014 ${r} lapsed`,repair:Tn()})}return t==="unresolved"?Nr({state:"project unknown \u2014 this directory resolved to no project",repair:Wa("the directory must resolve to a project before registration args can be safe")}):{prose:""}}function Ba(e){return/^\d{4}-\d{2}-\d{2}T(\d{2}:\d{2}:\d{2})/.exec(e)?.[1]??e}function Ha(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?`${Ge(t)}/${Ge(n)}`:Ge(t)}function hm(e){let r=e.staleness.age_ms;return r==null?"!unmeasured":`!stale ${Math.round(r/1e3)}s`}function iv(e,r,t,n){let o=t.map(s=>Xo(s,bn(e[s],r[s])));return fe(`${qe}${ke}${o.join(" ")}${Le}`,n)}function av(e,r,t){let n=e.map(a=>Yo(a,r,t)),o=br.filter(a=>n.some(l=>xe(l[a])>0)),s=[...o],i=ym(n,s);for(;s.length>1&&km(i,s)>r.maxWidth;)s.pop(),i=ym(n,s);return{lines:n.map(a=>iv(a,i,s,r.maxWidth)),degraded:s.length<o.length||km(i,s)>r.maxWidth}}function ym(e,r){let t=Object.fromEntries(br.map(n=>[n,0]));for(let n of e)for(let o of r)t[o]=Math.max(t[o],xe(n[o]));return t}function km(e,r){return r.reduce((t,n)=>t+e[n],0)+Math.max(0,r.length-1)*2}function lv(e,r){let t=ft(e.log.last_line);return t==null?null:fe(` ${Ca} ${bm(e,r.mode)}: ${t}`,r.maxWidth)}function bm(e,r){return r==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function dv(e){return`${e.project_label} ${e.worker_count}w ${Ge(e.observed_rss_bytes)}`}function cv(e,r,t){return[e,...r].join(t)}var Zo=1;async function xn(e,r){return await bo(e,r,"redskilled daemon")}function Rm(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:Zo,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:gv(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:Mc(r,{hostCeilingBytes:e.ceiling?.memory_bytes??e.hostCeilingBytes??null}),upgrade:fv(e)}}function gv(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:Eu(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 fv(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 wm(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||_v(r.ceiling))&&Array.isArray(r.workers)&&Array.isArray(r.projects)&&Fc(r.budget_accounting)&&(r.scope===void 0||yu(r.scope))&&(r.registrations===void 0||Array.isArray(r.registrations)&&r.registrations.every(an))&&(r.demand===void 0||nu(r.demand))&&(r.lapsed_registrations===void 0||Array.isArray(r.lapsed_registrations)&&r.lapsed_registrations.every(yv))&&(r.stopped_registrations===void 0||Array.isArray(r.stopped_registrations)&&r.stopped_registrations.every(kv))&&(r.orphaned_registrations===void 0||Array.isArray(r.orphaned_registrations)&&r.orphaned_registrations.every(bv))&&(r.birth_latches===void 0||Array.isArray(r.birth_latches)&&r.birth_latches.every(hv))&&(r.upgrade===void 0||Rv(r.upgrade))}function hv(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 yv(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 kv(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 bv(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 _v(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 Rv(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||wv(r.major_hold))}function wv(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 Ev}from"node:crypto";import{mkdir as vv,readFile as Sv,rename as Tv,writeFile as xv}from"node:fs/promises";import{dirname as Pv}from"node:path";function Em(e){let r=Promise.resolve(),t=null;async function n(){await r;let s;try{s=await Sv(e,"utf8")}catch(a){if(a.code==="ENOENT")return[];throw a}let i=Ov(s);return Av(i)?i.registrations:[]}async function o(s){await vv(Pv(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.${Ev()}.tmp`,a={version:1,registrations:[...s]};await xv(i,`${X(a,{keyedMapCollapse:!0})}
|
|
91
|
+
`,{encoding:"utf8",mode:384}),await Tv(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 Ov(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return me(r)}catch{return null}}}function Av(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(an)}import{spawnSync as ts}from"node:child_process";import{existsSync as Qa}from"node:fs";import{delimiter as Mv,join as Lm}from"node:path";import{join as vm}from"node:path";import{existsSync as Dv}from"node:fs";import{createRequire as jv}from"node:module";var Sm="redskilled-job-object.node",Fr=100;function _t(e){return{available:!1,reason:e}}function Lv(e,r,t){return[vm(t,"prebuilds",`${e}-${r}`,Sm),vm(t,"native","build","Release",Sm)]}function Tm(e={}){let r=e.platform??process.platform,t=e.arch??process.arch;if(r!=="win32")return _t(`Job Object placement is the Windows backend (platform=${r}), so there is no native reach to load here`);let n=e.packageRoot??Iv(),o=e.exists??Dv,s=Lv(r,t,n),i=s.find(d=>o(d));if(i==null)return _t(`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??jv(import.meta.url),l;try{l=a(i)}catch(d){return _t(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return Gv(l)?{available:!0,binding:l}:_t(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function Gv(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Iv(){return new URL("..",import.meta.url).pathname}function xm(e){let r=e??{},t=[],n=$v(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<Fr?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 ${Fr}, 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 $v(e){return gn({budget:e})}var es=5,Pm=19;function Va(e){return{available:!1,reason:e}}var Cv="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 Am(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=es;else if(t.cpu_weight<Fr){let a=Math.round(Pm*(Fr-t.cpu_weight)/Fr);o=Math.min(Pm,Math.max(es,a))}else o=es,n.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${Fr}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${es}`);let s=Om(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=Om(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:Cv,...n.length>0?{note:n.join("; ")}:{}}}function Dm(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 ${Nv(e.nice)} -n ${r.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
|
|
92
|
+
`),e.command,...e.args]}function jm(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 Ka(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 Om(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function Nv(e){return`'${e.replace(/'/g,"'\\''")}'`}var Gm="REDSKILLED_PLACEMENT",rs="red-worker",Ja="/bin/sh";function Im(e=process.env,r=process.platform){let t=Va(`POSIX rlimit and priority placement is the macOS backend (platform=${r})`);if(r==="win32")return{platform:r,systemdRun:null,userSession:!1,jobObjects:Tm({platform:r}),posix:t};let n=_t(`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:Fv(e)};if(r!=="linux")return{platform:r,systemdRun:null,userSession:!1,jobObjects:n,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Qa(Lm(o,"systemd","private"));return{platform:r,systemdRun:Mm("systemd-run",e),userSession:s,jobObjects:n,posix:t}}function Fv(e){return Qa(Ja)?{available:!0,shell:Ja,nice:Mm("nice",e)}:Va(`no POSIX shell was found at ${Ja}, so there is nothing to apply rlimits or priority in`)}function $m(e=process.env){let r=(e[Gm]??"").trim().toLowerCase();return r===""?!0:!["off","false","0","no"].includes(r)}function Wv(e,r,t=rs){return Cm(e,r,t).replace(/\.service$/,"")}function Cm(e,r,t=rs){return`${za(t,"red-worker",24)}-${za(e,"project",32)}-${za(r,"worker",32)}.service`}function Nm(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:zt({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 ${Gm}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return Bv(e,r,t,n,o,i);if(e.probes.platform==="darwin")return Uv(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=Cm(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=zt({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=Ka(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 Uv(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=Am(t,{canRenice:s.nice!=null}),a=t.memory_high!=null||t.memory_max!=null,l=jm(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:Dm({limits:i,nice:s.nice,command:e.command,args:r}),cwd:e.workspacePath,posix:i,warning:l,budget:t,...n!=null?{memoryCeiling:n}:{},environment:zt({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 Bv(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=xm(t),l=Wv(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:zt({scope:l,memory_ceiling:n,scope_degradation:null}),...Hv(o&&a.note!=null?`${a.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,Ka(e.budget))}}function Hv(...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(Mv)){if(!t)continue;let n=Lm(t,e);if(Qa(n))return n}return null}function za(e,r,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||r}async function Ya(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 Fm=3e4;function Wm(e){return e.unit!=null&&e.unit!==""?qv(e.unit):ne(e.pid)}function qv(e){let r=ts("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return r.error!=null?!1:r.status===0}var Vv="REDSKILLED_UNIT_DISCOVERY",Um="(unowned)";function Bm(e){let r=ts("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 Kv(e=process.env){let r=(e[Vv]??"").trim().toLowerCase();return r===""?!0:!["off","false","0","no"].includes(r)}function Hm(e,r,t=process.env){return Kv(t)&&e===r}function qm(e=rs){let r=ts("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return r.error!=null||r.status!==0?[]:(r.stdout??"").split(`
|
|
93
|
+
`).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function Vm(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:Um,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 Km(e){return e.project_label.trim()!==""?e:{...e,project_label:Um,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 Jm(e){if(e.unit!=null&&e.unit!==""){let r=ts("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 An=50,Za=15e3,VL=2*Za;function Jv(e,r=An){if(el(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 Qm(e,r={}){let t=r.batchSize??An;if(el(e),e.length>t)throw new Error(`redskilled queue discovery spans at most ${t} selectors in one query, and this batch holds ${e.length}: split it with planQueueDiscoveryBatches rather than dropping the remainder`);let n=e.map((i,a)=>({alias:`q${a}`,project:i}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...n.map(({alias:i,project:a})=>` ${i}: search(query: ${JSON.stringify(a.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
|
|
94
|
+
`),aliases:n}}function Ym(e,r){let t=On(r),n=On(t.data),o=Array.isArray(t.errors)?t.errors.map(On):[],s=Zv(n.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=rS(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=>eS(u.path,a));return s.exhausted||eg(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: ${Xa(c?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function zv(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:An,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function Xm(e,r,t){return{version:1,fetched_at:r,request_count:0,project_count:e.length,batch_size:An,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 Zm(e){if(e.projects.length===0)return zv(e.now);if(e.transport.conditionalList)return await Yv(e);let r=e.batchSize??An,t=Jv(e.projects,r),n=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=Qm(s,{batchSize:r});try{let a=await e.transport(i.query),l=Ym(i,a);n.push(...l.projects),o=Pn(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=Pn(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 Qv={key:"redskilled queue poll",budget:"rest"};async function Yv(e){el(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=Qm([s],{batchSize:1}),d=Ym(l,await e.transport(l.query));o+=1,t.push(...d.projects),n=Pn(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:Qv});o+=i.requestCount;let a=i.data.filter(l=>!rg(l.pull_request)).length;n=Pn(n,Xv(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=un(i);n=Pn(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 el(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 Pn(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 Xv(e){let r=zm(e,"x-ratelimit-remaining"),t=zm(e,"x-ratelimit-reset");return{remaining:r,reset_at:t==null?null:new Date(t*1e3).toISOString(),exhausted:r===0}}function zm(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 Zv(e,r){let t=On(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(eg)||n===0}}function eg(e){return e==null?!1:Xa(e.type)==="RATE_LIMITED"||/rate limit/i.test(Xa(e.message))}function eS(e,r){return Array.isArray(e)&&e.includes(r)}function rS(e){let r=On(e);return Number.isInteger(r.issueCount)?r.issueCount:null}function On(e){return rg(e)?e:{}}function rg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xa(e){return typeof e=="string"?e:""}function tg(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(tS,Math.max(r,i))}let o=n.remaining;return o==null?r:o<=nS?Math.max(r,3e4):o<=oS?Math.max(r,2e4):r}var tS=1e5,nS=250,oS=1e3;var sS={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},iS=["runner","model","effort","origin","issue","phase","step","heartbeat","wait_kind","wait_subject","wait_started_at","wait_deadline","wait_escalation","started_at"],aS=["phase_index","phase_total","wait_pid","context","eta","added","removed","tokens","tools","reasoning","text"];function ng(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let r=e,t={...sS};for(let n of iS){let o=r[n];t[n]=typeof o=="string"&&o.trim()!==""?o:null}for(let n of aS){let o=r[n];t[n]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=r.failed===!0,t}import{randomInt as uS}from"node:crypto";import{spawn as pS}from"node:child_process";import{appendFileSync as mS,mkdirSync as gS}from"node:fs";import{dirname as fS}from"node:path";import{delimiter as og,dirname as lS}from"node:path";function dS(e,r=og){return(e??"").split(r).map(t=>t.trim()).filter(t=>t!=="")}function cS(e=process.execPath){let r=(e??"").trim();if(r==="")return null;let t=lS(r);return t===""||t==="."?null:t}function sg(e,r=process.execPath,t=og){let n=dS(e,t),o=cS(r);return o==null?n.join(t):[o,...n.filter(s=>s!==o)].join(t)}var Rt=class extends Error{constructor(r){super(r),this.name="RedskilledWorkerSpecError"}},Ke=class extends Error{constructor(t,n){super(t);this.admission=n;this.name="RedskilledAdmissionError"}},rl="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",ig=4,hS=rl.length**ig;function nl(e,r=uS){let t=new Set(e);for(let n=0;n<hS;n+=1){let o="h";for(let s=0;s<ig;s+=1)o+=rl[r(rl.length)];if(!t.has(o))return o}throw new Rt("redskilled exhausted the host Worker id space")}function yS(e){if(e==null||e.trim()==="")return{ready:!1};let r=fS(e);try{return gS(r,{recursive:!0}),{ready:!0}}catch(t){let n=t?.code;return{ready:!1,warning:`redskilled could not create the log directory ${JSON.stringify(r)} for ${JSON.stringify(e)}${n==null?"":` (${n})`}: ${tl(t)}. This Worker runs with NO log at all, so nothing but its heartbeat can show what it did`}}}function kS(e,r){let t=(n,o)=>{if(n==null)return;let s="",i=a=>{try{mS(r,ye().push({at:new Date().toISOString(),kind:o,msg:a}),"utf8")}catch{}};n.on("data",a=>{s+=String(a);let l=s.split(`
|
|
95
|
+
`);s=l.pop()??"";for(let d of l)i(d)}),n.on("end",()=>{s!==""&&i(s)})};t(e.stdout,"worker.stdout"),t(e.stderr,"worker.stderr")}function bS(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 Rt(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new Rt("redskilled worker spec args must be an array")}function _S(e){if(e==null)throw new Ke("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new Ke(e.reason,e)}function ag(e){let{spec:r,admission:t}=e;_S(t),bS(r);let n=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(r.worker_id??e.workerId)?.trim()||nl(e.liveWorkerIds??[]),i=e.probes??Im(n),a=bu(r.log_path,{worker_id:s,workspace_path:r.workspace_path}),l=e.openLog===!1?{ready:!1}:yS(a),d=l.ready,c={...r.env??{},...e.forkSha==null||e.forkSha===""?{}:{RED_AFK_FORK_SHA:e.forkSha},PATH:sg(r.env?.PATH??n.PATH,e.execPath??process.execPath)},u=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:c,enabled:e.enabled??$m(n),probes:i,pipeOutput:d}),f=(e.spawnFn??pS)(u.command,u.args,{...u.cwd!=null?{cwd:u.cwd}:{},detached:!0,stdio:d?["ignore","pipe","pipe"]:"ignore",env:u.backend==="transient-unit"?{...n}:{...n,...c,...u.environment}});if(d&&a!=null&&kS(f,a),f.pid==null)throw f.once("error",()=>{}),new Rt(`redskilled could not spawn ${JSON.stringify(u.command)} for worker ${s}`);let h=u.job!=null?RS(u,i,f.pid):null;f.once("error",()=>{}),f.once("exit",(I,F)=>{try{h?.job?.close()}catch{}e.onExit?.(s,I,F)}),f.unref();let v=u.job!=null?h?.job!=null:u.isolated,k=[u.warning,h?.warning,u.budgetWarning,l.warning].filter(I=>I!=null);return{worker:{worker_id:s,project_label:r.project_label,pid:f.pid,started_at:o(),workspace_path:r.workspace_path,...d&&a!=null?{log_path:a}:{},isolated:v,...u.unit!=null?{unit:u.unit}:{},...r.budget!=null?{budget:r.budget}:{},...Object.keys(u.budget).length>0?{applied_budget:u.budget}:{},...u.memoryCeiling!=null?{memory_ceiling:u.memoryCeiling,memory_ceiling_reason:e.memoryCeiling?.reason??"this Worker's ceiling is the budget its client declared"}:{},warnings:k},admission:t,...e.forkSha==null||e.forkSha===""?{}:{fork_sha:e.forkSha},warnings:k,plan:u,child:f,...h?.job!=null?{job:h.job}:{}}}function RS(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: ${tl(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)}: ${tl(i)}. ${o}`}}return{job:s}}function tl(e){return e instanceof Error?e.message:String(e)}import{execFile as wS}from"node:child_process";var ES="refs/heads/red-trunk";function ns(e,r){return new Promise((t,n)=>{wS("git",[...r],{cwd:e},(o,s,i)=>{if(o!=null){n(new Error(i.trim()||o.message));return}t(s.trim())})})}async function lg(e){await ns(e.workspace_path,["fetch",e.trunk.remote,e.trunk.branch]);let r=await ns(e.workspace_path,["rev-parse","--verify","FETCH_HEAD^{commit}"]);if(r==="")throw new Error("the fetched trunk did not resolve to a commit");return await ns(e.workspace_path,["update-ref",ES,r]),r}async function dg(e){let r=await ns(e.workspace_path,["rev-list","--count",`${e.fork_sha}..${e.head_sha}`]),t=Number(r);if(!Number.isInteger(t)||t<0)throw new Error(`git returned an invalid base movement count: ${r}`);return t}import{open as vS,stat as SS}from"node:fs/promises";var TS=16*1024;async function cg(e,r=TS){let t;try{t=(await SS(e)).size}catch{return null}if(t<=0)return null;let n=Math.min(r,t),o;try{let s=await vS(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 xS(o)}function xS(e){let r=e.split(`
|
|
96
|
+
`);for(let t=r.length-1;t>=0;t-=1){let n=r[t].replace(/\r$/,"");if(n.trim()!=="")return n}return null}import{spawn as US}from"node:child_process";import{existsSync as BS,readdirSync as HS}from"node:fs";import{dirname as qS,join as hg,resolve as VS}from"node:path";var PS="<version>";function _r(e,r=[],t){let n=t&&t.trim().length>0?t.trim():PS;return[`npx -y -p ${Gr}@${n}`,e,...r].join(" ")}function Ie(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 ol(e,r){let t=Ie(e),n=Ie(r);return!t||!n?0:t.major-n.major||t.minor-n.minor||t.patch-n.patch}var fG=4*60*60*1e3;rr();rr();import{spawnSync as OS}from"node:child_process";import{mkdir as AS,rm as DS,writeFile as jS}from"node:fs/promises";import{existsSync as LS}from"node:fs";import{homedir as GS}from"node:os";import{dirname as IS,join as sl}from"node:path";var Rr="redskilled.service",il="REDSKILLED_SUPERVISED",$S="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function CS(e=process.env){let r=e.XDG_CONFIG_HOME?.trim()||sl(e.HOME?.trim()||GS(),".config");return sl(r,"systemd","user")}function al(e=process.env){return sl(CS(e),Rr)}function ug(e,r={}){let t=r.env??process.env,n=Eo(r.override??{},r.entryLookup??{}),o=[...n.args,...jr(e,r.idleMs==null?{}:{idleMs:r.idleMs})];return{unitName:Rr,unitPath:al(t),command:n.command,args:o,text:NS(n.command,o,e)}}function NS(e,r,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${$S}`,"","[Service]","Type=simple",`ExecStart=${[e,...r].map(MS).join(" ")}`,"Restart=always","RestartSec=1",`Environment="${il}=1"`,`Environment="REDSKILLED_SESSION=${pg(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
|
|
97
|
+
`)}function MS(e){return/[\s"'\\$%]/.test(e)?`"${pg(e)}"`:e}function pg(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function mg(e,r={}){let t=r.writeFile??FS,n=r.run??ll,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(os("daemon-reload",n,["systemctl","--user","daemon-reload"])),o.push(os("enable",n,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function gg(e={}){let r=e.removeFile??WS,t=e.run??ll,n=al(e.env??process.env),o=[os("disable",t,["systemctl","--user","disable","--now",Rr])];return await r(n),o.push({step:"remove-unit",ok:!0,detail:n}),o.push(os("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:n,installed:!1,steps:o}}function fg(e={}){let r=e.exists??LS,t=e.run??ll,n=al(e.env??process.env),o=r(n),s=o&&t(["systemctl","--user","is-enabled",Rr]).status===0,i=o&&t(["systemctl","--user","is-active",Rr]).status===0,a=s&&!i?[{code:"enabled-but-inactive",evidence:`${Rr} is installed and enabled but inactive`,fix:`systemctl --user restart ${Rr}`}]:[];return{unitName:Rr,unitPath:n,installed:o,enabled:s,active:i,findings:a,floor:"auto-spawn"}}function os(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 FS(e,r){await AS(IS(e),{recursive:!0}),await jS(e,r,{encoding:"utf8",mode:420})}async function WS(e){await DS(e,{force:!0})}function ll(e){let r=OS(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 yg=75,bg=9e5,kg="redskilled-replacement-entry-unresolved",KS="REDSKILLED_NO_REGISTRY_PROBE",_g="REDSKILLED_BORN_BY_REPLACEMENT";function Rg(e=process.env){return e[_g]==="1"}function wg(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function Eg(e){let r=e.running.trim();if(Dn(r))return null;let t=e.newest?.trim()??"",n=Ie(t),o=Ie(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:JS(n.major,e.supervised)}}function JS(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: ${_r("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 vg(e){let r=e.running.trim();if(Dn(r))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||Ie(t)===null?{act:"hold",reason:"published-unknown"}:ol(t,r)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function Dn(e){let r=e.trim();return Ie(r)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(r)}function Sg(e=process.env){return e[il]==="1"}var dl=class extends Error{code=kg;searched;constructor(r,t){super(`${kg}: the published redskilled bundle ${r} exists on no reachable path and the version-pinned dispatch is disabled
|
|
98
98
|
searched:
|
|
99
99
|
${t.map(n=>` ${n}`).join(`
|
|
100
|
-
`)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function
|
|
101
|
-
`}function nT(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return me(r)}catch{return null}}}function oT(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 jn=3e5,uT=1e4,pT=6e4,mT=15e3,Fg=3e4,gT=Fg*2,fT=6e4,ss=16;function hT(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 Ng(e){let r=e?.match(/\bsession-error:\s*(.+)$/)?.[1]?.trim();return r==null||r===""?null:r}var Wr=class extends Error{constructor(t,n){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=n;this.name="RedskilledAlreadyRunningError"}},yT="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Wg(e){let{paths:r}=e,t=e.daemonVersion??"0.0.0-dev",n=e.idleMs??jn,o=e.clock??(()=>new Date().toISOString()),s=e.launch??sg,i=e.refreshTrunk??ig,a=e.countBaseMovement??ag,l=e.ceiling??xo();e.repositoryActivity!=null&&Ta(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let d=e.owner??Ig(),c=e.leaseStore??$g(r.leasePath,{sessionKeyHash:r.sessionKeyHash,machineIdHash:r.machineIdHash,socketPath:r.socketPath},{clock:o}),u=e.machineOwner??gu(),m={machineIdHash:r.machineIdHash,sessionKeyHash:r.sessionKeyHash,socketPath:r.socketPath},f=e.machineClaimStore??Ao(r.machineClaimPath,m,{clock:o});await aT(cT(r.socketPath),{recursive:!0,mode:448});let[h,v]=await Promise.all([c.read().catch(()=>{}),f.read().catch(()=>{})]),k=Date.parse(o()),T=h==null?Number.NaN:Date.parse(h.renewed_at);h!=null&&v!=null&&h.pid===v.pid&&h.start_time===v.start_time&&h.socket_path===r.socketPath&&v.socket_path===r.socketPath&&Number.isFinite(k)&&Number.isFinite(T)&&k-T>=gT&&await Ug(r.socketPath)==="unowned"&&await c.release({pid:h.pid,startTime:h.start_time}).catch(()=>!1)&&await f.release({pid:v.pid,startTime:v.start_time,uid:v.uid}).catch(()=>!1);let U=await f.claim(u);if(!U.claimed)throw U.claim?.socket_path===r.socketPath?new Wr(r.socketPath):new ur(f.claimPath,U.reason,U.claim);let G=await c.acquire(d);if(!G.acquired)throw await f.release(u).catch(()=>{}),new Wr(r.socketPath,G.lease);let H;try{H=await kT(r.socketPath,async()=>{let[p,y]=await Promise.all([c.read().catch(()=>{}),f.read().catch(()=>{})]);return p!=null&&p.pid!==d.pid&&ne(p.pid)?!0:y!=null&&y.socket_path===r.socketPath&&y.pid!==u.pid&&ne(y.pid)})}catch(p){throw await c.release(d).catch(()=>{}),await f.release(u).catch(()=>{}),p}let ee=o(),q=e.eventLane??Xc(r.eventLanePath),he=e.registrationIntentStore??_m(r.registrationIntentPath),wr=e.liveness??Nm,Cn=e.livenessGraceMs??Cm,Nn=e.stopWorker??qm,Mn=e.unitInventory??(()=>Wm(r.machineClaimPath,Oo({machineIdHash:r.machineIdHash}))?Um():[]),Br=e.unitMainPid??Fm,ps=e.treeSampler??qp,vt=e.readLogTail??lg,Fn=e.sampleMs??mT,Wn=e.leaseRenewMs??Fg,St=e.registrationSustainMs??fT,Tt=e.publishedVersion??(p=>Tg(p)),Un=e.replaceCheckMs??yg,xt=e.publishedProbeTimeoutMs??uT,Bn=e.localPublishedEvidence??(p=>xg(p,e.replacementIO?.env??process.env)),Hn=e.bornByReplacement??bg(),Pt=e.replaceBootCheckMs??pT,Ot=e.supervised??Eg(),Er=e.replacementIO??{},be=e.repositoryActivity,At=be?.intervalMs??Sa,vr=e.githubBalance,$e=e.queueDiscovery,Hr=$e?.transport??be?.transport,Dt=$e?.unconfiguredReason??yT,jt=$e?.intervalMs??Za,Lt=e.demandMs??15e3,qn=e.demandBackoffMs??3e4,C=new Map,sr=new Map,Pe=new Set,Ce=new Map,ir=new Map,qr=[],Sr=[],ar=e.deaths===void 0?void 0:[...e.deaths],_e=await he.read().catch(()=>[]),Vr=Date.parse(ee),W=new Map,oe=new Map;for(let p of _e){let y=Date.parse(p.renew_by);!Number.isFinite(Vr)||!Number.isFinite(y)||y>=Vr?W.set(p.project_label,p):Vr-y<=p.renew_within_ms&&oe.set(p.project_label,p)}let D=new Set,b={},g=null,_=null,R=null,E=!1,x=0,A=null,N="none",V=null,z=null,Qe=null,Tr=null,se=null,Gt=null,Ye=[],Xe=[],ms=new Map((e.orphanedRegistrations??[]).map(p=>[p.project_label,p])),It=null,Re={},gs=!1,Kr,$t,Ct,Nt,Mt,Ft,Vn,Wt,Jr,zr,pe=!1,fs=!1,Kn=null,Sl,hs=new Promise(p=>{Sl=p});function Qr(p){Tl(p);let y=Date.parse(p),w=Ru(W.values(),y);for(let S of w.lapsed){W.delete(S.project_label);let O=se?.projects.find(L=>L.project_label===S.project_label),j=[...C.values()].some(L=>L.project_label===S.project_label);(O?.outcome==="counted"&&(O.depth??0)>0||j)&&oe.set(S.project_label,S),Af(S,y)}return w.lapsed.length>0&&Yr(),w.lapsed}function Yr(){let p=new Map(oe);for(let[y,w]of W)p.set(y,w);he.replace([...p.values()]).catch(()=>{})}function Af(p,y){let w=Number.isFinite(y)?new Date(y).toISOString():p.renew_by;Ye.push({project_label:p.project_label,registered_at:p.registered_at,at:w,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`}),Ye.length>ss&&Ye.splice(0,Ye.length-ss)}function Tl(p){if(W.size===0)return;let y=Date.parse(p);if(!Number.isFinite(y))return;let w={};for(let L of C.values())w[L.project_label]=(w[L.project_label]??0)+1;let S=se==null?Number.NaN:Date.parse(se.fetched_at),O=new Map((se?.projects??[]).map(L=>[L.project_label,L])),j=!1;for(let L of[...W.values()]){let J=Number.isFinite(S)&&y-S<=L.renew_within_ms?O.get(L.project_label):void 0,Xr=Mi(L,{now:p,...J==null?{}:{queue:{outcome:J.outcome,depth:J.depth}},liveWorkers:w[L.project_label]??0});Xr.registration!==L&&(W.set(L.project_label,Xr.registration),j=!0)}j&&Yr()}function xl(p){if(oe.size===0)return;let y=Date.parse(p);if(!Number.isFinite(y))return;let w=new Map((se?.projects??[]).map(O=>[O.project_label,O])),S=!1;for(let[O,j]of[...oe]){if(y-Date.parse(j.renew_by)>j.renew_within_ms){oe.delete(O),S=!0;continue}let L=w.get(O),Q=Mi(j,{now:p,...L==null?{}:{queue:{outcome:L.outcome,depth:L.depth}},liveWorkers:[...C.values()].filter(J=>J.project_label===O).length});Q.verdict==="open-work"||Q.verdict==="live-worker"?(W.set(O,Q.registration),oe.delete(O),S=!0):Q.verdict==="drained"&&(oe.delete(O),S=!0)}S&&Yr()}function Jn(){let p=o();return Qr(p),km({now:p,daemonVersion:t,machineIdHash:r.machineIdHash,sessionKeyHash:r.sessionKeyHash,pid:d.pid,startedAt:ee,ceiling:l,scope:fu(f.claimPath,m,u),workers:[...C.values()],registrations:[...W.values()],demand:Gt,lapses:Ye,stops:Xe,orphanedRegistrations:[...ms.values()],birthLatches:su(Re,Date.parse(p)),queue:se,published:{version:_,checkedAt:R,newer:E,replacement:N,newest:V,majorHold:z,checks:x,holdReason:A}})}function zn(){return sm({hostState:Jn(),ceiling:l,rss:b,sampledAt:g,logLines:Object.fromEntries(Ce),displays:Object.fromEntries(ir),now:o(),reattachedWorkerIds:[...Pe],repositoryActivity:Qe,githubBalance:Tr,...ar===void 0?{}:{deaths:ar},metrics:Up({observations:qr,outcomes:Sr,now:o()})})}function Df(p,y){qr=mn([...qr,{worker_id:y,observed_at:p.published_at,tokens:p.display.tokens,tools:p.display.tools,runner:p.display.runner,model:p.display.model}],w=>w.observed_at,{now:o()})}function jf(p){Sr=mn([...Sr,p],y=>y.ts,{now:o()})}async function ys(){return be==null||be.projects.length===0?null:(Qe=await Xp({projects:be.projects,hostTokenRef:be.hostTokenRef,transport:be.transport,closedWindowMs:be.closedWindowMs,now:o()}),Qe)}async function Pl(){return vr==null?null:(Tr=await ha({transport:vr.transport,now:o()}),Tr)}function Lf(){if(pe||Jr!=null||vr==null)return;let p=()=>{Jr=void 0,Pl().catch(()=>{}).then(()=>{if(pe)return;let y=vr.intervalMsOverride??Ho(Tr??Gf(),{now:o()});Jr=setTimeout(p,y),Jr.unref()})};p()}function Gf(){return Bo(o())}function If(){if(!(Hr!=null||$e?.armTransport==null))try{let p=$e.armTransport();if(p.transport!=null){Hr=p.transport;return}p.unconfiguredReason!=null&&(Dt=p.unconfiguredReason)}catch(p){Dt=`this host could not resolve a tracker credential: ${p instanceof Error?p.message:String(p)}`}}async function Ol(){let p=o();Qr(p);let y=Date.parse(p);for(let[j,L]of[...oe])Number.isFinite(y)&&y-Date.parse(L.renew_by)>L.renew_within_ms&&oe.delete(j);let S=[...new Map([...oe,...W]).values()].map(j=>({project_label:j.project_label,selector:j.selector,...j.queue_poll==null?{}:{poll:j.queue_poll}})).sort((j,L)=>j.project_label.localeCompare(L.project_label));if(S.length===0)return null;if(If(),Hr==null)return se=zm(S,p,Dt),se;se=await Qm({projects:S,transport:Hr,now:p,...$e?.batchSize==null?{}:{batchSize:$e.batchSize}});let O=o();return xl(O),Tl(O),se}async function Al(){let p=o();if(gs)return Gt??ru(p);gs=!0;try{await bs().catch(()=>{});let y={};for(let I of C.values())y[I.project_label]=(y[I.project_label]??0)+1;let w={};for(let I of se?.projects??[])w[I.project_label]=I.depth;let S=Date.parse(p),O=Number.isFinite(S)?S:0;for(let[I,le]of Object.entries(Re)){if(le.probeWorkerId==null)continue;let to=C.get(le.probeWorkerId);to!=null&&O-Date.parse(to.started_at)>=6e4&&(Re[I]=Di())}let j=eu({projects:[...W.values()].map(I=>({project_label:I.project_label,selector:I.selector,argv:I.argv,workspace_path:I.workspace_path,target:I.target})),queue:w,live:y,nowMs:O,backoffUntilMs:It,birthHealth:Re}),L=[],Q=new Map,J=null;for(let I of j.births){let le,to=tl(C.keys()),Zr=W.get(I.project_label),no=yu({argv:I.argv,...Zr?.env==null?{}:{env:Zr.env},...Zr?.log_path==null?{}:{log_path:Zr.log_path}},{worker_id:to,slot:I.index,workspace_path:I.workspace_path},{project_label:I.project_label});try{if(Zr?.trunk==null)le=Yn(no);else{let Ze={workspace_path:I.workspace_path,trunk:Zr.trunk},Bt=Ut(no);if(!Bt.admitted)throw new Ke(Bt.reason,Bt);let Kl=Cl(Ze),oo=Q.get(Kl);oo==null&&(oo=ks(Ze),Q.set(Kl,oo)),le=await Nl(no,Ze,oo,Bt)}}catch(Ze){J=Ze instanceof Error?Ze.message:String(Ze),Ze instanceof Ke&&Ze.admission?.verdict==="refused-unreachable-trunk-remote"||(It=(Number.isFinite(S)?S:Date.now())+qn);break}L.push({project_label:I.project_label,worker_id:le.worker.worker_id,pid:le.worker.pid,...le.fork_sha==null?{}:{fork_sha:le.fork_sha},warnings:no.log_path==null?[...le.warnings,`project ${JSON.stringify(I.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(le.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:le.warnings});let Es=Re[I.project_label];Es?.haltUntilMs!=null&&O>=Es.haltUntilMs&&(Re[I.project_label]=ou(Es,le.worker.worker_id))}J==null&&j.births.length>0&&(It=null);let Xr=new Set(L.map(I=>I.project_label));for(let I of j.intents){if(I.queue_depth==null||I.queue_depth<=0||I.live>=I.target||Xr.has(I.project_label))continue;let le=J!=null&&(I.outcome==="asking"||I.outcome==="half-open-probe")?`project ${JSON.stringify(I.project_label)} was birth-eligible but the host refused it: ${J}`:I.detail;await q.recordDemandRefusal({ts:p,projectLabel:I.project_label,detail:le}).catch(()=>{})}return Gt={version:1,at:p,requested:j.births.length,granted:L,shortfall:j.births.length-L.length,refusal:J,retry_after:It==null?null:new Date(It).toISOString(),projects:j.intents},Gt}finally{gs=!1}}function $f(p){return Mr(zn(),{...B,mode:p?.mode??B.mode,project:p?.project??B.project,maxWorkers:p?.max_workers??B.maxWorkers,maxProjects:p?.max_projects??B.maxProjects,maxWidth:p?.max_width??B.maxWidth,verbose:p?.verbose??B.verbose})}function Cf(p){return bt(zn(),{mode:p?.mode??Ve.mode,project:p?.project??Ve.project,maxWidth:p?.max_width??Ve.maxWidth,maxRows:p?.max_rows??Ve.maxRows})}function xr(p,y,w){return vu({op:p,sessionProject:y??null,targetProject:w})}async function Nf(p){let y=C.get(p.worker_id),w=xr(Eu(p.command),p.session_project,y?.project_label??null);if(!w.permitted)throw new Error(w.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 S=y!=null&&await Bf(y,p.detail??"stopped by its own project");return{version:1,command:p.command,worker_id:p.worker_id,applied:S,reach:w,detail:S?`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 Qn(p){C.delete(p),Pe.delete(p),Ce.delete(p),ir.delete(p)}function Dl(p){let y=C.get(p.worker_id),w=xr("worker-heartbeat",p.session_project,y?.project_label??null);if(!w.permitted)throw new Error(w.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:w,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(p.worker_id)} to publish a line for`};let S=o();Ce.set(p.worker_id,{line:p.last_log_line,published_at:S,source:"heartbeat"});let O=p.display===void 0?null:eg(p.display);if(O!=null){let j=ir.get(p.worker_id)?.display,L={display:O,published_at:S};ir.set(p.worker_id,L),Df(L,p.worker_id),(O.phase!==j?.phase||O.step!==j?.step)&&we("worker-activity",y,null,{phase:O.phase,step:O.step})}return p.mechanical_heal?.heal_kind==="mechanical-regeneration"&&we("worker-heal",y,`${p.mechanical_heal.cause}; cycle ${p.mechanical_heal.cycle}/${p.mechanical_heal.cap}; free=${p.mechanical_heal.free}`,{healKind:p.mechanical_heal.heal_kind}),{version:1,worker_id:p.worker_id,accepted:!0,reach:w,published_at:S,detail:`redskilled stored a line for Worker ${JSON.stringify(p.worker_id)} without reading it`}}async function Mf(p,y,w){let S=`exit code=${y??"null"} signal=${w??"null"}`;if(p.unit!=null&&p.unit!==""&&await Wf(p)){Uf(p,`its launch client ended (${S}) 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 O=p.log_path==null?null:Ng(await vt(p.log_path).catch(()=>null));Qn(p.worker_id),we("worker-death",p,O==null?S:`session-error: ${O}`,{exitCode:y,signal:w,refusal:O}),re()}function Ff(p,y){if(!Number.isFinite(y)||y<0){Re[p]=on;return}let w=Re[p]??on,S=nu(w,y,Date.parse(o()));Re[p]=S,S.haltUntilMs!=null&&w.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(p)} lost ${S.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(S.haltUntilMs).toISOString()}
|
|
102
|
-
`)}function jl(p,y){let w=xr("project-reset",y,p);if(!w.permitted)throw new Error(w.reason);let S=Re[p]?.haltUntilMs!=null||Re[p]?.probeWorkerId!=null;return Re[p]=Di(),{version:1,project_label:p,latch:"project-birth-breaker",reset:S,reach:w,detail:S?`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 Wf(p){try{return await wr(p)===!0}catch{return!1}}function Uf(p,y){let w=p.unit==null?null:Br(p.unit);C.set(p.worker_id,{...p,...w!=null&&w>0?{pid:w}:{},warnings:[...p.warnings,y]}),Pe.add(p.worker_id),re()}function Ll(p,y){let w=xr("project-register",y,p.project_label);if(!w.permitted)throw new Error(w.reason);let S=o();Qr(S);let O=ku(p,{now:S,held:W.get(p.project_label)});return W.set(O.project_label,O),Yr(),$l(O.project_label),re(),{version:1,registration:O,reach:w,detail:`redskilled holds a registration for project ${JSON.stringify(O.project_label)} at a target of ${O.target} until ${O.renew_by}, and has read neither its selector nor its argv`}}function Gl(p,y={}){let w=xr("project-renew",y.sessionProject,p);if(!w.permitted)throw new Error(w.reason);let S=o();Qr(S);let O=W.get(p);if(O==null){if(ms.has(p))throw new Ir(p,{kind:"orphaned"});let L=[...Xe].reverse().find(J=>J.project_label===p);if(L!=null)throw new Ir(p,{kind:"stopped",at:L.at});let Q=[...Ye].reverse().find(J=>J.project_label===p);throw Q!=null?new Ir(p,{kind:"lapsed",at:Q.at,...Q.registered_at==null?{}:{registered_at:Q.registered_at}}):new Ir(p)}let j=bu(O,{now:S,...y.renewWithinMs==null?{}:{renew_within_ms:y.renewWithinMs},...y.launch==null?{}:{launch:y.launch}});return W.set(j.project_label,j),Yr(),re(),{version:1,registration:j,reach:w,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 Il(p,y){let w=xr("project-deregister",y,p);if(!w.permitted)throw new Error(w.reason);let S=W.get(p)??oe.get(p),O=W.delete(p),j=oe.delete(p),L=O||j;if(S!=null){let Q=`redskilled released the registration for project ${JSON.stringify(p)}`;$l(p),Xe.push({project_label:p,registered_at:S.registered_at,at:o(),detail:Q}),Xe.length>ss&&Xe.splice(0,Xe.length-ss)}return L&&Yr(),{version:1,project_label:p,released:L,reach:w,detail:L?`redskilled released the registration for project ${JSON.stringify(p)}`:`redskilled held no registration for project ${JSON.stringify(p)}, so there was nothing to release`}}function $l(p){oe.delete(p);for(let y=Ye.length-1;y>=0;y-=1)Ye[y].project_label===p&&Ye.splice(y,1);for(let y=Xe.length-1;y>=0;y-=1)Xe[y].project_label===p&&Xe.splice(y,1);ms.delete(p)}async function Bf(p,y){try{await Nn(p)}catch{}return Qn(p.worker_id),we("worker-death",p,y),re(),!0}function Ut(p){return Kc({ceiling:l,workers:[...C.values()],budget:p.budget,projectLabel:p.project_label,...p.reservation==null?{}:{reservation:p.reservation}})}function Cl(p){return`${p.workspace_path}\0${p.trunk.remote}\0${p.trunk.branch}`}function ks(p){let y=Cl(p),w=sr.get(y);if(w!=null)return w;let S=i(p).finally(()=>{sr.get(y)===S&&sr.delete(y)});return sr.set(y,S),S}function Hf(p,y,w){let S=w instanceof Error?w.message:String(w);return{...p,admitted:!1,verdict:"refused-unreachable-trunk-remote",reason:`refused-unreachable-trunk-remote: redskilled refused this Worker because trunk remote ${JSON.stringify(y.trunk.remote)} could not refresh branch ${JSON.stringify(y.trunk.branch)}: ${S}`}}async function Nl(p,y,w,S){let O=S??Ut(p);if(!O.admitted)throw new Ke(O.reason,O);let j;try{j=await(w??ks(y))}catch(Q){let J=Hf(O,y,Q);throw new Ke(J.reason,J)}let L=Ut(p);if(!L.admitted)throw new Ke(L.reason,L);return Yn(p,{admission:L,forkSha:j})}function Yn(p,y={}){let w=Jc({ceiling:l,workers:[...C.values()],budget:p.budget}),S=s({spec:p,admission:y.admission??Ut(p),...y.forkSha==null?{}:{forkSha:y.forkSha},memoryCeiling:w,liveWorkerIds:C.keys(),clock:o,onExit:(Q,J,Xr)=>{let I=C.get(Q);if(I==null){re();return}Mf(I,J,Xr).catch(()=>{})}}),O=y.forkSha??S.fork_sha??S.worker.fork_sha,j=O==null||O===""?S.worker:{...S.worker,fork_sha:O},L={...S,worker:j,...O==null||O===""?{}:{fork_sha:O}};return C.set(j.worker_id,j),we("worker-birth",j,null,{admissionVerdict:y.admission?.verdict??S.admission.verdict}),re(),L}function we(p,y,w,S={}){if(pe)return;let O=o(),j={kind:p,worker:y,ts:O,detail:w,...S};(p==="worker-death"||p==="worker-budget-kill")&&(jf({worker_id:y.worker_id,ts:O,outcome:p}),Ml(Po(j),{startedAt:y.started_at,...S.refusal==null?{}:{refusal:S.refusal}}),Ff(y.project_label,Date.parse(O)-Date.parse(y.started_at))),q.recordWorker(j).catch(()=>{})}function Ml(p,y={}){let w=hT(p,y);if(w==null)return;let S=[w,...(ar??[]).filter(O=>O.kind!==w.kind||O.id!==w.id||O.ts!==w.ts)].sort((O,j)=>Date.parse(O.ts)-Date.parse(j.ts));ar=mn(S,O=>O.ts,{now:o()})}async function bs(){let p=Date.parse(o()),y=[...C.values()].filter(S=>{if(Pe.has(S.worker_id))return!0;let O=Date.parse(S.started_at);return!Number.isFinite(O)||p-O>=Cn});if(y.length===0)return[];let{dead:w}=await Ya(y,wr);for(let S of w)Qn(S.worker_id),we("worker-death",S,"the host no longer confirms this Worker");return w.length>0&&re(),w}async function Fl(p,y){let w=C.get(p);if(!w)return!1;try{await Nn(w)}catch{}return Qn(p),we("worker-budget-kill",w,y),re(),!0}async function Wl(){let p=[...C.values()];if(p.length===0)return[];let y;try{y=await ps(p)}catch{return[]}let w=y.rss;b=w,g=o(),qf(y.cpu_seconds,g);let{terminations:S}=Hp({workers:p,rss:w}),O=[];for(let j of S)await Fl(j.worker_id,j.reason)&&O.push(j);return O}function qf(p,y){for(let[w,S]of Object.entries(p)){if(typeof S!="number"||!Number.isFinite(S))continue;let O=C.get(w);O&&C.set(w,{...O,cpu:{cpu_seconds:S,sampled_at:y}})}}async function Vf(){try{return xt<=0?await Tt(t):await new Promise(p=>{let y=setTimeout(()=>p(_s()),xt);y.unref(),Tt(t).then(w=>{clearTimeout(y),p(w)},()=>{clearTimeout(y),p(_s())})})}catch{return _s()}}function _s(){try{return Bn(t)}catch{return null}}async function Ul(){if(Dn(t))return x+=1,R=o(),A="local-build",{act:"hold",reason:"local-build"};let p=_g(await Vf()),y=p.version;_=y,V=p.newest??null,R=o(),z=Rg({running:t,newest:V,supervised:Ot});let w=wg({running:t,published:y,supervised:Ot});return E=w.act==="replace",x+=1,A=w.act==="hold"?w.reason:null,N!=="in-progress"&&(N=w.act==="replace"?"pending":"none"),w}async function Xn(){let p=await Ul();if(p.act!=="replace"||N==="in-progress")return p;let y=vg(p,Er);return N="in-progress",await q.flush().catch(()=>{}),await he.flush().catch(()=>{}),await eo({reason:"replaced"}),Sg(y,r,{...n==null?{}:{idleMs:n},io:Er}),p}function Kf(){pe||Ft!=null||Un<=0||(!Hn&&Pt>0&&(Vn=setTimeout(()=>{Xn().catch(()=>{})},Pt),Vn.unref()),Ft=setInterval(()=>{Xn().catch(()=>{})},Un),Ft.unref())}async function Bl(){return await c.renew(d).catch(()=>null)}function Jf(){pe||Ct!=null||Wn<=0||(Ct=setInterval(()=>{Bl()},Wn),Ct.unref())}function zf(){pe||Nt!=null||St<=0||(Nt=setInterval(()=>{Qr(o())},St),Nt.unref())}function Qf(){pe||$t!=null||Fn<=0||($t=setInterval(()=>{Wl().catch(()=>{})},Fn),$t.unref())}function Yf(){pe||Wt!=null||be==null||be.projects.length===0||At<=0||(ys().catch(()=>{}),Wt=setInterval(()=>{ys().catch(()=>{})},At),Wt.unref())}function Xf(){if(pe||zr!=null||jt<=0)return;let p=y=>{zr=setTimeout(()=>{zr=void 0,Hl().then(()=>Ol()).catch(()=>{}).finally(()=>{if(pe)return;let w=Date.parse(o());p(Zm(se,jt,Number.isFinite(w)?w:Date.now()))})},y),zr.unref()};p(jt)}async function Hl(){await Promise.allSettled([...W.values()].filter(p=>p.trunk!=null).map(async p=>{let y=await ks({workspace_path:p.workspace_path,trunk:p.trunk}),w=[...C.values()].filter(S=>S.project_label===p.project_label&&S.fork_sha!=null&&S.fork_sha!=="");await Promise.allSettled(w.map(async S=>{let O=await a({workspace_path:p.workspace_path,fork_sha:S.fork_sha,head_sha:y}),j=C.get(S.worker_id);if(j==null||j.fork_sha!==S.fork_sha)return;let L={...j,base_head_sha:y,base_commits_ahead:O};C.set(S.worker_id,L),(j.base_head_sha!==y||j.base_commits_ahead!==O)&&we("worker-drift",L,null,{baseHeadSha:y,baseCommitsAhead:O})}))}))}function Zf(){pe||Mt!=null||Lt<=0||(Mt=setInterval(()=>{Al().catch(()=>{})},Lt),Mt.unref())}function re(){pe||(Kr&&clearTimeout(Kr),Kr=setTimeout(()=>{bs().catch(()=>{}).then(()=>ql())},n),Kr.unref())}function ql(){return C.size>0?(re(),"held-by-workers"):(Qr(o()),W.size>0?(re(),"held-by-registrations"):(eh(),"exited"))}async function eh(){if(!Dn(t)){if((await Xn().catch(()=>null))?.act==="replace"||fs||pe)return;if(C.size>0||W.size>0){re();return}}await eo({reason:"idle"})}function Zn(p){return au({reason:p,socketPath:r.socketPath,daemonVersion:t,pid:d.pid,workers:[...C.values()],projects:[...W.keys()]})}function Vl(p){if(Kn!=null)return Kn;let y=p.reason??"requested",w=p.note?.trim();return Kn=q.recordDaemonStop({ts:o(),pid:d.pid,socketPath:r.socketPath,reason:y,detail:w==null||w===""?Zn(y).detail:`${Zn(y).detail} \u2014 ${w}`,...p.signal==null?{}:{signal:p.signal}}).catch(()=>{}),Kn}async function eo(p={}){if(fs)return await hs;fs=!0,await Vl(p),pe=!0,Kr&&clearTimeout(Kr),$t&&clearInterval($t),Ct&&clearInterval(Ct),Nt&&clearInterval(Nt),Ft&&clearInterval(Ft),Vn&&clearTimeout(Vn),Wt&&clearInterval(Wt),Jr&&clearTimeout(Jr),zr&&clearTimeout(zr),Mt&&clearInterval(Mt),await q.flush().catch(()=>{}),await he.flush().catch(()=>{}),await c.release(d),await f.release(u),H.close();for(let y of D)y.destroy();return await new Promise(y=>H.once("close",()=>y())),await Mg(r.socketPath,{force:!0}),Sl(),await hs}let Rs=await q.read().catch(()=>[]),ro=new Map;for(let p of Rs){if(p.event==="worker-birth"){ro.set(p.worker_id,p.ts);continue}let y=Ng(p.detail);Ml(p,{...ro.get(p.worker_id)==null?{}:{startedAt:ro.get(p.worker_id)},...y==null?{}:{refusal:y}}),(p.event==="worker-death"||p.event==="worker-budget-kill")&&ro.delete(p.worker_id)}Sr=mn(Rs.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 rh=Zc(Rs),ws=await Ya(rh,wr);for(let p of ws.alive){let y=Hm(p),w=y.unit==null||ne(y.pid)?null:Br(y.unit);C.set(y.worker_id,w!=null&&w>0?{...y,pid:w}:y),Pe.add(y.worker_id)}for(let p of ws.dead)we("worker-death",p,"the Worker ended while no daemon was watching");let th=Bm({units:await Promise.resolve(Mn()).catch(()=>[]),held:[...C.values()],mainPid:Br,now:ee});for(let p of th)C.set(p.worker_id,p),Pe.add(p.worker_id),we("worker-birth",p,"adopted from an active unit with no birth on this lane");xl(o());for(let p of ws.alive){if(p.log_path==null||Ce.has(p.worker_id))continue;let y=await vt(p.log_path).catch(()=>null);y==null||y.trim()===""||Ce.set(p.worker_id,{line:y,published_at:o(),source:"rehydrated"})}H.on("connection",p=>{D.add(p),p.once("close",()=>D.delete(p)),re(),bT(p,async(y,w)=>{re();let S=await nh(y);w(S),y.op==="shutdown"&&setImmediate(()=>void eo({reason:"requested"}).catch(()=>{}))})});async function nh(p){try{if(p.op==="ping")return{id:p.id,ok:!0,value:{pong:!0,protocol_version:Xo,daemon_version:t,pid:d.pid}};if(p.op==="host-state")return{id:p.id,ok:!0,value:Jn()};if(p.op==="statusline-payload")return{id:p.id,ok:!0,value:om(zn(),p.extras)};if(p.op==="statusline-string")return{id:p.id,ok:!0,value:$f(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:Dl(p.heartbeat)};if(p.op==="project-register"){let w=Ll(p.registration,p.session_project);return await he.flush(),{id:p.id,ok:!0,value:w}}if(p.op==="project-renew"){let w=Gl(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 he.flush(),{id:p.id,ok:!0,value:w}}if(p.op==="project-deregister"){let w=Il(p.project_label,p.session_project);return await he.flush(),{id:p.id,ok:!0,value:w}}if(p.op==="project-reset")return{id:p.id,ok:!0,value:jl(p.project_label,p.session_project)};if(p.op==="worker-command")return{id:p.id,ok:!0,value:await Nf(p.command)};if(p.op==="worker-start"){let w=xr("worker-start",p.session_project,p.spec.project_label);if(!w.permitted)return{id:p.id,ok:!1,error:w.reason};let S=p.spec.trunk==null?Yn(p.spec):await Nl(p.spec,{workspace_path:p.spec.workspace_path,trunk:p.spec.trunk});return await q.flush().catch(()=>{}),{id:p.id,ok:!0,value:{worker:S.worker,admission:S.admission,fork_sha:S.fork_sha,warnings:S.warnings}}}if(p.op==="shutdown"){let w=Zn("requested");return await Vl({reason:"requested",...p.detail==null?{}:{note:p.detail}}),{id:p.id,ok:!0,value:w}}let y=p;return{id:y.id??is(),ok:!1,error:`unsupported redskilled op: ${y.op??"unknown"}`}}catch(y){return{id:p.id??is(),ok:!1,error:y instanceof Error?y.message:String(y)}}}return re(),Qf(),Jf(),zf(),Kf(),Yf(),Lf(),Xf(),Zf(),{socketPath:r.socketPath,lease:G.lease,startedAt:ee,closed:hs,startWorker:Yn,admit:Ut,ceiling:()=>l,killWorkerOverBudget:Fl,sampleMemoryBudgets:Wl,renewLease:Bl,pollRepositoryActivity:ys,pollGithubBalance:Pl,githubBalance:()=>Tr,pollQueueDiscovery:Ol,queueDiscovery:()=>se,driveDemand:Al,demand:()=>Gt,sweepWorkerLiveness:bs,publishWorkerHeartbeat:Dl,reattached:()=>[...Pe].map(p=>C.get(p)).filter(p=>p!=null),flushEvents:()=>q.flush(),trackWorker(p){C.set(p.worker_id,p),we("worker-birth",p,null),re()},releaseWorker(p){let y=C.get(p),w=C.delete(p);return Pe.delete(p),Ce.delete(p),ir.delete(p),y&&we("worker-death",y,"released by the daemon"),re(),w},workerCount:()=>C.size,registerProject:Ll,renewProject:Gl,resetProjectBirthBreaker:jl,deregisterProject:Il,registrations:()=>Jn().registrations??[],hostState:Jn,refreshRegisteredTrunks:Hl,statuslinePayload:zn,evaluateIdle:ql,observePublishedVersion:Ul,checkForReplacement:Xn,stopReport:Zn,stop:eo}}async function Ug(e,r=250){return await new Promise(t=>{let n=lT(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 kT(e,r){for(let t=0;t<2;t++){let n=dT();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 Ug(e)!=="unowned")throw new Wr(e);if(await r?.())throw new Wr(e);await Mg(e,{force:!0})}}throw new Wr(e)}async function Je(e,r=250){try{return(await bo({socketPath:e,timeoutMs:r},{id:is(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function bT(e,r){Ec(e,(t,n)=>r(t,n),(t,n,o)=>{o({id:n?.id??is(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function pl(e){let r=e.socketPath,t=_T(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 ${Bg(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 \`${_r("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 \`${_r("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function ml(e){return`${e.reason} ${e.repair}`}function _T(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:RT(r.acquired_at,e.now??new Date().toISOString())}}function RT(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 Bg(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`}rr();var Vg=1e4,Ur=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"?`. ${ml(o)}`:""}`);this.socketPath=t;this.cause=n;this.presence=o;this.name="RedskilledUnreachableError"}},gl=class extends Ur{constructor(t,n,o){super(t,o,n);this.presence=n;this.name="RedskilledDaemonHeldError"}},as=class extends Error{constructor(t){super(t);this.refusal=t;this.name="RedskilledRequestRefusedError"}};async function ls(e,r={}){let t=r.answers??await Je(e.socketPath),n=await wt(e.leasePath).catch(()=>{});return pl({socketPath:e.socketPath,answers:t,lease:n,holderAlive:n!=null&&ne(n.pid)})}async function fl(e,r={}){try{return await ST(e,r)}catch(t){if(t instanceof ur||t instanceof Ur)throw t;let n=await ls(e).catch(()=>{});throw new Ur(e.socketPath,t,n)}}async function ST(e,r){if(await ET(vT(e.socketPath),{recursive:!0,mode:448}),await Je(e.socketPath))return"already-running";await PT(e);let t=await xT(e,r);if(t!=null)return t;let n=await Sc(e.lockPath,{...r.spawnLockMaxAgeMs==null?{}:{maxAgeMs:r.spawnLockMaxAgeMs},onReap:r.onSpawnLockReaped??TT});if(!n.acquired)return await Hg(e,r,void 0,n),"joined";try{if(await Je(e.socketPath))return"already-running";let o=await AT(e,r);return await Hg(e,r,o),"spawned"}finally{await Tc(n)}}function TT(e){process.stderr.write(`redskilled: reaped the spawn lock ${JSON.stringify(e.lockPath)} (${e.reason}, ${Math.round(e.ageMs/1e3)}s old, holder ${e.holder==null?"unnamed":`pid ${e.holder.pid}`}) and went on to spawn
|
|
103
|
-
`)}async function
|
|
104
|
-
`)}import{chmod as
|
|
100
|
+
`)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function zS(e,r={}){let t=r.env??process.env,n=r.exists??BS,o=r.execPath??process.execPath,s=r.callerEntry===void 0?process.argv[1]:r.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[hg(wo(t),i),"bundle-cache"]];s&&l.push([hg(qS(VS(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 dl(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 Tg(e,r={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=r.resolveEntry??(n=>zS(n,r.env==null?{}:{env:r.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function xg(e,r,t={}){let n=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(n.exit??YS)(yg),{...e,exitCode:yg};let o=[...e.entry.args,...jr(r,t.idleMs==null?{}:{idleMs:t.idleMs})];return(n.spawnSuccessor??QS(n.env))(e.entry,o),e}function QS(e){return(r,t)=>{let n=US(r.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[_g]:"1"}});n.on("error",()=>{}),n.unref()}}function YS(e){process.exitCode=e,process.exit(e)}async function Pg(e,r=process.env,t=XS){let n=Ag(r),o=Dg(e,r);if(r[KS]==="1")return{version:o,newest:n};let s=Ie(e)===null?"0.0.0":e;try{let i=await Lc({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??n}}catch{return{version:o,newest:n}}}function Og(e,r=process.env,t){let n=t??cl;return{version:Dg(e,r,n),newest:Ag(r,n)}}function Ag(e=process.env,r=cl){return Lg(jg(e,r))}function Dg(e,r=process.env,t=cl){let n=Ie(e.trim())?.major;return n===void 0?null:Lg(jg(r,t).filter(o=>Ie(o)?.major===n))}function jg(e,r){let t=[];for(let n of r(wo(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(n)?.[1];!o||Ie(o)===null||t.push(o)}return t}function Lg(e){let r=null;for(let t of e)(r===null||ol(t,r)>0)&&(r=t);return r}function cl(e){try{return HS(e)}catch{return[]}}async function XS(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 ZS,readFile as eT,rename as rT,rm as ul,writeFile as Gg}from"node:fs/promises";import{randomUUID as tT}from"node:crypto";import{dirname as nT}from"node:path";var ss=class extends Error{constructor(r){super(`redskilled lease ${JSON.stringify(r)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function wt(e){let r;try{r=await eT(e,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}let t=oT(r);return sT(t)?t:void 0}var Ig;function Cg(){return Ig??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Ig}function Ng(e,r,t={}){let n=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??ne;async function s(){return await wt(e)}async function i(l){let d=`${e}.${l.pid}.${tT()}.tmp`;await Gg(d,$g(l),{encoding:"utf8",mode:384}),await rT(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 ZS(nT(e),{recursive:!0,mode:448});let d=!1;for(;;){let c=n(),u=a(l,c);try{return await Gg(e,$g(u),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:u}}catch(f){if(f.code!=="EEXIST")throw f}let m=await s();if(!m){await ul(e,{force:!0}),d=!0;continue}if(pl(m,l))return{acquired:!0,reaped:d,lease:m};if(await o(m.pid))return{acquired:!1,lease:m};await ul(e,{force:!0}),d=!0}},async renew(l){let d=await s();if(!d||!pl(d,l))throw new ss(e);let c={...d,renewed_at:n()};return await i(c),c},async release(l){let d=await s();if(!d)return!1;if(!pl(d,l))throw new ss(e);return await ul(e,{force:!0}),!0}}}function pl(e,r){return e.pid===r.pid&&e.start_time===r.startTime}function $g(e){return`${X(e,{keyedMapCollapse:!0})}
|
|
101
|
+
`}function oT(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return me(r)}catch{return null}}}function sT(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 jn=3e5,pT=1e4,mT=6e4,gT=15e3,Ug=3e4,fT=Ug*2,hT=6e4,is=16;function yT(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 Fg(e){let r=e?.match(/\bsession-error:\s*(.+)$/)?.[1]?.trim();return r==null||r===""?null:r}var Wr=class extends Error{constructor(t,n){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=n;this.name="RedskilledAlreadyRunningError"}},kT="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Bg(e){let{paths:r}=e,t=e.daemonVersion??"0.0.0-dev",n=e.idleMs??jn,o=e.clock??(()=>new Date().toISOString()),s=e.launch??ag,i=e.refreshTrunk??lg,a=e.countBaseMovement??dg,l=e.ceiling??xo();e.repositoryActivity!=null&&Ta(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let d=e.owner??Cg(),c=e.leaseStore??Ng(r.leasePath,{sessionKeyHash:r.sessionKeyHash,machineIdHash:r.machineIdHash,socketPath:r.socketPath},{clock:o}),u=e.machineOwner??fu(),m={machineIdHash:r.machineIdHash,sessionKeyHash:r.sessionKeyHash,socketPath:r.socketPath},f=e.machineClaimStore??Ao(r.machineClaimPath,m,{clock:o});await lT(uT(r.socketPath),{recursive:!0,mode:448});let[h,v]=await Promise.all([c.read().catch(()=>{}),f.read().catch(()=>{})]),k=Date.parse(o()),T=h==null?Number.NaN:Date.parse(h.renewed_at);h!=null&&v!=null&&h.pid===v.pid&&h.start_time===v.start_time&&h.socket_path===r.socketPath&&v.socket_path===r.socketPath&&Number.isFinite(k)&&Number.isFinite(T)&&k-T>=fT&&await Hg(r.socketPath)==="unowned"&&await c.release({pid:h.pid,startTime:h.start_time}).catch(()=>!1)&&await f.release({pid:v.pid,startTime:v.start_time,uid:v.uid}).catch(()=>!1);let F=await f.claim(u);if(!F.claimed)throw F.claim?.socket_path===r.socketPath?new Wr(r.socketPath):new ur(f.claimPath,F.reason,F.claim);let G=await c.acquire(d);if(!G.acquired)throw await f.release(u).catch(()=>{}),new Wr(r.socketPath,G.lease);let H;try{H=await bT(r.socketPath,async()=>{let[p,y]=await Promise.all([c.read().catch(()=>{}),f.read().catch(()=>{})]);return p!=null&&p.pid!==d.pid&&ne(p.pid)?!0:y!=null&&y.socket_path===r.socketPath&&y.pid!==u.pid&&ne(y.pid)})}catch(p){throw await c.release(d).catch(()=>{}),await f.release(u).catch(()=>{}),p}let ee=o(),q=e.eventLane??Zc(r.eventLanePath),he=e.registrationIntentStore??Em(r.registrationIntentPath),wr=e.liveness??Wm,Cn=e.livenessGraceMs??Fm,Nn=e.stopWorker??Jm,Mn=e.unitInventory??(()=>Hm(r.machineClaimPath,Oo({machineIdHash:r.machineIdHash}))?qm():[]),Br=e.unitMainPid??Bm,ms=e.treeSampler??Jp,vt=e.readLogTail??cg,Fn=e.sampleMs??gT,Wn=e.leaseRenewMs??Ug,St=e.registrationSustainMs??hT,Tt=e.publishedVersion??(p=>Pg(p)),Un=e.replaceCheckMs??bg,xt=e.publishedProbeTimeoutMs??pT,Bn=e.localPublishedEvidence??(p=>Og(p,e.replacementIO?.env??process.env)),Hn=e.bornByReplacement??Rg(),Pt=e.replaceBootCheckMs??mT,Ot=e.supervised??Sg(),Er=e.replacementIO??{},be=e.repositoryActivity,At=be?.intervalMs??Sa,vr=e.githubBalance,$e=e.queueDiscovery,Hr=$e?.transport??be?.transport,Dt=$e?.unconfiguredReason??kT,jt=$e?.intervalMs??Za,Lt=e.demandMs??15e3,qn=e.demandBackoffMs??3e4,C=new Map,sr=new Map,Pe=new Set,Ce=new Map,ir=new Map,qr=[],Sr=[],ar=e.deaths===void 0?void 0:[...e.deaths],_e=await he.read().catch(()=>[]),Vr=Date.parse(ee),U=new Map,oe=new Map;for(let p of _e){let y=Date.parse(p.renew_by);!Number.isFinite(Vr)||!Number.isFinite(y)||y>=Vr?U.set(p.project_label,p):Vr-y<=p.renew_within_ms&&oe.set(p.project_label,p)}let D=new Set,b={},g=null,_=null,R=null,E=!1,x=0,A=null,N="none",V=null,z=null,Qe=null,Tr=null,se=null,Gt=null,Ye=[],Xe=[],gs=new Map((e.orphanedRegistrations??[]).map(p=>[p.project_label,p])),It=null,Re={},fs=!1,Kr,$t,Ct,Nt,Mt,Ft,Vn,Wt,Jr,zr,pe=!1,hs=!1,Kn=null,Tl,ys=new Promise(p=>{Tl=p});function Qr(p){xl(p);let y=Date.parse(p),w=vu(U.values(),y);for(let S of w.lapsed){U.delete(S.project_label);let O=se?.projects.find(L=>L.project_label===S.project_label),j=[...C.values()].some(L=>L.project_label===S.project_label);(O?.outcome==="counted"&&(O.depth??0)>0||j)&&oe.set(S.project_label,S),jf(S,y)}return w.lapsed.length>0&&Yr(),w.lapsed}function Yr(){let p=new Map(oe);for(let[y,w]of U)p.set(y,w);he.replace([...p.values()]).catch(()=>{})}function jf(p,y){let w=Number.isFinite(y)?new Date(y).toISOString():p.renew_by;Ye.push({project_label:p.project_label,registered_at:p.registered_at,at:w,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`}),Ye.length>is&&Ye.splice(0,Ye.length-is)}function xl(p){if(U.size===0)return;let y=Date.parse(p);if(!Number.isFinite(y))return;let w={};for(let L of C.values())w[L.project_label]=(w[L.project_label]??0)+1;let S=se==null?Number.NaN:Date.parse(se.fetched_at),O=new Map((se?.projects??[]).map(L=>[L.project_label,L])),j=!1;for(let L of[...U.values()]){let J=Number.isFinite(S)&&y-S<=L.renew_within_ms?O.get(L.project_label):void 0,Xr=Mi(L,{now:p,...J==null?{}:{queue:{outcome:J.outcome,depth:J.depth}},liveWorkers:w[L.project_label]??0});Xr.registration!==L&&(U.set(L.project_label,Xr.registration),j=!0)}j&&Yr()}function Pl(p){if(oe.size===0)return;let y=Date.parse(p);if(!Number.isFinite(y))return;let w=new Map((se?.projects??[]).map(O=>[O.project_label,O])),S=!1;for(let[O,j]of[...oe]){if(y-Date.parse(j.renew_by)>j.renew_within_ms){oe.delete(O),S=!0;continue}let L=w.get(O),Q=Mi(j,{now:p,...L==null?{}:{queue:{outcome:L.outcome,depth:L.depth}},liveWorkers:[...C.values()].filter(J=>J.project_label===O).length});Q.verdict==="open-work"||Q.verdict==="live-worker"?(U.set(O,Q.registration),oe.delete(O),S=!0):Q.verdict==="drained"&&(oe.delete(O),S=!0)}S&&Yr()}function Jn(){let p=o();return Qr(p),Rm({now:p,daemonVersion:t,machineIdHash:r.machineIdHash,sessionKeyHash:r.sessionKeyHash,pid:d.pid,startedAt:ee,ceiling:l,scope:hu(f.claimPath,m,u),workers:[...C.values()],registrations:[...U.values()],demand:Gt,lapses:Ye,stops:Xe,orphanedRegistrations:[...gs.values()],birthLatches:iu(Re,Date.parse(p)),queue:se,published:{version:_,checkedAt:R,newer:E,replacement:N,newest:V,majorHold:z,checks:x,holdReason:A}})}function zn(){return lm({hostState:Jn(),ceiling:l,rss:b,sampledAt:g,logLines:Object.fromEntries(Ce),displays:Object.fromEntries(ir),now:o(),reattachedWorkerIds:[...Pe],repositoryActivity:Qe,githubBalance:Tr,...ar===void 0?{}:{deaths:ar},metrics:qp({observations:qr,outcomes:Sr,now:o()})})}function Lf(p,y){qr=mn([...qr,{worker_id:y,observed_at:p.published_at,tokens:p.display.tokens,tools:p.display.tools,runner:p.display.runner,model:p.display.model}],w=>w.observed_at,{now:o()})}function Gf(p){Sr=mn([...Sr,p],y=>y.ts,{now:o()})}async function ks(){return be==null||be.projects.length===0?null:(Qe=await rm({projects:be.projects,hostTokenRef:be.hostTokenRef,transport:be.transport,closedWindowMs:be.closedWindowMs,now:o()}),Qe)}async function Ol(){return vr==null?null:(Tr=await ha({transport:vr.transport,now:o()}),Tr)}function If(){if(pe||Jr!=null||vr==null)return;let p=()=>{Jr=void 0,Ol().catch(()=>{}).then(()=>{if(pe)return;let y=vr.intervalMsOverride??qo(Tr??$f(),{now:o()});Jr=setTimeout(p,y),Jr.unref()})};p()}function $f(){return Ho(o())}function Cf(){if(!(Hr!=null||$e?.armTransport==null))try{let p=$e.armTransport();if(p.transport!=null){Hr=p.transport;return}p.unconfiguredReason!=null&&(Dt=p.unconfiguredReason)}catch(p){Dt=`this host could not resolve a tracker credential: ${p instanceof Error?p.message:String(p)}`}}async function Al(){let p=o();Qr(p);let y=Date.parse(p);for(let[j,L]of[...oe])Number.isFinite(y)&&y-Date.parse(L.renew_by)>L.renew_within_ms&&oe.delete(j);let S=[...new Map([...oe,...U]).values()].map(j=>({project_label:j.project_label,selector:j.selector,...j.queue_poll==null?{}:{poll:j.queue_poll}})).sort((j,L)=>j.project_label.localeCompare(L.project_label));if(S.length===0)return null;if(Cf(),Hr==null)return se=Xm(S,p,Dt),se;se=await Zm({projects:S,transport:Hr,now:p,...$e?.batchSize==null?{}:{batchSize:$e.batchSize}});let O=o();return Pl(O),xl(O),se}async function Dl(){let p=o();if(fs)return Gt??tu(p);fs=!0;try{await _s().catch(()=>{});let y={};for(let $ of C.values())y[$.project_label]=(y[$.project_label]??0)+1;let w={};for(let $ of se?.projects??[])w[$.project_label]=$.depth;let S=Date.parse(p),O=Number.isFinite(S)?S:0;for(let[$,le]of Object.entries(Re)){if(le.probeWorkerId==null)continue;let to=C.get(le.probeWorkerId);to!=null&&O-Date.parse(to.started_at)>=6e4&&(Re[$]=ji())}let j=ru({projects:[...U.values()].map($=>({project_label:$.project_label,selector:$.selector,argv:$.argv,workspace_path:$.workspace_path,target:$.target})),queue:w,live:y,nowMs:O,backoffUntilMs:It,birthHealth:Re}),L=[],Q=new Map,J=null;for(let $ of j.births){let le,to=nl(C.keys()),Zr=U.get($.project_label),no=_u({argv:$.argv,...Zr?.env==null?{}:{env:Zr.env},...Zr?.log_path==null?{}:{log_path:Zr.log_path}},{worker_id:to,slot:$.index,workspace_path:$.workspace_path},{project_label:$.project_label});try{if(Zr?.trunk==null)le=Yn(no);else{let Ze={workspace_path:$.workspace_path,trunk:Zr.trunk},Bt=Ut(no);if(!Bt.admitted)throw new Ke(Bt.reason,Bt);let Jl=Nl(Ze),oo=Q.get(Jl);oo==null&&(oo=bs(Ze),Q.set(Jl,oo)),le=await Ml(no,Ze,oo,Bt)}}catch(Ze){J=Ze instanceof Error?Ze.message:String(Ze),Ze instanceof Ke&&Ze.admission?.verdict==="refused-unreachable-trunk-remote"||(It=(Number.isFinite(S)?S:Date.now())+qn);break}L.push({project_label:$.project_label,worker_id:le.worker.worker_id,pid:le.worker.pid,...le.fork_sha==null?{}:{fork_sha:le.fork_sha},warnings:no.log_path==null?[...le.warnings,`project ${JSON.stringify($.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(le.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:le.warnings});let vs=Re[$.project_label];vs?.haltUntilMs!=null&&O>=vs.haltUntilMs&&(Re[$.project_label]=su(vs,le.worker.worker_id))}J==null&&j.births.length>0&&(It=null);let Xr=new Set(L.map($=>$.project_label));for(let $ of j.intents){if($.queue_depth==null||$.queue_depth<=0||$.live>=$.target||Xr.has($.project_label))continue;let le=J!=null&&($.outcome==="asking"||$.outcome==="half-open-probe")?`project ${JSON.stringify($.project_label)} was birth-eligible but the host refused it: ${J}`:$.detail;await q.recordDemandRefusal({ts:p,projectLabel:$.project_label,detail:le}).catch(()=>{})}return Gt={version:1,at:p,requested:j.births.length,granted:L,shortfall:j.births.length-L.length,refusal:J,retry_after:It==null?null:new Date(It).toISOString(),projects:j.intents},Gt}finally{fs=!1}}function Nf(p){return Mr(zn(),{...B,mode:p?.mode??B.mode,project:p?.project??B.project,maxWorkers:p?.max_workers??B.maxWorkers,maxProjects:p?.max_projects??B.maxProjects,maxWidth:p?.max_width??B.maxWidth,verbose:p?.verbose??B.verbose})}function Mf(p){return bt(zn(),{mode:p?.mode??Ve.mode,project:p?.project??Ve.project,maxWidth:p?.max_width??Ve.maxWidth,maxRows:p?.max_rows??Ve.maxRows})}function xr(p,y,w){return xu({op:p,sessionProject:y??null,targetProject:w})}async function Ff(p){let y=C.get(p.worker_id),w=xr(Tu(p.command),p.session_project,y?.project_label??null);if(!w.permitted)throw new Error(w.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 S=y!=null&&await qf(y,p.detail??"stopped by its own project");return{version:1,command:p.command,worker_id:p.worker_id,applied:S,reach:w,detail:S?`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 Qn(p){C.delete(p),Pe.delete(p),Ce.delete(p),ir.delete(p)}function jl(p){let y=C.get(p.worker_id),w=xr("worker-heartbeat",p.session_project,y?.project_label??null);if(!w.permitted)throw new Error(w.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:w,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(p.worker_id)} to publish a line for`};let S=o();Ce.set(p.worker_id,{line:p.last_log_line,published_at:S,source:"heartbeat"});let O=p.display===void 0?null:ng(p.display);if(O!=null){let j=ir.get(p.worker_id)?.display,L={display:O,published_at:S};ir.set(p.worker_id,L),Lf(L,p.worker_id),(O.phase!==j?.phase||O.step!==j?.step)&&we("worker-activity",y,null,{phase:O.phase,step:O.step})}return p.mechanical_heal?.heal_kind==="mechanical-regeneration"&&we("worker-heal",y,`${p.mechanical_heal.cause}; cycle ${p.mechanical_heal.cycle}/${p.mechanical_heal.cap}; free=${p.mechanical_heal.free}`,{healKind:p.mechanical_heal.heal_kind}),{version:1,worker_id:p.worker_id,accepted:!0,reach:w,published_at:S,detail:`redskilled stored a line for Worker ${JSON.stringify(p.worker_id)} without reading it`}}async function Wf(p,y,w){let S=`exit code=${y??"null"} signal=${w??"null"}`;if(p.unit!=null&&p.unit!==""&&await Bf(p)){Hf(p,`its launch client ended (${S}) 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 O=p.log_path==null?null:Fg(await vt(p.log_path).catch(()=>null));Qn(p.worker_id),we("worker-death",p,O==null?S:`session-error: ${O}`,{exitCode:y,signal:w,refusal:O}),re()}function Uf(p,y){if(!Number.isFinite(y)||y<0){Re[p]=on;return}let w=Re[p]??on,S=ou(w,y,Date.parse(o()));Re[p]=S,S.haltUntilMs!=null&&w.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(p)} lost ${S.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(S.haltUntilMs).toISOString()}
|
|
102
|
+
`)}function Ll(p,y){let w=xr("project-reset",y,p);if(!w.permitted)throw new Error(w.reason);let S=Re[p]?.haltUntilMs!=null||Re[p]?.probeWorkerId!=null;return Re[p]=ji(),{version:1,project_label:p,latch:"project-birth-breaker",reset:S,reach:w,detail:S?`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 Bf(p){try{return await wr(p)===!0}catch{return!1}}function Hf(p,y){let w=p.unit==null?null:Br(p.unit);C.set(p.worker_id,{...p,...w!=null&&w>0?{pid:w}:{},warnings:[...p.warnings,y]}),Pe.add(p.worker_id),re()}function Gl(p,y){let w=xr("project-register",y,p.project_label);if(!w.permitted)throw new Error(w.reason);let S=o();Qr(S);let O=Ru(p,{now:S,held:U.get(p.project_label)});return U.set(O.project_label,O),Yr(),Cl(O.project_label),re(),{version:1,registration:O,reach:w,detail:`redskilled holds a registration for project ${JSON.stringify(O.project_label)} at a target of ${O.target} until ${O.renew_by}, and has read neither its selector nor its argv`}}function Il(p,y={}){let w=xr("project-renew",y.sessionProject,p);if(!w.permitted)throw new Error(w.reason);let S=o();Qr(S);let O=U.get(p);if(O==null){if(gs.has(p))throw new Ir(p,{kind:"orphaned"});let L=[...Xe].reverse().find(J=>J.project_label===p);if(L!=null)throw new Ir(p,{kind:"stopped",at:L.at});let Q=[...Ye].reverse().find(J=>J.project_label===p);throw Q!=null?new Ir(p,{kind:"lapsed",at:Q.at,...Q.registered_at==null?{}:{registered_at:Q.registered_at}}):new Ir(p)}let j=wu(O,{now:S,...y.renewWithinMs==null?{}:{renew_within_ms:y.renewWithinMs},...y.launch==null?{}:{launch:y.launch}});return U.set(j.project_label,j),Yr(),re(),{version:1,registration:j,reach:w,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 $l(p,y){let w=xr("project-deregister",y,p);if(!w.permitted)throw new Error(w.reason);let S=U.get(p)??oe.get(p),O=U.delete(p),j=oe.delete(p),L=O||j;if(S!=null){let Q=`redskilled released the registration for project ${JSON.stringify(p)}`;Cl(p),Xe.push({project_label:p,registered_at:S.registered_at,at:o(),detail:Q}),Xe.length>is&&Xe.splice(0,Xe.length-is)}return L&&Yr(),{version:1,project_label:p,released:L,reach:w,detail:L?`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 Cl(p){oe.delete(p);for(let y=Ye.length-1;y>=0;y-=1)Ye[y].project_label===p&&Ye.splice(y,1);for(let y=Xe.length-1;y>=0;y-=1)Xe[y].project_label===p&&Xe.splice(y,1);gs.delete(p)}async function qf(p,y){try{await Nn(p)}catch{}return Qn(p.worker_id),we("worker-death",p,y),re(),!0}function Ut(p){return Jc({ceiling:l,workers:[...C.values()],budget:p.budget,projectLabel:p.project_label,...p.reservation==null?{}:{reservation:p.reservation}})}function Nl(p){return`${p.workspace_path}\0${p.trunk.remote}\0${p.trunk.branch}`}function bs(p){let y=Nl(p),w=sr.get(y);if(w!=null)return w;let S=i(p).finally(()=>{sr.get(y)===S&&sr.delete(y)});return sr.set(y,S),S}function Vf(p,y,w){let S=w instanceof Error?w.message:String(w);return{...p,admitted:!1,verdict:"refused-unreachable-trunk-remote",reason:`refused-unreachable-trunk-remote: redskilled refused this Worker because trunk remote ${JSON.stringify(y.trunk.remote)} could not refresh branch ${JSON.stringify(y.trunk.branch)}: ${S}`}}async function Ml(p,y,w,S){let O=S??Ut(p);if(!O.admitted)throw new Ke(O.reason,O);let j;try{j=await(w??bs(y))}catch(Q){let J=Vf(O,y,Q);throw new Ke(J.reason,J)}let L=Ut(p);if(!L.admitted)throw new Ke(L.reason,L);return Yn(p,{admission:L,forkSha:j})}function Yn(p,y={}){let w=zc({ceiling:l,workers:[...C.values()],budget:p.budget}),S=s({spec:p,admission:y.admission??Ut(p),...y.forkSha==null?{}:{forkSha:y.forkSha},memoryCeiling:w,liveWorkerIds:C.keys(),clock:o,onExit:(Q,J,Xr)=>{let $=C.get(Q);if($==null){re();return}Wf($,J,Xr).catch(()=>{})}}),O=y.forkSha??S.fork_sha??S.worker.fork_sha,j=O==null||O===""?S.worker:{...S.worker,fork_sha:O},L={...S,worker:j,...O==null||O===""?{}:{fork_sha:O}};return C.set(j.worker_id,j),we("worker-birth",j,null,{admissionVerdict:y.admission?.verdict??S.admission.verdict}),re(),L}function we(p,y,w,S={}){if(pe)return;let O=o(),j={kind:p,worker:y,ts:O,detail:w,...S};(p==="worker-death"||p==="worker-budget-kill")&&(Gf({worker_id:y.worker_id,ts:O,outcome:p}),Fl(Po(j),{startedAt:y.started_at,...S.refusal==null?{}:{refusal:S.refusal}}),Uf(y.project_label,Date.parse(O)-Date.parse(y.started_at))),q.recordWorker(j).catch(()=>{})}function Fl(p,y={}){let w=yT(p,y);if(w==null)return;let S=[w,...(ar??[]).filter(O=>O.kind!==w.kind||O.id!==w.id||O.ts!==w.ts)].sort((O,j)=>Date.parse(O.ts)-Date.parse(j.ts));ar=mn(S,O=>O.ts,{now:o()})}async function _s(){let p=Date.parse(o()),y=[...C.values()].filter(S=>{if(Pe.has(S.worker_id))return!0;let O=Date.parse(S.started_at);return!Number.isFinite(O)||p-O>=Cn});if(y.length===0)return[];let{dead:w}=await Ya(y,wr);for(let S of w)Qn(S.worker_id),we("worker-death",S,"the host no longer confirms this Worker");return w.length>0&&re(),w}async function Wl(p,y){let w=C.get(p);if(!w)return!1;try{await Nn(w)}catch{}return Qn(p),we("worker-budget-kill",w,y),re(),!0}async function Ul(){let p=[...C.values()];if(p.length===0)return[];let y;try{y=await ms(p)}catch{return[]}let w=y.rss;b=w,g=o(),Kf(y.cpu_seconds,g);let{terminations:S}=Kp({workers:p,rss:w}),O=[];for(let j of S)await Wl(j.worker_id,j.reason)&&O.push(j);return O}function Kf(p,y){for(let[w,S]of Object.entries(p)){if(typeof S!="number"||!Number.isFinite(S))continue;let O=C.get(w);O&&C.set(w,{...O,cpu:{cpu_seconds:S,sampled_at:y}})}}async function Jf(){try{return xt<=0?await Tt(t):await new Promise(p=>{let y=setTimeout(()=>p(Rs()),xt);y.unref(),Tt(t).then(w=>{clearTimeout(y),p(w)},()=>{clearTimeout(y),p(Rs())})})}catch{return Rs()}}function Rs(){try{return Bn(t)}catch{return null}}async function Bl(){if(Dn(t))return x+=1,R=o(),A="local-build",{act:"hold",reason:"local-build"};let p=wg(await Jf()),y=p.version;_=y,V=p.newest??null,R=o(),z=Eg({running:t,newest:V,supervised:Ot});let w=vg({running:t,published:y,supervised:Ot});return E=w.act==="replace",x+=1,A=w.act==="hold"?w.reason:null,N!=="in-progress"&&(N=w.act==="replace"?"pending":"none"),w}async function Xn(){let p=await Bl();if(p.act!=="replace"||N==="in-progress")return p;let y=Tg(p,Er);return N="in-progress",await q.flush().catch(()=>{}),await he.flush().catch(()=>{}),await eo({reason:"replaced"}),xg(y,r,{...n==null?{}:{idleMs:n},io:Er}),p}function zf(){pe||Ft!=null||Un<=0||(!Hn&&Pt>0&&(Vn=setTimeout(()=>{Xn().catch(()=>{})},Pt),Vn.unref()),Ft=setInterval(()=>{Xn().catch(()=>{})},Un),Ft.unref())}async function Hl(){return await c.renew(d).catch(()=>null)}function Qf(){pe||Ct!=null||Wn<=0||(Ct=setInterval(()=>{Hl()},Wn),Ct.unref())}function Yf(){pe||Nt!=null||St<=0||(Nt=setInterval(()=>{Qr(o())},St),Nt.unref())}function Xf(){pe||$t!=null||Fn<=0||($t=setInterval(()=>{Ul().catch(()=>{})},Fn),$t.unref())}function Zf(){pe||Wt!=null||be==null||be.projects.length===0||At<=0||(ks().catch(()=>{}),Wt=setInterval(()=>{ks().catch(()=>{})},At),Wt.unref())}function eh(){if(pe||zr!=null||jt<=0)return;let p=y=>{zr=setTimeout(()=>{zr=void 0,ql().then(()=>Al()).catch(()=>{}).finally(()=>{if(pe)return;let w=Date.parse(o());p(tg(se,jt,Number.isFinite(w)?w:Date.now()))})},y),zr.unref()};p(jt)}async function ql(){await Promise.allSettled([...U.values()].filter(p=>p.trunk!=null).map(async p=>{let y=await bs({workspace_path:p.workspace_path,trunk:p.trunk}),w=[...C.values()].filter(S=>S.project_label===p.project_label&&S.fork_sha!=null&&S.fork_sha!=="");await Promise.allSettled(w.map(async S=>{let O=await a({workspace_path:p.workspace_path,fork_sha:S.fork_sha,head_sha:y}),j=C.get(S.worker_id);if(j==null||j.fork_sha!==S.fork_sha)return;let L={...j,base_head_sha:y,base_commits_ahead:O};C.set(S.worker_id,L),(j.base_head_sha!==y||j.base_commits_ahead!==O)&&we("worker-drift",L,null,{baseHeadSha:y,baseCommitsAhead:O})}))}))}function rh(){pe||Mt!=null||Lt<=0||(Mt=setInterval(()=>{Dl().catch(()=>{})},Lt),Mt.unref())}function re(){pe||(Kr&&clearTimeout(Kr),Kr=setTimeout(()=>{_s().catch(()=>{}).then(()=>Vl())},n),Kr.unref())}function Vl(){return C.size>0?(re(),"held-by-workers"):(Qr(o()),U.size>0?(re(),"held-by-registrations"):(th(),"exited"))}async function th(){if(!Dn(t)){if((await Xn().catch(()=>null))?.act==="replace"||hs||pe)return;if(C.size>0||U.size>0){re();return}}await eo({reason:"idle"})}function Zn(p){return lu({reason:p,socketPath:r.socketPath,daemonVersion:t,pid:d.pid,workers:[...C.values()],projects:[...U.keys()]})}function Kl(p){if(Kn!=null)return Kn;let y=p.reason??"requested",w=p.note?.trim();return Kn=q.recordDaemonStop({ts:o(),pid:d.pid,socketPath:r.socketPath,reason:y,detail:w==null||w===""?Zn(y).detail:`${Zn(y).detail} \u2014 ${w}`,...p.signal==null?{}:{signal:p.signal}}).catch(()=>{}),Kn}async function eo(p={}){if(hs)return await ys;hs=!0,await Kl(p),pe=!0,Kr&&clearTimeout(Kr),$t&&clearInterval($t),Ct&&clearInterval(Ct),Nt&&clearInterval(Nt),Ft&&clearInterval(Ft),Vn&&clearTimeout(Vn),Wt&&clearInterval(Wt),Jr&&clearTimeout(Jr),zr&&clearTimeout(zr),Mt&&clearInterval(Mt),await q.flush().catch(()=>{}),await he.flush().catch(()=>{}),await c.release(d),await f.release(u),H.close();for(let y of D)y.destroy();return await new Promise(y=>H.once("close",()=>y())),await Wg(r.socketPath,{force:!0}),Tl(),await ys}let ws=await q.read().catch(()=>[]),ro=new Map;for(let p of ws){if(p.event==="worker-birth"){ro.set(p.worker_id,p.ts);continue}let y=Fg(p.detail);Fl(p,{...ro.get(p.worker_id)==null?{}:{startedAt:ro.get(p.worker_id)},...y==null?{}:{refusal:y}}),(p.event==="worker-death"||p.event==="worker-budget-kill")&&ro.delete(p.worker_id)}Sr=mn(ws.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 nh=eu(ws),Es=await Ya(nh,wr);for(let p of Es.alive){let y=Km(p),w=y.unit==null||ne(y.pid)?null:Br(y.unit);C.set(y.worker_id,w!=null&&w>0?{...y,pid:w}:y),Pe.add(y.worker_id)}for(let p of Es.dead)we("worker-death",p,"the Worker ended while no daemon was watching");let oh=Vm({units:await Promise.resolve(Mn()).catch(()=>[]),held:[...C.values()],mainPid:Br,now:ee});for(let p of oh)C.set(p.worker_id,p),Pe.add(p.worker_id),we("worker-birth",p,"adopted from an active unit with no birth on this lane");Pl(o());for(let p of Es.alive){if(p.log_path==null||Ce.has(p.worker_id))continue;let y=await vt(p.log_path).catch(()=>null);y==null||y.trim()===""||Ce.set(p.worker_id,{line:y,published_at:o(),source:"rehydrated"})}H.on("connection",p=>{D.add(p),p.once("close",()=>D.delete(p)),re(),_T(p,async(y,w)=>{re();let S=await sh(y);w(S),y.op==="shutdown"&&setImmediate(()=>void eo({reason:"requested"}).catch(()=>{}))})});async function sh(p){try{if(p.op==="ping")return{id:p.id,ok:!0,value:{pong:!0,protocol_version:Zo,daemon_version:t,pid:d.pid}};if(p.op==="host-state")return{id:p.id,ok:!0,value:Jn()};if(p.op==="statusline-payload")return{id:p.id,ok:!0,value:am(zn(),p.extras)};if(p.op==="statusline-string")return{id:p.id,ok:!0,value:Nf(p.render)};if(p.op==="statusline-dashboard")return{id:p.id,ok:!0,value:Mf(p.dashboard)};if(p.op==="worker-heartbeat")return{id:p.id,ok:!0,value:jl(p.heartbeat)};if(p.op==="project-register"){let w=Gl(p.registration,p.session_project);return await he.flush(),{id:p.id,ok:!0,value:w}}if(p.op==="project-renew"){let w=Il(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 he.flush(),{id:p.id,ok:!0,value:w}}if(p.op==="project-deregister"){let w=$l(p.project_label,p.session_project);return await he.flush(),{id:p.id,ok:!0,value:w}}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 Ff(p.command)};if(p.op==="worker-start"){let w=xr("worker-start",p.session_project,p.spec.project_label);if(!w.permitted)return{id:p.id,ok:!1,error:w.reason};let S=p.spec.trunk==null?Yn(p.spec):await Ml(p.spec,{workspace_path:p.spec.workspace_path,trunk:p.spec.trunk});return await q.flush().catch(()=>{}),{id:p.id,ok:!0,value:{worker:S.worker,admission:S.admission,fork_sha:S.fork_sha,warnings:S.warnings}}}if(p.op==="shutdown"){let w=Zn("requested");return await Kl({reason:"requested",...p.detail==null?{}:{note:p.detail}}),{id:p.id,ok:!0,value:w}}let y=p;return{id:y.id??as(),ok:!1,error:`unsupported redskilled op: ${y.op??"unknown"}`}}catch(y){return{id:p.id??as(),ok:!1,error:y instanceof Error?y.message:String(y)}}}return re(),Xf(),Qf(),Yf(),zf(),Zf(),If(),eh(),rh(),{socketPath:r.socketPath,lease:G.lease,startedAt:ee,closed:ys,startWorker:Yn,admit:Ut,ceiling:()=>l,killWorkerOverBudget:Wl,sampleMemoryBudgets:Ul,renewLease:Hl,pollRepositoryActivity:ks,pollGithubBalance:Ol,githubBalance:()=>Tr,pollQueueDiscovery:Al,queueDiscovery:()=>se,driveDemand:Dl,demand:()=>Gt,sweepWorkerLiveness:_s,publishWorkerHeartbeat:jl,reattached:()=>[...Pe].map(p=>C.get(p)).filter(p=>p!=null),flushEvents:()=>q.flush(),trackWorker(p){C.set(p.worker_id,p),we("worker-birth",p,null),re()},releaseWorker(p){let y=C.get(p),w=C.delete(p);return Pe.delete(p),Ce.delete(p),ir.delete(p),y&&we("worker-death",y,"released by the daemon"),re(),w},workerCount:()=>C.size,registerProject:Gl,renewProject:Il,resetProjectBirthBreaker:Ll,deregisterProject:$l,registrations:()=>Jn().registrations??[],hostState:Jn,refreshRegisteredTrunks:ql,statuslinePayload:zn,evaluateIdle:Vl,observePublishedVersion:Bl,checkForReplacement:Xn,stopReport:Zn,stop:eo}}async function Hg(e,r=250){return await new Promise(t=>{let n=dT(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 bT(e,r){for(let t=0;t<2;t++){let n=cT();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 Hg(e)!=="unowned")throw new Wr(e);if(await r?.())throw new Wr(e);await Wg(e,{force:!0})}}throw new Wr(e)}async function Je(e,r=250){try{return(await bo({socketPath:e,timeoutMs:r},{id:as(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function _T(e,r){vc(e,(t,n)=>r(t,n),(t,n,o)=>{o({id:n?.id??as(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function ml(e){let r=e.socketPath,t=RT(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 ${qg(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 \`${_r("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 \`${_r("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function gl(e){return`${e.reason} ${e.repair}`}function RT(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:wT(r.acquired_at,e.now??new Date().toISOString())}}function wT(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 qg(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`}rr();var Jg=1e4,Ur=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"?`. ${gl(o)}`:""}`);this.socketPath=t;this.cause=n;this.presence=o;this.name="RedskilledUnreachableError"}},fl=class extends Ur{constructor(t,n,o){super(t,o,n);this.presence=n;this.name="RedskilledDaemonHeldError"}},ls=class extends Error{constructor(t){super(t);this.refusal=t;this.name="RedskilledRequestRefusedError"}};async function ds(e,r={}){let t=r.answers??await Je(e.socketPath),n=await wt(e.leasePath).catch(()=>{});return ml({socketPath:e.socketPath,answers:t,lease:n,holderAlive:n!=null&&ne(n.pid)})}async function hl(e,r={}){try{return await TT(e,r)}catch(t){if(t instanceof ur||t instanceof Ur)throw t;let n=await ds(e).catch(()=>{});throw new Ur(e.socketPath,t,n)}}async function TT(e,r){if(await vT(ST(e.socketPath),{recursive:!0,mode:448}),await Je(e.socketPath))return"already-running";await OT(e);let t=await PT(e,r);if(t!=null)return t;let n=await Tc(e.lockPath,{...r.spawnLockMaxAgeMs==null?{}:{maxAgeMs:r.spawnLockMaxAgeMs},onReap:r.onSpawnLockReaped??xT});if(!n.acquired)return await Vg(e,r,void 0,n),"joined";try{if(await Je(e.socketPath))return"already-running";let o=await DT(e,r);return await Vg(e,r,o),"spawned"}finally{await xc(n)}}function xT(e){process.stderr.write(`redskilled: reaped the spawn lock ${JSON.stringify(e.lockPath)} (${e.reason}, ${Math.round(e.ageMs/1e3)}s old, holder ${e.holder==null?"unnamed":`pid ${e.holder.pid}`}) and went on to spawn
|
|
103
|
+
`)}async function PT(e,r){let t=await ds(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let n=r.readyTimeoutMs??Jg,o=Date.now()+n;for(;;){if(await Je(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(i=>setTimeout(i,25))}let s=await ds(e).catch(()=>{});if(s==null||s.kind!=="held-unresponsive")return null;throw new fl(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 OT(e){let t=await Ao(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&ne(t.pid))throw new ur(e.machineClaimPath,"held",t)}async function zg(e,r,t={}){await hl(e,t);let n;try{n=await xn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...r,id:Kg()})}catch(o){throw new Ur(e.socketPath,o,await ds(e).catch(()=>{}))}if(!n.ok)throw new ls(n.error);return n.value}async function Qg(e,r={},t={}){if(!await Je(e.socketPath))return du(e.socketPath);let n;try{n=await xn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Kg(),op:"shutdown",...r.detail==null?{}:{detail:r.detail}})}catch(i){throw new Ur(e.socketPath,i)}if(!n.ok)throw new ls(n.error);if(!Li(n.value))throw new Error("redskilled daemon returned a malformed stop report");let o=n.value,s=await AT(e,o.pid,r.settleTimeoutMs??5e3);return s.complete?o:{...o,stopped:!1,detail:`${o.detail}; the daemon accepted the stop but did not finish its bounded drain by ${s.deadline}: ${s.pending.join(", ")}`}}async function AT(e,r,t){let n=Date.now()+t;for(;;){let o=[];if(await Je(e.socketPath)&&o.push(`the socket ${JSON.stringify(e.socketPath)} still answers`),await wt(e.leasePath).catch(()=>{})&&o.push("the session lease is still held"),r!=null&&r!==process.pid&&ne(r)&&o.push(`daemon pid ${r} is still alive`),o.length===0)return{complete:!0,deadline:new Date(n).toISOString(),pending:o};if(Date.now()>=n)return{complete:!1,deadline:new Date(n).toISOString(),pending:o};await new Promise(s=>setTimeout(s,25))}}async function Yg(e,r={}){let t=await zg(e,{op:"host-state"},r);if(!wm(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Xg(e,r={},t){let n=await zg(e,{op:"statusline-payload",...r.sessionProject!=null?{session_project:r.sessionProject}:{},...t==null?{}:{extras:t}},r);if(!xa(n))throw new Error("redskilled daemon returned a malformed statusline payload");return n}async function Zg(e,r=B,t={}){let n=await Xg(e,t,{vitals:!0,logs:r.verbose,display:!0});return Mr(n,r)}async function ef(e,r={},t={}){let n=await Xg(e,t,{vitals:!0,logs:!0,display:!0});return bt(n,{...Ve,...r})}async function Vg(e,r,t,n){let o=Date.now()+(r.readyTimeoutMs??Jg);for(;;){if(await Je(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 ${Pc(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 DT(e,r){let t=r.serverCommand??(r.serverArgs!=null?process.execPath:void 0),n=await Nc({...t!=null?{serverCommand:t}:{},serverArgs:r.serverArgs},r.entryLookup??{}),o={entry:n},s=[...n.args,...jr(e,r.idleMs==null?{}:{idleMs:r.idleMs})],i=ET(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}rr();import{readFile as jT}from"node:fs/promises";import{homedir as LT,totalmem as GT}from"node:os";import{join as IT}from"node:path";var $T="REDSKILLED_IDLE_MS",CT=".red/config.yaml";async function tf(e=LT()){let r=IT(e,CT),t;try{t=await jT(r,"utf8")}catch(n){return n.code==="ENOENT"?{}:(yl(`redskilled: cannot read host config ${JSON.stringify(r)}; using environment and defaults instead: ${rf(n)}`),{})}try{let n=MT(t);return{...cs(n,"plugins.dev.redskilled.worker_ceiling","workerCeiling"),...cs(n,"plugins.dev.redskilled.memory_ceiling","memoryCeiling"),...cs(n,"plugins.dev.redskilled.validation_ceiling","validationCeiling"),...cs(n,"plugins.dev.redskilled.idle_ms","idleMs")}}catch(n){return yl(`redskilled: malformed host config ${JSON.stringify(r)}; using environment and defaults instead: ${rf(n)}`),{}}}function nf(e={}){let r=e.env??process.env,t=e.config??{},n=xo(r,e.totalMemoryBytes??GT(),{flags:e.flags,config:t,...e.availableParallelism==null?{}:{availableParallelism:e.availableParallelism}}),o=NT(e.flags?.idleMs==null?void 0:String(e.flags.idleMs),r[$T],t.idleMs);if(o==null)return{ceiling:n,idleMs:jn,idleMsSource:"derived-default"};let s=Number(o.value);return Number.isSafeInteger(s)&&s>0?{ceiling:n,idleMs:s,idleMsSource:o.source}:(yl(`redskilled: ${UT(o.source)} idle_ms=${JSON.stringify(o.value)} is not a positive integer; using the default ${jn}ms instead.`),{ceiling:n,idleMs:jn,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 cs(e,r,t){let n=e[r];return n===void 0?{}:{[t]:n}}function MT(e){let r={},t=[];for(let[n,o]of e.split(/\r?\n/).entries()){let s=FT(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(".")]=WT(c.trim())}return r}function FT(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 WT(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function UT(e){return e==="flag"?"serve flag":e==="environment"?"environment":e==="home-config"?"home config":"derived default"}function rf(e){return e instanceof Error?e.message:String(e)}function yl(e){process.stderr.write(`${e}
|
|
104
|
+
`)}import{chmod as uf,mkdir as mf,readFile as gf,stat as ZT,writeFile as ff}from"node:fs/promises";import{homedir as _l}from"node:os";import{dirname as hf,join as us}from"node:path";import{join as BT}from"node:path";var of=["local","tmp","host"],HT="local",Ln="plugins.dev.workspace.target";var kl=class extends Error{constructor(r){super(r),this.name="WorkspaceConfigError"}};function af(e){let r=lt(e,Ln),t=KT(r??"").trim();return t===""?void 0:t}function lf(e){let r=(e??"").trim();if(r==="")return{kind:"preset",preset:HT};let t=of.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 kl(`${Ln}: unknown workspace target ${JSON.stringify(r)}. Use one of the presets (${of.join(", ")}) or an absolute parent directory for Workers.`)}function df(e,r){return e.kind==="preset"?e.preset==="host":VT(qT(e.parentDir,r),Ue(r))}function qT(e,r){return e==="~"?sf(r):e.startsWith("~/")?BT(r,e.slice(2)):sf(e)}function VT(e,r){return e===r?!0:r==="/"?e.startsWith("/"):e.startsWith(`${r}/`)}function sf(e){let r=e.trim();return r.length>1?r.replace(/\/+$/,""):r}function KT(e){let r=e.trim(),t=/^(["'])(.*)\1$/.exec(r);return t?t[2]:r}rr();import{createHash as JT}from"node:crypto";import{hostname as zT}from"node:os";import{join as Gn}from"node:path";var Et="redskilled.sock",QT="REDSKILLED_SESSION";function YT(e={}){let r=e.env??process.env,t=r[QT]?.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 XT(e={}){return cf(e.host??zT())}function ze(e={}){let r=YT(e),t=e.runtimeDir??_o({key:`redskilled:${r}`,socketFileName:Et,env:e.env,uid:e.uid}),n=XT(e),o=e.homeDir??e.env?.HOME??(e.runtimeDir==null?process.env.HOME:e.runtimeDir)??t;return{sessionKey:r,sessionKeyHash:cf(r),machineIdHash:n,runtimeDir:t,socketPath:Gn(t,Et),lockPath:Gn(t,"redskilled.spawn.lock"),leasePath:Gn(t,"redskilled.lease.toon"),eventLanePath:Gn(Ue(o),Xc),registrationIntentPath:Gn(t,"redskilled.registrations.toon"),machineClaimPath:e.machineClaimPath??Oo({env:e.env,machineIdHash:n,platform:e.platform})}}function cf(e){return JT("sha256").update(e).digest("hex").slice(0,12)}var bl=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${_r("red-skills-redskilled",["provision"])}\` directly`,ex=`# Host-scoped redskilled policy. This file is never read from a repository.
|
|
105
105
|
plugins:
|
|
106
106
|
dev:
|
|
107
107
|
redskilled:
|
|
@@ -109,8 +109,8 @@ plugins:
|
|
|
109
109
|
# memory_ceiling: 8G
|
|
110
110
|
# validation_ceiling: 2
|
|
111
111
|
# idle_ms: 300000
|
|
112
|
-
`;async function
|
|
113
|
-
`)}async function
|
|
112
|
+
`;async function yf(e=_l()){let r=Ue(e),t=us(hf(r),"config.yaml"),n=await wl(r),o=!1,s=!1;n===void 0?(await mf(r,{recursive:!0,mode:er}),await uf(r,er),o=!0):n!==er&&(await uf(r,er),s=!0);let i=!1;try{await ff(t,ex,{encoding:"utf8",flag:"wx",mode:384}),i=!0}catch(a){if(a.code!=="EEXIST")throw a}return{path:r,created:o,tightened:s,mode:er,configPath:t,configCreated:i}}var kf={needed:!1,declaredBy:`no ${Ln} in view`};async function Rl(e={}){let r=e.homeDir??_l(),t=e.declaredTarget?.trim();if(t)return pf(t,r,"stated on the command line");let n=e.projectRoot?.trim();if(!n)return kf;let o=us(n,".red","config.yaml"),s=await gf(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=af(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:pf(i,r,o)}function pf(e,r,t){let n=`${Ln}: ${e} (${t})`;try{return{needed:df(lf(e),r),declaredBy:n}}catch{return{needed:!1,declaredBy:`${n} \u2014 off-contract, so it names no lane under the home`}}}function bf(e){let r=[rx(e),tx(e),nx(e),ox(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 rx(e){let r=e.homeNeed??kf;if(!e.homePresent)return r.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${r.declaredBy}`,fix:bl}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${r.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??er;return t!==er?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${er.toString(8)}`,fix:`${bl} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function tx(e){return He(e.entry)?{check:"daemon-entry",verdict:"ok",evidence:`${e.entry.entry??e.entry.command} (resolved as ${e.entry.source})`,fix:""}:{check:"daemon-entry",verdict:"missing",evidence:`no published redskilled bundle; probed ${e.entry.searched.join(", ")||"nothing"}`,fix:`install or warm the RedSkills bundle for this host, then re-run \`${_r("red-skills-redskilled",["provision"])}\``}}function nx(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:`${bl} \u2014 it starts the daemon and waits for the socket`}}function ox(e){return{check:"supervisor-unit",verdict:"ok",evidence:e.supervisorUnit==="installed"?"redskilled.service is installed (optional supervision, Restart=always)":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 _f(e={}){let r=e.env??process.env,t=e.homeDir??_l(),n=e.paths??ze({env:r}),o=Ue(t),[s,i,a]=await Promise.all([wl(o),Je(n.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Rl({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:a,entry:cr(e.entryOverride??{},{env:r,...e.entryLookup}),socketPath:n.socketPath,reachable:i,supervisorUnit:await ix(ax(e,r,t),r)}}var sx="redskilled.service";function Rf(e){return us(e,"systemd","user",sx)}function wf(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=always","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
|
|
113
|
+
`)}async function Ef(e){let r=Rf(e.configHome);return await wl(r)!==void 0?{path:r,status:"already-present"}:(await mf(hf(r),{recursive:!0}),await ff(r,e.unit,"utf8"),{path:r,status:"installed"})}async function ix(e,r){if(process.platform!=="linux")return"unsupported";try{return await gf(Rf(e),"utf8"),"installed"}catch{return r.XDG_RUNTIME_DIR?"absent":"unsupported"}}function ax(e,r,t){return e.configHome??r.XDG_CONFIG_HOME?.trim()??us(t,".config")}async function wl(e){try{return(await ZT(e)).mode&511}catch{return}}import{readdir as Sf,rm as lx,stat as dx}from"node:fs/promises";import{dirname as cx,join as El}from"node:path";var ux=5*6e4,px="redskilled.";function mx(e={}){let r=e.env??process.env,t=i=>cx(_o({key:"redskilled:reclaim-probe",socketFileName:Et,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 Tf(e={}){let r=e.roots??mx(e),t=e.graceMs??ux,n=e.now??Date.now,o=e.isPidAlive??ne,s=e.answers??yx,i=e.dryRun===!0,a=[];for(let l of r){let d;try{d=(await Sf(l,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name)}catch{continue}for(let c of d.sort())a.push(await gx(El(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 gx(e,r){let t;try{t=(await Sf(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:xf(i),removed:[]}}let n=t.filter(i=>i.startsWith(px));if(t.length>0&&n.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await fx(El(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 vf(e,t,`lease pid ${o.pid} is dead`,r);if(t.includes(Et)&&await r.answers(El(e,Et)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await hx(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 vf(e,t,t.length===0?"empty and stale":"no lease and stale",r)}async function vf(e,r,t,n){if(n.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:r};try{await lx(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:xf(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:r}}async function fx(e){try{return await wt(e)}catch{return}}async function hx(e,r){try{return Math.max(0,r()-(await dx(e)).mtimeMs)}catch{return}}async function yx(e){try{return(await xn({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function xf(e){return e instanceof Error?e.message:String(e)}var kx="plugins.dev.statusline",bx="dev.statusline";function _x(e){let r=[],t=a=>{for(let l of[kx,bx]){let d=`${l}.${a}`,c=lt(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 Rx={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 vl(e){let{values:r,positionals:t}=dr(e,Rx),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 Sl(e={}){let r=e.configText==null?{config:{},warnings:[]}:_x(e.configText),t=e.flags??{};return{options:{...B,mode:t.mode??r.config.mode??B.mode,project:t.project!==void 0?t.project:e.project??B.project,maxWorkers:t.maxWorkers??r.config.maxWorkers??B.maxWorkers,maxProjects:t.maxProjects??r.config.maxProjects??B.maxProjects,maxWidth:t.maxWidth??r.config.maxWidth??B.maxWidth,verbose:t.verbose??r.config.verbose??B.verbose},warnings:r.warnings}}var Ex=`Usage: redskilled <command> [options]
|
|
114
114
|
|
|
115
115
|
Commands:
|
|
116
116
|
host-state (default) print the host's state as JSON
|
|
@@ -124,7 +124,7 @@ Commands:
|
|
|
124
124
|
|
|
125
125
|
Run \`redskilled <command> --help\` for a command's own usage.
|
|
126
126
|
\`--version\` (\`-v\`) prints the build stamp; both answer offline.
|
|
127
|
-
`,
|
|
127
|
+
`,vx={serve:`Usage: redskilled serve [options]
|
|
128
128
|
|
|
129
129
|
Runs the daemon in this process. Every path is a flag and none is derived
|
|
130
130
|
(ADR 0130 rule 3); what is absent falls back to the session derivation.
|
|
@@ -209,28 +209,28 @@ Reports every session runtime dir it looked at and why it kept or removed it.
|
|
|
209
209
|
|
|
210
210
|
--dry-run the same report with nothing removed
|
|
211
211
|
--grace-ms <n> how long a dir must be idle before it is reclaimed
|
|
212
|
-
`};function
|
|
213
|
-
`:`${
|
|
214
|
-
`),0}if(
|
|
215
|
-
`);let m=
|
|
216
|
-
`),0}var
|
|
217
|
-
`),0}function
|
|
218
|
-
`),o.running&&!o.stopped?1:0}async function
|
|
219
|
-
`),0;if(o==="install"){let s=await ug(
|
|
220
|
-
`),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await
|
|
221
|
-
`),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function
|
|
222
|
-
`);let a;try{a=await
|
|
212
|
+
`};function Sx(e){return e==="--help"||e==="-h"||e==="help"}var Tx={socket:{kind:"value",coerce:e=>e},lease:{kind:"value",coerce:e=>e},events:{kind:"value",coerce:e=>e},"session-key-hash":{kind:"value",coerce:e=>e},"machine-id-hash":{kind:"value",coerce:e=>e},"machine-claim":{kind:"value",coerce:e=>e},"worker-ceiling":{kind:"value",coerce:e=>e},"memory-ceiling":{kind:"value",coerce:e=>e},"idle-ms":{kind:"value",coerce:e=>Number(e)},"daemon-version":{kind:"value",coerce:e=>e},"queue-endpoint":{kind:"value",coerce:e=>e},"queue-ms":{kind:"value",coerce:e=>Number(e)},"demand-ms":{kind:"value",coerce:e=>Number(e)}},Of="REDSKILLED_HOST_TOKEN";function $n(){try{let r=wx("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return r===""?null:r}catch{return null}}function Af(e=process.env,r=$n){let t=(e[Of]??e.GITHUB_TOKEN??e.GH_TOKEN??"").trim();if(t!=="")return{token:t,source:"env"};let n=(r()??"").trim();return n!==""?{token:n,source:"tracker-cli"}:null}function xx(e,r=process.env,t=$n,n){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...Pf(e,r,t,n),armTransport:()=>Pf(e,r,t,n)}}function Px(e,r=process.env,t=$n){let n=Af(r,t);if(n==null)return null;let o=r.GITHUB_API_URL;return{transport:Ra({token:n.token,...o?{origin:o}:{}})}}function Pf(e,r=process.env,t=$n,n){let o=Af(r,t);if(o==null)return{unconfiguredReason:`no credential names a tracker for this host: ${Of}, GITHUB_TOKEN and GH_TOKEN are all unset in the daemon's environment and \`gh auth token\` returned nothing \u2014 so no queue depth is asked for, and no depth is invented either`};let s=e["queue-endpoint"]??r.GITHUB_GRAPHQL_URL;return{transport:om({token:o.token,...s?{endpoint:s}:{},...n?{attribution:n}:{}})}}async function Ox(e){if(e[0]==="--version"||e[0]==="-v"){let o=Vs("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
|
|
213
|
+
`:`${Ld(o)}
|
|
214
|
+
`),0}if(Sx(e[0]))return process.stdout.write(Ex),0;let{command:r,args:t}=Cd(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(vx[r]),0;if(r==="serve"){let{values:o}=dr(t,Tx),s=await tf(In()),i=nf({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=ps(Ue(In()),"state"),l=Lo({path:ps(a,"github","spend.toonl")}),d=xx(o,process.env,$n,l),c=Px(o),u=nc({stateRoot:a});process.stderr.write(`${oc(u)}
|
|
215
|
+
`);let m=Xd({lanePath:Qt(a),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),f=await Bg({paths:Ux(o),idleMs:i.idleMs,ceiling:i.ceiling,daemonVersion:o["daemon-version"]??Vs("redskilled").version,deaths:u.attributions,queueDiscovery:d,...c==null?{}:{githubBalance:c},...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let h of["SIGTERM","SIGINT"])process.once(h,()=>void f.stop({reason:"signal",signal:h}).catch(()=>{}));return await f.closed,m.phase("closed"),0}if(r==="stop")return await Gx(t);if(r==="statusline")return await $x(t);if(r==="dashboard")return await Hx(t);if(r==="github-spend")return await Dx(t);if(r==="unit")return await Ix(t);if(r==="provision")return await Nx(t);if(r==="reclaim")return await Fx(t);let n=await Yg(ze());return process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
216
|
+
`),0}var Ax={pool:{kind:"value",coerce:e=>e},hours:{kind:"value",coerce:e=>Number(e)}};async function Dx(e,r={}){let{values:t}=dr(e,Ax,{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:jx(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??Lo({path:ps(Ue(r.homeDir??In()),"state","github","spend.toonl")})).report({from:l,to:i,...s===void 0?{}:{pool:s}});return(r.write??(u=>process.stdout.write(u)))(`${X({version:c.version,origin:c.origin,window:{from:c.window.from,to:c.window.to},pool:c.pool,total_count:c.total_count,total_cost:c.total_cost,operations:c.operations.map(u=>({operation_key:u.operation_key,pool:u.pool,...u.actor===void 0?{}:{actor:u.actor},count:u.count,cost:u.cost})),unreadable_records:c.unreadable_records})}
|
|
217
|
+
`),0}function jx(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 Lx={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function Gx(e,r={}){let t=r.write??(s=>process.stdout.write(s)),{values:n}=dr(e,Lx),o=await Qg(r.paths??ze(),{...n.reason==null?{}:{detail:n.reason},...Number.isFinite(n["settle-timeout-ms"])?{settleTimeoutMs:n["settle-timeout-ms"]}:{}},r.client??{});return t(`${X({running:o.running,stopped:o.stopped,reason:o.reason,socket:o.socket_path,daemon_version:o.daemon_version,pid:o.pid,holding:{workers:o.holding.workers.length,projects:[...o.holding.projects]},surviving:[...o.surviving],workers:o.holding.workers.map(s=>({worker_id:s.worker_id,project_label:s.project_label,pid:s.pid,unit:s.unit,isolated:s.isolated,survives:s.survives})),detail:o.detail})}
|
|
218
|
+
`),o.running&&!o.stopped?1:0}async function Ix(e,r={}){let t=r.write??(s=>process.stdout.write(s)),n=r.paths??ze(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(fg(r.unitIO??{}),null,2)}
|
|
219
|
+
`),0;if(o==="install"){let s=await mg(ug(n),r.unitIO??{});return t(`${JSON.stringify(s,null,2)}
|
|
220
|
+
`),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await gg(r.unitIO??{}),null,2)}
|
|
221
|
+
`),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function $x(e,r={}){let t=r.write??(l=>process.stdout.write(l)),n=r.warn??(l=>process.stderr.write(l)),o=vl(e),s=Df(r.cwd??process.cwd()),i=Sl({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let l of[...i.warnings,...o.warnings])n(`redskilled statusline: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
|
|
222
|
+
`);let a;try{a=await Zg(r.paths??ze(),i.options,{...r.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(l){n(`redskilled statusline: ${l instanceof Error?l.message:String(l)}
|
|
223
223
|
`),a=qa({options:i.options,generated_at:(r.now??(()=>new Date().toISOString()))()})}return t(`${a.lines.join(`
|
|
224
224
|
`)}
|
|
225
|
-
`),0}var
|
|
226
|
-
`),u.verdict==="ok"?0:1}var
|
|
227
|
-
`),o.entries.some(s=>s.verdict==="failed")?1:0}function
|
|
228
|
-
`),process.exitCode=1})}async function
|
|
229
|
-
`);try{let a=await
|
|
225
|
+
`),0}var Cx={"no-start":{kind:"boolean"},"install-unit":{kind:"boolean"},check:{kind:"boolean"},project:{kind:"value",coerce:e=>e},workspace:{kind:"value",coerce:e=>e}};async function Nx(e,r={}){let t=r.write??(m=>process.stdout.write(m)),{values:n}=dr(e,Cx),o=r.paths??ze(),s=r.homeDir??In(),i=await Rl({homeDir:s,declaredTarget:n.workspace,projectRoot:n.project??r.projectRoot??process.cwd()}),a=n.check||!i.needed?void 0:await yf(s),l;if(!n.check&&!n["no-start"])try{await hl(o,r.client??{})}catch(m){l=m instanceof Error?m.message:String(m)}let d=await _f({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"]&&He(d.entry)?await Ef({configHome:r.configHome??Wx(),unit:wf({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=bf(d);return t(`${X({verdict:u.verdict,home:{path:a?.path??d.homePath,created:a?.created??!1,tightened:a?.tightened??!1,needed:i.needed,needed_by:i.declaredBy},socket:d.socketPath,...l==null?{}:{start_error:l},...c==null?{}:{unit:{path:c.path,status:c.status}},checks:u.rows.map(m=>({check:m.check,verdict:m.verdict,evidence:m.evidence})),fixes:u.findings.map(m=>({check:m.check,fix:m.fix}))})}
|
|
226
|
+
`),u.verdict==="ok"?0:1}var Mx={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function Fx(e,r={}){let t=r.write??(s=>process.stdout.write(s)),{values:n}=dr(e,Mx),o=await Tf({...r.options??{},dryRun:n["dry-run"]===!0,...Number.isFinite(n["grace-ms"])?{graceMs:n["grace-ms"]}:{}});return t(`${X({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(s=>({dir:s.dir,verdict:s.verdict,reason:s.reason,removed:[...s.removed]}))})}
|
|
227
|
+
`),o.entries.some(s=>s.verdict==="failed")?1:0}function Wx(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:ps(In(),".config")}function Df(e){let r=ui(e);return r.configText==null?{label:null}:{configText:r.configText,label:pc(e)}}function Ux(e){let r=ze();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 Bx=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;if(Bx){let e=process.argv.slice(2);Ox(e).then(r=>{e[0]==="serve"&&process.exit(r),process.exitCode=r},r=>{process.stderr.write(`redskilled: ${r instanceof Error?r.message:String(r)}
|
|
228
|
+
`),process.exitCode=1})}async function Hx(e,r={}){let t=r.write??(a=>process.stdout.write(a)),n=r.warn??(a=>process.stderr.write(a)),o=vl(e),s=Df(r.cwd??process.cwd()),i=Sl({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let a of[...i.warnings,...o.warnings])n(`redskilled dashboard: ignoring ${a.key}=${a.value} \u2014 ${a.reason}
|
|
229
|
+
`);try{let a=await ef(r.paths??ze(),{...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(`
|
|
230
230
|
`)}
|
|
231
231
|
`)}catch(a){n(`redskilled dashboard: ${a instanceof Error?a.message:String(a)}
|
|
232
232
|
`),t(`redskilled unreachable \u2014 the host was not asked, so its Workers are unknown
|
|
233
|
-
`)}return 0}export{
|
|
233
|
+
`)}return 0}export{Of as REDSKILLED_HOST_TOKEN_ENV,Ex as REDSKILLED_USAGE,Pf as armRedskilledQueueTransport,Af as resolveRedskilledHostToken,Px as resolveServeGithubBalance,xx as resolveServeQueueDiscovery,Hx as runDashboard,Dx as runGithubSpend,Nx as runProvision,Fx as runReclaim,Ox as runRedskilledCli,$x as runStatusline,Gx as runStop,Ix as runUnit};
|
|
234
234
|
/*! Bundled license information:
|
|
235
235
|
|
|
236
236
|
content-type/dist/index.js:
|