@reddb-io/red-skills 3.5.1 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -37,7 +37,7 @@ var zE=Object.create;var ya=Object.defineProperty;var YE=Object.getOwnPropertyDe
37
37
  `;return _+=v,a+=1,c+=1,u+=v.length,_},declareLane(E,y){if(p)throw j(0,"TOONL encoder is closed");let _=Ok(y),T=Ha(Q,_),v=k(E);return Mp(v.fields,_)?"":(v.fields=_,Fp(E,T))},pushTagged(E,y){if(p)throw j(0,"TOONL encoder is closed");let _=k(E),T=Up(jp(y),_.fieldsByShape),v=Ha(Q,T),G=T.map(V=>Ee(y[V],Q)),B="";return Mp(_.fields,T)||(_.fields=T,B+=Fp(E,v)),`${B}${E}:${G.join(Q)}
38
38
  `},end(){return p?"":(p=!0,g())}}}var Hp,qp,Wp,gN,hN,Vp=h(()=>{kt();jn();fr();Hp=[Q,"|"," "],qp=8,Wp=/^[A-Za-z0-9_-]+$/,gN=new TextEncoder,hN=new TextDecoder});var W=h(()=>{op();kt();jn();jn();Gp();Vp()});function Lk(e){return e==="no-op"?0:e==="usage"?2:1}function J(e){return Buffer.from(`${$(qa(e))}
39
39
  `)}function qa(e){let t={command:e.command,category:e.category,exit_code:e.exitCode??Lk(e.category),error:e.error,help:[e.help]};return e.validFlags&&e.validFlags.length>0&&(t.valid_flags=[...e.validFlags]),e.diagnostics&&(t.diagnostics=Dk(e.diagnostics,3)),t}function Ve(e,t,r){let s=([r,t].find(i=>i.trim())??"").trim(),o=s.toLowerCase();return/\bgh\b/.test(e)&&np(s)?{command:e,category:"transient",error:Un(s)||"GitHub API rate limit exceeded",help:rp,diagnostics:s}:/\bgh\b/.test(e)&&(o.includes("gh_token")||o.includes("not logged in")||o.includes("authentication"))?{command:e,category:"real-error",error:Un(s)||"GitHub authentication failed",help:"gh auth login",diagnostics:s}:o.includes("not a git repository")?{command:e,category:"real-error",error:Un(s)||"not a git repository",help:"git status",diagnostics:s}:o.includes("repository not found")||o.includes("could not resolve host")?{command:e,category:"real-error",error:Un(s)||"repository is unavailable",help:e.startsWith("gh ")?"gh repo view":"git remote -v",diagnostics:s}:{command:e,category:"real-error",error:Un(s)||"command failed",help:`${e} --help`,diagnostics:s}}function Kp(e,t,r,n){return J({command:e,category:"usage",error:`unknown flag: ${t}`,help:n,validFlags:r})}function Un(e){return e.split(/\r?\n/,1)[0]?.trim()??""}function Dk(e,t){return e.split(/\r?\n/).slice(0,t).join(`
40
- `).trim()}var ut=h(()=>{"use strict";sp();W()});function lo(e){let t={app:e,version:Wk(Kr("__RED_BUILD_VERSION__",()=>"3.5.1")??"0.0.0-dev"),gitSha:Kr("__RED_BUILD_GIT_SHA__",()=>"3a85e059fd10de65880fd7233fc71449463b03d1")??"unknown",buildTime:Kr("__RED_BUILD_TIME__",()=>"2026-08-05T02:34:10Z")??"unknown",bundleAsset:Kr("__RED_BUNDLE_ASSET__",()=>"rsp.bundle.min.mjs")??"unknown"},r=Kr("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=Kr("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Wk(e){return e.startsWith("v")?e.slice(1):e}function nm(e){return`${e.app} ${e.version} ${e.gitSha}`}function Kr(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var Ja=h(()=>{});import{isAbsolute as Jk,join as St,resolve as Va}from"node:path";function zk(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function om(e){return St(zk(e),sm)}function im(e){return St(om(e),"state")}function am(e){return St(om(e),"tmp")}function ne(e){return St(im(e),"rsp")}function Yk(e){return St(im(e),"red-skills.rdb")}function Qk(e){return St(am(e),"red-skills.rdb")}function lm(e,t){let r=Yk(e);if(t(r))return r;let n=Qk(e);if(t(n))throw Xk();return r}function Xk(){return new Error("Legacy shared store found at .red/tmp/red-skills.rdb. Run `rsp setup` to migrate it to .red/state/red-skills.rdb before using rsp, memory, or brain.")}function dm(e){return St(am(e),"waits")}function pm(e){let t=e.overrideEnvVars??Ka;for(let n of t){let s=e.env[n];if(s)return Jk(s)?s:Va(e.startDir,s)}let r=Va(e.startDir);for(;;){if(e.exists(St(r,sm)))return r;let n=St(r,".."),s=Va(n);if(s===r)break;r=s}return e.startDir}var sm,Vk,Kk,Ka,cm,um,$e=h(()=>{sm=".red",Vk="MEMORY_ROOT",Kk="RED_BRAIN_ROOT",Ka=[Vk,Kk];cm=".red/state/red-skills.rdb";um=".red/tmp/red-skills.rdb"});function se(e){return $(e,{keyedMapCollapse:!0})}var Zk,eS,XN,Tt=h(()=>{W();$e();Zk=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],eS=[{id:"dev.afk-history",plugin:"dev",legacyPath:".red/state/afk-history.jsonl",toonPath:".red/state/castle/history.toonl",kind:"toonl"},{id:"dev.agent-log",plugin:"dev",legacyPath:".red/tmp/agent.log.toonl",toonPath:".red/tmp/agent.log.toonl",kind:"toonl"},{id:"dev.supervisor-firehose",plugin:"dev",legacyPath:".red/tmp/afk-supervisor.log.toonl",toonPath:".red/tmp/supervisors/default/supervisor.log.toonl",kind:"toonl",migration:"sniff-read"},{id:"dev.code-understanding-bench-runs",plugin:"dev",legacyPath:".red/tmp/bench/code-understanding/runs.jsonl",toonPath:".red/tmp/bench/code-understanding/runs.toonl",kind:"toonl"},{id:"dev.attempt-state",plugin:"dev",legacyPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",toonPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",kind:"toon"},{id:"dev.statusline-count-cache",plugin:"dev",legacyPath:".red/tmp/statusline-cache.json",toonPath:".red/state/statusline/statusline-cache.toon",kind:"toon"},{id:"dev.statusline-repo-cache",plugin:"dev",legacyPath:".red/tmp/statusline-repo-cache.json",toonPath:".red/state/statusline/statusline-repo-cache.toon",kind:"toon"},{id:"dev.rsp-resident-registry",plugin:"dev",legacyPath:".red/state/rsp/rsp-resident.pid.json",toonPath:".red/state/rsp/rsp-resident.pid.json",kind:"toon"},{id:"dev.rsp-status-summary",plugin:"dev",legacyPath:".red/state/rsp/rsp-status-summary.json",toonPath:".red/state/rsp/rsp-status-summary.json",kind:"toon"},{id:"dev.rsp-wait-registry",plugin:"dev",legacyPath:".red/tmp/waits/*.json",toonPath:".red/tmp/waits/*.json",kind:"toon"}],XN=[...Zk,...eS]});function Hn(e){let{values:t,rest:r}=dr(e,{query:mm.query},fm);return{argv:r,query:t.query?.trim()||void 0}}function gm(e){let{values:t,rest:r}=dr(e,mm,fm);return{argv:r,query:t.query?.trim()||void 0,full:t.full===!0}}function tS(e,t){if(!t)return!0;let r=za(e).toLowerCase();return t.toLowerCase().split(/\s+/).filter(Boolean).every(n=>r.includes(n))}function Re(e,t){return t?e.filter(r=>tS(r,t)):[...e]}function vt(e,t){return Ya(e,t,{includeLegacyHelp:!0})}function Ya(e,t,r={}){let n=t.filter(Boolean);return n.length===0?e:{...e,...r.includeLegacyHelp?{help:n}:{},next_steps:n}}function za(e){return Array.isArray(e)?e.map(za).join(" "):typeof e=="object"&&e!==null?Object.values(e).map(za).join(" "):String(e??"")}var mm,fm,qn=h(()=>{"use strict";Ra();mm={query:{kind:"value",coerce:e=>e},full:{kind:"boolean"}},fm={stopAtSeparator:!1}});var wo={};K(wo,{DEFAULT_RSP_MAX_OVERHEAD_MS:()=>po,DEFAULT_RSP_MAX_SELF_STATE_BYTES:()=>mo,DEFAULT_RSP_OVERHEAD_CEILING:()=>Ke,DEFAULT_RSP_OVERHEAD_CONSECUTIVE_BREACHES:()=>go,DEFAULT_RSP_OVERHEAD_COOLDOWN_MS:()=>ho,DEFAULT_RSP_OVERHEAD_NET_LOSS_FLOOR_BYTES:()=>fo,RSP_OVERHEAD_FAMILIES:()=>cS,RSP_OVERHEAD_LEDGER_FILE:()=>bm,RSP_OVERHEAD_SCHEMA_VERSION:()=>wm,classifyOverheadSample:()=>Za,noteChildProcessMs:()=>Em,noteSelfStateBytesRead:()=>Vn,overheadCounters:()=>Kn,overheadFamilyDisabled:()=>tc,overheadHealth:()=>Wt,overheadLedgerPath:()=>ec,overheadMsOf:()=>_m,overheadTelemetryFields:()=>yo,readOverheadLedger:()=>Wn,readSelfStateFile:()=>bo,readSelfStateFileSync:()=>dS,recordOverheadSample:()=>Jn,resetOverheadCounters:()=>lS,resetOverheadLedger:()=>uS,startChildProcessTimer:()=>ke});import{existsSync as rS,mkdirSync as nS,readFileSync as hm,renameSync as sS,writeFileSync as oS}from"node:fs";import{readFile as iS}from"node:fs/promises";import{dirname as aS,join as ym}from"node:path";function _m(e){let t=e.wrapperMs-e.childMs;return Number.isFinite(t)?Math.max(0,Xa(t)):0}function Za(e,t=Ke){let r=_m(e),n=[];return r>t.maxOverheadMs&&n.push("wall-clock-ceiling"),e.selfStateBytesRead>t.maxSelfStateBytes&&n.push("self-state-byte-ceiling"),e.selfStateBytesRead>t.netLossFloorBytes&&e.selfStateBytesRead>e.bytesSaved&&n.push("overhead-exceeds-savings"),{overhead_ms:r,breached:n.length>0,reasons:n}}function yo(e,t=Ke){let r=Za(e,t);return{wrapper_ms:Xa(e.wrapperMs),overhead_ms:r.overhead_ms,child_ms:Xa(Math.max(0,e.childMs)),self_state_bytes_read:Math.max(0,Math.trunc(e.selfStateBytesRead)),bytes_saved:Math.max(0,Math.trunc(e.bytesSaved)),overhead_breached:r.breached,overhead_breach_reasons:r.reasons.join(",")}}function ec(e){return ym(ne(e),bm)}function Wn(e){try{let t=hm(ec(e),"utf8"),r=gS(t);if(hS(r))return r}catch{}return{version:1,families:{}}}function Jn(e,t,r=Ke,n=Date.now()){let s=Wn(e),o=Za(t,r),i=s.families[t.family]??fS(t.family,n),a=sc(i,n)?Rm(i):i,c=o.breached?a.consecutive_breaches+1:0,u={...a,family:t.family,invocations:a.invocations+1,breaches:a.breaches+(o.breached?1:0),consecutive_breaches:c,breached:o.breached,reasons:o.reasons,last_overhead_ms:o.overhead_ms,last_self_state_bytes_read:Math.max(0,Math.trunc(t.selfStateBytesRead)),last_bytes_saved:Math.max(0,Math.trunc(t.bytesSaved)),updated_at:new Date(n).toISOString()};return o.breached?c>=r.consecutiveBreaches&&(u.disabled=!0,u.disabled_at=new Date(n).toISOString(),u.disabled_until=new Date(n+r.cooldownMs).toISOString(),u.disabled_reason=pS(t.family,c,o,r)):(u.disabled=!1,u.disabled_at=null,u.disabled_until=null,u.disabled_reason=null),s.families[t.family]=u,km(e,s),u}function tc(e,t,r=Date.now()){let n=Wn(e).families[t];return!n?.disabled||sc(n,r)?null:n}function uS(e,t){let r=Wn(e);return t?delete r.families[t]:r.families={},km(e,r),r}function Wt(e,t=Ke,r=Date.now()){let n=Object.values(Wn(e).families).map(a=>sc(a,r)?Rm(a):a).sort((a,c)=>a.family.localeCompare(c.family)),s=n.filter(a=>a.disabled),o=n.filter(a=>a.consecutive_breaches>0),i=s.length>0||o.length>0?"red":"green";return{schema_version:wm,verdict:i,summary:mS(i,s,o),ceiling:t,breaching_families:o,disabled_families:s,families:n}}function Vn(e){Number.isFinite(e)&&e>0&&(rc+=e)}function Em(e){Number.isFinite(e)&&e>0&&(nc+=e)}function Kn(){return{selfStateBytesRead:rc,childMs:nc}}function lS(){rc=0,nc=0}function ke(){let e=process.hrtime.bigint(),t=!1;return()=>{t||(t=!0,Em(Number(process.hrtime.bigint()-e)/1e6))}}async function bo(e){let t=await iS(e,"utf8");return Vn(Buffer.byteLength(t)),t}function dS(e){let t=hm(e,"utf8");return Vn(Buffer.byteLength(t)),t}function pS(e,t,r,n){let s=r.reasons.map(o=>o==="wall-clock-ceiling"?`added ${r.overhead_ms}ms > ${n.maxOverheadMs}ms`:o==="self-state-byte-ceiling"?`self-state read > ${n.maxSelfStateBytes}B`:"self-state read exceeded bytes saved").join("; ");return`rsp ${e} exceeded its overhead ceiling on ${t} consecutive invocations (${s}); wrapper self-disabled, commands pass through raw`}function mS(e,t,r){if(e==="green")return"every wrapper family is inside its overhead ceiling";let n=[];return t.length>0&&n.push(`self-disabled: ${t.map(s=>`${s.family} (${s.reasons.join(",")||"ceiling"})`).join(", ")}`),r.length>0&&n.push(`breaching: ${r.map(s=>`${s.family} x${s.consecutive_breaches}`).join(", ")}`),n.join("; ")}function sc(e,t){if(!e.disabled||!e.disabled_until)return!1;let r=Date.parse(e.disabled_until);return Number.isFinite(r)&&r<=t}function Rm(e){return{...e,disabled:!1,disabled_at:null,disabled_until:null,disabled_reason:null,consecutive_breaches:0,breached:!1,reasons:[]}}function fS(e,t){return{family:e,invocations:0,breaches:0,consecutive_breaches:0,breached:!1,reasons:[],disabled:!1,disabled_at:null,disabled_until:null,disabled_reason:null,last_overhead_ms:0,last_self_state_bytes_read:0,last_bytes_saved:0,updated_at:new Date(t).toISOString()}}function km(e,t){try{let r=ec(e);if(!rS(ym(e,".red")))return;nS(aS(r),{recursive:!0});let n=`${r}.${process.pid}.tmp`;oS(n,`${$(t)}
40
+ `).trim()}var ut=h(()=>{"use strict";sp();W()});function lo(e){let t={app:e,version:Wk(Kr("__RED_BUILD_VERSION__",()=>"3.6.0")??"0.0.0-dev"),gitSha:Kr("__RED_BUILD_GIT_SHA__",()=>"dd8922efad583c6a2a7b6a4963ba4f3f5334eaac")??"unknown",buildTime:Kr("__RED_BUILD_TIME__",()=>"2026-08-05T04:59:15Z")??"unknown",bundleAsset:Kr("__RED_BUNDLE_ASSET__",()=>"rsp.bundle.min.mjs")??"unknown"},r=Kr("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=Kr("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Wk(e){return e.startsWith("v")?e.slice(1):e}function nm(e){return`${e.app} ${e.version} ${e.gitSha}`}function Kr(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var Ja=h(()=>{});import{isAbsolute as Jk,join as St,resolve as Va}from"node:path";function zk(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function om(e){return St(zk(e),sm)}function im(e){return St(om(e),"state")}function am(e){return St(om(e),"tmp")}function ne(e){return St(im(e),"rsp")}function Yk(e){return St(im(e),"red-skills.rdb")}function Qk(e){return St(am(e),"red-skills.rdb")}function lm(e,t){let r=Yk(e);if(t(r))return r;let n=Qk(e);if(t(n))throw Xk();return r}function Xk(){return new Error("Legacy shared store found at .red/tmp/red-skills.rdb. Run `rsp setup` to migrate it to .red/state/red-skills.rdb before using rsp, memory, or brain.")}function dm(e){return St(am(e),"waits")}function pm(e){let t=e.overrideEnvVars??Ka;for(let n of t){let s=e.env[n];if(s)return Jk(s)?s:Va(e.startDir,s)}let r=Va(e.startDir);for(;;){if(e.exists(St(r,sm)))return r;let n=St(r,".."),s=Va(n);if(s===r)break;r=s}return e.startDir}var sm,Vk,Kk,Ka,cm,um,$e=h(()=>{sm=".red",Vk="MEMORY_ROOT",Kk="RED_BRAIN_ROOT",Ka=[Vk,Kk];cm=".red/state/red-skills.rdb";um=".red/tmp/red-skills.rdb"});function se(e){return $(e,{keyedMapCollapse:!0})}var Zk,eS,XN,Tt=h(()=>{W();$e();Zk=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],eS=[{id:"dev.afk-history",plugin:"dev",legacyPath:".red/state/afk-history.jsonl",toonPath:".red/state/castle/history.toonl",kind:"toonl"},{id:"dev.agent-log",plugin:"dev",legacyPath:".red/tmp/agent.log.toonl",toonPath:".red/tmp/agent.log.toonl",kind:"toonl"},{id:"dev.supervisor-firehose",plugin:"dev",legacyPath:".red/tmp/afk-supervisor.log.toonl",toonPath:".red/tmp/supervisors/default/supervisor.log.toonl",kind:"toonl",migration:"sniff-read"},{id:"dev.code-understanding-bench-runs",plugin:"dev",legacyPath:".red/tmp/bench/code-understanding/runs.jsonl",toonPath:".red/tmp/bench/code-understanding/runs.toonl",kind:"toonl"},{id:"dev.attempt-state",plugin:"dev",legacyPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",toonPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",kind:"toon"},{id:"dev.statusline-count-cache",plugin:"dev",legacyPath:".red/tmp/statusline-cache.json",toonPath:".red/state/statusline/statusline-cache.toon",kind:"toon"},{id:"dev.statusline-repo-cache",plugin:"dev",legacyPath:".red/tmp/statusline-repo-cache.json",toonPath:".red/state/statusline/statusline-repo-cache.toon",kind:"toon"},{id:"dev.rsp-resident-registry",plugin:"dev",legacyPath:".red/state/rsp/rsp-resident.pid.json",toonPath:".red/state/rsp/rsp-resident.pid.json",kind:"toon"},{id:"dev.rsp-status-summary",plugin:"dev",legacyPath:".red/state/rsp/rsp-status-summary.json",toonPath:".red/state/rsp/rsp-status-summary.json",kind:"toon"},{id:"dev.rsp-wait-registry",plugin:"dev",legacyPath:".red/tmp/waits/*.json",toonPath:".red/tmp/waits/*.json",kind:"toon"}],XN=[...Zk,...eS]});function Hn(e){let{values:t,rest:r}=dr(e,{query:mm.query},fm);return{argv:r,query:t.query?.trim()||void 0}}function gm(e){let{values:t,rest:r}=dr(e,mm,fm);return{argv:r,query:t.query?.trim()||void 0,full:t.full===!0}}function tS(e,t){if(!t)return!0;let r=za(e).toLowerCase();return t.toLowerCase().split(/\s+/).filter(Boolean).every(n=>r.includes(n))}function Re(e,t){return t?e.filter(r=>tS(r,t)):[...e]}function vt(e,t){return Ya(e,t,{includeLegacyHelp:!0})}function Ya(e,t,r={}){let n=t.filter(Boolean);return n.length===0?e:{...e,...r.includeLegacyHelp?{help:n}:{},next_steps:n}}function za(e){return Array.isArray(e)?e.map(za).join(" "):typeof e=="object"&&e!==null?Object.values(e).map(za).join(" "):String(e??"")}var mm,fm,qn=h(()=>{"use strict";Ra();mm={query:{kind:"value",coerce:e=>e},full:{kind:"boolean"}},fm={stopAtSeparator:!1}});var wo={};K(wo,{DEFAULT_RSP_MAX_OVERHEAD_MS:()=>po,DEFAULT_RSP_MAX_SELF_STATE_BYTES:()=>mo,DEFAULT_RSP_OVERHEAD_CEILING:()=>Ke,DEFAULT_RSP_OVERHEAD_CONSECUTIVE_BREACHES:()=>go,DEFAULT_RSP_OVERHEAD_COOLDOWN_MS:()=>ho,DEFAULT_RSP_OVERHEAD_NET_LOSS_FLOOR_BYTES:()=>fo,RSP_OVERHEAD_FAMILIES:()=>cS,RSP_OVERHEAD_LEDGER_FILE:()=>bm,RSP_OVERHEAD_SCHEMA_VERSION:()=>wm,classifyOverheadSample:()=>Za,noteChildProcessMs:()=>Em,noteSelfStateBytesRead:()=>Vn,overheadCounters:()=>Kn,overheadFamilyDisabled:()=>tc,overheadHealth:()=>Wt,overheadLedgerPath:()=>ec,overheadMsOf:()=>_m,overheadTelemetryFields:()=>yo,readOverheadLedger:()=>Wn,readSelfStateFile:()=>bo,readSelfStateFileSync:()=>dS,recordOverheadSample:()=>Jn,resetOverheadCounters:()=>lS,resetOverheadLedger:()=>uS,startChildProcessTimer:()=>ke});import{existsSync as rS,mkdirSync as nS,readFileSync as hm,renameSync as sS,writeFileSync as oS}from"node:fs";import{readFile as iS}from"node:fs/promises";import{dirname as aS,join as ym}from"node:path";function _m(e){let t=e.wrapperMs-e.childMs;return Number.isFinite(t)?Math.max(0,Xa(t)):0}function Za(e,t=Ke){let r=_m(e),n=[];return r>t.maxOverheadMs&&n.push("wall-clock-ceiling"),e.selfStateBytesRead>t.maxSelfStateBytes&&n.push("self-state-byte-ceiling"),e.selfStateBytesRead>t.netLossFloorBytes&&e.selfStateBytesRead>e.bytesSaved&&n.push("overhead-exceeds-savings"),{overhead_ms:r,breached:n.length>0,reasons:n}}function yo(e,t=Ke){let r=Za(e,t);return{wrapper_ms:Xa(e.wrapperMs),overhead_ms:r.overhead_ms,child_ms:Xa(Math.max(0,e.childMs)),self_state_bytes_read:Math.max(0,Math.trunc(e.selfStateBytesRead)),bytes_saved:Math.max(0,Math.trunc(e.bytesSaved)),overhead_breached:r.breached,overhead_breach_reasons:r.reasons.join(",")}}function ec(e){return ym(ne(e),bm)}function Wn(e){try{let t=hm(ec(e),"utf8"),r=gS(t);if(hS(r))return r}catch{}return{version:1,families:{}}}function Jn(e,t,r=Ke,n=Date.now()){let s=Wn(e),o=Za(t,r),i=s.families[t.family]??fS(t.family,n),a=sc(i,n)?Rm(i):i,c=o.breached?a.consecutive_breaches+1:0,u={...a,family:t.family,invocations:a.invocations+1,breaches:a.breaches+(o.breached?1:0),consecutive_breaches:c,breached:o.breached,reasons:o.reasons,last_overhead_ms:o.overhead_ms,last_self_state_bytes_read:Math.max(0,Math.trunc(t.selfStateBytesRead)),last_bytes_saved:Math.max(0,Math.trunc(t.bytesSaved)),updated_at:new Date(n).toISOString()};return o.breached?c>=r.consecutiveBreaches&&(u.disabled=!0,u.disabled_at=new Date(n).toISOString(),u.disabled_until=new Date(n+r.cooldownMs).toISOString(),u.disabled_reason=pS(t.family,c,o,r)):(u.disabled=!1,u.disabled_at=null,u.disabled_until=null,u.disabled_reason=null),s.families[t.family]=u,km(e,s),u}function tc(e,t,r=Date.now()){let n=Wn(e).families[t];return!n?.disabled||sc(n,r)?null:n}function uS(e,t){let r=Wn(e);return t?delete r.families[t]:r.families={},km(e,r),r}function Wt(e,t=Ke,r=Date.now()){let n=Object.values(Wn(e).families).map(a=>sc(a,r)?Rm(a):a).sort((a,c)=>a.family.localeCompare(c.family)),s=n.filter(a=>a.disabled),o=n.filter(a=>a.consecutive_breaches>0),i=s.length>0||o.length>0?"red":"green";return{schema_version:wm,verdict:i,summary:mS(i,s,o),ceiling:t,breaching_families:o,disabled_families:s,families:n}}function Vn(e){Number.isFinite(e)&&e>0&&(rc+=e)}function Em(e){Number.isFinite(e)&&e>0&&(nc+=e)}function Kn(){return{selfStateBytesRead:rc,childMs:nc}}function lS(){rc=0,nc=0}function ke(){let e=process.hrtime.bigint(),t=!1;return()=>{t||(t=!0,Em(Number(process.hrtime.bigint()-e)/1e6))}}async function bo(e){let t=await iS(e,"utf8");return Vn(Buffer.byteLength(t)),t}function dS(e){let t=hm(e,"utf8");return Vn(Buffer.byteLength(t)),t}function pS(e,t,r,n){let s=r.reasons.map(o=>o==="wall-clock-ceiling"?`added ${r.overhead_ms}ms > ${n.maxOverheadMs}ms`:o==="self-state-byte-ceiling"?`self-state read > ${n.maxSelfStateBytes}B`:"self-state read exceeded bytes saved").join("; ");return`rsp ${e} exceeded its overhead ceiling on ${t} consecutive invocations (${s}); wrapper self-disabled, commands pass through raw`}function mS(e,t,r){if(e==="green")return"every wrapper family is inside its overhead ceiling";let n=[];return t.length>0&&n.push(`self-disabled: ${t.map(s=>`${s.family} (${s.reasons.join(",")||"ceiling"})`).join(", ")}`),r.length>0&&n.push(`breaching: ${r.map(s=>`${s.family} x${s.consecutive_breaches}`).join(", ")}`),n.join("; ")}function sc(e,t){if(!e.disabled||!e.disabled_until)return!1;let r=Date.parse(e.disabled_until);return Number.isFinite(r)&&r<=t}function Rm(e){return{...e,disabled:!1,disabled_at:null,disabled_until:null,disabled_reason:null,consecutive_breaches:0,breached:!1,reasons:[]}}function fS(e,t){return{family:e,invocations:0,breaches:0,consecutive_breaches:0,breached:!1,reasons:[],disabled:!1,disabled_at:null,disabled_until:null,disabled_reason:null,last_overhead_ms:0,last_self_state_bytes_read:0,last_bytes_saved:0,updated_at:new Date(t).toISOString()}}function km(e,t){try{let r=ec(e);if(!rS(ym(e,".red")))return;nS(aS(r),{recursive:!0});let n=`${r}.${process.pid}.tmp`;oS(n,`${$(t)}
41
41
  `,{encoding:"utf8",mode:384}),sS(n,r)}catch{}}function gS(e){try{return JSON.parse(e)}catch{return H(e)}}function hS(e){return!Qa(e)||e.version!==1||!Qa(e.families)?!1:Object.values(e.families).every(yS)}function yS(e){return Qa(e)&&typeof e.family=="string"&&typeof e.consecutive_breaches=="number"&&typeof e.disabled=="boolean"}function Qa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xa(e){return Number.isFinite(e)?Math.round(e*1e3)/1e3:0}var bm,wm,po,mo,fo,go,ho,cS,Ke,rc,nc,oe=h(()=>{"use strict";$e();W();bm="overhead-budget.toon",wm="red.rsp.overhead.v1",po=250,mo=1024*1024,fo=64*1024,go=3,ho=6*60*60*1e3,cS=["git","gh","gh-api-json","vitest","cargo","cat","exec","proxy"],Ke={maxOverheadMs:po,maxSelfStateBytes:mo,netLossFloorBytes:fo,consecutiveBreaches:go,cooldownMs:ho};rc=0,nc=0});function vm(e){return e.trimStart().startsWith("{")?"json":"toon"}function ic(e){let t=0;for(;e[t]===`
42
42
  `||e[t]==="\r";)t+=1;let r=e.slice(t);if(r==="")return null;let n=vm(r);if(n==="json"){let o=r.indexOf(`
43
43
  `);return o<0?null:{frame:r.slice(0,o),dialect:n,rest:r.slice(o+1)}}let s=r.indexOf(`
@@ -85,7 +85,7 @@ ${s}
85
85
  `,o),a=i>=0?t.slice(o,i):t.slice(o),c=new Map;for(let u of a.split(`
86
86
  `)){let l=u.indexOf(":");l<=0||c.set(u.slice(0,l).trim().toLowerCase(),u.slice(l+1).trim())}return{statusCode:s,headers:c,body:i>=0?t.slice(i+2):""}}async function qu(e,t,r){await Dt(e,{collection:he,id:KC(),created_at:new Date().toISOString(),command:t,command_family:"gh api",decision:"contributed",reason:r?"gh-conditional-304":"gh-conditional-fetch",quota_free:r,saved_units:r?1:0})}var hi=h(()=>{"use strict";us();us();oe();et()});import{spawn as ZC}from"node:child_process";async function Ps(e,t){return await eO(t,async r=>{let n=await rO(e,t.cwd,r);return n||await tO(e,t.cwd,r)})}async function eO(e,t){if(e.signal.aborted)return{status:1,stdout:"",stderr:"wait cancelled"};let r=new AbortController,n=setTimeout(()=>r.abort(),e.timeoutMs),s=AbortSignal.any([e.signal,r.signal]);try{let o=await t(s);return r.signal.aborted?{status:1,stdout:"",stderr:`GitHub probe exceeded ${e.timeoutMs}ms`}:o}finally{clearTimeout(n)}}async function tO(e,t,r){return r.aborted?{status:1,stdout:"",stderr:"gh call cancelled"}:await new Promise(n=>{let s=!1,o=l=>{s||(s=!0,r.removeEventListener("abort",a),n(l))},i=ZC("gh",e,{cwd:t,stdio:["ignore","pipe","pipe"]});function a(){let l=i.pid;l&&Ao(l).then(p=>Oo(p,"SIGKILL"));try{i.kill("SIGKILL")}catch{}o({status:1,stdout:"",stderr:"gh call cancelled"})}r.addEventListener("abort",a,{once:!0});let c=[],u=[];i.stdout.on("data",l=>c.push(Buffer.from(l))),i.stderr.on("data",l=>u.push(Buffer.from(l))),i.once("error",l=>o({status:1,stdout:"",stderr:l.message})),i.once("close",l=>{o({status:l??1,stdout:Buffer.concat(c).toString("utf8"),stderr:Buffer.concat(u).toString("utf8").trim()})})})}async function rO(e,t,r){if(e[0]==="pr"&&e[1]==="view"&&e[2])return await nO(e[2],t,r);if(e[0]==="run"&&e[1]==="view"&&e[2]){let n=await Oe({path:`repos/{owner}/{repo}/actions/runs/${e[2]}`,cwd:t,signal:r,command:`gh ${e.join(" ")}`});if(n.status!==0)return n;let s=pt(JSON.parse(n.stdout));return{status:0,stderr:n.stderr,stdout:JSON.stringify({databaseId:sn(s,"database_id")||sn(s,"id"),status:ge(s,"status").toUpperCase(),conclusion:ge(s,"conclusion").toUpperCase(),workflowName:ge(s,"workflow_name")||ge(s,"name"),headBranch:ge(s,"head_branch"),url:ge(s,"html_url")})}}if(e[0]==="run"&&e[1]==="list"){let n=Go(e,"--branch"),s=Go(e,"--limit")??"20",o=await Oe({path:"repos/{owner}/{repo}/actions/runs",params:{branch:n,per_page:s},cwd:t,signal:r,command:`gh ${e.join(" ")}`});if(o.status!==0)return o;let i=Rr(pt(JSON.parse(o.stdout)).workflow_runs).map(a=>({databaseId:sn(a,"database_id")||sn(a,"id")}));return{status:0,stdout:JSON.stringify(i),stderr:o.stderr}}if(e[0]==="release"&&e[1]==="list"){let n=Go(e,"--limit")??"20",s=await Oe({path:"repos/{owner}/{repo}/releases",params:{per_page:n},cwd:t,signal:r,command:`gh ${e.join(" ")}`});if(s.status!==0)return s;let o=Rr(JSON.parse(s.stdout)).map(i=>({tagName:ge(i,"tag_name"),publishedAt:ge(i,"published_at"),isDraft:i.draft===!0}));return{status:0,stdout:JSON.stringify(o),stderr:s.stderr}}return null}async function nO(e,t,r){let n=await Oe({path:`repos/{owner}/{repo}/pulls/${e}`,cwd:t,signal:r,command:`gh pr view ${e}`});if(n.status!==0)return n;let s=pt(JSON.parse(n.stdout));if(Array.isArray(s.statusCheckRollup))return{status:0,stdout:n.stdout,stderr:n.stderr};let o=ge(pt(s.head),"sha"),[i,a]=o?await Promise.all([Oe({path:`repos/{owner}/{repo}/commits/${o}/status`,cwd:t,signal:r,command:`gh pr view ${e} status`}),Oe({path:`repos/{owner}/{repo}/commits/${o}/check-runs`,cwd:t,signal:r,command:`gh pr view ${e} check-runs`})]):[{status:0,stdout:"{}",stderr:"",quotaFree:!1},{status:0,stdout:"{}",stderr:"",quotaFree:!1}],c=i.status===0?Rr(pt(JSON.parse(i.stdout)).statuses):[],u=a.status===0?Rr(pt(JSON.parse(a.stdout)).check_runs):[];return{status:0,stderr:[n.stderr,i.stderr,a.stderr].filter(Boolean).join(`
87
87
  `),stdout:JSON.stringify({number:sn(s,"number"),state:ge(s,"state").toUpperCase(),mergeable:sO(s),statusCheckRollup:[...c.map(l=>({conclusion:ge(l,"state").toUpperCase()})),...u.map(l=>({status:ge(l,"status").toUpperCase(),conclusion:ge(l,"conclusion").toUpperCase()}))],url:ge(s,"html_url")})}}function sO(e){let t=ge(e,"mergeable_state").toUpperCase();return t&&t!=="UNKNOWN"?t==="CLEAN"?"MERGEABLE":t:e.mergeable===!0?"MERGEABLE":e.mergeable===!1?"CONFLICTING":"UNKNOWN"}var Rh=h(()=>{"use strict";hi();$o();Pt()});function Sh(e,t,r){let n=Date.now();return()=>oO(e,t,r,n)}async function oO(e,t,r,n){if(!/^[1-9][0-9]*$/.test(e))return fe("missing PR number");let s=await Ps(["pr","view",e,"--json","number,state,mergeable,statusCheckRollup,url"],t);if(s.status!==0)return fe(s.stderr||"gh pr view failed");let o=Uc(s.stdout),i=Array.isArray(o.statusCheckRollup)?o.statusCheckRollup:[],a=String(o.mergeable??""),c=i.map(iO),u=c.filter(p=>p==="failure").length,l=c.filter(p=>p==="pending").length;if(String(o.state)!=="OPEN")return At("failure",`PR #${e} is ${String(o.state).toLowerCase()}`,{mergeable:a});if(a==="CONFLICTING")return At("failure",`PR #${e} has merge conflicts`,{failing:u,pending:l,mergeable:a});if(u>0)return At("failure",`PR #${e} has failing checks`,{failing:u,pending:l,mergeable:a});if(l>0)return Xr(`PR #${e} has ${l} pending checks`);if(i.length===0){let p=Date.now()-n;return a==="UNKNOWN"||a==="BLOCKED"||p<r.emptyChecksGraceMs?Xr(`PR #${e} has no registered checks yet`,{checks:0,mergeable:a,empty_checks_elapsed_ms:p}):At("success",`PR #${e} has no checks configured`,{checks:0,mergeable:a})}return a==="UNKNOWN"?Xr(`PR #${e} mergeability is still unknown`,{checks:i.length,mergeable:a}):At("success",`PR #${e} checks passed`,{checks:i.length,mergeable:a})}async function Th(e,t){if(!e)return fe("missing run id");let r=await Ps(["run","view",e,"--json","databaseId,status,conclusion,workflowName,headBranch,url"],t);if(r.status!==0)return fe(r.stderr||"gh run view failed");let n=Uc(r.stdout),s=String(n.status??"").toLowerCase(),o=String(n.conclusion??"").toLowerCase();return s!=="completed"?Xr(`run ${e} is ${s||"pending"}`):o==="success"?At("success",`run ${e} succeeded`,kh(n)):At("failure",`run ${e} concluded ${o||"unknown"}`,kh(n))}async function vh(e,t){let r=await Ps(["run","list","--branch",e,"--limit","1","--json","databaseId"],t);if(r.status!==0)return"";let n=JSON.parse(r.stdout),s=Array.isArray(n)?n[0]:void 0;return nn(s)&&s.databaseId!=null?String(s.databaseId):""}async function xh(e,t,r){let n=await Ps(["release","list","--limit","20","--json","tagName,publishedAt,isDraft"],r);if(n.status!==0)return fe(n.stderr||"gh release list failed");let o=Rr(JSON.parse(n.stdout)).find(i=>{let a=String(i.tagName??""),c=new Date(String(i.publishedAt??""));return i.isDraft!==!0&&(!e||aO(e,a))&&c>=t});return o?At("success",`release ${String(o.tagName)} published`,{tag:String(o.tagName),published_at:String(o.publishedAt??"")}):Xr("no matching release is published yet")}function iO(e){let t=nn(e)?e:{},r=String(t.conclusion??t.state??t.status??"").toLowerCase();return["success","successful","passed","completed","neutral","skipped"].includes(r)?"success":["failure","failed","error","timed_out","cancelled","action_required"].includes(r)?"failure":"pending"}function kh(e){return{database_id:typeof e.databaseId=="number"?e.databaseId:String(e.databaseId??""),conclusion:String(e.conclusion??""),workflow:String(e.workflowName??""),branch:String(e.headBranch??""),url:String(e.url??"")}}function aO(e,t){let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`).test(t)}var Ch=h(()=>{"use strict";_r();Rh();$o()});function Is(){return["usage: rsp wait <subcommand> [options]","","Subcommands:"," rsp wait pr <number> [--timeout 45m] [--reason <text>]"," rsp wait run <id|--branch <branch> --latest> [--timeout 45m]"," rsp wait release [--tag <glob>] [--timeout 2h]",' rsp wait cmd -- "<command line>" [--timeout 30m]'," rsp wait ls","","Examples:",' rsp wait pr 123 --reason "before merge"'," rsp wait run --branch feature/wait --latest",' rsp wait release --tag "v2.*"',' rsp wait cmd -- "pnpm -C apps/rsp build"'," rsp wait ls","","Doctrine: never hand-write sleep polling loops; run rsp wait in a background shell - process exit IS the signal.","Exit codes: 0 = success verdict, 1 = failure verdict, 2 = timeout/indeterminate.","Result: TOON by default; --json selects JSON; --result-file <path> is written atomically before any wake.","Command capture: --capture-bytes <n> (default 16384); elision handles recover larger stdout/stderr.",'Completion hooks: --signal-pid <pid> [--signal USR1] and --notify-cmd "<cmd>" run after the result is durable.',"Hook timeout: --notify-timeout 10s. Process termination: TERM, --terminate-grace 2s, then KILL.","GitHub bounds: --probe-timeout 60s caps one probe, so a hung gh call cannot outlive --timeout.",""].join(`
88
- `)}var Wu=h(()=>{"use strict"});var Oh=h(()=>{"use strict";W()});var Ah=h(()=>{"use strict"});function cO(e){return Object.keys(e)}function wn(e){return{...e,fields:cO(e.fields)}}var Ph,Ih,Lh,uO,lO,dO,Dh,Ju=h(()=>{"use strict";Ph="red.castle.lane.v1",Ih="red.castle.state.v1",Lh="red.castle.history.v1",uO="red.castle.validation.v2",lO="red.castle.envelope.v1",dO="red.castle.hitl-card.v1",Dh=[wn({schemaId:Ph,docPath:".red/contracts/red.castle.lane.v1.md",typeNames:["CastleLaneRecord","CastleLaneKind"],fields:{at:!0,kind:!0,worker_id:!0,supervisor_id:!0,issue:!0,attempt:!0,payload:!0}}),wn({schemaId:Ih,docPath:".red/contracts/red.castle.state.v1.md",typeNames:["CastleStateSnapshot","CastleStateKind"],fields:{kind:!0,id:!0,version:!0,updated_at:!0,worker_id:!0,supervisor_id:!0,runner:!0,bundle_version:!0,pid:!0,started_at:!0,current:!0,queue:!0,completed:!0,envelope:!0}}),wn({schemaId:Lh,docPath:".red/contracts/red.castle.history.v1.md",typeNames:["CastleHistoryRecord","CastleHistoryEvent"],fields:{ts:!0,epoch:!0,worker:!0,issue:!0,event:!0,duration_s:!0,runner:!0,merge_sha:!0,reason:!0}}),wn({schemaId:uO,docPath:".red/contracts/red.castle.validation.v2.md",typeNames:["CastleValidationRecord","CastleValidationStatus"],fields:{schema:!0,name:!0,status:!0,command:!0,exitCode:!0,durationMs:!0,summary:!0}}),wn({schemaId:lO,docPath:".red/contracts/red.castle.envelope.v1.md",typeNames:["CastleEnvelope","CastleEnvelopeSection","CastleAttemptStatus"],fields:{status:!0,worker:!0,duration:!0,diff:!0,attempt:!0,mergeSha:!0,sections:!0}}),wn({schemaId:dO,docPath:".red/contracts/red.castle.hitl-card.v1.md",typeNames:["CastleHitlCard","CastleHitlCardPrStatus","CastleHitlCardAction"],fields:{issueNumber:!0,issueTitle:!0,issueUrl:!0,pendingDecision:!0,prStatus:!0,updatedAt:!0}})]});var yj,yi=h(()=>{"use strict";W();Ju();yj=new Map(Dh.map(e=>[e.schemaId,new Set(e.fields)]))});var Gh=h(()=>{"use strict";Ah();yi()});var $h=h(()=>{"use strict"});var bi=h(()=>{"use strict"});var Vu=h(()=>{"use strict";bi()});var wi=h(()=>{"use strict"});import{appendFile as fO,mkdir as gO,readFile as hO}from"node:fs/promises";import{dirname as yO,join as bO}from"node:path";function Ku(e,t){if(typeof e!="string"||e.length===0)throw new Error(`singleton event ${t} must be a non-empty string`);return e}function Nh(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("singleton event must be a record");let t={...e},r=t.payload;if(typeof r=="string")try{t.payload=JSON.parse(r)}catch{throw new Error("singleton event payload is not valid JSON")}if(t.payload!==void 0&&(t.payload===null||typeof t.payload!="object"||Array.isArray(t.payload)))throw new Error("singleton event payload must be a record");return{at:Ku(t.at,"at"),singleton:Ku(t.singleton,"singleton"),kind:Ku(t.kind,"kind"),...t.payload===void 0?{}:{payload:t.payload}}}function wO(e){return{at:e.at,singleton:e.singleton,kind:e.kind,...e.payload===void 0?{}:{payload:JSON.stringify(e.payload)}}}function _O(e){if(e!==void 0&&(!Number.isSafeInteger(e)||e<0))throw new Error("singleton event tail must be a non-negative integer")}function EO(e){return bO(e.castleStateRoot,"singleton-events.toonl")}function zu(e,t={}){let r=t.fs??{appendFile:fO,mkdir:gO,readFile:hO},n=t.clock??(()=>new Date().toISOString()),s=EO(e);return{path:s,async append(o){let i=Nh({at:o.at??n(),...o});return await r.mkdir(yO(s),{recursive:!0}),await r.appendFile(s,Ht().push(wO(i)),"utf8"),i},async read(o={}){_O(o.tail);let i;try{i=await r.readFile(s,"utf8")}catch(c){if(c.code==="ENOENT")return[];throw c}let a=Ut(i).map(Nh);return o.tail===void 0?a:o.tail===0?[]:a.slice(-o.tail)}}}var Yu=h(()=>{"use strict";W()});var _i=h(()=>{"use strict";W();wi();Yu()});var Fh=h(()=>{"use strict";bi();Vu();_i()});var Mh=h(()=>{"use strict"});var tU,Bh=h(()=>{"use strict";W();tU=24*60*60*1e3});var jh=h(()=>{"use strict";yi()});var oU,iU,Uh=h(()=>{"use strict";oU=15*6e4,iU=30*6e4});var Hh=h(()=>{"use strict"});var kO,SO,uU,lU,qh=h(()=>{"use strict";kO=["supervisor_start","supervisor_exit","fleet_scaled","worker_start","worker_exit","worker_steered","worker_escalated","post_claim","pre_worktree","post_issue","pre_requeue","pre_merge","post_merge"],SO={pre_worktree:["cargo","gradle"]},uU=Object.values(SO).flat(),lU=new Set(kO)});var Wh=h(()=>{"use strict"});var Jh=h(()=>{"use strict";_i()});var Vh=h(()=>{"use strict"});var Kh=h(()=>{});var zh=h(()=>{"use strict";Kh()});var Yh=h(()=>{"use strict"});var Qh=h(()=>{"use strict"});var Qu=h(()=>{"use strict"});var Xh=h(()=>{"use strict";W();Qu()});var Zh=h(()=>{"use strict";W()});var Xu=h(()=>{"use strict"});var Zu=h(()=>{"use strict"});import{resolve as be}from"node:path";function ey(e){let t=be(e),r=be(t,"state"),n=be(r,"castle"),s=be(t,"tmp"),o=be(s,"supervisors"),i=be(s,"workers"),a=be(s,"monitors"),c=be(s,"worktrees");return{redRoot:t,stateRoot:r,castleStateRoot:n,castleHistory:be(n,"history.toonl"),castleValidation:be(n,"validation.toonl"),tmpRoot:s,supervisorsRoot:o,supervisor:u=>be(o,u),projectSupervisor:be(o,TO),workersRoot:i,worker:u=>be(i,u),workerSteerFile:u=>be(i,u,"steer.toon"),monitorsRoot:a,monitor:u=>be(a,u),worktreesRoot:c,worktreeLane:u=>be(c,u)}}var TO,ty=h(()=>{"use strict";TO="default"});var ry=h(()=>{"use strict";wi()});var ny=h(()=>{"use strict"});var sy=h(()=>{"use strict";Xu();Zu()});import{mkdir as vO,readFile as xO,rename as CO,rm as OO,writeFile as AO}from"node:fs/promises";import{dirname as PO,join as IO}from"node:path";function DO(e){if(!LO.test(e)||e==="."||e==="..")throw new Error(`invalid singleton name ${JSON.stringify(e)}`)}function GO(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function $O(e){return e.code==="ENOENT"}function NO(e){return e.code==="EEXIST"}function FO(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("singleton lease must be a record");let t=e;if(!Number.isInteger(t.pid)||t.pid<=0)throw new Error("singleton lease pid must be a positive integer");for(let r of["start_time","acquired_at","renewed_at"])if(typeof t[r]!="string"||t[r].length===0)throw new Error(`singleton lease ${r} must be a non-empty string`);return t}function el(e,t){return e.pid===t.pid&&e.start_time===t.startTime}function Ei(e,t){return DO(t),IO(e.castleStateRoot,"singletons",t,"lease.toon")}function oy(e,t={}){let r=t.fs??{mkdir:vO,readFile:xO,rename:CO,rm:OO,writeFile:AO},n=t.clock??(()=>new Date().toISOString()),s=t.isPidAlive??GO;async function o(a){try{return FO(H(await r.readFile(a,"utf8")))}catch(c){if($O(c))return;throw c}}async function i(a,c){let u=`${a}.tmp-${c.pid}-${crypto.randomUUID()}`;await r.writeFile(u,$(c,{keyedMapCollapse:!0}),{encoding:"utf8"}),await r.rename(u,a)}return{read(a){return o(Ei(e,a))},async acquire(a,c){let u=Ei(e,a);await r.mkdir(PO(u),{recursive:!0});let l=!1;for(;;){let p=n(),d={pid:c.pid,start_time:c.startTime,acquired_at:p,renewed_at:p};try{return await r.writeFile(u,$(d,{keyedMapCollapse:!0}),{encoding:"utf8",flag:"wx"}),{acquired:!0,reaped:l,lease:d}}catch(f){if(!NO(f))throw f}let g=await o(u);if(g){if(el(g,c))return{acquired:!0,reaped:l,lease:g};if(await s(g.pid))return{acquired:!1,lease:g};await r.rm(u,{force:!0}),l=!0}}},async renew(a,c){let u=Ei(e,a),l=await o(u);if(!l||!el(l,c))throw new Ri(a);let p={...l,renewed_at:n()};return await i(u,p),p},async release(a,c){let u=Ei(e,a),l=await o(u);if(!l)return!1;if(!el(l,c))throw new Ri(a);return await r.rm(u,{force:!0}),!0}}}var Ri,LO,iy=h(()=>{"use strict";W();Ri=class extends Error{constructor(t){super(`singleton lease ${JSON.stringify(t)} is held by another owner`),this.name="SingletonLeaseOwnershipError"}},LO=/^[a-z0-9][a-z0-9._-]{0,63}$/});var tl=h(()=>{"use strict"});var ay=h(()=>{"use strict"});var MO,BO,jO,XU,cy=h(()=>{"use strict";MO={refreshCadenceS:270,tolerance:3},BO=270,jO=2700,XU={...MO,claimGraceS:BO,recentCommitProtectionS:jO}});var uy=h(()=>{"use strict"});function ly(e){return e==="single-object"?"rest":"graphql"}function Z(e,t,r,n,s,o){return{key:e,kind:"read",cardinality:t,volatility:r,surface:o??ly(t),budget:n,...o?{only:o}:{},why:s}}function Ae(e,t,r,n){return{key:e,kind:"write",cardinality:"single-object",surface:t,budget:r,why:n}}var dy,eH,py=h(()=>{dy=[Z("issue view","single-object","stable-poll","rest","one issue by number, repeatedly polled while usually unchanged; REST answers in one request"),Z("pr view","single-object","stable-poll","rest","one pull request by number, polled per Worker per iteration"),Z("repo view","single-object","stable-poll","rest","one repository's own metadata, repeatedly read while usually unchanged"),Z("run view","single-object","stable-poll","rest","one Actions run repeatedly polled to terminal; Actions has no GraphQL surface"),Z("release view","single-object","stable-poll","rest","one release by tag, repeatedly checked while usually absent or unchanged"),Z("pr diff","single-object","one-shot","rest","one pull request's diff, read once for review and served by a REST media type"),Z("issue list","multi-node","stable-poll","graphql","a repeatedly polled, usually-unchanged issue connection; GraphQL avoids N REST pages"),Z("pr list","multi-node","stable-poll","graphql","a repeatedly polled, usually-unchanged pull-request connection; GraphQL avoids N REST pages"),Z("pr checks","multi-node","stable-poll","graphql","check contexts form a connection repeatedly polled while awaiting terminal state"),Z("release list","multi-node","stable-poll","rest","release waits poll a usually-unchanged list; Releases has no GraphQL connection gh reads","rest"),Z("run list","multi-node","stable-poll","rest","run waits poll a usually-unchanged list; Actions has no GraphQL surface","rest"),Z("label list","multi-node","one-shot","graphql","a label connection loaded once for the current operation"),Z("issue list (search)","multi-node","stable-poll","search","queue discovery polls usually-unchanged search results through the 30/min search connection"),Z("pr list (search)","multi-node","stable-poll","search","PR discovery polls usually-unchanged search results through the 30/min search connection"),Z("search issues","multi-repository","one-shot","search","a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),Z("search prs","multi-repository","one-shot","search","a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),Z("search repos","multi-repository","one-shot","search","a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),Z("api graphql","multi-node","one-shot","graphql","the caller supplies one explicit GraphQL query rather than a routed poll"),Z("api rest","single-object","one-shot","rest","the caller supplies one explicit REST path rather than a routed poll"),Ae("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),Ae("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),Ae("issue close","graphql","graphql","gh closes with the closeIssue mutation"),Ae("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),Ae("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),Ae("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),Ae("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),Ae("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),Ae("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),Ae("pr close","graphql","graphql","gh closes with a GraphQL mutation"),Ae("pr edit","graphql","graphql","gh edits with GraphQL mutations"),Ae("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),Ae("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),Ae("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],eH=new Map(dy.map(e=>[e.key,e]))});var my=h(()=>{W()});var sl=Qd((rl,nl)=>{(function(e,t){typeof rl=="object"&&typeof nl<"u"?nl.exports=t():typeof define=="function"&&define.amd?define(t):e.Bottleneck=t()})(rl,function(){"use strict";var e=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function t(I){return I&&I.default||I}var r=function(I,b,m={}){var w,R,S;for(w in b)S=b[w],m[w]=(R=I[w])!=null?R:S;return m},n=function(I,b,m={}){var w,R;for(w in I)R=I[w],b[w]!==void 0&&(m[w]=R);return m},s={load:r,overwrite:n},o;o=class{constructor(b,m){this.incr=b,this.decr=m,this._first=null,this._last=null,this.length=0}push(b){var m;this.length++,typeof this.incr=="function"&&this.incr(),m={value:b,prev:this._last,next:null},this._last!=null?(this._last.next=m,this._last=m):this._first=this._last=m}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,m,w;for(b=this._first,w=[];b!=null;)w.push((m=b,b=b.next,m.value));return w}forEachShift(b){var m;for(m=this.shift();m!=null;)b(m),m=this.shift()}debug(){var b,m,w,R,S;for(b=this._first,S=[];b!=null;)S.push((m=b,b=b.next,{value:m.value,prev:(w=m.prev)!=null?w.value:void 0,next:(R=m.next)!=null?R.value:void 0}));return S}};var i=o,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=(m,w)=>this._addListener(m,"many",w),this.instance.once=(m,w)=>this._addListener(m,"once",w),this.instance.removeAllListeners=(m=null)=>m!=null?delete this._events[m]:this._events={}}_addListener(b,m,w){var R;return(R=this._events)[b]==null&&(R[b]=[]),this._events[b].push({cb:w,status:m}),this.instance}listenerCount(b){return this._events[b]!=null?this._events[b].length:0}async trigger(b,...m){var w,R;try{return b!=="debug"&&this.trigger("debug",`Event triggered: ${b}`,m),this._events[b]==null?void 0:(this._events[b]=this._events[b].filter(function(S){return S.status!=="none"}),R=this._events[b].map(async S=>{var C,A;if(S.status!=="none"){S.status==="once"&&(S.status="none");try{return A=typeof S.cb=="function"?S.cb(...m):void 0,typeof A?.then=="function"?await A:A}catch(U){return C=U,this.trigger("error",C),null}}}),(await Promise.all(R)).find(function(S){return S!=null}))}catch(S){return w=S,this.trigger("error",w),null}}};var c=a,u,l,p;u=i,l=c,p=class{constructor(b){var m;this.Events=new l(this),this._length=0,this._lists=function(){var w,R,S;for(S=[],m=w=1,R=b;1<=R?w<=R:w>=R;m=1<=R?++w:--w)S.push(new u(()=>this.incr(),()=>this.decr()));return S}.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(m){return m.forEachShift(b)})}getFirst(b=this._lists){var m,w,R;for(m=0,w=b.length;m<w;m++)if(R=b[m],R.length>0)return R;return[]}shiftLastFrom(b){return this.getFirst(this._lists.slice(b).reverse()).shift()}};var d=p,g;g=class extends Error{};var f=g,k,E,y,_,T;_=10,E=5,T=s,k=f,y=class{constructor(b,m,w,R,S,C,A,U){this.task=b,this.args=m,this.rejectOnDrop=S,this.Events=C,this._states=A,this.Promise=U,this.options=T.load(w,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((ie,pe)=>{this._resolve=ie,this._reject=pe}),this.retryCount=0}_sanitizePriority(b){var m;return m=~~b!==b?E:b,m<0?0:m>_-1?_-1:m}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:b,message:m="This job has been dropped by Bottleneck"}={}){return this._states.remove(this.options.id)?(this.rejectOnDrop&&this._reject(b??new k(m)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0):!1}_assertStatus(b){var m;if(m=this._states.jobStatus(this.options.id),!(m===b||b==="DONE"&&m===null))throw new k(`Invalid job status ${m}, 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,m){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:b,blocked:m})}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,m,w,R){var S,C,A;this.retryCount===0?(this._assertStatus("RUNNING"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),C={args:this.args,options:this.options,retryCount:this.retryCount},this.Events.trigger("executing",C);try{if(A=await(b!=null?b.schedule(this.options,this.task,...this.args):this.task(...this.args)),m())return this.doDone(C),await R(this.options,C),this._assertStatus("DONE"),this._resolve(A)}catch(U){return S=U,this._onFailure(S,C,m,w,R)}}doExpire(b,m,w){var R,S;return this._states.jobStatus(this.options.id==="RUNNING")&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),S={args:this.args,options:this.options,retryCount:this.retryCount},R=new k(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(R,S,b,m,w)}async _onFailure(b,m,w,R,S){var C,A;if(w())return C=await this.Events.trigger("failed",b,m),C!=null?(A=~~C,this.Events.trigger("retry",`Retrying ${this.options.id} after ${A} ms`,m),this.retryCount++,R(A)):(this.doDone(m),await S(this.options,m),this._assertStatus("DONE"),this._reject(b))}doDone(b){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",b)}};var v=y,G,B,V;V=s,G=f,B=class{constructor(b,m,w){this.instance=b,this.storeOptions=m,this.clientId=this.instance._randomIndex(),V.load(w,w,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 m,w,R,S,C;if(S=Date.now(),this.storeOptions.reservoirRefreshInterval!=null&&S>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=S,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),this.storeOptions.reservoirIncreaseInterval!=null&&S>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval&&({reservoirIncreaseAmount:m,reservoirIncreaseMaximum:R,reservoir:C}=this.storeOptions,this._lastReservoirIncrease=S,w=R!=null?Math.min(m,R-C):m,w>0))return this.storeOptions.reservoir+=w,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(m,w){return setTimeout(m,b)})}computePenalty(){var b;return(b=this.storeOptions.penalty)!=null?b:15*this.storeOptions.minTime||5e3}async __updateSettings__(b){return await this.yieldLoop(),V.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,m;return{maxConcurrent:b,reservoir:m}=this.storeOptions,b!=null&&m!=null?Math.min(b-this._running,m):b!=null?b-this._running:m??null}conditionsCheck(b){var m;return m=this.computeCapacity(),m==null||b<=m}async __incrementReservoir__(b){var m;return await this.yieldLoop(),m=this.storeOptions.reservoir+=b,this.instance._drainAll(this.computeCapacity()),m}async __currentReservoir__(){return await this.yieldLoop(),this.storeOptions.reservoir}isBlocked(b){return this._unblockTime>=b}check(b,m){return this.conditionsCheck(b)&&this._nextRequest-m<=0}async __check__(b){var m;return await this.yieldLoop(),m=Date.now(),this.check(b,m)}async __register__(b,m,w){var R,S;return await this.yieldLoop(),R=Date.now(),this.conditionsCheck(m)?(this._running+=m,this.storeOptions.reservoir!=null&&(this.storeOptions.reservoir-=m),S=Math.max(this._nextRequest-R,0),this._nextRequest=R+S+this.storeOptions.minTime,{success:!0,wait:S,reservoir:this.storeOptions.reservoir}):{success:!1}}strategyIsBlock(){return this.storeOptions.strategy===3}async __submit__(b,m){var w,R,S;if(await this.yieldLoop(),this.storeOptions.maxConcurrent!=null&&m>this.storeOptions.maxConcurrent)throw new G(`Impossible to add a job having a weight of ${m} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`);return R=Date.now(),S=this.storeOptions.highWater!=null&&b===this.storeOptions.highWater&&!this.check(m,R),w=this.strategyIsBlock()&&(S||this.isBlocked(R)),w&&(this._unblockTime=R+this.computePenalty(),this._nextRequest=this._unblockTime+this.storeOptions.minTime,this.instance._dropAllQueued()),{reachedHWM:S,blocked:w,strategy:this.storeOptions.strategy}}async __free__(b,m){return await this.yieldLoop(),this._running-=m,this._done+=m,this.instance._drainAll(this.computeCapacity()),{running:this._running}}};var te=B,re,He;re=f,He=class{constructor(b){this.status=b,this._jobs={},this.counts=this.status.map(function(){return 0})}next(b){var m,w;if(m=this._jobs[b],w=m+1,m!=null&&w<this.status.length)return this.counts[m]--,this.counts[w]++,this._jobs[b]++;if(m!=null)return this.counts[m]--,delete this._jobs[b]}start(b){var m;return m=0,this._jobs[b]=m,this.counts[m]++}remove(b){var m;return m=this._jobs[b],m!=null&&(this.counts[m]--,delete this._jobs[b]),m!=null}jobStatus(b){var m;return(m=this.status[this._jobs[b]])!=null?m:null}statusJobs(b){var m,w,R,S,C;if(b!=null){if(w=this.status.indexOf(b),w<0)throw new re(`status must be one of ${this.status.join(", ")}`);R=this._jobs,S=[];for(m in R)C=R[m],C===w&&S.push(m);return S}else return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce((b,m,w)=>(b[this.status[w]]=m,b),{})}};var de=He,Ft,P;Ft=i,P=class{constructor(b,m){this.schedule=this.schedule.bind(this),this.name=b,this.Promise=m,this._running=0,this._queue=new Ft}isEmpty(){return this._queue.length===0}async _tryToRun(){var b,m,w,R,S,C,A;if(this._running<1&&this._queue.length>0)return this._running++,{task:A,args:b,resolve:S,reject:R}=this._queue.shift(),m=await async function(){try{return C=await A(...b),function(){return S(C)}}catch(U){return w=U,function(){return R(w)}}}(),this._running--,this._tryToRun(),m()}schedule(b,...m){var w,R,S;return S=R=null,w=new this.Promise(function(C,A){return S=C,R=A}),this._queue.push({task:b,args:m,resolve:S,reject:R}),this._tryToRun(),w}};var M=P,De="2.19.5",_t={version:De},Mt=Object.freeze({version:De,default:_t}),O=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),N=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Et=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),st,ve,xe,Rt,Fr,Bt;Bt=s,st=c,Rt=O,xe=N,Fr=Et,ve=function(){class I{constructor(m={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=m,Bt.load(this.limiterOptions,this.defaults,this),this.Events=new st(this),this.instances={},this.Bottleneck=zd,this._startAutoCleanup(),this.sharedConnection=this.connection!=null,this.connection==null&&(this.limiterOptions.datastore==="redis"?this.connection=new Rt(Object.assign({},this.limiterOptions,{Events:this.Events})):this.limiterOptions.datastore==="ioredis"&&(this.connection=new xe(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(m=""){var w;return(w=this.instances[m])!=null?w:(()=>{var R;return R=this.instances[m]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${m}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",R,m),R})()}async deleteKey(m=""){var w,R;return R=this.instances[m],this.connection&&(w=await this.connection.__runCommand__(["del",...Fr.allKeys(`${this.id}-${m}`)])),R!=null&&(delete this.instances[m],await R.disconnect()),R!=null||w>0}limiters(){var m,w,R,S;w=this.instances,R=[];for(m in w)S=w[m],R.push({key:m,limiter:S});return R}keys(){return Object.keys(this.instances)}async clusterKeys(){var m,w,R,S,C,A,U,ie,pe;if(this.connection==null)return this.Promise.resolve(this.keys());for(A=[],m=null,pe=`b_${this.id}-`.length,w=9;m!==0;)for([ie,R]=await this.connection.__runCommand__(["scan",m??0,"match",`b_${this.id}-*_settings`,"count",1e4]),m=~~ie,S=0,U=R.length;S<U;S++)C=R[S],A.push(C.slice(pe,-w));return A}_startAutoCleanup(){var m;return clearInterval(this.interval),typeof(m=this.interval=setInterval(async()=>{var w,R,S,C,A,U;A=Date.now(),S=this.instances,C=[];for(R in S){U=S[R];try{await U._store.__groupCheck__(A)?C.push(this.deleteKey(R)):C.push(void 0)}catch(ie){w=ie,C.push(U.Events.trigger("error",w))}}return C},this.timeout/2)).unref=="function"?m.unref():void 0}updateSettings(m={}){if(Bt.overwrite(m,this.defaults,this),Bt.overwrite(m,m,this.limiterOptions),m.timeout!=null)return this._startAutoCleanup()}disconnect(m=!0){var w;if(!this.sharedConnection)return(w=this.connection)!=null?w.disconnect(m):void 0}}return I.prototype.defaults={timeout:1e3*60*5,connection:null,Promise,id:"group-key"},I}.call(e);var Pn=ve,ur,In,jd;jd=s,In=c,ur=function(){class I{constructor(m={}){this.options=m,jd.load(this.options,this.defaults,this),this.Events=new In(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise((m,w)=>this._resolve=m)}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(m){var w;return this._arr.push(m),w=this._promise,this._arr.length===this.maxSize?this._flush():this.maxTime!=null&&this._arr.length===1&&(this._timeout=setTimeout(()=>this._flush(),this.maxTime)),w}}return I.prototype.defaults={maxTime:null,maxSize:null,Promise},I}.call(e);var qE=ur,WE=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),JE=t(Mt),Ud,Hd,ma,fa,qd,ga,Wd,Jd,Vd,ha,ot,Kd=[].splice;ga=10,Hd=5,ot=s,Wd=d,fa=v,qd=te,Jd=WE,ma=c,Vd=de,ha=M,Ud=function(){class I{constructor(m={},...w){var R,S;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(m,w),ot.load(m,this.instanceDefaults,this),this._queues=new Wd(ga),this._scheduled={},this._states=new Vd(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new ma(this),this._submitLock=new ha("submit",this.Promise),this._registerLock=new ha("register",this.Promise),S=ot.load(m,this.storeDefaults,{}),this._store=function(){if(this.datastore==="redis"||this.datastore==="ioredis"||this.connection!=null)return R=ot.load(m,this.redisStoreDefaults,{}),new Jd(this,S,R);if(this.datastore==="local")return R=ot.load(m,this.localStoreDefaults,{}),new qd(this,S,R);throw new I.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}.call(this),this._queues.on("leftzero",()=>{var C;return(C=this._store.heartbeat)!=null&&typeof C.ref=="function"?C.ref():void 0}),this._queues.on("zero",()=>{var C;return(C=this._store.heartbeat)!=null&&typeof C.unref=="function"?C.unref():void 0})}_validateOptions(m,w){if(!(m!=null&&typeof m=="object"&&w.length===0))throw new I.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(m){return this._store.__publish__(m)}disconnect(m=!0){return this._store.__disconnect__(m)}chain(m){return this._limiter=m,this}queued(m){return this._queues.queued(m)}clusterQueued(){return this._store.__queued__()}empty(){return this.queued()===0&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(m){return this._states.jobStatus(m)}jobs(m){return this._states.statusJobs(m)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(m=1){return this._store.__check__(m)}_clearGlobalState(m){return this._scheduled[m]!=null?(clearTimeout(this._scheduled[m].expiration),delete this._scheduled[m],!0):!1}async _free(m,w,R,S){var C,A;try{if({running:A}=await this._store.__free__(m,R.weight),this.Events.trigger("debug",`Freed ${R.id}`,S),A===0&&this.empty())return this.Events.trigger("idle")}catch(U){return C=U,this.Events.trigger("error",C)}}_run(m,w,R){var S,C,A;return w.doRun(),S=this._clearGlobalState.bind(this,m),A=this._run.bind(this,m,w),C=this._free.bind(this,m,w),this._scheduled[m]={timeout:setTimeout(()=>w.doExecute(this._limiter,S,A,C),R),expiration:w.options.expiration!=null?setTimeout(function(){return w.doExpire(S,A,C)},R+w.options.expiration):void 0,job:w}}_drainOne(m){return this._registerLock.schedule(()=>{var w,R,S,C,A;return this.queued()===0?this.Promise.resolve(null):(A=this._queues.getFirst(),{options:C,args:w}=S=A.first(),m!=null&&C.weight>m?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${C.id}`,{args:w,options:C}),R=this._randomIndex(),this._store.__register__(R,C.weight,C.expiration).then(({success:U,wait:ie,reservoir:pe})=>{var Ln;return this.Events.trigger("debug",`Drained ${C.id}`,{success:U,args:w,options:C}),U?(A.shift(),Ln=this.empty(),Ln&&this.Events.trigger("empty"),pe===0&&this.Events.trigger("depleted",Ln),this._run(R,S,ie),this.Promise.resolve(C.weight)):this.Promise.resolve(null)})))})}_drainAll(m,w=0){return this._drainOne(m).then(R=>{var S;return R!=null?(S=m!=null?m-R:m,this._drainAll(S,w+R)):this.Promise.resolve(w)}).catch(R=>this.Events.trigger("error",R))}_dropAllQueued(m){return this._queues.shiftAll(function(w){return w.doDrop({message:m})})}stop(m={}){var w,R;return m=ot.load(m,this.stopDefaults),R=S=>{var C;return C=()=>{var A;return A=this._states.counts,A[0]+A[1]+A[2]+A[3]===S},new this.Promise((A,U)=>C()?A():this.on("done",()=>{if(C())return this.removeAllListeners("done"),A()}))},w=m.dropWaitingJobs?(this._run=function(S,C){return C.doDrop({message:m.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule(()=>this._submitLock.schedule(()=>{var S,C,A;C=this._scheduled;for(S in C)A=C[S],this.jobStatus(A.job.options.id)==="RUNNING"&&(clearTimeout(A.timeout),clearTimeout(A.expiration),A.job.doDrop({message:m.dropErrorMessage}));return this._dropAllQueued(m.dropErrorMessage),R(0)}))):this.schedule({priority:ga-1,weight:0},()=>R(1)),this._receive=function(S){return S._reject(new I.prototype.BottleneckError(m.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new I.prototype.BottleneckError("stop() has already been called")),w}async _addToQueue(m){var w,R,S,C,A,U,ie;({args:w,options:C}=m);try{({reachedHWM:A,blocked:R,strategy:ie}=await this._store.__submit__(this.queued(),C.weight))}catch(pe){return S=pe,this.Events.trigger("debug",`Could not queue ${C.id}`,{args:w,options:C,error:S}),m.doDrop({error:S}),!1}return R?(m.doDrop(),!0):A&&(U=ie===I.prototype.strategy.LEAK?this._queues.shiftLastFrom(C.priority):ie===I.prototype.strategy.OVERFLOW_PRIORITY?this._queues.shiftLastFrom(C.priority+1):ie===I.prototype.strategy.OVERFLOW?m:void 0,U?.doDrop(),U==null||ie===I.prototype.strategy.OVERFLOW)?(U==null&&m.doDrop(),A):(m.doQueue(A,R),this._queues.push(m),await this._drainAll(),A)}_receive(m){return this._states.jobStatus(m.options.id)!=null?(m._reject(new I.prototype.BottleneckError(`A job with the same id already exists (id=${m.options.id})`)),!1):(m.doReceive(),this._submitLock.schedule(this._addToQueue,m))}submit(...m){var w,R,S,C,A,U,ie;return typeof m[0]=="function"?(A=m,[R,...m]=A,[w]=Kd.call(m,-1),C=ot.load({},this.jobDefaults)):(U=m,[C,R,...m]=U,[w]=Kd.call(m,-1),C=ot.load(C,this.jobDefaults)),ie=(...pe)=>new this.Promise(function(Ln,KE){return R(...pe,function(...Yd){return(Yd[0]!=null?KE:Ln)(Yd)})}),S=new fa(ie,m,C,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),S.promise.then(function(pe){return typeof w=="function"?w(...pe):void 0}).catch(function(pe){return Array.isArray(pe)?typeof w=="function"?w(...pe):void 0:typeof w=="function"?w(pe):void 0}),this._receive(S)}schedule(...m){var w,R,S;return typeof m[0]=="function"?([S,...m]=m,R={}):[R,S,...m]=m,w=new fa(S,m,R,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(w),w.promise}wrap(m){var w,R;return w=this.schedule.bind(this),R=function(...S){return w(m.bind(this),...S)},R.withOptions=function(S,...C){return w(S,m,...C)},R}async updateSettings(m={}){return await this._store.__updateSettings__(ot.overwrite(m,this.storeDefaults)),ot.overwrite(m,this.instanceDefaults,this),this}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(m=0){return this._store.__incrementReservoir__(m)}}return I.default=I,I.Events=ma,I.version=I.prototype.version=JE.version,I.strategy=I.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},I.BottleneckError=I.prototype.BottleneckError=f,I.Group=I.prototype.Group=Pn,I.RedisConnection=I.prototype.RedisConnection=O,I.IORedisConnection=I.prototype.IORedisConnection=N,I.Batcher=I.prototype.Batcher=qE,I.prototype.jobDefaults={priority:Hd,weight:1,expiration:null,id:"<no-id>"},I.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:I.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},I.prototype.localStoreDefaults={Promise,timeout:null,heartbeatInterval:250},I.prototype.redisStoreDefaults={Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},I.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise},I.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},I}.call(e);var zd=Ud,VE=zd;return VE})});var Nt,ol=h(()=>{Nt=class extends Error{name;status;request;response;constructor(t,r,n){super(t,{cause:n.cause}),this.name="HttpError",this.status=Number.parseInt(r),Number.isNaN(this.status)&&(this.status=0);"response"in n&&(this.response=n.response);let s=Object.assign({},n.request);n.request.headers.authorization&&(s.headers=Object.assign({},n.request.headers,{authorization:n.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),s.url=s.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=s}}});function HO(e){return e.request!==void 0}async function fy(e,t,r,n){if(!HO(r)||!r?.request.request)throw r;if(r.status>=400&&!e.doNotRetry.includes(r.status)){let s=n.request.retries!=null?n.request.retries:e.retries,o=Math.pow((n.request.retryCount||0)+1,2);throw t.retry.retryRequest(r,s,o)}throw r}async function qO(e,t,r,n){let s=new gy.default;return s.on("failed",function(o,i){let a=~~o.request.request?.retries,c=~~o.request.request?.retryAfter;if(n.request.retryCount=i.retryCount+1,a>i.retryCount)return c*e.retryAfterBaseValue}),s.schedule(WO.bind(null,e,t,r),n)}async function WO(e,t,r,n){let s=await r(n);if(s.data&&s.data.errors&&s.data.errors.length>0&&/Something went wrong while executing your query/.test(s.data.errors[0].message)){let o=new Nt(s.data.errors[0].message,500,{request:n,response:s});return fy(e,t,o,n)}return s}function il(e,t){let r=Object.assign({enabled:!0,retryAfterBaseValue:1e3,doNotRetry:[400,401,403,404,410,422,451],retries:3},t.retry),n={retry:{retryRequest:(s,o,i)=>(s.request.request=Object.assign({},s.request.request,{retries:o,retryAfter:i}),s)}};return r.enabled&&(e.hook.error("request",fy.bind(null,r,n)),e.hook.wrap("request",qO.bind(null,r,n))),n}var gy,UO,hy=h(()=>{gy=ba(sl(),1);ol();UO="0.0.0-development";il.VERSION=UO});function VO(e,t,r){return e.retryLimiter.schedule(KO,e,t,r)}async function KO(e,t,r){let{pathname:n}=new URL(r.url,"http://github.test"),s=zO(r.method,n),o=!s&&r.method!=="GET"&&r.method!=="HEAD",i=r.method==="GET"&&n.startsWith("/search/"),a=n.startsWith("/graphql"),u=~~t.retryCount>0?{priority:0,weight:0}:{};e.clustering&&(u.expiration=1e3*60),(o||a)&&await e.write.key(e.id).schedule(u,al),o&&e.triggersNotification(n)&&await e.notifications.key(e.id).schedule(u,al),i&&await e.search.key(e.id).schedule(u,al);let l=(s?e.auth:e.global).key(e.id).schedule(u,t,r);if(a){let p=await l;if(p.data.errors!=null&&p.data.errors.some(d=>d.type==="RATE_LIMITED"))throw Object.assign(new Error("GraphQL Rate Limit Exceeded"),{response:p,data:p.data})}return l}function zO(e,t){return e==="PATCH"&&/^\/applications\/[^/]+\/token\/scoped$/.test(t)||e==="POST"&&(/^\/applications\/[^/]+\/token$/.test(t)||/^\/app\/installations\/[^/]+\/access_tokens$/.test(t)||t==="/login/oauth/access_token")}function QO(e){let r=`^(?:${e.map(n=>n.split("/").map(s=>s.startsWith("{")?"(?:.+?)":s).join("/")).map(n=>`(?:${n})`).join("|")})[^/]*$`;return new RegExp(r,"i")}function ki(e,t){let{enabled:r=!0,Bottleneck:n=by.default,id:s="no-id",timeout:o=1e3*60*2,connection:i}=t.throttle||{};if(!r)return{};let a={timeout:o};typeof i<"u"&&(a.connection=i);let c=Object.assign({clustering:i!=null,triggersNotification:wy,fallbackSecondaryRateRetryAfter:60,retryAfterBaseValue:1e3,id:s},t.throttle);if(typeof c.onSecondaryRateLimit!="function"||typeof c.onRateLimit!="function")throw new Error(`octokit/plugin-throttling error:
88
+ `)}var Wu=h(()=>{"use strict"});var Oh=h(()=>{"use strict";W()});var Ah=h(()=>{"use strict"});function cO(e){return Object.keys(e)}function wn(e){return{...e,fields:cO(e.fields)}}var Ph,Ih,Lh,uO,lO,dO,Dh,Ju=h(()=>{"use strict";Ph="red.castle.lane.v1",Ih="red.castle.state.v1",Lh="red.castle.history.v1",uO="red.castle.validation.v2",lO="red.castle.envelope.v1",dO="red.castle.hitl-card.v1",Dh=[wn({schemaId:Ph,docPath:".red/contracts/red.castle.lane.v1.md",typeNames:["CastleLaneRecord","CastleLaneKind"],fields:{at:!0,kind:!0,worker_id:!0,supervisor_id:!0,issue:!0,attempt:!0,msg:!0,payload:!0}}),wn({schemaId:Ih,docPath:".red/contracts/red.castle.state.v1.md",typeNames:["CastleStateSnapshot","CastleStateKind"],fields:{kind:!0,id:!0,version:!0,updated_at:!0,worker_id:!0,supervisor_id:!0,runner:!0,bundle_version:!0,pid:!0,started_at:!0,current:!0,queue:!0,completed:!0,envelope:!0}}),wn({schemaId:Lh,docPath:".red/contracts/red.castle.history.v1.md",typeNames:["CastleHistoryRecord","CastleHistoryEvent"],fields:{ts:!0,epoch:!0,worker:!0,issue:!0,event:!0,duration_s:!0,runner:!0,merge_sha:!0,reason:!0}}),wn({schemaId:uO,docPath:".red/contracts/red.castle.validation.v2.md",typeNames:["CastleValidationRecord","CastleValidationStatus"],fields:{schema:!0,name:!0,status:!0,command:!0,exitCode:!0,durationMs:!0,summary:!0}}),wn({schemaId:lO,docPath:".red/contracts/red.castle.envelope.v1.md",typeNames:["CastleEnvelope","CastleEnvelopeSection","CastleAttemptStatus"],fields:{status:!0,worker:!0,duration:!0,diff:!0,attempt:!0,mergeSha:!0,sections:!0}}),wn({schemaId:dO,docPath:".red/contracts/red.castle.hitl-card.v1.md",typeNames:["CastleHitlCard","CastleHitlCardPrStatus","CastleHitlCardAction"],fields:{issueNumber:!0,issueTitle:!0,issueUrl:!0,pendingDecision:!0,prStatus:!0,updatedAt:!0}})]});var yj,yi=h(()=>{"use strict";W();Ju();yj=new Map(Dh.map(e=>[e.schemaId,new Set(e.fields)]))});var Gh=h(()=>{"use strict";Ah();yi()});var $h=h(()=>{"use strict"});var bi=h(()=>{"use strict"});var Vu=h(()=>{"use strict";bi()});var wi=h(()=>{"use strict"});import{appendFile as fO,mkdir as gO,readFile as hO}from"node:fs/promises";import{dirname as yO,join as bO}from"node:path";function Ku(e,t){if(typeof e!="string"||e.length===0)throw new Error(`singleton event ${t} must be a non-empty string`);return e}function Nh(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("singleton event must be a record");let t={...e},r=t.payload;if(typeof r=="string")try{t.payload=JSON.parse(r)}catch{throw new Error("singleton event payload is not valid JSON")}if(t.payload!==void 0&&(t.payload===null||typeof t.payload!="object"||Array.isArray(t.payload)))throw new Error("singleton event payload must be a record");return{at:Ku(t.at,"at"),singleton:Ku(t.singleton,"singleton"),kind:Ku(t.kind,"kind"),...t.payload===void 0?{}:{payload:t.payload}}}function wO(e){return{at:e.at,singleton:e.singleton,kind:e.kind,...e.payload===void 0?{}:{payload:JSON.stringify(e.payload)}}}function _O(e){if(e!==void 0&&(!Number.isSafeInteger(e)||e<0))throw new Error("singleton event tail must be a non-negative integer")}function EO(e){return bO(e.castleStateRoot,"singleton-events.toonl")}function zu(e,t={}){let r=t.fs??{appendFile:fO,mkdir:gO,readFile:hO},n=t.clock??(()=>new Date().toISOString()),s=EO(e);return{path:s,async append(o){let i=Nh({at:o.at??n(),...o});return await r.mkdir(yO(s),{recursive:!0}),await r.appendFile(s,Ht().push(wO(i)),"utf8"),i},async read(o={}){_O(o.tail);let i;try{i=await r.readFile(s,"utf8")}catch(c){if(c.code==="ENOENT")return[];throw c}let a=Ut(i).map(Nh);return o.tail===void 0?a:o.tail===0?[]:a.slice(-o.tail)}}}var Yu=h(()=>{"use strict";W()});var _i=h(()=>{"use strict";W();wi();Yu()});var Fh=h(()=>{"use strict";bi();Vu();_i()});var Mh=h(()=>{"use strict"});var tU,Bh=h(()=>{"use strict";W();tU=24*60*60*1e3});var jh=h(()=>{"use strict";yi()});var oU,iU,Uh=h(()=>{"use strict";oU=15*6e4,iU=30*6e4});var Hh=h(()=>{"use strict"});var kO,SO,uU,lU,qh=h(()=>{"use strict";kO=["supervisor_start","supervisor_exit","fleet_scaled","worker_start","worker_exit","worker_steered","worker_escalated","post_claim","pre_worktree","post_issue","pre_requeue","pre_merge","post_merge"],SO={pre_worktree:["cargo","gradle"]},uU=Object.values(SO).flat(),lU=new Set(kO)});var Wh=h(()=>{"use strict"});var Jh=h(()=>{"use strict";_i()});var Vh=h(()=>{"use strict"});var Kh=h(()=>{});var zh=h(()=>{"use strict";Kh()});var Yh=h(()=>{"use strict"});var Qh=h(()=>{"use strict"});var Qu=h(()=>{"use strict"});var Xh=h(()=>{"use strict";W();Qu()});var Zh=h(()=>{"use strict";W()});var Xu=h(()=>{"use strict"});var Zu=h(()=>{"use strict"});import{resolve as be}from"node:path";function ey(e){let t=be(e),r=be(t,"state"),n=be(r,"castle"),s=be(t,"tmp"),o=be(s,"supervisors"),i=be(s,"workers"),a=be(s,"monitors"),c=be(s,"worktrees");return{redRoot:t,stateRoot:r,castleStateRoot:n,castleHistory:be(n,"history.toonl"),castleValidation:be(n,"validation.toonl"),tmpRoot:s,supervisorsRoot:o,supervisor:u=>be(o,u),projectSupervisor:be(o,TO),workersRoot:i,worker:u=>be(i,u),workerSteerFile:u=>be(i,u,"steer.toon"),monitorsRoot:a,monitor:u=>be(a,u),worktreesRoot:c,worktreeLane:u=>be(c,u)}}var TO,ty=h(()=>{"use strict";TO="default"});var ry=h(()=>{"use strict";wi()});var ny=h(()=>{"use strict"});var sy=h(()=>{"use strict";Xu();Zu()});import{mkdir as vO,readFile as xO,rename as CO,rm as OO,writeFile as AO}from"node:fs/promises";import{dirname as PO,join as IO}from"node:path";function DO(e){if(!LO.test(e)||e==="."||e==="..")throw new Error(`invalid singleton name ${JSON.stringify(e)}`)}function GO(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function $O(e){return e.code==="ENOENT"}function NO(e){return e.code==="EEXIST"}function FO(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("singleton lease must be a record");let t=e;if(!Number.isInteger(t.pid)||t.pid<=0)throw new Error("singleton lease pid must be a positive integer");for(let r of["start_time","acquired_at","renewed_at"])if(typeof t[r]!="string"||t[r].length===0)throw new Error(`singleton lease ${r} must be a non-empty string`);return t}function el(e,t){return e.pid===t.pid&&e.start_time===t.startTime}function Ei(e,t){return DO(t),IO(e.castleStateRoot,"singletons",t,"lease.toon")}function oy(e,t={}){let r=t.fs??{mkdir:vO,readFile:xO,rename:CO,rm:OO,writeFile:AO},n=t.clock??(()=>new Date().toISOString()),s=t.isPidAlive??GO;async function o(a){try{return FO(H(await r.readFile(a,"utf8")))}catch(c){if($O(c))return;throw c}}async function i(a,c){let u=`${a}.tmp-${c.pid}-${crypto.randomUUID()}`;await r.writeFile(u,$(c,{keyedMapCollapse:!0}),{encoding:"utf8"}),await r.rename(u,a)}return{read(a){return o(Ei(e,a))},async acquire(a,c){let u=Ei(e,a);await r.mkdir(PO(u),{recursive:!0});let l=!1;for(;;){let p=n(),d={pid:c.pid,start_time:c.startTime,acquired_at:p,renewed_at:p};try{return await r.writeFile(u,$(d,{keyedMapCollapse:!0}),{encoding:"utf8",flag:"wx"}),{acquired:!0,reaped:l,lease:d}}catch(f){if(!NO(f))throw f}let g=await o(u);if(g){if(el(g,c))return{acquired:!0,reaped:l,lease:g};if(await s(g.pid))return{acquired:!1,lease:g};await r.rm(u,{force:!0}),l=!0}}},async renew(a,c){let u=Ei(e,a),l=await o(u);if(!l||!el(l,c))throw new Ri(a);let p={...l,renewed_at:n()};return await i(u,p),p},async release(a,c){let u=Ei(e,a),l=await o(u);if(!l)return!1;if(!el(l,c))throw new Ri(a);return await r.rm(u,{force:!0}),!0}}}var Ri,LO,iy=h(()=>{"use strict";W();Ri=class extends Error{constructor(t){super(`singleton lease ${JSON.stringify(t)} is held by another owner`),this.name="SingletonLeaseOwnershipError"}},LO=/^[a-z0-9][a-z0-9._-]{0,63}$/});var tl=h(()=>{"use strict"});var ay=h(()=>{"use strict"});var MO,BO,jO,XU,cy=h(()=>{"use strict";MO={refreshCadenceS:270,tolerance:3},BO=270,jO=2700,XU={...MO,claimGraceS:BO,recentCommitProtectionS:jO}});var uy=h(()=>{"use strict"});function ly(e){return e==="single-object"?"rest":"graphql"}function Z(e,t,r,n,s,o){return{key:e,kind:"read",cardinality:t,volatility:r,surface:o??ly(t),budget:n,...o?{only:o}:{},why:s}}function Ae(e,t,r,n){return{key:e,kind:"write",cardinality:"single-object",surface:t,budget:r,why:n}}var dy,eH,py=h(()=>{dy=[Z("issue view","single-object","stable-poll","rest","one issue by number, repeatedly polled while usually unchanged; REST answers in one request"),Z("pr view","single-object","stable-poll","rest","one pull request by number, polled per Worker per iteration"),Z("repo view","single-object","stable-poll","rest","one repository's own metadata, repeatedly read while usually unchanged"),Z("run view","single-object","stable-poll","rest","one Actions run repeatedly polled to terminal; Actions has no GraphQL surface"),Z("release view","single-object","stable-poll","rest","one release by tag, repeatedly checked while usually absent or unchanged"),Z("pr diff","single-object","one-shot","rest","one pull request's diff, read once for review and served by a REST media type"),Z("issue list","multi-node","stable-poll","graphql","a repeatedly polled, usually-unchanged issue connection; GraphQL avoids N REST pages"),Z("pr list","multi-node","stable-poll","graphql","a repeatedly polled, usually-unchanged pull-request connection; GraphQL avoids N REST pages"),Z("pr checks","multi-node","stable-poll","graphql","check contexts form a connection repeatedly polled while awaiting terminal state"),Z("release list","multi-node","stable-poll","rest","release waits poll a usually-unchanged list; Releases has no GraphQL connection gh reads","rest"),Z("run list","multi-node","stable-poll","rest","run waits poll a usually-unchanged list; Actions has no GraphQL surface","rest"),Z("label list","multi-node","one-shot","graphql","a label connection loaded once for the current operation"),Z("issue list (search)","multi-node","stable-poll","search","queue discovery polls usually-unchanged search results through the 30/min search connection"),Z("pr list (search)","multi-node","stable-poll","search","PR discovery polls usually-unchanged search results through the 30/min search connection"),Z("search issues","multi-repository","one-shot","search","a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),Z("search prs","multi-repository","one-shot","search","a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),Z("search repos","multi-repository","one-shot","search","a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),Z("api graphql","multi-node","one-shot","graphql","the caller supplies one explicit GraphQL query rather than a routed poll"),Z("api rest","single-object","one-shot","rest","the caller supplies one explicit REST path rather than a routed poll"),Ae("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),Ae("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),Ae("issue close","graphql","graphql","gh closes with the closeIssue mutation"),Ae("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),Ae("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),Ae("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),Ae("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),Ae("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),Ae("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),Ae("pr close","graphql","graphql","gh closes with a GraphQL mutation"),Ae("pr edit","graphql","graphql","gh edits with GraphQL mutations"),Ae("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),Ae("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),Ae("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],eH=new Map(dy.map(e=>[e.key,e]))});var my=h(()=>{W()});var sl=Qd((rl,nl)=>{(function(e,t){typeof rl=="object"&&typeof nl<"u"?nl.exports=t():typeof define=="function"&&define.amd?define(t):e.Bottleneck=t()})(rl,function(){"use strict";var e=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function t(I){return I&&I.default||I}var r=function(I,b,m={}){var w,R,S;for(w in b)S=b[w],m[w]=(R=I[w])!=null?R:S;return m},n=function(I,b,m={}){var w,R;for(w in I)R=I[w],b[w]!==void 0&&(m[w]=R);return m},s={load:r,overwrite:n},o;o=class{constructor(b,m){this.incr=b,this.decr=m,this._first=null,this._last=null,this.length=0}push(b){var m;this.length++,typeof this.incr=="function"&&this.incr(),m={value:b,prev:this._last,next:null},this._last!=null?(this._last.next=m,this._last=m):this._first=this._last=m}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,m,w;for(b=this._first,w=[];b!=null;)w.push((m=b,b=b.next,m.value));return w}forEachShift(b){var m;for(m=this.shift();m!=null;)b(m),m=this.shift()}debug(){var b,m,w,R,S;for(b=this._first,S=[];b!=null;)S.push((m=b,b=b.next,{value:m.value,prev:(w=m.prev)!=null?w.value:void 0,next:(R=m.next)!=null?R.value:void 0}));return S}};var i=o,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=(m,w)=>this._addListener(m,"many",w),this.instance.once=(m,w)=>this._addListener(m,"once",w),this.instance.removeAllListeners=(m=null)=>m!=null?delete this._events[m]:this._events={}}_addListener(b,m,w){var R;return(R=this._events)[b]==null&&(R[b]=[]),this._events[b].push({cb:w,status:m}),this.instance}listenerCount(b){return this._events[b]!=null?this._events[b].length:0}async trigger(b,...m){var w,R;try{return b!=="debug"&&this.trigger("debug",`Event triggered: ${b}`,m),this._events[b]==null?void 0:(this._events[b]=this._events[b].filter(function(S){return S.status!=="none"}),R=this._events[b].map(async S=>{var C,A;if(S.status!=="none"){S.status==="once"&&(S.status="none");try{return A=typeof S.cb=="function"?S.cb(...m):void 0,typeof A?.then=="function"?await A:A}catch(U){return C=U,this.trigger("error",C),null}}}),(await Promise.all(R)).find(function(S){return S!=null}))}catch(S){return w=S,this.trigger("error",w),null}}};var c=a,u,l,p;u=i,l=c,p=class{constructor(b){var m;this.Events=new l(this),this._length=0,this._lists=function(){var w,R,S;for(S=[],m=w=1,R=b;1<=R?w<=R:w>=R;m=1<=R?++w:--w)S.push(new u(()=>this.incr(),()=>this.decr()));return S}.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(m){return m.forEachShift(b)})}getFirst(b=this._lists){var m,w,R;for(m=0,w=b.length;m<w;m++)if(R=b[m],R.length>0)return R;return[]}shiftLastFrom(b){return this.getFirst(this._lists.slice(b).reverse()).shift()}};var d=p,g;g=class extends Error{};var f=g,k,E,y,_,T;_=10,E=5,T=s,k=f,y=class{constructor(b,m,w,R,S,C,A,U){this.task=b,this.args=m,this.rejectOnDrop=S,this.Events=C,this._states=A,this.Promise=U,this.options=T.load(w,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((ie,pe)=>{this._resolve=ie,this._reject=pe}),this.retryCount=0}_sanitizePriority(b){var m;return m=~~b!==b?E:b,m<0?0:m>_-1?_-1:m}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:b,message:m="This job has been dropped by Bottleneck"}={}){return this._states.remove(this.options.id)?(this.rejectOnDrop&&this._reject(b??new k(m)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0):!1}_assertStatus(b){var m;if(m=this._states.jobStatus(this.options.id),!(m===b||b==="DONE"&&m===null))throw new k(`Invalid job status ${m}, 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,m){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:b,blocked:m})}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,m,w,R){var S,C,A;this.retryCount===0?(this._assertStatus("RUNNING"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),C={args:this.args,options:this.options,retryCount:this.retryCount},this.Events.trigger("executing",C);try{if(A=await(b!=null?b.schedule(this.options,this.task,...this.args):this.task(...this.args)),m())return this.doDone(C),await R(this.options,C),this._assertStatus("DONE"),this._resolve(A)}catch(U){return S=U,this._onFailure(S,C,m,w,R)}}doExpire(b,m,w){var R,S;return this._states.jobStatus(this.options.id==="RUNNING")&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),S={args:this.args,options:this.options,retryCount:this.retryCount},R=new k(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(R,S,b,m,w)}async _onFailure(b,m,w,R,S){var C,A;if(w())return C=await this.Events.trigger("failed",b,m),C!=null?(A=~~C,this.Events.trigger("retry",`Retrying ${this.options.id} after ${A} ms`,m),this.retryCount++,R(A)):(this.doDone(m),await S(this.options,m),this._assertStatus("DONE"),this._reject(b))}doDone(b){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",b)}};var v=y,G,B,V;V=s,G=f,B=class{constructor(b,m,w){this.instance=b,this.storeOptions=m,this.clientId=this.instance._randomIndex(),V.load(w,w,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 m,w,R,S,C;if(S=Date.now(),this.storeOptions.reservoirRefreshInterval!=null&&S>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=S,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),this.storeOptions.reservoirIncreaseInterval!=null&&S>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval&&({reservoirIncreaseAmount:m,reservoirIncreaseMaximum:R,reservoir:C}=this.storeOptions,this._lastReservoirIncrease=S,w=R!=null?Math.min(m,R-C):m,w>0))return this.storeOptions.reservoir+=w,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(m,w){return setTimeout(m,b)})}computePenalty(){var b;return(b=this.storeOptions.penalty)!=null?b:15*this.storeOptions.minTime||5e3}async __updateSettings__(b){return await this.yieldLoop(),V.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,m;return{maxConcurrent:b,reservoir:m}=this.storeOptions,b!=null&&m!=null?Math.min(b-this._running,m):b!=null?b-this._running:m??null}conditionsCheck(b){var m;return m=this.computeCapacity(),m==null||b<=m}async __incrementReservoir__(b){var m;return await this.yieldLoop(),m=this.storeOptions.reservoir+=b,this.instance._drainAll(this.computeCapacity()),m}async __currentReservoir__(){return await this.yieldLoop(),this.storeOptions.reservoir}isBlocked(b){return this._unblockTime>=b}check(b,m){return this.conditionsCheck(b)&&this._nextRequest-m<=0}async __check__(b){var m;return await this.yieldLoop(),m=Date.now(),this.check(b,m)}async __register__(b,m,w){var R,S;return await this.yieldLoop(),R=Date.now(),this.conditionsCheck(m)?(this._running+=m,this.storeOptions.reservoir!=null&&(this.storeOptions.reservoir-=m),S=Math.max(this._nextRequest-R,0),this._nextRequest=R+S+this.storeOptions.minTime,{success:!0,wait:S,reservoir:this.storeOptions.reservoir}):{success:!1}}strategyIsBlock(){return this.storeOptions.strategy===3}async __submit__(b,m){var w,R,S;if(await this.yieldLoop(),this.storeOptions.maxConcurrent!=null&&m>this.storeOptions.maxConcurrent)throw new G(`Impossible to add a job having a weight of ${m} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`);return R=Date.now(),S=this.storeOptions.highWater!=null&&b===this.storeOptions.highWater&&!this.check(m,R),w=this.strategyIsBlock()&&(S||this.isBlocked(R)),w&&(this._unblockTime=R+this.computePenalty(),this._nextRequest=this._unblockTime+this.storeOptions.minTime,this.instance._dropAllQueued()),{reachedHWM:S,blocked:w,strategy:this.storeOptions.strategy}}async __free__(b,m){return await this.yieldLoop(),this._running-=m,this._done+=m,this.instance._drainAll(this.computeCapacity()),{running:this._running}}};var te=B,re,He;re=f,He=class{constructor(b){this.status=b,this._jobs={},this.counts=this.status.map(function(){return 0})}next(b){var m,w;if(m=this._jobs[b],w=m+1,m!=null&&w<this.status.length)return this.counts[m]--,this.counts[w]++,this._jobs[b]++;if(m!=null)return this.counts[m]--,delete this._jobs[b]}start(b){var m;return m=0,this._jobs[b]=m,this.counts[m]++}remove(b){var m;return m=this._jobs[b],m!=null&&(this.counts[m]--,delete this._jobs[b]),m!=null}jobStatus(b){var m;return(m=this.status[this._jobs[b]])!=null?m:null}statusJobs(b){var m,w,R,S,C;if(b!=null){if(w=this.status.indexOf(b),w<0)throw new re(`status must be one of ${this.status.join(", ")}`);R=this._jobs,S=[];for(m in R)C=R[m],C===w&&S.push(m);return S}else return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce((b,m,w)=>(b[this.status[w]]=m,b),{})}};var de=He,Ft,P;Ft=i,P=class{constructor(b,m){this.schedule=this.schedule.bind(this),this.name=b,this.Promise=m,this._running=0,this._queue=new Ft}isEmpty(){return this._queue.length===0}async _tryToRun(){var b,m,w,R,S,C,A;if(this._running<1&&this._queue.length>0)return this._running++,{task:A,args:b,resolve:S,reject:R}=this._queue.shift(),m=await async function(){try{return C=await A(...b),function(){return S(C)}}catch(U){return w=U,function(){return R(w)}}}(),this._running--,this._tryToRun(),m()}schedule(b,...m){var w,R,S;return S=R=null,w=new this.Promise(function(C,A){return S=C,R=A}),this._queue.push({task:b,args:m,resolve:S,reject:R}),this._tryToRun(),w}};var M=P,De="2.19.5",_t={version:De},Mt=Object.freeze({version:De,default:_t}),O=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),N=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),Et=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),st,ve,xe,Rt,Fr,Bt;Bt=s,st=c,Rt=O,xe=N,Fr=Et,ve=function(){class I{constructor(m={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=m,Bt.load(this.limiterOptions,this.defaults,this),this.Events=new st(this),this.instances={},this.Bottleneck=zd,this._startAutoCleanup(),this.sharedConnection=this.connection!=null,this.connection==null&&(this.limiterOptions.datastore==="redis"?this.connection=new Rt(Object.assign({},this.limiterOptions,{Events:this.Events})):this.limiterOptions.datastore==="ioredis"&&(this.connection=new xe(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(m=""){var w;return(w=this.instances[m])!=null?w:(()=>{var R;return R=this.instances[m]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${m}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",R,m),R})()}async deleteKey(m=""){var w,R;return R=this.instances[m],this.connection&&(w=await this.connection.__runCommand__(["del",...Fr.allKeys(`${this.id}-${m}`)])),R!=null&&(delete this.instances[m],await R.disconnect()),R!=null||w>0}limiters(){var m,w,R,S;w=this.instances,R=[];for(m in w)S=w[m],R.push({key:m,limiter:S});return R}keys(){return Object.keys(this.instances)}async clusterKeys(){var m,w,R,S,C,A,U,ie,pe;if(this.connection==null)return this.Promise.resolve(this.keys());for(A=[],m=null,pe=`b_${this.id}-`.length,w=9;m!==0;)for([ie,R]=await this.connection.__runCommand__(["scan",m??0,"match",`b_${this.id}-*_settings`,"count",1e4]),m=~~ie,S=0,U=R.length;S<U;S++)C=R[S],A.push(C.slice(pe,-w));return A}_startAutoCleanup(){var m;return clearInterval(this.interval),typeof(m=this.interval=setInterval(async()=>{var w,R,S,C,A,U;A=Date.now(),S=this.instances,C=[];for(R in S){U=S[R];try{await U._store.__groupCheck__(A)?C.push(this.deleteKey(R)):C.push(void 0)}catch(ie){w=ie,C.push(U.Events.trigger("error",w))}}return C},this.timeout/2)).unref=="function"?m.unref():void 0}updateSettings(m={}){if(Bt.overwrite(m,this.defaults,this),Bt.overwrite(m,m,this.limiterOptions),m.timeout!=null)return this._startAutoCleanup()}disconnect(m=!0){var w;if(!this.sharedConnection)return(w=this.connection)!=null?w.disconnect(m):void 0}}return I.prototype.defaults={timeout:1e3*60*5,connection:null,Promise,id:"group-key"},I}.call(e);var Pn=ve,ur,In,jd;jd=s,In=c,ur=function(){class I{constructor(m={}){this.options=m,jd.load(this.options,this.defaults,this),this.Events=new In(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise((m,w)=>this._resolve=m)}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(m){var w;return this._arr.push(m),w=this._promise,this._arr.length===this.maxSize?this._flush():this.maxTime!=null&&this._arr.length===1&&(this._timeout=setTimeout(()=>this._flush(),this.maxTime)),w}}return I.prototype.defaults={maxTime:null,maxSize:null,Promise},I}.call(e);var qE=ur,WE=()=>console.log("You must import the full version of Bottleneck in order to use this feature."),JE=t(Mt),Ud,Hd,ma,fa,qd,ga,Wd,Jd,Vd,ha,ot,Kd=[].splice;ga=10,Hd=5,ot=s,Wd=d,fa=v,qd=te,Jd=WE,ma=c,Vd=de,ha=M,Ud=function(){class I{constructor(m={},...w){var R,S;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(m,w),ot.load(m,this.instanceDefaults,this),this._queues=new Wd(ga),this._scheduled={},this._states=new Vd(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new ma(this),this._submitLock=new ha("submit",this.Promise),this._registerLock=new ha("register",this.Promise),S=ot.load(m,this.storeDefaults,{}),this._store=function(){if(this.datastore==="redis"||this.datastore==="ioredis"||this.connection!=null)return R=ot.load(m,this.redisStoreDefaults,{}),new Jd(this,S,R);if(this.datastore==="local")return R=ot.load(m,this.localStoreDefaults,{}),new qd(this,S,R);throw new I.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}.call(this),this._queues.on("leftzero",()=>{var C;return(C=this._store.heartbeat)!=null&&typeof C.ref=="function"?C.ref():void 0}),this._queues.on("zero",()=>{var C;return(C=this._store.heartbeat)!=null&&typeof C.unref=="function"?C.unref():void 0})}_validateOptions(m,w){if(!(m!=null&&typeof m=="object"&&w.length===0))throw new I.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(m){return this._store.__publish__(m)}disconnect(m=!0){return this._store.__disconnect__(m)}chain(m){return this._limiter=m,this}queued(m){return this._queues.queued(m)}clusterQueued(){return this._store.__queued__()}empty(){return this.queued()===0&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(m){return this._states.jobStatus(m)}jobs(m){return this._states.statusJobs(m)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(m=1){return this._store.__check__(m)}_clearGlobalState(m){return this._scheduled[m]!=null?(clearTimeout(this._scheduled[m].expiration),delete this._scheduled[m],!0):!1}async _free(m,w,R,S){var C,A;try{if({running:A}=await this._store.__free__(m,R.weight),this.Events.trigger("debug",`Freed ${R.id}`,S),A===0&&this.empty())return this.Events.trigger("idle")}catch(U){return C=U,this.Events.trigger("error",C)}}_run(m,w,R){var S,C,A;return w.doRun(),S=this._clearGlobalState.bind(this,m),A=this._run.bind(this,m,w),C=this._free.bind(this,m,w),this._scheduled[m]={timeout:setTimeout(()=>w.doExecute(this._limiter,S,A,C),R),expiration:w.options.expiration!=null?setTimeout(function(){return w.doExpire(S,A,C)},R+w.options.expiration):void 0,job:w}}_drainOne(m){return this._registerLock.schedule(()=>{var w,R,S,C,A;return this.queued()===0?this.Promise.resolve(null):(A=this._queues.getFirst(),{options:C,args:w}=S=A.first(),m!=null&&C.weight>m?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${C.id}`,{args:w,options:C}),R=this._randomIndex(),this._store.__register__(R,C.weight,C.expiration).then(({success:U,wait:ie,reservoir:pe})=>{var Ln;return this.Events.trigger("debug",`Drained ${C.id}`,{success:U,args:w,options:C}),U?(A.shift(),Ln=this.empty(),Ln&&this.Events.trigger("empty"),pe===0&&this.Events.trigger("depleted",Ln),this._run(R,S,ie),this.Promise.resolve(C.weight)):this.Promise.resolve(null)})))})}_drainAll(m,w=0){return this._drainOne(m).then(R=>{var S;return R!=null?(S=m!=null?m-R:m,this._drainAll(S,w+R)):this.Promise.resolve(w)}).catch(R=>this.Events.trigger("error",R))}_dropAllQueued(m){return this._queues.shiftAll(function(w){return w.doDrop({message:m})})}stop(m={}){var w,R;return m=ot.load(m,this.stopDefaults),R=S=>{var C;return C=()=>{var A;return A=this._states.counts,A[0]+A[1]+A[2]+A[3]===S},new this.Promise((A,U)=>C()?A():this.on("done",()=>{if(C())return this.removeAllListeners("done"),A()}))},w=m.dropWaitingJobs?(this._run=function(S,C){return C.doDrop({message:m.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule(()=>this._submitLock.schedule(()=>{var S,C,A;C=this._scheduled;for(S in C)A=C[S],this.jobStatus(A.job.options.id)==="RUNNING"&&(clearTimeout(A.timeout),clearTimeout(A.expiration),A.job.doDrop({message:m.dropErrorMessage}));return this._dropAllQueued(m.dropErrorMessage),R(0)}))):this.schedule({priority:ga-1,weight:0},()=>R(1)),this._receive=function(S){return S._reject(new I.prototype.BottleneckError(m.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new I.prototype.BottleneckError("stop() has already been called")),w}async _addToQueue(m){var w,R,S,C,A,U,ie;({args:w,options:C}=m);try{({reachedHWM:A,blocked:R,strategy:ie}=await this._store.__submit__(this.queued(),C.weight))}catch(pe){return S=pe,this.Events.trigger("debug",`Could not queue ${C.id}`,{args:w,options:C,error:S}),m.doDrop({error:S}),!1}return R?(m.doDrop(),!0):A&&(U=ie===I.prototype.strategy.LEAK?this._queues.shiftLastFrom(C.priority):ie===I.prototype.strategy.OVERFLOW_PRIORITY?this._queues.shiftLastFrom(C.priority+1):ie===I.prototype.strategy.OVERFLOW?m:void 0,U?.doDrop(),U==null||ie===I.prototype.strategy.OVERFLOW)?(U==null&&m.doDrop(),A):(m.doQueue(A,R),this._queues.push(m),await this._drainAll(),A)}_receive(m){return this._states.jobStatus(m.options.id)!=null?(m._reject(new I.prototype.BottleneckError(`A job with the same id already exists (id=${m.options.id})`)),!1):(m.doReceive(),this._submitLock.schedule(this._addToQueue,m))}submit(...m){var w,R,S,C,A,U,ie;return typeof m[0]=="function"?(A=m,[R,...m]=A,[w]=Kd.call(m,-1),C=ot.load({},this.jobDefaults)):(U=m,[C,R,...m]=U,[w]=Kd.call(m,-1),C=ot.load(C,this.jobDefaults)),ie=(...pe)=>new this.Promise(function(Ln,KE){return R(...pe,function(...Yd){return(Yd[0]!=null?KE:Ln)(Yd)})}),S=new fa(ie,m,C,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),S.promise.then(function(pe){return typeof w=="function"?w(...pe):void 0}).catch(function(pe){return Array.isArray(pe)?typeof w=="function"?w(...pe):void 0:typeof w=="function"?w(pe):void 0}),this._receive(S)}schedule(...m){var w,R,S;return typeof m[0]=="function"?([S,...m]=m,R={}):[R,S,...m]=m,w=new fa(S,m,R,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(w),w.promise}wrap(m){var w,R;return w=this.schedule.bind(this),R=function(...S){return w(m.bind(this),...S)},R.withOptions=function(S,...C){return w(S,m,...C)},R}async updateSettings(m={}){return await this._store.__updateSettings__(ot.overwrite(m,this.storeDefaults)),ot.overwrite(m,this.instanceDefaults,this),this}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(m=0){return this._store.__incrementReservoir__(m)}}return I.default=I,I.Events=ma,I.version=I.prototype.version=JE.version,I.strategy=I.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},I.BottleneckError=I.prototype.BottleneckError=f,I.Group=I.prototype.Group=Pn,I.RedisConnection=I.prototype.RedisConnection=O,I.IORedisConnection=I.prototype.IORedisConnection=N,I.Batcher=I.prototype.Batcher=qE,I.prototype.jobDefaults={priority:Hd,weight:1,expiration:null,id:"<no-id>"},I.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:I.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},I.prototype.localStoreDefaults={Promise,timeout:null,heartbeatInterval:250},I.prototype.redisStoreDefaults={Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},I.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise},I.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},I}.call(e);var zd=Ud,VE=zd;return VE})});var Nt,ol=h(()=>{Nt=class extends Error{name;status;request;response;constructor(t,r,n){super(t,{cause:n.cause}),this.name="HttpError",this.status=Number.parseInt(r),Number.isNaN(this.status)&&(this.status=0);"response"in n&&(this.response=n.response);let s=Object.assign({},n.request);n.request.headers.authorization&&(s.headers=Object.assign({},n.request.headers,{authorization:n.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),s.url=s.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=s}}});function HO(e){return e.request!==void 0}async function fy(e,t,r,n){if(!HO(r)||!r?.request.request)throw r;if(r.status>=400&&!e.doNotRetry.includes(r.status)){let s=n.request.retries!=null?n.request.retries:e.retries,o=Math.pow((n.request.retryCount||0)+1,2);throw t.retry.retryRequest(r,s,o)}throw r}async function qO(e,t,r,n){let s=new gy.default;return s.on("failed",function(o,i){let a=~~o.request.request?.retries,c=~~o.request.request?.retryAfter;if(n.request.retryCount=i.retryCount+1,a>i.retryCount)return c*e.retryAfterBaseValue}),s.schedule(WO.bind(null,e,t,r),n)}async function WO(e,t,r,n){let s=await r(n);if(s.data&&s.data.errors&&s.data.errors.length>0&&/Something went wrong while executing your query/.test(s.data.errors[0].message)){let o=new Nt(s.data.errors[0].message,500,{request:n,response:s});return fy(e,t,o,n)}return s}function il(e,t){let r=Object.assign({enabled:!0,retryAfterBaseValue:1e3,doNotRetry:[400,401,403,404,410,422,451],retries:3},t.retry),n={retry:{retryRequest:(s,o,i)=>(s.request.request=Object.assign({},s.request.request,{retries:o,retryAfter:i}),s)}};return r.enabled&&(e.hook.error("request",fy.bind(null,r,n)),e.hook.wrap("request",qO.bind(null,r,n))),n}var gy,UO,hy=h(()=>{gy=ba(sl(),1);ol();UO="0.0.0-development";il.VERSION=UO});function VO(e,t,r){return e.retryLimiter.schedule(KO,e,t,r)}async function KO(e,t,r){let{pathname:n}=new URL(r.url,"http://github.test"),s=zO(r.method,n),o=!s&&r.method!=="GET"&&r.method!=="HEAD",i=r.method==="GET"&&n.startsWith("/search/"),a=n.startsWith("/graphql"),u=~~t.retryCount>0?{priority:0,weight:0}:{};e.clustering&&(u.expiration=1e3*60),(o||a)&&await e.write.key(e.id).schedule(u,al),o&&e.triggersNotification(n)&&await e.notifications.key(e.id).schedule(u,al),i&&await e.search.key(e.id).schedule(u,al);let l=(s?e.auth:e.global).key(e.id).schedule(u,t,r);if(a){let p=await l;if(p.data.errors!=null&&p.data.errors.some(d=>d.type==="RATE_LIMITED"))throw Object.assign(new Error("GraphQL Rate Limit Exceeded"),{response:p,data:p.data})}return l}function zO(e,t){return e==="PATCH"&&/^\/applications\/[^/]+\/token\/scoped$/.test(t)||e==="POST"&&(/^\/applications\/[^/]+\/token$/.test(t)||/^\/app\/installations\/[^/]+\/access_tokens$/.test(t)||t==="/login/oauth/access_token")}function QO(e){let r=`^(?:${e.map(n=>n.split("/").map(s=>s.startsWith("{")?"(?:.+?)":s).join("/")).map(n=>`(?:${n})`).join("|")})[^/]*$`;return new RegExp(r,"i")}function ki(e,t){let{enabled:r=!0,Bottleneck:n=by.default,id:s="no-id",timeout:o=1e3*60*2,connection:i}=t.throttle||{};if(!r)return{};let a={timeout:o};typeof i<"u"&&(a.connection=i);let c=Object.assign({clustering:i!=null,triggersNotification:wy,fallbackSecondaryRateRetryAfter:60,retryAfterBaseValue:1e3,id:s},t.throttle);if(typeof c.onSecondaryRateLimit!="function"||typeof c.onRateLimit!="function")throw new Error(`octokit/plugin-throttling error:
89
89
  You must pass the onSecondaryRateLimit and onRateLimit error handlers.
90
90
  See https://octokit.github.io/rest.js/#throttling
91
91
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reddb-io/red-skills",
3
- "version": "3.5.1",
3
+ "version": "3.6.0",
4
4
  "description": "RedSkills plugin runtime bundles (dev, code-nav, memory, brain) distributed over npm — the v2 client transport (ADR 0091). Carries the platform-independent JS bundles inside the tarball plus thin bin shims; no postinstall download.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",