import{s as e}from"./DrKWWDpL.js";import{t}from"./DYP3EJMY.js";import{Bt as n,D as r,Jt as i,Xt as a}from"./DIQmuJJZ.js";import{r as o}from"./DOqzs8kl2.js";import{i as s}from"./CX8DOZuw2.js";import{t as c}from"./BYJC6_MM.js";import{t as l}from"./DTkg6Mnx.js";import{t as u}from"./D1Pv_C30.js";var d=e(c(),1),f=e(t(),1),p=`cleo-supervisor.sock`,m=250,h=2e3;function g(){return{}.CLEO_SUPERVISOR_SOCKET??(0,f.join)(o(),p)}async function _(e,t,n,r){let i=await y(e,{kind:`resource_admit`,class:t,holder_id:n,budget:r},`resource_admit_result`);return`unavailable`in i||i.kind===`resource_admit_result`?i:{unavailable:!0,reason:`unexpected response kind: ${i.kind}`}}async function v(e,t,n){let r=await y(e,{kind:`resource_release`,class:t,holder_id:n},`resource_release_result`);return`unavailable`in r||r.kind===`resource_release_result`?r:{unavailable:!0,reason:`unexpected response kind: ${r.kind}`}}function y(e,t,r){return new Promise(o=>{let s=`ra-${process.pid}-${t.kind}`,c=i.parse({protocol_version:n,id:s,direction:`request`,request:t}),l=`${JSON.stringify(c)}\n`,u=!1,d=``,p=(0,f.connect)(e),g=e=>{u||(u=!0,p.removeAllListeners(),p.destroy(),o(e))},_=e=>g({unavailable:!0,reason:e});p.setTimeout(h);let v=setTimeout(()=>_(`supervisor connect timeout`),m);p.on(`connect`,()=>{clearTimeout(v),p.write(l)}),p.on(`timeout`,()=>_(`supervisor request timeout`)),p.on(`error`,e=>{clearTimeout(v),_(e.message)}),p.on(`close`,()=>{u||_(`supervisor closed the connection before responding`)}),p.on(`data`,e=>{d+=e.toString(`utf8`);let n=d.indexOf(`
`);if(n<0)return;let i;try{i=JSON.parse(d.slice(0,n))}catch(e){_(`malformed lease-ipc frame: ${e instanceof Error?e.message:e}`);return}let o=a.safeParse(i);if(!o.success){_(`off-contract lease-ipc response: ${o.error.message}`);return}let{response:s}=o.data;if(s.kind===r){g(s);return}if(s.kind===`error`){_(`${s.code}: ${s.message}`);return}_(`unexpected lease-ipc response kind for ${t.kind}: ${s.kind}`)})})}var b=null;function x(){return b===null&&(b=l(`resource-governor`)),b}var S=null,C=!1;function w(){if(S!==null)return S;let e={}.CLEO_RESOURCES_MODE;return S=e===`supervisor`||e===`local`||e===`off`?e:`local`,S}function T(e){C||(C=!0,x().info(`CLEO_RESOURCES_MODE=supervisor but the arbiter is unreachable (${e}); degrading to local-mode admission for the process lifetime.`))}var E=1024*1024;function D(e){return(e.globalPressure?.some??e.slicePressure?.some)?.avg10??0}function O(e,t,n={}){if(e===`interactive-cli`)return 1/0;let r=Math.max(1,n.cpuCount??(0,f.availableParallelism)()),i=n.totalMemBytes??(0,f.totalmem)(),a=(n.headroomMb??2048)*E,o=n.holdSomeAvg10??10,s=n.floorSomeAvg10??25,c=D(t),l=t.memAvailableBytes??i,u=t.globalPressure?.full?.avg10??t.slicePressure?.full?.avg10??0,d=c>s||u>10;switch(e){case`full-build`:return 1;case`agent-session`:{let e=(n.agentEstRamMb??4096)*E;return k(1,Math.floor((l-a)/e),Math.max(1,r-2))}case`llm-call`:return Math.max(1,r-2);case`test-run`:case`scoped-build`:{let e=Math.max(1,Math.floor(r/4));return c>s?1:c>o?Math.max(1,Math.floor(e/2)):e}case`db-heavy`:return+!d;case`background-autonomous`:return c>o||u>5?0:1;default:return 1}}function k(e,t,n){return Math.max(e,Math.min(t,n))}function A(e){return(0,f.join)(s(),`locks`,`resource-${e}`)}function j(e,t){(0,f.existsSync)(e)||(0,f.mkdirSync)(e,{recursive:!0});let n=[];for(let r=0;r<t;r++){let t=(0,f.join)(e,`slot-${r}.lock`);(0,f.existsSync)(t)||(0,f.writeFileSync)(t,``,{flag:`a`}),n.push(t)}return n}var M=6e5;function N(e){return new Promise(t=>setTimeout(t,e))}function P(e){return{deferred:!1,class:e,slot:-1,acquiredAtMs:Date.now(),release:async()=>{}}}function F(e,t,n){return{deferred:!0,class:e,retryAfterMs:n,reason:t}}var I=0;function L(e){return I+=1,`${process.pid}:${e}:${I}`}var R=class{async acquire(e,t={}){let n=w();if(n===`off`||e===`interactive-cli`)return P(e);let i=t.sample??await(t.monitor??new u).sample(),a=O(e,i,t);if(!Number.isFinite(a))return P(e);if(a<=0)return F(e,`class '${e}' budget is 0 under current pressure (some avg10=${D(i).toFixed(1)})`,r);if(n===`supervisor`){let t=await this.acquireViaSupervisor(e,Math.floor(a));if(t!==null)return t}let o=j(A(e),a),s=t.blocking??!0,c=t.timeoutMs??36e5,l=t.pollMs??200,f=Date.now();do{let t=z(o.length);for(let n of t){let t=o[n];if(t)try{let r=await d.default.lock(t,{retries:0,stale:M,realpath:!1}),i=!1;return{deferred:!1,class:e,slot:n,acquiredAtMs:Date.now(),release:async()=>{if(!i){i=!0;try{await r()}catch{}}}}}catch{}}if(!s)break;await N(l)}while(Date.now()-f<c);return F(e,`class '${e}' is at capacity (${a} slot(s)); `+(s?`timed out after ${c}ms`:`no slot free`),Math.min(l*4,r))}async acquireViaSupervisor(e,t){let n=g(),r=L(e),i=await _(n,e,r,t);if(`unavailable`in i)return T(i.reason),null;if(i.disposition===`deferred`)return F(e,`class '${e}' deferred by supervisor (budget ${t})`,i.retry_after_ms||2e3);let a=!1;return{deferred:!1,class:e,slot:0,acquiredAtMs:Date.now(),release:async()=>{a||(a=!0,await v(n,e,r).catch(()=>{}))}}}async tryAcquire(e,t={}){return this.acquire(e,{...t,blocking:!1})}async available(e,t={}){if(w()===`off`||e===`interactive-cli`)return 1/0;let n=O(e,t.sample??await(t.monitor??new u).sample(),t);if(!Number.isFinite(n))return 1/0;if(n<=0)return 0;let r=await B(e,n);return Math.max(0,n-r)}};function z(e){let t=Array.from({length:e},(e,t)=>t);for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1)),r=t[e],i=t[n];r!==void 0&&i!==void 0&&(t[e]=i,t[n]=r)}return t}async function B(e,t){let n=A(e);if(!(0,f.existsSync)(n))return 0;let r=j(n,t),i=0;for(let e of r)try{await(await d.default.lock(e,{retries:0,stale:M,realpath:!1}))()}catch{i++}return i}var V=new R;export{w as a,A as i,O as n,V as r,R as t};