@reddb-io/red-skills 3.9.0 → 3.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -5
- package/dist/brain.bundle.min.mjs +1 -1
- package/dist/castle-mcp.bundle.min.mjs +386 -384
- package/dist/code-nav.bundle.min.mjs +1 -1
- package/dist/dev.bundle.min.mjs +696 -674
- package/dist/memory.bundle.min.mjs +1 -1
- package/dist/redskilled.bundle.min.mjs +89 -89
- 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 fh=Object.create;var vs=Object.defineProperty;var hh=Object.getOwnPropertyDescriptor;var yh=Object.getOwnPropertyNames;var kh=Object.getPrototypeOf,bh=Object.prototype.hasOwnProperty;var _h=(e,r)=>()=>(e&&(r=e(e=0)),r);var Yl=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),Rh=(e,r)=>{for(var t in r)vs(e,t,{get:r[t],enumerable:!0})},wh=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of yh(r))!bh.call(e,o)&&o!==t&&vs(e,o,{get:()=>r[o],enumerable:!(n=hh(r,o))||n.enumerable});return e};var Ss=(e,r,t)=>(t=e!=null?fh(kh(e)):{},wh(r||!e||!e.__esModule?vs(t,"default",{value:e,enumerable:!0}):t,e));var Lc={};Rh(Lc,{REDSKILLED_BIN_ENV:()=>ki,REDSKILLED_BUNDLE_ASSET:()=>Be,REDSKILLED_ENTRY_UNRESOLVED:()=>en,RedskilledDaemonEntryError:()=>rn,isRedskilledEntryPath:()=>_i,isResolvedRedskilledEntry:()=>He,redskilledBundleCacheRoot:()=>Eo,redskilledServeArgv:()=>Lr,requireRedskilledEntry:()=>vo,resolveRedskilledEntry:()=>ur});import{existsSync as Tb,readdirSync as xb}from"node:fs";import{homedir as Pb}from"node:os";import{basename as yi,dirname as hi,join as Se,resolve as wo}from"node:path";function He(e){return"command"in e}function Lr(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 Eo(e=process.env){return jc(e)}function ur(e={},r={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=r.env??process.env,n=r.exists??Tb,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[ki];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(i&&_i(i))return a(wo(i),"caller-entry");let d=[];for(let[c,u]of jb(i,r.rootDir,t,r.listDir??Ib))if(d.push(c),n(c))return a(c,u);return{diagnostic:en,searched:d,...i?{callerEntry:wo(i)}:{}}}function vo(e={},r={}){let t=ur(e,r);if(He(t))return t;throw new rn(t)}function _i(e){let r=yi(e);return r===Be||bi.test(r)||r==="red-skills-redskilled"||r==="red-skills-redskilled.mjs"?!0:r!=="cli.js"&&r!=="cli.mjs"&&r!=="cli.ts"?!1:Db(wo(e))}function Db(e){let r=hi(e);for(let t=0;t<4;t++){if(yi(r)==="redskilled")return!0;let n=hi(r);if(n===r)return!1;r=n}return!1}function*jb(e,r,t,n){if(e){let s=hi(wo(e));yield[Se(s,Be),"caller-sibling-bundle"];let i=Ob.exec(yi(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 Ab){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=jc(t);yield[Se(o,Be),"bundle-cache"];for(let s of Lb(o,n))yield[Se(o,s),"bundle-cache"]}function jc(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let r=e.XDG_CACHE_HOME||Se(e.HOME||Pb(),".cache");return Se(r,"red-skills","bundles")}function Lb(e,r){return r(e).filter(t=>bi.test(t)).sort((t,n)=>Gb(Dc(n),Dc(t)))}function Dc(e){return bi.exec(e)?.[1]??""}function Gb(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 Ib(e){try{return xb(e)}catch{return[]}}var Be,en,ki,rn,Ob,bi,Ab,tr=_h(()=>{"use strict";Be="redskilled.bundle.min.mjs",en="redskilled-daemon-entry-unresolved",ki="REDSKILLED_BIN";rn=class extends Error{code=en;searched;callerEntry;constructor(r){super(`${en}: 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
|
|
9
|
-
`),e.push(" order: ",ce(t.order.encoded,
|
|
10
|
-
`),e.push(" discriminator: ",ce(t.discriminator,
|
|
6
|
+
`)}`),this.name="RedskilledDaemonEntryError",this.searched=r.searched,r.callerEntry!=null&&(this.callerEntry=r.callerEntry)}};Ob=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,bi=/^redskilled-(.+)\.bundle\.min\.mjs$/,Ab=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});var Ki=Yl((qi,Vi)=>{(function(e,r){typeof qi=="object"&&typeof Vi<"u"?Vi.exports=r():typeof define=="function"&&define.amd?define(r):e.Bottleneck=r()})(qi,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,Er,Nn;Er=h,Nn=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 Er(`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 Mn=Nn,Fn,Br;Fn=i,Br=class{constructor(b,g){this.schedule=this.schedule.bind(this),this.name=b,this.Promise=g,this._running=0,this._queue=new Fn}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,St="2.19.5",Wn={version:St},Un=Object.freeze({version:St,default:Wn}),Tt=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),xt=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Bn=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Pt,Hn,qn,Ot,At,vr;vr=o,Pt=l,Ot=Tt,qn=xt,At=Bn,Hn=function(){class D{constructor(g={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=g,vr.load(this.limiterOptions,this.defaults,this),this.Events=new Pt(this),this.instances={},this.Bottleneck=U,this._startAutoCleanup(),this.sharedConnection=this.connection!=null,this.connection==null&&(this.limiterOptions.datastore==="redis"?this.connection=new Ot(Object.assign({},this.limiterOptions,{Events:this.Events})):this.limiterOptions.datastore==="ioredis"&&(this.connection=new qn(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",...At.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(vr.overwrite(g,this.defaults,this),vr.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=Hn,Dt,Sr,$e;$e=o,Sr=l,Dt=function(){class D{constructor(g={}){this.options=g,$e.load(this.options,this.defaults,this),this.Events=new Sr(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=Dt,jt=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Lt=r(Un),Gt,Vn,C,ir,Pe,Ce,ar,qr,Tr,lr,_e,Vr=[].splice;Ce=10,Vn=5,_e=o,ar=m,ir=G,Pe=he,qr=jt,C=l,Tr=Mn,lr=ps,Gt=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 ar(Ce),this._scheduled={},this._states=new Tr(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new C(this),this._submitLock=new lr("submit",this.Promise),this._registerLock=new lr("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 Ye;return this.Events.trigger("debug",`Drained ${x.id}`,{success:N,args:_,options:x}),N?(A.shift(),Ye=this.empty(),Ye&&this.Events.trigger("empty"),z===0&&this.Events.trigger("depleted",Ye),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(Ye,xr){return R(...z,function(...se){return(se[0]!=null?xr:Ye)(se)})}),E=new ir(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 ir(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=Lt.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=Tt,D.IORedisConnection=D.prototype.IORedisConnection=xt,D.Batcher=D.prototype.Batcher=Hr,D.prototype.jobDefaults={priority:Vn,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=Gt,oe=U;return oe})});var hp=Yl(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.format=XR;Co.parse=ZR;var zR=/^[\u0009\u0020-\u007e\u0080-\u00ff]*$/,up=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,QR=/[\\"]/g,YR=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,pp=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function XR(e){let{type:r,parameters:t}=e;if(!r||!YR.test(r))throw new TypeError(`Invalid type: ${r}`);let n=r;if(t)for(let o of Object.keys(t)){if(!up.test(o))throw new TypeError(`Invalid parameter name: ${o}`);n+=`; ${o}=${nw(t[o])}`}return n}function ZR(e,r){let t=e.length,n=Zi(e,0,t),o=n;n=Xi(e,n,t);let s=ea(e,o,n),i=e.slice(o,s).toLowerCase(),a=r?.parameters===!1?new pp:tw(e,n,t);return{type:i,parameters:a}}var mp=32,gp=9,fp=59,ew=61,cp=34,rw=92;function tw(e,r,t){let n=new pp;e:for(;r<t;){r=Zi(e,r+1,t);let o=r;for(;r<t;){let s=e.charCodeAt(r);if(s===fp)continue e;if(s===ew){let i=ea(e,o,r),a=e.slice(o,i).toLowerCase();if(r=Zi(e,r+1,t),r<t&&e.charCodeAt(r)===cp){r++;let d="";for(;r<t;){let c=e.charCodeAt(r++);if(c===cp){r=Xi(e,r,t),n[a]===void 0&&(n[a]=d);break}if(c===rw&&r<t){d+=e[r++];continue}d+=String.fromCharCode(c)}continue e}let l=r;if(r=Xi(e,r,t),n[a]===void 0){let d=ea(e,l,r);n[a]=e.slice(l,d)}continue e}r++}}return n}function Xi(e,r,t){for(;r<t&&e.charCodeAt(r)!==fp;)r++;return r}function Zi(e,r,t){for(;r<t;){let n=e.charCodeAt(r);if(n!==mp&&n!==gp)break;r++}return r}function ea(e,r,t){for(;t>r;){let n=e.charCodeAt(t-1);if(n!==mp&&n!==gp)break;t--}return t}function nw(e){if(up.test(e))return e;if(zR.test(e))return`"${e.replace(QR,"\\$&")}"`;throw new TypeError(`Invalid parameter value: ${e}`)}});import{execFileSync as vx}from"node:child_process";import{homedir as $n}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}},Or=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 Or(e,r)}function rt(e){return e instanceof Or?e:e instanceof et?new Or(e.line,e.reason):new Or(0,String(e&&e.message?e.message:e))}var Xl=["type","kind","event"],Ar="|",Zl=new Set(["order","discriminator","rows","common"]);var K=",";function io(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 td(e,r);if(e.includes('"'))throw Ne(r);return e==="true"?!0:e==="false"?!1:e==="null"?null:Eh(e)?Number(e):e}function Oe(e,r){let t=e.trim();if(t.startsWith('"'))return[td(t,r),!0];if(t.includes('"')||/\s/.test(t))throw P(r,"expected non-empty field name");return[t,!1]}var ed=/["\\\u0000-\u0008\u000a-\u001f]/g;function td(e,r){if(e.charCodeAt(0)!==34)throw Ne(r);let t="",n=1;for(;n<e.length;){ed.lastIndex=n;let o=ed.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 nd(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=nd(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=nd(e,o+1,t)}return-1}function Eh(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function vh(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Sh(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 Sh(e);if(typeof e=="string")return xh(e,r);throw P(0,"not a primitive")}function Th(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function ne(e){return Th(e)?e:ao(e)}function xh(e,r){return Ts(e,r)?ao(e):e}function Ts(e,r){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||vh(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(r)||e.startsWith("-")}var rd=/["\\\u0000-\u001f]/g;function ao(e){let r='"',t=0;rd.lastIndex=0;let n;for(;(n=rd.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 od(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 sd(e,r){let t=[],n=!1;return io(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 Kt(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 ld(e){if(!Y(e)||Object.keys(e).length===0)return e;let r={};for(let[t,n]of Object.entries(e)){let o=Ph(n,1);if(o===void 0)return e;De(r,t,o)}return r}function Ph(e,r){if(!Y(e)||!Oh(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=Ah(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 dd(r);let l=new Map;for(let[u,m]of Object.entries(e))if(!Zl.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 xs(r);let h=d.get(u)??0,v=f[h];if(v===void 0)throw xs(r);return d.set(u,h+1),Dh(n,u,a[m],v,r)});for(let[u,m]of l)if((d.get(u)??0)!==m.length)throw xs(r);return c}function Oh(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function Ah(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=>Ih(c,t));if(a.some(c=>c===""))throw ie(t);let l=Gh(i,t),d=a.length*l;if(!Number.isSafeInteger(d))throw ie(t);if(d!==r)throw dd(t);return Array.from({length:d},(c,u)=>a[u%a.length])}function Dh(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(jh(n,o))){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw ie(o);De(s,i,a)}return s}function jh(e,r){let t={};for(let[n,o]of Object.entries(e))Lh(t,n.split("."),o,r);return lo(t,r)}function Lh(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 lo(e,r){return Array.isArray(e)?e.map(t=>lo(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 lo(e[String(n)],r)}):Object.fromEntries(Object.entries(e).map(([t,n])=>[t,lo(n,r)])):e}function Gh(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 Ih(e,r){try{return decodeURIComponent(e)}catch{throw ie(r)}}function id(e){return encodeURIComponent(e)}function ie(e){return P(e,"invalid cyclic array wire")}function dd(e){return P(e,"cyclic array length mismatch")}function xs(e){return P(e,"cyclic array group length mismatch")}function cd(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=$h(s);if(i===void 0)return;t.push([o,i])}let n=[];for(let[o,s]of t)Fh(n,o,s);return n.join("")}function $h(e){if(!Array.isArray(e)||e.length===0||!e.every(Y))return;let r=Ch(e);if(r===void 0)return;let t=e.map(a=>a[r]),n=Nh(t);if(n===void 0)return;let o=Mh(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)&&!Ps(u,c,d))return;s.get(l).push(d)}let i=[];for(let a of n.cycle){let l=s.get(a),d=Uh(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 Ch(e){return Xl.find(r=>e.every(t=>typeof t[r]=="string"))}function Nh(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(id).join(","),s=`cycle(${t.map(id).join(",")})*${n}`;if(s.length<=o.length*.4)return{cycle:t,encoded:s,repeats:n}}}function Mh(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(!Wh(s)||!e.every(i=>Object.prototype.hasOwnProperty.call(i,s))||!e.every(i=>Me(i[s])))break;t.push(s)}return t}function Fh(e,r,t){e.push(ne(r),`:
|
|
9
|
+
`),e.push(" order: ",ce(t.order.encoded,Ar),`
|
|
10
|
+
`),e.push(" discriminator: ",ce(t.discriminator,Ar),`
|
|
11
11
|
`),e.push(" rows: ",String(t.rows.length),`
|
|
12
|
-
`),t.common.length>0&&
|
|
13
|
-
`);for(let o of n)e.push(" ",t.map(s=>ce(o[s],
|
|
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(
|
|
16
|
-
`),e.push(...l)}return}e.push(
|
|
17
|
-
`),
|
|
18
|
-
`)}function Ns(e,r,t,n,o,s){if(Fe(n,0,s),t.length===0){r!==void 0?e.push(
|
|
12
|
+
`),t.common.length>0&&ad(e,"common",t.common,t.commonRows);for(let n of t.groups)ad(e,n.label,n.fields,n.rows)}function ad(e,r,t,n){e.push(" ",ne(r),"[",String(n.length),Ar,"]{",t.map(ne).join(Ar),`}:
|
|
13
|
+
`);for(let o of n)e.push(" ",t.map(s=>ce(o[s],Ar)).join(Ar),`
|
|
14
|
+
`)}function Wh(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 Uh(e){let r=Object.keys(e[0]??{});if(e.every(t=>Bh(Object.keys(t),r)))return r.every(Os)?r:void 0}function Bh(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 co(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=qh(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 ud(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=Hh(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 Hh(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(!pd(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(md(n[l].path,n[d].path)||Jt(n[l].path,n[d].path)||Jt(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 qh(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=Vh(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(pd(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(md(a[l].path,a[d].path)||Jt(a[l].path,a[d].path)||Jt(a[d].path,a[l].path))throw P(0,"duplicate key");return i}function Vh(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 uo(e,r,t){return e.listDelimiter===void 0?Ee(r,t):Ae(r,e.listDelimiter,t).map(n=>Ee(n,t))}function pd(e,r){return e.length===1&&e!==r&&!/[ \t\r\n"[\]{}:]/.test(e)}function md(e,r){return e.length===r.length&&Jt(e,r)}function Jt(e,r){return r.every((t,n)=>e[n]===t)}function po(e,r){return P(r,e.reason??String(e.message))}function me(e,r){let t=od(r),n=sd(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("[")){Kt(o.content,o.number,t);let d;try{d=co(o.content,de(o.content,":",o.number))}catch(c){if(t.strict)throw po(c,o.number);d=void 0}if(d!==void 0)return zh(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?ld(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}=Kh(e,r,t,n);_d(o,i,a,l,n,s.number)}return o}function Kh(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)){Kt(a,o.number,n);let h;try{h=ud(a)}catch(k){if(n.strict)throw po(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=Jh(h,e,r,t+1,n);return{key:h.key,quoted:h.keyQuoted,value:v}}if(d!==-1){Kt(a,o.number,n);let h;try{h=co(a,i)}catch(k){if(n.strict)throw po(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 Jh(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,uo(m,c[f],i.number),o,i.number)}),_d(s,l,d,u,o,i.number),t.index+=1}return s}function zh(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 Qh(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 ny(e,t,n,o+1,s)}function Qh(e,r,t,n,o,s){if(e.fieldTree!==void 0&&ry(e.fieldTree))return Yh(e,t,n,o,s);let i=[];for(;i.length<e.len;){let l=t[n.index];if(l===void 0)throw 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,uo(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 Yh(e,r,t,n,o){return gd(e.len,e.fieldTree,e.delimiter,r,t,n,o,!0)}function gd(e,r,t,n,o,s,i,a){let l=[],d=hd(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:mo(r),childTableFields:d},h=fd(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(ey(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 fd(e,r,t,n,o,s,i,a){let l={};return e.forEach((d,c)=>{let u=e.slice(c+1),m=Xh(d,u,r,t,n,o,s,i,a);ot(l,[d.key],m,a,t)}),l}function Xh(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=mo(e.children),u=t[s.cellIndex],m=kd(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+ty(r)):k){if(m===void 0)throw P(n,"array row length mismatch");return s.cellIndex+=1,gd(m,e.children,a,o,{get index(){return s.nextIndex},set index(I){s.nextIndex=I}},i,l,!1)}return fd(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,uo(e,d,n)}function hd(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=yd(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 yd(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=Zh(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 Zh(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=kd(t[l]);if(m===void 0)return;l+=1;let f=hd(m,u.children,n,o,d,i,a);if(f===void 0)return;let h=yd(m,u.children,f,n,o,d,i,a);if(h===void 0)return;d=h.nextIndex,c+=m+h.consumedChildRows}else l+=mo(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:c}}function ey(e,r,t){return t&&e.length===1&&e[0].fixedLength!==void 0?r[e[0].key]:r}function kd(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function ry(e){return e.some(r=>r.fixedLength!==void 0||r.children!==void 0)}function mo(e){return e.reduce((r,t)=>r+bd(t),0)}function bd(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?mo(e.children):1}function ty(e){return e.reduce((r,t)=>t.children!==void 0?r+1:r+bd(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 ny(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(oy(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 oy(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);Kt(s,o.number,n);let a;try{a=co(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 _d(e,r,t,n,o,s){if(o.expandPaths&&!t&&r.includes(".")){let i=r.split(".");if(i.every(sy)){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 sy(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=cd(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?Ns(s,void 0,e,0,!1,o):Y(e)?Rd(s,e,0,o):s.push(ce(e,n)),s.join("")}function st(e,r){e.push(" ".repeat(r*2))}function Rd(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?ay(t,o,n+1):void 0;if(s!==void 0){e.push(ne(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(ne(i),": ",s.paths.map(d=>Bs(Ws(a,d.path),d,o.delimiter,o,l,n+2)).join(o.delimiter),`
|
|
16
|
+
`),e.push(...l)}return}e.push(ne(r),`:
|
|
17
|
+
`),Rd(e,t,n+1,o);return}e.push(ne(r),": ",ce(t,o.delimiter),`
|
|
18
|
+
`)}function Ns(e,r,t,n,o,s){if(Fe(n,0,s),t.length===0){r!==void 0?e.push(ne(r),`: []
|
|
19
19
|
`):o?e.push(`[0]:
|
|
20
20
|
`):e.push(`[]
|
|
21
21
|
`);return}if(t.every(Me)){Is(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:
|
|
22
|
+
`);return}let i=o?void 0:wd(t,s,n+1);if(i!==void 0){Is(e,r,t.length,i.fields,s.delimiter),e.push(`
|
|
23
23
|
`);for(let a of t){st(e,n+1);let l=[];e.push(i.paths.map(d=>Bs(Ws(a,d.path),d,s.delimiter,s,l,n+2)).join(s.delimiter)),e.push(`
|
|
24
24
|
`),e.push(...l)}return}Is(e,r,t.length,void 0,s.delimiter),e.push(`
|
|
25
|
-
`);for(let a of t)st(e,n+1),
|
|
25
|
+
`);for(let a of t)st(e,n+1),iy(e,a,n+1,s)}function iy(e,r,t,n){if(Fe(t,0,n),Array.isArray(r)){e.push("- "),Ns(e,void 0,r,t,!0,n);return}if(Y(r)){let o=Object.entries(r);if(o.length===0){e.push(`-
|
|
26
26
|
`);return}e.push("- "),$s(e,o[0][0],o[0][1],t+1,n);for(let[s,i]of o.slice(1))st(e,t+1),$s(e,s,i,t+1,n);return}e.push("- ",ce(r,n.delimiter),`
|
|
27
|
-
`)}function Is(e,r,t,n,o){r!==void 0&&e.push(
|
|
28
|
-
`),e.push(...i)}}function
|
|
29
|
-
`}function
|
|
30
|
-
`}function Hs(e,r){return r.map(
|
|
31
|
-
`,h=()=>
|
|
32
|
-
`;return
|
|
33
|
-
`},end(){return u?"":(u=!0,f())}}}function qs(e){let r={app:e,version:
|
|
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 ti(e){let r=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${r}-${e.pid}.toon`}function ni(e,r){let t=at(e,ti(r));try{return
|
|
43
|
-
`)}catch{return!0}},append(e,r){
|
|
44
|
-
`),t.append(e,n),r}function
|
|
27
|
+
`)}function Is(e,r,t,n,o){r!==void 0&&e.push(ne(r)),e.push("[",String(t),Ms(o),"]"),n!==void 0&&e.push("{",n.map(s=>Us(s,o)).join(o),"}"),e.push(":")}function Ms(e){return e===K?"":e}function wd(e,r,t){let n=ly(e,r);if(n!==void 0)return n;let o=Cs(e.map(s=>({value:s})),r,t);return o===void 0?void 0:{fields:o,paths:Fs(o)}}function ay(e,r,t){let n=Object.values(e);if(!(n.length<2))return wd(n,r,t)}function Cs(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=Ed(i.map(({value:c})=>c));if(l!==void 0){s.fixedLength=l.fixedLength,s.fixedDelimiter=r.delimiter;continue}let d=Cs(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=Cs(i,r,t+1);if(a===void 0)return;s.children=a}return o}}function ly(e,r){if(!r.objectArrayColumns)return;let t=Ed(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:r.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function Ed(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 Fs(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}]:Fs(t.children,n)})}function Ws(e,r){let t=e;for(let n of r)t=t[n];return t}function Us(e,r){return e.listDelimiter!==void 0?`${ne(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${ne(e.key)}[${e.fixedLength}${Ms(r)}]`:e.children===void 0?ne(e.key):`${ne(e.key)}{${e.children.map(t=>Us(t,r)).join(r)}}`}function Bs(e,r,t,n,o,s){return r.childFields!==void 0?(dy(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=>cy(i,t,r.listDelimiter)).join(r.listDelimiter)}function dy(e,r,t,n,o){for(let s of r){st(e,o);let i=[];e.push(Fs(t).map(a=>Bs(Ws(s,a.path),a,n.delimiter,n,i,o+1)).join(n.delimiter)),e.push(`
|
|
28
|
+
`),e.push(...i)}}function cy(e,r,t){return typeof e!="string"?ce(e,r):Ts(e,r)||e.includes(t)?ao(e):e}var Dd=[K,"|"," "];var jd=8,Ld=/^[A-Za-z0-9_-]+$/,HP=new TextEncoder,qP=new TextDecoder;function gy(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 Gd(e,r){if(!Ld.test(e))throw M(r,"invalid tag")}function fy(e,r){let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t);if(!Ld.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 hy(e,r){if(!e.startsWith("["))return null;let t=e.slice(1),n=t.indexOf("]");if(n===-1)throw M(r,"invalid header");let o=t.slice(0,n),s=o.startsWith("~"),i=s?o.slice(1):o;if(!s&&i.startsWith("="))return null;if(!Dd.includes(i)&&i!=="")throw M(r,"invalid header delimiter");let a=i===""?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),Gd(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 yy(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 vd(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 ky(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 by(e,r,t){if(e.startsWith("- "))throw M(r,"reserved line prefix");let n=gy(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=hy(e,r);if(o!==null)return o.continuation?(yy(t,o,r),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=fy(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:vd(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:vd(e,t.delimiter,t.fields.length,r)}}function _y(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>=jd)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(io(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=by(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 _y(e).flatMap(r=>r.rows.map(t=>ky(r.fields,t,0)))}function Ry(e){if(!Dd.includes(e))throw M(0,"invalid header delimiter")}function Sd(e,r,t=!1){return`[${`${t?"~":""}${e===K?"":e}`}]{${r}}:
|
|
29
|
+
`}function Td(e,r){return`[]<${e}>{${r}}:
|
|
30
|
+
`}function Hs(e,r){return r.map(ne).join(e)}function wy(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 xd(e,r){return e!==null&&e.length===r.length&&e.every((t,n)=>t===r[n])}function Pd(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw M(0,"TOONL continuation cadence must be positive")}function Ey(e,r,t){return e.continuationEveryRows!==void 0&&r>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function Od(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 vy(e){return JSON.stringify([...e].sort())}function Ad(e,r){let t=vy(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}={}){Ry(e),Pd(t),Pd(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=()=>Ey(m,l,d)?(l=0,d=0,Sd(e,s,!0)):"",v=k=>{Gd(k,0);let T=c.get(k);if(T===void 0){if(c.size>=jd)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=Ad(Od(k),i),I="";(o===null||o.length!==T.length||o.some((H,ee)=>H!==T[ee]))&&(I+=f(),o=T,s=Hs(e,o),a=0,l=0,d=0,I+=Sd(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=wy(T),F=Hs(K,I),G=v(k);return xd(G.fields,I)?"":(G.fields=I,Td(k,F))},pushTagged(k,T){if(u)throw M(0,"TOONL encoder is closed");let I=v(k),F=Ad(Od(T),I.fieldsByShape),G=Hs(K,F),H=F.map(q=>ce(T[q],K)),ee="";return xd(I.fields,F)||(I.fields=F,ee+=Td(k,G)),`${ee}${k}:${H.join(K)}
|
|
33
|
+
`},end(){return u?"":(u=!0,f())}}}function qs(e){let r={app:e,version:Sy(it("__RED_BUILD_VERSION__",()=>"3.11.0")??"0.0.0-dev"),gitSha:it("__RED_BUILD_GIT_SHA__",()=>"9d42283ac3a291ae4a1fe379c1eaee761207aa03")??"unknown",buildTime:it("__RED_BUILD_TIME__",()=>"2026-08-07T13:53:44-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 Sy(e){return e.startsWith("v")?e.slice(1):e}function Id(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 $d={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Ty=/^[a-z][a-z0-9+.-]*:\/\//i;function xy(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 Py(e=$d){return Object.entries(e).map(([r,t])=>xy(r,t)).sort((r,t)=>t.separator.length-r.separator.length)}function Oy(e){return/^-\d+(\.\d+)?$/.test(e)}function zt(e){return!(!e||e.startsWith("-")&&!Oy(e))}function go(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 Cd(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=>Cd(t.trim())):e}function Dr(e,r){switch(r){case"boolean":return Ay(e);case"number":return Dy(e);case"array":return e.split(",").map(t=>go(t.trim()));case"string":default:return e}}function Ay(e){let r=e.toLowerCase().trim();return r==="true"||r==="yes"||r==="1"||r==="on"}function Dy(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 dr(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function jy(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 Ly(e){let r=[],t=Iy(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=$y(e.options);r.push(...n)}return r}function Gy(e,r){let t=Ly(e);return jy(t,r)}function Iy(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 $y(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 Nd(e){let r=By(e.options??{},e.autoShort??!1),t=Py(e.separators??$d);return{schema:e,parse(n){return Cy(n,e,r,t)},help(){return Gy(e,e.formatter)}}}function Cy(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?Dr(h,m.type):h),l++}o.positional[m.name]=f,i++}else{let f=m.type?Dr(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=Wy(c,l,e,o,t,r);continue}if(c.startsWith("-")&&c.length>1&&!Jy(c)){l=Uy(c,l,e,o,t,r);continue}let u=Ny(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?Cd(f):dr(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?Dr(v,m.type):v),l++}o.positional[m.name]=h,i++;continue}let f=m.type?Dr(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 qy(o,r,t),Vy(o,r,a),Ky(o,r,t),o}function Ny(e,r){if(Ty.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(My(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(Fy(o,s,t))return{key:o,value:s,config:t}}}return null}function My(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function Fy(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 Wy(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 fo(d,c,r+1,n,o,s)}let a=o.get(i);if(a){if(a.type!=="boolean"){let l=t[r+1];return zt(l)?fo(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 Uy(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=Vs(l,o);return c?fo(c.name,d,r+1,n,o,s):(s.strict?n.errors.push(`Unknown option: -${l}`):s.allowUnknown!==!1&&(n.options[l]=go(dr(d))),r+1)}if(i.length===1){let a=Vs(i,o);if(a){if(a.type!=="boolean"){let l=t[r+1];return zt(l)?fo(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(zt(l))return n.options[i]=go(dr(l)),r+2;n.options[i]=!0}return r+1}for(let a of i){let l=Vs(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 fo(e,r,t,n,o,s){let i=o.get(e);if(i){if(i.choices){let l=i.type?Dr(dr(r),i.type):dr(r);if(!i.choices.includes(l))return n.errors.push(`Invalid value for '${e}': '${r}'. Allowed: ${i.choices.join(", ")}`),t}let a=i.type?Dr(dr(r),i.type):dr(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]=go(dr(r)));return t}function By(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=Hy(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 Hy(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 Vs(e,r){for(let t of r.values())if(t.short===e||t.aliases.includes(e))return t}function qy(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?Dr(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 Vy(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 Ky(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 Jy(e){return/^-\d+(\.\d+)?$/.test(e)}var Ks=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 zy(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 Qy(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&&zt(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 cr(e,r,t={}){let o=Nd({options:zy(r),separators:{},allowUnknown:!0}).parse([...e]),s={},i=Qy(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 Ks(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 Js=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 Md(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 Js(t,Object.keys(r.commands))}let o=r.keepArgvOnDefault??!0;return{command:r.default,args:o?[...e]:n}}import{appendFileSync as ak,mkdirSync as lk,readFileSync as zd,statSync as dk}from"node:fs";import{dirname as Yd,join as ck}from"node:path";var Fd="RED_WORKER_SCOPE",Wd="RED_WORKER_MEMORY_CEILING",Ud="RED_WORKER_SCOPE_DEGRADATION",Qs={scope:null,memory_ceiling:null,scope_degradation:null};function Ys(e){return{scope:zs(e[Fd]),memory_ceiling:zs(e[Wd]),scope_degradation:zs(e[Ud])}}function Qt(e){let r={};return e.scope!=null&&e.scope!==""&&(r[Fd]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(r[Wd]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(r[Ud]=e.scope_degradation),r}function zs(e){let r=(e??"").trim();return r===""?null:r}import{mkdirSync as Zy,readdirSync as ek,readFileSync as Vd,rmSync as rk,writeFileSync as tk}from"node:fs";import{basename as nk,join as at}from"node:path";import{isAbsolute as vO,join as ho,resolve as SO}from"node:path";function Yy(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var Bd="deaths",Hd="deaths.toonl";function yo(e){return ho(Yy(e),Bd)}function Yt(e){return ho(yo(e),Hd)}var Xt="live",qd="attributions.toonl";function ko(e){return ho(yo(e),Xt)}function Xs(e){return ho(yo(e),qd)}var ei=at("sys","kernel","random","boot_id"),Kd=1;function ri(e,r={}){let t=r.procRoot??"/proc",n=e.pid??process.pid;return{version:Kd,ts:(r.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:n,ppid:e.ppid??process.ppid,boot_id:Jd(at(t,ei)),cgroup:ok(t,n),last_phase:e.last_phase}}function Jd(e){try{let r=Vd(e,"utf8").trim();return r===""?null:r}catch{return null}}function ok(e,r){let t=Jd(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 ti(e){let r=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${r}-${e.pid}.toon`}function ni(e,r){let t=at(e,ti(r));try{return Zy(e,{recursive:!0,mode:448}),tk(t,ye({trailer:!1}).push(ik(r)),{encoding:"utf8",mode:384}),t}catch{return null}}function jr(e,r){try{rk(at(e,ti(r)),{force:!0})}catch{}}function oi(e,r){let t;try{t=ek(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(Vd(s,"utf8"))[0];if(a===void 0)throw new Error("anchor holds no record");n.push(sk(a))}catch(i){r?.(nk(s),i instanceof Error?i.message:String(i))}}return n}function sk(e){let r=e.kind;if(r!=="launcher"&&r!=="worker"&&r!=="daemon")throw new Error(`presence anchor has unknown kind ${String(r)}`);return{version:Zs(e.version),ts:String(e.ts),kind:r,id:String(e.id),pid:Zs(e.pid),ppid:Zs(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 Zs(e){return typeof e=="number"?e:Number(e)}function ik(e){return{...e}}var uk=1,pk=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function mk(e){return typeof e=="string"&&pk.has(e)}var gk="startup";function fk(e,r){return{...e.scope??Qs,version:uk,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 hk(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 ii={mkdir(e){lk(e,{recursive:!0,mode:448})},endsClean(e){let r;try{r=dk(e).size}catch{return!0}if(r===0)return!0;try{return zd(e,"utf8").endsWith(`
|
|
43
|
+
`)}catch{return!0}},append(e,r){ak(e,r,{encoding:"utf8",mode:384})},read(e){return zd(e,"utf8")}};function yk(e){let r={};for(let[t,n]of Object.entries(e))r[t]=n;return r}function kk(e,r,t=ii){let n=ye({trailer:!1}).push(yk(r));return t.mkdir(Yd(e)),t.endsClean(e)||t.append(e,`
|
|
44
|
+
`),t.append(e,n),r}function Xd(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:ai(d),detail:null})}return{boot_id:s,live_pids:i,journal:a,probes:n}}function ai(e){return e.code==="ENOENT"?"absent":"unreadable"}function
|
|
46
|
+
`)+1);return r===""?[]:We(r).map(bk)}function bk(e){let r=e.exit_path;if(!mk(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 Zd(e,r=ii){let t;try{t=r.read(e)}catch(n){if(n.code==="ENOENT")return[];throw n}return Xd(t)}var _k=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],si=null;function ec(e){let r=e.host??process,t=e.io??ii,n=e.clock??(()=>new Date().toISOString()),o=r.pid,s=e.scope??Ys(process.env),i=e.phase??gk,a=null,l=e.presenceDir===void 0?ck(Yd(e.lanePath),Xt):e.presenceDir,d=null,c=()=>{l!==null&&(d=ri({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),ni(l,d))},u=k=>{if(!a){try{a=kk(e.lanePath,fk({ts:n(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...k},hk(r)),t)}catch{}l!==null&&d!==null&&jr(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:Qd(k)})},unhandledRejection(k){u({exit_path:"unhandled-rejection",detail:Qd(k)})}},h=[...(e.signals??_k).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&&jr(l,d),si===v&&(si=null)},handlers:m};return e.setActive!==!1&&(si=v),c(),v}function Qd(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Rk,readdirSync as wk,readFileSync as bo,statSync as Ek,writeFileSync as vk}from"node:fs";import{join as oc}from"node:path";var Sk=1,Tk=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],xk=512*1024;function Pk(e={}){let r=e.procRoot??"/proc",t=e.journalPaths??Tk,n=[],o=oc(r,ei),s=null;try{let l=bo(o,"utf8").trim();s=l===""?null:l,n.push({source:o,result:s?"read":"empty",detail:s})}catch(l){n.push({source:o,result:ai(l),detail:null})}let i=new Set;try{for(let l of wk(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:ai(l),detail:null})}let a=[];for(let l of t)try{let c=Ok(l,e.tailBytes??xk).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:ai(d),detail:null})}return{boot_id:s,live_pids:i,journal:a,probes:n}}function ai(e){return e.code==="ENOENT"?"absent":"unreadable"}function Ok(e,r){let t=Ek(e).size,n=bo(e,"utf8");return t<=r?n:n.slice(n.length-r)}var Ak=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,Dk=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,jk=/Killed (\/\S*) due to memory pressure/,Lk=/\bopid=(\d+)\b/,rc=/\bsig=(\d+)\b/,Gk=/\buid=(\d+)\b/,Ik=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,$k={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function Ck(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:Sk,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=>tc(u,e.pid,Ak)||tc(u,e.pid,Dk));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=jk.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(Lk.exec(u)?.[1])===e.pid&&rc.test(u));if(d!==void 0){let u=Number(rc.exec(d)?.[1]),m=Gk.exec(d)?.[1];return i("user-signal",o?"medium":"high",$k[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=>Ik.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 tc(e,r,t){return Number(t.exec(e)?.[1])===r}var Nk=" | ";function nc(e){return e.map(r=>r.replace(/[|\n\r]+/g," ").trim()).join(Nk)}function Mk(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:nc(e.evidence),checked:nc(e.checked)}}function Fk(e){let r=ye({trailer:!1});return e.map(t=>r.push(Mk(t))).join("")}function sc(e){let r=ko(e.stateRoot),t=Xs(e.stateRoot),n=e.now??(()=>new Date().toISOString()),o=e.evidence??Pk({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=oi(r,u=>s.push(u)),a=Zd(Yt(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),jr(r,u);continue}l.push(Ck(u,o,a,n())),jr(r,u)}return l.length>0&&Wk(t,l),{attributions:l,alive:d,self_recorded:c,skipped:s,laneText:()=>{try{return bo(t,"utf8")}catch{return""}}}}function ic(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 Wk(e,r){try{Rk(oc(e,".."),{recursive:!0,mode:448});let t=Uk(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
|
+
`;vk(e,`${t}${n}${Fk(r)}`,{encoding:"utf8",mode:384})}catch{}}function Uk(e){try{return bo(e,"utf8")}catch{return""}}import{join as Bk}from"node:path";var Hk=[".red","redskilled"],rr=448;function Ue(e){return Bk(e,...Hk)}import{execFileSync as ob}from"node:child_process";import{readFileSync as sb}from"node:fs";import{dirname as mc,join as ib}from"node:path";import{existsSync as qk,readFileSync as tA}from"node:fs";import{dirname as Vk,join as Kk}from"node:path";function ac(e,r){let t=e;for(let n=0;n<16;n++){let o=Kk(t,r);if(qk(o))return o;let s=Vk(t);if(s===t)break;t=s}return null}function Jk(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 Jk(d)}}import{createHash as zk}from"node:crypto";var Qk="project.name";function dc(e){let r=lt(e,Qk)?.trim();return r===void 0||r===""?void 0:r}var Yk=8,cc="project";function uc(e){let r=tb(e.gitCommonDir),t=(e.declaredName??"").trim(),n=t!==""?{name:t,source:"declared"}:Xk(e.remoteUrl)??{name:Zk(e.checkoutPath,r),source:"basename"},o=rb(r??li(e.checkoutPath));return{name:n.name,slug:`${eb(n.name)}-${o}`,hash:o,source:n.source}}function pc(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 Xk(e){let r=pc(e);return r===void 0?void 0:{name:r,source:"remote"}}function Zk(e,r){let t=r===void 0?"":lc(nb(r));if(t!=="")return t;let n=lc(li(e));return n===""?cc:n}function eb(e){let t=e.split("/").map(n=>n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(n=>n!=="").join("--");return t===""?cc:t}function rb(e){return zk("sha256").update(e).digest("hex").slice(0,Yk)}function tb(e){let r=li(e??"");return r===""?void 0:r}function li(e){let r=e.trim().replace(/\\/g,"/");return r.length>1?r.replace(/\/+$/,""):r}function lc(e){let r=e.split("/").filter(t=>t!=="");return r[r.length-1]??""}function nb(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var ab=2e3;function gc(e){return lb(e).name}function lb(e){let r=ci(e),t=di(e,["rev-parse","--absolute-git-dir"])??di(e,["rev-parse","--git-common-dir"]),n=di(e,["remote","get-url","origin"]);return uc({checkoutPath:r.root??e,...t!==void 0?{gitCommonDir:t}:{},...n!==void 0?{remoteUrl:n}:{},...r.name!==void 0?{declaredName:r.name}:{}})}function ci(e){let r=ac(e,ib(".red","config.yaml"));if(r==null)return{};let t;try{t=sb(r,"utf8")}catch{return{}}let n=dc(t),o=mc(mc(r));return{...n===void 0?{}:{name:n},configText:t,root:o}}function di(e,r){try{let t=ob("git",[...r],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:ab}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as tf}from"node:crypto";import{spawn as ST}from"node:child_process";import{mkdir as TT}from"node:fs/promises";import{dirname as xT}from"node:path";import{createHash as ub}from"node:crypto";import{constants as fi}from"node:fs";import{mkdir as Ec,open as pb,readFile as mb,rm as vc,stat as gb}from"node:fs/promises";import{createConnection as fb}from"node:net";import{tmpdir as hb}from"node:os";import{dirname as Sc,join as Zt}from"node:path";var db="toon";function yc(e){return e.trimStart().startsWith("{")?"json":"toon"}function pi(e){let r=0;for(;e[r]===`
|
|
51
|
+
`||e[r]==="\r";)r+=1;let t=e.slice(r);if(t==="")return null;let n=yc(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 mi(e){let r=
|
|
54
|
+
`);return o<0?null:{frame:t.slice(0,o+1),dialect:n,rest:t.slice(o+2)}}function mi(e){let r=yc(e)==="json"?ui:fc,t=r===ui?fc:ui;try{return r(e)}catch(n){try{return t(e)}catch{throw n}}}function ui(e){return JSON.parse(e)}function fc(e){return me(e)}function gi(e,r){if(r==="toon"){let t=cb(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 cb(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 kc(e,r){return!hc(e)||!hc(r)||r.ok!==!1?!1:typeof e.id=="string"&&typeof r.id=="string"&&r.id!==e.id}function hc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var bc=new Set;function _c(e){return bc.has(e)?"json":db}function Rc(e){bc.add(e)}var yb=108;async function _o(e,r,t="resident server"){let n=e.wire,o=n??_c(e.socketPath),s=await wc(e,r,t,o);return n||o==="json"||!kc(r,s)?s:(Rc(e.socketPath),await wc(e,r,t,"json"))}async function wc(e,r,t,n){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let a=fb(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(gi(r,n))}),a.on("data",m=>{d+=m.toString("utf8");let f=pi(d);f&&(d=f.rest,u(()=>{try{s(mi(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 Tc(e,r,t){let n="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{n+=o;let s=pi(n);if(!s)return;n=s.rest,e.pause();let i=a=>{if(!(e.destroyed||!e.writable))try{e.write(gi(a,s.dialect))}catch{}};(async()=>{let a;try{a=mi(s.frame),await r(a,i)}catch(l){t(l,a,i)}finally{e.end()}})()})}async function kb(e){await Ec(Sc(e),{recursive:!0,mode:448});try{return await pb(e,fi.O_CREAT|fi.O_EXCL|fi.O_RDWR)}catch(r){if(r.code!=="EEXIST")throw r;return null}}var bb=6e4,xc="resident-spawn-lock v1",_b=3;async function Pc(e,r={}){let t=r.maxAgeMs??bb,n=r.now??Date.now,o=r.pid??process.pid,s=r.isPidAlive??re;await Ec(Sc(e),{recursive:!0,mode:448});let i=[];for(let a=0;;a+=1){let l=await kb(e);if(l)return await l.writeFile(`${xc} pid=${o} taken=${new Date(n()).toISOString()}
|
|
60
|
+
`).catch(()=>{}),{acquired:!0,lockPath:e,handle:l,reaped:i};let d=await wb(e),c=await vb(e,d,n());if(a>=_b||c==null)return{acquired:!1,lockPath:e,holder:d,ageMs:c};let u=Rb(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 vc(e,{force:!0}),i.push(m),r.onReap?.(m)}}async function Oc(e){await e.handle.close().catch(()=>{}),await vc(e.lockPath,{force:!0})}function Rb(e,r,t,n){return e==null?r>t?"unattributed":null:n(e.pid)?r>t?"aged-out":null:"holder-dead"}function Ac(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 wb(e){try{return Eb(await mb(e,"utf8"))}catch{return null}}function Eb(e){let r=e.split(`
|
|
61
|
+
`,1)[0]?.trim()??"";if(!r.startsWith(xc))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 vb(e,r,t){let n=r==null?Number.NaN:Date.parse(r.takenAt);if(Number.isFinite(n))return Math.max(0,t-n);try{return Math.max(0,t-(await gb(e)).mtimeMs)}catch{return null}}function re(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}var Sb="/tmp";function Ro(e){let r=e.env??process.env,t=ub("sha256").update(e.key).digest("hex").slice(0,20),n=l=>Zt(l,e.socketFileName).length<yb,o=r.XDG_RUNTIME_DIR;if(o){let l=Zt(o,"red-skills",t);if(n(l))return l}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=Zt(`red-skills-${s}`,t),a=Zt(hb(),i);return n(a)||process.platform==="win32"?a:Zt(Sb,i)}tr();import{homedir as Jb}from"node:os";import{join as xi}from"node:path";import{spawnSync as zb}from"node:child_process";import{createHash as Qb}from"node:crypto";import{existsSync as Yb,readdirSync as Xb}from"node:fs";import{mkdir as Nc,readFile as Zb,rename as e_,writeFile as r_}from"node:fs/promises";import{dirname as t_}from"node:path";var Ir="@reddb-io/red-skills",$b="https://registry.npmjs.org",Cb="canary",Gr=class extends Error{kind;cause;constructor(r,t,n){super(t),this.name="BundleFetchError",this.kind=r,this.cause=n}},Nb=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;function wi(e){return typeof e=="string"&&Nb.test(e.trim())}function Gc(e){return`${e}-.bundle.min.mjs`}var Mb=".unversioned";function Fb(e,r,t="stable"){if(t==="canary")return`${e}-canary.bundle.min.mjs`;if(!wi(r))throw new Gr("invalid-version",`refusing to key the ${e} bundle cache on ${JSON.stringify(r??"")}: it would mint ${Gc(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 So(e){let{plugin:r,version:t,cacheDir:n,channel:o}=e;return tn(n,Fb(r,t,o))}function Wb(e){return e==="dev"?["rsp","redskilled"]:[]}function Ub(e){return`${e}.bundle.min.mjs`}function Bb(e){return tn("dist",Ub(e))}function Hb(e,r="stable"){return`${Ir}@${r==="canary"?Cb:e}`}function Ei(e=Ir){return`${$b}/${e.replace("/","%2F")}`}async function vi(e,r){let{plugin:t,version:n,cacheDir:o,channel:s="stable"}=r,i=So({plugin:t,version:n,cacheDir:o,channel:s}),a=Wb(t),l=a.map(m=>So({plugin:m,version:n,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await Vb(e,l))return i;let d=Hb(n,s),c=tn(o,`.staging-${t}-${s==="canary"?"canary":n}`),u;try{u=await e.materialize(d,c)}catch(m){throw Cc(m,d)}for(let m of[t,...a]){let f=Bb(m),h=tn(u,f);if(!await e.exists(h))throw new Gr("bundle-missing",`npm package ${d} has no ${f}`);let v=m===t?i:So({plugin:m,version:n,cacheDir:o,channel:s});await e.writeFile(v,await e.readFile(h))}return await qb(e,o,[t,...a]),i}async function qb(e,r,t){if(e.rename)for(let n of t){let o=tn(r,Gc(n));try{if(!await e.exists(o))continue;await e.rename(o,`${o}${Mb}`)}catch{}}}async function Vb(e,r){for(let t of r)if(!await e.exists(t))return!1;return!0}async function Ic(e,r,t=Ir){let n;try{n=await e.fetchText(Ei(t))}catch(s){throw Cc(s,t)}let o=Si(n);return{sameMajor:Kb(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 Kb(e,r){let t=Ri(r);if(t===null)return null;let n=null;for(let o of e)Ri(o)===t&&(n===null||$c(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||$c(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 $c(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 Cc(e,r){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Gr("npm-unavailable",`npm is unavailable while resolving ${r}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Gr("package-missing",`npm could not resolve ${r}: ${t}`,e):new Gr("network",`failed to resolve ${r}: ${t}`,e)}function tn(e,r){return e.endsWith("/")?`${e}${r}`:`${e}/${r}`}tr();var Mc={async materialize(e,r){await Nc(r,{recursive:!0});let t=zb("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",...Ir.split("/"))},async readFile(e){return new Uint8Array(await Zb(e))},async writeFile(e,r){await Nc(t_(e),{recursive:!0}),await r_(e,r)},async exists(e){return Yb(e)},sha256(e){return Qb("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 e_(e,r)}},n_="redskilled";function o_(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let r=e.XDG_CACHE_HOME||xi(e.HOME||Jb(),".cache");return xi(r,"red-skills","bundles")}var s_=/^([a-z0-9-]+)-(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?)\.bundle\.min\.mjs$/;async function i_(e,r){if(wi(e.version))return e.version.trim();let t=e.listCacheDir??d_,n=a_(t(r),"dev");if(n)return n;try{let s=await(e.bundleIO??Mc).fetchText(Ei());return Ti(Si(s))}catch{return null}}function a_(e,r){let t=null;for(let n of e){let o=s_.exec(n);if(!o||o[1]!==r)continue;let s=o[2];(t===null||l_(s,t)>0)&&(t=s)}return t}function l_(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 d_(e){try{return Xb(e)}catch{return[]}}async function c_(e={},r={},t={}){let n=ur(e,r);if(He(n))return n;let o=t.env??r.env??process.env,s=o_(o),i=await i_(t,s);if(i===null)return n;try{await vi(t.bundleIO??Mc,{plugin:n_,version:i,cacheDir:s})}catch{return n}return ur(e,r)}async function Fc(e={},r={},t={}){let n=await c_(e,r,t);if(He(n))return n;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(tr(),Lc));throw new o(n)}var dt=3e5,Wc=1e4,Uc=6e4,Bc=15e3,Pi=3e4,Hc=Pi*2,qc=6e4,nn=16;function Vc(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 Oi(e){let r=e?.match(/\bsession-error:\s*(.+)$/)?.[1]?.trim();return r==null||r===""?null:r}var Kc="no tracker transport was given to this daemon, so no queue depth was ever asked for";import{randomUUID as Xg}from"node:crypto";import{mkdir as _T,rm as RT}from"node:fs/promises";import{dirname as wT}from"node:path";import{randomUUID as Jc}from"node:crypto";import{rm as u_}from"node:fs/promises";import{connect as p_,createServer as m_}from"node:net";var qe=class extends Error{constructor(t,n){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=n;this.name="RedskilledAlreadyRunningError"}};async function Ai(e,r=250){return await new Promise(t=>{let n=p_(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 zc(e,r){for(let t=0;t<2;t++){let n=m_();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 Ai(e)!=="unowned")throw new qe(e);if(await r?.())throw new qe(e);await u_(e,{force:!0})}}throw new qe(e)}async function Ve(e,r=250){try{return(await _o({socketPath:e,timeoutMs:r},{id:Jc(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function Qc(e,r){Tc(e,(t,n)=>r(t,n),(t,n,o)=>{o({id:n?.id??Jc(),ok:!1,error:t instanceof Error?t.message:String(t)})})}import{availableParallelism as Zc,totalmem as f_}from"node:os";function on(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 Yc(e,r={}){let t=0,n=0,o=0,s=[],i=[];for(let d of e){let c=on(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=ct(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:g_(e.length,n,a,l)}}function g_(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 ct(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 Xc(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 eu="REDSKILLED_MEMORY_CEILING",ji="REDSKILLED_WORKER_CEILING",ou="REDSKILLED_VALIDATION_CEILING",ru="REDSKILLED_INTERACTIVE_RESERVATION",sn=1,tu=.7,h_=2*1024**3,y_=2;function su(e){let r=e?.memory_max??e?.memory_high;if(r!=null)return ct(r)}function xo(e){let r=0,t=[];for(let n of e){let o=su(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 iu(e){let{ceiling:r}=e,t=xo(e.workers),n=su(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??sn),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 au(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=xo(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 (${ji} is unset), so this ceiling is a per-Worker wall and not memory the host sets aside \u2014 N Workers may carry N such walls, and the host ceiling is not enforced host-wide. Declare a slot count to make it divide into shares that sum to it`:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes shared across its ${o} Worker slot(s)`;return{memory_max:String(i),reason:`derived from ${a} (ceiling source: ${e.ceiling.source})`}}function Po(e=process.env,r=f_(),t={}){let n=Di(t.flags?.memoryCeiling,e[eu],t.config?.memoryCeiling),o=Di(t.flags?.workerCeiling,e[ji],t.config?.workerCeiling),s=Di(t.flags?.validationCeiling,e[ou],t.config?.validationCeiling),i=n?.value??"",a=o?.value??"",l=(e[ru]??"").trim(),d=lu(a),c=l===""?sn:__(l),u=o?.source??"derived-default";if(a!==""&&d===null&&!k_(a)&&(To(`redskilled: ${Li(o)} ${ji}=${JSON.stringify(a)} is not a positive integer; this host admits an unbounded number of Workers instead.`),u="derived-default"),i!==""){let m=b_(i,r);if(m!==void 0)return nu({memory_bytes:m,worker_count:d,interactive_reservation:c??sn,source:"declared",memory_source:n.source,worker_source:u},s,t.availableParallelism??Zc());To(`redskilled: ${Li(n)} ${eu}=${JSON.stringify(i)} is not a memory ceiling this host can read; using ${tu*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return l!==""&&c===void 0&&To(`redskilled: ${ru}=${JSON.stringify(l)} is not a non-negative integer; using the default reservation of ${sn} Worker(s) instead.`),nu({memory_bytes:Math.floor(r*tu),worker_count:d,interactive_reservation:c??sn,memory_source:"derived-default",worker_source:u,source:"host-fraction"},s,t.availableParallelism??Zc())}function nu(e,r,t){if(r!==void 0){let i=lu(r.value);if(i!==null)return{...e,validation_count:i,validation_source:r.source};To(`redskilled: ${Li(r)} ${ou}=${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)/y_)),o=e.memory_bytes==null?Number.POSITIVE_INFINITY:Math.max(1,Math.floor(e.memory_bytes/h_)),s=e.worker_count??Number.POSITIVE_INFINITY;return{...e,validation_count:Math.max(1,Math.min(n,o,s)),validation_source:"derived-default"}}function Di(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 Li(e){return e.source==="flag"?"serve flag":e.source==="environment"?"environment":e.source==="home-config"?"home config":"derived default"}function k_(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var To=e=>process.stderr.write(`${e}
|
|
62
|
+
`);function b_(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)):ct(e)??void 0}function lu(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 __(e){let r=Number(e);return Number.isSafeInteger(r)&&r>=0?r:void 0}import{appendFile as R_,mkdir as w_,open as E_,readFile as v_,stat as S_,truncate as du}from"node:fs/promises";import{dirname as T_}from"node:path";var x_=["worker-birth","worker-activity","worker-drift","worker-heal","worker-death","worker-budget-kill"],P_=["demand-refusal","daemon-stop"],cu="redskilled.log.toonl";function Oo(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 O_="daemon:";function A_(e){return{version:1,ts:e.ts,kind:"daemon-stop",event:"daemon-stop",worker_id:`${O_}${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 D_(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 uu(e){let r=ye({trailer:!1}),t=Promise.resolve();async function n(o){let s=t.then(async()=>{await w_(T_(e),{recursive:!0,mode:448}),await j_(e),await R_(e,r.push($_(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>n(Oo(o)),recordWorker:o=>n(Oo(o)),recordDemandRefusal:o=>n(D_(o)),recordDaemonStop:o=>n(A_(o)),read:()=>L_(e),flush:async()=>{await t}}}async function j_(e){let r;try{r=(await S_(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(r===0)return;let t=64*1024,n=await E_(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 du(e,s-i+l+1);return}}await du(e,0)}finally{await n.close()}}async function L_(e){let r;try{r=await v_(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return G_(r)}function G_(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(C_).map(N_)}function pu(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,I_(t)):(t.kind==="worker-death"||t.kind==="worker-budget-kill")&&r.delete(t.worker_id));return[...r.values()]}function I_(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 $_(e){return{...e}}function C_(e){let r=e.kind??e.event;return e.version===1&&typeof e.ts=="string"&&typeof e.worker_id=="string"&&[...x_,...P_].includes(r)}function N_(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 mu(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 gu(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}function fu(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 an={shortLifeStreak:0,haltUntilMs:null,openedAtMs:null,probeWorkerId:null};function hu(e,r,t){if(r>=6e4)return an;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 yu(e,r){return e.haltUntilMs==null?e:{...e,probeWorkerId:r}}function Gi(){return an}function M_(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 ku(e,r){return Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>M_(t,n,r)).filter(t=>t!=null)}function _u(e){let r=e.workers.map(F_),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:U_({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:r.length,projects:t.length,surviving:n.length})}}function Ru(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 F_(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 W_(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 U_(e){let r=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${W_(e.reason)}`;return e.held===0?`${r}; it holds no Workers, so nothing survives the stop`:`${r}; it holds ${bu(e.held,"Worker")} across ${bu(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 bu(e,r){return`${e} ${r}${e===1?"":"s"}`}function Ii(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 B_,mkdir as H_,readFile as q_,rm as V_,writeFile as K_}from"node:fs/promises";import{dirname as wu,join as Tu}from"node:path";import{tmpdir as Eu}from"node:os";var J_="redskilled.machine.claim.toon",z_="REDSKILLED_MACHINE_DIR",Q_=8,pr=class extends Error{constructor(t,n,o){super(X_(t,n,o));this.claimPath=t;this.reason=n;this.claim=o;this.name="RedskilledMachineHeldError"}},vu;function xu(){return vu??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},vu}function Y_(e={machineIdHash:"unknown"}){let r=e.env??process.env,t=r[z_]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?r.PROGRAMDATA?.trim()||Eu():Eu();return Tu(o,`redskilled-${e.machineIdHash}`)}function Ao(e){return Tu(Y_(e),J_)}function Do(e,r,t={}){let n=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??re;async function s(){let l;try{l=await q_(e,"utf8")}catch(c){if(c.code==="ENOENT"||$i(c))return;throw c}let d=eR(l);return rR(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 V_(e,{force:!0}),!0}catch(l){if($i(l))return!1;throw l}}return{claimPath:e,read:s,async claim(l){await H_(wu(e),{recursive:!0,mode:1023})!=null&&await B_(wu(e),1023).catch(()=>{});let c=!1;for(let u=0;u<Q_;u+=1){let m=i(l,n());try{return await K_(e,Z_(m),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:c,claim:m}}catch(h){if(h.code!=="EEXIST"){if($i(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(Su(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||!Su(d,l,r.socketPath)?!1:await a()}}}function Pu(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 Ou(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 X_(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 $i(e){let r=e?.code;return r==="EACCES"||r==="EPERM"||r==="EROFS"}function Su(e,r,t){return e.pid===r.pid&&e.start_time===r.startTime&&e.socket_path===t}function Z_(e){return`${X(e,{keyedMapCollapse:!0})}
|
|
66
|
+
`}function eR(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return me(r)}catch{return null}}}function rR(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 tR=["worker_id","slot","workspace_path","log_path"],jo=class extends Error{constructor(t,n){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${n}: the facts a birth supplies are ${tR.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},Au=/\{\{([a-z_]+)\}\}/g;function nR(e,r){let t=(i,a)=>i.replace(Au,(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 jo(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 Du(e,r){if(!(e==null||e.trim()===""))return e.replace(Au,(t,n)=>{switch(n){case"worker_id":return r.worker_id;case"workspace_path":return r.workspace_path;default:throw new jo(n,"the log path")}})}function ju(e,r,t){let n=nR(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 Ci(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 Ni(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 Mi(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 oR=3e5,sR=.5,Fi=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 Lu(e,r){if(r.held!=null)throw new Fi(r.held);let t=ln(e.project_label,"a project label"),n=ln(e.selector,"a selector"),o=dR(e.queue_poll,t),s=Ci(e.argv,t),i=Mi(e.env,t),a=Ni(e.log_path,t),l=ln(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`),d=e.trunk==null?void 0:{remote:ln(e.trunk.remote,`a trunk remote for project ${JSON.stringify(t)}`),branch:ln(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??oR;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 $r=class extends Error{constructor(t,n={kind:"never"}){super(iR(t,n));this.projectLabel=t;this.absence=n;this.name="RedskilledProjectUnregisteredError"}};function iR(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 Gu(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:Ci(r.launch.argv,e.project_label),env:Mi(r.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=r.launch==null?e.log_path:Ni(r.launch.log_path,e.project_label),{log_path:i,...a}=e;return{...a,...s==null?{}:{log_path:s},...o,renew_within_ms:n,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+n).toISOString(),renewals:e.renewals+1,session_renewals:(e.session_renewals??e.renewals)+1}}function Wi(e,r){let t=Date.parse(r.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(r.now)}`);let n=JSON.stringify(e.project_label),o=Math.max(0,r.liveWorkers??0),s=r.queue,i=s!=null&&s.outcome==="counted"?s.depth:null,a=i!=null&&i>0?"open-work":o>0?"live-worker":null;if(a==null){let l=i===0?"drained":"uncounted";return{registration:e,verdict:l,detail:l==="drained"?`project ${n} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${n}, and an uncounted queue never sustains a registration \u2014 it stands on its own deadline of ${e.renew_by}`}}return{registration:{...e,renew_by:new Date(t+e.renew_within_ms).toISOString(),sustained_at:new Date(t).toISOString(),sustains:(e.sustains??0)+1,sustained_by:a,renewals:e.renewals+1,session_renewals:e.session_renewals??e.renewals},verdict:a,detail:a==="open-work"?`project ${n} has ${i} item(s) queued, so its registration stands past its window`:`project ${n} holds ${o} Worker(s), so its registration stands past its window`}}function aR(e,r){let t=Date.parse(e.renew_by);return Number.isFinite(t)?r>=t:!1}function Iu(e,r){let t=Date.parse(e.renewed_at??e.registered_at),n=s=>Number.isFinite(s)&&r-s<=e.renew_within_ms*sR;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 $u(e,r){let t=[],n=[];for(let o of e)(aR(o,r)?n:t).push(o);return{standing:t,lapsed:n}}function dn(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||Cu(r.queue_poll))&&Array.isArray(r.argv)&&r.argv.every(t=>typeof t=="string")&&typeof r.workspace_path=="string"&&(r.trunk===void 0||lR(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||cR(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 lR(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 dR(e,r){if(e!==void 0){if(!Cu(e))throw new Error(`redskilled needs a complete queue poll plan for project ${JSON.stringify(r)} when one is stated`);return e}}function Cu(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 cR(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(r=>typeof r=="string")}function ln(e,r){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${r} to register a project, not ${JSON.stringify(e)}`);return e}var uR={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 Nu(e){return`worker-${e}`}function Mu(e){let r=uR[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 Fu(e){return e==="single-object"?"rest":"graphql"}function Wu(e,r){return e==="stable-poll"?"rest":Fu(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??Wu(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 Uu=[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")],pR=new Map(Uu.map(e=>[e.key,e]));function Bu(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 Ui(e){let r=Bu(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 Lo=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(r){let t=Ui(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 Hu(e){return pR.get(Ui(e))??null}function qu(e){let r=Hu(e);if(!r)throw new Lo(e);return r}function Bi(e){return qu(e).surface}import{appendFile as mR,mkdir as gR,readFile as fR}from"node:fs/promises";import{dirname as hR}from"node:path";function Go(e){let r=e.now??(()=>new Date().toISOString()),t=Promise.resolve();return{record(n){let o=yR(n.operation,n.cost,n.observedAt??r(),n.actor),s=ye().push(bR(o));return t=t.then(async()=>{await gR(hR(e.path),{recursive:!0}),await mR(e.path,s,"utf8")}),t},async report(n){await t;let o=Hi(n.from,"report window start"),s=Hi(n.to,"report window end");if(s<=o)throw new Error("GitHub attribution report window end must be after its start");let i=await kR(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 yR(e,r,t,n){if(Hi(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 kR(e){let r;try{r=await fR(e,"utf8")}catch(s){if(wR(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(!_R(l)){n+=1,s+=1;continue}t.push(l),s+=1}return{observations:t,unreadable:n}}function bR(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 _R(e){return RR(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 Hi(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 RR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wR(e){return e instanceof Error&&"code"in e}var Ku=Ss(Ki(),1);var nr=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 ER="0.0.0-development";function vR(e){return e.request!==void 0}async function Vu(e,r,t,n){if(!vR(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 SR(e,r,t,n){let o=new Ku.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(TR.bind(null,e,r,t),n)}async function TR(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 nr(o.data.errors[0].message,500,{request:n,response:o});return Vu(e,r,s,n)}return o}function Ji(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",Vu.bind(null,t,n)),e.hook.wrap("request",SR.bind(null,t,n))),n}Ji.VERSION=ER;var zu=Ss(Ki(),1),xR="0.0.0-development",zi=()=>Promise.resolve();function PR(e,r,t){return e.retryLimiter.schedule(OR,e,r,t)}async function OR(e,r,t){let{pathname:n}=new URL(t.url,"http://github.test"),o=AR(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,zi),s&&e.triggersNotification(n)&&await e.notifications.key(e.id).schedule(d,zi),i&&await e.search.key(e.id).schedule(d,zi);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 AR(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 DR=["/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 jR(e){let t=`^(?:${e.map(n=>n.split("/").map(o=>o.startsWith("{")?"(?:.+?)":o).join("/")).map(n=>`(?:${n})`).join("|")})[^/]*$`;return new RegExp(t,"i")}var Ju=jR(DR),Qu=Ju.test.bind(Ju),je={},LR=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 Io(e,r){let{enabled:t=!0,Bottleneck:n=zu.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:Qu,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(
|
|
81
|
-
`+n.repeat(u)+
|
|
82
|
-
`+n.repeat(u)),c.push(h.isArray?"]":"}"),f.delete(h.val),m.pop())}return c.join("")},
|
|
79
|
+
`);let d=!1,c=()=>{if(d)return;d=!0,je.global==null&&LR(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(),PR(l,u,m))),{}}Io.VERSION=xR;Io.triggersNotification=Qu;function mr(){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 $o(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)=>$o.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 Yu(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 Xu(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 Zu=Function.bind,ep=Zu.bind(Zu);function rp(e,r,t){let n=ep(Xu,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]=ep(Yu,null).apply(null,s)})}function GR(){let e=Symbol("Singular"),r={registry:{}},t=$o.bind(null,r,e);return rp(t,r,e),t}function IR(){let e={registry:{}},r=$o.bind(null,e);return rp(r,e),r}var tp={Singular:GR,Collection:IR};var $R="0.0.0-development",CR=`octokit-endpoint.js/${$R} ${mr()}`,NR={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":CR},mediaType:{format:""}};function MR(e){return e?Object.keys(e).reduce((r,t)=>(r[t.toLowerCase()]=e[t],r),{}):{}}function FR(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 sp(e,r){let t=Object.assign({},e);return Object.keys(r).forEach(n=>{FR(r[n])?n in e?t[n]=sp(e[n],r[n]):Object.assign(t,{[n]:r[n]}):Object.assign(t,{[n]:r[n]})}),t}function np(e){for(let r in e)e[r]===void 0&&delete e[r];return e}function Yi(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=MR(t.headers),np(t),np(t.headers);let n=sp(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 WR(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 UR=/\{[^{}}]+\}/g;function BR(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function HR(e){let r=e.match(UR);return r?r.map(BR).reduce((t,n)=>t.concat(n),[]):[]}function op(e,r){let t={__proto__:null};for(let n of Object.keys(e))r.indexOf(n)===-1&&(t[n]=e[n]);return t}function ip(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 pt(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(r){return"%"+r.charCodeAt(0).toString(16).toUpperCase()})}function cn(e,r,t){return r=e==="+"||e==="#"?ip(r):pt(r),t?pt(t)+"="+r:r}function ut(e){return e!=null}function Qi(e){return e===";"||e==="&"||e==="?"}function qR(e,r,t,n){var o=e[t],s=[];if(ut(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(cn(r,o,Qi(r)?t:""));else if(n==="*")Array.isArray(o)?o.filter(ut).forEach(function(i){s.push(cn(r,i,Qi(r)?t:""))}):Object.keys(o).forEach(function(i){ut(o[i])&&s.push(cn(r,o[i],i))});else{let i=[];Array.isArray(o)?o.filter(ut).forEach(function(a){i.push(cn(r,a))}):Object.keys(o).forEach(function(a){ut(o[a])&&(i.push(pt(a)),i.push(cn(r,o[a].toString())))}),Qi(r)?s.push(pt(t)+"="+i.join(",")):i.length!==0&&s.push(i.join(","))}else r===";"?ut(o)&&s.push(pt(t)):o===""&&(r==="&"||r==="?")?s.push(pt(t)+"="):o===""&&s.push("");return s}function VR(e){return{expand:KR.bind(null,e)}}function KR(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(qR(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 ip(s)}),e==="/"?e:e.replace(/\/$/,"")}function ap(e){let r=e.method.toUpperCase(),t=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),n=Object.assign({},e.headers),o,s=op(e,["method","baseUrl","url","headers","request","mediaType"]),i=HR(t);t=VR(t).expand(s),/^http/.test(t)||(t=e.baseUrl+t);let a=Object.keys(e).filter(c=>i.includes(c)).concat("baseUrl"),l=op(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=WR(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 JR(e,r,t){return ap(Yi(e,r,t))}function lp(e,r){let t=Yi(e,r),n=JR.bind(null,t);return Object.assign(n,{DEFAULTS:t,defaults:lp.bind(null,t),merge:Yi.bind(null,t),parse:ap})}var dp=lp(null,NR);var xp=Ss(hp(),1);var ow=/^-?\d+$/,Mo=/^-?\d+n+$/,gr=JSON.stringify,ra=JSON.parse,Rp=/^-?\d+n$/,yp=/([\[:])?"(-?\d+)n"($|\s*[,\}\]])/g,kp=/([\[:])?("-?\d+n+)n("$|"\s*[,\}\]])/g,ta=e=>e===void 0||typeof e=="function"||typeof e=="symbol",na=e=>e!==null&&typeof e=="object"&&e.constructor&&e.constructor.name==="RawJSON",sw=(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"&&Mo.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(ta(a))return;let l=a===null||typeof a!="object",d=na(a);if(l||d)return gr(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(ta(T))c.push("null"),h.first=!1,h.index++;else{let I=T!==null&&typeof T=="object",F=na(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(gr(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(ta(G))continue;h.first||c.push(","),n?c.push(`
|
|
81
|
+
`+n.repeat(u)+gr(T)+": "):c.push(gr(T)+":");let H=G!==null&&typeof G=="object",ee=na(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(gr(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("")},wp=(e,r,t)=>{try{return"rawJSON"in JSON?gr(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?gr(e,(a,l)=>typeof l=="string"&&Mo.test(l)||typeof l=="bigint"?l.toString()+"n":typeof r=="function"?r(a,l):(Array.isArray(r)&&r.includes(a),l),t).replace(yp,"$1$2$3").replace(kp,"$1$2$3"):gr(e,r,t)}catch(n){if(n instanceof RangeError){let o=sw(e,r,t);return o===void 0?void 0:"rawJSON"in JSON?o:o.replace(yp,"$1$2$3").replace(kp,"$1$2$3")}throw n}},No=new Map,iw=()=>{let e=JSON.parse.toString();if(No.has(e))return No.get(e);try{let r=JSON.parse("1",(t,n,o)=>!!o?.source&&o.source==="1");return No.set(e,r),r}catch{return No.set(e,!1),!1}},aw=(e,r,t,n)=>typeof r=="string"&&Rp.test(r)?BigInt(r.slice(0,-1)):typeof r=="string"&&Mo.test(r)?r.slice(0,-1):typeof n=="function"?n(e,r,t):r,lw=(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&&ow.test(o.source);return a&&l?BigInt(o.source):typeof r=="function"?r(t,n,o):n}),Ep=Number.MAX_SAFE_INTEGER.toString(),bp=Ep.length,dw=/"(?:\\.|[^"])*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g,cw=/^"-?\d+n+"$/,uw=(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"&&(Rp.test(a)?a=BigInt(a.slice(0,-1)):Mo.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[""]},_p=e=>e.replace(dw,(r,t,n,o)=>{let s=r[0]==='"';if(s&&cw.test(r))return r.substring(0,r.length-1)+'n"';let a=n||o,l=t&&(t.length<bp||t.length===bp&&t<=Ep);return s||a||l?r:'"'+r+'n"'}),vp=(e,r)=>{if(!e)return ra(e,r);try{if(iw())return lw(e,r);let t=_p(e);return ra(t,(n,o,s)=>aw(n,o,s,r))}catch(t){if(t instanceof RangeError){let n=_p(e),o=ra(n);return uw(o,r)}throw t}};var pw="10.0.13",mw={headers:{"user-agent":`octokit-request.js/${pw} ${mr()}`}};function gw(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 Sp=()=>"";async function Tp(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=gw(e.body)||Array.isArray(e.body)?wp(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 nr(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 nr(i.statusText,a,{response:c,request:e})}if(a===304)throw c.data=await oa(i),new nr("Not modified",a,{response:c,request:e});if(a>=400)throw c.data=await oa(i),new nr(hw(c.data),a,{response:c,request:e});return c.data=n?await oa(i):i.body,c}async function oa(e){let r=e.headers.get("content-type");if(!r)return e.text().catch(Sp);let t=(0,xp.parse)(r);if(fw(t)){let n="";try{return n=await e.text(),vp(n)}catch{return n}}else return t.type.startsWith("text/")||t.parameters.charset?.toLowerCase()==="utf-8"&&t.type!=="application/octet-stream"?e.text().catch(Sp):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function fw(e){return e.type==="application/json"||e.type==="application/scim+json"}function hw(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 sa(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 Tp(t.parse(i));let a=(l,d)=>Tp(t.parse(t.merge(l,d)));return Object.assign(a,{endpoint:t,defaults:sa.bind(null,t)}),i.request.hook(a,i)},{endpoint:t,defaults:sa.bind(null,t)})}var un=sa(dp,mw);var yw="0.0.0-development";function kw(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 bw=class extends Error{constructor(e,r,t){super(kw(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},_w=["method","baseUrl","url","headers","request","query","mediaType","operationName"],Rw=["query","method","url"],Pp=/\/api\/v3\/?$/;function ww(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(Rw.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)=>_w.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 Pp.test(s)&&(o.url=s.replace(Pp,"/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 bw(o,a,i.data)}return i.data.data})}function ia(e,r){let t=e.defaults(r);return Object.assign((o,s)=>ww(t,o,s),{defaults:ia.bind(null,t),endpoint:t.endpoint})}var zD=ia(un,{headers:{"user-agent":`octokit-graphql.js/${yw} ${mr()}`},method:"POST",url:"/graphql"});function Op(e){return ia(e,{method:"POST",url:"/graphql"})}var aa="(?:[a-zA-Z0-9_-]+)",Ap="\\.",Dp=new RegExp(`^${aa}${Ap}${aa}${Ap}${aa}$`),Ew=Dp.test.bind(Dp);async function vw(e){let r=Ew(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 Sw(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function Tw(e,r,t,n){let o=r.endpoint.merge(t,n);return o.headers.authorization=Sw(e),r(o)}var jp=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(vw.bind(null,r),{hook:Tw.bind(null,r)})};var la="7.0.7";var Lp=()=>{},xw=console.warn.bind(console),Pw=console.error.bind(console);function Ow(e={}){return typeof e.debug!="function"&&(e.debug=Lp),typeof e.info!="function"&&(e.info=Lp),typeof e.warn!="function"&&(e.warn=xw),typeof e.error!="function"&&(e.error=Pw),e}var Gp=`octokit-core.js/${la} ${mr()}`,Fo=class{static VERSION=la;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 tp.Collection,n={baseUrl:un.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} ${Gp}`:Gp,r.baseUrl&&(n.baseUrl=r.baseUrl),r.previews&&(n.mediaType.previews=r.previews),r.timeZone&&(n.headers["time-zone"]=r.timeZone),this.request=un.defaults(n),this.graphql=Op(this.request).defaults(n),this.log=Ow(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=jp(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 Ip="6.0.0";function da(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})})}da.VERSION=Ip;var Aw="0.0.0-development";function Dw(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 ca(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=Dw(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 $p(e,r,t,n){return typeof t=="function"&&(n=t,t=void 0),Cp(e,[],ca(e,r,t)[Symbol.asyncIterator](),n)}function Cp(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:Cp(e,r,t,n)})}var pj=Object.assign($p,{iterator:ca});function ua(e){return{paginate:Object.assign($p.bind(null,e),{iterator:ca.bind(null,e)})}}ua.VERSION=Aw;var pa="17.0.0";var jw={actions:{addCustomLabelsToSelfHostedRunnerForOrg:["POST /orgs/{org}/actions/runners/{runner_id}/labels"],addCustomLabelsToSelfHostedRunnerForRepo:["POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],addRepoAccessToSelfHostedRunnerGroupInOrg:["PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}"],addSelectedRepoToOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],addSelectedRepoToOrgVariable:["PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"],approveWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"],cancelWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"],createEnvironmentVariable:["POST /repos/{owner}/{repo}/environments/{environment_name}/variables"],createHostedRunnerForOrg:["POST /orgs/{org}/actions/hosted-runners"],createOrUpdateEnvironmentSecret:["PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],createOrUpdateOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"],createOrgVariable:["POST /orgs/{org}/actions/variables"],createRegistrationTokenForOrg:["POST /orgs/{org}/actions/runners/registration-token"],createRegistrationTokenForRepo:["POST /repos/{owner}/{repo}/actions/runners/registration-token"],createRemoveTokenForOrg:["POST /orgs/{org}/actions/runners/remove-token"],createRemoveTokenForRepo:["POST /repos/{owner}/{repo}/actions/runners/remove-token"],createRepoVariable:["POST /repos/{owner}/{repo}/actions/variables"],createWorkflowDispatch:["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"],deleteActionsCacheById:["DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}"],deleteActionsCacheByKey:["DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}"],deleteArtifact:["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],deleteCustomImageFromOrg:["DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}"],deleteCustomImageVersionFromOrg:["DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}"],deleteEnvironmentSecret:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],deleteEnvironmentVariable:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],deleteHostedRunnerForOrg:["DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],deleteOrgSecret:["DELETE /orgs/{org}/actions/secrets/{secret_name}"],deleteOrgVariable:["DELETE /orgs/{org}/actions/variables/{name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"],deleteRepoVariable:["DELETE /repos/{owner}/{repo}/actions/variables/{name}"],deleteSelfHostedRunnerFromOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}"],deleteSelfHostedRunnerFromRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"],deleteWorkflowRun:["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],deleteWorkflowRunLogs:["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],disableSelectedRepositoryGithubActionsOrganization:["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"],disableWorkflow:["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"],downloadArtifact:["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"],downloadJobLogsForWorkflowRun:["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"],downloadWorkflowRunAttemptLogs:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"],downloadWorkflowRunLogs:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],enableSelectedRepositoryGithubActionsOrganization:["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"],enableWorkflow:["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"],forceCancelWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel"],generateRunnerJitconfigForOrg:["POST /orgs/{org}/actions/runners/generate-jitconfig"],generateRunnerJitconfigForRepo:["POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig"],getActionsCacheList:["GET /repos/{owner}/{repo}/actions/caches"],getActionsCacheUsage:["GET /repos/{owner}/{repo}/actions/cache/usage"],getActionsCacheUsageByRepoForOrg:["GET /orgs/{org}/actions/cache/usage-by-repository"],getActionsCacheUsageForOrg:["GET /orgs/{org}/actions/cache/usage"],getAllowedActionsOrganization:["GET /orgs/{org}/actions/permissions/selected-actions"],getAllowedActionsRepository:["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"],getArtifact:["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],getCustomImageForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}"],getCustomImageVersionForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}"],getCustomOidcSubClaimForRepo:["GET /repos/{owner}/{repo}/actions/oidc/customization/sub"],getEnvironmentPublicKey:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key"],getEnvironmentSecret:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],getEnvironmentVariable:["GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],getGithubActionsDefaultWorkflowPermissionsOrganization:["GET /orgs/{org}/actions/permissions/workflow"],getGithubActionsDefaultWorkflowPermissionsRepository:["GET /repos/{owner}/{repo}/actions/permissions/workflow"],getGithubActionsPermissionsOrganization:["GET /orgs/{org}/actions/permissions"],getGithubActionsPermissionsRepository:["GET /repos/{owner}/{repo}/actions/permissions"],getHostedRunnerForOrg:["GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],getHostedRunnersGithubOwnedImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/github-owned"],getHostedRunnersLimitsForOrg:["GET /orgs/{org}/actions/hosted-runners/limits"],getHostedRunnersMachineSpecsForOrg:["GET /orgs/{org}/actions/hosted-runners/machine-sizes"],getHostedRunnersPartnerImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/partner"],getHostedRunnersPlatformsForOrg:["GET /orgs/{org}/actions/hosted-runners/platforms"],getJobForWorkflowRun:["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],getOrgPublicKey:["GET /orgs/{org}/actions/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/actions/secrets/{secret_name}"],getOrgVariable:["GET /orgs/{org}/actions/variables/{name}"],getPendingDeploymentsForRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],getRepoPermissions:["GET /repos/{owner}/{repo}/actions/permissions",{},{renamed:["actions","getGithubActionsPermissionsRepository"]}],getRepoPublicKey:["GET /repos/{owner}/{repo}/actions/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],getRepoVariable:["GET /repos/{owner}/{repo}/actions/variables/{name}"],getReviewsForRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"],getSelfHostedRunnerForOrg:["GET /orgs/{org}/actions/runners/{runner_id}"],getSelfHostedRunnerForRepo:["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"],getWorkflow:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],getWorkflowAccessToRepository:["GET /repos/{owner}/{repo}/actions/permissions/access"],getWorkflowRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],getWorkflowRunAttempt:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"],getWorkflowRunUsage:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"],getWorkflowUsage:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"],listArtifactsForRepo:["GET /repos/{owner}/{repo}/actions/artifacts"],listCustomImageVersionsForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions"],listCustomImagesForOrg:["GET /orgs/{org}/actions/hosted-runners/images/custom"],listEnvironmentSecrets:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets"],listEnvironmentVariables:["GET /repos/{owner}/{repo}/environments/{environment_name}/variables"],listGithubHostedRunnersInGroupForOrg:["GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners"],listHostedRunnersForOrg:["GET /orgs/{org}/actions/hosted-runners"],listJobsForWorkflowRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"],listJobsForWorkflowRunAttempt:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"],listLabelsForSelfHostedRunnerForOrg:["GET /orgs/{org}/actions/runners/{runner_id}/labels"],listLabelsForSelfHostedRunnerForRepo:["GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],listOrgSecrets:["GET /orgs/{org}/actions/secrets"],listOrgVariables:["GET /orgs/{org}/actions/variables"],listRepoOrganizationSecrets:["GET /repos/{owner}/{repo}/actions/organization-secrets"],listRepoOrganizationVariables:["GET /repos/{owner}/{repo}/actions/organization-variables"],listRepoSecrets:["GET /repos/{owner}/{repo}/actions/secrets"],listRepoVariables:["GET /repos/{owner}/{repo}/actions/variables"],listRepoWorkflows:["GET /repos/{owner}/{repo}/actions/workflows"],listRunnerApplicationsForOrg:["GET /orgs/{org}/actions/runners/downloads"],listRunnerApplicationsForRepo:["GET /repos/{owner}/{repo}/actions/runners/downloads"],listSelectedReposForOrgSecret:["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"],listSelectedReposForOrgVariable:["GET /orgs/{org}/actions/variables/{name}/repositories"],listSelectedRepositoriesEnabledGithubActionsOrganization:["GET /orgs/{org}/actions/permissions/repositories"],listSelfHostedRunnersForOrg:["GET /orgs/{org}/actions/runners"],listSelfHostedRunnersForRepo:["GET /repos/{owner}/{repo}/actions/runners"],listWorkflowRunArtifacts:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"],listWorkflowRuns:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"],listWorkflowRunsForRepo:["GET /repos/{owner}/{repo}/actions/runs"],reRunJobForWorkflowRun:["POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun"],reRunWorkflow:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],reRunWorkflowFailedJobs:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs"],removeAllCustomLabelsFromSelfHostedRunnerForOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}/labels"],removeAllCustomLabelsFromSelfHostedRunnerForRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],removeCustomLabelFromSelfHostedRunnerForOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}"],removeCustomLabelFromSelfHostedRunnerForRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],removeSelectedRepoFromOrgVariable:["DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"],reviewCustomGatesForRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule"],reviewPendingDeploymentsForRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],setAllowedActionsOrganization:["PUT /orgs/{org}/actions/permissions/selected-actions"],setAllowedActionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"],setCustomLabelsForSelfHostedRunnerForOrg:["PUT /orgs/{org}/actions/runners/{runner_id}/labels"],setCustomLabelsForSelfHostedRunnerForRepo:["PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],setCustomOidcSubClaimForRepo:["PUT /repos/{owner}/{repo}/actions/oidc/customization/sub"],setGithubActionsDefaultWorkflowPermissionsOrganization:["PUT /orgs/{org}/actions/permissions/workflow"],setGithubActionsDefaultWorkflowPermissionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions/workflow"],setGithubActionsPermissionsOrganization:["PUT /orgs/{org}/actions/permissions"],setGithubActionsPermissionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"],setSelectedReposForOrgVariable:["PUT /orgs/{org}/actions/variables/{name}/repositories"],setSelectedRepositoriesEnabledGithubActionsOrganization:["PUT /orgs/{org}/actions/permissions/repositories"],setWorkflowAccessToRepository:["PUT /repos/{owner}/{repo}/actions/permissions/access"],updateEnvironmentVariable:["PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],updateHostedRunnerForOrg:["PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}"],updateOrgVariable:["PATCH /orgs/{org}/actions/variables/{name}"],updateRepoVariable:["PATCH /repos/{owner}/{repo}/actions/variables/{name}"]},activity:{checkRepoIsStarredByAuthenticatedUser:["GET /user/starred/{owner}/{repo}"],deleteRepoSubscription:["DELETE /repos/{owner}/{repo}/subscription"],deleteThreadSubscription:["DELETE /notifications/threads/{thread_id}/subscription"],getFeeds:["GET /feeds"],getRepoSubscription:["GET /repos/{owner}/{repo}/subscription"],getThread:["GET /notifications/threads/{thread_id}"],getThreadSubscriptionForAuthenticatedUser:["GET /notifications/threads/{thread_id}/subscription"],listEventsForAuthenticatedUser:["GET /users/{username}/events"],listNotificationsForAuthenticatedUser:["GET /notifications"],listOrgEventsForAuthenticatedUser:["GET /users/{username}/events/orgs/{org}"],listPublicEvents:["GET /events"],listPublicEventsForRepoNetwork:["GET /networks/{owner}/{repo}/events"],listPublicEventsForUser:["GET /users/{username}/events/public"],listPublicOrgEvents:["GET /orgs/{org}/events"],listReceivedEventsForUser:["GET /users/{username}/received_events"],listReceivedPublicEventsForUser:["GET /users/{username}/received_events/public"],listRepoEvents:["GET /repos/{owner}/{repo}/events"],listRepoNotificationsForAuthenticatedUser:["GET /repos/{owner}/{repo}/notifications"],listReposStarredByAuthenticatedUser:["GET /user/starred"],listReposStarredByUser:["GET /users/{username}/starred"],listReposWatchedByUser:["GET /users/{username}/subscriptions"],listStargazersForRepo:["GET /repos/{owner}/{repo}/stargazers"],listWatchedReposForAuthenticatedUser:["GET /user/subscriptions"],listWatchersForRepo:["GET /repos/{owner}/{repo}/subscribers"],markNotificationsAsRead:["PUT /notifications"],markRepoNotificationsAsRead:["PUT /repos/{owner}/{repo}/notifications"],markThreadAsDone:["DELETE /notifications/threads/{thread_id}"],markThreadAsRead:["PATCH /notifications/threads/{thread_id}"],setRepoSubscription:["PUT /repos/{owner}/{repo}/subscription"],setThreadSubscription:["PUT /notifications/threads/{thread_id}/subscription"],starRepoForAuthenticatedUser:["PUT /user/starred/{owner}/{repo}"],unstarRepoForAuthenticatedUser:["DELETE /user/starred/{owner}/{repo}"]},apps:{addRepoToInstallation:["PUT /user/installations/{installation_id}/repositories/{repository_id}",{},{renamed:["apps","addRepoToInstallationForAuthenticatedUser"]}],addRepoToInstallationForAuthenticatedUser:["PUT /user/installations/{installation_id}/repositories/{repository_id}"],checkToken:["POST /applications/{client_id}/token"],createFromManifest:["POST /app-manifests/{code}/conversions"],createInstallationAccessToken:["POST /app/installations/{installation_id}/access_tokens"],deleteAuthorization:["DELETE /applications/{client_id}/grant"],deleteInstallation:["DELETE /app/installations/{installation_id}"],deleteToken:["DELETE /applications/{client_id}/token"],getAuthenticated:["GET /app"],getBySlug:["GET /apps/{app_slug}"],getInstallation:["GET /app/installations/{installation_id}"],getOrgInstallation:["GET /orgs/{org}/installation"],getRepoInstallation:["GET /repos/{owner}/{repo}/installation"],getSubscriptionPlanForAccount:["GET /marketplace_listing/accounts/{account_id}"],getSubscriptionPlanForAccountStubbed:["GET /marketplace_listing/stubbed/accounts/{account_id}"],getUserInstallation:["GET /users/{username}/installation"],getWebhookConfigForApp:["GET /app/hook/config"],getWebhookDelivery:["GET /app/hook/deliveries/{delivery_id}"],listAccountsForPlan:["GET /marketplace_listing/plans/{plan_id}/accounts"],listAccountsForPlanStubbed:["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"],listInstallationReposForAuthenticatedUser:["GET /user/installations/{installation_id}/repositories"],listInstallationRequestsForAuthenticatedApp:["GET /app/installation-requests"],listInstallations:["GET /app/installations"],listInstallationsForAuthenticatedUser:["GET /user/installations"],listPlans:["GET /marketplace_listing/plans"],listPlansStubbed:["GET /marketplace_listing/stubbed/plans"],listReposAccessibleToInstallation:["GET /installation/repositories"],listSubscriptionsForAuthenticatedUser:["GET /user/marketplace_purchases"],listSubscriptionsForAuthenticatedUserStubbed:["GET /user/marketplace_purchases/stubbed"],listWebhookDeliveries:["GET /app/hook/deliveries"],redeliverWebhookDelivery:["POST /app/hook/deliveries/{delivery_id}/attempts"],removeRepoFromInstallation:["DELETE /user/installations/{installation_id}/repositories/{repository_id}",{},{renamed:["apps","removeRepoFromInstallationForAuthenticatedUser"]}],removeRepoFromInstallationForAuthenticatedUser:["DELETE /user/installations/{installation_id}/repositories/{repository_id}"],resetToken:["PATCH /applications/{client_id}/token"],revokeInstallationAccessToken:["DELETE /installation/token"],scopeToken:["POST /applications/{client_id}/token/scoped"],suspendInstallation:["PUT /app/installations/{installation_id}/suspended"],unsuspendInstallation:["DELETE /app/installations/{installation_id}/suspended"],updateWebhookConfigForApp:["PATCH /app/hook/config"]},billing:{getGithubActionsBillingOrg:["GET /orgs/{org}/settings/billing/actions"],getGithubActionsBillingUser:["GET /users/{username}/settings/billing/actions"],getGithubBillingPremiumRequestUsageReportOrg:["GET /organizations/{org}/settings/billing/premium_request/usage"],getGithubBillingPremiumRequestUsageReportUser:["GET /users/{username}/settings/billing/premium_request/usage"],getGithubBillingUsageReportOrg:["GET /organizations/{org}/settings/billing/usage"],getGithubBillingUsageReportUser:["GET /users/{username}/settings/billing/usage"],getGithubPackagesBillingOrg:["GET /orgs/{org}/settings/billing/packages"],getGithubPackagesBillingUser:["GET /users/{username}/settings/billing/packages"],getSharedStorageBillingOrg:["GET /orgs/{org}/settings/billing/shared-storage"],getSharedStorageBillingUser:["GET /users/{username}/settings/billing/shared-storage"]},campaigns:{createCampaign:["POST /orgs/{org}/campaigns"],deleteCampaign:["DELETE /orgs/{org}/campaigns/{campaign_number}"],getCampaignSummary:["GET /orgs/{org}/campaigns/{campaign_number}"],listOrgCampaigns:["GET /orgs/{org}/campaigns"],updateCampaign:["PATCH /orgs/{org}/campaigns/{campaign_number}"]},checks:{create:["POST /repos/{owner}/{repo}/check-runs"],createSuite:["POST /repos/{owner}/{repo}/check-suites"],get:["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"],getSuite:["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"],listAnnotations:["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"],listForRef:["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"],listForSuite:["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"],listSuitesForRef:["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"],rerequestRun:["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"],rerequestSuite:["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"],setSuitesPreferences:["PATCH /repos/{owner}/{repo}/check-suites/preferences"],update:["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]},codeScanning:{commitAutofix:["POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits"],createAutofix:["POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"],createVariantAnalysis:["POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses"],deleteAnalysis:["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"],deleteCodeqlDatabase:["DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"],getAlert:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}",{},{renamedParameters:{alert_id:"alert_number"}}],getAnalysis:["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"],getAutofix:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"],getCodeqlDatabase:["GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"],getDefaultSetup:["GET /repos/{owner}/{repo}/code-scanning/default-setup"],getSarif:["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],getVariantAnalysis:["GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}"],getVariantAnalysisRepoTask:["GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}"],listAlertInstances:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"],listAlertsForOrg:["GET /orgs/{org}/code-scanning/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/code-scanning/alerts"],listAlertsInstances:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",{},{renamed:["codeScanning","listAlertInstances"]}],listCodeqlDatabases:["GET /repos/{owner}/{repo}/code-scanning/codeql/databases"],listRecentAnalyses:["GET /repos/{owner}/{repo}/code-scanning/analyses"],updateAlert:["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"],updateDefaultSetup:["PATCH /repos/{owner}/{repo}/code-scanning/default-setup"],uploadSarif:["POST /repos/{owner}/{repo}/code-scanning/sarifs"]},codeSecurity:{attachConfiguration:["POST /orgs/{org}/code-security/configurations/{configuration_id}/attach"],attachEnterpriseConfiguration:["POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach"],createConfiguration:["POST /orgs/{org}/code-security/configurations"],createConfigurationForEnterprise:["POST /enterprises/{enterprise}/code-security/configurations"],deleteConfiguration:["DELETE /orgs/{org}/code-security/configurations/{configuration_id}"],deleteConfigurationForEnterprise:["DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}"],detachConfiguration:["DELETE /orgs/{org}/code-security/configurations/detach"],getConfiguration:["GET /orgs/{org}/code-security/configurations/{configuration_id}"],getConfigurationForRepository:["GET /repos/{owner}/{repo}/code-security-configuration"],getConfigurationsForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations"],getConfigurationsForOrg:["GET /orgs/{org}/code-security/configurations"],getDefaultConfigurations:["GET /orgs/{org}/code-security/configurations/defaults"],getDefaultConfigurationsForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations/defaults"],getRepositoriesForConfiguration:["GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories"],getRepositoriesForEnterpriseConfiguration:["GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories"],getSingleConfigurationForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}"],setConfigurationAsDefault:["PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults"],setConfigurationAsDefaultForEnterprise:["PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults"],updateConfiguration:["PATCH /orgs/{org}/code-security/configurations/{configuration_id}"],updateEnterpriseConfiguration:["PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}"]},codesOfConduct:{getAllCodesOfConduct:["GET /codes_of_conduct"],getConductCode:["GET /codes_of_conduct/{key}"]},codespaces:{addRepositoryForSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],addSelectedRepoToOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"],checkPermissionsForDevcontainer:["GET /repos/{owner}/{repo}/codespaces/permissions_check"],codespaceMachinesForAuthenticatedUser:["GET /user/codespaces/{codespace_name}/machines"],createForAuthenticatedUser:["POST /user/codespaces"],createOrUpdateOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],createOrUpdateSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}"],createWithPrForAuthenticatedUser:["POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces"],createWithRepoForAuthenticatedUser:["POST /repos/{owner}/{repo}/codespaces"],deleteForAuthenticatedUser:["DELETE /user/codespaces/{codespace_name}"],deleteFromOrganization:["DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}"],deleteOrgSecret:["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],deleteSecretForAuthenticatedUser:["DELETE /user/codespaces/secrets/{secret_name}"],exportForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/exports"],getCodespacesForUserInOrg:["GET /orgs/{org}/members/{username}/codespaces"],getExportDetailsForAuthenticatedUser:["GET /user/codespaces/{codespace_name}/exports/{export_id}"],getForAuthenticatedUser:["GET /user/codespaces/{codespace_name}"],getOrgPublicKey:["GET /orgs/{org}/codespaces/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/codespaces/secrets/{secret_name}"],getPublicKeyForAuthenticatedUser:["GET /user/codespaces/secrets/public-key"],getRepoPublicKey:["GET /repos/{owner}/{repo}/codespaces/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],getSecretForAuthenticatedUser:["GET /user/codespaces/secrets/{secret_name}"],listDevcontainersInRepositoryForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/devcontainers"],listForAuthenticatedUser:["GET /user/codespaces"],listInOrganization:["GET /orgs/{org}/codespaces",{},{renamedParameters:{org_id:"org"}}],listInRepositoryForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces"],listOrgSecrets:["GET /orgs/{org}/codespaces/secrets"],listRepoSecrets:["GET /repos/{owner}/{repo}/codespaces/secrets"],listRepositoriesForSecretForAuthenticatedUser:["GET /user/codespaces/secrets/{secret_name}/repositories"],listSecretsForAuthenticatedUser:["GET /user/codespaces/secrets"],listSelectedReposForOrgSecret:["GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories"],preFlightWithRepoForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/new"],publishForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/publish"],removeRepositoryForSecretForAuthenticatedUser:["DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"],repoMachinesForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/machines"],setRepositoriesForSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}/repositories"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories"],startForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/start"],stopForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/stop"],stopInOrganization:["POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop"],updateForAuthenticatedUser:["PATCH /user/codespaces/{codespace_name}"]},copilot:{addCopilotSeatsForTeams:["POST /orgs/{org}/copilot/billing/selected_teams"],addCopilotSeatsForUsers:["POST /orgs/{org}/copilot/billing/selected_users"],cancelCopilotSeatAssignmentForTeams:["DELETE /orgs/{org}/copilot/billing/selected_teams"],cancelCopilotSeatAssignmentForUsers:["DELETE /orgs/{org}/copilot/billing/selected_users"],copilotMetricsForOrganization:["GET /orgs/{org}/copilot/metrics"],copilotMetricsForTeam:["GET /orgs/{org}/team/{team_slug}/copilot/metrics"],getCopilotOrganizationDetails:["GET /orgs/{org}/copilot/billing"],getCopilotSeatDetailsForUser:["GET /orgs/{org}/members/{username}/copilot"],listCopilotSeats:["GET /orgs/{org}/copilot/billing/seats"]},credentials:{revoke:["POST /credentials/revoke"]},dependabot:{addSelectedRepoToOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],createOrUpdateOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],deleteOrgSecret:["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],getAlert:["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],getOrgPublicKey:["GET /orgs/{org}/dependabot/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/dependabot/secrets/{secret_name}"],getRepoPublicKey:["GET /repos/{owner}/{repo}/dependabot/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],listAlertsForEnterprise:["GET /enterprises/{enterprise}/dependabot/alerts"],listAlertsForOrg:["GET /orgs/{org}/dependabot/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/dependabot/alerts"],listOrgSecrets:["GET /orgs/{org}/dependabot/secrets"],listRepoSecrets:["GET /repos/{owner}/{repo}/dependabot/secrets"],listSelectedReposForOrgSecret:["GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],repositoryAccessForOrg:["GET /organizations/{org}/dependabot/repository-access"],setRepositoryAccessDefaultLevel:["PUT /organizations/{org}/dependabot/repository-access/default-level"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],updateAlert:["PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],updateRepositoryAccessForOrg:["PATCH /organizations/{org}/dependabot/repository-access"]},dependencyGraph:{createRepositorySnapshot:["POST /repos/{owner}/{repo}/dependency-graph/snapshots"],diffRange:["GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}"],exportSbom:["GET /repos/{owner}/{repo}/dependency-graph/sbom"]},emojis:{get:["GET /emojis"]},enterpriseTeamMemberships:{add:["PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"],bulkAdd:["POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add"],bulkRemove:["POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove"],get:["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"],list:["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships"],remove:["DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}"]},enterpriseTeamOrganizations:{add:["PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],bulkAdd:["POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add"],bulkRemove:["POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove"],delete:["DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],getAssignment:["GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}"],getAssignments:["GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations"]},enterpriseTeams:{create:["POST /enterprises/{enterprise}/teams"],delete:["DELETE /enterprises/{enterprise}/teams/{team_slug}"],get:["GET /enterprises/{enterprise}/teams/{team_slug}"],list:["GET /enterprises/{enterprise}/teams"],update:["PATCH /enterprises/{enterprise}/teams/{team_slug}"]},gists:{checkIsStarred:["GET /gists/{gist_id}/star"],create:["POST /gists"],createComment:["POST /gists/{gist_id}/comments"],delete:["DELETE /gists/{gist_id}"],deleteComment:["DELETE /gists/{gist_id}/comments/{comment_id}"],fork:["POST /gists/{gist_id}/forks"],get:["GET /gists/{gist_id}"],getComment:["GET /gists/{gist_id}/comments/{comment_id}"],getRevision:["GET /gists/{gist_id}/{sha}"],list:["GET /gists"],listComments:["GET /gists/{gist_id}/comments"],listCommits:["GET /gists/{gist_id}/commits"],listForUser:["GET /users/{username}/gists"],listForks:["GET /gists/{gist_id}/forks"],listPublic:["GET /gists/public"],listStarred:["GET /gists/starred"],star:["PUT /gists/{gist_id}/star"],unstar:["DELETE /gists/{gist_id}/star"],update:["PATCH /gists/{gist_id}"],updateComment:["PATCH /gists/{gist_id}/comments/{comment_id}"]},git:{createBlob:["POST /repos/{owner}/{repo}/git/blobs"],createCommit:["POST /repos/{owner}/{repo}/git/commits"],createRef:["POST /repos/{owner}/{repo}/git/refs"],createTag:["POST /repos/{owner}/{repo}/git/tags"],createTree:["POST /repos/{owner}/{repo}/git/trees"],deleteRef:["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],getBlob:["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],getCommit:["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],getRef:["GET /repos/{owner}/{repo}/git/ref/{ref}"],getTag:["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],getTree:["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],listMatchingRefs:["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],updateRef:["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]},gitignore:{getAllTemplates:["GET /gitignore/templates"],getTemplate:["GET /gitignore/templates/{name}"]},hostedCompute:{createNetworkConfigurationForOrg:["POST /orgs/{org}/settings/network-configurations"],deleteNetworkConfigurationFromOrg:["DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}"],getNetworkConfigurationForOrg:["GET /orgs/{org}/settings/network-configurations/{network_configuration_id}"],getNetworkSettingsForOrg:["GET /orgs/{org}/settings/network-settings/{network_settings_id}"],listNetworkConfigurationsForOrg:["GET /orgs/{org}/settings/network-configurations"],updateNetworkConfigurationForOrg:["PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}"]},interactions:{getRestrictionsForAuthenticatedUser:["GET /user/interaction-limits"],getRestrictionsForOrg:["GET /orgs/{org}/interaction-limits"],getRestrictionsForRepo:["GET /repos/{owner}/{repo}/interaction-limits"],getRestrictionsForYourPublicRepos:["GET /user/interaction-limits",{},{renamed:["interactions","getRestrictionsForAuthenticatedUser"]}],removeRestrictionsForAuthenticatedUser:["DELETE /user/interaction-limits"],removeRestrictionsForOrg:["DELETE /orgs/{org}/interaction-limits"],removeRestrictionsForRepo:["DELETE /repos/{owner}/{repo}/interaction-limits"],removeRestrictionsForYourPublicRepos:["DELETE /user/interaction-limits",{},{renamed:["interactions","removeRestrictionsForAuthenticatedUser"]}],setRestrictionsForAuthenticatedUser:["PUT /user/interaction-limits"],setRestrictionsForOrg:["PUT /orgs/{org}/interaction-limits"],setRestrictionsForRepo:["PUT /repos/{owner}/{repo}/interaction-limits"],setRestrictionsForYourPublicRepos:["PUT /user/interaction-limits",{},{renamed:["interactions","setRestrictionsForAuthenticatedUser"]}]},issues:{addAssignees:["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"],addBlockedByDependency:["POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by"],addLabels:["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],addSubIssue:["POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"],checkUserCanBeAssigned:["GET /repos/{owner}/{repo}/assignees/{assignee}"],checkUserCanBeAssignedToIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}"],create:["POST /repos/{owner}/{repo}/issues"],createComment:["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"],createLabel:["POST /repos/{owner}/{repo}/labels"],createMilestone:["POST /repos/{owner}/{repo}/milestones"],deleteComment:["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"],deleteLabel:["DELETE /repos/{owner}/{repo}/labels/{name}"],deleteMilestone:["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"],get:["GET /repos/{owner}/{repo}/issues/{issue_number}"],getComment:["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],getEvent:["GET /repos/{owner}/{repo}/issues/events/{event_id}"],getLabel:["GET /repos/{owner}/{repo}/labels/{name}"],getMilestone:["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],getParent:["GET /repos/{owner}/{repo}/issues/{issue_number}/parent"],list:["GET /issues"],listAssignees:["GET /repos/{owner}/{repo}/assignees"],listComments:["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],listCommentsForRepo:["GET /repos/{owner}/{repo}/issues/comments"],listDependenciesBlockedBy:["GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by"],listDependenciesBlocking:["GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking"],listEvents:["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],listEventsForRepo:["GET /repos/{owner}/{repo}/issues/events"],listEventsForTimeline:["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"],listForAuthenticatedUser:["GET /user/issues"],listForOrg:["GET /orgs/{org}/issues"],listForRepo:["GET /repos/{owner}/{repo}/issues"],listLabelsForMilestone:["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"],listLabelsForRepo:["GET /repos/{owner}/{repo}/labels"],listLabelsOnIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"],listMilestones:["GET /repos/{owner}/{repo}/milestones"],listSubIssues:["GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"],lock:["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],removeAllLabels:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"],removeAssignees:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"],removeDependencyBlockedBy:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}"],removeLabel:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"],removeSubIssue:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue"],reprioritizeSubIssue:["PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority"],setLabels:["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],unlock:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],update:["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],updateComment:["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],updateLabel:["PATCH /repos/{owner}/{repo}/labels/{name}"],updateMilestone:["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"]},licenses:{get:["GET /licenses/{license}"],getAllCommonlyUsed:["GET /licenses"],getForRepo:["GET /repos/{owner}/{repo}/license"]},markdown:{render:["POST /markdown"],renderRaw:["POST /markdown/raw",{headers:{"content-type":"text/plain; charset=utf-8"}}]},meta:{get:["GET /meta"],getAllVersions:["GET /versions"],getOctocat:["GET /octocat"],getZen:["GET /zen"],root:["GET /"]},migrations:{deleteArchiveForAuthenticatedUser:["DELETE /user/migrations/{migration_id}/archive"],deleteArchiveForOrg:["DELETE /orgs/{org}/migrations/{migration_id}/archive"],downloadArchiveForOrg:["GET /orgs/{org}/migrations/{migration_id}/archive"],getArchiveForAuthenticatedUser:["GET /user/migrations/{migration_id}/archive"],getStatusForAuthenticatedUser:["GET /user/migrations/{migration_id}"],getStatusForOrg:["GET /orgs/{org}/migrations/{migration_id}"],listForAuthenticatedUser:["GET /user/migrations"],listForOrg:["GET /orgs/{org}/migrations"],listReposForAuthenticatedUser:["GET /user/migrations/{migration_id}/repositories"],listReposForOrg:["GET /orgs/{org}/migrations/{migration_id}/repositories"],listReposForUser:["GET /user/migrations/{migration_id}/repositories",{},{renamed:["migrations","listReposForAuthenticatedUser"]}],startForAuthenticatedUser:["POST /user/migrations"],startForOrg:["POST /orgs/{org}/migrations"],unlockRepoForAuthenticatedUser:["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"],unlockRepoForOrg:["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"]},oidc:{getOidcCustomSubTemplateForOrg:["GET /orgs/{org}/actions/oidc/customization/sub"],updateOidcCustomSubTemplateForOrg:["PUT /orgs/{org}/actions/oidc/customization/sub"]},orgs:{addSecurityManagerTeam:["PUT /orgs/{org}/security-managers/teams/{team_slug}",{},{deprecated:"octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team"}],assignTeamToOrgRole:["PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"],assignUserToOrgRole:["PUT /orgs/{org}/organization-roles/users/{username}/{role_id}"],blockUser:["PUT /orgs/{org}/blocks/{username}"],cancelInvitation:["DELETE /orgs/{org}/invitations/{invitation_id}"],checkBlockedUser:["GET /orgs/{org}/blocks/{username}"],checkMembershipForUser:["GET /orgs/{org}/members/{username}"],checkPublicMembershipForUser:["GET /orgs/{org}/public_members/{username}"],convertMemberToOutsideCollaborator:["PUT /orgs/{org}/outside_collaborators/{username}"],createArtifactStorageRecord:["POST /orgs/{org}/artifacts/metadata/storage-record"],createInvitation:["POST /orgs/{org}/invitations"],createIssueType:["POST /orgs/{org}/issue-types"],createWebhook:["POST /orgs/{org}/hooks"],customPropertiesForOrgsCreateOrUpdateOrganizationValues:["PATCH /organizations/{org}/org-properties/values"],customPropertiesForOrgsGetOrganizationValues:["GET /organizations/{org}/org-properties/values"],customPropertiesForReposCreateOrUpdateOrganizationDefinition:["PUT /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposCreateOrUpdateOrganizationDefinitions:["PATCH /orgs/{org}/properties/schema"],customPropertiesForReposCreateOrUpdateOrganizationValues:["PATCH /orgs/{org}/properties/values"],customPropertiesForReposDeleteOrganizationDefinition:["DELETE /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposGetOrganizationDefinition:["GET /orgs/{org}/properties/schema/{custom_property_name}"],customPropertiesForReposGetOrganizationDefinitions:["GET /orgs/{org}/properties/schema"],customPropertiesForReposGetOrganizationValues:["GET /orgs/{org}/properties/values"],delete:["DELETE /orgs/{org}"],deleteAttestationsBulk:["POST /orgs/{org}/attestations/delete-request"],deleteAttestationsById:["DELETE /orgs/{org}/attestations/{attestation_id}"],deleteAttestationsBySubjectDigest:["DELETE /orgs/{org}/attestations/digest/{subject_digest}"],deleteIssueType:["DELETE /orgs/{org}/issue-types/{issue_type_id}"],deleteWebhook:["DELETE /orgs/{org}/hooks/{hook_id}"],disableSelectedRepositoryImmutableReleasesOrganization:["DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}"],enableSelectedRepositoryImmutableReleasesOrganization:["PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}"],get:["GET /orgs/{org}"],getImmutableReleasesSettings:["GET /orgs/{org}/settings/immutable-releases"],getImmutableReleasesSettingsRepositories:["GET /orgs/{org}/settings/immutable-releases/repositories"],getMembershipForAuthenticatedUser:["GET /user/memberships/orgs/{org}"],getMembershipForUser:["GET /orgs/{org}/memberships/{username}"],getOrgRole:["GET /orgs/{org}/organization-roles/{role_id}"],getOrgRulesetHistory:["GET /orgs/{org}/rulesets/{ruleset_id}/history"],getOrgRulesetVersion:["GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}"],getWebhook:["GET /orgs/{org}/hooks/{hook_id}"],getWebhookConfigForOrg:["GET /orgs/{org}/hooks/{hook_id}/config"],getWebhookDelivery:["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"],list:["GET /organizations"],listAppInstallations:["GET /orgs/{org}/installations"],listArtifactStorageRecords:["GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records"],listAttestationRepositories:["GET /orgs/{org}/attestations/repositories"],listAttestations:["GET /orgs/{org}/attestations/{subject_digest}"],listAttestationsBulk:["POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}"],listBlockedUsers:["GET /orgs/{org}/blocks"],listFailedInvitations:["GET /orgs/{org}/failed_invitations"],listForAuthenticatedUser:["GET /user/orgs"],listForUser:["GET /users/{username}/orgs"],listInvitationTeams:["GET /orgs/{org}/invitations/{invitation_id}/teams"],listIssueTypes:["GET /orgs/{org}/issue-types"],listMembers:["GET /orgs/{org}/members"],listMembershipsForAuthenticatedUser:["GET /user/memberships/orgs"],listOrgRoleTeams:["GET /orgs/{org}/organization-roles/{role_id}/teams"],listOrgRoleUsers:["GET /orgs/{org}/organization-roles/{role_id}/users"],listOrgRoles:["GET /orgs/{org}/organization-roles"],listOrganizationFineGrainedPermissions:["GET /orgs/{org}/organization-fine-grained-permissions"],listOutsideCollaborators:["GET /orgs/{org}/outside_collaborators"],listPatGrantRepositories:["GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories"],listPatGrantRequestRepositories:["GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories"],listPatGrantRequests:["GET /orgs/{org}/personal-access-token-requests"],listPatGrants:["GET /orgs/{org}/personal-access-tokens"],listPendingInvitations:["GET /orgs/{org}/invitations"],listPublicMembers:["GET /orgs/{org}/public_members"],listSecurityManagerTeams:["GET /orgs/{org}/security-managers",{},{deprecated:"octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams"}],listWebhookDeliveries:["GET /orgs/{org}/hooks/{hook_id}/deliveries"],listWebhooks:["GET /orgs/{org}/hooks"],pingWebhook:["POST /orgs/{org}/hooks/{hook_id}/pings"],redeliverWebhookDelivery:["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],removeMember:["DELETE /orgs/{org}/members/{username}"],removeMembershipForUser:["DELETE /orgs/{org}/memberships/{username}"],removeOutsideCollaborator:["DELETE /orgs/{org}/outside_collaborators/{username}"],removePublicMembershipForAuthenticatedUser:["DELETE /orgs/{org}/public_members/{username}"],removeSecurityManagerTeam:["DELETE /orgs/{org}/security-managers/teams/{team_slug}",{},{deprecated:"octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team"}],reviewPatGrantRequest:["POST /orgs/{org}/personal-access-token-requests/{pat_request_id}"],reviewPatGrantRequestsInBulk:["POST /orgs/{org}/personal-access-token-requests"],revokeAllOrgRolesTeam:["DELETE /orgs/{org}/organization-roles/teams/{team_slug}"],revokeAllOrgRolesUser:["DELETE /orgs/{org}/organization-roles/users/{username}"],revokeOrgRoleTeam:["DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"],revokeOrgRoleUser:["DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}"],setImmutableReleasesSettings:["PUT /orgs/{org}/settings/immutable-releases"],setImmutableReleasesSettingsRepositories:["PUT /orgs/{org}/settings/immutable-releases/repositories"],setMembershipForUser:["PUT /orgs/{org}/memberships/{username}"],setPublicMembershipForAuthenticatedUser:["PUT /orgs/{org}/public_members/{username}"],unblockUser:["DELETE /orgs/{org}/blocks/{username}"],update:["PATCH /orgs/{org}"],updateIssueType:["PUT /orgs/{org}/issue-types/{issue_type_id}"],updateMembershipForAuthenticatedUser:["PATCH /user/memberships/orgs/{org}"],updatePatAccess:["POST /orgs/{org}/personal-access-tokens/{pat_id}"],updatePatAccesses:["POST /orgs/{org}/personal-access-tokens"],updateWebhook:["PATCH /orgs/{org}/hooks/{hook_id}"],updateWebhookConfigForOrg:["PATCH /orgs/{org}/hooks/{hook_id}/config"]},packages:{deletePackageForAuthenticatedUser:["DELETE /user/packages/{package_type}/{package_name}"],deletePackageForOrg:["DELETE /orgs/{org}/packages/{package_type}/{package_name}"],deletePackageForUser:["DELETE /users/{username}/packages/{package_type}/{package_name}"],deletePackageVersionForAuthenticatedUser:["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],deletePackageVersionForOrg:["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],deletePackageVersionForUser:["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],getAllPackageVersionsForAPackageOwnedByAnOrg:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions",{},{renamed:["packages","getAllPackageVersionsForPackageOwnedByOrg"]}],getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions",{},{renamed:["packages","getAllPackageVersionsForPackageOwnedByAuthenticatedUser"]}],getAllPackageVersionsForPackageOwnedByAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions"],getAllPackageVersionsForPackageOwnedByOrg:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"],getAllPackageVersionsForPackageOwnedByUser:["GET /users/{username}/packages/{package_type}/{package_name}/versions"],getPackageForAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}"],getPackageForOrganization:["GET /orgs/{org}/packages/{package_type}/{package_name}"],getPackageForUser:["GET /users/{username}/packages/{package_type}/{package_name}"],getPackageVersionForAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],getPackageVersionForOrganization:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],getPackageVersionForUser:["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],listDockerMigrationConflictingPackagesForAuthenticatedUser:["GET /user/docker/conflicts"],listDockerMigrationConflictingPackagesForOrganization:["GET /orgs/{org}/docker/conflicts"],listDockerMigrationConflictingPackagesForUser:["GET /users/{username}/docker/conflicts"],listPackagesForAuthenticatedUser:["GET /user/packages"],listPackagesForOrganization:["GET /orgs/{org}/packages"],listPackagesForUser:["GET /users/{username}/packages"],restorePackageForAuthenticatedUser:["POST /user/packages/{package_type}/{package_name}/restore{?token}"],restorePackageForOrg:["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"],restorePackageForUser:["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"],restorePackageVersionForAuthenticatedUser:["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],restorePackageVersionForOrg:["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],restorePackageVersionForUser:["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"]},privateRegistries:{createOrgPrivateRegistry:["POST /orgs/{org}/private-registries"],deleteOrgPrivateRegistry:["DELETE /orgs/{org}/private-registries/{secret_name}"],getOrgPrivateRegistry:["GET /orgs/{org}/private-registries/{secret_name}"],getOrgPublicKey:["GET /orgs/{org}/private-registries/public-key"],listOrgPrivateRegistries:["GET /orgs/{org}/private-registries"],updateOrgPrivateRegistry:["PATCH /orgs/{org}/private-registries/{secret_name}"]},projects:{addItemForOrg:["POST /orgs/{org}/projectsV2/{project_number}/items"],addItemForUser:["POST /users/{username}/projectsV2/{project_number}/items"],deleteItemForOrg:["DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],deleteItemForUser:["DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}"],getFieldForOrg:["GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}"],getFieldForUser:["GET /users/{username}/projectsV2/{project_number}/fields/{field_id}"],getForOrg:["GET /orgs/{org}/projectsV2/{project_number}"],getForUser:["GET /users/{username}/projectsV2/{project_number}"],getOrgItem:["GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],getUserItem:["GET /users/{username}/projectsV2/{project_number}/items/{item_id}"],listFieldsForOrg:["GET /orgs/{org}/projectsV2/{project_number}/fields"],listFieldsForUser:["GET /users/{username}/projectsV2/{project_number}/fields"],listForOrg:["GET /orgs/{org}/projectsV2"],listForUser:["GET /users/{username}/projectsV2"],listItemsForOrg:["GET /orgs/{org}/projectsV2/{project_number}/items"],listItemsForUser:["GET /users/{username}/projectsV2/{project_number}/items"],updateItemForOrg:["PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}"],updateItemForUser:["PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}"]},pulls:{checkIfMerged:["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],create:["POST /repos/{owner}/{repo}/pulls"],createReplyForReviewComment:["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"],createReview:["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],createReviewComment:["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"],deletePendingReview:["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],deleteReviewComment:["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"],dismissReview:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"],get:["GET /repos/{owner}/{repo}/pulls/{pull_number}"],getReview:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],getReviewComment:["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],list:["GET /repos/{owner}/{repo}/pulls"],listCommentsForReview:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"],listCommits:["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],listFiles:["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],listRequestedReviewers:["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],listReviewComments:["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"],listReviewCommentsForRepo:["GET /repos/{owner}/{repo}/pulls/comments"],listReviews:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],merge:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],removeRequestedReviewers:["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],requestReviewers:["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],submitReview:["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"],update:["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],updateBranch:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"],updateReview:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],updateReviewComment:["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"]},rateLimit:{get:["GET /rate_limit"]},reactions:{createForCommitComment:["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"],createForIssue:["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"],createForIssueComment:["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],createForPullRequestReviewComment:["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],createForRelease:["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"],createForTeamDiscussionCommentInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],createForTeamDiscussionInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"],deleteForCommitComment:["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"],deleteForIssue:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"],deleteForIssueComment:["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"],deleteForPullRequestComment:["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"],deleteForRelease:["DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}"],deleteForTeamDiscussion:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"],deleteForTeamDiscussionComment:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"],listForCommitComment:["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"],listForIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"],listForIssueComment:["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],listForPullRequestReviewComment:["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],listForRelease:["GET /repos/{owner}/{repo}/releases/{release_id}/reactions"],listForTeamDiscussionCommentInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],listForTeamDiscussionInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"]},repos:{acceptInvitation:["PATCH /user/repository_invitations/{invitation_id}",{},{renamed:["repos","acceptInvitationForAuthenticatedUser"]}],acceptInvitationForAuthenticatedUser:["PATCH /user/repository_invitations/{invitation_id}"],addAppAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],addCollaborator:["PUT /repos/{owner}/{repo}/collaborators/{username}"],addStatusCheckContexts:["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],addTeamAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],addUserAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],cancelPagesDeployment:["POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel"],checkAutomatedSecurityFixes:["GET /repos/{owner}/{repo}/automated-security-fixes"],checkCollaborator:["GET /repos/{owner}/{repo}/collaborators/{username}"],checkImmutableReleases:["GET /repos/{owner}/{repo}/immutable-releases"],checkPrivateVulnerabilityReporting:["GET /repos/{owner}/{repo}/private-vulnerability-reporting"],checkVulnerabilityAlerts:["GET /repos/{owner}/{repo}/vulnerability-alerts"],codeownersErrors:["GET /repos/{owner}/{repo}/codeowners/errors"],compareCommits:["GET /repos/{owner}/{repo}/compare/{base}...{head}"],compareCommitsWithBasehead:["GET /repos/{owner}/{repo}/compare/{basehead}"],createAttestation:["POST /repos/{owner}/{repo}/attestations"],createAutolink:["POST /repos/{owner}/{repo}/autolinks"],createCommitComment:["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"],createCommitSignatureProtection:["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],createCommitStatus:["POST /repos/{owner}/{repo}/statuses/{sha}"],createDeployKey:["POST /repos/{owner}/{repo}/keys"],createDeployment:["POST /repos/{owner}/{repo}/deployments"],createDeploymentBranchPolicy:["POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"],createDeploymentProtectionRule:["POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"],createDeploymentStatus:["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],createDispatchEvent:["POST /repos/{owner}/{repo}/dispatches"],createForAuthenticatedUser:["POST /user/repos"],createFork:["POST /repos/{owner}/{repo}/forks"],createInOrg:["POST /orgs/{org}/repos"],createOrUpdateEnvironment:["PUT /repos/{owner}/{repo}/environments/{environment_name}"],createOrUpdateFileContents:["PUT /repos/{owner}/{repo}/contents/{path}"],createOrgRuleset:["POST /orgs/{org}/rulesets"],createPagesDeployment:["POST /repos/{owner}/{repo}/pages/deployments"],createPagesSite:["POST /repos/{owner}/{repo}/pages"],createRelease:["POST /repos/{owner}/{repo}/releases"],createRepoRuleset:["POST /repos/{owner}/{repo}/rulesets"],createUsingTemplate:["POST /repos/{template_owner}/{template_repo}/generate"],createWebhook:["POST /repos/{owner}/{repo}/hooks"],customPropertiesForReposCreateOrUpdateRepositoryValues:["PATCH /repos/{owner}/{repo}/properties/values"],customPropertiesForReposGetRepositoryValues:["GET /repos/{owner}/{repo}/properties/values"],declineInvitation:["DELETE /user/repository_invitations/{invitation_id}",{},{renamed:["repos","declineInvitationForAuthenticatedUser"]}],declineInvitationForAuthenticatedUser:["DELETE /user/repository_invitations/{invitation_id}"],delete:["DELETE /repos/{owner}/{repo}"],deleteAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],deleteAdminBranchProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],deleteAnEnvironment:["DELETE /repos/{owner}/{repo}/environments/{environment_name}"],deleteAutolink:["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"],deleteBranchProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"],deleteCommitComment:["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],deleteCommitSignatureProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],deleteDeployKey:["DELETE /repos/{owner}/{repo}/keys/{key_id}"],deleteDeployment:["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"],deleteDeploymentBranchPolicy:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],deleteFile:["DELETE /repos/{owner}/{repo}/contents/{path}"],deleteInvitation:["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"],deleteOrgRuleset:["DELETE /orgs/{org}/rulesets/{ruleset_id}"],deletePagesSite:["DELETE /repos/{owner}/{repo}/pages"],deletePullRequestReviewProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],deleteRelease:["DELETE /repos/{owner}/{repo}/releases/{release_id}"],deleteReleaseAsset:["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"],deleteRepoRuleset:["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"],deleteWebhook:["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],disableAutomatedSecurityFixes:["DELETE /repos/{owner}/{repo}/automated-security-fixes"],disableDeploymentProtectionRule:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"],disableImmutableReleases:["DELETE /repos/{owner}/{repo}/immutable-releases"],disablePrivateVulnerabilityReporting:["DELETE /repos/{owner}/{repo}/private-vulnerability-reporting"],disableVulnerabilityAlerts:["DELETE /repos/{owner}/{repo}/vulnerability-alerts"],downloadArchive:["GET /repos/{owner}/{repo}/zipball/{ref}",{},{renamed:["repos","downloadZipballArchive"]}],downloadTarballArchive:["GET /repos/{owner}/{repo}/tarball/{ref}"],downloadZipballArchive:["GET /repos/{owner}/{repo}/zipball/{ref}"],enableAutomatedSecurityFixes:["PUT /repos/{owner}/{repo}/automated-security-fixes"],enableImmutableReleases:["PUT /repos/{owner}/{repo}/immutable-releases"],enablePrivateVulnerabilityReporting:["PUT /repos/{owner}/{repo}/private-vulnerability-reporting"],enableVulnerabilityAlerts:["PUT /repos/{owner}/{repo}/vulnerability-alerts"],generateReleaseNotes:["POST /repos/{owner}/{repo}/releases/generate-notes"],get:["GET /repos/{owner}/{repo}"],getAccessRestrictions:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],getAdminBranchProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],getAllDeploymentProtectionRules:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"],getAllEnvironments:["GET /repos/{owner}/{repo}/environments"],getAllStatusCheckContexts:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"],getAllTopics:["GET /repos/{owner}/{repo}/topics"],getAppsWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"],getAutolink:["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"],getBranch:["GET /repos/{owner}/{repo}/branches/{branch}"],getBranchProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection"],getBranchRules:["GET /repos/{owner}/{repo}/rules/branches/{branch}"],getClones:["GET /repos/{owner}/{repo}/traffic/clones"],getCodeFrequencyStats:["GET /repos/{owner}/{repo}/stats/code_frequency"],getCollaboratorPermissionLevel:["GET /repos/{owner}/{repo}/collaborators/{username}/permission"],getCombinedStatusForRef:["GET /repos/{owner}/{repo}/commits/{ref}/status"],getCommit:["GET /repos/{owner}/{repo}/commits/{ref}"],getCommitActivityStats:["GET /repos/{owner}/{repo}/stats/commit_activity"],getCommitComment:["GET /repos/{owner}/{repo}/comments/{comment_id}"],getCommitSignatureProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],getCommunityProfileMetrics:["GET /repos/{owner}/{repo}/community/profile"],getContent:["GET /repos/{owner}/{repo}/contents/{path}"],getContributorsStats:["GET /repos/{owner}/{repo}/stats/contributors"],getCustomDeploymentProtectionRule:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"],getDeployKey:["GET /repos/{owner}/{repo}/keys/{key_id}"],getDeployment:["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],getDeploymentBranchPolicy:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],getDeploymentStatus:["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"],getEnvironment:["GET /repos/{owner}/{repo}/environments/{environment_name}"],getLatestPagesBuild:["GET /repos/{owner}/{repo}/pages/builds/latest"],getLatestRelease:["GET /repos/{owner}/{repo}/releases/latest"],getOrgRuleSuite:["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"],getOrgRuleSuites:["GET /orgs/{org}/rulesets/rule-suites"],getOrgRuleset:["GET /orgs/{org}/rulesets/{ruleset_id}"],getOrgRulesets:["GET /orgs/{org}/rulesets"],getPages:["GET /repos/{owner}/{repo}/pages"],getPagesBuild:["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],getPagesDeployment:["GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}"],getPagesHealthCheck:["GET /repos/{owner}/{repo}/pages/health"],getParticipationStats:["GET /repos/{owner}/{repo}/stats/participation"],getPullRequestReviewProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],getPunchCardStats:["GET /repos/{owner}/{repo}/stats/punch_card"],getReadme:["GET /repos/{owner}/{repo}/readme"],getReadmeInDirectory:["GET /repos/{owner}/{repo}/readme/{dir}"],getRelease:["GET /repos/{owner}/{repo}/releases/{release_id}"],getReleaseAsset:["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],getReleaseByTag:["GET /repos/{owner}/{repo}/releases/tags/{tag}"],getRepoRuleSuite:["GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}"],getRepoRuleSuites:["GET /repos/{owner}/{repo}/rulesets/rule-suites"],getRepoRuleset:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"],getRepoRulesetHistory:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history"],getRepoRulesetVersion:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}"],getRepoRulesets:["GET /repos/{owner}/{repo}/rulesets"],getStatusChecksProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],getTeamsWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"],getTopPaths:["GET /repos/{owner}/{repo}/traffic/popular/paths"],getTopReferrers:["GET /repos/{owner}/{repo}/traffic/popular/referrers"],getUsersWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"],getViews:["GET /repos/{owner}/{repo}/traffic/views"],getWebhook:["GET /repos/{owner}/{repo}/hooks/{hook_id}"],getWebhookConfigForRepo:["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"],getWebhookDelivery:["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"],listActivities:["GET /repos/{owner}/{repo}/activity"],listAttestations:["GET /repos/{owner}/{repo}/attestations/{subject_digest}"],listAutolinks:["GET /repos/{owner}/{repo}/autolinks"],listBranches:["GET /repos/{owner}/{repo}/branches"],listBranchesForHeadCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"],listCollaborators:["GET /repos/{owner}/{repo}/collaborators"],listCommentsForCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"],listCommitCommentsForRepo:["GET /repos/{owner}/{repo}/comments"],listCommitStatusesForRef:["GET /repos/{owner}/{repo}/commits/{ref}/statuses"],listCommits:["GET /repos/{owner}/{repo}/commits"],listContributors:["GET /repos/{owner}/{repo}/contributors"],listCustomDeploymentRuleIntegrations:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps"],listDeployKeys:["GET /repos/{owner}/{repo}/keys"],listDeploymentBranchPolicies:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"],listDeploymentStatuses:["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],listDeployments:["GET /repos/{owner}/{repo}/deployments"],listForAuthenticatedUser:["GET /user/repos"],listForOrg:["GET /orgs/{org}/repos"],listForUser:["GET /users/{username}/repos"],listForks:["GET /repos/{owner}/{repo}/forks"],listInvitations:["GET /repos/{owner}/{repo}/invitations"],listInvitationsForAuthenticatedUser:["GET /user/repository_invitations"],listLanguages:["GET /repos/{owner}/{repo}/languages"],listPagesBuilds:["GET /repos/{owner}/{repo}/pages/builds"],listPublic:["GET /repositories"],listPullRequestsAssociatedWithCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"],listReleaseAssets:["GET /repos/{owner}/{repo}/releases/{release_id}/assets"],listReleases:["GET /repos/{owner}/{repo}/releases"],listTags:["GET /repos/{owner}/{repo}/tags"],listTeams:["GET /repos/{owner}/{repo}/teams"],listWebhookDeliveries:["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"],listWebhooks:["GET /repos/{owner}/{repo}/hooks"],merge:["POST /repos/{owner}/{repo}/merges"],mergeUpstream:["POST /repos/{owner}/{repo}/merge-upstream"],pingWebhook:["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],redeliverWebhookDelivery:["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],removeAppAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],removeCollaborator:["DELETE /repos/{owner}/{repo}/collaborators/{username}"],removeStatusCheckContexts:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],removeStatusCheckProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],removeTeamAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],removeUserAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],renameBranch:["POST /repos/{owner}/{repo}/branches/{branch}/rename"],replaceAllTopics:["PUT /repos/{owner}/{repo}/topics"],requestPagesBuild:["POST /repos/{owner}/{repo}/pages/builds"],setAdminBranchProtection:["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],setAppAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],setStatusCheckContexts:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],setTeamAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],setUserAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],testPushWebhook:["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],transfer:["POST /repos/{owner}/{repo}/transfer"],update:["PATCH /repos/{owner}/{repo}"],updateBranchProtection:["PUT /repos/{owner}/{repo}/branches/{branch}/protection"],updateCommitComment:["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],updateDeploymentBranchPolicy:["PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],updateInformationAboutPagesSite:["PUT /repos/{owner}/{repo}/pages"],updateInvitation:["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"],updateOrgRuleset:["PUT /orgs/{org}/rulesets/{ruleset_id}"],updatePullRequestReviewProtection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],updateRelease:["PATCH /repos/{owner}/{repo}/releases/{release_id}"],updateReleaseAsset:["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"],updateRepoRuleset:["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"],updateStatusCheckPotection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks",{},{renamed:["repos","updateStatusCheckProtection"]}],updateStatusCheckProtection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],updateWebhook:["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],updateWebhookConfigForRepo:["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"],uploadReleaseAsset:["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}",{baseUrl:"https://uploads.github.com"}]},search:{code:["GET /search/code"],commits:["GET /search/commits"],issuesAndPullRequests:["GET /search/issues"],labels:["GET /search/labels"],repos:["GET /search/repositories"],topics:["GET /search/topics"],users:["GET /search/users"]},secretScanning:{createPushProtectionBypass:["POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses"],getAlert:["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],getScanHistory:["GET /repos/{owner}/{repo}/secret-scanning/scan-history"],listAlertsForOrg:["GET /orgs/{org}/secret-scanning/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/secret-scanning/alerts"],listLocationsForAlert:["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"],listOrgPatternConfigs:["GET /orgs/{org}/secret-scanning/pattern-configurations"],updateAlert:["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],updateOrgPatternConfigs:["PATCH /orgs/{org}/secret-scanning/pattern-configurations"]},securityAdvisories:{createFork:["POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks"],createPrivateVulnerabilityReport:["POST /repos/{owner}/{repo}/security-advisories/reports"],createRepositoryAdvisory:["POST /repos/{owner}/{repo}/security-advisories"],createRepositoryAdvisoryCveRequest:["POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve"],getGlobalAdvisory:["GET /advisories/{ghsa_id}"],getRepositoryAdvisory:["GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}"],listGlobalAdvisories:["GET /advisories"],listOrgRepositoryAdvisories:["GET /orgs/{org}/security-advisories"],listRepositoryAdvisories:["GET /repos/{owner}/{repo}/security-advisories"],updateRepositoryAdvisory:["PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}"]},teams:{addOrUpdateMembershipForUserInOrg:["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"],addOrUpdateRepoPermissionsInOrg:["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],checkPermissionsForRepoInOrg:["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],create:["POST /orgs/{org}/teams"],createDiscussionCommentInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],createDiscussionInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions"],deleteDiscussionCommentInOrg:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],deleteDiscussionInOrg:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],deleteInOrg:["DELETE /orgs/{org}/teams/{team_slug}"],getByName:["GET /orgs/{org}/teams/{team_slug}"],getDiscussionCommentInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],getDiscussionInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],getMembershipForUserInOrg:["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"],list:["GET /orgs/{org}/teams"],listChildInOrg:["GET /orgs/{org}/teams/{team_slug}/teams"],listDiscussionCommentsInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],listDiscussionsInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions"],listForAuthenticatedUser:["GET /user/teams"],listMembersInOrg:["GET /orgs/{org}/teams/{team_slug}/members"],listPendingInvitationsInOrg:["GET /orgs/{org}/teams/{team_slug}/invitations"],listReposInOrg:["GET /orgs/{org}/teams/{team_slug}/repos"],removeMembershipForUserInOrg:["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"],removeRepoInOrg:["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],updateDiscussionCommentInOrg:["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],updateDiscussionInOrg:["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],updateInOrg:["PATCH /orgs/{org}/teams/{team_slug}"]},users:{addEmailForAuthenticated:["POST /user/emails",{},{renamed:["users","addEmailForAuthenticatedUser"]}],addEmailForAuthenticatedUser:["POST /user/emails"],addSocialAccountForAuthenticatedUser:["POST /user/social_accounts"],block:["PUT /user/blocks/{username}"],checkBlocked:["GET /user/blocks/{username}"],checkFollowingForUser:["GET /users/{username}/following/{target_user}"],checkPersonIsFollowedByAuthenticated:["GET /user/following/{username}"],createGpgKeyForAuthenticated:["POST /user/gpg_keys",{},{renamed:["users","createGpgKeyForAuthenticatedUser"]}],createGpgKeyForAuthenticatedUser:["POST /user/gpg_keys"],createPublicSshKeyForAuthenticated:["POST /user/keys",{},{renamed:["users","createPublicSshKeyForAuthenticatedUser"]}],createPublicSshKeyForAuthenticatedUser:["POST /user/keys"],createSshSigningKeyForAuthenticatedUser:["POST /user/ssh_signing_keys"],deleteAttestationsBulk:["POST /users/{username}/attestations/delete-request"],deleteAttestationsById:["DELETE /users/{username}/attestations/{attestation_id}"],deleteAttestationsBySubjectDigest:["DELETE /users/{username}/attestations/digest/{subject_digest}"],deleteEmailForAuthenticated:["DELETE /user/emails",{},{renamed:["users","deleteEmailForAuthenticatedUser"]}],deleteEmailForAuthenticatedUser:["DELETE /user/emails"],deleteGpgKeyForAuthenticated:["DELETE /user/gpg_keys/{gpg_key_id}",{},{renamed:["users","deleteGpgKeyForAuthenticatedUser"]}],deleteGpgKeyForAuthenticatedUser:["DELETE /user/gpg_keys/{gpg_key_id}"],deletePublicSshKeyForAuthenticated:["DELETE /user/keys/{key_id}",{},{renamed:["users","deletePublicSshKeyForAuthenticatedUser"]}],deletePublicSshKeyForAuthenticatedUser:["DELETE /user/keys/{key_id}"],deleteSocialAccountForAuthenticatedUser:["DELETE /user/social_accounts"],deleteSshSigningKeyForAuthenticatedUser:["DELETE /user/ssh_signing_keys/{ssh_signing_key_id}"],follow:["PUT /user/following/{username}"],getAuthenticated:["GET /user"],getById:["GET /user/{account_id}"],getByUsername:["GET /users/{username}"],getContextForUser:["GET /users/{username}/hovercard"],getGpgKeyForAuthenticated:["GET /user/gpg_keys/{gpg_key_id}",{},{renamed:["users","getGpgKeyForAuthenticatedUser"]}],getGpgKeyForAuthenticatedUser:["GET /user/gpg_keys/{gpg_key_id}"],getPublicSshKeyForAuthenticated:["GET /user/keys/{key_id}",{},{renamed:["users","getPublicSshKeyForAuthenticatedUser"]}],getPublicSshKeyForAuthenticatedUser:["GET /user/keys/{key_id}"],getSshSigningKeyForAuthenticatedUser:["GET /user/ssh_signing_keys/{ssh_signing_key_id}"],list:["GET /users"],listAttestations:["GET /users/{username}/attestations/{subject_digest}"],listAttestationsBulk:["POST /users/{username}/attestations/bulk-list{?per_page,before,after}"],listBlockedByAuthenticated:["GET /user/blocks",{},{renamed:["users","listBlockedByAuthenticatedUser"]}],listBlockedByAuthenticatedUser:["GET /user/blocks"],listEmailsForAuthenticated:["GET /user/emails",{},{renamed:["users","listEmailsForAuthenticatedUser"]}],listEmailsForAuthenticatedUser:["GET /user/emails"],listFollowedByAuthenticated:["GET /user/following",{},{renamed:["users","listFollowedByAuthenticatedUser"]}],listFollowedByAuthenticatedUser:["GET /user/following"],listFollowersForAuthenticatedUser:["GET /user/followers"],listFollowersForUser:["GET /users/{username}/followers"],listFollowingForUser:["GET /users/{username}/following"],listGpgKeysForAuthenticated:["GET /user/gpg_keys",{},{renamed:["users","listGpgKeysForAuthenticatedUser"]}],listGpgKeysForAuthenticatedUser:["GET /user/gpg_keys"],listGpgKeysForUser:["GET /users/{username}/gpg_keys"],listPublicEmailsForAuthenticated:["GET /user/public_emails",{},{renamed:["users","listPublicEmailsForAuthenticatedUser"]}],listPublicEmailsForAuthenticatedUser:["GET /user/public_emails"],listPublicKeysForUser:["GET /users/{username}/keys"],listPublicSshKeysForAuthenticated:["GET /user/keys",{},{renamed:["users","listPublicSshKeysForAuthenticatedUser"]}],listPublicSshKeysForAuthenticatedUser:["GET /user/keys"],listSocialAccountsForAuthenticatedUser:["GET /user/social_accounts"],listSocialAccountsForUser:["GET /users/{username}/social_accounts"],listSshSigningKeysForAuthenticatedUser:["GET /user/ssh_signing_keys"],listSshSigningKeysForUser:["GET /users/{username}/ssh_signing_keys"],setPrimaryEmailVisibilityForAuthenticated:["PATCH /user/email/visibility",{},{renamed:["users","setPrimaryEmailVisibilityForAuthenticatedUser"]}],setPrimaryEmailVisibilityForAuthenticatedUser:["PATCH /user/email/visibility"],unblock:["DELETE /user/blocks/{username}"],unfollow:["DELETE /user/following/{username}"],updateAuthenticated:["PATCH /user"]}},Np=jw;var Cr=new Map;for(let[e,r]of Object.entries(Np))for(let[t,n]of Object.entries(r)){let[o,s,i]=n,[a,l]=o.split(/ /),d=Object.assign({method:a,url:l},s);Cr.has(e)||Cr.set(e,new Map),Cr.get(e).set(t,{scope:e,methodName:t,endpointDefaults:d,decorations:i})}var Lw={has({scope:e},r){return Cr.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[...Cr.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=Cr.get(r).get(n);if(!o)return;let{endpointDefaults:s,decorations:i}=o;return i?t[n]=Gw(e,r,n,s,i):t[n]=e.request.defaults(s),t[n]}};function ma(e){let r={};for(let t of Cr.keys())r[t]=new Proxy({octokit:e,scope:t,cache:{}},Lw);return r}function Gw(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 Iw(e){return{rest:ma(e)}}Iw.VERSION=pa;function ga(e){let r=ma(e);return{...r,rest:r}}ga.VERSION=pa;var Mp="22.0.1";var Fp=Fo.plugin(da,ga,ua).defaults({userAgent:`octokit-rest.js/${Mp}`});function $w(e){return`r${e}`}function Wp(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=$w(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 Up(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 Cw=Fp.plugin(Ji,Io);function Bp(){let e=new Map;return{get:r=>e.get(r),set:(r,t)=>e.set(r,t)}}function Hp(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 mt=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 fa(e){let r=e.etags??Bp(),t=new Cw({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=fr(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=Wo(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(pn(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=qp(h),k={...u.headers,...v},T=Wo(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 pn(h)===401?new mt({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=Wp(c.map(({input:k})=>k)),m=await t.graphql(u.query),f=Up(u,m),h=Mw(m),v=c[0].input;await e.attribution?.record({operation:{key:v.operation.key,budget:"graphql"},cost:h,actor:Fw(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=pn(u)===401?new mt({cause:u}):u;c.forEach(f=>f.reject(m))}},l=async()=>{let c=null;try{c=await e.balance?.()??null}catch{}let u=Hp(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,!Nw(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 pn(f)===401?new mt({cause:f}):f}}}}function Nw(e){let r=Wo(e,"link");return r!==void 0&&/(?:^|,)\s*<[^>]+>;\s*rel="next"(?:\s*;|\s*(?:,|$))/i.test(r)}function mn(e){let r=pn(e),t=qp(e);return r===429||r===403&&Wo(t,"x-ratelimit-remaining")==="0"||e instanceof Error&&/secondary rate|rate limit/i.test(e.message)}function pn(e){if(fr(e))return typeof e.status=="number"?e.status:void 0}function qp(e){return!fr(e)||!fr(e.response)||!fr(e.response.headers)?{}:e.response.headers}function Wo(e,r){let t=e[r]??e[r.toLowerCase()];return typeof t=="string"?t:typeof t=="number"?String(t):void 0}function fr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mw(e){let r=fr(e)?e:{},t=fr(r.data)?r.data:r,o=(fr(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 Fw(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 Kp="rate_limit",Jp={rest:"core",graphql:"graphql",search:"search"},or=["rest","graphql","search"];function qo(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:[...or],detail:r??"no balance has been asked for yet, so none is known"}}var ya=15e3,gt=.15,Bo=[{at_or_below_fraction:0,every_ms:ya,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:gt,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 Gj=60*6e4,ha=2;function zp(e,r){let t=Vp(e),n=Vp(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let a of or){let l=Jp[a],d=n[l],c=Bw(a,l,d);o[a]=c,c==null&&s.push(a)}let i=or.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 ${or.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function ka(e){try{let r=await e.transport();return zp(r,{askedAt:e.now})}catch(r){let t=r instanceof Error?r.message:String(r);return{...qo(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function ba(e){let r=null;for(let t of or){let n=e.pools[t];n!=null&&(r==null||n.fraction<r.fraction)&&(r=n)}return r}function Vo(e,r){let t=ba(e);if(t==null)return Ho(gt).every_ms;let n=Ho(t.fraction);if(t.remaining>0)return n.every_ms;let o=Yp(r.now,t.reset_at);return o==null?n.every_ms:Math.max(ya,Math.min(n.every_ms,o))}function _a(e,r=gt){return Math.ceil(e.limit*r)}function Qp(e,r,t=gt){let n=e.pools[r];return n==null?"unknown":n.remaining<=0?"spent":n.remaining<_a(n,t)?"reserved":"open"}function Ra(e){let r=e.reservedFraction??gt,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:Ho(r).every_ms*ha,stale:!1,posture:"unknown",reserved_fraction:r,next_poll_ms:Ho(r).every_ms,pools:[],unreported_pools:[...or],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let n=Vo(t,{now:e.now}),o=e.stalenessMs??n*ha,s=Yp(t.asked_at,e.now),i=t.outcome==="asked"&&(s==null||s>o),a=or.map(c=>t.pools[c]).filter(c=>c!=null),l=Uw(t,r),d=ba(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`:Ww(l,d,t,r)}}function wa(e){if(!va(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 Ww(e,r,t,n){if(r==null)return t.detail;let o=_a(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 Uw(e,r){let t="unknown";for(let n of or){if(e.pools[n]==null)continue;let o=Qp(e,n,r);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function Ho(e){for(let r of Bo)if(e<=r.at_or_below_fraction)return r;return Bo[Bo.length-1]}function Bw(e,r,t){if(!va(t))return null;let n=Uo(t.limit),o=Uo(t.remaining),s=Uo(t.used),i=Uo(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 Ea(e){let r=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let n=await t(`${r}/${Kp}`,{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 Yp(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 Uo(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function Vp(e){return va(e)?e:{}}function va(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nm(e){return{generated_at:e.now,hour:Xp("hour",36e5,e),day:Xp("day",864e5,e)}}function fn(e,r,t){let n=gn(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(a=>{let l=gn(r(a));return l==null?!1:n==null||n-l<=o});return i.length<=s?i:i.slice(i.length-s)}function Xp(e,r,t){let n=gn(t.now),o=n==null?null:n-r,s=e==="hour"?"1h":"24h",i=t.observations.map(u=>({observation:u,at:gn(u.observed_at)})).filter(u=>u.at!=null&&rm(u.at,o,n)).sort((u,m)=>u.at-m.at),a=t.outcomes.map(u=>gn(u.ts)).filter(u=>u!=null&&rm(u,o,n)),l=Zp(i,u=>u.tokens,"tokens",s),d=Zp(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:Hw(a.length,r,s),runner_share:em("runner",i,u=>u.runner,s),model_share:em("model",i,u=>u.model,s),unavailable:c}}function Zp(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 Hw(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 em(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 rm(e,r,t){return r==null||t==null?!0:e>=r&&e<=t}function gn(e){let r=Date.parse(e);return Number.isFinite(r)?r:null}function om(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.generated_at=="string"&&tm(r.hour)&&tm(r.day)}function tm(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"&&Sa(r.tokens_per_min)&&Sa(r.tools_per_min)&&Sa(r.issues_per_hour)&&Array.isArray(r.unavailable)}function Sa(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 qw}from"node:child_process";import{existsSync as Vw,readFileSync as Ko,readdirSync as Kw}from"node:fs";import{dirname as Jw,join as Nr}from"node:path";function hn(e){let r=on(e),t=[["MemoryMax",r.memory_max],["MemoryHigh",r.memory_high]];for(let[n,o]of t){if(o==null)continue;let s=ct(o);return s==null?null:{name:n,declared:o,bytes:s}}return null}function sm(e){let r=[],t=[];for(let n of e.workers){let o=hn(n);if(o==null){t.push({worker_id:n.worker_id,reason:(on(n).memory_max??on(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(zw(n,o,s))}}return{terminations:r,unenforceable:t}}function zw(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 Qw=4096;function im(e,r={}){let t=r.platform??process.platform,n={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return n;let o={},s={},i={},a=Xw(e,t,r);for(let[u,m]of a){let f=rE(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=oE(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 Yw="/sys/fs/cgroup";function Xw(e,r,t){let n=new Map;if(!(t.cgroupRoot!=null)&&r!=="linux")return n;let s=t.cgroupRoot??Yw,i=e.filter(l=>l.unit!=null&&l.unit!=="");if(i.length===0)return n;let a=Zw(s,t);for(let l of i)for(let d of a){let c=Nr(d,l.unit);if(Vw(Nr(c,"memory.current"))){n.set(l.worker_id,c);break}}return n}function Zw(e,r){let t=r.selfCgroupPath??eE(),n=[],o=a=>{n.includes(a)||n.push(a)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(Nr(e,s));let a=Jw(s);if(a===s)break;s=a}o(e);let i=r.uid??process.getuid?.();return i!=null&&o(Nr(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),n}function eE(){try{for(let e of Ko("/proc/self/cgroup","utf8").split(`
|
|
87
|
+
`))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function rE(e){let r;try{r=Ko(Nr(e,"memory.current"),"utf8")}catch{return null}let t=Number(r.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:tE(e)}}function tE(e){let r;try{r=Ko(Nr(e,"cpu.stat"),"utf8")}catch{return null}return nE(r)}function nE(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 oE(e,r){return r.procRoot!=null||e==="linux"?cE(r.procRoot??"/proc"):r.psTable!=null||e==="darwin"?lE(sE(r.psTable)):new Map}function sE(e){try{return(e??iE)()}catch{return""}}function iE(){return qw("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var aE=1024;function lE(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=dE(n[3]);a!=null&&r.set(o,{pid:o,ppid:s,rssBytes:i*aE,cpuSeconds:a})}return r}function dE(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 cE(e){let r=new Map,t;try{t=Kw(e)}catch{return r}for(let n of t){if(!/^\d+$/.test(n))continue;let o;try{o=Ko(Nr(e,n,"stat"),"utf8")}catch{continue}let s=pE(o);s&&r.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*Qw,cpuSeconds:s.cpuTicks/uE})}return r}var uE=100;function pE(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 mE=["api","graphql"],pL=Bi(mE);var am=100,xa=6e4,gE=2*xa,fE=7*24*60*60*1e3,Ta=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 Pa(e,r){for(let t of e)if(t.token_ref!=null&&t.token_ref!==r)throw new Ta(t.project_label,t.token_ref,r)}function pm(e,r={now:new Date(0).toISOString()}){ym(e);let t=r.closedWindowMs??fE,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 hE(e,r,t){let n=ft(r),o=ft(n.data),s=Array.isArray(n.errors)?n.errors.map(ft):[],i=wE(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=>cm(h.path,l)||cm(h.path,d));if(yn(m)){let h=um(m.open_pull_requests),v=um(m.open_issues),k=EE(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||km(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: ${Jo(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 yE(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 mm(e){if(e.projects.length===0)return yE(e.now);if(Pa(e.projects,e.hostTokenRef),e.transport.conditionalList)return await bE(e);let r=pm(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(r.query);return hE(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 kE={key:"redskilled repository activity poll",budget:"rest"};async function bE(e){ym(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=pm(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:kE});i+=v.requestCount;let k=m==="open-prs"?v.data:v.data.filter(T=>!yn(T.pull_request));u.push(m==="recently-closed"?k.filter(T=>Jo(T.closed_at)>=n.closed_since).length:k.length),a=lm(a,RE(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=mn(m);a=lm(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 gm(e){let r=e.stalenessMs??gE,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 fm(e){if(!yn(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)&&yn(r.rate_limit)&&Array.isArray(r.projects)&&typeof r.reason=="string"}function hm(e){let r=e.endpoint==null?void 0:_E(e.endpoint),t=fa({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 _E(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 RE(e){let r=dm(e,"x-ratelimit-remaining"),t=dm(e,"x-ratelimit-reset");return{remaining:r,reset_at:t==null?null:new Date(t*1e3).toISOString(),exhausted:r===0,point_cost:null}}function lm(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 dm(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 ym(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>am)throw new Error(`redskilled activity fetch spans at most ${am} 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 wE(e,r){let t=ft(e),n=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=r.some(km),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 km(e){if(e==null)return!1;let r=Jo(e.type),t=Jo(e.message);return r==="RATE_LIMITED"||/rate limit/i.test(t)}function cm(e,r){return Array.isArray(e)&&e.includes(r)}function um(e){let r=ft(e);return Number.isInteger(r.totalCount)?r.totalCount:null}function EE(e){let r=ft(e);return Number.isInteger(r.issueCount)?r.issueCount:null}function ft(e){return yn(e)?e:{}}function yn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jo(e){return typeof e=="string"?e:""}var vE=3e4,SE=2,TE=3,xE=4,PE=["logs","vitals","display"];function bm(e,r){if(r===void 0)return e;let t=PE.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:OE,budget:{...o.budget,used_bytes:null,used_fraction:null}},...n("logs")?{}:{log:AE},...n("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var OE={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},AE={last_line:null,published_at:null,source:null};function _m(e){let r=e.stalenessMs??vE,t=hr(e.now),n=e.sampledAt==null?null:hr(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=>GE(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=xo(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:NE({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:CE(a),known_projects:$E(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:Ra({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:gm({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:DE(e.deaths,e.recentDeathLimit??xE)},engine:LE(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function DE(e,r){let t=[...e].sort((s,i)=>(hr(i.ts)??0)-(hr(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=jE(t);return{count:t.length,recent:n,latest:n[0]??null,reaped_at:n[0]?.ts??null,...o==null?{}:{boot_loop:o}}}function jE(e){let r=new Map;for(let n of e){if(n.sender_class!=="boot-refused"||n.uptime_s==null||n.uptime_s>SE||n.project_label==null||n.project_label===""||hr(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>=TE).map(([n,o])=>{let s=o[0],i=hr(s.ts),a=Math.min(...o.map(d=>hr(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 LE(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 GE(e,r){let t=r.rss[e.worker_id],n=typeof t=="number"&&Number.isFinite(t)?t:null,o=hn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=hr(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:IE(r.log),display:r.display?.display??null,display_published_at:r.display?.published_at??null}}function IE(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 $E(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 CE(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 NE(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 hr(e){let r=Date.parse(e);return Number.isFinite(r)?r:null}function Oa(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(ME))&&(r.stopped_projects===void 0||Array.isArray(r.stopped_projects)&&r.stopped_projects.every(FE))&&(r.orphaned_projects===void 0||Array.isArray(r.orphaned_projects)&&r.orphaned_projects.every(s=>typeof s=="string"))&&(r.repository_activity===void 0||fm(r.repository_activity))&&(r.github_balance===void 0||wa(r.github_balance))&&(r.deaths===void 0||WE(r.deaths))&&(r.engine===void 0||UE(r.engine))&&(r.metrics===void 0||om(r.metrics))}function ME(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 FE(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 WE(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 UE(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 Rm={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 wm(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`,kn=ae("48;2;114;47;55"),Aa=ae("48;2;88;36;42"),yr=ae("38;2;255;255;255"),Da=ae("38;2;201;150;158"),bn=ae("38;2;255;214;214"),_n=ae("39"),ke=ae("38;2;224;138;148"),ja=ae("38;2;240;200;120"),La=ae("38;2;240;110;120"),Ga=ae("38;2;255;214;214"),Ia=ae("38;2;146;84;94"),$a=ae("38;2;255;95;95"),Ke=ae("49"),Le=ae("0"),zo=ae("1"),Qo=ae("22");var BE=/\x1b\[[0-9;]*m/g,HE=/(\x1b\[[0-9;]*m)/,qE=/^\x1b\[[0-9;]*m$/;function Em(e){return e.replace(BE,"")}function VE(e){return e.slice(2,-1).split(";").every(t=>t===""||Number(t)===0)}function xe(e){return[...Em(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(HE))if(i!==""){if(qE.test(i)){s+=i,o=!VE(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 Rn(e,r){return e+" ".repeat(Math.max(0,r-xe(e)))}function Ca(e){let r=e.toLowerCase();for(let t of["opus","sonnet","haiku","fable"]){let n=r.indexOf(t);if(n===-1)continue;let s=r.slice(n+t.length).match(/^-(\d+(?:[-.]\d+)*)/)?.[1]?.split(/[-.]/)??[];return/^\d{8}$/.test(s.at(-1)??"")&&s.pop(),s.length===0?t:`${t}-${s.join(".")}`}return e}function 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 wn(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 En(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return wn(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 kr(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 ht(e){if(e==null)return null;let r=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return r===""?null:r}var vn="!unregistered",Na="!lapsed",Sn="\u21E1",sr="\u2020",yt="\u25D0",kt="\u25EF",Ma="\u21B3",Fa="redskilled unreachable \u2014 Worker state unknown";function bt(e,r){return r.mode==="global"?e.workers:r.project==null?[]:e.workers.filter(t=>t.project_label===r.project)}function Yo(e,r){return r.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===r.project)}function Tn(e,r){return r==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(r)?e.registered_projects==null||e.registered_projects.includes(r)?"matched":e.orphaned_projects?.includes(r)===!0?"orphaned":e.stopped_projects?.some(t=>t.project_label===r)===!0?"stopped":e.lapsed_projects?.some(t=>t.project_label===r)===!0?"lapsed":"name-only":"unregistered"}function Wa(e){let r=[];return e.workers.length>0&&e.workers.length<=e.maxWorkers&&r.push("workers"),e.mode==="global"&&e.projects.length>0&&e.projects.length<=e.maxProjects&&r.push("projects"),r.push("host"),r}var _r=["wid","run","org","iss","bar","phase","base","elapsed","eta","hb","loc","tks","ctx","tls","rsn","txt"],Je={mode:"local",project:null,maxWidth:200,maxRows:16},KE=" ",vm="\u2588",JE="\u25B6",zE="\u2717",QE="\u2591",YE=new Set(["gate","push-pr","merge","cascade"]),XE=new Set(["requeue"]),ZE="repair";function xn(e){return e.display?.origin===ZE}function _t(e,r=Je){let t=Tn(e,r.project),n=bt(e,r),o=n.slice(0,Math.max(0,Math.floor(r.maxRows))),s=o.map(u=>Xo(u,r,e.generated_at)),i=dv(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(cv(s[m],i),r.maxWidth)})),l=rv(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(...sv(e,r)),c.push(...ov(e,r)),{version:1,generated_at:e.generated_at,mode:r.mode,project:r.project,columns:_r,header:l,rows:a,lines:c,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Xo(e,r,t){let n=e.display??Rm,o=xn(e),s=[n.runner,n.model==null?null:Ca(n.model),n.effort].filter(l=>!!l).join(" "),i=n.phase!=null&&YE.has(n.phase),a=o||i||n.origin!=null&&XE.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:Sm(n),phase:[n.phase,n.step].filter(l=>!!l).join("\xB7"),base:e.base_commits_ahead==null?"":`base +${e.base_commits_ahead}`,elapsed:kr(wm(e,t)),eta:n.eta==null?"":`eta=${kr(n.eta*1e3)}`,hb:ev(n,t)??`hb=${n.heartbeat??"?"}`,loc:a?"":lv(n.added,n.removed),tks:a||n.tokens==null?"":`tks=${wn(n.tokens)}`,ctx:n.context==null?"":`ctx=${wn(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 ev(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} ${kr(Math.max(0,n-t))}`}function Sm(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 vm.repeat(Math.floor(r));let o=e.failed?zE:JE;return`${vm.repeat(n)}${o}${QE.repeat(Math.floor(r)-n-1)}`}function rv(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=av(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=[tv(l??"host",c,d!=null&&d.current===!1?Sn:"")];(n==="unregistered"||n==="name-only")&&f.push(vn),n==="lapsed"&&f.push(Na),a!=null&&f.push(`${kn}${yr}${a}${Ke}${ke}`);let h=e.workers.filter(xn).length;if(h>0){let G=Math.max(0,e.host.worker_count-h);f.push(`${br(`workers=${G} coding +`)} ${kn}${yr}${h} repairing${Ke}${ke}`)}else f.push(br(`wrk=${t.length}/${e.host.worker_count}`));let v=i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`;f.push(br(`${v} reserve=${i.interactive_reservation} interactive`)),f.push(br(iv(i))),s.open_pull_requests!=null&&f.push(br(`prs=${s.open_pull_requests}`)),s.recently_closed!=null&&f.push(br(`cpr=${s.recently_closed}`)),s.open_issues!=null&&f.push(br(`iss=${s.open_issues}`)),s.stale&&f.push("!counts stale");let k=m==null?null:Tm(m.hour),T=k==null?null:br(k);if(T!=null&&f.push(T),u!=null&&u.count>0&&u.latest!=null){let G=u.boot_loop,H=ht(G?.latest_refusal);f.push(G==null?`${sr}${u.count} ${u.latest.sender_class}`:`${sr}${u.count} boot-refused \xD7${G.count} in ${nv(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 tv(e,r,t){return`${Aa}${yr}${ja}\xBB${yr} ${zo}${e}${Qo} ${Da}v${r}${t}${yr}${Ke}${ke}`}function br(e){return e.replace(/(^|\s)([A-Za-z][A-Za-z0-9/]*=)([^\s]+)/g,(r,t,n,o)=>`${t}${bn}${n}${_n}${o}${ke}`)}function nv(e){return kr(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function Tm(e){let r=[];e.tokens_per_min.value!=null&&r.push(`tk/m=${En(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&r.push(`tl/m=${En(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&r.push(`iss/h=${En(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 ov(e,r){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let n=t.posture==="spent"?kt:yt,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 sv(e,r){let t=e.deaths;if(t==null||t.count<=0)return[];let n=t.recent.map(s=>fe(`${sr} ${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 iv(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 av(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 lv(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 dv(e){let r=Object.fromEntries(_r.map(t=>[t,0]));for(let t of e)for(let n of _r)r[n]=Math.max(r[n],xe(t[n]));return r}function cv(e,r){let t=_r.filter(o=>r[o]>0);if(t.length===0)return"";let n=t.map((o,s)=>Zo(o,Rn(e[o],s===t.length-1?xe(e[o]):r[o])));return`${Ke}${ke}${n.join(KE)}${Le}`}function Zo(e,r){if(e==="wid")return`${zo}${r}${Qo}`;if(e==="org"&&r.trim()==="lane=repair"){let n=r.slice(r.trimEnd().length);return`${kn}${yr}${r.trimEnd()}${Ke}${ke}${n}`}if(e==="bar")return r.replace(/█+/g,n=>`${La}${n}`).replace("\u25B6",`${Ga}\u25B6`).replace("\u2717",`${$a}\u2717`).replace(/░+/g,n=>`${Ia}${n}`)+ke;let t=r.indexOf("=");return t>0?`${bn}${r.slice(0,t+1)}${_n}${r.slice(t+1)}${ke}`:r}function Ba(e){return Object.freeze({none:!0,reason:e})}function Pn(){return{tool:"project_start",args:{runner:"claude",target:1},why:"register this project with the host so its queue can drain"}}function Ua(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=>Ua(n,r)));let t={};for(let[n,o]of Object.entries(e))t[n]=Ua(o,r);return Object.freeze(t)}finally{r.delete(e)}}function uv(e){let r=Ua(e.args,new Set);return Object.freeze({tool:e.tool,args:r,why:e.why})}function Mr(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=uv(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 Fr(e,r=B){let t=Tn(e,r.project),n=bt(e,r),o=Yo(e,r),s=yv(e,r.project,t),i=mv(e,r,n,t,s.prose),a=Wa({mode:r.mode,maxWorkers:r.maxWorkers,maxProjects:r.maxProjects,workers:n,projects:o}),l={detail:"host",line:i};for(let f of a){let h=f==="workers"?i:wv(i,pv(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"?bv(n,r,e.generated_at):{lines:[],degraded:!1},u=l.detail==="workers"?n.flatMap((f,h)=>{let v=r.verbose?_v(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 Ka(e){let r=e.options??B,t=fe(Fa,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 pv(e,r){return e==="projects"?r.map(Rv):[]}function mv(e,r,t,n,o){let s=[],i=n!=="matched"&&n!=="name-only";r.mode==="global"?(s.push(`host ${Ha(e.workers,e.host.worker_count)}/${e.host.project_count}p`),s.push(Va(e,r))):n==="matched"?(s.push(`${r.project} ${Ha(t,t.length)}`),s.push(Va(e,r)),t.length===0&&s.push("idle")):n==="name-only"?(s.push(`${r.project} ${Ha(t,t.length)}`),s.push(Va(e,r)),s.push(vn)):s.push(o),s.push(xm(e));let a=gv(e);a!=null&&s.push(a);let l=fv(e);l!=null&&s.push(l),e.staleness.stale&&s.push(Pm(e));let d=s.join(" ");return!i||xe(d)<=r.maxWidth||a==null&&l==null?d:[a,l,o,xm(e),e.staleness.stale?Pm(e):null].filter(c=>c!=null).join(" ")}function Ha(e,r){let t=e.filter(xn).length;return t===0?`${r}w`:`${Math.max(0,r-t)} coding + ${t} repairing`}function xm(e){let r=e.engine,t=r?.running_version??e.daemon.daemon_version;return r==null||r.current!==!1?`v${t}`:`v${t}${Sn}`}function gv(e){let r=e.github_balance;return r==null?null:r.posture==="spent"?`${kt} quota spent`:r.posture==="reserved"?`${yt} quota band`:null}function fv(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=ht(t.latest_refusal);return`${sr}${r.count} boot-refused \xD7${t.count} in ${hv(t.span_ms)}`+(n==null?"":` \u2014 ${n}`)}return`${sr}${r.count} ${r.latest.sender_class}`}function hv(e){return kr(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function yv(e,r,t){if(t==="unregistered")return Mr({state:`project unknown \u2014 ${r} was never registered on this host`,repair:Pn()});if(t==="orphaned")return Mr({state:`project unknown \u2014 ${r} is registered on a daemon this socket does not reach`,repair:Ba("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 Mr({state:`project unknown \u2014 ${r} was stopped${n==null?"":` at ${qa(n.at)}`}`,repair:Pn()})}if(t==="lapsed"){let n=e.lapsed_projects?.find(o=>o.project_label===r);if(n!=null){let o=n.registered_at==null?"":` (registered ${qa(n.registered_at)})`;return Mr({state:`project unknown \u2014 ${r} lapsed at ${qa(n.at)}${o}`,repair:Pn()})}return Mr({state:`project unknown \u2014 ${r} lapsed`,repair:Pn()})}return t==="unresolved"?Mr({state:"project unknown \u2014 this directory resolved to no project",repair:Ba("the directory must resolve to a project before registration args can be safe")}):{prose:""}}function qa(e){return/^\d{4}-\d{2}-\d{2}T(\d{2}:\d{2}:\d{2})/.exec(e)?.[1]??e}function Va(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 Pm(e){let r=e.staleness.age_ms;return r==null?"!unmeasured":`!stale ${Math.round(r/1e3)}s`}function kv(e,r,t,n){let o=t.map(s=>Zo(s,Rn(e[s],r[s])));return fe(`${Ke}${ke}${o.join(" ")}${Le}`,n)}function bv(e,r,t){let n=e.map(a=>Xo(a,r,t)),o=_r.filter(a=>n.some(l=>xe(l[a])>0)),s=[...o],i=Om(n,s);for(;s.length>1&&Am(i,s)>r.maxWidth;)s.pop(),i=Om(n,s);return{lines:n.map(a=>kv(a,i,s,r.maxWidth)),degraded:s.length<o.length||Am(i,s)>r.maxWidth}}function Om(e,r){let t=Object.fromEntries(_r.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 Am(e,r){return r.reduce((t,n)=>t+e[n],0)+Math.max(0,r.length-1)*2}function _v(e,r){let t=ht(e.log.last_line);return t==null?null:fe(` ${Ma} ${Dm(e,r.mode)}: ${t}`,r.maxWidth)}function Dm(e,r){return r==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Rv(e){return`${e.project_label} ${e.worker_count}w ${Ge(e.observed_rss_bytes)}`}function wv(e,r,t){return[e,...r].join(t)}var es=1;async function On(e,r){return await _o(e,r,"redskilled daemon")}function Lm(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:es,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:Tv(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:Yc(r,{hostCeilingBytes:e.ceiling?.memory_bytes??e.hostCeilingBytes??null}),upgrade:xv(e)}}function Tv(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:Iu(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 xv(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 Gm(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||jv(r.ceiling))&&Array.isArray(r.workers)&&Array.isArray(r.projects)&&Xc(r.budget_accounting)&&(r.scope===void 0||Ou(r.scope))&&(r.registrations===void 0||Array.isArray(r.registrations)&&r.registrations.every(dn))&&(r.demand===void 0||fu(r.demand))&&(r.lapsed_registrations===void 0||Array.isArray(r.lapsed_registrations)&&r.lapsed_registrations.every(Ov))&&(r.stopped_registrations===void 0||Array.isArray(r.stopped_registrations)&&r.stopped_registrations.every(Av))&&(r.orphaned_registrations===void 0||Array.isArray(r.orphaned_registrations)&&r.orphaned_registrations.every(Dv))&&(r.birth_latches===void 0||Array.isArray(r.birth_latches)&&r.birth_latches.every(Pv))&&(r.upgrade===void 0||Lv(r.upgrade))}function Pv(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 Ov(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 Av(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 Dv(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 jv(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 Lv(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||Gv(r.major_hold))}function Gv(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 Iv}from"node:crypto";import{mkdir as $v,readFile as Cv,rename as Nv,writeFile as Mv}from"node:fs/promises";import{dirname as Fv}from"node:path";function Im(e){let r=Promise.resolve(),t=null;async function n(){await r;let s;try{s=await Cv(e,"utf8")}catch(a){if(a.code==="ENOENT")return[];throw a}let i=Wv(s);return Uv(i)?i.registrations:[]}async function o(s){await $v(Fv(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.${Iv()}.tmp`,a={version:1,registrations:[...s]};await Mv(i,`${X(a,{keyedMapCollapse:!0})}
|
|
91
|
+
`,{encoding:"utf8",mode:384}),await Nv(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 Wv(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return me(r)}catch{return null}}}function Uv(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(dn)}import{spawnSync as ns}from"node:child_process";import{existsSync as Xa}from"node:fs";import{delimiter as Yv,join as qm}from"node:path";import{join as $m}from"node:path";import{existsSync as Bv}from"node:fs";import{createRequire as Hv}from"node:module";var Cm="redskilled-job-object.node",Wr=100;function Rt(e){return{available:!1,reason:e}}function qv(e,r,t){return[$m(t,"prebuilds",`${e}-${r}`,Cm),$m(t,"native","build","Release",Cm)]}function Nm(e={}){let r=e.platform??process.platform,t=e.arch??process.arch;if(r!=="win32")return Rt(`Job Object placement is the Windows backend (platform=${r}), so there is no native reach to load here`);let n=e.packageRoot??Kv(),o=e.exists??Bv,s=qv(r,t,n),i=s.find(d=>o(d));if(i==null)return Rt(`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??Hv(import.meta.url),l;try{l=a(i)}catch(d){return Rt(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return Vv(l)?{available:!0,binding:l}:Rt(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function Vv(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Kv(){return new URL("..",import.meta.url).pathname}function Mm(e){let r=e??{},t=[],n=Jv(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<Wr?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 ${Wr}, 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 Jv(e){return hn({budget:e})}var rs=5,Fm=19;function Ja(e){return{available:!1,reason:e}}var zv="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 Um(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=rs;else if(t.cpu_weight<Wr){let a=Math.round(Fm*(Wr-t.cpu_weight)/Wr);o=Math.min(Fm,Math.max(rs,a))}else o=rs,n.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${Wr}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${rs}`);let s=Wm(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=Wm(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:zv,...n.length>0?{note:n.join("; ")}:{}}}function Bm(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 ${Qv(e.nice)} -n ${r.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
|
|
92
|
+
`),e.command,...e.args]}function Hm(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 za(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 Wm(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function Qv(e){return`'${e.replace(/'/g,"'\\''")}'`}var Vm="REDSKILLED_PLACEMENT",ts="red-worker",Qa="/bin/sh";function Km(e=process.env,r=process.platform){let t=Ja(`POSIX rlimit and priority placement is the macOS backend (platform=${r})`);if(r==="win32")return{platform:r,systemdRun:null,userSession:!1,jobObjects:Nm({platform:r}),posix:t};let n=Rt(`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:Xv(e)};if(r!=="linux")return{platform:r,systemdRun:null,userSession:!1,jobObjects:n,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Xa(qm(o,"systemd","private"));return{platform:r,systemdRun:Ym("systemd-run",e),userSession:s,jobObjects:n,posix:t}}function Xv(e){return Xa(Qa)?{available:!0,shell:Qa,nice:Ym("nice",e)}:Ja(`no POSIX shell was found at ${Qa}, so there is nothing to apply rlimits or priority in`)}function Jm(e=process.env){let r=(e[Vm]??"").trim().toLowerCase();return r===""?!0:!["off","false","0","no"].includes(r)}function Zv(e,r,t=ts){return zm(e,r,t).replace(/\.service$/,"")}function zm(e,r,t=ts){return`${Ya(t,"red-worker",24)}-${Ya(e,"project",32)}-${Ya(r,"worker",32)}.service`}function Qm(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:Qt({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 ${Vm}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return rS(e,r,t,n,o,i);if(e.probes.platform==="darwin")return eS(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=zm(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=Qt({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=za(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 eS(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=Um(t,{canRenice:s.nice!=null}),a=t.memory_high!=null||t.memory_max!=null,l=Hm(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:Bm({limits:i,nice:s.nice,command:e.command,args:r}),cwd:e.workspacePath,posix:i,warning:l,budget:t,...n!=null?{memoryCeiling:n}:{},environment:Qt({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 rS(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=Mm(t),l=Zv(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:Qt({scope:l,memory_ceiling:n,scope_degradation:null}),...tS(o&&a.note!=null?`${a.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,za(e.budget))}}function tS(...e){let r=e.filter(t=>t!=null&&t!=="");return r.length>0?{budgetWarning:r.join("; ")}:{}}function Ym(e,r){for(let t of(r.PATH??"").split(Yv)){if(!t)continue;let n=qm(t,e);if(Xa(n))return n}return null}function Ya(e,r,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||r}async function Za(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 Xm=3e4;function Zm(e){return e.unit!=null&&e.unit!==""?nS(e.unit):re(e.pid)}function nS(e){let r=ns("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return r.error!=null?!1:r.status===0}var oS="REDSKILLED_UNIT_DISCOVERY",eg="(unowned)";function rg(e){let r=ns("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 sS(e=process.env){let r=(e[oS]??"").trim().toLowerCase();return r===""?!0:!["off","false","0","no"].includes(r)}function tg(e,r,t=process.env){return sS(t)&&e===r}function ng(e=ts){let r=ns("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 og(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:eg,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 sg(e){return e.project_label.trim()!==""?e:{...e,project_label:eg,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 ig(e){if(e.unit!=null&&e.unit!==""){let r=ns("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 jn=50,rl=15e3,nG=2*rl;function iS(e,r=jn){if(tl(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 lg(e,r={}){let t=r.batchSize??jn;if(tl(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 dg(e,r){let t=Dn(r),n=Dn(t.data),o=Array.isArray(t.errors)?t.errors.map(Dn):[],s=uS(n.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=mS(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=>pS(u.path,a));return s.exhausted||pg(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: ${el(c?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function aS(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:jn,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function cg(e,r,t){return{version:1,fetched_at:r,request_count:0,project_count:e.length,batch_size:jn,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 ug(e){if(e.projects.length===0)return aS(e.now);if(e.transport.conditionalList)return await dS(e);let r=e.batchSize??jn,t=iS(e.projects,r),n=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=lg(s,{batchSize:r});try{let a=await e.transport(i.query),l=dg(i,a);n.push(...l.projects),o=An(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=An(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 lS={key:"redskilled queue poll",budget:"rest"};async function dS(e){tl(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=lg([s],{batchSize:1}),d=dg(l,await e.transport(l.query));o+=1,t.push(...d.projects),n=An(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:lS});o+=i.requestCount;let a=i.data.filter(l=>!mg(l.pull_request)).length;n=An(n,cS(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=mn(i);n=An(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 tl(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 An(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 cS(e){let r=ag(e,"x-ratelimit-remaining"),t=ag(e,"x-ratelimit-reset");return{remaining:r,reset_at:t==null?null:new Date(t*1e3).toISOString(),exhausted:r===0}}function ag(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 uS(e,r){let t=Dn(e),n=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null;return{remaining:n,reset_at:o,exhausted:r.some(pg)||n===0}}function pg(e){return e==null?!1:el(e.type)==="RATE_LIMITED"||/rate limit/i.test(el(e.message))}function pS(e,r){return Array.isArray(e)&&e.includes(r)}function mS(e){let r=Dn(e);return Number.isInteger(r.issueCount)?r.issueCount:null}function Dn(e){return mg(e)?e:{}}function mg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function el(e){return typeof e=="string"?e:""}function gg(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(gS,Math.max(r,i))}let o=n.remaining;return o==null?r:o<=fS?Math.max(r,3e4):o<=hS?Math.max(r,2e4):r}var gS=1e5,fS=250,hS=1e3;var yS={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},kS=["runner","model","effort","origin","issue","phase","step","heartbeat","wait_kind","wait_subject","wait_started_at","wait_deadline","wait_escalation","started_at"],bS=["phase_index","phase_total","wait_pid","context","eta","added","removed","tokens","tools","reasoning","text"];function fg(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let r=e,t={...yS};for(let n of kS){let o=r[n];t[n]=typeof o=="string"&&o.trim()!==""?o:null}for(let n of bS){let o=r[n];t[n]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=r.failed===!0,t}import{randomInt as ES}from"node:crypto";import{spawn as vS}from"node:child_process";import{appendFileSync as SS,mkdirSync as TS}from"node:fs";import{dirname as xS}from"node:path";import{delimiter as hg,dirname as _S}from"node:path";function RS(e,r=hg){return(e??"").split(r).map(t=>t.trim()).filter(t=>t!=="")}function wS(e=process.execPath){let r=(e??"").trim();if(r==="")return null;let t=_S(r);return t===""||t==="."?null:t}function yg(e,r=process.execPath,t=hg){let n=RS(e,t),o=wS(r);return o==null?n.join(t):[o,...n.filter(s=>s!==o)].join(t)}var wt=class extends Error{constructor(r){super(r),this.name="RedskilledWorkerSpecError"}},ze=class extends Error{constructor(t,n){super(t);this.admission=n;this.name="RedskilledAdmissionError"}},nl="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",kg=4,PS=nl.length**kg;function sl(e,r=ES){let t=new Set(e);for(let n=0;n<PS;n+=1){let o="h";for(let s=0;s<kg;s+=1)o+=nl[r(nl.length)];if(!t.has(o))return o}throw new wt("redskilled exhausted the host Worker id space")}function OS(e){if(e==null||e.trim()==="")return{ready:!1};let r=xS(e);try{return TS(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})`}: ${ol(t)}. This Worker runs with NO log at all, so nothing but its heartbeat can show what it did`}}}function AS(e,r){let t=(n,o)=>{if(n==null)return;let s="",i=a=>{try{SS(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 DS(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 wt(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new wt("redskilled worker spec args must be an array")}function jS(e){if(e==null)throw new ze("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new ze(e.reason,e)}function bg(e){let{spec:r,admission:t}=e;jS(t),DS(r);let n=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(r.worker_id??e.workerId)?.trim()||sl(e.liveWorkerIds??[]),i=e.probes??Km(n),a=Du(r.log_path,{worker_id:s,workspace_path:r.workspace_path}),l=e.openLog===!1?{ready:!1}:OS(a),d=l.ready,c={...r.env??{},...e.forkSha==null||e.forkSha===""?{}:{RED_AFK_FORK_SHA:e.forkSha},PATH:yg(r.env?.PATH??n.PATH,e.execPath??process.execPath)},u=Qm({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??Jm(n),probes:i,pipeOutput:d}),f=(e.spawnFn??vS)(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&&AS(f,a),f.pid==null)throw f.once("error",()=>{}),new wt(`redskilled could not spawn ${JSON.stringify(u.command)} for worker ${s}`);let h=u.job!=null?LS(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 LS(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: ${ol(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)}: ${ol(i)}. ${o}`}}return{job:s}}function ol(e){return e instanceof Error?e.message:String(e)}import{execFile as GS}from"node:child_process";var IS="refs/heads/red-trunk";function os(e,r){return new Promise((t,n)=>{GS("git",[...r],{cwd:e},(o,s,i)=>{if(o!=null){n(new Error(i.trim()||o.message));return}t(s.trim())})})}async function _g(e){await os(e.workspace_path,["fetch",e.trunk.remote,e.trunk.branch]);let r=await os(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 os(e.workspace_path,["update-ref",IS,r]),r}async function Rg(e){let r=await os(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 $S,stat as CS}from"node:fs/promises";var NS=16*1024;async function wg(e,r=NS){let t;try{t=(await CS(e)).size}catch{return null}if(t<=0)return null;let n=Math.min(r,t),o;try{let s=await $S(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 MS(o)}function MS(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 eT}from"node:child_process";import{existsSync as rT,readdirSync as tT}from"node:fs";import{dirname as nT,join as Pg,resolve as oT}from"node:path";var FS="<version>";function Rr(e,r=[],t){let n=t&&t.trim().length>0?t.trim():FS;return[`npx -y -p ${Ir}@${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 il(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 TG=4*60*60*1e3;tr();tr();import{spawnSync as WS}from"node:child_process";import{mkdir as US,rm as BS,writeFile as HS}from"node:fs/promises";import{existsSync as qS}from"node:fs";import{homedir as VS}from"node:os";import{dirname as KS,join as al}from"node:path";var wr="redskilled.service",ll="REDSKILLED_SUPERVISED",JS="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function zS(e=process.env){let r=e.XDG_CONFIG_HOME?.trim()||al(e.HOME?.trim()||VS(),".config");return al(r,"systemd","user")}function dl(e=process.env){return al(zS(e),wr)}function Eg(e,r={}){let t=r.env??process.env,n=vo(r.override??{},r.entryLookup??{}),o=[...n.args,...Lr(e,r.idleMs==null?{}:{idleMs:r.idleMs})];return{unitName:wr,unitPath:dl(t),command:n.command,args:o,text:QS(n.command,o,e)}}function QS(e,r,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${JS}`,"","[Service]","Type=simple",`ExecStart=${[e,...r].map(YS).join(" ")}`,"Restart=always","RestartSec=1",`Environment="${ll}=1"`,`Environment="REDSKILLED_SESSION=${vg(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
|
|
97
|
+
`)}function YS(e){return/[\s"'\\$%]/.test(e)?`"${vg(e)}"`:e}function vg(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function Sg(e,r={}){let t=r.writeFile??XS,n=r.run??cl,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(ss("daemon-reload",n,["systemctl","--user","daemon-reload"])),o.push(ss("enable",n,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function Tg(e={}){let r=e.removeFile??ZS,t=e.run??cl,n=dl(e.env??process.env),o=[ss("disable",t,["systemctl","--user","disable","--now",wr])];return await r(n),o.push({step:"remove-unit",ok:!0,detail:n}),o.push(ss("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:n,installed:!1,steps:o}}function xg(e={}){let r=e.exists??qS,t=e.run??cl,n=dl(e.env??process.env),o=r(n),s=o&&t(["systemctl","--user","is-enabled",wr]).status===0,i=o&&t(["systemctl","--user","is-active",wr]).status===0,a=s&&!i?[{code:"enabled-but-inactive",evidence:`${wr} is installed and enabled but inactive`,fix:`systemctl --user restart ${wr}`}]:[];return{unitName:wr,unitPath:n,installed:o,enabled:s,active:i,findings:a,floor:"auto-spawn"}}function ss(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 XS(e,r){await US(KS(e),{recursive:!0}),await HS(e,r,{encoding:"utf8",mode:420})}async function ZS(e){await BS(e,{force:!0})}function cl(e){let r=WS(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 Og=75,Dg=9e5,Ag="redskilled-replacement-entry-unresolved",sT="REDSKILLED_NO_REGISTRY_PROBE",jg="REDSKILLED_BORN_BY_REPLACEMENT";function Lg(e=process.env){return e[jg]==="1"}function Gg(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function Ig(e){let r=e.running.trim();if(Ln(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:iT(n.major,e.supervised)}}function iT(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: ${Rr("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 $g(e){let r=e.running.trim();if(Ln(r))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||Ie(t)===null?{act:"hold",reason:"published-unknown"}:il(t,r)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function Ln(e){let r=e.trim();return Ie(r)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(r)}function Cg(e=process.env){return e[ll]==="1"}var ul=class extends Error{code=Ag;searched;constructor(r,t){super(`${Ag}: 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 aT(e,r={}){let t=r.env??process.env,n=r.exists??rT,o=r.execPath??process.execPath,s=r.callerEntry===void 0?process.argv[1]:r.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[Pg(Eo(t),i),"bundle-cache"]];s&&l.push([Pg(nT(oT(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 ul(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 Ng(e,r={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=r.resolveEntry??(n=>aT(n,r.env==null?{}:{env:r.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function Mg(e,r,t={}){let n=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(n.exit??dT)(Og),{...e,exitCode:Og};let o=[...e.entry.args,...Lr(r,t.idleMs==null?{}:{idleMs:t.idleMs})];return(n.spawnSuccessor??lT(n.env))(e.entry,o),e}function lT(e){return(r,t)=>{let n=eT(r.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[jg]:"1"}});n.on("error",()=>{}),n.unref()}}function dT(e){process.exitCode=e,process.exit(e)}async function Fg(e,r=process.env,t=cT){let n=Ug(r),o=Bg(e,r);if(r[sT]==="1")return{version:o,newest:n};let s=Ie(e)===null?"0.0.0":e;try{let i=await Ic({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??n}}catch{return{version:o,newest:n}}}function Wg(e,r=process.env,t){let n=t??pl;return{version:Bg(e,r,n),newest:Ug(r,n)}}function Ug(e=process.env,r=pl){return qg(Hg(e,r))}function Bg(e,r=process.env,t=pl){let n=Ie(e.trim())?.major;return n===void 0?null:qg(Hg(r,t).filter(o=>Ie(o)?.major===n))}function Hg(e,r){let t=[];for(let n of r(Eo(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(n)?.[1];!o||Ie(o)===null||t.push(o)}return t}function qg(e){let r=null;for(let t of e)(r===null||il(t,r)>0)&&(r=t);return r}function pl(e){try{return tT(e)}catch{return[]}}async function cT(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 uT,readFile as pT,rename as mT,rm as ml,writeFile as Vg}from"node:fs/promises";import{randomUUID as gT}from"node:crypto";import{dirname as fT}from"node:path";var is=class extends Error{constructor(r){super(`redskilled lease ${JSON.stringify(r)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function Et(e){let r;try{r=await pT(e,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}let t=hT(r);return yT(t)?t:void 0}var Kg;function zg(){return Kg??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Kg}function Qg(e,r,t={}){let n=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??re;async function s(){return await Et(e)}async function i(l){let d=`${e}.${l.pid}.${gT()}.tmp`;await Vg(d,Jg(l),{encoding:"utf8",mode:384}),await mT(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 uT(fT(e),{recursive:!0,mode:448});let d=!1;for(;;){let c=n(),u=a(l,c);try{return await Vg(e,Jg(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 ml(e,{force:!0}),d=!0;continue}if(gl(m,l))return{acquired:!0,reaped:d,lease:m};if(await o(m.pid))return{acquired:!1,lease:m};await ml(e,{force:!0}),d=!0}},async renew(l){let d=await s();if(!d||!gl(d,l))throw new is(e);let c={...d,renewed_at:n()};return await i(c),c},async release(l){let d=await s();if(!d)return!1;if(!gl(d,l))throw new is(e);return await ml(e,{force:!0}),!0}}}function gl(e,r){return e.pid===r.pid&&e.start_time===r.startTime}function Jg(e){return`${X(e,{keyedMapCollapse:!0})}
|
|
101
|
+
`}function hT(e){let r=e.trim();if(!r)return null;try{return JSON.parse(r)}catch{try{return me(r)}catch{return null}}}function yT(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}async function Zg(e){let{paths:r}=e,t=e.daemonVersion??"0.0.0-dev",n=e.idleMs??dt,o=e.clock??(()=>new Date().toISOString()),s=e.launch??bg,i=e.refreshTrunk??_g,a=e.countBaseMovement??Rg,l=e.ceiling??Po();e.repositoryActivity!=null&&Pa(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let d=e.owner??zg(),c=e.leaseStore??Qg(r.leasePath,{sessionKeyHash:r.sessionKeyHash,machineIdHash:r.machineIdHash,socketPath:r.socketPath},{clock:o}),u=e.machineOwner??xu(),m={machineIdHash:r.machineIdHash,sessionKeyHash:r.sessionKeyHash,socketPath:r.socketPath},f=e.machineClaimStore??Do(r.machineClaimPath,m,{clock:o});await _T(wT(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>=Hc&&await Ai(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 qe(r.socketPath):new pr(f.claimPath,F.reason,F.claim);let G=await c.acquire(d);if(!G.acquired)throw await f.release(u).catch(()=>{}),new qe(r.socketPath,G.lease);let H;try{H=await zc(r.socketPath,async()=>{let[p,y]=await Promise.all([c.read().catch(()=>{}),f.read().catch(()=>{})]);return p!=null&&p.pid!==d.pid&&re(p.pid)?!0:y!=null&&y.socket_path===r.socketPath&&y.pid!==u.pid&&re(y.pid)})}catch(p){throw await c.release(d).catch(()=>{}),await f.release(u).catch(()=>{}),p}let ee=o(),q=e.eventLane??uu(r.eventLanePath),he=e.registrationIntentStore??Im(r.registrationIntentPath),Er=e.liveness??Zm,Nn=e.livenessGraceMs??Xm,Mn=e.stopWorker??ig,Fn=e.unitInventory??(()=>tg(r.machineClaimPath,Ao({machineIdHash:r.machineIdHash}))?ng():[]),Br=e.unitMainPid??rg,ps=e.treeSampler??im,St=e.readLogTail??wg,Wn=e.sampleMs??Bc,Un=e.leaseRenewMs??Pi,Tt=e.registrationSustainMs??qc,xt=e.publishedVersion??(p=>Fg(p)),Bn=e.replaceCheckMs??Dg,Pt=e.publishedProbeTimeoutMs??Wc,Hn=e.localPublishedEvidence??(p=>Wg(p,e.replacementIO?.env??process.env)),qn=e.bornByReplacement??Lg(),Ot=e.replaceBootCheckMs??Uc,At=e.supervised??Cg(),vr=e.replacementIO??{},be=e.repositoryActivity,Dt=be?.intervalMs??xa,Sr=e.githubBalance,$e=e.queueDiscovery,Hr=$e?.transport??be?.transport,jt=$e?.unconfiguredReason??Kc,Lt=$e?.intervalMs??rl,Gt=e.demandMs??15e3,Vn=e.demandBackoffMs??3e4,C=new Map,ir=new Map,Pe=new Set,Ce=new Map,ar=new Map,qr=[],Tr=[],lr=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,Ye=null,xr=null,se=null,It=null,Xe=[],Ze=[],ms=new Map((e.orphanedRegistrations??[]).map(p=>[p.project_label,p])),$t=null,Re={},gs=!1,Kr,Ct,Nt,Mt,Ft,Wt,Kn,Ut,Jr,zr,pe=!1,fs=!1,Jn=null,Pl,hs=new Promise(p=>{Pl=p});function Qr(p){Ol(p);let y=Date.parse(p),w=$u(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),Wf(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 Wf(p,y){let w=Number.isFinite(y)?new Date(y).toISOString():p.renew_by;Xe.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`}),Xe.length>nn&&Xe.splice(0,Xe.length-nn)}function Ol(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=Wi(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 Al(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=Wi(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 zn(){let p=o();return Qr(p),Lm({now:p,daemonVersion:t,machineIdHash:r.machineIdHash,sessionKeyHash:r.sessionKeyHash,pid:d.pid,startedAt:ee,ceiling:l,scope:Pu(f.claimPath,m,u),workers:[...C.values()],registrations:[...U.values()],demand:It,lapses:Xe,stops:Ze,orphanedRegistrations:[...ms.values()],birthLatches:ku(Re,Date.parse(p)),queue:se,published:{version:_,checkedAt:R,newer:E,replacement:N,newest:V,majorHold:z,checks:x,holdReason:A}})}function Qn(){return _m({hostState:zn(),ceiling:l,rss:b,sampledAt:g,logLines:Object.fromEntries(Ce),displays:Object.fromEntries(ar),now:o(),reattachedWorkerIds:[...Pe],repositoryActivity:Ye,githubBalance:xr,...lr===void 0?{}:{deaths:lr},metrics:nm({observations:qr,outcomes:Tr,now:o()})})}function Uf(p,y){qr=fn([...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 Bf(p){Tr=fn([...Tr,p],y=>y.ts,{now:o()})}async function ys(){return be==null||be.projects.length===0?null:(Ye=await mm({projects:be.projects,hostTokenRef:be.hostTokenRef,transport:be.transport,closedWindowMs:be.closedWindowMs,now:o()}),Ye)}async function Dl(){return Sr==null?null:(xr=await ka({transport:Sr.transport,now:o()}),xr)}function Hf(){if(pe||Jr!=null||Sr==null)return;let p=()=>{Jr=void 0,Dl().catch(()=>{}).then(()=>{if(pe)return;let y=Sr.intervalMsOverride??Vo(xr??qf(),{now:o()});Jr=setTimeout(p,y),Jr.unref()})};p()}function qf(){return qo(o())}function Vf(){if(!(Hr!=null||$e?.armTransport==null))try{let p=$e.armTransport();if(p.transport!=null){Hr=p.transport;return}p.unconfiguredReason!=null&&(jt=p.unconfiguredReason)}catch(p){jt=`this host could not resolve a tracker credential: ${p instanceof Error?p.message:String(p)}`}}async function jl(){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(Vf(),Hr==null)return se=cg(S,p,jt),se;se=await ug({projects:S,transport:Hr,now:p,...$e?.batchSize==null?{}:{batchSize:$e.batchSize}});let O=o();return Al(O),Ol(O),se}async function Ll(){let p=o();if(gs)return It??gu(p);gs=!0;try{await bs().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 no=C.get(le.probeWorkerId);no!=null&&O-Date.parse(no.started_at)>=6e4&&(Re[$]=Gi())}let j=mu({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:$t,birthHealth:Re}),L=[],Q=new Map,J=null;for(let $ of j.births){let le,no=sl(C.keys()),Zr=U.get($.project_label),oo=ju({argv:$.argv,...Zr?.env==null?{}:{env:Zr.env},...Zr?.log_path==null?{}:{log_path:Zr.log_path}},{worker_id:no,slot:$.index,workspace_path:$.workspace_path},{project_label:$.project_label});try{if(Zr?.trunk==null)le=Xn(oo);else{let er={workspace_path:$.workspace_path,trunk:Zr.trunk},Ht=Bt(oo);if(!Ht.admitted)throw new ze(Ht.reason,Ht);let Ql=Fl(er),so=Q.get(Ql);so==null&&(so=ks(er),Q.set(Ql,so)),le=await Wl(oo,er,so,Ht)}}catch(er){J=er instanceof Error?er.message:String(er),er instanceof ze&&er.admission?.verdict==="refused-unreachable-trunk-remote"||($t=(Number.isFinite(S)?S:Date.now())+Vn);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:oo.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 Es=Re[$.project_label];Es?.haltUntilMs!=null&&O>=Es.haltUntilMs&&(Re[$.project_label]=yu(Es,le.worker.worker_id))}J==null&&j.births.length>0&&($t=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 It={version:1,at:p,requested:j.births.length,granted:L,shortfall:j.births.length-L.length,refusal:J,retry_after:$t==null?null:new Date($t).toISOString(),projects:j.intents},It}finally{gs=!1}}function Kf(p){return Fr(Qn(),{...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 Jf(p){return _t(Qn(),{mode:p?.mode??Je.mode,project:p?.project??Je.project,maxWidth:p?.max_width??Je.maxWidth,maxRows:p?.max_rows??Je.maxRows})}function Pr(p,y,w){return Mu({op:p,sessionProject:y??null,targetProject:w})}async function zf(p){let y=C.get(p.worker_id),w=Pr(Nu(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 eh(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 Yn(p){C.delete(p),Pe.delete(p),Ce.delete(p),ar.delete(p)}function Gl(p){let y=C.get(p.worker_id),w=Pr("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:fg(p.display);if(O!=null){let j=ar.get(p.worker_id)?.display,L={display:O,published_at:S};ar.set(p.worker_id,L),Uf(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 Qf(p,y,w){let S=`exit code=${y??"null"} signal=${w??"null"}`;if(p.unit!=null&&p.unit!==""&&await Xf(p)){Zf(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:Oi(await St(p.log_path).catch(()=>null));Yn(p.worker_id),we("worker-death",p,O==null?S:`session-error: ${O}`,{exitCode:y,signal:w,refusal:O}),te()}function Yf(p,y){if(!Number.isFinite(y)||y<0){Re[p]=an;return}let w=Re[p]??an,S=hu(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 Il(p,y){let w=Pr("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]=Gi(),{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 Xf(p){try{return await Er(p)===!0}catch{return!1}}function Zf(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),te()}function $l(p,y){let w=Pr("project-register",y,p.project_label);if(!w.permitted)throw new Error(w.reason);let S=o();Qr(S);let O=Lu(p,{now:S,held:U.get(p.project_label)});return U.set(O.project_label,O),Yr(),Ml(O.project_label),te(),{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 Cl(p,y={}){let w=Pr("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(ms.has(p))throw new $r(p,{kind:"orphaned"});let L=[...Ze].reverse().find(J=>J.project_label===p);if(L!=null)throw new $r(p,{kind:"stopped",at:L.at});let Q=[...Xe].reverse().find(J=>J.project_label===p);throw Q!=null?new $r(p,{kind:"lapsed",at:Q.at,...Q.registered_at==null?{}:{registered_at:Q.registered_at}}):new $r(p)}let j=Gu(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(),te(),{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 Nl(p,y){let w=Pr("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)}`;Ml(p),Ze.push({project_label:p,registered_at:S.registered_at,at:o(),detail:Q}),Ze.length>nn&&Ze.splice(0,Ze.length-nn)}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 Ml(p){oe.delete(p);for(let y=Xe.length-1;y>=0;y-=1)Xe[y].project_label===p&&Xe.splice(y,1);for(let y=Ze.length-1;y>=0;y-=1)Ze[y].project_label===p&&Ze.splice(y,1);ms.delete(p)}async function eh(p,y){try{await Mn(p)}catch{}return Yn(p.worker_id),we("worker-death",p,y),te(),!0}function Bt(p){return iu({ceiling:l,workers:[...C.values()],budget:p.budget,projectLabel:p.project_label,...p.reservation==null?{}:{reservation:p.reservation}})}function Fl(p){return`${p.workspace_path}\0${p.trunk.remote}\0${p.trunk.branch}`}function ks(p){let y=Fl(p),w=ir.get(y);if(w!=null)return w;let S=i(p).finally(()=>{ir.get(y)===S&&ir.delete(y)});return ir.set(y,S),S}function rh(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 Wl(p,y,w,S){let O=S??Bt(p);if(!O.admitted)throw new ze(O.reason,O);let j;try{j=await(w??ks(y))}catch(Q){let J=rh(O,y,Q);throw new ze(J.reason,J)}let L=Bt(p);if(!L.admitted)throw new ze(L.reason,L);return Xn(p,{admission:L,forkSha:j})}function Xn(p,y={}){let w=au({ceiling:l,workers:[...C.values()],budget:p.budget}),S=s({spec:p,admission:y.admission??Bt(p),...y.forkSha==null?{}:{forkSha:y.forkSha},memoryCeiling:w,liveWorkerIds:C.keys(),clock:o,onExit:(Q,J,Xr)=>{let $=C.get(Q);if($==null){te();return}Qf($,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}),te(),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")&&(Bf({worker_id:y.worker_id,ts:O,outcome:p}),Ul(Oo(j),{startedAt:y.started_at,...S.refusal==null?{}:{refusal:S.refusal}}),Yf(y.project_label,Date.parse(O)-Date.parse(y.started_at))),q.recordWorker(j).catch(()=>{})}function Ul(p,y={}){let w=Vc(p,y);if(w==null)return;let S=[w,...(lr??[]).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));lr=fn(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>=Nn});if(y.length===0)return[];let{dead:w}=await Za(y,Er);for(let S of w)Yn(S.worker_id),we("worker-death",S,"the host no longer confirms this Worker");return w.length>0&&te(),w}async function Bl(p,y){let w=C.get(p);if(!w)return!1;try{await Mn(w)}catch{}return Yn(p),we("worker-budget-kill",w,y),te(),!0}async function Hl(){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(),th(y.cpu_seconds,g);let{terminations:S}=sm({workers:p,rss:w}),O=[];for(let j of S)await Bl(j.worker_id,j.reason)&&O.push(j);return O}function th(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 nh(){try{return Pt<=0?await xt(t):await new Promise(p=>{let y=setTimeout(()=>p(_s()),Pt);y.unref(),xt(t).then(w=>{clearTimeout(y),p(w)},()=>{clearTimeout(y),p(_s())})})}catch{return _s()}}function _s(){try{return Hn(t)}catch{return null}}async function ql(){if(Ln(t))return x+=1,R=o(),A="local-build",{act:"hold",reason:"local-build"};let p=Gg(await nh()),y=p.version;_=y,V=p.newest??null,R=o(),z=Ig({running:t,newest:V,supervised:At});let w=$g({running:t,published:y,supervised:At});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 Zn(){let p=await ql();if(p.act!=="replace"||N==="in-progress")return p;let y=Ng(p,vr);return N="in-progress",await q.flush().catch(()=>{}),await he.flush().catch(()=>{}),await ro({reason:"replaced"}),Mg(y,r,{...n==null?{}:{idleMs:n},io:vr}),p}function oh(){pe||Wt!=null||Bn<=0||(!qn&&Ot>0&&(Kn=setTimeout(()=>{Zn().catch(()=>{})},Ot),Kn.unref()),Wt=setInterval(()=>{Zn().catch(()=>{})},Bn),Wt.unref())}async function Vl(){return await c.renew(d).catch(()=>null)}function sh(){pe||Nt!=null||Un<=0||(Nt=setInterval(()=>{Vl()},Un),Nt.unref())}function ih(){pe||Mt!=null||Tt<=0||(Mt=setInterval(()=>{Qr(o())},Tt),Mt.unref())}function ah(){pe||Ct!=null||Wn<=0||(Ct=setInterval(()=>{Hl().catch(()=>{})},Wn),Ct.unref())}function lh(){pe||Ut!=null||be==null||be.projects.length===0||Dt<=0||(ys().catch(()=>{}),Ut=setInterval(()=>{ys().catch(()=>{})},Dt),Ut.unref())}function dh(){if(pe||zr!=null||Lt<=0)return;let p=y=>{zr=setTimeout(()=>{zr=void 0,Kl().then(()=>jl()).catch(()=>{}).finally(()=>{if(pe)return;let w=Date.parse(o());p(gg(se,Lt,Number.isFinite(w)?w:Date.now()))})},y),zr.unref()};p(Lt)}async function Kl(){await Promise.allSettled([...U.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 ch(){pe||Ft!=null||Gt<=0||(Ft=setInterval(()=>{Ll().catch(()=>{})},Gt),Ft.unref())}function te(){pe||(Kr&&clearTimeout(Kr),Kr=setTimeout(()=>{bs().catch(()=>{}).then(()=>Jl())},n),Kr.unref())}function Jl(){return C.size>0?(te(),"held-by-workers"):(Qr(o()),U.size>0?(te(),"held-by-registrations"):(uh(),"exited"))}async function uh(){if(!Ln(t)){if((await Zn().catch(()=>null))?.act==="replace"||fs||pe)return;if(C.size>0||U.size>0){te();return}}await ro({reason:"idle"})}function eo(p){return _u({reason:p,socketPath:r.socketPath,daemonVersion:t,pid:d.pid,workers:[...C.values()],projects:[...U.keys()]})}function zl(p){if(Jn!=null)return Jn;let y=p.reason??"requested",w=p.note?.trim();return Jn=q.recordDaemonStop({ts:o(),pid:d.pid,socketPath:r.socketPath,reason:y,detail:w==null||w===""?eo(y).detail:`${eo(y).detail} \u2014 ${w}`,...p.signal==null?{}:{signal:p.signal}}).catch(()=>{}),Jn}async function ro(p={}){if(fs)return await hs;fs=!0,await zl(p),pe=!0,Kr&&clearTimeout(Kr),Ct&&clearInterval(Ct),Nt&&clearInterval(Nt),Mt&&clearInterval(Mt),Wt&&clearInterval(Wt),Kn&&clearTimeout(Kn),Ut&&clearInterval(Ut),Jr&&clearTimeout(Jr),zr&&clearTimeout(zr),Ft&&clearInterval(Ft),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 RT(r.socketPath,{force:!0}),Pl(),await hs}let Rs=await q.read().catch(()=>[]),to=new Map;for(let p of Rs){if(p.event==="worker-birth"){to.set(p.worker_id,p.ts);continue}let y=Oi(p.detail);Ul(p,{...to.get(p.worker_id)==null?{}:{startedAt:to.get(p.worker_id)},...y==null?{}:{refusal:y}}),(p.event==="worker-death"||p.event==="worker-budget-kill")&&to.delete(p.worker_id)}Tr=fn(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 ph=pu(Rs),ws=await Za(ph,Er);for(let p of ws.alive){let y=sg(p),w=y.unit==null||re(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 mh=og({units:await Promise.resolve(Fn()).catch(()=>[]),held:[...C.values()],mainPid:Br,now:ee});for(let p of mh)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");Al(o());for(let p of ws.alive){if(p.log_path==null||Ce.has(p.worker_id))continue;let y=await St(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)),te(),Qc(p,async(y,w)=>{te();let S=await gh(y);w(S),y.op==="shutdown"&&setImmediate(()=>void ro({reason:"requested"}).catch(()=>{}))})});async function gh(p){try{if(p.op==="ping")return{id:p.id,ok:!0,value:{pong:!0,protocol_version:es,daemon_version:t,pid:d.pid}};if(p.op==="host-state")return{id:p.id,ok:!0,value:zn()};if(p.op==="statusline-payload")return{id:p.id,ok:!0,value:bm(Qn(),p.extras)};if(p.op==="statusline-string")return{id:p.id,ok:!0,value:Kf(p.render)};if(p.op==="statusline-dashboard")return{id:p.id,ok:!0,value:Jf(p.dashboard)};if(p.op==="worker-heartbeat")return{id:p.id,ok:!0,value:Gl(p.heartbeat)};if(p.op==="project-register"){let w=$l(p.registration,p.session_project);return await he.flush(),{id:p.id,ok:!0,value:w}}if(p.op==="project-renew"){let w=Cl(p.project_label,{...p.session_project==null?{}:{sessionProject:p.session_project},...p.renew_within_ms==null?{}:{renewWithinMs:p.renew_within_ms},...p.launch==null?{}:{launch:p.launch}});return await he.flush(),{id:p.id,ok:!0,value:w}}if(p.op==="project-deregister"){let w=Nl(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:Il(p.project_label,p.session_project)};if(p.op==="worker-command")return{id:p.id,ok:!0,value:await zf(p.command)};if(p.op==="worker-start"){let w=Pr("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?Xn(p.spec):await Wl(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=eo("requested");return await zl({reason:"requested",...p.detail==null?{}:{note:p.detail}}),{id:p.id,ok:!0,value:w}}let y=p;return{id:y.id??Xg(),ok:!1,error:`unsupported redskilled op: ${y.op??"unknown"}`}}catch(y){return{id:p.id??Xg(),ok:!1,error:y instanceof Error?y.message:String(y)}}}return te(),ah(),sh(),ih(),oh(),lh(),Hf(),dh(),ch(),{socketPath:r.socketPath,lease:G.lease,startedAt:ee,closed:hs,startWorker:Xn,admit:Bt,ceiling:()=>l,killWorkerOverBudget:Bl,sampleMemoryBudgets:Hl,renewLease:Vl,pollRepositoryActivity:ys,pollGithubBalance:Dl,githubBalance:()=>xr,pollQueueDiscovery:jl,queueDiscovery:()=>se,driveDemand:Ll,demand:()=>It,sweepWorkerLiveness:bs,publishWorkerHeartbeat:Gl,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),te()},releaseWorker(p){let y=C.get(p),w=C.delete(p);return Pe.delete(p),Ce.delete(p),ar.delete(p),y&&we("worker-death",y,"released by the daemon"),te(),w},workerCount:()=>C.size,registerProject:$l,renewProject:Cl,resetProjectBirthBreaker:Il,deregisterProject:Nl,registrations:()=>zn().registrations??[],hostState:zn,refreshRegisteredTrunks:Kl,statuslinePayload:Qn,evaluateIdle:Jl,observePublishedVersion:ql,checkForReplacement:Zn,stopReport:eo,stop:ro}}function fl(e){let r=e.socketPath,t=ET(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 ${ef(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 \`${Rr("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 \`${Rr("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function hl(e){return`${e.reason} ${e.repair}`}function ET(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:vT(r.acquired_at,e.now??new Date().toISOString())}}function vT(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 ef(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`}tr();var nf=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"?`. ${hl(o)}`:""}`);this.socketPath=t;this.cause=n;this.presence=o;this.name="RedskilledUnreachableError"}},yl=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 Ve(e.socketPath),n=await Et(e.leasePath).catch(()=>{});return fl({socketPath:e.socketPath,answers:t,lease:n,holderAlive:n!=null&&re(n.pid)})}async function kl(e,r={}){try{return await PT(e,r)}catch(t){if(t instanceof pr||t instanceof Ur)throw t;let n=await ls(e).catch(()=>{});throw new Ur(e.socketPath,t,n)}}async function PT(e,r){if(await TT(xT(e.socketPath),{recursive:!0,mode:448}),await Ve(e.socketPath))return"already-running";await DT(e);let t=await AT(e,r);if(t!=null)return t;let n=await Pc(e.lockPath,{...r.spawnLockMaxAgeMs==null?{}:{maxAgeMs:r.spawnLockMaxAgeMs},onReap:r.onSpawnLockReaped??OT});if(!n.acquired)return await rf(e,r,void 0,n),"joined";try{if(await Ve(e.socketPath))return"already-running";let o=await LT(e,r);return await rf(e,r,o),"spawned"}finally{await Oc(n)}}function OT(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 AT(e,r){let t=await ls(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let n=r.readyTimeoutMs??nf,o=Date.now()+n;for(;;){if(await Ve(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(i=>setTimeout(i,25))}let s=await ls(e).catch(()=>{});if(s==null||s.kind!=="held-unresponsive")return null;throw new yl(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 DT(e){let t=await Do(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&re(t.pid))throw new pr(e.machineClaimPath,"held",t)}async function of(e,r,t={}){await kl(e,t);let n;try{n=await On({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...r,id:tf()})}catch(o){throw new Ur(e.socketPath,o,await ls(e).catch(()=>{}))}if(!n.ok)throw new as(n.error);return n.value}async function sf(e,r={},t={}){if(!await Ve(e.socketPath))return Ru(e.socketPath);let n;try{n=await On({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:tf(),op:"shutdown",...r.detail==null?{}:{detail:r.detail}})}catch(i){throw new Ur(e.socketPath,i)}if(!n.ok)throw new as(n.error);if(!Ii(n.value))throw new Error("redskilled daemon returned a malformed stop report");let o=n.value,s=await jT(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 jT(e,r,t){let n=Date.now()+t;for(;;){let o=[];if(await Ve(e.socketPath)&&o.push(`the socket ${JSON.stringify(e.socketPath)} still answers`),await Et(e.leasePath).catch(()=>{})&&o.push("the session lease is still held"),r!=null&&r!==process.pid&&re(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 af(e,r={}){let t=await of(e,{op:"host-state"},r);if(!Gm(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function lf(e,r={},t){let n=await of(e,{op:"statusline-payload",...r.sessionProject!=null?{session_project:r.sessionProject}:{},...t==null?{}:{extras:t}},r);if(!Oa(n))throw new Error("redskilled daemon returned a malformed statusline payload");return n}async function df(e,r=B,t={}){let n=await lf(e,t,{vitals:!0,logs:r.verbose,display:!0});return Fr(n,r)}async function cf(e,r={},t={}){let n=await lf(e,t,{vitals:!0,logs:!0,display:!0});return _t(n,{...Je,...r})}async function rf(e,r,t,n){let o=Date.now()+(r.readyTimeoutMs??nf);for(;;){if(await Ve(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 ${Ac(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 LT(e,r){let t=r.serverCommand??(r.serverArgs!=null?process.execPath:void 0),n=await Fc({...t!=null?{serverCommand:t}:{},serverArgs:r.serverArgs},r.entryLookup??{}),o={entry:n},s=[...n.args,...Lr(e,r.idleMs==null?{}:{idleMs:r.idleMs})],i=ST(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}tr();import{readFile as GT}from"node:fs/promises";import{homedir as IT,totalmem as $T}from"node:os";import{join as CT}from"node:path";var NT="REDSKILLED_IDLE_MS",MT=".red/config.yaml";async function pf(e=IT()){let r=CT(e,MT),t;try{t=await GT(r,"utf8")}catch(n){return n.code==="ENOENT"?{}:(bl(`redskilled: cannot read host config ${JSON.stringify(r)}; using environment and defaults instead: ${uf(n)}`),{})}try{let n=WT(t);return{...ds(n,"plugins.dev.redskilled.worker_ceiling","workerCeiling"),...ds(n,"plugins.dev.redskilled.memory_ceiling","memoryCeiling"),...ds(n,"plugins.dev.redskilled.validation_ceiling","validationCeiling"),...ds(n,"plugins.dev.redskilled.idle_ms","idleMs")}}catch(n){return bl(`redskilled: malformed host config ${JSON.stringify(r)}; using environment and defaults instead: ${uf(n)}`),{}}}function mf(e={}){let r=e.env??process.env,t=e.config??{},n=Po(r,e.totalMemoryBytes??$T(),{flags:e.flags,config:t,...e.availableParallelism==null?{}:{availableParallelism:e.availableParallelism}}),o=FT(e.flags?.idleMs==null?void 0:String(e.flags.idleMs),r[NT],t.idleMs);if(o==null)return{ceiling:n,idleMs:dt,idleMsSource:"derived-default"};let s=Number(o.value);return Number.isSafeInteger(s)&&s>0?{ceiling:n,idleMs:s,idleMsSource:o.source}:(bl(`redskilled: ${HT(o.source)} idle_ms=${JSON.stringify(o.value)} is not a positive integer; using the default ${dt}ms instead.`),{ceiling:n,idleMs:dt,idleMsSource:"derived-default"})}function FT(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 ds(e,r,t){let n=e[r];return n===void 0?{}:{[t]:n}}function WT(e){let r={},t=[];for(let[n,o]of e.split(/\r?\n/).entries()){let s=UT(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(".")]=BT(c.trim())}return r}function UT(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 BT(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function HT(e){return e==="flag"?"serve flag":e==="environment"?"environment":e==="home-config"?"home config":"derived default"}function uf(e){return e instanceof Error?e.message:String(e)}function bl(e){process.stderr.write(`${e}
|
|
104
|
+
`)}import{chmod as _f,mkdir as wf,readFile as Ef,stat as rx,writeFile as vf}from"node:fs/promises";import{homedir as wl}from"node:os";import{dirname as Sf,join as cs}from"node:path";import{join as qT}from"node:path";var gf=["local","tmp","host"],VT="local",Gn="plugins.dev.workspace.target";var _l=class extends Error{constructor(r){super(r),this.name="WorkspaceConfigError"}};function hf(e){let r=lt(e,Gn),t=zT(r??"").trim();return t===""?void 0:t}function yf(e){let r=(e??"").trim();if(r==="")return{kind:"preset",preset:VT};let t=gf.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 _l(`${Gn}: unknown workspace target ${JSON.stringify(r)}. Use one of the presets (${gf.join(", ")}) or an absolute parent directory for Workers.`)}function kf(e,r){return e.kind==="preset"?e.preset==="host":JT(KT(e.parentDir,r),Ue(r))}function KT(e,r){return e==="~"?ff(r):e.startsWith("~/")?qT(r,e.slice(2)):ff(e)}function JT(e,r){return e===r?!0:r==="/"?e.startsWith("/"):e.startsWith(`${r}/`)}function ff(e){let r=e.trim();return r.length>1?r.replace(/\/+$/,""):r}function zT(e){let r=e.trim(),t=/^(["'])(.*)\1$/.exec(r);return t?t[2]:r}tr();import{createHash as QT}from"node:crypto";import{hostname as YT}from"node:os";import{join as In}from"node:path";var vt="redskilled.sock",XT="REDSKILLED_SESSION";function ZT(e={}){let r=e.env??process.env,t=r[XT]?.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 ex(e={}){return bf(e.host??YT())}function Qe(e={}){let r=ZT(e),t=e.runtimeDir??Ro({key:`redskilled:${r}`,socketFileName:vt,env:e.env,uid:e.uid}),n=ex(e),o=e.homeDir??e.env?.HOME??(e.runtimeDir==null?process.env.HOME:e.runtimeDir)??t;return{sessionKey:r,sessionKeyHash:bf(r),machineIdHash:n,runtimeDir:t,socketPath:In(t,vt),lockPath:In(t,"redskilled.spawn.lock"),leasePath:In(t,"redskilled.lease.toon"),eventLanePath:In(Ue(o),cu),registrationIntentPath:In(t,"redskilled.registrations.toon"),machineClaimPath:e.machineClaimPath??Ao({env:e.env,machineIdHash:n,platform:e.platform})}}function bf(e){return QT("sha256").update(e).digest("hex").slice(0,12)}var Rl=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${Rr("red-skills-redskilled",["provision"])}\` directly`,tx=`# 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 Tf(e=wl()){let r=Ue(e),t=cs(Sf(r),"config.yaml"),n=await vl(r),o=!1,s=!1;n===void 0?(await wf(r,{recursive:!0,mode:rr}),await _f(r,rr),o=!0):n!==rr&&(await _f(r,rr),s=!0);let i=!1;try{await vf(t,tx,{encoding:"utf8",flag:"wx",mode:384}),i=!0}catch(a){if(a.code!=="EEXIST")throw a}return{path:r,created:o,tightened:s,mode:rr,configPath:t,configCreated:i}}var xf={needed:!1,declaredBy:`no ${Gn} in view`};async function El(e={}){let r=e.homeDir??wl(),t=e.declaredTarget?.trim();if(t)return Rf(t,r,"stated on the command line");let n=e.projectRoot?.trim();if(!n)return xf;let o=cs(n,".red","config.yaml"),s=await Ef(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=hf(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Rf(i,r,o)}function Rf(e,r,t){let n=`${Gn}: ${e} (${t})`;try{return{needed:kf(yf(e),r),declaredBy:n}}catch{return{needed:!1,declaredBy:`${n} \u2014 off-contract, so it names no lane under the home`}}}function Pf(e){let r=[nx(e),ox(e),sx(e),ix(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 nx(e){let r=e.homeNeed??xf;if(!e.homePresent)return r.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${r.declaredBy}`,fix:Rl}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${r.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??rr;return t!==rr?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${rr.toString(8)}`,fix:`${Rl} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function ox(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 \`${Rr("red-skills-redskilled",["provision"])}\``}}function sx(e){return e.reachable?{check:"reach",verdict:"ok",evidence:`daemon answered on ${e.socketPath}`,fix:""}:{check:"reach",verdict:"missing",evidence:`no daemon answered on ${e.socketPath}`,fix:`${Rl} \u2014 it starts the daemon and waits for the socket`}}function ix(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 Of(e={}){let r=e.env??process.env,t=e.homeDir??wl(),n=e.paths??Qe({env:r}),o=Ue(t),[s,i,a]=await Promise.all([vl(o),Ve(n.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):El({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:a,entry:ur(e.entryOverride??{},{env:r,...e.entryLookup}),socketPath:n.socketPath,reachable:i,supervisorUnit:await lx(dx(e,r,t),r)}}var ax="redskilled.service";function Af(e){return cs(e,"systemd","user",ax)}function Df(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 jf(e){let r=Af(e.configHome);return await vl(r)!==void 0?{path:r,status:"already-present"}:(await wf(Sf(r),{recursive:!0}),await vf(r,e.unit,"utf8"),{path:r,status:"installed"})}async function lx(e,r){if(process.platform!=="linux")return"unsupported";try{return await Ef(Af(e),"utf8"),"installed"}catch{return r.XDG_RUNTIME_DIR?"absent":"unsupported"}}function dx(e,r,t){return e.configHome??r.XDG_CONFIG_HOME?.trim()??cs(t,".config")}async function vl(e){try{return(await rx(e)).mode&511}catch{return}}import{readdir as Gf,rm as cx,stat as ux}from"node:fs/promises";import{dirname as px,join as Sl}from"node:path";var mx=5*6e4,gx="redskilled.";function fx(e={}){let r=e.env??process.env,t=i=>px(Ro({key:"redskilled:reclaim-probe",socketFileName:vt,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 If(e={}){let r=e.roots??fx(e),t=e.graceMs??mx,n=e.now??Date.now,o=e.isPidAlive??re,s=e.answers??bx,i=e.dryRun===!0,a=[];for(let l of r){let d;try{d=(await Gf(l,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name)}catch{continue}for(let c of d.sort())a.push(await hx(Sl(l,c),{graceMs:t,now:n,pidAlive:o,answers:s,dryRun:i}))}return{roots:r,scanned:a.length,reclaimed:a.filter(l=>l.verdict==="reclaimed").length,dryRun:i,entries:a}}async function hx(e,r){let t;try{t=(await Gf(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:$f(i),removed:[]}}let n=t.filter(i=>i.startsWith(gx));if(t.length>0&&n.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await yx(Sl(e,"redskilled.lease.toon"));if(o!==void 0)return await r.pidAlive(o.pid)?{dir:e,verdict:"live",reason:`lease pid ${o.pid} is alive`,removed:[]}:await Lf(e,t,`lease pid ${o.pid} is dead`,r);if(t.includes(vt)&&await r.answers(Sl(e,vt)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await kx(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 Lf(e,t,t.length===0?"empty and stale":"no lease and stale",r)}async function Lf(e,r,t,n){if(n.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:r};try{await cx(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:$f(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:r}}async function yx(e){try{return await Et(e)}catch{return}}async function kx(e,r){try{return Math.max(0,r()-(await ux(e)).mtimeMs)}catch{return}}async function bx(e){try{return(await On({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function $f(e){return e instanceof Error?e.message:String(e)}var _x="plugins.dev.statusline",Rx="dev.statusline";function wx(e){let r=[],t=a=>{for(let l of[_x,Rx]){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 Ex={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 Tl(e){let{values:r,positionals:t}=cr(e,Ex),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 xl(e={}){let r=e.configText==null?{config:{},warnings:[]}:wx(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 Sx=`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
|
+
`,Tx={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
|
|
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
|
|
223
|
-
`),a=
|
|
212
|
+
`};function xx(e){return e==="--help"||e==="-h"||e==="help"}var Px={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)}},Nf="REDSKILLED_HOST_TOKEN";function Cn(){try{let r=vx("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return r===""?null:r}catch{return null}}function Mf(e=process.env,r=Cn){let t=(e[Nf]??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 Ox(e,r=process.env,t=Cn,n){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...Cf(e,r,t,n),armTransport:()=>Cf(e,r,t,n)}}function Ax(e,r=process.env,t=Cn){let n=Mf(r,t);if(n==null)return null;let o=r.GITHUB_API_URL;return{transport:Ea({token:n.token,...o?{origin:o}:{}})}}function Cf(e,r=process.env,t=Cn,n){let o=Mf(r,t);if(o==null)return{unconfiguredReason:`no credential names a tracker for this host: ${Nf}, 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:hm({token:o.token,...s?{endpoint:s}:{},...n?{attribution:n}:{}})}}async function Dx(e){if(e[0]==="--version"||e[0]==="-v"){let o=qs("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
|
|
213
|
+
`:`${Id(o)}
|
|
214
|
+
`),0}if(xx(e[0]))return process.stdout.write(Sx),0;let{command:r,args:t}=Md(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(Tx[r]),0;if(r==="serve"){let{values:o}=cr(t,Px),s=await pf($n()),i=mf({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=us(Ue($n()),"state"),l=Go({path:us(a,"github","spend.toonl")}),d=Ox(o,process.env,Cn,l),c=Ax(o),u=sc({stateRoot:a});process.stderr.write(`${ic(u)}
|
|
215
|
+
`);let m=ec({lanePath:Yt(a),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),f=await Zg({paths:Hx(o),idleMs:i.idleMs,ceiling:i.ceiling,daemonVersion:o["daemon-version"]??qs("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 $x(t);if(r==="statusline")return await Nx(t);if(r==="dashboard")return await Vx(t);if(r==="github-spend")return await Lx(t);if(r==="unit")return await Cx(t);if(r==="provision")return await Fx(t);if(r==="reclaim")return await Ux(t);let n=await af(Qe());return process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
216
|
+
`),0}var jx={pool:{kind:"value",coerce:e=>e},hours:{kind:"value",coerce:e=>Number(e)}};async function Lx(e,r={}){let{values:t}=cr(e,jx,{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:Gx(o),i=(r.now??(()=>new Date().toISOString()))(),a=Date.parse(i);if(!Number.isFinite(a))throw new Error(`redskilled github-spend clock returned an invalid instant: ${i}`);let l=new Date(a-n*60*60*1e3).toISOString(),c=await(r.ledger??Go({path:us(Ue(r.homeDir??$n()),"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 Gx(e){if(e==="graphql"||e==="rest"||e==="search")return e;throw new Error(`redskilled github-spend --pool must be graphql, rest, search or all; received ${JSON.stringify(e)}`)}var Ix={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function $x(e,r={}){let t=r.write??(s=>process.stdout.write(s)),{values:n}=cr(e,Ix),o=await sf(r.paths??Qe(),{...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 Cx(e,r={}){let t=r.write??(s=>process.stdout.write(s)),n=r.paths??Qe(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(xg(r.unitIO??{}),null,2)}
|
|
219
|
+
`),0;if(o==="install"){let s=await Sg(Eg(n),r.unitIO??{});return t(`${JSON.stringify(s,null,2)}
|
|
220
|
+
`),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await Tg(r.unitIO??{}),null,2)}
|
|
221
|
+
`),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function Nx(e,r={}){let t=r.write??(l=>process.stdout.write(l)),n=r.warn??(l=>process.stderr.write(l)),o=Tl(e),s=Ff(r.cwd??process.cwd()),i=xl({...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 df(r.paths??Qe(),i.options,{...r.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(l){n(`redskilled statusline: ${l instanceof Error?l.message:String(l)}
|
|
223
|
+
`),a=Ka({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 Mx={"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 Fx(e,r={}){let t=r.write??(m=>process.stdout.write(m)),{values:n}=cr(e,Mx),o=r.paths??Qe(),s=r.homeDir??$n(),i=await El({homeDir:s,declaredTarget:n.workspace,projectRoot:n.project??r.projectRoot??process.cwd()}),a=n.check||!i.needed?void 0:await Tf(s),l;if(!n.check&&!n["no-start"])try{await kl(o,r.client??{})}catch(m){l=m instanceof Error?m.message:String(m)}let d=await Of({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 jf({configHome:r.configHome??Bx(),unit:Df({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=Pf(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 Wx={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function Ux(e,r={}){let t=r.write??(s=>process.stdout.write(s)),{values:n}=cr(e,Wx),o=await If({...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 Bx(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:us($n(),".config")}function Ff(e){let r=ci(e);return r.configText==null?{label:null}:{configText:r.configText,label:gc(e)}}function Hx(e){let r=Qe();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 qx=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;if(qx){let e=process.argv.slice(2);Dx(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 Vx(e,r={}){let t=r.write??(a=>process.stdout.write(a)),n=r.warn??(a=>process.stderr.write(a)),o=Tl(e),s=Ff(r.cwd??process.cwd()),i=xl({...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 cf(r.paths??Qe(),{...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{Nf as REDSKILLED_HOST_TOKEN_ENV,Sx as REDSKILLED_USAGE,Cf as armRedskilledQueueTransport,Mf as resolveRedskilledHostToken,Ax as resolveServeGithubBalance,Ox as resolveServeQueueDiscovery,Vx as runDashboard,Lx as runGithubSpend,Fx as runProvision,Ux as runReclaim,Dx as runRedskilledCli,Nx as runStatusline,$x as runStop,Cx as runUnit};
|
|
234
234
|
/*! Bundled license information:
|
|
235
235
|
|
|
236
236
|
content-type/dist/index.js:
|