import{t as e}from"./providerRegistry-DXZVv1rc.js";import{t}from"./client-CG1X3JM2.js";import{n,t as r}from"./types-D9R5QJnK.js";import{spawn as i}from"node:child_process";import*as a from"node:path";const o={debug:(e,...t)=>console.debug(`[Router] ${e}`,...t),info:(e,...t)=>console.info(`[Router] ${e}`,...t),warn:(e,...t)=>console.warn(`[Router] ${e}`,...t),error:(e,...t)=>console.error(`[Router] ${e}`,...t)};var s=class{#e;#t;#n;#r;constructor(t,n){this.#e=new e(t),this.#t=new Map,this.#n=t.prompt.retryPolicy||{maxRetries:2,backoffMs:1e3},this.#r=n||o}#i(e){if(!this.#t.has(e.name))if(e.baseUrl.startsWith(`cli:`)){let t=e.baseUrl.replace(`cli:`,``);this.#t.set(e.name,new l(t))}else this.#t.set(e.name,new t(e));return this.#t.get(e.name)}async execute(e){let t=e.model||this.#e.getDefaultModel();if(!t)throw Error(`No model specified and no default model configured. Please specify a model with --model or configure a default model.`);let r=this.#e.getProvidersForModel(t);if(r.length===0)throw new n(t,this.#e.getAllModels());return this.#r.info(`Using model: ${t} (${r.length} provider(s) available)`),await this.#a(t,e,r)}async#a(e,t,n){let i=[];for(let a=0;a<n.length;a++){let o=n[a],s=a===n.length-1;try{this.#r.debug(`Trying provider: ${o.name} (priority: ${o.priority||`default`})`);let n=this.#i(o),r={...t,model:e},i=await this.#c(()=>n.generate(r),o.timeout||6e4);return this.#r.info(`✓ Successfully used provider: ${o.name}`),i}catch(t){let n=t;if(this.#r.warn(`✗ Provider ${o.name} failed: ${n.message}`),i.push({provider:o.name,error:n}),!(this.#o(n)&&!s))throw s&&i.length>1?new r(e,i):n;s||await this.#s(a)}}throw new r(e,i)}#o(e){let t=e.message.toLowerCase();if(t.includes(`econnrefused`)||t.includes(`etimedout`)||t.includes(`enotfound`)||t.includes(`network`)||t.includes(`fetch failed`))return!0;let n=e;if(typeof n.status==`number`){let e=n.status;if(e>=500&&e<600||e===429)return!0;if(e>=400&&e<500)return!1}return!!t.match(/\b(5\d{2}|429)\b/)}async#s(e){let t=Math.min(this.#n.backoffMs*2**e,3e4);this.#r.debug(`Backing off for ${t}ms before next attempt`),await new Promise(e=>setTimeout(e,t))}async#c(e,t){return new Promise((n,r)=>{let i=setTimeout(()=>{r(Error(`Request timed out after ${t}ms`))},t);e().then(e=>{clearTimeout(i),n(e)}).catch(e=>{clearTimeout(i),r(e)})})}async executeStream(e){let t=e.model||this.#e.getDefaultModel();if(!t)throw Error(`No model specified and no default model configured. Please specify a model with --model or configure a default model.`);let r=this.#e.getProvidersForModel(t);if(r.length===0)throw new n(t,this.#e.getAllModels());let i=r[0],a=this.#i(i);this.#r.debug(`Streaming with model: ${t} via provider: ${i.name}`);let o={...e,model:t};return await a.stream(o)}getRegistry(){return this.#e}clearClients(){this.#t.clear()}async reloadConfig(){await this.#e.reload(),this.clearClients()}};async function c(e){let{XlingAdapter:t}=await import(`./services/settings/adapters/xling.js`),n=new t;return new s(n.readConfig(n.resolvePath(`user`)),e)}var l=class{#e;constructor(e){this.#e=e}async generate(e){let t=u(e);return{content:await d(this.#e,t,e.abortSignal),model:e.model||this.#e,provider:`cli:${this.#e}`}}async stream(e){let t=u(e);return{textStream:f(this.#e,t,e.abortSignal)}}};function u(e){return e.messages&&e.messages.length>0?e.messages.map(e=>`${e.role.toUpperCase()}: ${e.content}`).join(`

`):[e.system,e.prompt].filter(Boolean).join(`

`)}function d(e,t,n){return new Promise((r,i)=>{let a=``,o=``,s=p(e,n);s.stdout.on(`data`,e=>{a+=e.toString()}),s.stderr.on(`data`,e=>{o+=e.toString()}),s.on(`error`,e=>i(e)),s.on(`close`,t=>{t===0?r(m(a)):i(Error(o||`cli:${e} exited with code ${t}`))}),s.stdin.write(t),s.stdin.end()})}async function*f(e,t,n){let r=p(e,n),i=``;r.stdout.on(`data`,e=>{i+=e.toString()});let a=new Promise((e,t)=>{r.on(`error`,t),r.on(`close`,()=>e())});r.stdin.write(t),r.stdin.end(),await a;let o=m(i);o.length>0&&(yield o)}function p(e,t){let n=i(a.resolve(process.cwd(),`dist/run.js`),[`p`,`--tool`,e],{stdio:[`pipe`,`pipe`,`pipe`],env:process.env});return t&&(t.aborted?n.kill():t.addEventListener(`abort`,()=>n.kill(`SIGTERM`),{once:!0})),n}function m(e){return e.split(/\r?\n/).filter(e=>e.trim().length>0&&!e.startsWith(`[backend:`)&&!e.startsWith(`yolo on`)).join(`
`).trim()}export{c as n,s as t};