import{s as e}from"./DrKWWDpL.js";import{t}from"./DYP3EJMY.js";import{Bt as n,Jt as r,Xt as i}from"./DIQmuJJZ.js";import{r as a}from"./DOqzs8kl2.js";import{t as o}from"./DTkg6Mnx.js";import{t as s}from"./6qfzuuhO.js";import{t as c}from"./CvWN0JfP.js";import{t as l}from"./DiIbXgam.js";import{n as u}from"./DoOTPDI-.js";import{a as d}from"./NC6fXeo_.js";import{r as f}from"./b2R8Ad-3.js";var p=e(t(),1),m=`cleo-supervisor.sock`,h=250,g=2e3,_=5e3,v=null;function y(){return v===null&&(v=o(`llm-queue-admit`)),v}var b=null,x=!1;function S(){return b===null&&(b={}.CLEO_LLM_QUEUE_MODE===`supervisor`?`supervisor`:`off`),b}function C(e){x||(x=!0,y().info(`CLEO_LLM_QUEUE_MODE=supervisor but the LLM-queue arbiter is unavailable (${e}); degrading to direct LLM execution for the process lifetime.`))}function w(){let e={}.CLEO_SUPERVISOR_SOCKET;return e!==void 0&&e.length>0?e:(0,p.join)(a(),m)}var T={admitted:!0,via:`direct`};function E(e){return new Promise(t=>setTimeout(t,Math.max(0,Math.round(e))))}async function D(e,t,n,r,i={}){if(S()===`off`)return T;let a=i.socketPath??w(),o=Date.now()+(i.deadlineMs??3e4);for(;;){let i;try{i=await O(a,{kind:`queue_admit`,provider:e,priority_class:t,est_tokens:Math.max(0,Math.trunc(n)),child_id:r})}catch(e){return C(e instanceof Error?e.message:String(e)),T}if(`unavailable`in i)return C(i.reason),T;if(i.disposition===`admitted`)return{admitted:!0,via:`supervisor`};if(Date.now()>=o)return y().debug({provider:e,priorityClass:t,queuePosition:i.queue_position},`llm-queue admit deadline exceeded while deferred; proceeding directly`),T;await E(Math.min(_,Math.max(1,i.retry_after_ms)))}}function O(e,t){return new Promise((a,o)=>{let s=`qa-${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,c=r.parse({protocol_version:n,id:s,direction:`request`,request:t}),l=`${JSON.stringify(c)}\n`,u=!1,d=``,f=(0,p.connect)(e),m=()=>{f.removeAllListeners(),f.destroy()},_=e=>{u||(u=!0,m(),o(e))},v=e=>{u||(u=!0,m(),a(e))};f.setTimeout(g);let y=setTimeout(()=>_(Error(`supervisor connect timeout`)),h);f.on(`connect`,()=>{clearTimeout(y),f.write(l)}),f.on(`timeout`,()=>_(Error(`supervisor request timeout`))),f.on(`error`,e=>{clearTimeout(y),_(e)}),f.on(`close`,()=>{u||_(Error(`supervisor closed the connection before responding`))}),f.on(`data`,e=>{d+=e.toString(`utf8`);let t=d.indexOf(`
`);if(t<0)return;let n=d.slice(0,t),r;try{r=JSON.parse(n)}catch(e){_(Error(`malformed lease-ipc frame: ${e instanceof Error?e.message:e}`));return}let a=i.safeParse(r);if(!a.success){_(Error(`off-contract lease-ipc response: ${a.error.message}`));return}let{response:o}=a.data;if(o.kind===`queue_admit_result`){v(o);return}if(o.kind===`error`){v({unavailable:!0,reason:`${o.code}: ${o.message}`});return}_(Error(`unexpected lease-ipc response kind for queue_admit: ${o.kind}`))})})}var k=new Set;function A(e,t){k.has(e)||(k.add(e),console.warn(t))}function j(){switch({}.CLEO_AGENT_ROLE){case`lead`:case`orchestrator`:return`lead`;case`worker`:case`subagent`:return`worker`;default:return`background`}}var M=1024;async function N(e,t,n,r={}){let i=await f(e,{projectRoot:r.projectRoot});if(!i.sealedCredential||!i.credential)return A(`${e}|${i.provider}|<none>`,`[role-executor] role=${e} provider=${i.provider}: no usable credential. Run 'cleo llm login' (or 'cleo llm add ${i.provider}') to authenticate, or 'cleo llm profile ${e} <provider>' to bind this role to a configured provider.`),null;let a=i.credentialLabel??`<default>`,o=r.modelOverride??i.model,p={model:o,system:t,messages:[{role:`user`,content:n}],maxTokens:r.maxTokens??M,...r.temperature===void 0?{}:{temperature:r.temperature},...r.signal===void 0?{}:{signal:r.signal}};try{let t=i.credential.authType===`oauth`?`oauth`:`api_key`,n=(await i.sealedCredential.fetch()).value;i.provider===`kimi-code`&&t!==`oauth`&&!u(n)&&console.warn(`[role-executor] kimi-code credential is not sk-kimi- prefixed and not OAuth; the request may fail. Configure a coding-plan key from kimi.com/code or switch the provider to 'moonshot' for legacy mk- keys.`);let a=c(i.provider,t),o={provider:i.provider,label:i.credentialLabel??`default`,token:n,authType:t,expiresAt:null,refreshToken:null,extraHeaders:{},baseUrl:a.baseUrl,awsProfile:null},l=s.buildTransportFromCredential(i.provider,o,a.apiMode);await D(i.provider,j(),r.maxTokens??M,`role:${e}:pid-${process.pid}`);let d=await l.complete(p);return{content:d.content??``,usage:d.usage,provider:i.provider,model:d.model}}catch(t){let n=t instanceof Error?t.message:String(t),r=d(t,{provider:i.provider,model:o}),s=`${e}|${i.provider}|${a}`;return r.reason===`auth`&&i.credentialLabel?(new l(i.provider).markExhausted(i.credentialLabel,r.statusCode??401).catch(()=>{}),A(s,`[role-executor] role=${e} provider=${i.provider} model=${o} credential '${a}' rejected (${r.statusCode??401} auth). Quarantined this credential. Run 'cleo llm login' to re-authenticate, or 'cleo llm profile ${e} <provider>' to bind this role elsewhere.`)):A(s,`[role-executor] role=${e} provider=${i.provider} model=${o} call failed: ${n}`),null}}export{N as t};