import{n as e}from"./chunk-DR8-3Aex.js";import{U as t,l as n,p as r,z as i}from"./debug-otxXY3j-.js";import{o as a,u as o}from"./proxy-CF7ZDxaW.js";import{G_ as s,K_ as c,Qo as l,Uo as u,W_ as d,Xo as f,dD as p,mo as m,q_ as h,st as g,uD as _,ut as v}from"./loadAgentsDir-C_wFhytF.js";import{G as y,H as b,K as x,P as S,U as C,W as w,q as T}from"./rcDebugLog-C42A0pX1.js";import{n as E,r as D}from"./SSETransport-D3e5KNL3.js";import{randomUUID as O}from"crypto";function k(){return(process.env.GEMINI_BASE_URL||M).replace(/\/+$/,``)}function A(e){let t=e.replace(/^\/+/,``);return t.startsWith(`models/`)?t:`models/${t}`}async function*j(e){let t=await(e.fetchOverride??fetch)(`${k()}/${A(e.model)}:streamGenerateContent?alt=sse`,{method:`POST`,headers:{"Content-Type":`application/json`,"x-goog-api-key":process.env.GEMINI_API_KEY||``},body:JSON.stringify(e.body),signal:e.signal,...a({forAnthropicAPI:!1})});if(!t.ok){let e=await t.text();throw Error(`Gemini API request failed (${t.status} ${t.statusText}): ${e||`empty response body`}`)}if(!t.body)throw Error(`Gemini API returned no response body`);let n=t.body.getReader(),r=new TextDecoder,o=``;try{for(;;){let{done:e,value:t}=await n.read();if(e)break;o+=r.decode(t,N);let{frames:a,remaining:s}=D(o);o=s;for(let e of a)if(!(!e.data||e.data===`[DONE]`))try{yield JSON.parse(e.data)}catch(e){throw Error(`Failed to parse Gemini SSE payload: ${i(e)}`)}}o+=r.decode();let{frames:e}=D(o);for(let t of e)if(!(!t.data||t.data===`[DONE]`))try{yield JSON.parse(t.data)}catch(e){throw Error(`Failed to parse trailing Gemini SSE payload: ${i(e)}`)}}finally{n.releaseLock()}}var M,N,P=e((()=>{E(),t(),o(),M=`https://generativelanguage.googleapis.com/v1beta`,N={stream:!0}}));async function*F(e,t,n,i,a,o){try{let u=T(a.model),m=l(e,n),h=await Promise.all(n.map(e=>v(e,{getToolPermissionContext:a.getToolPermissionContext,tools:n,agents:a.agents,allowedAgentTypes:a.allowedAgentTypes,model:a.model}))),g=h.filter(e=>{let t=e;return t.type!==`advisor_20260301`&&t.type!==`computer_20250124`}),{contents:_,systemInstruction:S}=y(m,t),E=w(g),D=C(a.toolChoice),k=j({model:u,signal:i,fetchOverride:a.fetchOverride,body:{contents:_,...S&&{systemInstruction:S},...E.length>0&&{tools:E},...D&&{toolConfig:{functionCallingConfig:D}},generationConfig:{...a.temperatureOverride!==void 0&&{temperature:a.temperatureOverride},...o.type!==`disabled`&&{thinkingConfig:{includeThoughts:!0,...o.type===`enabled`&&{thinkingBudget:o.budgetTokens}}}}}});r(`[Gemini] Calling model=${u}, messages=${_.length}, tools=${E.length}`);let A=b(k,u),M={},N=[],P=null,F=0,I=Date.now();for await(let e of A){switch(e.type){case`message_start`:P=e.message,F=Date.now()-I;break;case`content_block_start`:{let t=e.index,n=e.content_block;n.type===`tool_use`?M[t]={...n,input:``}:n.type===`text`?M[t]={...n,text:``}:n.type===`thinking`?M[t]={...n,thinking:``,signature:``}:M[t]={...n};break}case`content_block_delta`:{let t=e.index,n=e.delta,r=M[t];if(!r)break;n.type===`text_delta`?r.text=(r.text||``)+n.text:n.type===`input_json_delta`?r.input=(r.input||``)+n.partial_json:n.type===`thinking_delta`?r.thinking=(r.thinking||``)+n.thinking:n.type===`signature_delta`&&(r.type===`thinking`?r.signature=n.signature:r[x]=n.signature);break}case`content_block_stop`:{let t=M[e.index];if(!t||!P)break;let r={message:{...P,content:f([t],n,a.agentId)},requestId:void 0,type:`assistant`,uuid:O(),timestamp:new Date().toISOString()};N.push(r),yield r;break}case`message_delta`:case`message_stop`:break}yield{type:`stream_event`,event:e,...e.type===`message_start`?{ttftMs:F}:void 0}}p(a.langfuseTrace??null,{model:u,provider:`gemini`,input:d(m,t),output:s(N),usage:{input_tokens:0,output_tokens:0},startTime:new Date(I),endTime:new Date,completionStartTime:F>0?new Date(I+F):void 0,tools:c(h),thinking:o.type===`disabled`?void 0:{type:o.type,...o.type===`enabled`&&{budgetTokens:o.budgetTokens}}})}catch(e){let t=e instanceof Error?e.message:String(e);r(`[Gemini] Error: ${t}`,{level:`error`}),yield m({content:`API Error: ${t}`,apiError:`api_error`,error:e instanceof Error?e:Error(String(e))})}}e((()=>{g(),n(),u(),_(),h(),P(),S()}))();export{F as queryModelGemini};