import{c as e,zi as t}from"./model-selection-BDkm-Fer.js";function n(e){if(e.startsWith(`{`))try{let t=JSON.parse(e);if(typeof t.token==`string`&&t.token)return{headers:{Authorization:`Bearer ${t.token}`,"Content-Type":`application/json`}}}catch{}return{headers:{"x-goog-api-key":e,"Content-Type":`application/json`}}}const r=/[\s,;]+/g,i=`OPENCLAW_LIVE_GEMINI_KEY`,a={google:`GEMINI`,"google-vertex":`GEMINI`},o={anthropic:{liveSingle:`OPENCLAW_LIVE_ANTHROPIC_KEY`,listVar:`OPENCLAW_LIVE_ANTHROPIC_KEYS`,primaryVar:`ANTHROPIC_API_KEY`,prefixedVar:`ANTHROPIC_API_KEY_`},google:{liveSingle:i,listVar:`GEMINI_API_KEYS`,primaryVar:`GEMINI_API_KEY`,prefixedVar:`GEMINI_API_KEY_`},"google-vertex":{liveSingle:i,listVar:`GEMINI_API_KEYS`,primaryVar:`GEMINI_API_KEY`,prefixedVar:`GEMINI_API_KEY_`},openai:{liveSingle:`OPENCLAW_LIVE_OPENAI_KEY`,listVar:`OPENAI_API_KEYS`,primaryVar:`OPENAI_API_KEY`,prefixedVar:`OPENAI_API_KEY_`}};function s(e){return e?e.split(r).map(e=>e.trim()).filter(Boolean):[]}function c(e){let t=[];for(let[n,r]of Object.entries(process.env)){if(!n.startsWith(e))continue;let i=r?.trim();i&&t.push(i)}return t}function l(t){let n=e(t),r=o[n],i=a[n]??n.toUpperCase().replace(/-/g,`_`),s=r?.liveSingle??`OPENCLAW_LIVE_${i}_KEY`,c=r?.listVar??`${i}_API_KEYS`,l=r?.primaryVar??`${i}_API_KEY`,u=r?.prefixedVar??`${i}_API_KEY_`;return n===`google`||n===`google-vertex`?{liveSingle:s,listVar:c,primaryVar:l,prefixedVar:u,fallbackVars:[`GOOGLE_API_KEY`]}:{liveSingle:s,listVar:c,primaryVar:l,prefixedVar:u,fallbackVars:[]}}function u(e){let t=l(e),n=t.liveSingle?process.env[t.liveSingle]?.trim():void 0;if(n)return[n];let r=s(t.listVar?process.env[t.listVar]:void 0),i=t.primaryVar?process.env[t.primaryVar]?.trim():void 0,a=t.prefixedVar?c(t.prefixedVar):[],o=t.fallbackVars.map(e=>process.env[e]?.trim()).filter(Boolean),u=new Set,d=e=>{e&&(u.has(e)||u.add(e))};for(let e of r)d(e);d(i);for(let e of a)d(e);for(let e of o)d(e);return Array.from(u)}function d(e){let t=e.toLowerCase();return!!(t.includes(`rate_limit`)||t.includes(`rate limit`)||t.includes(`429`)||t.includes(`quota exceeded`)||t.includes(`quota_exceeded`)||t.includes(`resource exhausted`)||t.includes(`resource_exhausted`)||t.includes(`too many requests`))}function f(e){let t=new Set,n=[];for(let r of e){let e=r.trim();!e||t.has(e)||(t.add(e),n.push(e))}return n}function p(e){let{primaryApiKey:t,provider:n}=e;return f([t?.trim()??``,...u(n)])}async function m(e){let n=f(e.apiKeys);if(n.length===0)throw Error(`No API keys configured for provider "${e.provider}".`);let r;for(let i=0;i<n.length;i+=1){let a=n[i];try{return await e.execute(a)}catch(o){r=o;let s=t(o);if(!(e.shouldRetry?e.shouldRetry({apiKey:a,error:o,attempt:i,message:s}):d(s))||i+1>=n.length)break;e.onRetry?.({apiKey:a,error:o,attempt:i,message:s})}}throw r===void 0?Error(`Failed to run API request for ${e.provider}.`):r}export{m as n,n as r,p as t};
