@juspay/neurolink 11.14.0 → 11.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
## [11.
|
|
1
|
+
## [11.15.0](https://github.com/juspay/neurolink/compare/v11.14.0...v11.15.0) (2026-08-21)
|
|
2
2
|
|
|
3
3
|
### Features
|
|
4
4
|
|
|
5
|
-
- **(
|
|
5
|
+
- **(core):** let a Gemini adapter supply its own step collector ([d6a303f](https://github.com/juspay/neurolink/commit/d6a303f4d30a4069efcf57edffc5e9f535d32d53))
|
|
6
6
|
|
|
7
7
|
## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
|
|
8
8
|
|
|
@@ -1067,7 +1067,7 @@ Based on this analysis, provide your response.`:`Here is a video/image analysis
|
|
|
1067
1067
|
${s}
|
|
1068
1068
|
|
|
1069
1069
|
Based on this analysis, provide your response.`;h.debug("[VideoAnalysis] Formatting via Claude",{userTextLength:i.length,analysisLength:s.length});const u=await yT({model:n,system:t.systemPrompt,messages:[{role:"user",content:c}],maxOutputTokens:t.maxTokens||8192,temperature:.3,abortSignal:t.abortSignal,experimental_telemetry:this.telemetryHandler?.getTelemetryConfig(t,"generate")});a=u.text,l=mv(u.totalUsage??u.usage),h.debug("[VideoAnalysis] Claude formatting complete",{formattedLength:a.length,usage:l})}catch(c){h.warn("[VideoAnalysis] Claude formatting failed, using raw Gemini output",{error:c instanceof Error?c.message:String(c)})}return this.enhanceResult({content:a,provider:t.provider??this.providerName,model:this.modelName,usage:l},t,o)}async executeStandardGenerateFlow(t,r,n,o,s){const i=t.timeout??18e4,a=Bl(i,this.providerName,"generate"),l=CI(t.abortSignal,a?.controller.signal),c=l?{...t,abortSignal:l}:t;let u;try{u=await this.executeGeneration(n,o,s,c)}finally{a?.cleanup()}this.analyzeAIResponse(u),this.logGenerationComplete(u);const d=Date.now()-r,{toolsUsed:m,toolExecutions:f}=this.extractToolInformation(u),g=$1(t,f);let y=this.formatEnhancedResult(u,s,m,g,t);return await this.recordPerformanceMetrics(y.usage,d),y=await this.synthesizeAIResponseIfNeeded(y,t),await this.enhanceResult(y,t,r)}async synthesizeAIResponseIfNeeded(t,r){if(!r.tts?.enabled||!r.tts?.useAiResponse)return t;const n=r.tts,o=t.content,s=n.provider??r.provider??this.providerName;if(!o||!s)return h.warn("TTS synthesis skipped despite being enabled",{provider:this.providerName,hasAiResponse:!!o,aiResponseLength:o?.length??0,hasProvider:!!s,ttsConfig:{enabled:r.tts?.enabled,useAiResponse:r.tts?.useAiResponse},reason:o?"Provider is missing":"AI response is empty or undefined"}),{...t,ttsMetadata:{attempted:!1,success:!1}};const i=Date.now(),a=this.getTimeout(r);try{const l=await pR(()=>rm.synthesize(o,s,n),a,`TTS synthesis timed out after ${a}ms for provider "${s}"`);return{...t,audio:l,ttsMetadata:{attempted:!0,success:!0,latency:Date.now()-i}}}catch(l){const c=Date.now()-i,u=this.getTTSErrorDetails(l);return this.telemetryHandler.recordTTSFailure(s,u,c),h.error("TTS synthesis failed in Mode 2 (AI response synthesis):",l),{...t,ttsMetadata:{attempted:!0,success:!1,error:u,latency:c}}}}getTTSErrorDetails(t){return t instanceof Oc?{code:Kt.SYNTHESIS_FAILED,message:t.message,retriable:!0}:t instanceof $e?{code:t.code,message:t.message,retriable:t.retriable}:{code:Kt.SYNTHESIS_FAILED,message:t instanceof Error?t.message:String(t)}}async generateText(t){const r=t.prompt||t.input?.text;if(!r||typeof r!="string"||r.trim()==="")throw new Error("GenerateText options must include prompt or input.text as a non-empty string");const n=await this.generate(t);if(!n)throw new Error("Generation failed: No result returned");return{content:n.content||"",provider:n.provider||this.providerName,model:n.model||this.modelName,usage:n.usage||{input:0,output:0,total:0},responseTime:0,toolsUsed:n.toolsUsed||[],toolExecutions:n.toolExecutions?.map(o=>({toolName:o.toolName,executionTime:o.durationMs,success:!o.isError})),enhancedWithTools:!!(n.toolsUsed&&n.toolsUsed.length>0),analytics:n.analytics,evaluation:n.evaluation,audio:n.audio,reasoning:n.reasoning,reasoningTokens:n.reasoningTokens}}async embed(t,r){throw h.warn(`embed() called on ${this.providerName} which does not have a native implementation`,{textLength:t.length}),new Error(`Embedding generation is not supported by the ${this.providerName} provider. Supported providers: openai, vertex/google, bedrock, cohere, voyage, jina. Use an embedding model like text-embedding-3-small (OpenAI), text-embedding-004 (Vertex), embed-english-v3.0 (Cohere), voyage-3 (Voyage), jina-embeddings-v3 (Jina), or amazon.titan-embed-text-v2:0 (Bedrock).`)}async embedMany(t,r){throw h.warn(`embedMany() called on ${this.providerName} which does not have a native implementation`,{count:t.length}),new Error(`Batch embedding generation is not supported by the ${this.providerName} provider. Supported providers: openai, googleAiStudio, vertex/google, bedrock, cohere, voyage, jina. Use an embedding model like text-embedding-3-small (OpenAI), gemini-embedding-001 (Google AI), text-embedding-004 (Vertex), embed-english-v3.0 (Cohere), voyage-3 (Voyage), jina-embeddings-v3 (Jina), or amazon.titan-embed-text-v2:0 (Bedrock).`)}getDefaultEmbeddingModel(){}getToolCallRepairFn(t){if(!t?.disableToolCallRepair)return(async(...r)=>{const{createToolCallRepair:n}=await Promise.resolve().then(()=>(UH(),$H));return n()(...r)})}async executeStream(t,r){if(!this.doStream)throw new $e({code:Xe.INVALID_CONFIGURATION,message:`${this.providerName} cannot stream: it neither implements doStream() nor overrides executeStream()`,category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}});const n=Date.now(),{stream:o,finishReason:s,usage:i,warnings:a}=await this.doStream(t);a?.length&&h.warn(`[${this.providerName}] doStream reported warnings`,{provider:this.providerName,count:a.length});const l={startTime:n,streamId:`${this.providerName}-${n}`},c=(async()=>{const[u,d]=await Promise.all([s,i]);return l.finishReason=u,l.rawFinishReason=u,hv(this.providerName,this.modelName||this.getDefaultModel(),{usage:{input:d.inputTokens,output:d.outputTokens,total:d.inputTokens+d.outputTokens},stopReason:u},Date.now()-n,{streamingMode:!0})})();return{stream:o,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:c,metadata:l}}async getAISDKModelWithMiddleware(t={}){const r=await this.getAISDKModel();h.debug(`Retrieved base model for ${this.providerName}`,{provider:this.providerName,model:this.modelName,hasMiddlewareConfig:!!this.middlewareOptions,timestamp:Date.now()});const n=this.extractMiddlewareOptions(t);if(h.debug("Middleware extraction result",{provider:this.providerName,model:this.modelName,middlewareOptions:n}),!n)return r;try{h.debug(`Applying middleware to ${this.providerName} model`,{provider:this.providerName,model:this.modelName,middlewareOptions:n});const o=new _8(n),s=o.createContext(this.providerName,this.modelName,t,{sessionId:this.sessionId,userId:this.userId}),i=o.applyMiddleware(r,s,n);return h.debug(`Applied middleware to ${this.providerName} model`,{provider:this.providerName,model:this.modelName,hasMiddleware:!0}),i}catch(o){return h.warn(`Failed to apply middleware to ${this.providerName}, using base model`,{error:o instanceof Error?o.message:String(o)}),r}}extractMiddlewareOptions(t){return this.utilities.extractMiddlewareOptions(t)}isZodSchema(t){return this.utilities.isZodSchema(t)}async convertToolResult(t){return this.utilities.convertToolResult(t)}fixSchemaForOpenAIStrictMode(t){return this.utilities.fixSchemaForOpenAIStrictMode(t)}async getAllTools(){return this.toolsManager.getAllTools()}async calculateActualCost(t){return this.telemetryHandler.calculateActualCost(t)}createPermissiveZodSchema(){return this.utilities.createPermissiveZodSchema()}setSessionContext(t,r){this.sessionId=t,this.userId=r,this.toolsManager.setSessionContext(t,r)}handleProviderError(t){if(Ur(t))return t instanceof Error?t:new DOMException("The operation was aborted","AbortError");const r=this.formatProviderError(t);if(t&&typeof t=="object"&&r!==t){const n=t,o=r,s=sR(t);if(s!==void 0&&o.statusCode===void 0&&(o.statusCode=s),typeof n.isRetryable=="boolean"&&o.isRetryable===void 0&&(o.isRetryable=n.isRetryable),o.retryAfterMs===void 0){const i=ESe(t);i!==void 0&&(o.retryAfterMs=i)}}Tb(t)&&b1(r);try{const n=Tt.getSpan(Tr.active());if(n){let o="provider_error";const s=r?.constructor?.name??"";s==="RateLimitError"?o="rate_limit":s==="AuthenticationError"?o="auth_failure":s==="NetworkError"?o="network":s==="InvalidModelError"?o="invalid_model":s==="TimeoutError"&&(o="timeout"),n.setAttribute("error.type",o),r instanceof Error&&n.setAttribute("error.message",r.message.substring(0,500))}}catch{}return r}async executeImageGeneration(t){throw new Error(`Image generation is not supported by the ${this.providerName} provider or the selected model.`)}async executeWithTimeout(t,r){const n=this.getTimeout(r),o=Bl(n,this.providerName,r.operationType||"generate");try{return o?await Promise.race([t(),new Promise((s,i)=>{o.controller.signal.addEventListener("abort",()=>{i(new pd(`${this.providerName} operation timed out`,o.timeoutMs,this.providerName,r.operationType||"generate"))})})]):await t()}finally{o?.cleanup()}}validateStreamOptions(t){this.streamHandler.validateStreamOptions(t)}createTextStream(t,r){return this.streamHandler.createTextStream(t,r)}createStreamResult(t,r={}){return this.streamHandler.createStreamResult(t,r)}async createStreamAnalytics(t,r,n){return this.streamHandler.createStreamAnalytics(t,r,n)}handleCommonErrors(t){return this.utilities.handleCommonErrors(t)}setupToolExecutor(t,r){this.toolsManager.setupToolExecutor(t,r)}normalizeTextOptions(t){return this.utilities.normalizeTextOptions(t)}normalizeStreamOptions(t){return this.utilities.normalizeStreamOptions(t)}async enhanceResult(t,r,n){const o=Date.now()-n,s=t.imageOutput;let i={...t};if(r.enableAnalytics)try{const a=await this.createAnalytics(t,o,r);i={...i,analytics:a,imageOutput:s}}catch(a){h.warn(`Analytics creation failed for ${this.providerName}:`,a)}if(r.enableEvaluation)try{const a=await this.createEvaluation(t,r);i={...i,evaluation:a,imageOutput:s}}catch(a){h.warn(`Evaluation creation failed for ${this.providerName}:`,a)}return s&&(i.imageOutput=s),i}async handleVideoGeneration(t,r){const{VideoProcessor:n,VideoError:o,VIDEO_ERROR_CODES:s}=await Promise.resolve().then(()=>(Rf(),sW)),{validateVideoGenerationInput:i,validateImageForVideo:a,validateDirectorModeInput:l}=await Promise.resolve().then(()=>(Sf(),wmt)),{ErrorFactory:c}=await Promise.resolve().then(()=>(ct(),sT)),u={input:t.input||{text:t.prompt||""},output:t.output,provider:t.provider,model:t.model};if(u.input?.segments&&Array.isArray(u.input.segments)&&u.input.segments.length>0){const I=u.input.segments,A=l(u);if(!A.isValid)throw c.invalidParameters("director-mode",new Error(A.errors.map(J=>J.message).join("; ")),{errors:A.errors});if(A.warnings.length>0)for(const J of A.warnings)h.warn(`Director Mode warning: ${J}`);const{executeDirectorPipeline:M,DIRECTOR_PIPELINE_TIMEOUT_MS:O}=await Promise.resolve().then(()=>(IEr(),Hft)),N=t.timeout??O,D=await this.executeWithTimeout(()=>M(I,u.output?.video??{},u.output?.director??{},t.region),{timeout:N,operationType:"generate"}),F=u.input.segments.map(J=>J.prompt).join(" \u2192 "),U=D.metadata?.segmentCount??u.input.segments.length,$=D.metadata?.transitionCount??Math.max(0,U-1),B=D.metadata?.duration??0,j={content:`${F} \u2014 duration: ${B}s, segments: ${U}, transitions: ${$}`,provider:"vertex",model:t.model||"veo-3.1-generate-001",usage:{input:0,output:0,total:0},video:D};return await this.enhanceResult(j,t,r)}const d=i(u);if(!d.isValid)throw c.invalidParameters("video-generation",new Error(d.errors.map(I=>I.message).join("; ")),{errors:d.errors});if(d.warnings.length>0)for(const I of d.warnings)h.warn(`Video generation warning: ${I}`);const m=t.input?.images?.[0];if(!m)throw new o({code:s.INVALID_INPUT,message:"Video generation requires an input image. Provide via input.images array.",retriable:!1,context:{field:"input.images"}});const f=15e3;let g;if(typeof m=="string")if(m.startsWith("http://")||m.startsWith("https://")){h.debug("Fetching image from URL for video generation",{url:m.substring(0,100)});let I;try{I=await this.executeWithTimeout(()=>fetch(m),{timeout:f,operationType:"generate"})}catch(A){throw new o({code:s.INVALID_INPUT,message:`Failed to fetch image from URL: ${A instanceof Error?A.message:"Request timed out"}`,retriable:!0,context:{url:m,timeout:f},originalError:A instanceof Error?A:void 0})}if(!I.ok)throw new o({code:s.INVALID_INPUT,message:`Failed to fetch image from URL: ${I.status} ${I.statusText}`,retriable:I.status>=500,context:{url:m,status:I.status}});g=Buffer.from(await I.arrayBuffer())}else{h.debug("Reading image from path for video generation",{path:m});const I=await Promise.resolve().then(()=>(Fs(),vv));try{g=await this.executeWithTimeout(()=>I.readFile(m),{timeout:f,operationType:"generate"})}catch(A){throw new o({code:s.INVALID_INPUT,message:`Failed to read image file: ${A instanceof Error?A.message:String(A)}`,retriable:!1,context:{path:m,timeout:f},originalError:A instanceof Error?A:void 0})}}else if(Buffer.isBuffer(m))g=m;else if(typeof m=="object"&&"data"in m){const I=m.data;if(typeof I=="string")g=Buffer.from(I,"base64");else if(Buffer.isBuffer(I))g=I;else throw new o({code:s.INVALID_INPUT,message:"ImageWithAltText.data must be a base64 string or Buffer.",retriable:!1,context:{field:"input.images[0].data",type:typeof I}})}else throw new o({code:s.INVALID_INPUT,message:"Invalid image input type. Provide Buffer, path string, URL, or ImageWithAltText.",retriable:!1,context:{field:"input.images[0]",type:typeof m}});const y=a(g);if(y)throw c.invalidParameters("video-generation",new Error(y.message),{field:"input.images[0]",validation:y});const v=t.prompt||t.input?.text||"",w=t.output?.video?.provider??"vertex";if(!n.supports(w))throw new o({code:s.PROVIDER_NOT_SUPPORTED,message:`Video provider "${w}" is not registered. Available: ${n.listProviders().join(", ")}`,retriable:!1,context:{provider:w,available:n.listProviders()}});const T=t.output?.video?.model??t.model??(w==="vertex"?"veo-3.1-generate-001":void 0);h.info("Starting video generation",{provider:w,...T?{model:T}:{},promptLength:v.length,imageSize:g.length,resolution:t.output?.video?.resolution||"720p",duration:t.output?.video?.length||6});const x=t.timeout??6e5,k=await this.executeWithTimeout(()=>n.generate(w,g,v,t.output?.video??{},t.region),{timeout:x,operationType:"generate"}),R=k.metadata?.model??T??(w==="vertex"?"veo-3.1-generate-001":"unknown");h.info("Video generation complete",{provider:w,model:R,videoSize:k.data.length,duration:k.metadata?.duration,processingTime:k.metadata?.processingTime});const P={content:v,provider:w,model:R,usage:{input:0,output:0,total:0},video:k};return await this.enhanceResult(P,t,r)}async createAnalytics(t,r,n){return this.telemetryHandler.createAnalytics(t,r,n.context)}async createEvaluation(t,r){return this.telemetryHandler.createEvaluation(t,r)}validateOptions(t){this.utilities.validateOptions(t)}getProviderInfo(){return this.utilities.getProviderInfo()}getTimeout(t){return this.utilities.getTimeout(t)}async handleToolExecutionStorage(t,r,n,o){return this.telemetryHandler.handleToolExecutionStorage(t,r,n,o)}static chunkPrompt(t,r=9e5,n=100){if(t.length<=r)return[t];const o=[];let s=0;for(;s<t.length;){const i=Math.min(s+r,t.length);if(o.push(t.slice(s,i)),i>=t.length)break;const a=i-n;a<=s?s=i:s=Math.max(a,0)}return o}}}});function aW(e){if(!(!e?.enabled&&!e?.thinkingLevel))return{includeThoughts:!0,thinkingLevel:e.thinkingLevel??tgt}}var tgt,rgt=C({"src/lib/utils/thinkingConfig.ts"(){"use strict";tgt="high"}});function REr(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r).sort().reduce((n,o)=>(n[o]=r[o],n),{}):r)}function PEr(e){if(dgt.test(e))return e;let t=e.replace(/[^A-Za-z0-9_.:-]/g,"_");return/^[A-Za-z_]/.test(t)||(t=`_${t}`),t.length>NM&&(t=t.slice(0,NM)),t}function MEr(e,t){if(!t(e))return e;let r=2;for(;;){const n=`_${r}`,s=`${e.slice(0,NM-n.length)}${n}`;if(!t(s))return s;r++}}function _m(e){if(Array.isArray(e.anyOf)||Array.isArray(e.oneOf)){const n=e.anyOf?"anyOf":"oneOf",o=e[n],s=o.filter(c=>c.type!=="null"&&c.type!=="undefined");if(s.length===1){const c=_m({...s[0]});return c.nullable=!0,e.description&&(c.description=e.description),c}const i=s.map(c=>c.type||"unknown").join(" | "),a={type:"string"},l=e.description?`${e.description} (accepts: ${i})`:`Value as string (accepts: ${i})`;return a.description=l,o.some(c=>c.type==="null")&&(a.nullable=!0),a}const t={};for(const[n,o]of Object.entries(e))if(!(n==="$schema"||n==="additionalProperties"||n==="default"))if(n==="properties"&&o&&typeof o=="object"){const s={};for(const[i,a]of Object.entries(o))a&&typeof a=="object"?s[i]=_m(a):s[i]=a;t[n]=s}else n==="items"&&o&&typeof o=="object"?Array.isArray(o)?t[n]=o.map(s=>s&&typeof s=="object"?_m(s):s):t[n]=_m(o):t[n]=o;Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(n=>_m(n))),t.not&&typeof t.not=="object"&&(t.not=_m(t.not));for(const n of["if","then","else"])t[n]&&typeof t[n]=="object"&&(t[n]=_m(t[n]));typeof t.exclusiveMinimum=="boolean"&&(t.exclusiveMinimum===!0&&typeof t.minimum=="number"?(t.exclusiveMinimum=t.minimum,delete t.minimum):delete t.exclusiveMinimum),typeof t.exclusiveMaximum=="boolean"&&(t.exclusiveMaximum===!0&&typeof t.maximum=="number"?(t.exclusiveMaximum=t.maximum,delete t.maximum):delete t.exclusiveMaximum);const r=2147483647;return typeof t.maximum=="number"&&t.maximum>r&&delete t.maximum,typeof t.minimum=="number"&&t.minimum<-r&&delete t.minimum,t}function ngt(e,t){const r=[],n=new jv,o=[],s=[],i=new Set(t??[]),a=new Map;for(const[l,c]of Object.entries(e))try{const u=PEr(l),d=MEr(u,g=>i.has(g));a.set(d,l),d!==l&&s.push({from:l,to:d});const m={name:d,description:c.description||`Tool: ${d}`},f=c;if(f.parameters||c.inputSchema){let g;const y=f.parameters||c.inputSchema;z8(y)?g=$s(y,"openApi3"):typeof y=="object"?g=y:g={type:"object",properties:{}},g.jsonSchema&&typeof g.jsonSchema=="object"&&!g.type&&(g=g.jsonSchema),m.parametersJsonSchema=_m(ln(g))}r.push(m),i.add(d),c.execute&&n.set(m.name,c.execute)}catch(u){o.push(l),h.error(`[buildNativeToolDeclarations] Failed to convert tool "${l}":`,u)}return o.length>0&&h.warn(`[buildNativeToolDeclarations] ${o.length} tool(s) skipped due to schema errors: ${o.join(", ")}`),s.length>0&&h.warn(`[buildNativeToolDeclarations] ${s.length} tool name(s) sanitized for Google's function-name regex: ${s.map(l=>`"${l.from}" -> "${l.to}"`).join(", ")}`),{toolsConfig:[{functionDeclarations:r}],executeMap:n,originalNameMap:a}}function DEr(e,t){if(!e)return!1;const r=new Set(t.originalNameMap.values()),n=Object.entries(e).filter(([s])=>!r.has(s));if(n.length===0)return!1;const o=ngt(Object.fromEntries(n),new Set(t.originalNameMap.keys()));t.toolsConfig[0].functionDeclarations.push(...o.toolsConfig[0].functionDeclarations);for(const[s,i]of o.originalNameMap)t.originalNameMap.set(s,i);for(const[s,i]of o.executeMap)t.executeMap.set(s,i);return h.info(`[buildNativeToolDeclarations] ${n.length} tool(s) hydrated mid-turn via discovery: ${n.map(([s])=>s).join(", ")}`),!0}function ogt(e,t){const r=Bc("google-ai",e.model,{temperature:e.temperature??1},"googleAiStudio.buildNativeConfig"),n={...r.temperature!==void 0&&{temperature:r.temperature},maxOutputTokens:e.maxTokens};t&&(n.tools=t),e.systemPrompt&&(n.systemInstruction=e.systemPrompt);const o=aW(e.thinkingConfig);return o&&(n.thinkingConfig=o),t||((e.responseSchema||e.wantsJsonOutput)&&(n.responseMimeType="application/json"),e.responseSchema&&(n.responseSchema=e.responseSchema)),n}function sgt(e){const t=e||Zs;return Number.isFinite(t)&&t>0?Math.min(Math.floor(t),uW):Math.min(Zs,uW)}function lW(e){switch(e){case"MAX_TOKENS":return"length";case"MALFORMED_FUNCTION_CALL":case"UNEXPECTED_TOOL_CALL":return"error";case"SAFETY":case"RECITATION":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":case"IMAGE_SAFETY":return"content-filter";default:return"stop"}}function igt(e,t){return t?e?`${e}
|
|
1070
|
-
${t}`:t:e}async function OEr(e,t){const r=[],n=[];let o=0,s=0,i=0,a=0,l;for await(const c of e){const u=c,m=u.candidates?.[0],f=m?.finishReason;typeof f=="string"&&(l=f);const g=m?.content;if(g&&Array.isArray(g.parts))for(const v of g.parts)r.push(v),typeof v.text=="string"&&v.text.length>0&&t.push({content:v.text});c.functionCalls&&n.push(...c.functionCalls);const y=u.usageMetadata;y&&(o=Math.max(o,y.promptTokenCount||0),s=Math.max(s,y.candidatesTokenCount||0),i=Math.max(i,y.cachedContentTokenCount||0),a=Math.max(a,y.thoughtsTokenCount||0))}return{rawResponseParts:r,stepFunctionCalls:n,finishReason:l,inputTokens:o,outputTokens:s,cacheReadTokens:i,reasoningTokens:a}}function RM(e){for(let t=e.length-1;t>=0;t--){const r=e[t];if(r!=null&&typeof r=="object"&&"thoughtSignature"in r&&typeof r.thoughtSignature=="string")return r.thoughtSignature}}function NEr(e){return e.filter(t=>typeof t.text=="string").map(t=>t.text).join("")}function agt(e,t,r,n,o){return t>=r&&!n?(h.warn(`${e} Tool call loop terminated after reaching maxSteps (${r}). Model was still calling tools. Using accumulated text from last step.`),o||wm(r,0)):n}function rc(e){if(!e)return!1;const t=e;return t.name==="AbortError"||typeof t.message=="string"&&/abort/i.test(t.message)||typeof DOMException<"u"&&e instanceof DOMException&&t.code===20}function wm(e,t){return`${t>0?`I gathered information across ${t} tool call${t===1?"":"s"} but `:"I "}reached the ${e}-step limit for a single turn before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function nc(e){return`${e>0?`I gathered information across ${e} tool call${e===1?"":"s"} but `:"I "}had to stop because the gathered material filled this turn's context window before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function lgt(e){const t=Math.max(0,Math.round(e/1e3)),r=Math.floor(t/60),n=t%60;return r>0?`${r}m ${n}s`:`${n}s`}function LEr(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop after ${lgt(e)} \u2014 this turn hit its processing time limit.${r} ask me to continue and I'll pick up from there.`}function $Er(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop because this turn made no progress for ${lgt(e)} \u2014 a tool or model call appears to be stuck.${r} ask me to continue and I'll pick up from there.`}function FEr(e){return`This turn was stopped before I could finish.${e>0?` I completed ${e} tool call${e===1?"":"s"} before stopping.`:""}`}function PM(e){return"NOTE: processing time for this turn is nearly up. Consolidate what you have and "+(e?"call final_result with your best answer now.":"provide your final answer now.")}function MM(e){return e.timedOut?"time-limit":e.stalled?"stalled":e.wasAborted?"aborted":e.contextCappedWithoutAnswer?"context-cap":e.cappedWithoutAnswer?"step-cap":e.finishReason==="error"?"provider-error":"completed"}function DM(e){const t=Date.now(),r=u=>u!==void 0&&Number.isFinite(u)&&u>0,n=r(e.turnTimeoutMs)?e.turnTimeoutMs:r(e.defaultTurnTimeoutMs)?e.defaultTurnTimeoutMs:void 0,o=r(e.turnTimeoutMs)?e.wrapupTimeLeadMs??JR:void 0;let s=!1,i=!1,a=t,l,c;if(n!==void 0&&(l=setTimeout(()=>{s=!0,e.onDeadline("timeout")},n),l.unref?.()),r(e.stallTimeoutMs)){const u=e.stallTimeoutMs,d=Math.min(Math.max(1e3,Math.floor(u/4)),15e3);c=setInterval(()=>{!i&&!s&&Date.now()-a>=u&&(i=!0,e.onDeadline("stall"))},d),c.unref?.()}return{get timedOut(){return s},get stalled(){return i},get expired(){return s||i},get turnTimeoutMs(){return n},elapsedMs(){return Date.now()-t},noteProgress(){a=Date.now()},shouldNudgeWrapup(){if(n===void 0||o===void 0)return!1;const u=n-(Date.now()-t);return u>0&&u<=o},dispose(){l&&clearTimeout(l),c&&clearInterval(c)}}}function zv(e,t=VT){const r=Math.floor(e*t);let n=0,o=0;return{get thresholdTokens(){return r},get projectedNextPromptTokens(){return n+o},noteUsage(s,i){s>0&&(n=s,o=Math.max(0,i))},noteAppendedChars(s){s>0&&(o+=Math.ceil(s/4))},resetAfterReclaim(){n=0,o=0},shouldStop(){return n>0&&n+o>=r}}}function UEr(e,t,r){e.push({role:"model",parts:t.length>0?t:r.map(n=>({functionCall:n}))})}function cgt(e){const t=$s(e,"openApi3"),r=ln(t);return r.$schema&&delete r.$schema,bi(r)}function OM(e,t){if(!t||t.length===0)return;const r=new Map,n=[];let o=0;const s=a=>`${o}:${a??"undefined"}`,i=a=>{const l=s(a),c=r.get(l);if(c)return c;const u={type:"tool_step",callParts:[],resultParts:[]};return r.set(l,u),n.push(u),u};for(const a of t){if(a.role==="tool_call"){const u=i(a.metadata?.stepIndex),d={functionCall:{name:a.tool||"unknown",args:a.args||{}}};a.metadata?.thoughtSignature&&(d.thoughtSignature=a.metadata.thoughtSignature),u.callParts.push(d);continue}if(a.role==="tool_result"){const u=i(a.metadata?.stepIndex);let d;try{d=a.content!==void 0&&a.content!==null?{result:JSON.parse(a.content)}:{result:"success"}}catch{d={result:a.content??"success"}}u.resultParts.push({functionResponse:{name:a.tool||"unknown",response:d}});continue}const l=a.role==="assistant"?"model":a.role;if(l!=="user"&&l!=="model"||!a.content||a.content.trim().length===0)continue;o++;const c={text:a.content};a.metadata?.thoughtSignature&&(c.thoughtSignature=a.metadata.thoughtSignature),n.push({type:"regular",role:l,parts:[c]})}for(const a of n){if(a.type==="regular"){e.push({role:a.role,parts:a.parts});continue}if(a.callParts.length===0){a.resultParts.length>0&&h.debug("[GoogleNativeGemini3] Dropping orphan tool_result segment with no matching tool_call rows",{resultCount:a.resultParts.length});continue}e.push({role:"model",parts:a.callParts}),a.resultParts.length>0&&e.push({role:"user",parts:a.resultParts})}}async function cW(e,t,r="[GeminiNative]"){if(!(!t||t.length===0))for(const n of t){const o=n.filename.split(/[\\/]/).pop()??n.filename,s=o.lastIndexOf("."),i=s>0?o.slice(s):".bin",a=await emt(n.buffer,n.mimeType,i);if(l9(a.mimeType)){h.warn(`${r} Skipping native audio for ${o}: ${a.mimeType} is not accepted and could not be converted. The metadata summary was still included.`);continue}e.push({inlineData:{mimeType:a.mimeType,data:a.buffer.toString("base64")}}),h.debug(`${r} Added native audio part for ${o} (${a.mimeType})`)}}async function ugt(e,t,r="[GeminiNative]"){const o=[{text:typeof t=="string"?t:e?.text??""}];if(e?.pdfFiles&&e.pdfFiles.length>0){h.debug(`${r} Processing ${e.pdfFiles.length} PDF(s)`);for(const s of e.pdfFiles){let i;typeof s=="string"?Gi(s)?i=Hi(s):i=Buffer.from(s,"base64"):i=s,o.push({inlineData:{mimeType:"application/pdf",data:i.toString("base64")}})}}if(e?.images&&e.images.length>0){h.debug(`${r} Processing ${e.images.length} image(s)`);for(const s of e.images){const i=s&&typeof s=="object"&&!Buffer.isBuffer(s)?s.data:s;let a,l="image/jpeg";if(typeof i=="string")if(Gi(i)){a=Hi(i);const c=xv(i).toLowerCase();c===".png"?l="image/png":c===".gif"?l="image/gif":c===".webp"&&(l="image/webp")}else if(i.startsWith("data:")){const c=i.match(/^data:([^;]+);base64,(.+)$/);if(c)l=c[1],a=Buffer.from(c[2],"base64");else continue}else if(i.startsWith("http://")||i.startsWith("https://"))try{const c=await fetch(i);if(!c.ok){h.warn(`${r} Image fetch failed: ${c.status} ${c.statusText}, skipping`,{url:i});continue}const u=await c.arrayBuffer();a=Buffer.from(u);const d=c.headers.get("content-type");d&&d.startsWith("image/")&&(l=d.split(";")[0])}catch(c){h.warn(`${r} Image URL fetch threw, skipping: ${c instanceof Error?c.message:String(c)}`,{url:i});continue}else a=Buffer.from(i,"base64");else a=i;a&&o.push({inlineData:{mimeType:l,data:a.toString("base64")}})}}return await cW(o,e?.nativeAudioFiles,r),o}var jv,dgt,NM,uW,LM=C({"src/lib/providers/googleNativeGemini3/utils.ts"(){"use strict";ji(),Jo(),Gr(),Fo(),nmt(),W(),em(),qi(),rgt(),jv=class extends Map{resultCache=new Map;get(e){const t=super.get(e);if(!t)return t;const r=this.resultCache;return async(o,s)=>{const i=`${e}::${REr(o)}`;if(r.has(i))return h.warn(`[DedupExecuteMap] Tool "${e}" re-requested with identical arguments in the same turn \u2014 reusing the previous result instead of re-executing.`),r.get(i);const a=await t(o,s);return r.set(i,a),a}}},dgt=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/,NM=128,uW=100}});function pgt(e){const t=n=>e.declarations?.originalNameMap?.get(n)??n,r=n=>{const o=e.declarations?.originalNameMap;if(!o)return n;for(const[s,i]of o)if(i===n)return s;return n};return{providerLabel:e.providerLabel,maxSteps:e.maxSteps,...e.toolFailureBreaker?{toolFailureBreaker:e.toolFailureBreaker}:{},buildStepRequest(n,o){return e.declarations&&DEr(e.liveTools,e.declarations),{raw:e.buildRequest(n,o)}},...e.planReclaim?{planReclaim:(n,o)=>{const s=e.planReclaim?.(n,o);return s?{conversation:s}:void 0}}:{},...e.enableMalformedRetry&&e.buildMalformedRetryNote?{isMalformedStep:n=>n.toolCalls.length===0&&!n.text&&n.rawStopReason==="MALFORMED_FUNCTION_CALL",buildMalformedRetryNote:e.buildMalformedRetryNote}:{},resolveToolOnMiss:n=>{const s=e.liveTools?.[n]?.execute;if(s)return{execute:async(i,a)=>s(i,a)}},async executeStep(n,o,s){const i=await e.sendStep(n.raw,s),a=await OEr(i,{push:u=>o.push(u)});e.noteUsage?.(a.inputTokens,a.outputTokens);const l=NEr(a.rawResponseParts),c=a.stepFunctionCalls.map((u,d)=>({id:`${e.providerLabel}_${d}_${u.name}`,name:t(u.name),args:u.args}));return{text:l,toolCalls:c,usage:{inputTokens:a.inputTokens,outputTokens:a.outputTokens,...a.cacheReadTokens?{cacheReadTokens:a.cacheReadTokens}:{},...a.reasoningTokens?{reasoningTokens:a.reasoningTokens}:{}},rawStopReason:a.finishReason,raw:{rawResponseParts:a.rawResponseParts,stepFunctionCalls:a.stepFunctionCalls}}},buildToolResultMessages(n,o,s){const i=[...n];return UEr(i,o.raw.rawResponseParts,o.raw.stepFunctionCalls),i.push({role:"user",parts:s.map(a=>({functionResponse:{name:r(a.name),response:a.error?{error:a.error}:{result:a.output}}}))}),i},mapFinishReason(n,o){const s=lW(n);return o&&s==="stop"?"tool-calls":s}}}var BEr=C({"src/lib/core/geminiLoopAdapter.ts"(){"use strict";LM()}});function qv(){const e=[];let t=!1,r,n=!1,o=null;function s(){if(o){const d=o;o=null,d()}}function i(d){t||(e.push(d),s())}function a(){t=!0,s()}function l(d){t=!0,r=d,n=!0,s()}let c=0;async function*u(){try{for(;;)if(c<e.length)yield e[c++],c>1024&&c*2>=e.length&&(e.splice(0,c),c=0);else if(t){if(n)throw r instanceof Error?r:new Error(String(r));return}else await new Promise(d=>{o=d})}finally{t=!0,e.length=0,o?.()}}return{push:i,close:a,error:l,iterable:u()}}var Gv=C({"src/lib/core/streamChannel.ts"(){"use strict"}});function zEr(e,t){return{inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,cacheReadTokens:(e.cacheReadTokens??0)+(t.cacheReadTokens??0)||void 0,cacheWriteTokens:(e.cacheWriteTokens??0)+(t.cacheWriteTokens??0)||void 0,reasoningTokens:(e.reasoningTokens??0)+(t.reasoningTokens??0)||void 0}}function kE(e,t,r){const n=qv(),o=new AbortController,s=()=>o.abort();r.abortSignal?.addEventListener("abort",s),r.abortSignal?.aborted&&o.abort();const i=new Map;let a=!1;const l=(async()=>{let c=t,u={inputTokens:0,outputTokens:0},d="",m="",f;const g=[],y=[];let v=!1;try{for(let b=0;b<e.maxSteps&&!o.signal.aborted;b++){if(e.planReclaim){const I=e.planReclaim(c,b);I&&(c=I.conversation)}const T=e.buildStepRequest(c,b);let x=!1;const k={push:I=>{x=!0,n.push(I)}};let R;try{R=await Hy(async()=>{x=!1;try{return await e.executeStep(T,k,o.signal)}catch(I){throw x?new dW(I):I}},void 0,`${e.providerLabel}.step`)}catch(I){throw I instanceof dW?I.cause:I}if(u=zEr(u,R.usage),f=R.rawStopReason,m=R.text||m,e.isMalformedStep?.(R)&&!a&&!o.signal.aborted){a=!0,h.warn(`[${e.providerLabel}] Malformed function call at step ${b+1}/${e.maxSteps}; retrying once.`),c=e.buildMalformedRetryNote?.(c)??c;continue}if(R.toolCalls.length===0){d=R.text||d;break}b===e.maxSteps-1&&(v=!0);const P=[];for(const I of R.toolCalls){g.push(I);const A=e.toolFailureBreaker,M=A?i.get(I.name):void 0;if(A&&M&&M.count>=A.maxRetries){const D={error:`TOOL_PERMANENTLY_FAILED: "${I.name}" has failed ${M.count} times. Last error: ${M.lastError}.`,status:"permanently_failed",do_not_retry:!0};P.push({...I,output:D,error:D.error,permanentlyFailed:!0}),y.push({id:I.id,name:I.name,input:I.args,output:D,error:D.error});continue}const O=r.tools?.[I.name],N=O?.execute?O:e.resolveToolOnMiss?.(I.name)??O;if(!N?.execute){const D=A?{error:`TOOL_NOT_FOUND: "${I.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${I.name}`};P.push({...I,output:D,error:D.error,permanentlyFailed:!!A}),y.push({id:I.id,name:I.name,input:I.args,output:D,error:D.error});continue}try{const D=await N.execute(I.args,{toolCallId:I.id,abortSignal:o.signal});P.push({...I,output:D}),y.push({id:I.id,name:I.name,input:I.args,output:D})}catch(D){const F=D instanceof Error?D.message:String(D);if(A){const $=i.get(I.name)??{count:0,lastError:""};$.count++,$.lastError=F,i.set(I.name,$)}const U={error:F,status:"failed"};P.push({...I,output:U,error:F}),y.push({id:I.id,name:I.name,input:I.args,output:U,error:F})}}c=e.buildToolResultMessages(c,R,P)}const w=e.mapFinishReason(f,v);return{text:d||(v?m:""),toolCalls:g,toolExecutions:y,usage:u,finishReason:w,rawStopReason:f,conversation:c}}catch(w){throw n.error(w),w}finally{n.close(),r.abortSignal?.removeEventListener("abort",s)}})();return{stream:n.iterable,resultPromise:l}}var dW,pW=C({"src/lib/core/loopEngine.ts"(){"use strict";Gv(),W(),Ph(),dW=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e)),this.cause=e}cause}}});function jEr(e){return e?.kind==="toolCall"||e?.kind==="toolResult"}function qEr(e,t,r){const n=[];let o=t;for(;o<r;){if(!jEr(e[o])){o++;continue}const s=o;for(;o<e.length&&e[o].kind==="toolCall";)o++;for(;o<e.length&&e[o].kind==="toolResult";)o++;if(o>r)break;n.push({start:s,end:o})}return n}function mW(e,t){const{availableInputTokens:r,fixedOverheadTokens:n,thresholdRatio:o=VT,lowWaterRatio:s=mgt,protectedTailCount:i=hgt,calibration:a=1}=t,l=a>0?a:1,c=Math.floor(r*o/l),u=Math.floor(r*s/l);let d=n;for(const w of e)d+=w.tokens;if(d<=c)return{fire:!1,truncate:[],drop:[],projectedTokens:d};const m=1,f=Math.max(m,e.length-i),g=[],y=new Set;for(let w=m;w<f&&d>u;w++){const b=e[w];if(b.kind!=="toolResult"||b.previewTokens===void 0)continue;const T=b.tokens-b.previewTokens;T<=0||(g.push(w),d-=T)}if(d>u){const w=qEr(e,m,f);for(const b of w){if(d<=u)break;for(let T=b.start;T<b.end;T++){const x=e[T],k=g.includes(T)?x.previewTokens??x.tokens:x.tokens;d-=k,y.add(T)}}}const v=g.filter(w=>!y.has(w));return{fire:v.length>0||y.size>0,truncate:v,drop:[...y].sort((w,b)=>w-b),projectedTokens:d}}var mgt,hgt,hW=C({"src/lib/context/loopGuardCore.ts"(){"use strict";Fo(),mgt=.6,hgt=4}});function fgt(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function ggt(e,t){return Array.isArray(e.parts)&&e.parts.some(r=>r&&typeof r=="object"&&t in r)}function GEr(e){return ggt(e,"functionResponse")}function fW(e){const{preview:t}=Wl(e,{maxBytes:gW,maxLines:vgt});return t}function HEr(e,t){return pr(fgt(e.parts),t)+hl}function VEr(e,t){return e.map(r=>{const n=HEr(r,t);if(GEr(r)){const o=fgt(r.parts),s=o.length>gW?pr(fW(o),t)+hl:n;return{kind:"toolResult",tokens:n,...s<n?{previewTokens:s}:{}}}return ggt(r,"functionCall")?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function ygt(e){const{contents:t,availableInputTokens:r,fixedOverheadTokens:n=0,provider:o,observedPromptTokens:s}=e,i=VEr(t,o);let a=1;if(s&&s>0){const c=n+i.reduce((u,d)=>u+d.tokens,0);c>0&&(a=Math.min(3,Math.max(1,s/c)))}const l=mW(i,{availableInputTokens:r,fixedOverheadTokens:n,calibration:a});if(l.fire)return h.info("[GeminiLoopGuard] Reclaiming agent-loop context",{provider:o,contents:t.length,toolResponsesTruncated:l.truncate.length,contentsDropped:l.drop.length,projectedTokens:l.projectedTokens,calibration:a}),l}var gW,vgt,yW,_gt=C({"src/lib/context/geminiLoopGuard.ts"(){"use strict";Qs(),ef(),hW(),W(),gW=2048,vgt=60,yW="[Earlier tool exchanges were removed to fit the context window.]"}}),IE=C({"src/lib/utils/async/index.ts"(){"use strict";Kn()}}),wgt=C({"src/lib/providers/googleNativeGemini3/index.ts"(){"use strict";LM()}}),Dd,Tgt=C({"src/lib/providers/anthropic/cacheControl.ts"(){"use strict";Dd=e=>e?.providerOptions?.anthropic?.cacheControl?.type==="ephemeral"?{type:"ephemeral"}:void 0}});function Hv(e,t){if(t==="functionDeclarations")return ngt(e);const r=Object.entries(e??{});if(r.length!==0)return r.map(([n,o])=>{const s=o,i=s.inputSchema??s.parameters,a=i?$s(i):{type:"object",properties:{}},l=Dd(o);return{name:n,...s.description?{description:s.description}:{},input_schema:a,...l?{cache_control:l}:{}}})}var vW=C({"src/lib/core/nativeToolFormat.ts"(){"use strict";LM(),Tgt(),qi()}});function WEr(e,t){try{const[r,n]=t.split("/"),o=parseInt(n,10);if(isNaN(o)||o<0||o>32)return!1;const s=c=>{const u=c.split(".").map(Number);return(u[0]<<24)+(u[1]<<16)+(u[2]<<8)+u[3]},i=s(e),a=s(r),l=-1<<32-o>>>0;return(i&l)===(a&l)}catch{return!1}}function KEr(e,t){const r=t||process.env.NO_PROXY||process.env.no_proxy;if(!r)return!1;try{const n=new URL(e),o=n.hostname.toLowerCase(),s=n.port||(n.protocol==="https:"?"443":"80"),i=r.split(",").map(a=>a.trim()).filter(Boolean);for(const a of i){const l=a.toLowerCase();if(l==="*")return!0;if(l.startsWith(".")){const c=l.slice(1);if(o.endsWith(c)||o===c)return!0}else if(l.includes(":")){const[c,u]=l.split(":");if(o===c&&s===u)return!0}else if(l.includes("/")){if(/^\d{1,3}(\.\d{1,3}){3}$/.test(o)&&WEr(o,l))return!0}else if(o===l)return!0}return!1}catch(n){return h.warn("[Proxy] Error in NO_PROXY bypass logic",{targetUrl:e,error:n}),!1}}var JEr=C({"src/lib/proxy/utils/noProxyUtils.ts"(){"use strict";W()}});async function YEr(){try{return(await Promise.resolve().then(()=>(ym(),O9))).getLangfuseContext?.()}catch{return}}function ZEr(e,t){const r=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers){const n=new Headers(t.headers);for(const[o,s]of n.entries())r.set(o,s)}return r}async function bgt(e,t){const r={};Qg.inject(Tr.active(),r);const n=await YEr();if(n?.sessionId&&(r["x-neurolink-session-id"]=n.sessionId),n?.userId&&(r["x-neurolink-user-id"]=n.userId),n?.conversationId&&(r["x-neurolink-conversation-id"]=n.conversationId),Object.keys(r).length===0)return t??{};const o=ZEr(e,t);for(const[s,i]of Object.entries(r))o.has(s)||o.set(s,i);return{...t,headers:o}}function XEr(e){try{const t=typeof e=="string"?e:e instanceof URL?e.href:e.url;return new URL(t).hostname}catch{return"[unknown]"}}function QEr(e){let t=e;for(let r=0;r<5&&t;r++){const n=t;if(n.code&&dz.has(n.code)||n.message?.includes("socket hang up")||n.message?.includes("network socket disconnected")||n.message?.includes("other side closed"))return!0;t=n.cause}return!1}async function Egt(e,t,r=3,n=500){const o=XEr(e);return kgt.startActiveSpan("neurolink.http.fetchWithRetry",async s=>{s.setAttribute("http.request.max_retries",r),s.setAttribute("http.request.hostname",o),s.setAttribute("http.request.method",t?.method||"GET");let i=0;try{for(let a=0;a<=r;a++){i=a+1;try{const l=await fetch(e,t);return s.setAttribute("http.request.total_attempts",i),s.setAttribute("http.response.status_code",l.status),s.setStatus({code:je.OK}),l}catch(l){const c=QEr(l),u=l;if(!c||a===r)throw s.setAttribute("http.request.total_attempts",i),s.setStatus({code:je.ERROR,message:u?.message||u?.code||"fetchWithRetry final failure"}),s.recordException(l instanceof Error?l:new Error(String(l))),l;const d=n*Math.pow(2,a);s.addEvent("http.request.retry",{"retry.attempt":a+1,"retry.delay_ms":d,"retry.error":(u?.code||u?.message||String(l)).slice(0,256)}),h.debug(`[fetchWithRetry] Transient error (${u?.code||u?.message}), retrying in ${d}ms (attempt ${a+1}/${r})`),await new Promise(m=>setTimeout(m,d))}}throw new Error("fetchWithRetry exhausted")}finally{s.end()}})}function Sgt(e){if(!e)return{parsed:null,size:0,type:"empty"};if(typeof e=="string")try{return{parsed:JSON.parse(e),size:e.length,type:"json"}}catch{return{parsed:e,size:e.length,type:"text"}}return e instanceof ArrayBuffer?{parsed:"[ArrayBuffer]",size:e.byteLength,type:"arraybuffer"}:e instanceof Uint8Array?{parsed:"[Uint8Array]",size:e.length,type:"uint8array"}:{parsed:"[Stream]",size:-1,type:"stream"}}async function _W(e){const t={};e.headers.forEach((r,n)=>{t[n]=Igt.has(n.toLowerCase())?`${r.substring(0,4)}***`:r});try{const n=await e.clone().text();try{return{parsed:JSON.parse(n),size:n.length,type:"json",headers:t}}catch{return{parsed:n,size:n.length,type:"text",headers:t}}}catch{return{parsed:"[unable to read body]",size:-1,type:"error",headers:t}}}function eSr(e){try{const t=new URL(e),r={protocol:t.protocol,hostname:t.hostname,port:parseInt(t.port)||Cgt(t.protocol),cleanUrl:`${t.protocol}//${t.hostname}:${t.port||Cgt(t.protocol)}`};return t.username&&t.password&&(r.auth={username:decodeURIComponent(t.username),password:decodeURIComponent(t.password)}),r}catch(t){let r;try{const n=new URL(e);n.username="",n.password="",r=n.toString()}catch{r="[invalid-url]"}throw h.error("[Proxy] Failed to parse proxy URL",{proxyUrl:r,error:t}),new Error(`Invalid proxy URL: ${r}`,{cause:t})}}function Cgt(e){switch(e){case"http:":return 8080;case"https:":return 8080;case"socks4:":return 1080;case"socks5:":return 1080;default:return 8080}}function tSr(e){if(KEr(e))return h.debug("[Proxy] Bypassing proxy due to NO_PROXY",{targetUrl:e}),null;try{const t=new URL(e),r=process.env.HTTPS_PROXY||process.env.https_proxy,n=process.env.HTTP_PROXY||process.env.http_proxy,o=process.env.ALL_PROXY||process.env.all_proxy,s=process.env.SOCKS_PROXY||process.env.socks_proxy;return t.protocol==="https:"&&r?r:t.protocol==="http:"&&n?n:o||s||null}catch(t){return h.warn("[Proxy] Error selecting proxy URL",{targetUrl:e,error:t}),null}}async function rSr(e){const t=eSr(e);switch(h.debug("[Proxy] Creating proxy agent",{protocol:t.protocol,hostname:t.hostname,port:t.port,hasAuth:!!t.auth}),t.protocol){case"http:":case"https:":{const{ProxyAgent:r}=await Promise.resolve().then(()=>(Sv(),KH));return new r(e)}case"socks4:":case"socks5:":throw new Error("SOCKS proxy support requires 'proxy-agent' package. Install it with: npm install proxy-agent");default:throw new Error(`Unsupported proxy protocol: ${t.protocol}`)}}function fa(e){return Vv(e)??"NOT_SET"}function xgt(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}function nSr(){return async(e,t)=>{const r=await bgt(e,t),n=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,o=Date.now(),s=xgt(e);if(h.shouldLog("debug")){const{size:i,type:a}=Sgt(r?.body);h.debug("[Observability] HTTP request to LLM provider",{requestId:n,url:s,method:r?.method||"POST",bodySize:i,bodyType:a})}try{const i=await Egt(e,r);if(h.shouldLog("debug")){const{parsed:a,size:l,type:c,headers:u}=await _W(i);h.debug("[Observability] HTTP response from LLM provider",{requestId:n,url:s,status:i.status,statusText:i.statusText,durationMs:Date.now()-o,contentLength:l,hasContent:!!a,bodyType:c,responseHeaders:u})}return i}catch(i){throw h.debug("[Observability] HTTP request failed",{requestId:n,url:s,error:i instanceof Error?i.message:String(i),durationMs:Date.now()-o}),i}}}async function oSr(e,t,r){const{httpsProxy:n,httpProxy:o,allProxy:s,socksProxy:i,noProxy:a}=r;t=await bgt(e,t);const l=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,c=Date.now(),u=xgt(e);if(h.shouldLog("debug")){const{size:f,type:g}=Sgt(t?.body);h.debug("[Observability] HTTP request to LLM provider",{requestId:l,url:u,method:t?.method||"POST",bodySize:f,bodyType:g})}h.debug("[Proxy Fetch] ENHANCED REQUEST START",{requestId:l,targetUrl:u,timestamp:new Date().toISOString(),httpProxy:fa(o),httpsProxy:fa(n),allProxy:fa(s),socksProxy:fa(i),noProxy:a||"NOT_SET",initMethod:t?.method||"GET"});const d=e instanceof Request?e.clone():null;try{const f=tSr(u);if(f){const g=new URL(u);h.debug("[Proxy Fetch] \u{1F517} ENHANCED URL ANALYSIS",{requestId:l,targetUrl:u,urlHostname:g.hostname,urlProtocol:g.protocol,urlPort:g.port,selectedProxyUrl:fa(f),timestamp:new Date().toISOString()}),h.debug("[Proxy Fetch] \u{1F3AF} ENHANCED PROXY AGENT CREATION",{requestId:l,proxyUrl:fa(f),targetHostname:g.hostname,targetProtocol:g.protocol,aboutToCreateProxyAgent:!0,timestamp:new Date().toISOString()});const y=globalThis;y.__NL_PROXY_AGENT_CACHE__||(y.__NL_PROXY_AGENT_CACHE__=new Map);const v=y.__NL_PROXY_AGENT_CACHE__,w=QR("sha256").update(Vv(f)??f).digest("hex"),b=v.get(w)||await rSr(f);v.set(w,b),h.debug("[Proxy Fetch] \u2705 ENHANCED PROXY AGENT CREATED",{requestId:l,hasDispatcher:!!b,dispatcherType:typeof b,dispatcherConstructor:b?.constructor?.name||"unknown",timestamp:new Date().toISOString()});let T,x={...t};e instanceof Request?(T=e.url,x={method:e.method,headers:e.headers,body:e.body,...t}):T=e;const R=await(await Promise.resolve().then(()=>(Sv(),KH))).fetch(T,{...x,dispatcher:b});if(h.shouldLog("debug")){const{parsed:P,size:I,type:A,headers:M}=await _W(R);h.debug("[Observability] HTTP response from LLM provider",{requestId:l,url:u,status:R?.status,statusText:R?.statusText,durationMs:Date.now()-c,contentLength:I,hasContent:!!P,bodyType:A,proxied:!0,responseHeaders:M})}return h.debug("[Proxy Fetch] ENHANCED PROXY SUCCESS",{requestId:l,responseStatus:R?.status,responseOk:R?.ok,proxyUsed:!0,timestamp:new Date().toISOString()}),R}}catch(f){const g=f instanceof Error?f.message:String(f);h.debug("[Observability] HTTP request failed",{requestId:l,url:u,error:g,durationMs:Date.now()-c}),h.debug("[Proxy Fetch] ENHANCED ERROR ANALYSIS",{requestId:l,error:g,errorType:f instanceof Error?f.constructor.name:typeof f,willFallback:!0,timestamp:new Date().toISOString()}),h.warn(`[Proxy Fetch] Enhanced proxy failed (${g}), falling back to direct connection`)}h.debug("[Proxy Fetch] ENHANCED FALLBACK TO STANDARD FETCH",{requestId:l,fallbackReason:"No proxy configured or proxy failed",timestamp:new Date().toISOString()});const m=e instanceof Request?d??e:e;try{const f=await Egt(m,t);if(h.shouldLog("debug")){const{parsed:g,size:y,type:v,headers:w}=await _W(f);h.debug("[Observability] HTTP response from LLM provider",{requestId:l,url:u,status:f.status,statusText:f.statusText,durationMs:Date.now()-c,contentLength:y,hasContent:!!g,bodyType:v,proxied:!1,responseHeaders:w})}return f}catch(f){const g=f instanceof Error?f.message:String(f);throw h.debug("[Observability] HTTP request failed",{requestId:l,url:u,error:g,durationMs:Date.now()-c}),f}}function sSr(e){return async(t,r)=>oSr(t,r,e)}function Bt(){const e=process.env.HTTPS_PROXY||process.env.https_proxy,t=process.env.HTTP_PROXY||process.env.http_proxy,r=process.env.ALL_PROXY||process.env.all_proxy,n=process.env.SOCKS_PROXY||process.env.socks_proxy,o=process.env.NO_PROXY||process.env.no_proxy,s={httpsProxy:e,httpProxy:t,allProxy:r,socksProxy:n,noProxy:o};if(h.shouldLog("debug")){const i=Object.keys(process.env).filter(a=>a.toLowerCase().includes("proxy")).reduce((a,l)=>{const c=process.env[l]||"NOT_SET";return a[l]=l.toLowerCase()==="no_proxy"?c:fa(c),a},{});h.debug("[Proxy Fetch] ENHANCED_PROXY_ENV_DETECTION",{httpProxy:fa(t),httpsProxy:fa(e),allProxy:fa(r),socksProxy:fa(n),noProxy:o||"NOT_SET",allProxyRelatedEnvVars:i,message:"Enhanced proxy environment detection \u2014 credentials redacted"})}return!e&&!t&&!r&&!n?(h.debug("[Proxy Fetch] No proxy environment variables found - using standard fetch"),nSr()):(h.debug("[Proxy Fetch] Configuring enhanced proxy with multiple protocol support"),h.debug(`[Proxy Fetch] HTTP_PROXY: ${fa(t)}`),h.debug(`[Proxy Fetch] HTTPS_PROXY: ${fa(e)}`),h.debug(`[Proxy Fetch] ALL_PROXY: ${fa(r)}`),h.debug(`[Proxy Fetch] SOCKS_PROXY: ${fa(n)}`),h.debug(`[Proxy Fetch] NO_PROXY: ${o||"not set"}`),sSr(s))}function Vv(e){if(!e)return null;try{const t=new URL(e);return(t.username||t.password)&&(t.username="***",t.password="***"),t.toString()}catch{return"[invalid-url]"}}function iSr(){const e=process.env.HTTPS_PROXY||process.env.https_proxy,t=process.env.HTTP_PROXY||process.env.http_proxy,r=process.env.ALL_PROXY||process.env.all_proxy,n=process.env.SOCKS_PROXY||process.env.socks_proxy,o=process.env.NO_PROXY||process.env.no_proxy;return{enabled:!!(e||t||r||n),httpProxy:Vv(t),httpsProxy:Vv(e),allProxy:Vv(r),socksProxy:Vv(n),noProxy:o||null,method:"enhanced-proxy-agent",capabilities:["HTTP/HTTPS Proxy","SOCKS4/SOCKS5 Proxy","Proxy Authentication","NO_PROXY Bypass","CIDR Range Matching","Wildcard Domain Matching"]}}function Agt(e){wW||!iSr().enabled||(wW=!0,h.warn(`[${e}] A proxy is configured, but the @google/genai SDK provides no way to route its requests through it (HttpOptions has no 'fetch', and GoogleGenAIOptions accepts none). Requests from this provider go direct.`))}var kgt,Igt,wW,Zn=C({"src/lib/proxy/proxyFetch.ts"(){"use strict";W(),Xt(),gr(),JEr(),ji(),kSe(),kgt=Ve.http,Igt=new Set(["authorization","x-api-key","api-key","x-goog-api-key","proxy-authorization","cookie","set-cookie"]),wW=!1}});async function Wv(e,t){const n=(await Promise.resolve().then(()=>(GT(),Jy))).GoogleGenAI;if(!n)throw new $e({code:Xe.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const o=n;return Agt("GoogleAIStudio"),new o({apiKey:e,httpOptions:{...t?{baseUrl:t}:{}}})}function Rgt(e,t,r){const n=ygt({contents:e,availableInputTokens:qc("googleAiStudio",t),provider:"googleAiStudio",...r?{observedPromptTokens:r}:{}});if(!n)return!1;const o=new Set(n.drop),s=new Set(n.truncate),i=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const l=e[a];if(s.has(a)&&Array.isArray(l.parts)){i.push({...l,parts:l.parts.map(c=>{const u=c;if(!u.functionResponse)return c;const d=JSON.stringify(u.functionResponse.response)??"";return d.length<=2048?c:{functionResponse:{name:u.functionResponse.name,response:{result:fW(d)}}}})});continue}i.push(l)}if(o.size>0){let a=i.findIndex(l=>Array.isArray(l.parts)&&l.parts.some(c=>!!c.functionCall||!!c.functionResponse));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",parts:[{text:yW}]})}return e.length=0,e.push(...i),!0}var Pgt,aSr=C({"src/lib/providers/googleAiStudio/client.ts"(){"use strict";tc(),Fo(),nM(),ul(),Ct(),ct(),W(),BEr(),pW(),Fo(),kH(),_gt(),Mu(),Pa(),IE(),Qs(),Sd(),U1(),wgt(),Gv(),vW(),Zn(),Pgt=class extends gl{credentials;constructor(e,t,r){super(e,"google-ai",t),this.credentials=r,h.debug("GoogleAIStudioProvider initialized",{model:this.modelName,provider:this.providerName,sdkProvided:!!t})}getProviderName(){return"google-ai"}getDefaultModel(){return process.env.GOOGLE_AI_MODEL||"gemini-2.5-flash"}getAISDKModel(){throw new $e({code:Xe.INVALID_CONFIGURATION,message:"GoogleAIStudioProvider no longer uses @ai-sdk/google. All models use native @google/genai SDK.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}formatProviderError(e){if(e instanceof pd)return new Go(e.message,this.providerName);const t=e,r=typeof t?.message=="string"?t.message:"Unknown error",n=typeof t?.status=="number"?t.status:typeof t?.statusCode=="number"?t.statusCode:void 0;return r.includes("API_KEY_INVALID")||r.includes("Invalid API key")||n===401?new dr("Invalid Google AI API key. Please check your GOOGLE_AI_API_KEY environment variable.",this.providerName):r.includes("RATE_LIMIT_EXCEEDED")||r.includes("rate limit")||r.includes("429")||n===429?new Ws("Google AI rate limit exceeded. Please try again later.",this.providerName):n===404||n===void 0&&(r.includes("model not found")||r.includes("Model not found"))?new no(`Model '${this.modelName}' not found. Please check the model name and ensure it is available.`,this.providerName):r.includes("ECONNRESET")||r.includes("ENOTFOUND")||r.includes("ETIMEDOUT")||r.includes("ECONNREFUSED")||r.includes("network")||r.includes("connection")?new Go(`Connection error: ${r}`,this.providerName):r.includes("500")||r.includes("502")||r.includes("503")||r.includes("504")||r.includes("server error")||r.includes("Internal Server Error")||n&&n>=500&&n<600?new bt(`Google AI server error: ${r}. Please try again later.`,this.providerName):new bt(`Google AI error: ${r}`,this.providerName)}async executeImageGeneration(e){await vE(e.input);const t=e.prompt||e.input?.text||"",r=e.model||this.modelName,n=Date.now(),o=this.getApiKey();h.info("\u{1F3A8} Starting Google AI Studio image generation",{model:r,prompt:t.substring(0,100),provider:this.providerName});let s;try{s=await Wv(o,this.getBaseURL())}catch{throw new dr("Missing '@google/genai'. Install with: npm install @google/genai",this.providerName)}try{const i=await Promise.all((e.input?.images||[]).map(async d=>{if(typeof d=="object"&&"url"in d){const g=d.url;if(g.startsWith("http")){const w=await fetch(g);if(!w.ok)throw new Error(`Failed to fetch image from ${g}: ${w.status} ${w.statusText}`);const b=await w.arrayBuffer(),T=Buffer.from(b),x=this.detectImageType(T);return h.debug(`Downloaded and detected image MIME type: ${x}`),{inlineData:{mimeType:x,data:T.toString("base64")}}}const y=Buffer.from(g,"base64");return{inlineData:{mimeType:this.detectImageType(y),data:y.toString("base64")}}}if(typeof d=="string"&&d.startsWith("http")){const g=await fetch(d);if(!g.ok)throw new Error(`Failed to fetch image from ${d}: ${g.status} ${g.statusText}`);const y=await g.arrayBuffer(),v=Buffer.from(y),w=this.detectImageType(v);return h.debug(`Downloaded and detected image MIME type: ${w}`),{inlineData:{mimeType:w,data:v.toString("base64")}}}const m=Buffer.isBuffer(d)?d:typeof d=="string"?Buffer.from(d,"base64"):Buffer.from(""),f=this.detectImageType(m);return h.debug(`Detected image MIME type: ${f}`),{inlineData:{mimeType:f,data:m.toString("base64")}}})),a=[{role:"user",parts:[{text:t},...i]}],l={responseModalities:["IMAGE","TEXT"]};h.debug("Starting image generation request",{model:r,contentParts:a[0].parts.length,responseModalities:l.responseModalities});let c=null,u="";try{const d=await s.models.generateContentStream({model:r,contents:a,config:l});for await(const m of d){h.debug("Received chunk",{hasCandidate:!!m.candidates?.[0],hasContent:!!m.candidates?.[0]?.content,hasParts:!!m.candidates?.[0]?.content?.parts});const f=m.candidates?.[0];if(f?.content?.parts)for(const g of f.content.parts){if("inlineData"in g&&g.inlineData?.data){const y=g.inlineData.data;c=y;const v=g.inlineData.mimeType||"image/png";h.info("Image generation successful",{model:r,mimeType:v,dataLength:y.length,responseTime:Date.now()-n});const w={content:`Generated image using ${r} (${v})`,imageOutput:{base64:y},provider:this.providerName,model:r,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(w,e,n)}"text"in g&&g.text&&(u+=g.text,h.debug("Received text content",{text:g.text.substring(0,100)}))}}}catch(d){h.debug("Streaming failed, trying non-streaming approach",{error:d instanceof Error?d.message:String(d)})}if(!c){h.debug("Trying non-streaming approach");const m=(await s.models.generateContent({model:r,contents:a,config:l})).candidates?.[0];if(m?.content?.parts)for(const f of m.content.parts){if("inlineData"in f&&f.inlineData?.data){const g=f.inlineData.data;c=g;const y=f.inlineData.mimeType||"image/png";h.info("Image generation successful (non-streaming)",{model:r,mimeType:y,dataLength:g.length,responseTime:Date.now()-n});const v={content:`Generated image using ${r} (${y})`,imageOutput:{base64:g},provider:this.providerName,model:r,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(v,e,n)}"text"in f&&f.text&&(u+=f.text)}}throw h.warn("No image data found in response",{model:r,prompt:t.substring(0,100),hasTextContent:!!u,textContent:u.substring(0,200)}),new bt(u||`Image generation completed but no image data was returned. This may indicate an issue with the model "${r}" or the prompt: "${t}". Please try again or use a different model.`,this.providerName)}catch(i){throw h.error("Image generation failed",{error:i instanceof Error?i.message:String(i),model:r,prompt:t.substring(0,100)}),this.handleProviderError(i)}}detectImageType(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70?"image/gif":"image/png"}estimateTokenCount(e){return pr(e,"google-ai")}async preprocessNativeFileInput(e){if(e.input&&m9(e.input),e.input?.files&&e.input.files.length>0)try{await h9(e,100*1024*1024,this.providerName)}catch(t){h.warn(`[GoogleAIStudio] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await vE(e.input)}async executeStream(e,t){const r=e.model||this.modelName;if(e.input?.audio)return await this.executeAudioStreamViaGeminiLive(e);await this.preprocessNativeFileInput(e);const n=!!(t||e.output?.format==="json"||e.schema),o=!e.disableTools&&this.supportsTools()&&!n,s=e.tools||{};let i={...e,tools:s};const a=e.output?.format==="json"||e.schema,l=AH(this.providerName,r,!i.disableTools,Object.keys(i.tools??{}).length);return a&&l&&(h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),i={...i,disableTools:!0,tools:{}}),o&&!i.disableTools&&i.tools&&Object.keys(i.tools).length>0&&h.info("[GoogleAIStudio] Routing to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(i.tools??{}).length}),this.executeNativeGemini3Stream(i)}async executeNativeGemini3Stream(e){const t=e.model||this.modelName;return K$e({name:"neurolink.provider.stream",tracer:Ve.provider,attributes:{[Me.GEN_AI_SYSTEM]:"google-ai",[Me.GEN_AI_MODEL]:t,[Me.GEN_AI_OPERATION]:"stream",[Me.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),s=Bl(o,this.providerName,"stream");{const i=this.getApiKey(),a=await Wv(i,this.getBaseURL());h.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const l=[];OM(l,e.conversationMessages);const c=await ugt(e.input,e.input.text,"[GoogleAIStudio:stream]");l.push({role:"user",parts:c});let u,d;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){const M=Hv(e.tools,"functionDeclarations");d=M,u=M.toolsConfig,h.debug("[GoogleAIStudio] Converted tools for native SDK",{toolCount:u[0].functionDeclarations.length,toolNames:u[0].functionDeclarations.map(O=>O.name)})}const m=!u&&(e.output?.format==="json"||!!e.schema),f=m&&e.schema?cgt(e.schema):void 0,g=ogt({...e,model:t,wantsJsonOutput:m,responseSchema:f},u),y=sgt(e.maxSteps),v=CI(e.abortSignal,s?.controller.signal),w=qv(),b=[],T=[];let x,k;const R=new Promise((M,O)=>{x=M,k=O}),P={streamId:`native-${Date.now()}`,startTime:n,responseTime:0,totalToolExecutions:0};(async()=>{let M="",O=0,N=0,D=0,F=0,U=0;const $=zv(Cd("googleAiStudio",t));try{const B=pgt({providerLabel:"GoogleAIStudio",maxSteps:y,toolFailureBreaker:{maxRetries:$o},liveTools:e.tools??{},...d?{declarations:d}:{},buildRequest:ve=>({model:t,contents:ve,config:g,...v?{httpOptions:{signal:v}}:{}}),sendStep:async ve=>a.models.generateContentStream(ve),noteUsage:(ve,le)=>{$.noteUsage(ve,le)},planReclaim:(ve,le)=>{if(le!==0&&!$.shouldStop())return;const H=[...ve];if(Rgt(H,t,$.projectedNextPromptTokens))return $.resetAfterReclaim(),H}}),z={...B,buildToolResultMessages:(ve,le,H)=>{U++;for(const fe of le.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":fe.name,"tool.step":U});M=le.text||M;for(const fe of le.toolCalls)b.push({toolName:fe.name,args:fe.args});for(const fe of H)T.push({name:fe.name,input:fe.args,output:fe.output});if(H.length>0){const fe=RM(le.raw.rawResponseParts);Nt(this.handleToolExecutionStorage(le.toolCalls.map((Y,ae)=>({toolName:Y.name,args:Y.args,...ae===0&&fe?{thoughtSignature:fe}:{},stepIndex:U})),H.map(Y=>({toolName:Y.name,output:Y.output,stepIndex:U})),e,new Date),Kp,"tool storage write timed out").catch(Y=>{h.warn("[GoogleAIStudio] Failed to store native tool executions",{error:Y instanceof Error?Y.message:String(Y)})})}const ie=B.buildToolResultMessages(ve,le,H);try{const fe=ie[ie.length-1];$.noteAppendedChars(JSON.stringify(fe?.parts??[]).length)}catch{}return ie}},j={};for(const[ve,le]of Object.entries(e.tools??{})){const H=le?.execute;H&&(j[ve]={execute:async(ie,fe)=>H(ie,fe)})}const{stream:J,resultPromise:Z}=kE(z,l,{tools:j,...v?{abortSignal:v}:{}}),pe=(async()=>{for await(const ve of J)w.push(ve)})();let Ce;try{Ce=await Z}catch(ve){throw await pe.catch(()=>{}),h.error("[GoogleAIStudio] Native SDK error",ve),this.handleProviderError(ve)}await pe,O+=Ce.usage.inputTokens,N+=Ce.usage.outputTokens,D+=Ce.usage.cacheReadTokens??0,F+=Ce.usage.reasoningTokens??0;const re=Ce.toolCalls.length===0||Ce.finishReason!=="tool-calls",Q=U>=y&&!re;if(Q){const ve=agt("[GoogleAIStudio]",U,y,"",M);ve&&w.push({content:ve})}const ne=Date.now()-n;P.responseTime=ne,P.totalToolExecutions=b.length,r.setAttribute(Me.GEN_AI_INPUT_TOKENS,O),r.setAttribute(Me.GEN_AI_OUTPUT_TOKENS,N),r.setAttribute(Me.GEN_AI_FINISH_REASON,Q?"max_steps":"stop");const Ie=Math.max(0,O-D);x({provider:this.providerName,model:t,tokenUsage:{input:Ie,output:N+F,total:Ie+D+N+F,...D>0?{cacheReadTokens:D}:{},...F>0?{reasoning:F}:{}},requestDuration:ne,timestamp:new Date().toISOString()}),w.close()}catch(B){w.error(B),k(B)}finally{s?.cleanup()}})().catch(()=>{});const A={stream:w.iterable,provider:this.providerName,model:t,toolCalls:b,analytics:R,metadata:P};return Object.defineProperty(A,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>b.map(M=>M.toolName)}),Object.defineProperty(A,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>O1(T)}),A}},r=>r.stream,(r,n)=>({...r,stream:n}))}async executeNativeGemini3Generate(e){const t=e.model||this.modelName;return XT({name:"neurolink.provider.generate",tracer:Ve.provider,attributes:{[Me.GEN_AI_SYSTEM]:"google-ai",[Me.GEN_AI_MODEL]:t,[Me.GEN_AI_OPERATION]:"generate",[Me.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),s=Bl(o,this.providerName,"generate");try{const i=this.getApiKey(),a=await Wv(i,this.getBaseURL());h.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3 generate",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const l=e.input?.text||e.prompt||"",c=[];OM(c,e.conversationMessages);const u=await ugt(e.input,l,"[GoogleAIStudio:generate]");c.push({role:"user",parts:u});let d,m;const f=!e.disableTools,g=!!(e.output?.format==="json"||e.schema),y=AH(this.providerName,t,f,Object.keys(e.tools||{}).length);if(g&&y&&h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request (generate())."),f&&!(g&&y)){const Q=e.tools||{};if(Object.keys(Q).length>0){const ne=Hv(Q,"functionDeclarations");m=ne,d=ne.toolsConfig,h.debug("[GoogleAIStudio] Converted tools for native SDK generate",{toolCount:d[0].functionDeclarations.length,toolNames:d[0].functionDeclarations.map(Ie=>Ie.name)})}}const v=!d&&g,w=v&&e.schema?cgt(e.schema):void 0,b=ogt({...e,model:t,wantsJsonOutput:v,responseSchema:w},d),T=CI(e.abortSignal,s?.controller.signal),x=sgt(e.maxSteps);let k="",R="",P=0,I=0,A=0,M=0;const O=[],N=[];let D=0;const F=zv(Cd("googleAiStudio",t)),U=pgt({providerLabel:"GoogleAIStudio",maxSteps:x,toolFailureBreaker:{maxRetries:$o},liveTools:e.tools??{},...m?{declarations:m}:{},buildRequest:Q=>({model:t,contents:Q,config:b,...T?{httpOptions:{signal:T}}:{}}),sendStep:async Q=>a.models.generateContentStream(Q),noteUsage:(Q,ne)=>{F.noteUsage(Q,ne)},planReclaim:(Q,ne)=>{if(ne!==0&&!F.shouldStop())return;const Ie=[...Q];if(Rgt(Ie,t,F.projectedNextPromptTokens))return F.resetAfterReclaim(),Ie}}),$={...U,buildToolResultMessages:(Q,ne,Ie)=>{D++;for(const le of ne.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":le.name,"tool.step":D}),O.push({toolName:le.name,args:le.args});R=ne.text||R;for(const le of Ie)N.push({name:le.name,input:le.args,output:le.output});if(Ie.length>0){const le=RM(ne.raw.rawResponseParts);Nt(this.handleToolExecutionStorage(ne.toolCalls.map((H,ie)=>({toolName:H.name,args:H.args,...ie===0&&le?{thoughtSignature:le}:{},stepIndex:D})),Ie.map(H=>({toolName:H.name,output:H.output,stepIndex:D})),e,new Date),Kp,"tool storage write timed out").catch(H=>{h.warn("[GoogleAIStudio] Failed to store native tool executions",{error:H instanceof Error?H.message:String(H)})})}const ve=U.buildToolResultMessages(Q,ne,Ie);try{const le=ve[ve.length-1];F.noteAppendedChars(JSON.stringify(le?.parts??[]).length)}catch{}return ve}},B={};for(const[Q,ne]of Object.entries(e.tools??{})){const Ie=ne?.execute;Ie&&(B[Q]={execute:async(ve,le)=>Ie(ve,le)})}const{stream:z,resultPromise:j}=kE($,c,{tools:B,...T?{abortSignal:T}:{}}),J=(async()=>{for await(const Q of z);})();let Z;try{Z=await j}catch(Q){throw await J.catch(()=>{}),h.error("[GoogleAIStudio] Native SDK generate error",Q),this.handleProviderError(Q)}await J,P+=Z.usage.inputTokens,I+=Z.usage.outputTokens,A+=Z.usage.cacheReadTokens??0,M+=Z.usage.reasoningTokens??0,k=Z.text,k=agt("[GoogleAIStudio]",D,x,k,R);const pe=Date.now()-n;r.setAttribute(Me.GEN_AI_INPUT_TOKENS,P),r.setAttribute(Me.GEN_AI_OUTPUT_TOKENS,I),r.setAttribute(Me.GEN_AI_FINISH_REASON,D>=x?"max_steps":"stop");const Ce=Math.max(0,P-A),re={content:k,provider:this.providerName,model:t,usage:{input:Ce,output:I+M,total:Ce+A+I+M,...A>0?{cacheReadTokens:A}:{},...M>0?{reasoning:M}:{}},...M>0&&{reasoningTokens:M},responseTime:pe,toolsUsed:O.map(Q=>Q.toolName),toolExecutions:$1(e,N),enhancedWithTools:O.length>0};return this.enhanceResult(re,e,n)}finally{s?.cleanup()}})}async generate(e){const t=typeof e=="string"?{prompt:e}:e,r=t.model||this.modelName;if(Wp.some(u=>r.toLowerCase().startsWith(u.toLowerCase())))return h.info("[GoogleAIStudio] Routing image generation model to executeImageGeneration",{model:r}),this.executeImageGeneration(t);if(t.tts?.enabled&&!t.tts?.useAiResponse)return h.info("[GoogleAIStudio] Routing TTS direct-synthesis to handleDirectTTSSynthesis",{model:r}),this.handleDirectTTSSynthesis(t,Date.now());await this.preprocessNativeFileInput(t);const o=t.disableTools?{}:await this.getToolsForStream(t);let s={...t,tools:o};(t.output?.format==="json"||t.schema)&&s.tools&&Object.keys(s.tools).length>0&&!s.disableTools&&(h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),s={...s,disableTools:!0,tools:{}}),!s.disableTools&&s.tools&&Object.keys(s.tools).length>0&&h.info("[GoogleAIStudio] Routing generate to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(s.tools??{}).length});const l=Date.now(),c=s.input?.text||s.prompt||"";try{let u=await gt({name:"neurolink.executeGeneration",tracer:Ve.provider,attributes:{[Me.GEN_AI_SYSTEM]:this.providerName,[Me.GEN_AI_MODEL]:r,"neurolink.path":"native.google-genai"}},async()=>this.executeNativeGemini3Generate(s));return u=await this.synthesizeAIResponseIfNeeded(u,t),this.emitPipelineBGenerationEvent(r,u,l,!0,void 0,c),u}catch(u){throw this.emitPipelineBGenerationEvent(r,null,l,!1,u,c),u}}emitPipelineBGenerationEvent(e,t,r,n,o,s){const i=this.neurolink?.getEventEmitter();if(!i)return;const a=t?.usage&&typeof t.usage=="object"?t.usage:{input:0,output:0,total:0};t&&typeof t=="object"&&(t._generationEndEmitted=!0),i.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),prompt:s||"",result:{content:t?.content||"",usage:a,model:e,provider:this.providerName,finishReason:n?"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async executeAudioStreamViaGeminiLive(e){const t=Date.now(),r=this.getApiKey();let n;try{n=await Wv(r,this.getBaseURL())}catch{throw new dr("Missing '@google/genai'. Install with: pnpm add @google/genai",this.providerName)}const o=this.modelName||process.env.GOOGLE_VOICE_AI_MODEL||"gemini-2.5-flash-preview-native-audio-dialog",s=[];let i=null,a=!1;const l=d=>{if(!a){if(d.type==="audio"&&i){const m=i;i=null,m({value:{type:"audio",audio:d.audio},done:!1});return}s.push(d)}},c=await n.live.connect({model:o,callbacks:{onopen:()=>{},onmessage:async d=>{try{const m=d?.serverContent?.modelTurn?.parts?.[0]?.inlineData;if(m?.data){const g={data:Buffer.from(String(m.data),"base64"),sampleRateHz:24e3,channels:1,encoding:"PCM16LE"};l({type:"audio",audio:g})}d?.serverContent?.interrupted}catch(m){l({type:"error",error:m})}},onerror:d=>{l({type:"error",error:d})},onclose:d=>{l({type:"end"})}},config:{responseModalities:["AUDIO"],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:"Orus"}}}}});return(async()=>{try{const d=e.input?.audio;if(!d){h.debug("[GeminiLive] No audio spec found on input; skipping upstream send");return}for await(const m of d.frames){if(!m||m.byteLength===0){try{c.sendInput?await c.sendInput({event:"flush"}):c.sendRealtimeInput&&await c.sendRealtimeInput({event:"flush"})}catch(y){h.debug("[GeminiLive] flush control failed (non-fatal)",{error:y instanceof Error?y.message:String(y)})}continue}const f=m.toString("base64"),g=`audio/pcm;rate=${d.sampleRateHz||16e3}`;await c.sendRealtimeInput?.({media:{data:f,mimeType:g}})}try{c.sendInput?await c.sendInput({event:"flush"}):c.sendRealtimeInput&&await c.sendRealtimeInput({event:"flush"})}catch(m){h.debug("[GeminiLive] final flush failed (non-fatal)",{error:m instanceof Error?m.message:String(m)})}}catch(d){l({type:"error",error:d})}})().catch(()=>{}),{stream:{[Symbol.asyncIterator](){return{async next(){if(s.length>0){const d=s.shift();if(!d)return{value:void 0,done:!0};if(d.type==="audio")return{value:{type:"audio",audio:d.audio},done:!1};if(d.type==="end")return a=!0,{value:void 0,done:!0};if(d.type==="error")throw a=!0,d.error instanceof Error?d.error:new Error(String(d.error))}return a?{value:void 0,done:!0}:await new Promise(d=>{i=d})}}}},provider:this.providerName,model:o,metadata:{startTime:t,streamId:`google-ai-audio-${Date.now()}`}}}getDefaultEmbeddingModel(){return process.env.GOOGLE_AI_EMBEDDING_MODEL||process.env.GOOGLE_EMBEDDING_MODEL||"gemini-embedding-001"}async embed(e,t){const r=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";h.debug("Generating embedding",{provider:this.providerName,model:r,textLength:e.length});try{const n=this.getApiKey(),i=(await(await Wv(n,this.getBaseURL())).models.embedContent({model:r,contents:[e]})).embeddings?.[0]?.values;if(!i)throw new bt("No embedding returned from Google AI",this.providerName);return h.debug("Embedding generated successfully",{provider:this.providerName,model:r,embeddingDimension:i.length}),i}catch(n){throw h.error("Embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,textLength:e.length}),this.handleProviderError(n)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";h.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=this.getApiKey(),i=((await(await Wv(n,this.getBaseURL())).models.embedContent({model:r,contents:e})).embeddings||[]).map(a=>a.values||[]);return h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:i.length,embeddingDimension:i[0]?.length}),i}catch(n){throw h.error("Batch embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,count:e.length}),this.handleProviderError(n)}}getApiKey(){const e=this.credentials?.apiKey||process.env.GOOGLE_AI_API_KEY||process.env.GOOGLE_GENERATIVE_AI_API_KEY;if(!e)throw new dr("GOOGLE_AI_API_KEY or GOOGLE_GENERATIVE_AI_API_KEY environment variable is not set",this.providerName);return e}getBaseURL(){const e=this.credentials?.baseURL?.trim()||process.env.GOOGLE_AI_BASE_URL?.trim();return e&&e.length>0?e:void 0}}}}),Mgt={};de(Mgt,{GoogleAIStudioProvider:()=>Pgt});var lSr=C({"src/lib/providers/googleAiStudio/index.ts"(){"use strict";aSr()}});async function Od(e,t,r){const n=parseInt(e.headers.get("content-length")??"0",10);if(n>0&&n>t)throw new Error(`${r} download too large: ${n} bytes (max ${t})`);const o=Buffer.from(await e.arrayBuffer());if(o.length>t)throw new Error(`${r} download exceeded size cap after fetch: ${o.length} bytes (max ${t})`);return o}var Pf,Mf,Df,yl=C({"src/lib/utils/sizeGuard.ts"(){"use strict";Pf=256*1024*1024,Mf=50*1024*1024,Df=25*1024*1024}}),cSr,uSr,dSr,pSr,$M,Dgt,TW,bW,mSr,hSr,fSr,gSr,ySr=C({"node-stub:node:dns/promises"(){cSr=globalThis.crypto,uSr=globalThis.ReadableStream||class{},dSr=globalThis.URL,pSr=globalThis.URLSearchParams,$M=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},$M.custom=Symbol.for("nodejs.util.inspect.custom"),$M.colors={},$M.styles={},Dgt=globalThis.TextDecoder,TW=globalThis.TextEncoder,bW=(e,t)=>t?.(null,"127.0.0.1",4),mSr=globalThis.performance||{now:()=>Date.now()},hSr=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new TW().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new TW().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new Dgt().decode(this)}},fSr=globalThis.clearTimeout,gSr=globalThis.clearInterval}}),vSr,_Sr,wSr,TSr,FM,Ogt,EW,bSr,ESr,Ngt,SSr,CSr,xSr=C({"node-stub:node:net"(){vSr=globalThis.crypto,_Sr=globalThis.ReadableStream||class{},wSr=globalThis.URL,TSr=globalThis.URLSearchParams,FM=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},FM.custom=Symbol.for("nodejs.util.inspect.custom"),FM.colors={},FM.styles={},Ogt=globalThis.TextDecoder,EW=globalThis.TextEncoder,bSr=globalThis.performance||{now:()=>Date.now()},ESr=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new EW().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new EW().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new Ogt().decode(this)}},Ngt=()=>0,SSr=globalThis.clearTimeout,CSr=globalThis.clearInterval}});function ASr(e){return e.length===0?null:/^0x[0-9a-f]+$/i.test(e)?parseInt(e.slice(2),16):e.length>1&&e.startsWith("0")&&/^0[0-7]+$/.test(e)?parseInt(e.slice(1),8):/^\d+$/.test(e)?parseInt(e,10):null}function UM(e){if(e.length===0)return null;const t=e.split(".");if(t.length===4){const r=t.map(ASr);return r.some(n=>n===null||n<0||n>255)?null:r.join(".")}if(t.length===1){let r;if(/^0x[0-9a-f]+$/i.test(e))r=parseInt(e.slice(2),16);else if(/^\d+$/.test(e))r=parseInt(e,10);else return null;return Number.isNaN(r)||r<0||r>4294967295?null:[r>>>24&255,r>>>16&255,r>>>8&255,r&255].join(".")}return null}function Lgt(e){if(Ngt(e)!==6)return null;const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);let r;if(t){const n=UM(t[1]);if(!n)return null;const o=n.split(".").map(a=>parseInt(a,10)),s=(o[0]<<8|o[1]).toString(16),i=(o[2]<<8|o[3]).toString(16);r=["0","0","0","0","0","ffff",s,i]}else{const[n,o=""]=e.split("::"),s=n?n.split(":"):[],i=o?o.split(":"):[],a=8-s.length-i.length;if(a<0)return null;r=[...s,...Array(a).fill("0"),...i]}return r.length!==8?null:r.map(n=>n.toLowerCase().padStart(4,"0")).join(":")}function $gt(e){const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(t)return UM(t[1]);const r=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(r){const n=parseInt(r[1],16),o=parseInt(r[2],16);return Number.isNaN(n)||Number.isNaN(o)||n>65535||o>65535?null:[n>>8&255,n&255,o>>8&255,o&255].join(".")}return null}function Fgt(e){const[t,r,n,o]=e.split(".").map(s=>parseInt(s,10));return(t<<24|r<<16|n<<8|o)>>>0}function RE(e){const t=Fgt(e);for(const[r,n]of qgt){const o=Fgt(r),s=n===0?0:4294967295<<32-n>>>0;if((t&s)===(o&s))return!0}return!1}function Ugt(e){return Ggt.some(t=>t.length===39?e===t:e.startsWith(t))}function Bgt(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function zgt(e){const t=UM(e);if(t)return RE(t)?`IPv4 ${e} \u2192 ${t} is in a blocked range`:null;if(e.includes(":")){const r=$gt(e);if(r)return RE(r)?`IPv4-mapped IPv6 ${e} \u2192 ${r} is in a blocked range`:null;const n=Lgt(e);return n?Ugt(n)?`IPv6 ${e} is in a blocked range`:null:`IPv6 ${e} could not be parsed`}return"not-an-ip"}async function Of(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${t.protocol}//" in "${e}"`);const r=Bgt(t.hostname).toLowerCase(),n=zgt(r);if(n!==null){if(n!=="not-an-ip")throw new Error(`URL "${e}" rejected: ${n}`);await jgt(e,r)}}async function jgt(e,t){const[r,n]=await Promise.allSettled([bW(t,{family:4,all:!0}),bW(t,{family:6,all:!0})]),o=[],s=[];let i=!1;if(r.status==="fulfilled"){i=!0;for(const a of r.value)o.push(a.address)}if(n.status==="fulfilled"){i=!0;for(const a of n.value)s.push(a.address)}if(!i){const a=r.status==="rejected"?r.reason instanceof Error?r.reason.message:String(r.reason):"ok",l=n.status==="rejected"?n.reason instanceof Error?n.reason.message:String(n.reason):"ok";throw new Error(`URL "${e}" rejected: hostname ${t} could not be resolved (A: ${a}; AAAA: ${l})`)}for(const a of o)if(RE(a))throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv4 in blocked range)`);for(const a of s){const l=zgt(a.toLowerCase());if(l&&l!=="not-an-ip")throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv6 ${l})`)}return{v4:o,v6:s}}async function kSr(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${t.protocol}//" in "${e}"`);const r=Bgt(t.hostname).toLowerCase(),n=UM(r);if(n){if(RE(n))throw new Error(`URL "${e}" rejected: IPv4 ${r} \u2192 ${n} is in a blocked range`);return{url:e,ip:n,family:4,addresses:[{ip:n,family:4}]}}if(r.includes(":")){const l=$gt(r);if(l){if(RE(l))throw new Error(`URL "${e}" rejected: IPv4-mapped IPv6 ${r} \u2192 ${l} is in a blocked range`);return{url:e,ip:l,family:4,addresses:[{ip:l,family:4}]}}const c=Lgt(r);if(!c)throw new Error(`URL "${e}" rejected: IPv6 ${r} could not be parsed`);if(Ugt(c))throw new Error(`URL "${e}" rejected: IPv6 ${r} is in a blocked range`);return{url:e,ip:r,family:6,addresses:[{ip:r,family:6}]}}const{v4:o,v6:s}=await jgt(e,r),i=[...o.map(l=>({ip:l,family:4})),...s.map(l=>({ip:l,family:6}))],a=i[0];if(!a)throw new Error(`URL "${e}" rejected: hostname ${r} resolved to an empty address set`);return{url:e,ip:a.ip,family:a.family,addresses:i}}var qgt,Ggt,Nf=C({"src/lib/utils/ssrfGuard.ts"(){"use strict";ySr(),xSr(),qgt=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.168.0.0",16],["198.18.0.0",15],["100.100.100.200",32],["224.0.0.0",4],["240.0.0.0",4]],Ggt=["0000:0000:0000:0000:0000:0000:0000:0000","0000:0000:0000:0000:0000:0000:0000:0001","fc","fd","fe8","fe9","fea","feb"]}}),Hgt={};de(Hgt,{createAnnotatedTool:()=>Wgt,filterToolsByAnnotations:()=>Ygt,getAnnotationSummary:()=>Zgt,getToolSafetyLevel:()=>Jgt,inferAnnotations:()=>Nd,isSafeToRetry:()=>CW,mergeAnnotations:()=>SW,requiresConfirmation:()=>Kgt,validateAnnotations:()=>Vgt});function Nd(e){const t=e.name,r=e.description.toLowerCase(),n={},o=(c,u)=>new RegExp(`\\b${u}\\b`,"i").test(c)?!0:c.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[_-]/).some(m=>m===u.toLowerCase());return["get","list","read","fetch","query","search","find","show","display","view","retrieve","check","inspect","look"].some(c=>o(r,c)||o(t,c))&&(n.readOnlyHint=!0),["delete","remove","drop","destroy","clear","purge","erase","wipe","truncate","reset"].some(c=>o(r,c)||o(t,c))&&(n.destructiveHint=!0,n.requiresConfirmation=!0),["set","update","put","upsert","replace"].some(c=>o(r,c)||o(t,c))&&!n.destructiveHint&&(n.idempotentHint=!0),["complex","analyze","process","generate","transform","compute","calculate"].some(c=>o(r,c)||o(t,c))?n.complexity="complex":r.length>100?n.complexity="medium":n.complexity="simple",n}function SW(...e){const t={};for(const r of e)if(r){const n=t.tags?[...t.tags]:[];if(Object.assign(t,r),n.length>0||r.tags){const o=r.tags??[];t.tags=[...new Set([...n,...o])]}}return t}function Vgt(e){const t=[];if(e.readOnlyHint&&e.destructiveHint&&t.push("Tool cannot be both readOnly and destructive - these are conflicting hints"),e.rateLimitHint!==void 0&&(e.rateLimitHint<0||!Number.isFinite(e.rateLimitHint))&&t.push("rateLimitHint must be a non-negative number"),e.estimatedDuration!==void 0&&(e.estimatedDuration<0||!Number.isFinite(e.estimatedDuration))&&t.push("estimatedDuration must be a non-negative number"),e.costHint!==void 0&&(e.costHint<0||!Number.isFinite(e.costHint))&&t.push("costHint must be a non-negative number"),e.tags){for(const r of e.tags)if(typeof r!="string"||r.length===0){t.push("All tags must be non-empty strings");break}}return t}function Wgt(e){const t=Nd(e),r=SW(t,e.annotations);return{...e,annotations:r}}function Kgt(e){return!!(e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)}function CW(e){return!!(e.annotations?.idempotentHint||e.annotations?.readOnlyHint)}function Jgt(e){return e.annotations?.destructiveHint?"dangerous":e.annotations?.readOnlyHint?"safe":(e.annotations?.idempotentHint,"moderate")}function Ygt(e,t){return e.filter(r=>{const n=r.annotations??{};return t(n)})}function Zgt(e){const t=[];return e.title&&t.push(e.title),e.readOnlyHint&&t.push("read-only"),e.destructiveHint&&t.push("DESTRUCTIVE"),e.idempotentHint&&t.push("idempotent"),e.requiresConfirmation&&t.push("requires confirmation"),e.complexity&&t.push(`${e.complexity} complexity`),e.estimatedDuration!==void 0&&t.push(`~${e.estimatedDuration}ms`),e.tags?.length&&t.push(`tags: ${e.tags.join(", ")}`),t.length>0?`[${t.join(" | ")}]`:"[no annotations]"}var PE=C({"src/lib/mcp/toolAnnotations.ts"(){"use strict"}}),xW={};de(xW,{TOOL_COMPATIBILITY:()=>RW,batchConvertToMCP:()=>eyt,batchConvertToNeuroLink:()=>tyt,createToolFromFunction:()=>ryt,mcpProtocolToolToServerTool:()=>Xgt,mcpToolToNeuroLink:()=>kW,neuroLinkToolToMCP:()=>AW,sanitizeToolName:()=>IW,serverToolToMCPProtocol:()=>Qgt,validateToolName:()=>nyt});function AW(e,t={}){const{inferAnnotations:r=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:s}=t,i=s?`${s}_${e.name}`:e.name,a=r?Nd({name:e.name,description:e.description}):{},l={...n,...a};e.tags?.length&&(l.tags=[...new Set([...l.tags??[],...e.tags])]);const c=e.parameters??{type:"object",properties:{}},u=o?{...e.metadata}:{};return e.category&&(u.category=e.category),e.isAsync!==void 0&&(u.isAsync=e.isAsync),{name:i,description:e.description,inputSchema:c,annotations:l,execute:e.execute,metadata:u}}function kW(e,t={}){const{removeNamespacePrefix:r}=t;let n=e.name;return r&&e.name.startsWith(`${r}_`)&&(n=e.name.slice(r.length+1)),{name:n,description:e.description,parameters:e.inputSchema,execute:e.execute,category:e.metadata?.category,tags:e.annotations?.tags,metadata:e.metadata}}function Xgt(e,t,r={}){const{inferAnnotations:n=!0,defaultAnnotations:o={}}=r,s=e.annotations??{},i=n?Nd({name:e.name,description:e.description??""}):{},a={...o,...i,title:s.title??i.title??o.title,readOnlyHint:s.readOnlyHint??i.readOnlyHint??o.readOnlyHint,destructiveHint:s.destructiveHint??i.destructiveHint??o.destructiveHint,idempotentHint:s.idempotentHint??i.idempotentHint??o.idempotentHint,openWorldHint:s.openWorldHint??i.openWorldHint??o.openWorldHint};return{name:e.name,description:e.description??"No description provided",inputSchema:e.inputSchema,annotations:a,execute:t}}function Qgt(e){const t={};e.annotations?.title&&(t.title=e.annotations.title),e.annotations?.readOnlyHint!==void 0&&(t.readOnlyHint=e.annotations.readOnlyHint),e.annotations?.destructiveHint!==void 0&&(t.destructiveHint=e.annotations.destructiveHint),e.annotations?.idempotentHint!==void 0&&(t.idempotentHint=e.annotations.idempotentHint),e.annotations?.openWorldHint!==void 0&&(t.openWorldHint=e.annotations.openWorldHint);const r=e.inputSchema??{type:"object",properties:{}};return{name:e.name,description:e.description,inputSchema:{type:"object",properties:r.properties??{},required:"required"in r?r.required:void 0},annotations:Object.keys(t).length>0?t:void 0}}function eyt(e,t={}){return e.map(r=>AW(r,t))}function tyt(e,t={}){return e.map(r=>kW(r,t))}function ryt(e,t,r,n){const o=Nd({name:e,description:t});return{name:e,description:t,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(s,i)=>await Nt(r(s,i),3e4,`Tool '${e}' execution timed out after 30000ms`),metadata:n?.metadata}}function nyt(e){const t=[];return!e||typeof e!="string"?t.push("Tool name is required and must be a string"):(e.length>64&&t.push("Tool name must be 64 characters or less"),/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e)||t.push("Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens")),{valid:t.length===0,errors:t}}function IW(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return/^[a-zA-Z_]/.test(t)||(t=`_${t}`),t.length>64&&(t=t.slice(0,64)),t}var RW,BM=C({"src/lib/mcp/toolConverter.ts"(){"use strict";PE(),Kn(),RW={MCP_2024_11_05:{annotations:!0,inputSchema:!0,outputSchema:!1,streamingResults:!1,batchExecution:!1},NEUROLINK:{annotations:!0,inputSchema:!0,outputSchema:!0,streamingResults:!0,batchExecution:!0,categories:!0,tags:!0}}}}),$a,PW,zM,MW,Vc,ME,DW,oyt,syt,OW,NW,iyt,ayt,lyt,cyt,uyt,LW,dyt,$W,pyt,DE,FW,myt,Tm=C({"src/lib/providers/openaiChatCompletionsClient.ts"(){"use strict";t5(),BM(),em(),qi(),Qs(),$a=e=>e.replace(/\/+$/,""),PW=/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/,zM=(e,t)=>{if(e.every(o=>PW.test(o)&&!t?.has(o)))return;const r=new Map,n=new Map;for(const o of e){let s=PW.test(o)?o:IW(o);if(n.has(s)||t?.has(s)){let i=2,a;do{const l=`_${i}`;a=`${s.slice(0,64-l.length)}${l}`,i++}while(n.has(a)||t?.has(a));s=a}r.set(o,s),n.set(s,o)}return{toWire:r,fromWire:n}},MW=(e,t,r)=>{let n=0;for(const o of e){const s=typeof o.content=="string"?o.content:Vc(o.content);n+=pr(s,r)+hl;const i=o.tool_calls;i&&(n+=pr(Vc(i),r))}return t&&t.length>0&&(n+=pr(Vc(t),r)),n},Vc=e=>{try{return JSON.stringify(e??"")}catch{return String(e??"")}},ME=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return"{}"}},DW=e=>{if(e==null)return"";if(typeof e=="string")return e;if(typeof e!="object")return String(e);const t=e;switch(t.type){case"text":return typeof t.value=="string"?t.value:Vc(t.value);case"json":return Vc(t.value);case"execution-denied":return`Tool execution denied${t.reason?`: ${t.reason}`:""}`;case"error-text":return typeof t.value=="string"?t.value:Vc(t.value);case"error-json":return Vc(t.value);case"content":return Array.isArray(t.value)?t.value.map(r=>r&&typeof r=="object"&&r.type==="text"?String(r.text??""):"").filter(r=>r.length>0).join(`
|
|
1070
|
+
${t}`:t:e}async function OEr(e,t){const r=[],n=[];let o=0,s=0,i=0,a=0,l;for await(const c of e){const u=c,m=u.candidates?.[0],f=m?.finishReason;typeof f=="string"&&(l=f);const g=m?.content;if(g&&Array.isArray(g.parts))for(const v of g.parts)r.push(v),typeof v.text=="string"&&v.text.length>0&&t.push({content:v.text});c.functionCalls&&n.push(...c.functionCalls);const y=u.usageMetadata;y&&(o=Math.max(o,y.promptTokenCount||0),s=Math.max(s,y.candidatesTokenCount||0),i=Math.max(i,y.cachedContentTokenCount||0),a=Math.max(a,y.thoughtsTokenCount||0))}return{rawResponseParts:r,stepFunctionCalls:n,finishReason:l,inputTokens:o,outputTokens:s,cacheReadTokens:i,reasoningTokens:a}}function RM(e){for(let t=e.length-1;t>=0;t--){const r=e[t];if(r!=null&&typeof r=="object"&&"thoughtSignature"in r&&typeof r.thoughtSignature=="string")return r.thoughtSignature}}function NEr(e){return e.filter(t=>typeof t.text=="string").map(t=>t.text).join("")}function agt(e,t,r,n,o){return t>=r&&!n?(h.warn(`${e} Tool call loop terminated after reaching maxSteps (${r}). Model was still calling tools. Using accumulated text from last step.`),o||wm(r,0)):n}function rc(e){if(!e)return!1;const t=e;return t.name==="AbortError"||typeof t.message=="string"&&/abort/i.test(t.message)||typeof DOMException<"u"&&e instanceof DOMException&&t.code===20}function wm(e,t){return`${t>0?`I gathered information across ${t} tool call${t===1?"":"s"} but `:"I "}reached the ${e}-step limit for a single turn before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function nc(e){return`${e>0?`I gathered information across ${e} tool call${e===1?"":"s"} but `:"I "}had to stop because the gathered material filled this turn's context window before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function lgt(e){const t=Math.max(0,Math.round(e/1e3)),r=Math.floor(t/60),n=t%60;return r>0?`${r}m ${n}s`:`${n}s`}function LEr(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop after ${lgt(e)} \u2014 this turn hit its processing time limit.${r} ask me to continue and I'll pick up from there.`}function $Er(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop because this turn made no progress for ${lgt(e)} \u2014 a tool or model call appears to be stuck.${r} ask me to continue and I'll pick up from there.`}function FEr(e){return`This turn was stopped before I could finish.${e>0?` I completed ${e} tool call${e===1?"":"s"} before stopping.`:""}`}function PM(e){return"NOTE: processing time for this turn is nearly up. Consolidate what you have and "+(e?"call final_result with your best answer now.":"provide your final answer now.")}function MM(e){return e.timedOut?"time-limit":e.stalled?"stalled":e.wasAborted?"aborted":e.contextCappedWithoutAnswer?"context-cap":e.cappedWithoutAnswer?"step-cap":e.finishReason==="error"?"provider-error":"completed"}function DM(e){const t=Date.now(),r=u=>u!==void 0&&Number.isFinite(u)&&u>0,n=r(e.turnTimeoutMs)?e.turnTimeoutMs:r(e.defaultTurnTimeoutMs)?e.defaultTurnTimeoutMs:void 0,o=r(e.turnTimeoutMs)?e.wrapupTimeLeadMs??JR:void 0;let s=!1,i=!1,a=t,l,c;if(n!==void 0&&(l=setTimeout(()=>{s=!0,e.onDeadline("timeout")},n),l.unref?.()),r(e.stallTimeoutMs)){const u=e.stallTimeoutMs,d=Math.min(Math.max(1e3,Math.floor(u/4)),15e3);c=setInterval(()=>{!i&&!s&&Date.now()-a>=u&&(i=!0,e.onDeadline("stall"))},d),c.unref?.()}return{get timedOut(){return s},get stalled(){return i},get expired(){return s||i},get turnTimeoutMs(){return n},elapsedMs(){return Date.now()-t},noteProgress(){a=Date.now()},shouldNudgeWrapup(){if(n===void 0||o===void 0)return!1;const u=n-(Date.now()-t);return u>0&&u<=o},dispose(){l&&clearTimeout(l),c&&clearInterval(c)}}}function zv(e,t=VT){const r=Math.floor(e*t);let n=0,o=0;return{get thresholdTokens(){return r},get projectedNextPromptTokens(){return n+o},noteUsage(s,i){s>0&&(n=s,o=Math.max(0,i))},noteAppendedChars(s){s>0&&(o+=Math.ceil(s/4))},resetAfterReclaim(){n=0,o=0},shouldStop(){return n>0&&n+o>=r}}}function UEr(e,t,r){e.push({role:"model",parts:t.length>0?t:r.map(n=>({functionCall:n}))})}function cgt(e){const t=$s(e,"openApi3"),r=ln(t);return r.$schema&&delete r.$schema,bi(r)}function OM(e,t){if(!t||t.length===0)return;const r=new Map,n=[];let o=0;const s=a=>`${o}:${a??"undefined"}`,i=a=>{const l=s(a),c=r.get(l);if(c)return c;const u={type:"tool_step",callParts:[],resultParts:[]};return r.set(l,u),n.push(u),u};for(const a of t){if(a.role==="tool_call"){const u=i(a.metadata?.stepIndex),d={functionCall:{name:a.tool||"unknown",args:a.args||{}}};a.metadata?.thoughtSignature&&(d.thoughtSignature=a.metadata.thoughtSignature),u.callParts.push(d);continue}if(a.role==="tool_result"){const u=i(a.metadata?.stepIndex);let d;try{d=a.content!==void 0&&a.content!==null?{result:JSON.parse(a.content)}:{result:"success"}}catch{d={result:a.content??"success"}}u.resultParts.push({functionResponse:{name:a.tool||"unknown",response:d}});continue}const l=a.role==="assistant"?"model":a.role;if(l!=="user"&&l!=="model"||!a.content||a.content.trim().length===0)continue;o++;const c={text:a.content};a.metadata?.thoughtSignature&&(c.thoughtSignature=a.metadata.thoughtSignature),n.push({type:"regular",role:l,parts:[c]})}for(const a of n){if(a.type==="regular"){e.push({role:a.role,parts:a.parts});continue}if(a.callParts.length===0){a.resultParts.length>0&&h.debug("[GoogleNativeGemini3] Dropping orphan tool_result segment with no matching tool_call rows",{resultCount:a.resultParts.length});continue}e.push({role:"model",parts:a.callParts}),a.resultParts.length>0&&e.push({role:"user",parts:a.resultParts})}}async function cW(e,t,r="[GeminiNative]"){if(!(!t||t.length===0))for(const n of t){const o=n.filename.split(/[\\/]/).pop()??n.filename,s=o.lastIndexOf("."),i=s>0?o.slice(s):".bin",a=await emt(n.buffer,n.mimeType,i);if(l9(a.mimeType)){h.warn(`${r} Skipping native audio for ${o}: ${a.mimeType} is not accepted and could not be converted. The metadata summary was still included.`);continue}e.push({inlineData:{mimeType:a.mimeType,data:a.buffer.toString("base64")}}),h.debug(`${r} Added native audio part for ${o} (${a.mimeType})`)}}async function ugt(e,t,r="[GeminiNative]"){const o=[{text:typeof t=="string"?t:e?.text??""}];if(e?.pdfFiles&&e.pdfFiles.length>0){h.debug(`${r} Processing ${e.pdfFiles.length} PDF(s)`);for(const s of e.pdfFiles){let i;typeof s=="string"?Gi(s)?i=Hi(s):i=Buffer.from(s,"base64"):i=s,o.push({inlineData:{mimeType:"application/pdf",data:i.toString("base64")}})}}if(e?.images&&e.images.length>0){h.debug(`${r} Processing ${e.images.length} image(s)`);for(const s of e.images){const i=s&&typeof s=="object"&&!Buffer.isBuffer(s)?s.data:s;let a,l="image/jpeg";if(typeof i=="string")if(Gi(i)){a=Hi(i);const c=xv(i).toLowerCase();c===".png"?l="image/png":c===".gif"?l="image/gif":c===".webp"&&(l="image/webp")}else if(i.startsWith("data:")){const c=i.match(/^data:([^;]+);base64,(.+)$/);if(c)l=c[1],a=Buffer.from(c[2],"base64");else continue}else if(i.startsWith("http://")||i.startsWith("https://"))try{const c=await fetch(i);if(!c.ok){h.warn(`${r} Image fetch failed: ${c.status} ${c.statusText}, skipping`,{url:i});continue}const u=await c.arrayBuffer();a=Buffer.from(u);const d=c.headers.get("content-type");d&&d.startsWith("image/")&&(l=d.split(";")[0])}catch(c){h.warn(`${r} Image URL fetch threw, skipping: ${c instanceof Error?c.message:String(c)}`,{url:i});continue}else a=Buffer.from(i,"base64");else a=i;a&&o.push({inlineData:{mimeType:l,data:a.toString("base64")}})}}return await cW(o,e?.nativeAudioFiles,r),o}var jv,dgt,NM,uW,LM=C({"src/lib/providers/googleNativeGemini3/utils.ts"(){"use strict";ji(),Jo(),Gr(),Fo(),nmt(),W(),em(),qi(),rgt(),jv=class extends Map{resultCache=new Map;get(e){const t=super.get(e);if(!t)return t;const r=this.resultCache;return async(o,s)=>{const i=`${e}::${REr(o)}`;if(r.has(i))return h.warn(`[DedupExecuteMap] Tool "${e}" re-requested with identical arguments in the same turn \u2014 reusing the previous result instead of re-executing.`),r.get(i);const a=await t(o,s);return r.set(i,a),a}}},dgt=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/,NM=128,uW=100}});function pgt(e){const t=n=>e.declarations?.originalNameMap?.get(n)??n,r=n=>{const o=e.declarations?.originalNameMap;if(!o)return n;for(const[s,i]of o)if(i===n)return s;return n};return{providerLabel:e.providerLabel,maxSteps:e.maxSteps,...e.toolFailureBreaker?{toolFailureBreaker:e.toolFailureBreaker}:{},buildStepRequest(n,o){return e.declarations&&DEr(e.liveTools,e.declarations),{raw:e.buildRequest(n,o)}},...e.planReclaim?{planReclaim:(n,o)=>{const s=e.planReclaim?.(n,o);return s?{conversation:s}:void 0}}:{},...e.enableMalformedRetry&&e.buildMalformedRetryNote?{isMalformedStep:n=>n.toolCalls.length===0&&!n.text&&n.rawStopReason==="MALFORMED_FUNCTION_CALL",buildMalformedRetryNote:e.buildMalformedRetryNote}:{},resolveToolOnMiss:n=>{const s=e.liveTools?.[n]?.execute;if(s)return{execute:async(i,a)=>s(i,a)}},async executeStep(n,o,s){const i=await e.sendStep(n.raw,s),a=e.collectStep?await e.collectStep(i,o):await OEr(i,{push:u=>o.push(u)});e.noteUsage?.(a.inputTokens,a.outputTokens);const l=NEr(a.rawResponseParts),c=a.stepFunctionCalls.map((u,d)=>({id:`${e.providerLabel}_${d}_${u.name}`,name:t(u.name),args:u.args}));return{text:l,toolCalls:c,usage:{inputTokens:a.inputTokens,outputTokens:a.outputTokens,...a.cacheReadTokens?{cacheReadTokens:a.cacheReadTokens}:{},...a.reasoningTokens?{reasoningTokens:a.reasoningTokens}:{}},rawStopReason:a.finishReason,raw:{rawResponseParts:a.rawResponseParts,stepFunctionCalls:a.stepFunctionCalls}}},buildToolResultMessages(n,o,s){const i=[...n];return UEr(i,o.raw.rawResponseParts,o.raw.stepFunctionCalls),i.push({role:"user",parts:s.map(a=>({functionResponse:{name:r(a.name),response:a.error?{error:a.error}:{result:a.output}}}))}),i},mapFinishReason(n,o){const s=lW(n);return o&&s==="stop"?"tool-calls":s}}}var BEr=C({"src/lib/core/geminiLoopAdapter.ts"(){"use strict";LM()}});function qv(){const e=[];let t=!1,r,n=!1,o=null;function s(){if(o){const d=o;o=null,d()}}function i(d){t||(e.push(d),s())}function a(){t=!0,s()}function l(d){t=!0,r=d,n=!0,s()}let c=0;async function*u(){try{for(;;)if(c<e.length)yield e[c++],c>1024&&c*2>=e.length&&(e.splice(0,c),c=0);else if(t){if(n)throw r instanceof Error?r:new Error(String(r));return}else await new Promise(d=>{o=d})}finally{t=!0,e.length=0,o?.()}}return{push:i,close:a,error:l,iterable:u()}}var Gv=C({"src/lib/core/streamChannel.ts"(){"use strict"}});function zEr(e,t){return{inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,cacheReadTokens:(e.cacheReadTokens??0)+(t.cacheReadTokens??0)||void 0,cacheWriteTokens:(e.cacheWriteTokens??0)+(t.cacheWriteTokens??0)||void 0,reasoningTokens:(e.reasoningTokens??0)+(t.reasoningTokens??0)||void 0}}function kE(e,t,r){const n=qv(),o=new AbortController,s=()=>o.abort();r.abortSignal?.addEventListener("abort",s),r.abortSignal?.aborted&&o.abort();const i=new Map;let a=!1;const l=(async()=>{let c=t,u={inputTokens:0,outputTokens:0},d="",m="",f;const g=[],y=[];let v=!1;try{for(let b=0;b<e.maxSteps&&!o.signal.aborted;b++){if(e.planReclaim){const I=e.planReclaim(c,b);I&&(c=I.conversation)}const T=e.buildStepRequest(c,b);let x=!1;const k={push:I=>{x=!0,n.push(I)}};let R;try{R=await Hy(async()=>{x=!1;try{return await e.executeStep(T,k,o.signal)}catch(I){throw x?new dW(I):I}},void 0,`${e.providerLabel}.step`)}catch(I){throw I instanceof dW?I.cause:I}if(u=zEr(u,R.usage),f=R.rawStopReason,m=R.text||m,e.isMalformedStep?.(R)&&!a&&!o.signal.aborted){a=!0,h.warn(`[${e.providerLabel}] Malformed function call at step ${b+1}/${e.maxSteps}; retrying once.`),c=e.buildMalformedRetryNote?.(c)??c;continue}if(R.toolCalls.length===0){d=R.text||d;break}b===e.maxSteps-1&&(v=!0);const P=[];for(const I of R.toolCalls){g.push(I);const A=e.toolFailureBreaker,M=A?i.get(I.name):void 0;if(A&&M&&M.count>=A.maxRetries){const D={error:`TOOL_PERMANENTLY_FAILED: "${I.name}" has failed ${M.count} times. Last error: ${M.lastError}.`,status:"permanently_failed",do_not_retry:!0};P.push({...I,output:D,error:D.error,permanentlyFailed:!0}),y.push({id:I.id,name:I.name,input:I.args,output:D,error:D.error});continue}const O=r.tools?.[I.name],N=O?.execute?O:e.resolveToolOnMiss?.(I.name)??O;if(!N?.execute){const D=A?{error:`TOOL_NOT_FOUND: "${I.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${I.name}`};P.push({...I,output:D,error:D.error,permanentlyFailed:!!A}),y.push({id:I.id,name:I.name,input:I.args,output:D,error:D.error});continue}try{const D=await N.execute(I.args,{toolCallId:I.id,abortSignal:o.signal});P.push({...I,output:D}),y.push({id:I.id,name:I.name,input:I.args,output:D})}catch(D){const F=D instanceof Error?D.message:String(D);if(A){const $=i.get(I.name)??{count:0,lastError:""};$.count++,$.lastError=F,i.set(I.name,$)}const U={error:F,status:"failed"};P.push({...I,output:U,error:F}),y.push({id:I.id,name:I.name,input:I.args,output:U,error:F})}}c=e.buildToolResultMessages(c,R,P)}const w=e.mapFinishReason(f,v);return{text:d||(v?m:""),toolCalls:g,toolExecutions:y,usage:u,finishReason:w,rawStopReason:f,conversation:c}}catch(w){throw n.error(w),w}finally{n.close(),r.abortSignal?.removeEventListener("abort",s)}})();return{stream:n.iterable,resultPromise:l}}var dW,pW=C({"src/lib/core/loopEngine.ts"(){"use strict";Gv(),W(),Ph(),dW=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e)),this.cause=e}cause}}});function jEr(e){return e?.kind==="toolCall"||e?.kind==="toolResult"}function qEr(e,t,r){const n=[];let o=t;for(;o<r;){if(!jEr(e[o])){o++;continue}const s=o;for(;o<e.length&&e[o].kind==="toolCall";)o++;for(;o<e.length&&e[o].kind==="toolResult";)o++;if(o>r)break;n.push({start:s,end:o})}return n}function mW(e,t){const{availableInputTokens:r,fixedOverheadTokens:n,thresholdRatio:o=VT,lowWaterRatio:s=mgt,protectedTailCount:i=hgt,calibration:a=1}=t,l=a>0?a:1,c=Math.floor(r*o/l),u=Math.floor(r*s/l);let d=n;for(const w of e)d+=w.tokens;if(d<=c)return{fire:!1,truncate:[],drop:[],projectedTokens:d};const m=1,f=Math.max(m,e.length-i),g=[],y=new Set;for(let w=m;w<f&&d>u;w++){const b=e[w];if(b.kind!=="toolResult"||b.previewTokens===void 0)continue;const T=b.tokens-b.previewTokens;T<=0||(g.push(w),d-=T)}if(d>u){const w=qEr(e,m,f);for(const b of w){if(d<=u)break;for(let T=b.start;T<b.end;T++){const x=e[T],k=g.includes(T)?x.previewTokens??x.tokens:x.tokens;d-=k,y.add(T)}}}const v=g.filter(w=>!y.has(w));return{fire:v.length>0||y.size>0,truncate:v,drop:[...y].sort((w,b)=>w-b),projectedTokens:d}}var mgt,hgt,hW=C({"src/lib/context/loopGuardCore.ts"(){"use strict";Fo(),mgt=.6,hgt=4}});function fgt(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function ggt(e,t){return Array.isArray(e.parts)&&e.parts.some(r=>r&&typeof r=="object"&&t in r)}function GEr(e){return ggt(e,"functionResponse")}function fW(e){const{preview:t}=Wl(e,{maxBytes:gW,maxLines:vgt});return t}function HEr(e,t){return pr(fgt(e.parts),t)+hl}function VEr(e,t){return e.map(r=>{const n=HEr(r,t);if(GEr(r)){const o=fgt(r.parts),s=o.length>gW?pr(fW(o),t)+hl:n;return{kind:"toolResult",tokens:n,...s<n?{previewTokens:s}:{}}}return ggt(r,"functionCall")?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function ygt(e){const{contents:t,availableInputTokens:r,fixedOverheadTokens:n=0,provider:o,observedPromptTokens:s}=e,i=VEr(t,o);let a=1;if(s&&s>0){const c=n+i.reduce((u,d)=>u+d.tokens,0);c>0&&(a=Math.min(3,Math.max(1,s/c)))}const l=mW(i,{availableInputTokens:r,fixedOverheadTokens:n,calibration:a});if(l.fire)return h.info("[GeminiLoopGuard] Reclaiming agent-loop context",{provider:o,contents:t.length,toolResponsesTruncated:l.truncate.length,contentsDropped:l.drop.length,projectedTokens:l.projectedTokens,calibration:a}),l}var gW,vgt,yW,_gt=C({"src/lib/context/geminiLoopGuard.ts"(){"use strict";Qs(),ef(),hW(),W(),gW=2048,vgt=60,yW="[Earlier tool exchanges were removed to fit the context window.]"}}),IE=C({"src/lib/utils/async/index.ts"(){"use strict";Kn()}}),wgt=C({"src/lib/providers/googleNativeGemini3/index.ts"(){"use strict";LM()}}),Dd,Tgt=C({"src/lib/providers/anthropic/cacheControl.ts"(){"use strict";Dd=e=>e?.providerOptions?.anthropic?.cacheControl?.type==="ephemeral"?{type:"ephemeral"}:void 0}});function Hv(e,t){if(t==="functionDeclarations")return ngt(e);const r=Object.entries(e??{});if(r.length!==0)return r.map(([n,o])=>{const s=o,i=s.inputSchema??s.parameters,a=i?$s(i):{type:"object",properties:{}},l=Dd(o);return{name:n,...s.description?{description:s.description}:{},input_schema:a,...l?{cache_control:l}:{}}})}var vW=C({"src/lib/core/nativeToolFormat.ts"(){"use strict";LM(),Tgt(),qi()}});function WEr(e,t){try{const[r,n]=t.split("/"),o=parseInt(n,10);if(isNaN(o)||o<0||o>32)return!1;const s=c=>{const u=c.split(".").map(Number);return(u[0]<<24)+(u[1]<<16)+(u[2]<<8)+u[3]},i=s(e),a=s(r),l=-1<<32-o>>>0;return(i&l)===(a&l)}catch{return!1}}function KEr(e,t){const r=t||process.env.NO_PROXY||process.env.no_proxy;if(!r)return!1;try{const n=new URL(e),o=n.hostname.toLowerCase(),s=n.port||(n.protocol==="https:"?"443":"80"),i=r.split(",").map(a=>a.trim()).filter(Boolean);for(const a of i){const l=a.toLowerCase();if(l==="*")return!0;if(l.startsWith(".")){const c=l.slice(1);if(o.endsWith(c)||o===c)return!0}else if(l.includes(":")){const[c,u]=l.split(":");if(o===c&&s===u)return!0}else if(l.includes("/")){if(/^\d{1,3}(\.\d{1,3}){3}$/.test(o)&&WEr(o,l))return!0}else if(o===l)return!0}return!1}catch(n){return h.warn("[Proxy] Error in NO_PROXY bypass logic",{targetUrl:e,error:n}),!1}}var JEr=C({"src/lib/proxy/utils/noProxyUtils.ts"(){"use strict";W()}});async function YEr(){try{return(await Promise.resolve().then(()=>(ym(),O9))).getLangfuseContext?.()}catch{return}}function ZEr(e,t){const r=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers){const n=new Headers(t.headers);for(const[o,s]of n.entries())r.set(o,s)}return r}async function bgt(e,t){const r={};Qg.inject(Tr.active(),r);const n=await YEr();if(n?.sessionId&&(r["x-neurolink-session-id"]=n.sessionId),n?.userId&&(r["x-neurolink-user-id"]=n.userId),n?.conversationId&&(r["x-neurolink-conversation-id"]=n.conversationId),Object.keys(r).length===0)return t??{};const o=ZEr(e,t);for(const[s,i]of Object.entries(r))o.has(s)||o.set(s,i);return{...t,headers:o}}function XEr(e){try{const t=typeof e=="string"?e:e instanceof URL?e.href:e.url;return new URL(t).hostname}catch{return"[unknown]"}}function QEr(e){let t=e;for(let r=0;r<5&&t;r++){const n=t;if(n.code&&dz.has(n.code)||n.message?.includes("socket hang up")||n.message?.includes("network socket disconnected")||n.message?.includes("other side closed"))return!0;t=n.cause}return!1}async function Egt(e,t,r=3,n=500){const o=XEr(e);return kgt.startActiveSpan("neurolink.http.fetchWithRetry",async s=>{s.setAttribute("http.request.max_retries",r),s.setAttribute("http.request.hostname",o),s.setAttribute("http.request.method",t?.method||"GET");let i=0;try{for(let a=0;a<=r;a++){i=a+1;try{const l=await fetch(e,t);return s.setAttribute("http.request.total_attempts",i),s.setAttribute("http.response.status_code",l.status),s.setStatus({code:je.OK}),l}catch(l){const c=QEr(l),u=l;if(!c||a===r)throw s.setAttribute("http.request.total_attempts",i),s.setStatus({code:je.ERROR,message:u?.message||u?.code||"fetchWithRetry final failure"}),s.recordException(l instanceof Error?l:new Error(String(l))),l;const d=n*Math.pow(2,a);s.addEvent("http.request.retry",{"retry.attempt":a+1,"retry.delay_ms":d,"retry.error":(u?.code||u?.message||String(l)).slice(0,256)}),h.debug(`[fetchWithRetry] Transient error (${u?.code||u?.message}), retrying in ${d}ms (attempt ${a+1}/${r})`),await new Promise(m=>setTimeout(m,d))}}throw new Error("fetchWithRetry exhausted")}finally{s.end()}})}function Sgt(e){if(!e)return{parsed:null,size:0,type:"empty"};if(typeof e=="string")try{return{parsed:JSON.parse(e),size:e.length,type:"json"}}catch{return{parsed:e,size:e.length,type:"text"}}return e instanceof ArrayBuffer?{parsed:"[ArrayBuffer]",size:e.byteLength,type:"arraybuffer"}:e instanceof Uint8Array?{parsed:"[Uint8Array]",size:e.length,type:"uint8array"}:{parsed:"[Stream]",size:-1,type:"stream"}}async function _W(e){const t={};e.headers.forEach((r,n)=>{t[n]=Igt.has(n.toLowerCase())?`${r.substring(0,4)}***`:r});try{const n=await e.clone().text();try{return{parsed:JSON.parse(n),size:n.length,type:"json",headers:t}}catch{return{parsed:n,size:n.length,type:"text",headers:t}}}catch{return{parsed:"[unable to read body]",size:-1,type:"error",headers:t}}}function eSr(e){try{const t=new URL(e),r={protocol:t.protocol,hostname:t.hostname,port:parseInt(t.port)||Cgt(t.protocol),cleanUrl:`${t.protocol}//${t.hostname}:${t.port||Cgt(t.protocol)}`};return t.username&&t.password&&(r.auth={username:decodeURIComponent(t.username),password:decodeURIComponent(t.password)}),r}catch(t){let r;try{const n=new URL(e);n.username="",n.password="",r=n.toString()}catch{r="[invalid-url]"}throw h.error("[Proxy] Failed to parse proxy URL",{proxyUrl:r,error:t}),new Error(`Invalid proxy URL: ${r}`,{cause:t})}}function Cgt(e){switch(e){case"http:":return 8080;case"https:":return 8080;case"socks4:":return 1080;case"socks5:":return 1080;default:return 8080}}function tSr(e){if(KEr(e))return h.debug("[Proxy] Bypassing proxy due to NO_PROXY",{targetUrl:e}),null;try{const t=new URL(e),r=process.env.HTTPS_PROXY||process.env.https_proxy,n=process.env.HTTP_PROXY||process.env.http_proxy,o=process.env.ALL_PROXY||process.env.all_proxy,s=process.env.SOCKS_PROXY||process.env.socks_proxy;return t.protocol==="https:"&&r?r:t.protocol==="http:"&&n?n:o||s||null}catch(t){return h.warn("[Proxy] Error selecting proxy URL",{targetUrl:e,error:t}),null}}async function rSr(e){const t=eSr(e);switch(h.debug("[Proxy] Creating proxy agent",{protocol:t.protocol,hostname:t.hostname,port:t.port,hasAuth:!!t.auth}),t.protocol){case"http:":case"https:":{const{ProxyAgent:r}=await Promise.resolve().then(()=>(Sv(),KH));return new r(e)}case"socks4:":case"socks5:":throw new Error("SOCKS proxy support requires 'proxy-agent' package. Install it with: npm install proxy-agent");default:throw new Error(`Unsupported proxy protocol: ${t.protocol}`)}}function fa(e){return Vv(e)??"NOT_SET"}function xgt(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}function nSr(){return async(e,t)=>{const r=await bgt(e,t),n=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,o=Date.now(),s=xgt(e);if(h.shouldLog("debug")){const{size:i,type:a}=Sgt(r?.body);h.debug("[Observability] HTTP request to LLM provider",{requestId:n,url:s,method:r?.method||"POST",bodySize:i,bodyType:a})}try{const i=await Egt(e,r);if(h.shouldLog("debug")){const{parsed:a,size:l,type:c,headers:u}=await _W(i);h.debug("[Observability] HTTP response from LLM provider",{requestId:n,url:s,status:i.status,statusText:i.statusText,durationMs:Date.now()-o,contentLength:l,hasContent:!!a,bodyType:c,responseHeaders:u})}return i}catch(i){throw h.debug("[Observability] HTTP request failed",{requestId:n,url:s,error:i instanceof Error?i.message:String(i),durationMs:Date.now()-o}),i}}}async function oSr(e,t,r){const{httpsProxy:n,httpProxy:o,allProxy:s,socksProxy:i,noProxy:a}=r;t=await bgt(e,t);const l=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,c=Date.now(),u=xgt(e);if(h.shouldLog("debug")){const{size:f,type:g}=Sgt(t?.body);h.debug("[Observability] HTTP request to LLM provider",{requestId:l,url:u,method:t?.method||"POST",bodySize:f,bodyType:g})}h.debug("[Proxy Fetch] ENHANCED REQUEST START",{requestId:l,targetUrl:u,timestamp:new Date().toISOString(),httpProxy:fa(o),httpsProxy:fa(n),allProxy:fa(s),socksProxy:fa(i),noProxy:a||"NOT_SET",initMethod:t?.method||"GET"});const d=e instanceof Request?e.clone():null;try{const f=tSr(u);if(f){const g=new URL(u);h.debug("[Proxy Fetch] \u{1F517} ENHANCED URL ANALYSIS",{requestId:l,targetUrl:u,urlHostname:g.hostname,urlProtocol:g.protocol,urlPort:g.port,selectedProxyUrl:fa(f),timestamp:new Date().toISOString()}),h.debug("[Proxy Fetch] \u{1F3AF} ENHANCED PROXY AGENT CREATION",{requestId:l,proxyUrl:fa(f),targetHostname:g.hostname,targetProtocol:g.protocol,aboutToCreateProxyAgent:!0,timestamp:new Date().toISOString()});const y=globalThis;y.__NL_PROXY_AGENT_CACHE__||(y.__NL_PROXY_AGENT_CACHE__=new Map);const v=y.__NL_PROXY_AGENT_CACHE__,w=QR("sha256").update(Vv(f)??f).digest("hex"),b=v.get(w)||await rSr(f);v.set(w,b),h.debug("[Proxy Fetch] \u2705 ENHANCED PROXY AGENT CREATED",{requestId:l,hasDispatcher:!!b,dispatcherType:typeof b,dispatcherConstructor:b?.constructor?.name||"unknown",timestamp:new Date().toISOString()});let T,x={...t};e instanceof Request?(T=e.url,x={method:e.method,headers:e.headers,body:e.body,...t}):T=e;const R=await(await Promise.resolve().then(()=>(Sv(),KH))).fetch(T,{...x,dispatcher:b});if(h.shouldLog("debug")){const{parsed:P,size:I,type:A,headers:M}=await _W(R);h.debug("[Observability] HTTP response from LLM provider",{requestId:l,url:u,status:R?.status,statusText:R?.statusText,durationMs:Date.now()-c,contentLength:I,hasContent:!!P,bodyType:A,proxied:!0,responseHeaders:M})}return h.debug("[Proxy Fetch] ENHANCED PROXY SUCCESS",{requestId:l,responseStatus:R?.status,responseOk:R?.ok,proxyUsed:!0,timestamp:new Date().toISOString()}),R}}catch(f){const g=f instanceof Error?f.message:String(f);h.debug("[Observability] HTTP request failed",{requestId:l,url:u,error:g,durationMs:Date.now()-c}),h.debug("[Proxy Fetch] ENHANCED ERROR ANALYSIS",{requestId:l,error:g,errorType:f instanceof Error?f.constructor.name:typeof f,willFallback:!0,timestamp:new Date().toISOString()}),h.warn(`[Proxy Fetch] Enhanced proxy failed (${g}), falling back to direct connection`)}h.debug("[Proxy Fetch] ENHANCED FALLBACK TO STANDARD FETCH",{requestId:l,fallbackReason:"No proxy configured or proxy failed",timestamp:new Date().toISOString()});const m=e instanceof Request?d??e:e;try{const f=await Egt(m,t);if(h.shouldLog("debug")){const{parsed:g,size:y,type:v,headers:w}=await _W(f);h.debug("[Observability] HTTP response from LLM provider",{requestId:l,url:u,status:f.status,statusText:f.statusText,durationMs:Date.now()-c,contentLength:y,hasContent:!!g,bodyType:v,proxied:!1,responseHeaders:w})}return f}catch(f){const g=f instanceof Error?f.message:String(f);throw h.debug("[Observability] HTTP request failed",{requestId:l,url:u,error:g,durationMs:Date.now()-c}),f}}function sSr(e){return async(t,r)=>oSr(t,r,e)}function Bt(){const e=process.env.HTTPS_PROXY||process.env.https_proxy,t=process.env.HTTP_PROXY||process.env.http_proxy,r=process.env.ALL_PROXY||process.env.all_proxy,n=process.env.SOCKS_PROXY||process.env.socks_proxy,o=process.env.NO_PROXY||process.env.no_proxy,s={httpsProxy:e,httpProxy:t,allProxy:r,socksProxy:n,noProxy:o};if(h.shouldLog("debug")){const i=Object.keys(process.env).filter(a=>a.toLowerCase().includes("proxy")).reduce((a,l)=>{const c=process.env[l]||"NOT_SET";return a[l]=l.toLowerCase()==="no_proxy"?c:fa(c),a},{});h.debug("[Proxy Fetch] ENHANCED_PROXY_ENV_DETECTION",{httpProxy:fa(t),httpsProxy:fa(e),allProxy:fa(r),socksProxy:fa(n),noProxy:o||"NOT_SET",allProxyRelatedEnvVars:i,message:"Enhanced proxy environment detection \u2014 credentials redacted"})}return!e&&!t&&!r&&!n?(h.debug("[Proxy Fetch] No proxy environment variables found - using standard fetch"),nSr()):(h.debug("[Proxy Fetch] Configuring enhanced proxy with multiple protocol support"),h.debug(`[Proxy Fetch] HTTP_PROXY: ${fa(t)}`),h.debug(`[Proxy Fetch] HTTPS_PROXY: ${fa(e)}`),h.debug(`[Proxy Fetch] ALL_PROXY: ${fa(r)}`),h.debug(`[Proxy Fetch] SOCKS_PROXY: ${fa(n)}`),h.debug(`[Proxy Fetch] NO_PROXY: ${o||"not set"}`),sSr(s))}function Vv(e){if(!e)return null;try{const t=new URL(e);return(t.username||t.password)&&(t.username="***",t.password="***"),t.toString()}catch{return"[invalid-url]"}}function iSr(){const e=process.env.HTTPS_PROXY||process.env.https_proxy,t=process.env.HTTP_PROXY||process.env.http_proxy,r=process.env.ALL_PROXY||process.env.all_proxy,n=process.env.SOCKS_PROXY||process.env.socks_proxy,o=process.env.NO_PROXY||process.env.no_proxy;return{enabled:!!(e||t||r||n),httpProxy:Vv(t),httpsProxy:Vv(e),allProxy:Vv(r),socksProxy:Vv(n),noProxy:o||null,method:"enhanced-proxy-agent",capabilities:["HTTP/HTTPS Proxy","SOCKS4/SOCKS5 Proxy","Proxy Authentication","NO_PROXY Bypass","CIDR Range Matching","Wildcard Domain Matching"]}}function Agt(e){wW||!iSr().enabled||(wW=!0,h.warn(`[${e}] A proxy is configured, but the @google/genai SDK provides no way to route its requests through it (HttpOptions has no 'fetch', and GoogleGenAIOptions accepts none). Requests from this provider go direct.`))}var kgt,Igt,wW,Zn=C({"src/lib/proxy/proxyFetch.ts"(){"use strict";W(),Xt(),gr(),JEr(),ji(),kSe(),kgt=Ve.http,Igt=new Set(["authorization","x-api-key","api-key","x-goog-api-key","proxy-authorization","cookie","set-cookie"]),wW=!1}});async function Wv(e,t){const n=(await Promise.resolve().then(()=>(GT(),Jy))).GoogleGenAI;if(!n)throw new $e({code:Xe.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const o=n;return Agt("GoogleAIStudio"),new o({apiKey:e,httpOptions:{...t?{baseUrl:t}:{}}})}function Rgt(e,t,r){const n=ygt({contents:e,availableInputTokens:qc("googleAiStudio",t),provider:"googleAiStudio",...r?{observedPromptTokens:r}:{}});if(!n)return!1;const o=new Set(n.drop),s=new Set(n.truncate),i=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const l=e[a];if(s.has(a)&&Array.isArray(l.parts)){i.push({...l,parts:l.parts.map(c=>{const u=c;if(!u.functionResponse)return c;const d=JSON.stringify(u.functionResponse.response)??"";return d.length<=2048?c:{functionResponse:{name:u.functionResponse.name,response:{result:fW(d)}}}})});continue}i.push(l)}if(o.size>0){let a=i.findIndex(l=>Array.isArray(l.parts)&&l.parts.some(c=>!!c.functionCall||!!c.functionResponse));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",parts:[{text:yW}]})}return e.length=0,e.push(...i),!0}var Pgt,aSr=C({"src/lib/providers/googleAiStudio/client.ts"(){"use strict";tc(),Fo(),nM(),ul(),Ct(),ct(),W(),BEr(),pW(),Fo(),kH(),_gt(),Mu(),Pa(),IE(),Qs(),Sd(),U1(),wgt(),Gv(),vW(),Zn(),Pgt=class extends gl{credentials;constructor(e,t,r){super(e,"google-ai",t),this.credentials=r,h.debug("GoogleAIStudioProvider initialized",{model:this.modelName,provider:this.providerName,sdkProvided:!!t})}getProviderName(){return"google-ai"}getDefaultModel(){return process.env.GOOGLE_AI_MODEL||"gemini-2.5-flash"}getAISDKModel(){throw new $e({code:Xe.INVALID_CONFIGURATION,message:"GoogleAIStudioProvider no longer uses @ai-sdk/google. All models use native @google/genai SDK.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}formatProviderError(e){if(e instanceof pd)return new Go(e.message,this.providerName);const t=e,r=typeof t?.message=="string"?t.message:"Unknown error",n=typeof t?.status=="number"?t.status:typeof t?.statusCode=="number"?t.statusCode:void 0;return r.includes("API_KEY_INVALID")||r.includes("Invalid API key")||n===401?new dr("Invalid Google AI API key. Please check your GOOGLE_AI_API_KEY environment variable.",this.providerName):r.includes("RATE_LIMIT_EXCEEDED")||r.includes("rate limit")||r.includes("429")||n===429?new Ws("Google AI rate limit exceeded. Please try again later.",this.providerName):n===404||n===void 0&&(r.includes("model not found")||r.includes("Model not found"))?new no(`Model '${this.modelName}' not found. Please check the model name and ensure it is available.`,this.providerName):r.includes("ECONNRESET")||r.includes("ENOTFOUND")||r.includes("ETIMEDOUT")||r.includes("ECONNREFUSED")||r.includes("network")||r.includes("connection")?new Go(`Connection error: ${r}`,this.providerName):r.includes("500")||r.includes("502")||r.includes("503")||r.includes("504")||r.includes("server error")||r.includes("Internal Server Error")||n&&n>=500&&n<600?new bt(`Google AI server error: ${r}. Please try again later.`,this.providerName):new bt(`Google AI error: ${r}`,this.providerName)}async executeImageGeneration(e){await vE(e.input);const t=e.prompt||e.input?.text||"",r=e.model||this.modelName,n=Date.now(),o=this.getApiKey();h.info("\u{1F3A8} Starting Google AI Studio image generation",{model:r,prompt:t.substring(0,100),provider:this.providerName});let s;try{s=await Wv(o,this.getBaseURL())}catch{throw new dr("Missing '@google/genai'. Install with: npm install @google/genai",this.providerName)}try{const i=await Promise.all((e.input?.images||[]).map(async d=>{if(typeof d=="object"&&"url"in d){const g=d.url;if(g.startsWith("http")){const w=await fetch(g);if(!w.ok)throw new Error(`Failed to fetch image from ${g}: ${w.status} ${w.statusText}`);const b=await w.arrayBuffer(),T=Buffer.from(b),x=this.detectImageType(T);return h.debug(`Downloaded and detected image MIME type: ${x}`),{inlineData:{mimeType:x,data:T.toString("base64")}}}const y=Buffer.from(g,"base64");return{inlineData:{mimeType:this.detectImageType(y),data:y.toString("base64")}}}if(typeof d=="string"&&d.startsWith("http")){const g=await fetch(d);if(!g.ok)throw new Error(`Failed to fetch image from ${d}: ${g.status} ${g.statusText}`);const y=await g.arrayBuffer(),v=Buffer.from(y),w=this.detectImageType(v);return h.debug(`Downloaded and detected image MIME type: ${w}`),{inlineData:{mimeType:w,data:v.toString("base64")}}}const m=Buffer.isBuffer(d)?d:typeof d=="string"?Buffer.from(d,"base64"):Buffer.from(""),f=this.detectImageType(m);return h.debug(`Detected image MIME type: ${f}`),{inlineData:{mimeType:f,data:m.toString("base64")}}})),a=[{role:"user",parts:[{text:t},...i]}],l={responseModalities:["IMAGE","TEXT"]};h.debug("Starting image generation request",{model:r,contentParts:a[0].parts.length,responseModalities:l.responseModalities});let c=null,u="";try{const d=await s.models.generateContentStream({model:r,contents:a,config:l});for await(const m of d){h.debug("Received chunk",{hasCandidate:!!m.candidates?.[0],hasContent:!!m.candidates?.[0]?.content,hasParts:!!m.candidates?.[0]?.content?.parts});const f=m.candidates?.[0];if(f?.content?.parts)for(const g of f.content.parts){if("inlineData"in g&&g.inlineData?.data){const y=g.inlineData.data;c=y;const v=g.inlineData.mimeType||"image/png";h.info("Image generation successful",{model:r,mimeType:v,dataLength:y.length,responseTime:Date.now()-n});const w={content:`Generated image using ${r} (${v})`,imageOutput:{base64:y},provider:this.providerName,model:r,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(w,e,n)}"text"in g&&g.text&&(u+=g.text,h.debug("Received text content",{text:g.text.substring(0,100)}))}}}catch(d){h.debug("Streaming failed, trying non-streaming approach",{error:d instanceof Error?d.message:String(d)})}if(!c){h.debug("Trying non-streaming approach");const m=(await s.models.generateContent({model:r,contents:a,config:l})).candidates?.[0];if(m?.content?.parts)for(const f of m.content.parts){if("inlineData"in f&&f.inlineData?.data){const g=f.inlineData.data;c=g;const y=f.inlineData.mimeType||"image/png";h.info("Image generation successful (non-streaming)",{model:r,mimeType:y,dataLength:g.length,responseTime:Date.now()-n});const v={content:`Generated image using ${r} (${y})`,imageOutput:{base64:g},provider:this.providerName,model:r,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(v,e,n)}"text"in f&&f.text&&(u+=f.text)}}throw h.warn("No image data found in response",{model:r,prompt:t.substring(0,100),hasTextContent:!!u,textContent:u.substring(0,200)}),new bt(u||`Image generation completed but no image data was returned. This may indicate an issue with the model "${r}" or the prompt: "${t}". Please try again or use a different model.`,this.providerName)}catch(i){throw h.error("Image generation failed",{error:i instanceof Error?i.message:String(i),model:r,prompt:t.substring(0,100)}),this.handleProviderError(i)}}detectImageType(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70?"image/gif":"image/png"}estimateTokenCount(e){return pr(e,"google-ai")}async preprocessNativeFileInput(e){if(e.input&&m9(e.input),e.input?.files&&e.input.files.length>0)try{await h9(e,100*1024*1024,this.providerName)}catch(t){h.warn(`[GoogleAIStudio] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await vE(e.input)}async executeStream(e,t){const r=e.model||this.modelName;if(e.input?.audio)return await this.executeAudioStreamViaGeminiLive(e);await this.preprocessNativeFileInput(e);const n=!!(t||e.output?.format==="json"||e.schema),o=!e.disableTools&&this.supportsTools()&&!n,s=e.tools||{};let i={...e,tools:s};const a=e.output?.format==="json"||e.schema,l=AH(this.providerName,r,!i.disableTools,Object.keys(i.tools??{}).length);return a&&l&&(h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),i={...i,disableTools:!0,tools:{}}),o&&!i.disableTools&&i.tools&&Object.keys(i.tools).length>0&&h.info("[GoogleAIStudio] Routing to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(i.tools??{}).length}),this.executeNativeGemini3Stream(i)}async executeNativeGemini3Stream(e){const t=e.model||this.modelName;return K$e({name:"neurolink.provider.stream",tracer:Ve.provider,attributes:{[Me.GEN_AI_SYSTEM]:"google-ai",[Me.GEN_AI_MODEL]:t,[Me.GEN_AI_OPERATION]:"stream",[Me.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),s=Bl(o,this.providerName,"stream");{const i=this.getApiKey(),a=await Wv(i,this.getBaseURL());h.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const l=[];OM(l,e.conversationMessages);const c=await ugt(e.input,e.input.text,"[GoogleAIStudio:stream]");l.push({role:"user",parts:c});let u,d;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){const M=Hv(e.tools,"functionDeclarations");d=M,u=M.toolsConfig,h.debug("[GoogleAIStudio] Converted tools for native SDK",{toolCount:u[0].functionDeclarations.length,toolNames:u[0].functionDeclarations.map(O=>O.name)})}const m=!u&&(e.output?.format==="json"||!!e.schema),f=m&&e.schema?cgt(e.schema):void 0,g=ogt({...e,model:t,wantsJsonOutput:m,responseSchema:f},u),y=sgt(e.maxSteps),v=CI(e.abortSignal,s?.controller.signal),w=qv(),b=[],T=[];let x,k;const R=new Promise((M,O)=>{x=M,k=O}),P={streamId:`native-${Date.now()}`,startTime:n,responseTime:0,totalToolExecutions:0};(async()=>{let M="",O=0,N=0,D=0,F=0,U=0;const $=zv(Cd("googleAiStudio",t));try{const B=pgt({providerLabel:"GoogleAIStudio",maxSteps:y,toolFailureBreaker:{maxRetries:$o},liveTools:e.tools??{},...d?{declarations:d}:{},buildRequest:ve=>({model:t,contents:ve,config:g,...v?{httpOptions:{signal:v}}:{}}),sendStep:async ve=>a.models.generateContentStream(ve),noteUsage:(ve,le)=>{$.noteUsage(ve,le)},planReclaim:(ve,le)=>{if(le!==0&&!$.shouldStop())return;const H=[...ve];if(Rgt(H,t,$.projectedNextPromptTokens))return $.resetAfterReclaim(),H}}),z={...B,buildToolResultMessages:(ve,le,H)=>{U++;for(const fe of le.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":fe.name,"tool.step":U});M=le.text||M;for(const fe of le.toolCalls)b.push({toolName:fe.name,args:fe.args});for(const fe of H)T.push({name:fe.name,input:fe.args,output:fe.output});if(H.length>0){const fe=RM(le.raw.rawResponseParts);Nt(this.handleToolExecutionStorage(le.toolCalls.map((Y,ae)=>({toolName:Y.name,args:Y.args,...ae===0&&fe?{thoughtSignature:fe}:{},stepIndex:U})),H.map(Y=>({toolName:Y.name,output:Y.output,stepIndex:U})),e,new Date),Kp,"tool storage write timed out").catch(Y=>{h.warn("[GoogleAIStudio] Failed to store native tool executions",{error:Y instanceof Error?Y.message:String(Y)})})}const ie=B.buildToolResultMessages(ve,le,H);try{const fe=ie[ie.length-1];$.noteAppendedChars(JSON.stringify(fe?.parts??[]).length)}catch{}return ie}},j={};for(const[ve,le]of Object.entries(e.tools??{})){const H=le?.execute;H&&(j[ve]={execute:async(ie,fe)=>H(ie,fe)})}const{stream:J,resultPromise:Z}=kE(z,l,{tools:j,...v?{abortSignal:v}:{}}),pe=(async()=>{for await(const ve of J)w.push(ve)})();let Ce;try{Ce=await Z}catch(ve){throw await pe.catch(()=>{}),h.error("[GoogleAIStudio] Native SDK error",ve),this.handleProviderError(ve)}await pe,O+=Ce.usage.inputTokens,N+=Ce.usage.outputTokens,D+=Ce.usage.cacheReadTokens??0,F+=Ce.usage.reasoningTokens??0;const re=Ce.toolCalls.length===0||Ce.finishReason!=="tool-calls",Q=U>=y&&!re;if(Q){const ve=agt("[GoogleAIStudio]",U,y,"",M);ve&&w.push({content:ve})}const ne=Date.now()-n;P.responseTime=ne,P.totalToolExecutions=b.length,r.setAttribute(Me.GEN_AI_INPUT_TOKENS,O),r.setAttribute(Me.GEN_AI_OUTPUT_TOKENS,N),r.setAttribute(Me.GEN_AI_FINISH_REASON,Q?"max_steps":"stop");const Ie=Math.max(0,O-D);x({provider:this.providerName,model:t,tokenUsage:{input:Ie,output:N+F,total:Ie+D+N+F,...D>0?{cacheReadTokens:D}:{},...F>0?{reasoning:F}:{}},requestDuration:ne,timestamp:new Date().toISOString()}),w.close()}catch(B){w.error(B),k(B)}finally{s?.cleanup()}})().catch(()=>{});const A={stream:w.iterable,provider:this.providerName,model:t,toolCalls:b,analytics:R,metadata:P};return Object.defineProperty(A,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>b.map(M=>M.toolName)}),Object.defineProperty(A,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>O1(T)}),A}},r=>r.stream,(r,n)=>({...r,stream:n}))}async executeNativeGemini3Generate(e){const t=e.model||this.modelName;return XT({name:"neurolink.provider.generate",tracer:Ve.provider,attributes:{[Me.GEN_AI_SYSTEM]:"google-ai",[Me.GEN_AI_MODEL]:t,[Me.GEN_AI_OPERATION]:"generate",[Me.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),s=Bl(o,this.providerName,"generate");try{const i=this.getApiKey(),a=await Wv(i,this.getBaseURL());h.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3 generate",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const l=e.input?.text||e.prompt||"",c=[];OM(c,e.conversationMessages);const u=await ugt(e.input,l,"[GoogleAIStudio:generate]");c.push({role:"user",parts:u});let d,m;const f=!e.disableTools,g=!!(e.output?.format==="json"||e.schema),y=AH(this.providerName,t,f,Object.keys(e.tools||{}).length);if(g&&y&&h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request (generate())."),f&&!(g&&y)){const Q=e.tools||{};if(Object.keys(Q).length>0){const ne=Hv(Q,"functionDeclarations");m=ne,d=ne.toolsConfig,h.debug("[GoogleAIStudio] Converted tools for native SDK generate",{toolCount:d[0].functionDeclarations.length,toolNames:d[0].functionDeclarations.map(Ie=>Ie.name)})}}const v=!d&&g,w=v&&e.schema?cgt(e.schema):void 0,b=ogt({...e,model:t,wantsJsonOutput:v,responseSchema:w},d),T=CI(e.abortSignal,s?.controller.signal),x=sgt(e.maxSteps);let k="",R="",P=0,I=0,A=0,M=0;const O=[],N=[];let D=0;const F=zv(Cd("googleAiStudio",t)),U=pgt({providerLabel:"GoogleAIStudio",maxSteps:x,toolFailureBreaker:{maxRetries:$o},liveTools:e.tools??{},...m?{declarations:m}:{},buildRequest:Q=>({model:t,contents:Q,config:b,...T?{httpOptions:{signal:T}}:{}}),sendStep:async Q=>a.models.generateContentStream(Q),noteUsage:(Q,ne)=>{F.noteUsage(Q,ne)},planReclaim:(Q,ne)=>{if(ne!==0&&!F.shouldStop())return;const Ie=[...Q];if(Rgt(Ie,t,F.projectedNextPromptTokens))return F.resetAfterReclaim(),Ie}}),$={...U,buildToolResultMessages:(Q,ne,Ie)=>{D++;for(const le of ne.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":le.name,"tool.step":D}),O.push({toolName:le.name,args:le.args});R=ne.text||R;for(const le of Ie)N.push({name:le.name,input:le.args,output:le.output});if(Ie.length>0){const le=RM(ne.raw.rawResponseParts);Nt(this.handleToolExecutionStorage(ne.toolCalls.map((H,ie)=>({toolName:H.name,args:H.args,...ie===0&&le?{thoughtSignature:le}:{},stepIndex:D})),Ie.map(H=>({toolName:H.name,output:H.output,stepIndex:D})),e,new Date),Kp,"tool storage write timed out").catch(H=>{h.warn("[GoogleAIStudio] Failed to store native tool executions",{error:H instanceof Error?H.message:String(H)})})}const ve=U.buildToolResultMessages(Q,ne,Ie);try{const le=ve[ve.length-1];F.noteAppendedChars(JSON.stringify(le?.parts??[]).length)}catch{}return ve}},B={};for(const[Q,ne]of Object.entries(e.tools??{})){const Ie=ne?.execute;Ie&&(B[Q]={execute:async(ve,le)=>Ie(ve,le)})}const{stream:z,resultPromise:j}=kE($,c,{tools:B,...T?{abortSignal:T}:{}}),J=(async()=>{for await(const Q of z);})();let Z;try{Z=await j}catch(Q){throw await J.catch(()=>{}),h.error("[GoogleAIStudio] Native SDK generate error",Q),this.handleProviderError(Q)}await J,P+=Z.usage.inputTokens,I+=Z.usage.outputTokens,A+=Z.usage.cacheReadTokens??0,M+=Z.usage.reasoningTokens??0,k=Z.text,k=agt("[GoogleAIStudio]",D,x,k,R);const pe=Date.now()-n;r.setAttribute(Me.GEN_AI_INPUT_TOKENS,P),r.setAttribute(Me.GEN_AI_OUTPUT_TOKENS,I),r.setAttribute(Me.GEN_AI_FINISH_REASON,D>=x?"max_steps":"stop");const Ce=Math.max(0,P-A),re={content:k,provider:this.providerName,model:t,usage:{input:Ce,output:I+M,total:Ce+A+I+M,...A>0?{cacheReadTokens:A}:{},...M>0?{reasoning:M}:{}},...M>0&&{reasoningTokens:M},responseTime:pe,toolsUsed:O.map(Q=>Q.toolName),toolExecutions:$1(e,N),enhancedWithTools:O.length>0};return this.enhanceResult(re,e,n)}finally{s?.cleanup()}})}async generate(e){const t=typeof e=="string"?{prompt:e}:e,r=t.model||this.modelName;if(Wp.some(u=>r.toLowerCase().startsWith(u.toLowerCase())))return h.info("[GoogleAIStudio] Routing image generation model to executeImageGeneration",{model:r}),this.executeImageGeneration(t);if(t.tts?.enabled&&!t.tts?.useAiResponse)return h.info("[GoogleAIStudio] Routing TTS direct-synthesis to handleDirectTTSSynthesis",{model:r}),this.handleDirectTTSSynthesis(t,Date.now());await this.preprocessNativeFileInput(t);const o=t.disableTools?{}:await this.getToolsForStream(t);let s={...t,tools:o};(t.output?.format==="json"||t.schema)&&s.tools&&Object.keys(s.tools).length>0&&!s.disableTools&&(h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),s={...s,disableTools:!0,tools:{}}),!s.disableTools&&s.tools&&Object.keys(s.tools).length>0&&h.info("[GoogleAIStudio] Routing generate to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(s.tools??{}).length});const l=Date.now(),c=s.input?.text||s.prompt||"";try{let u=await gt({name:"neurolink.executeGeneration",tracer:Ve.provider,attributes:{[Me.GEN_AI_SYSTEM]:this.providerName,[Me.GEN_AI_MODEL]:r,"neurolink.path":"native.google-genai"}},async()=>this.executeNativeGemini3Generate(s));return u=await this.synthesizeAIResponseIfNeeded(u,t),this.emitPipelineBGenerationEvent(r,u,l,!0,void 0,c),u}catch(u){throw this.emitPipelineBGenerationEvent(r,null,l,!1,u,c),u}}emitPipelineBGenerationEvent(e,t,r,n,o,s){const i=this.neurolink?.getEventEmitter();if(!i)return;const a=t?.usage&&typeof t.usage=="object"?t.usage:{input:0,output:0,total:0};t&&typeof t=="object"&&(t._generationEndEmitted=!0),i.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),prompt:s||"",result:{content:t?.content||"",usage:a,model:e,provider:this.providerName,finishReason:n?"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async executeAudioStreamViaGeminiLive(e){const t=Date.now(),r=this.getApiKey();let n;try{n=await Wv(r,this.getBaseURL())}catch{throw new dr("Missing '@google/genai'. Install with: pnpm add @google/genai",this.providerName)}const o=this.modelName||process.env.GOOGLE_VOICE_AI_MODEL||"gemini-2.5-flash-preview-native-audio-dialog",s=[];let i=null,a=!1;const l=d=>{if(!a){if(d.type==="audio"&&i){const m=i;i=null,m({value:{type:"audio",audio:d.audio},done:!1});return}s.push(d)}},c=await n.live.connect({model:o,callbacks:{onopen:()=>{},onmessage:async d=>{try{const m=d?.serverContent?.modelTurn?.parts?.[0]?.inlineData;if(m?.data){const g={data:Buffer.from(String(m.data),"base64"),sampleRateHz:24e3,channels:1,encoding:"PCM16LE"};l({type:"audio",audio:g})}d?.serverContent?.interrupted}catch(m){l({type:"error",error:m})}},onerror:d=>{l({type:"error",error:d})},onclose:d=>{l({type:"end"})}},config:{responseModalities:["AUDIO"],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:"Orus"}}}}});return(async()=>{try{const d=e.input?.audio;if(!d){h.debug("[GeminiLive] No audio spec found on input; skipping upstream send");return}for await(const m of d.frames){if(!m||m.byteLength===0){try{c.sendInput?await c.sendInput({event:"flush"}):c.sendRealtimeInput&&await c.sendRealtimeInput({event:"flush"})}catch(y){h.debug("[GeminiLive] flush control failed (non-fatal)",{error:y instanceof Error?y.message:String(y)})}continue}const f=m.toString("base64"),g=`audio/pcm;rate=${d.sampleRateHz||16e3}`;await c.sendRealtimeInput?.({media:{data:f,mimeType:g}})}try{c.sendInput?await c.sendInput({event:"flush"}):c.sendRealtimeInput&&await c.sendRealtimeInput({event:"flush"})}catch(m){h.debug("[GeminiLive] final flush failed (non-fatal)",{error:m instanceof Error?m.message:String(m)})}}catch(d){l({type:"error",error:d})}})().catch(()=>{}),{stream:{[Symbol.asyncIterator](){return{async next(){if(s.length>0){const d=s.shift();if(!d)return{value:void 0,done:!0};if(d.type==="audio")return{value:{type:"audio",audio:d.audio},done:!1};if(d.type==="end")return a=!0,{value:void 0,done:!0};if(d.type==="error")throw a=!0,d.error instanceof Error?d.error:new Error(String(d.error))}return a?{value:void 0,done:!0}:await new Promise(d=>{i=d})}}}},provider:this.providerName,model:o,metadata:{startTime:t,streamId:`google-ai-audio-${Date.now()}`}}}getDefaultEmbeddingModel(){return process.env.GOOGLE_AI_EMBEDDING_MODEL||process.env.GOOGLE_EMBEDDING_MODEL||"gemini-embedding-001"}async embed(e,t){const r=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";h.debug("Generating embedding",{provider:this.providerName,model:r,textLength:e.length});try{const n=this.getApiKey(),i=(await(await Wv(n,this.getBaseURL())).models.embedContent({model:r,contents:[e]})).embeddings?.[0]?.values;if(!i)throw new bt("No embedding returned from Google AI",this.providerName);return h.debug("Embedding generated successfully",{provider:this.providerName,model:r,embeddingDimension:i.length}),i}catch(n){throw h.error("Embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,textLength:e.length}),this.handleProviderError(n)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";h.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=this.getApiKey(),i=((await(await Wv(n,this.getBaseURL())).models.embedContent({model:r,contents:e})).embeddings||[]).map(a=>a.values||[]);return h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:i.length,embeddingDimension:i[0]?.length}),i}catch(n){throw h.error("Batch embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,count:e.length}),this.handleProviderError(n)}}getApiKey(){const e=this.credentials?.apiKey||process.env.GOOGLE_AI_API_KEY||process.env.GOOGLE_GENERATIVE_AI_API_KEY;if(!e)throw new dr("GOOGLE_AI_API_KEY or GOOGLE_GENERATIVE_AI_API_KEY environment variable is not set",this.providerName);return e}getBaseURL(){const e=this.credentials?.baseURL?.trim()||process.env.GOOGLE_AI_BASE_URL?.trim();return e&&e.length>0?e:void 0}}}}),Mgt={};de(Mgt,{GoogleAIStudioProvider:()=>Pgt});var lSr=C({"src/lib/providers/googleAiStudio/index.ts"(){"use strict";aSr()}});async function Od(e,t,r){const n=parseInt(e.headers.get("content-length")??"0",10);if(n>0&&n>t)throw new Error(`${r} download too large: ${n} bytes (max ${t})`);const o=Buffer.from(await e.arrayBuffer());if(o.length>t)throw new Error(`${r} download exceeded size cap after fetch: ${o.length} bytes (max ${t})`);return o}var Pf,Mf,Df,yl=C({"src/lib/utils/sizeGuard.ts"(){"use strict";Pf=256*1024*1024,Mf=50*1024*1024,Df=25*1024*1024}}),cSr,uSr,dSr,pSr,$M,Dgt,TW,bW,mSr,hSr,fSr,gSr,ySr=C({"node-stub:node:dns/promises"(){cSr=globalThis.crypto,uSr=globalThis.ReadableStream||class{},dSr=globalThis.URL,pSr=globalThis.URLSearchParams,$M=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},$M.custom=Symbol.for("nodejs.util.inspect.custom"),$M.colors={},$M.styles={},Dgt=globalThis.TextDecoder,TW=globalThis.TextEncoder,bW=(e,t)=>t?.(null,"127.0.0.1",4),mSr=globalThis.performance||{now:()=>Date.now()},hSr=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new TW().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new TW().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new Dgt().decode(this)}},fSr=globalThis.clearTimeout,gSr=globalThis.clearInterval}}),vSr,_Sr,wSr,TSr,FM,Ogt,EW,bSr,ESr,Ngt,SSr,CSr,xSr=C({"node-stub:node:net"(){vSr=globalThis.crypto,_Sr=globalThis.ReadableStream||class{},wSr=globalThis.URL,TSr=globalThis.URLSearchParams,FM=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},FM.custom=Symbol.for("nodejs.util.inspect.custom"),FM.colors={},FM.styles={},Ogt=globalThis.TextDecoder,EW=globalThis.TextEncoder,bSr=globalThis.performance||{now:()=>Date.now()},ESr=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new EW().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new EW().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new Ogt().decode(this)}},Ngt=()=>0,SSr=globalThis.clearTimeout,CSr=globalThis.clearInterval}});function ASr(e){return e.length===0?null:/^0x[0-9a-f]+$/i.test(e)?parseInt(e.slice(2),16):e.length>1&&e.startsWith("0")&&/^0[0-7]+$/.test(e)?parseInt(e.slice(1),8):/^\d+$/.test(e)?parseInt(e,10):null}function UM(e){if(e.length===0)return null;const t=e.split(".");if(t.length===4){const r=t.map(ASr);return r.some(n=>n===null||n<0||n>255)?null:r.join(".")}if(t.length===1){let r;if(/^0x[0-9a-f]+$/i.test(e))r=parseInt(e.slice(2),16);else if(/^\d+$/.test(e))r=parseInt(e,10);else return null;return Number.isNaN(r)||r<0||r>4294967295?null:[r>>>24&255,r>>>16&255,r>>>8&255,r&255].join(".")}return null}function Lgt(e){if(Ngt(e)!==6)return null;const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);let r;if(t){const n=UM(t[1]);if(!n)return null;const o=n.split(".").map(a=>parseInt(a,10)),s=(o[0]<<8|o[1]).toString(16),i=(o[2]<<8|o[3]).toString(16);r=["0","0","0","0","0","ffff",s,i]}else{const[n,o=""]=e.split("::"),s=n?n.split(":"):[],i=o?o.split(":"):[],a=8-s.length-i.length;if(a<0)return null;r=[...s,...Array(a).fill("0"),...i]}return r.length!==8?null:r.map(n=>n.toLowerCase().padStart(4,"0")).join(":")}function $gt(e){const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(t)return UM(t[1]);const r=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(r){const n=parseInt(r[1],16),o=parseInt(r[2],16);return Number.isNaN(n)||Number.isNaN(o)||n>65535||o>65535?null:[n>>8&255,n&255,o>>8&255,o&255].join(".")}return null}function Fgt(e){const[t,r,n,o]=e.split(".").map(s=>parseInt(s,10));return(t<<24|r<<16|n<<8|o)>>>0}function RE(e){const t=Fgt(e);for(const[r,n]of qgt){const o=Fgt(r),s=n===0?0:4294967295<<32-n>>>0;if((t&s)===(o&s))return!0}return!1}function Ugt(e){return Ggt.some(t=>t.length===39?e===t:e.startsWith(t))}function Bgt(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function zgt(e){const t=UM(e);if(t)return RE(t)?`IPv4 ${e} \u2192 ${t} is in a blocked range`:null;if(e.includes(":")){const r=$gt(e);if(r)return RE(r)?`IPv4-mapped IPv6 ${e} \u2192 ${r} is in a blocked range`:null;const n=Lgt(e);return n?Ugt(n)?`IPv6 ${e} is in a blocked range`:null:`IPv6 ${e} could not be parsed`}return"not-an-ip"}async function Of(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${t.protocol}//" in "${e}"`);const r=Bgt(t.hostname).toLowerCase(),n=zgt(r);if(n!==null){if(n!=="not-an-ip")throw new Error(`URL "${e}" rejected: ${n}`);await jgt(e,r)}}async function jgt(e,t){const[r,n]=await Promise.allSettled([bW(t,{family:4,all:!0}),bW(t,{family:6,all:!0})]),o=[],s=[];let i=!1;if(r.status==="fulfilled"){i=!0;for(const a of r.value)o.push(a.address)}if(n.status==="fulfilled"){i=!0;for(const a of n.value)s.push(a.address)}if(!i){const a=r.status==="rejected"?r.reason instanceof Error?r.reason.message:String(r.reason):"ok",l=n.status==="rejected"?n.reason instanceof Error?n.reason.message:String(n.reason):"ok";throw new Error(`URL "${e}" rejected: hostname ${t} could not be resolved (A: ${a}; AAAA: ${l})`)}for(const a of o)if(RE(a))throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv4 in blocked range)`);for(const a of s){const l=zgt(a.toLowerCase());if(l&&l!=="not-an-ip")throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv6 ${l})`)}return{v4:o,v6:s}}async function kSr(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${t.protocol}//" in "${e}"`);const r=Bgt(t.hostname).toLowerCase(),n=UM(r);if(n){if(RE(n))throw new Error(`URL "${e}" rejected: IPv4 ${r} \u2192 ${n} is in a blocked range`);return{url:e,ip:n,family:4,addresses:[{ip:n,family:4}]}}if(r.includes(":")){const l=$gt(r);if(l){if(RE(l))throw new Error(`URL "${e}" rejected: IPv4-mapped IPv6 ${r} \u2192 ${l} is in a blocked range`);return{url:e,ip:l,family:4,addresses:[{ip:l,family:4}]}}const c=Lgt(r);if(!c)throw new Error(`URL "${e}" rejected: IPv6 ${r} could not be parsed`);if(Ugt(c))throw new Error(`URL "${e}" rejected: IPv6 ${r} is in a blocked range`);return{url:e,ip:r,family:6,addresses:[{ip:r,family:6}]}}const{v4:o,v6:s}=await jgt(e,r),i=[...o.map(l=>({ip:l,family:4})),...s.map(l=>({ip:l,family:6}))],a=i[0];if(!a)throw new Error(`URL "${e}" rejected: hostname ${r} resolved to an empty address set`);return{url:e,ip:a.ip,family:a.family,addresses:i}}var qgt,Ggt,Nf=C({"src/lib/utils/ssrfGuard.ts"(){"use strict";ySr(),xSr(),qgt=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.168.0.0",16],["198.18.0.0",15],["100.100.100.200",32],["224.0.0.0",4],["240.0.0.0",4]],Ggt=["0000:0000:0000:0000:0000:0000:0000:0000","0000:0000:0000:0000:0000:0000:0000:0001","fc","fd","fe8","fe9","fea","feb"]}}),Hgt={};de(Hgt,{createAnnotatedTool:()=>Wgt,filterToolsByAnnotations:()=>Ygt,getAnnotationSummary:()=>Zgt,getToolSafetyLevel:()=>Jgt,inferAnnotations:()=>Nd,isSafeToRetry:()=>CW,mergeAnnotations:()=>SW,requiresConfirmation:()=>Kgt,validateAnnotations:()=>Vgt});function Nd(e){const t=e.name,r=e.description.toLowerCase(),n={},o=(c,u)=>new RegExp(`\\b${u}\\b`,"i").test(c)?!0:c.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[_-]/).some(m=>m===u.toLowerCase());return["get","list","read","fetch","query","search","find","show","display","view","retrieve","check","inspect","look"].some(c=>o(r,c)||o(t,c))&&(n.readOnlyHint=!0),["delete","remove","drop","destroy","clear","purge","erase","wipe","truncate","reset"].some(c=>o(r,c)||o(t,c))&&(n.destructiveHint=!0,n.requiresConfirmation=!0),["set","update","put","upsert","replace"].some(c=>o(r,c)||o(t,c))&&!n.destructiveHint&&(n.idempotentHint=!0),["complex","analyze","process","generate","transform","compute","calculate"].some(c=>o(r,c)||o(t,c))?n.complexity="complex":r.length>100?n.complexity="medium":n.complexity="simple",n}function SW(...e){const t={};for(const r of e)if(r){const n=t.tags?[...t.tags]:[];if(Object.assign(t,r),n.length>0||r.tags){const o=r.tags??[];t.tags=[...new Set([...n,...o])]}}return t}function Vgt(e){const t=[];if(e.readOnlyHint&&e.destructiveHint&&t.push("Tool cannot be both readOnly and destructive - these are conflicting hints"),e.rateLimitHint!==void 0&&(e.rateLimitHint<0||!Number.isFinite(e.rateLimitHint))&&t.push("rateLimitHint must be a non-negative number"),e.estimatedDuration!==void 0&&(e.estimatedDuration<0||!Number.isFinite(e.estimatedDuration))&&t.push("estimatedDuration must be a non-negative number"),e.costHint!==void 0&&(e.costHint<0||!Number.isFinite(e.costHint))&&t.push("costHint must be a non-negative number"),e.tags){for(const r of e.tags)if(typeof r!="string"||r.length===0){t.push("All tags must be non-empty strings");break}}return t}function Wgt(e){const t=Nd(e),r=SW(t,e.annotations);return{...e,annotations:r}}function Kgt(e){return!!(e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)}function CW(e){return!!(e.annotations?.idempotentHint||e.annotations?.readOnlyHint)}function Jgt(e){return e.annotations?.destructiveHint?"dangerous":e.annotations?.readOnlyHint?"safe":(e.annotations?.idempotentHint,"moderate")}function Ygt(e,t){return e.filter(r=>{const n=r.annotations??{};return t(n)})}function Zgt(e){const t=[];return e.title&&t.push(e.title),e.readOnlyHint&&t.push("read-only"),e.destructiveHint&&t.push("DESTRUCTIVE"),e.idempotentHint&&t.push("idempotent"),e.requiresConfirmation&&t.push("requires confirmation"),e.complexity&&t.push(`${e.complexity} complexity`),e.estimatedDuration!==void 0&&t.push(`~${e.estimatedDuration}ms`),e.tags?.length&&t.push(`tags: ${e.tags.join(", ")}`),t.length>0?`[${t.join(" | ")}]`:"[no annotations]"}var PE=C({"src/lib/mcp/toolAnnotations.ts"(){"use strict"}}),xW={};de(xW,{TOOL_COMPATIBILITY:()=>RW,batchConvertToMCP:()=>eyt,batchConvertToNeuroLink:()=>tyt,createToolFromFunction:()=>ryt,mcpProtocolToolToServerTool:()=>Xgt,mcpToolToNeuroLink:()=>kW,neuroLinkToolToMCP:()=>AW,sanitizeToolName:()=>IW,serverToolToMCPProtocol:()=>Qgt,validateToolName:()=>nyt});function AW(e,t={}){const{inferAnnotations:r=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:s}=t,i=s?`${s}_${e.name}`:e.name,a=r?Nd({name:e.name,description:e.description}):{},l={...n,...a};e.tags?.length&&(l.tags=[...new Set([...l.tags??[],...e.tags])]);const c=e.parameters??{type:"object",properties:{}},u=o?{...e.metadata}:{};return e.category&&(u.category=e.category),e.isAsync!==void 0&&(u.isAsync=e.isAsync),{name:i,description:e.description,inputSchema:c,annotations:l,execute:e.execute,metadata:u}}function kW(e,t={}){const{removeNamespacePrefix:r}=t;let n=e.name;return r&&e.name.startsWith(`${r}_`)&&(n=e.name.slice(r.length+1)),{name:n,description:e.description,parameters:e.inputSchema,execute:e.execute,category:e.metadata?.category,tags:e.annotations?.tags,metadata:e.metadata}}function Xgt(e,t,r={}){const{inferAnnotations:n=!0,defaultAnnotations:o={}}=r,s=e.annotations??{},i=n?Nd({name:e.name,description:e.description??""}):{},a={...o,...i,title:s.title??i.title??o.title,readOnlyHint:s.readOnlyHint??i.readOnlyHint??o.readOnlyHint,destructiveHint:s.destructiveHint??i.destructiveHint??o.destructiveHint,idempotentHint:s.idempotentHint??i.idempotentHint??o.idempotentHint,openWorldHint:s.openWorldHint??i.openWorldHint??o.openWorldHint};return{name:e.name,description:e.description??"No description provided",inputSchema:e.inputSchema,annotations:a,execute:t}}function Qgt(e){const t={};e.annotations?.title&&(t.title=e.annotations.title),e.annotations?.readOnlyHint!==void 0&&(t.readOnlyHint=e.annotations.readOnlyHint),e.annotations?.destructiveHint!==void 0&&(t.destructiveHint=e.annotations.destructiveHint),e.annotations?.idempotentHint!==void 0&&(t.idempotentHint=e.annotations.idempotentHint),e.annotations?.openWorldHint!==void 0&&(t.openWorldHint=e.annotations.openWorldHint);const r=e.inputSchema??{type:"object",properties:{}};return{name:e.name,description:e.description,inputSchema:{type:"object",properties:r.properties??{},required:"required"in r?r.required:void 0},annotations:Object.keys(t).length>0?t:void 0}}function eyt(e,t={}){return e.map(r=>AW(r,t))}function tyt(e,t={}){return e.map(r=>kW(r,t))}function ryt(e,t,r,n){const o=Nd({name:e,description:t});return{name:e,description:t,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(s,i)=>await Nt(r(s,i),3e4,`Tool '${e}' execution timed out after 30000ms`),metadata:n?.metadata}}function nyt(e){const t=[];return!e||typeof e!="string"?t.push("Tool name is required and must be a string"):(e.length>64&&t.push("Tool name must be 64 characters or less"),/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e)||t.push("Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens")),{valid:t.length===0,errors:t}}function IW(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return/^[a-zA-Z_]/.test(t)||(t=`_${t}`),t.length>64&&(t=t.slice(0,64)),t}var RW,BM=C({"src/lib/mcp/toolConverter.ts"(){"use strict";PE(),Kn(),RW={MCP_2024_11_05:{annotations:!0,inputSchema:!0,outputSchema:!1,streamingResults:!1,batchExecution:!1},NEUROLINK:{annotations:!0,inputSchema:!0,outputSchema:!0,streamingResults:!0,batchExecution:!0,categories:!0,tags:!0}}}}),$a,PW,zM,MW,Vc,ME,DW,oyt,syt,OW,NW,iyt,ayt,lyt,cyt,uyt,LW,dyt,$W,pyt,DE,FW,myt,Tm=C({"src/lib/providers/openaiChatCompletionsClient.ts"(){"use strict";t5(),BM(),em(),qi(),Qs(),$a=e=>e.replace(/\/+$/,""),PW=/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/,zM=(e,t)=>{if(e.every(o=>PW.test(o)&&!t?.has(o)))return;const r=new Map,n=new Map;for(const o of e){let s=PW.test(o)?o:IW(o);if(n.has(s)||t?.has(s)){let i=2,a;do{const l=`_${i}`;a=`${s.slice(0,64-l.length)}${l}`,i++}while(n.has(a)||t?.has(a));s=a}r.set(o,s),n.set(s,o)}return{toWire:r,fromWire:n}},MW=(e,t,r)=>{let n=0;for(const o of e){const s=typeof o.content=="string"?o.content:Vc(o.content);n+=pr(s,r)+hl;const i=o.tool_calls;i&&(n+=pr(Vc(i),r))}return t&&t.length>0&&(n+=pr(Vc(t),r)),n},Vc=e=>{try{return JSON.stringify(e??"")}catch{return String(e??"")}},ME=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return"{}"}},DW=e=>{if(e==null)return"";if(typeof e=="string")return e;if(typeof e!="object")return String(e);const t=e;switch(t.type){case"text":return typeof t.value=="string"?t.value:Vc(t.value);case"json":return Vc(t.value);case"execution-denied":return`Tool execution denied${t.reason?`: ${t.reason}`:""}`;case"error-text":return typeof t.value=="string"?t.value:Vc(t.value);case"error-json":return Vc(t.value);case"content":return Array.isArray(t.value)?t.value.map(r=>r&&typeof r=="object"&&r.type==="text"?String(r.text??""):"").filter(r=>r.length>0).join(`
|
|
1071
1071
|
`):"";default:return Vc(e)}},oyt=e=>{if(typeof e=="string")return e.startsWith("data:")||/^https?:\/\//i.test(e)?e:`data:image/png;base64,${e}`;if(e instanceof URL)return e.toString();if(e instanceof Uint8Array)return`data:image/png;base64,${Buffer.from(e).toString("base64")}`},syt=e=>{if(typeof e=="string")return e;if(!Array.isArray(e))return Vc(e);const t=[];for(const r of e){if(typeof r=="string"){t.push({type:"text",text:r});continue}if(!r||typeof r!="object")continue;const n=r;if(n.type==="text")t.push({type:"text",text:r.text??""});else if(n.type==="image"||n.type==="image_url"){const o=r.image??r.data??r.url,s=oyt(o);s&&t.push({type:"image_url",image_url:{url:s}})}}return t.length===1&&t[0].type==="text"?t[0].text:t},OW=(e,t)=>{const r=[];for(const n of e)switch(n.role){case"system":r.push({role:"system",content:typeof n.content=="string"?n.content:Vc(n.content)});break;case"user":r.push({role:"user",content:syt(n.content)});break;case"assistant":{const o=Array.isArray(n.content)?n.content:[n.content],s=[],i=[];for(const l of o)if(l&&typeof l=="object"){const c=l;if(c.type==="text")s.push({type:"text",text:l.text??""});else if(c.type==="tool-call"){const u=l,d=u.toolName??"";i.push({id:u.toolCallId??"",type:"function",function:{name:t?.get(d)??d,arguments:ME(u.input)}})}}else typeof l=="string"&&s.push({type:"text",text:l});const a=s.length===0?null:s.length===1&&s[0].type==="text"?s[0].text:s;r.push({role:"assistant",content:a,...i.length>0?{tool_calls:i}:{}});break}case"tool":{if(Array.isArray(n.content))for(const o of n.content){if(!o||typeof o!="object")continue;const s=o;s.type==="tool-result"&&r.push({role:"tool",tool_call_id:s.toolCallId??"",content:DW(s.output)})}else typeof n.content=="string"&&r.push({role:"tool",tool_call_id:n.toolCallId??"",content:n.content});break}}return r},NW=(e,t)=>{const r=Object.entries(e);if(r.length===0)return;const n=[];for(const[o,s]of r){const i=s,a=i.inputSchema??i.parameters,l=a?P5e($s(a)):{type:"object",properties:{}};n.push({type:"function",function:{name:t?.get(o)??o,...i.description?{description:i.description}:{},parameters:l}})}return n},iyt=(e,t)=>{if(!e||e.length===0)return;const r=[];for(const n of e)n.type==="function"&&r.push({type:"function",function:{name:t?.get(n.name)??n.name,...n.description?{description:n.description}:{},parameters:P5e(n.inputSchema),...n.strict!==void 0?{strict:n.strict}:{}}});return r.length>0?r:void 0},ayt=(e,t)=>{switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:t?.get(e.toolName)??e.toolName}}}},lyt=e=>e.type==="text"?{type:"text"}:e.schema?{type:"json_schema",json_schema:{name:e.name??"response",schema:e.schema,...e.description?{description:e.description}:{},strict:!0}}:{type:"json_object"},cyt=(e,t)=>{if(e){if(e==="auto"||e==="none"||e==="required")return e;if(typeof e=="object"&&e!==null){const r=e;if(r.type==="tool"&&r.toolName)return{type:"function",function:{name:t?.get(r.toolName)??r.toolName}}}}},uyt=e=>e.some(t=>{const r=t.content;return typeof r=="string"?/\bjson\b/i.test(r):Array.isArray(r)?r.some(n=>typeof n?.text=="string"&&/\bjson\b/i.test(n.text)):!1}),LW=e=>e.response_format?.type==="json_object"&&!uyt(e.messages)?{...e,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...e.messages]}:e,dyt=e=>/^(o\d|gpt-5)/i.test(e.replace(/^.*\//,"")),$W=e=>{const{modelId:t,messages:r,options:n,tools:o,toolChoice:s,streaming:i,responseFormat:a}=e,l={model:t,messages:r,...i?{stream:!0}:{},...i?{stream_options:{include_usage:!0}}:{}};n.maxTokens!==void 0&&n.maxTokens!==null&&(l.max_tokens=n.maxTokens);const c=Bc("openai-compatible",t,{...n.temperature!==void 0&&n.temperature!==null?{temperature:n.temperature}:{},...n.topP!==void 0&&n.topP!==null?{topP:n.topP}:{}},"openaiCompatible.buildBody");return c.temperature!==void 0&&(l.temperature=c.temperature),c.topP!==void 0&&(l.top_p=c.topP),n.presencePenalty!==void 0&&n.presencePenalty!==null&&(l.presence_penalty=n.presencePenalty),n.frequencyPenalty!==void 0&&n.frequencyPenalty!==null&&(l.frequency_penalty=n.frequencyPenalty),n.seed!==void 0&&n.seed!==null&&(l.seed=n.seed),n.stopSequences&&n.stopSequences.length>0&&(l.stop=n.stopSequences),o&&(l.tools=o),s!==void 0&&(l.tool_choice=s),a&&(l.response_format=a),n.extraBody&&Object.assign(l,n.extraBody),l},pyt=async(e,t,r)=>{const n={text:"",reasoning:"",toolCalls:new Map,finishReason:null,usage:void 0},o=new TextDecoder;let s;const a=X6({onEvent:c=>{const u=c.data;if(!u||u==="[DONE]")return;let d;try{d=JSON.parse(u)}catch(y){s=y instanceof Error?y:new Error(String(y));return}d.usage&&(n.usage=d.usage);const m=d.choices?.[0];if(!m)return;const f=m.delta;f?.content&&(n.text+=f.content,t(f.content));const g=f?.reasoning_content||f?.reasoning;if(g&&(n.reasoning+=g,r?.(g)),f?.tool_calls)for(const y of f.tool_calls){let v=n.toolCalls.get(y.index);v?y.id&&(v.id=y.id):(v={id:y.id??`call_${y.index}_${Date.now()}`,name:y.function?.name??"",argsBuffered:""},n.toolCalls.set(y.index,v)),y.function?.name&&(v.name=y.function.name),y.function?.arguments&&(v.argsBuffered+=y.function.arguments)}m.finish_reason&&(n.finishReason=m.finish_reason)}}),l=e.getReader();try{for(;;){const{done:c,value:u}=await l.read();if(c)break;a.feed(o.decode(u,{stream:!0}))}a.feed(o.decode())}finally{l.releaseLock()}if(s)throw s;return n},DE=async(e,t,r)=>{let n,o;try{n=await r.text(),o=n?JSON.parse(n):void 0}catch{o=void 0}const s=o?.error?.message??`OpenAI-compatible request failed with status ${r.status}`,i=new Error(s);return i.statusCode=r.status,i.responseHeaders=Object.fromEntries([...r.headers.entries()].filter(([a])=>{const l=a.toLowerCase();return l==="retry-after"||l.startsWith("x-ratelimit-")})),i.url=e,i.requestBody={model:t.model,stream:t.stream===!0,tool_count:t.tools?.length??0},n!==void 0&&(i.responseBody=n),i},FW=()=>{let e=()=>{};const t=new Promise(o=>{e=o});let r=()=>{};const n=new Promise(o=>{r=o});return{usagePromise:t,finishPromise:n,resolveUsage:e,resolveFinish:r}},myt=(e,t)=>{if(!e)return t;if(!t)return e;const r=(e.prompt_tokens_details?.cached_tokens??0)+(t.prompt_tokens_details?.cached_tokens??0),n=(e.completion_tokens_details?.reasoning_tokens??0)+(t.completion_tokens_details?.reasoning_tokens??0),o=s=>s.total_tokens||(s.prompt_tokens??0)+(s.completion_tokens??0);return{prompt_tokens:(e.prompt_tokens??0)+(t.prompt_tokens??0),completion_tokens:(e.completion_tokens??0)+(t.completion_tokens??0),total_tokens:o(e)+o(t),...r>0?{prompt_tokens_details:{cached_tokens:r}}:{},...n>0?{completion_tokens_details:{reasoning_tokens:n}}:{}}}}});function jM(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function ISr(e,t){let r=jM(e.content);return e.role==="assistant"&&e.tool_calls&&(r+=jM(e.tool_calls)),pr(r,t)+hl}function RSr(e,t){if(e.role!=="tool")return;const r=jM(e.content),n={maxBytes:UW,maxLines:BW};if(!kje(r,n))return;const{preview:o}=Wl(r,n);return pr(o,t)+hl}function PSr(e,t){return e.map(r=>{const n=ISr(r,t);if(r.role==="tool"){const o=RSr(r,t);return{kind:"toolResult",tokens:n,...o!==void 0?{previewTokens:o}:{}}}return r.role==="assistant"&&r.tool_calls?.length?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function MSr(e){const{conversation:t,availableInputTokens:r,fixedOverheadTokens:n,provider:o,observedPromptTokens:s,previousSentEstimate:i,onSentEstimate:a}=e,l=PSr(t,o),c=n+l.reduce((y,v)=>y+v.tokens,0);let u=1;s&&s>0&&i&&i>0&&(u=Math.min(3,Math.max(1,s/i)));const d=mW(l,{availableInputTokens:r,fixedOverheadTokens:n,calibration:u});if(!d.fire){a?.(c);return}const m=new Set(d.truncate),f=new Set(d.drop),g=[];for(let y=0;y<t.length;y++){if(f.has(y))continue;const v=t[y];if(m.has(y)&&v.role==="tool"){const{preview:w}=Wl(jM(v.content),{maxBytes:UW,maxLines:BW});g.push({...v,content:w});continue}g.push(v)}if(f.size>0){let y=g.findIndex(v=>v.role==="tool"||v.role==="assistant"&&v.tool_calls);y<0&&(y=Math.min(1,g.length)),g.splice(y,0,{role:"user",content:hyt})}return h.info("[OpenAICompatLoopGuard] Reclaimed agent-loop context",{provider:o,messagesBefore:t.length,messagesAfter:g.length,toolOutputsTruncated:d.truncate.length,messagesDropped:d.drop.length,projectedTokens:d.projectedTokens,calibration:u}),a?.(d.projectedTokens),g}var UW,BW,hyt,DSr=C({"src/lib/context/openaiCompatLoopGuard.ts"(){"use strict";Qs(),ef(),hW(),W(),UW=2048,BW=60,hyt="[Earlier tool exchanges were removed to fit the context window.]"}});function zW(e){const t=qW(e);return t?GW.some(({patterns:r})=>r.some(n=>n.test(t))):!1}function OSr(e){const t=qW(e);if(!t)return null;for(const{provider:r,patterns:n}of GW)if(n.some(o=>o.test(t)))return r;return null}function jW(e){const t=qW(e);if(!t||t.length>2e3)return null;const r=t.match(/resulted\s+in\s+(\d[\d,]{0,19})\s*tokens/i),n=t.match(/maximum\s+context\s+length\s+is\s+(\d[\d,]{0,19})/i);if(r&&n)return{actualTokens:parseInt(r[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10)};const o=t.match(/prompt\s+contains\s+at\s+least\s+(\d[\d,]{0,19})\s+input\s+tokens/i);if(o&&n){const a=t.match(/requested\s+(\d[\d,]{0,19})\s+output\s+tokens/i);return{actualTokens:parseInt(o[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10),...a?{requestedOutputTokens:parseInt(a[1].replace(/,/g,""),10)}:{}}}const s=t.match(/(\d[\d,]{0,19})\s*tokens?\s*[>:]\s*(\d[\d,]{0,19})/i);if(s)return{actualTokens:parseInt(s[1].replace(/,/g,""),10),budgetTokens:parseInt(s[2].replace(/,/g,""),10)};const i=t.match(/(\d[\d,]{0,19})\s*(?:>|exceeds)\s*(\d[\d,]{0,19})/i);return i?{actualTokens:parseInt(i[1].replace(/,/g,""),10),budgetTokens:parseInt(i[2].replace(/,/g,""),10)}:null}function qW(e){if(!e)return null;if(typeof e=="string")return e;if(e instanceof Error){const t=e.message,r=e?.cause;return r instanceof Error?`${t} ${r.message}`:t}if(typeof e=="object"){const t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error;if(typeof t.error=="object"&&t.error!==null){const r=t.error;if(typeof r.message=="string")return r.message}}return null}var GW,fyt=C({"src/lib/context/errorDetection.ts"(){"use strict";GW=[{provider:"openai",patterns:[/This model's maximum context length is/i,/tokens\. However, (?:your messages|you requested)/i,/reduce the length of the messages/i,/Please reduce the length/i]},{provider:"azure",patterns:[/content_length_exceeded/i]},{provider:"google",patterns:[/RESOURCE_EXHAUSTED/i,/exceeds the maximum number of tokens/i,/content is too long/i,/request payload size exceeds/i,/input token limit/i]},{provider:"bedrock",patterns:[/ValidationException.*token/i,/Input is too long/i,/exceeds the model's maximum/i]},{provider:"mistral",patterns:[/context length exceeded/i,/maximum number of tokens/i]},{provider:"openrouter",patterns:[/context_length_exceeded/i]},{provider:"anthropic",patterns:[/prompt is too long/i,/input is too long/i,/too many tokens/i,/maximum context length/i]}]}}),Fa,gyt=C({"src/lib/context/errors.ts"(){"use strict";Fa=class extends Error{estimatedTokens;availableTokens;stagesUsed;breakdown;constructor(e,t){super(e),this.name="ContextBudgetExceededError",this.estimatedTokens=t.estimatedTokens,this.availableTokens=t.availableTokens,this.stagesUsed=t.stagesUsed,this.breakdown=t.breakdown}}}}),yyt,HW,vyt=C({"src/lib/core/streamAnalytics.ts"(){"use strict";kb(),W(),xb(),_d(),yyt=class{async collectUsage(e){try{const t=await e.usage;return t?mv(t):(h.debug("No usage data available from stream result"),$6e())}catch(t){return Gl.isInstance(t)?h.debug("No output generated from stream \u2014 returning empty usage"):h.warn("Failed to collect usage from stream result",{error:t}),$6e()}}async collectMetadata(e){try{const[t,r]=await Promise.all([e.response,e.finishReason]);return{id:t?.id,model:t?.model,timestamp:t?.timestamp instanceof Date?t.timestamp.getTime():t?.timestamp||Date.now(),finishReason:r}}catch(t){return Gl.isInstance(t)?h.debug("No output generated from stream \u2014 returning default metadata"):h.warn("Failed to collect metadata from stream result",{error:t}),{timestamp:Date.now(),finishReason:"error"}}}async createAnalytics(e,t,r,n,o){try{const[s,i]=await Promise.all([this.collectUsage(r),this.collectMetadata(r)]),[a,l,c,u]=await Promise.all([Promise.resolve(r.text).catch(()=>""),Promise.resolve(r.finishReason).catch(()=>"error"),Promise.resolve(r.toolResults||[]).catch(()=>[]),Promise.resolve(r.toolCalls||[]).catch(()=>[])]);return hv(e,t,{usage:s,content:a,response:i,finishReason:l,toolResults:c,toolCalls:u},n,{...o,streamingMode:!0,responseId:i.id,finishReason:l})}catch(s){return h.error("Failed to create analytics from stream result",{provider:e,model:t,error:s instanceof Error?s.message:String(s)}),hv(e,t,{usage:{input:0,output:0,total:0}},n,{...o,streamingMode:!0,analyticsError:!0})}}cleanup(){const e=process.memoryUsage().heapUsed,t=500*1024*1024;typeof global<"u"&&global.gc&&e>t&&global.gc()}},HW=new yyt}});function _yt(e,t,r){return!r||!t||Object.keys(t).length===0?"none":e.toolChoice??"auto"}var wyt=C({"src/lib/utils/toolChoice.ts"(){"use strict"}}),qM,Ua,vl=C({"src/lib/providers/openaiChatCompletionsBase.ts"(){"use strict";Xt(),Mu(),DSr(),fyt(),gyt(),tc(),Fo(),vyt(),Zn(),W(),kr(),_d(),I9(),Pa(),fH(),wyt(),Sd(),Ph(),G1(),Tm(),Gv(),qM=512,Ua=class extends gl{config;resolvedModel;constructor(e,t,r,n){super(t,e,r),this.config=n}getFallbackModelName(){return"gpt-3.5-turbo"}getFallbackModels(){return[]}adjustBuildBodyOptions(e,t){return t}adjustResponseFormat(e,t){return e}suppressResponseFormatWithTools(){return!0}adjustRequestBody(e,t){return e}adjustBodyAfter400(e,t){}resolveWireMaxTokens(e,t,r,n){const o=gje(this.providerName,e);let s=t;o!==void 0&&(s===void 0||s>o)&&(s!==void 0&&h.debug(`${this.providerName}: clamping max_tokens ${s} to the advertised ${e} output ceiling ${o}`),s=o);const i=M0r(this.providerName,e);if(i!==void 0){const a=MW(r,n,this.providerName),l=i-a-qM;if(l<=0)throw new Fa(`Estimated input (${a} tokens) alone exceeds the ${this.providerName}/${e} context window advertised by the serving infrastructure (${i} tokens). Reduce the prompt/conversation size \u2014 no max_tokens value can make this request fit.`,{estimatedTokens:a,availableTokens:Math.max(0,i-qM),stagesUsed:[],breakdown:{}});s!==void 0&&s>l&&(h.warn(`${this.providerName}: max_tokens ${s} cannot fit the ${e} window (${i}) with ~${a} input tokens \u2014 re-fitting to ${l}`),s=l)}return s}correctBodyAfterContextOverflow(e,t){if(!zW(t))return;const r=jW(t)??jW(t.responseBody);if(!r||r.budgetTokens<=0)return;fje(this.providerName,e.model,r.budgetTokens);const n=typeof e.max_tokens=="number"?e.max_tokens:r.requestedOutputTokens;if(n===void 0||r.actualTokens<=0)return;const o=r.budgetTokens-r.actualTokens-qM;if(!(o<=0||o>=n))return h.warn(`${this.providerName}: ${e.model} rejected the request as over-window \u2014 retrying once with max_tokens re-fit from the provider's own numbers`,{window:r.budgetTokens,inputTokens:r.actualTokens,previousMaxTokens:n,refitMaxTokens:o}),{...e,max_tokens:o}}onStreamStart(e){}shouldAutoDiscoverModel(){return!0}getChatCompletionsURL(e){return`${$a(this.config.baseURL)}/chat/completions`}getAuthHeaders(){return{Authorization:`Bearer ${this.config.apiKey}`}}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}async probeModelsEndpoint(e={}){try{const t=`${$a(this.config.baseURL)}/models`,n=await Bt()(t,{headers:{...e,"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)});return n.ok?!!(await n.json().catch(()=>null))?.data?.some(s=>typeof s?.id=="string"&&s.id.trim().length>0):!1}catch(t){return h.debug(`[${this.constructor.name}] probeModelsEndpoint failed`,{baseURL:lo(this.config.baseURL),error:t instanceof Error?t.message:String(t)}),!1}}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}async getAISDKModel(){const e=await this.resolveModelName();return this.buildDelegatingModel(e)}async resolveModelName(){if(this.resolvedModel)return this.resolvedModel;const e=this.modelName||this.getDefaultModel();if(e&&e.trim()!=="")return this.resolvedModel=e,this.modelName!==e&&this.refreshHandlersForModel(e),e;if(this.shouldAutoDiscoverModel()){try{const r=await this.getAvailableModels();if(r.length>0)return this.resolvedModel=r[0],this.refreshHandlersForModel(r[0]),h.info(`\u{1F50D} Auto-discovered model: ${r[0]} from ${r.length} available models`),r[0]}catch(r){h.warn("Model auto-discovery failed, using fallback:",r)}return this.getFallbackModelName()}const t=this.getFallbackModelName();return this.resolvedModel=t,this.refreshHandlersForModel(t),t}buildDelegatingModel(e){const t=this.getChatCompletionsURL(e),r=Bt(),n=this.getAuthHeaders.bind(this),o=this.providerName,s=this.adjustBuildBodyOptions.bind(this),i=this.adjustResponseFormat.bind(this),a=this.adjustRequestBody.bind(this),l=this.adjustBodyAfter400.bind(this),c=this.correctBodyAfterContextOverflow.bind(this),u=this.resolveWireMaxTokens.bind(this),d=this.suppressResponseFormatWithTools.bind(this),m=f=>this.getTimeout(f??{});return{specificationVersion:"v3",provider:o,modelId:e,supportedUrls:{},doGenerate:async f=>{const g=zM((f.tools??[]).filter($=>$.type==="function").map($=>$.name)),y=OW(f.prompt,g?.toWire),v=Array.isArray(f.tools)&&f.tools.length>0,w=f.responseFormat&&!(v&&d())?i(lyt(f.responseFormat),e):void 0,b=iyt(f.tools,g?.toWire),T=u(e,f.maxOutputTokens,y,b),x=LW(a($W({modelId:e,messages:y,options:s(e,{maxTokens:T,temperature:f.temperature,topP:f.topP,presencePenalty:f.presencePenalty,frequencyPenalty:f.frequencyPenalty,seed:f.seed,stopSequences:f.stopSequences}),tools:b,...f.toolChoice?{toolChoice:ayt(f.toolChoice,g?.toWire)}:{},streaming:!1,...w?{responseFormat:w}:{}}),e)),k=f.providerOptions?.neurolink?.timeoutMs,R=Bl(typeof k=="number"?k:m(f),o,"generate"),{signal:P,dispose:I}=dir(f.abortSignal,R?.controller.signal);let A;try{let $=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(x),...P?{signal:P}:{}});if(!$.ok){const B=await DE(t,x,$),z=$.status===400?(()=>{const j=B,J=c(x,j);return l(J??x,j)??J})():void 0;if(!z)throw B;if($=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(z),...P?{signal:P}:{}}),!$.ok)throw await DE(t,z,$)}A=await $.json()}finally{R?.cleanup(),I()}const M=A.choices?.[0],O=(typeof M?.message?.content=="string"?M.message.content:"")??"",N=[],D=M?.message?.reasoning_content||M?.message?.reasoning;typeof D=="string"&&D.length>0&&N.push({type:"reasoning",text:D}),O.length>0&&N.push({type:"text",text:O});for(const $ of M?.message?.tool_calls??[])N.push({type:"tool-call",toolCallId:$.id,toolName:g?.fromWire.get($.function.name)??$.function.name,input:$.function.arguments??""});const F=M?.finish_reason;return{content:N,finishReason:{unified:F==="length"?"length":F==="tool_calls"||F==="function_call"?"tool-calls":F==="content_filter"?"content-filter":"stop",raw:F??"stop"},usage:{inputTokens:{total:A.usage?.prompt_tokens,noCache:A.usage?.prompt_tokens!==void 0&&A.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.max(0,A.usage.prompt_tokens-A.usage.prompt_tokens_details.cached_tokens):A.usage?.prompt_tokens,cacheRead:A.usage?.prompt_tokens!==void 0&&A.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.min(A.usage.prompt_tokens_details.cached_tokens,A.usage.prompt_tokens):A.usage?.prompt_tokens_details?.cached_tokens,cacheWrite:void 0},outputTokens:{total:A.usage?.completion_tokens,text:A.usage?.completion_tokens!==void 0&&A.usage?.completion_tokens_details?.reasoning_tokens!==void 0?Math.max(0,A.usage.completion_tokens-A.usage.completion_tokens_details.reasoning_tokens):A.usage?.completion_tokens,reasoning:A.usage?.completion_tokens_details?.reasoning_tokens}},warnings:[],request:{body:x},response:{...A.id?{id:A.id}:{},...A.model?{modelId:A.model}:{},headers:{},body:A}}},doStream:()=>{throw new Error(`${o}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}async executeStream(e,t){this.validateStreamOptions(e);const r=Date.now(),n=this.getTimeout(e),o=Bl(n,this.providerName,"stream"),s=new AbortController,i=Zpe([e.abortSignal,o?.controller.signal,s.signal]).signal;let a,l,c,u,d,m;try{a=await this.resolveModelName();const U=!e.disableTools&&this.supportsTools();l=U?e.tools||await this.getAllTools():{},c=U?zM(Object.keys(l)):void 0,u=U?NW(l,c?.toWire):void 0,d=cyt(_yt(e,l,U),c?.toWire);const $=await this.buildMessagesForStream(e);m=OW($,c?.toWire)}catch(U){throw o?.cleanup(),U}const f=this.getChatCompletionsURL(a),g=Bt(),y=e.maxSteps||Zs,v=this.neurolink?.getEventEmitter(),w=[],b=[],{usagePromise:T,finishPromise:x,resolveUsage:k,resolveFinish:R}=FW(),P=qv(),I=this.onStreamStart(a),A=this.runStreamLoop({maxSteps:y,modelId:a,url:f,fetchImpl:g,abortSignal:i,options:e,conversation:m,openAITools:u,openAIToolChoice:d,toolsRecord:l,toolNameFromWire:c?.fromWire,emitter:v,toolsUsed:w,toolExecutionSummaries:b,pushChunk:P.push,closeChannel:P.close,resolveUsage:k,resolveFinish:R});let M;const O=U=>{M=U};I?.onUsage&&T.then(I.onUsage).catch(()=>{}),I?.onFinish&&x.then(U=>I.onFinish?.(U,M)).catch(()=>{});const N=this.providerName,F={stream:async function*(){let U=0;try{for await(const $ of P.iterable)"content"in $&&typeof $.content=="string"&&$.content.length>0&&U++,yield $;if(await A,U===0&&w.length===0){h.warn(`${N}: Stream produced no output \u2014 emitting enriched sentinel`);const $=new Gl({message:"Stream produced no output"}),B=await Cf($,void 0,M);xf(B),yield B}}catch($){if(Gl.isInstance($)){const z=await Cf($,void 0,M);xf(z),yield z;return}const B=await Cf($,void 0,M);throw xf(B),yield B,$}finally{s.signal.aborted||s.abort()}}(),provider:this.providerName,model:a,analytics:HW.createAnalytics(this.providerName,a,{textStream:(async function*(){})(),usage:T,finishReason:x},Date.now()-r,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),toolsUsed:w,metadata:{startTime:r,streamId:`${this.providerName}-${Date.now()}`}};return Object.defineProperty(F,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>O1(b.map(U=>({toolName:U.toolName,input:U.input,output:U.output,duration:U.endTime.getTime()-U.startTime.getTime()})))}),A.finally(()=>o?.cleanup()).catch(U=>{O(U)}),F}async runStreamLoop(e){const{maxSteps:t,modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:l,openAIToolChoice:c,toolsRecord:u,toolNameFromWire:d,emitter:m,toolsUsed:f,toolExecutionSummaries:g,pushChunk:y,closeChannel:v,resolveUsage:w,resolveFinish:b}=e;let T=null,x;const k=()=>{const R=x?.prompt_tokens??0,P=x?.completion_tokens??0,I=Math.min(x?.prompt_tokens_details?.cached_tokens??0,R),A=Math.min(Math.max(0,x?.completion_tokens_details?.reasoning_tokens??0),P);return{promptTokens:R-I,completionTokens:P,totalTokens:x?.total_tokens||R+P,...I>0?{cacheReadTokens:I}:{},...A>0?{reasoningTokens:A}:{}}};try{let R=d,P,I;for(let A=0;A<t;A++){if(l){const N=new Set(l.map(F=>R?.get(F.function.name)??F.function.name)),D=Object.fromEntries(Object.entries(u).filter(([F])=>!N.has(F)));if(Object.keys(D).length>0){const F=zM(Object.keys(D),new Set(l.map(U=>U.function.name)));if(F){R??=new Map;for(const[U,$]of F.fromWire)R.set(U,$)}l.push(...NW(D,F?.toWire)??[]),h.info(`${this.providerName}: ${Object.keys(D).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(D).join(", ")}`)}}const M=MSr({conversation:a,availableInputTokens:qc(this.providerName,r,i.maxTokens??void 0),fixedOverheadTokens:MW([],l,this.providerName),provider:this.providerName,observedPromptTokens:P,previousSentEstimate:I,onSentEstimate:N=>{I=N}});M&&(a.length=0,a.push(...M));const O=await this.streamOneStep({modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:l,openAIToolChoice:c,pushChunk:y});if(P=O.usage?.prompt_tokens,T=O.finishReason,O.usage&&(x=myt(x,O.usage)),O.toolCalls.size===0)break;await this.executeToolBatch({stepResult:O,conversation:a,toolsRecord:u,toolNameFromWire:R,emitter:m,toolsUsed:f,toolExecutionSummaries:g,options:i})}return w(k()),b(T??"stop"),v(),{finishReason:T??"stop",usage:x}}catch(R){throw h.error(`${this.providerName}: Stream error`,{error:R instanceof Error?R.message:String(R)}),w(k()),b("error"),v(),R}}async streamOneStep(e){const t=this.resolveWireMaxTokens(e.modelId,e.options.maxTokens??void 0,e.conversation,e.openAITools),r=t!==e.options.maxTokens?{...e.options,maxTokens:t}:e.options,n=LW(this.adjustRequestBody($W({modelId:e.modelId,messages:e.conversation,options:this.adjustBuildBodyOptions(e.modelId,r),tools:e.openAITools,...e.openAIToolChoice!==void 0?{toolChoice:e.openAIToolChoice}:{},streaming:!0}),e.modelId)),o=async()=>{const i=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(n),...e.abortSignal?{signal:e.abortSignal}:{}});if(!i.ok)throw await DE(e.url,n,i);return i};let s;try{s=await Hy(o,Tt.getActiveSpan()??void 0,`${this.providerName} stream`)}catch(i){const a=i,l=a.statusCode===400?(()=>{const c=this.correctBodyAfterContextOverflow(n,a);return this.adjustBodyAfter400(c??n,a)??c})():void 0;if(!l)throw a;if(s=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(l),...e.abortSignal?{signal:e.abortSignal}:{}}),!s.ok)throw await DE(e.url,l,s)}if(!s.body)throw new Error(`${this.providerName}: stream response had no body`);return pyt(s.body,i=>{e.pushChunk({content:i})},i=>{e.pushChunk({content:"",reasoning:i})})}async executeToolBatch(e){const{stepResult:t,conversation:r,toolsRecord:n,toolNameFromWire:o,emitter:s,toolsUsed:i,toolExecutionSummaries:a,options:l}=e,c=[];for(const[,d]of t.toolCalls)c.push({id:d.id,type:"function",function:{name:d.name,arguments:d.argsBuffered}});r.push({role:"assistant",content:t.text.length>0?t.text:null,tool_calls:c});for(const[,d]of t.toolCalls){const m=new Date;let f;try{f=JSON.parse(d.argsBuffered||"{}")}catch{f=d.argsBuffered}let g,y;const v=o?.get(d.name)??d.name,w=n[v]??lH(n,v);if(s?.emit("tool:start",{toolName:v,toolCallId:d.id,input:f}),!w||typeof w.execute!="function")y=`Tool '${v}' is not registered.`,g={error:y};else try{g=await w.execute(f,{})}catch(T){y=T instanceof Error?T.message:String(T),g={error:y}}const b=new Date;i.push(v),a.push({toolCallId:d.id,toolName:v,input:f,output:g,...y?{error:y}:{},startTime:m,endTime:b}),r.push({role:"tool",tool_call_id:d.id,content:DW(g)})}const u=a.slice(-t.toolCalls.size);hH(s,u.map(d=>({toolName:d.toolName,output:d.output,...d.error?{error:d.error}:{}})));try{await this.handleToolExecutionStorage(u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,output:d.output})),u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,output:d.output})),l,new Date)}catch(d){h.warn(`[${this.constructor.name}] Failed to store tool executions`,{provider:this.providerName,error:d instanceof Error?d.message:String(d)})}}async getAvailableModels(){try{const e=`${$a(this.config.baseURL)}/models`;h.debug(`Fetching available models from: ${e}`);const t=Bt(),r=new AbortController,n=setTimeout(()=>r.abort(),5e3),o=await t(e,{headers:{...this.getAuthHeaders(),"Content-Type":"application/json"},signal:r.signal});if(clearTimeout(n),!o.ok)return h.warn(`Models endpoint returned ${o.status}: ${o.statusText}`),this.getFallbackModels();const s=await o.json();if(!s.data||!Array.isArray(s.data))return h.warn("Invalid models response format"),this.getFallbackModels();const i=s.data.map(a=>a.id).filter(Boolean);return h.shouldLog("debug")&&h.debug(`Discovered ${i.length} models:`,i),i.length>0?i:this.getFallbackModels()}catch(e){return h.warn(`[${this.constructor.name}] Failed to fetch models from endpoint:`,e),this.getFallbackModels()}}async getFirstAvailableModel(){return(await this.getAvailableModels())[0]||this.getFallbackModelName()}}}}),VW,Tyt,byt,Eyt,Syt,Cyt,NSr=C({"src/lib/providers/openAI/client.ts"(){"use strict";Xt(),Zn(),Ct(),W(),kr(),jc(),wi(),qo(),yl(),Nf(),Pa(),Tm(),vl(),VW="https://api.openai.com/v1",Tyt=(e,t)=>{const r=[e,t].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??VW;try{const n=new URL(r),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",$a(n.toString())}catch{}return r},byt=()=>Mi(QXt()),Eyt=()=>Di("OPENAI_MODEL","gpt-4o"),Syt=Tt.getTracer("neurolink.provider.openai"),Cyt=class extends Ua{constructor(e,t,r,n){const o=n?.apiKey?.trim(),s=o&&o.length>0?o:byt(),i=Tyt(n?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:i,apiKey:s}),h.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:lo(this.config.baseURL)})}suppressResponseFormatWithTools(){return!1}getProviderName(){return"openai"}getDefaultModel(){return Eyt()}formatProviderError(e){const t=e,r=t?.type&&typeof t.type=="string"?t.type:void 0,n=[{match:o=>o.statusCode===401||r==="invalid_api_key"||/API_KEY_INVALID|Invalid API key|Incorrect API key|invalid_api_key/i.test(o.message),errorClass:dr,message:o=>/Incorrect API key|Invalid API key/i.test(o.message)?o.message:"Invalid OpenAI API key. Please check your OPENAI_API_KEY environment variable."},{match:o=>o.statusCode===429||r==="rate_limit_error"||/rate limit/i.test(o.message),errorClass:Ws,message:"OpenAI rate limit exceeded. Please try again later."},{match:o=>/model_not_found/i.test(o.message),errorClass:no,message:o=>`Model not found: ${o.modelName}`},...os];return zi(e,n,this.providerName,this.modelName)}onStreamStart(e){const t=Syt.startSpan("neurolink.provider.streamText",{kind:$r.CLIENT,attributes:{"gen_ai.system":"openai","gen_ai.request.model":e}});let r=!1;const n=()=>{r||(r=!0,t.end())};return{onUsage:o=>{t.setAttribute("gen_ai.usage.input_tokens",o.promptTokens+(o.cacheReadTokens??0)+(o.cacheCreationTokens??0)),t.setAttribute("gen_ai.usage.output_tokens",o.completionTokens);const s=dl(this.providerName,e,{input:o.promptTokens,output:o.completionTokens,total:o.totalTokens,...o.cacheReadTokens?{cacheReadTokens:o.cacheReadTokens}:{},...o.cacheCreationTokens?{cacheCreationTokens:o.cacheCreationTokens}:{}});s&&s>0&&t.setAttribute("neurolink.cost",s)},onFinish:(o,s)=>{t.setAttribute("gen_ai.response.finish_reason",o||"unknown"),o==="error"&&t.setStatus({code:je.ERROR,message:s instanceof Error?s.message:String(s??"stream error")}),n()}}}getDefaultEmbeddingModel(){return process.env.OPENAI_EMBEDDING_MODEL||"text-embedding-3-small"}async embed(e,t){const r=t||this.getDefaultEmbeddingModel();h.debug("Generating embedding",{provider:this.providerName,model:r,textLength:e.length});try{const[n]=await this.callEmbeddings(r,[e],"embed");return h.debug("Embedding generated successfully",{provider:this.providerName,model:r,embeddingDimension:n.length}),n}catch(n){throw h.error("Embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,textLength:e.length}),this.handleProviderError(n)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel();h.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=await this.callEmbeddings(r,e,"embedMany");return h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:n.length,embeddingDimension:n[0]?.length}),n}catch(n){throw h.error("Batch embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,count:e.length}),this.handleProviderError(n)}}async callEmbeddings(e,t,r){const n=`${$a(this.config.baseURL)}/embeddings`,o=Bt(),s=Bl(3e4,this.providerName,"generate");try{const i=await o(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...s?.controller.signal?{signal:s.controller.signal}:{}});if(!i.ok){const c=await i.text().catch(()=>"");let u=`OpenAI ${r} failed with status ${i.status}`,d;if(c)try{const m=JSON.parse(c);m.error?.message&&(u=m.error.message),d=m.error?.type}catch{}throw Object.assign(new Error(u),{status:i.status,type:d})}const l=((await i.json()).data??[]).map(c=>c.embedding).filter(c=>Array.isArray(c));if(l.length===0)throw new bt(`OpenAI ${r} returned no embeddings`,this.providerName);return l}finally{s?.cleanup()}}async executeImageGeneration(e){const t=Date.now(),r=e.prompt??e.input?.text??"";if(!r.trim())throw new Error("OpenAI image generation requires a prompt (input.text or prompt)");const n=e.model??this.modelName,o=$a(this.config.baseURL??VW),s=e,i=s.size??this.aspectRatioToOpenAISize(s.aspectRatio,n),a=s.numberOfImages??1;let l;n==="gpt-image-1"||n.startsWith("dall-e-3")?l=1:n.startsWith("dall-e-2")?l=Math.min(Math.max(a,1),10):l=1;const u={model:n,prompt:r,n:l,size:i};n==="gpt-image-1"?s.quality&&(u.quality=s.quality):n.startsWith("dall-e-3")?(u.response_format="b64_json",s.quality&&(u.quality=s.quality),s.style&&(u.style=s.style)):u.response_format="b64_json";const d=12e4,m=new AbortController,f=setTimeout(()=>m.abort(),d);let g;try{g=await Bt()(`${o}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:m.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?new Error(`OpenAI image generation timed out after ${d/1e3}s`,{cause:T}):T}finally{clearTimeout(f)}if(!g.ok){const T=await g.text();throw new Error(`OpenAI image generation failed: ${g.status} \u2014 ${T}`)}const v=(await g.json()).data?.[0];if(!v)throw new Error("OpenAI image generation returned no images");let w=v.b64_json;if(!w&&v.url){await Of(v.url);const T=Bt(),x=new AbortController,k=setTimeout(()=>x.abort(),6e4);let R;try{R=await T(v.url,{signal:x.signal})}catch(I){throw I instanceof Error&&I.name==="AbortError"?new Error("OpenAI image URL download timed out after 60s",{cause:I}):I}finally{clearTimeout(k)}if(!R.ok)throw new Error(`OpenAI image generation: failed to fetch hosted URL ${v.url} (${R.status})`);w=(await Od(R,Df,"OpenAI image fallback")).toString("base64")}if(!w)throw new Error("OpenAI image generation returned neither b64_json nor a URL");const b=Date.now()-t;return h.info(`[OpenAIProvider] Generated image (${w.length} base64 chars) in ${b}ms \u2014 model ${n}`),{content:v.revised_prompt??r,provider:this.providerName,model:n,usage:{input:0,output:0,total:0},imageOutput:{base64:w}}}aspectRatioToOpenAISize(e,t){return t==="gpt-image-1"?e==="16:9"||e==="3:2"?"1536x1024":e==="9:16"||e==="2:3"?"1024x1536":"1024x1024":t.startsWith("dall-e-3")?e==="16:9"||e==="3:2"?"1792x1024":e==="9:16"||e==="2:3"?"1024x1792":"1024x1024":"1024x1024"}}}}),xyt={};de(xyt,{OpenAIProvider:()=>Cyt});var LSr=C({"src/lib/providers/openAI/index.ts"(){"use strict";NSr()}});function Ge(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r}function V(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var _l=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/tslib.mjs"(){}}),OE,WW=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs"(){OE=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return OE=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}}});function Kv(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var NE,Jv=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/errors.mjs"(){NE=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)}}}),pt,Vi,oc,Yv,KW,Ayt,JW,YW,ZW,XW,QW,eK,tK,rK,Xn=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/error.mjs"(){Jv(),pt=class extends Error{},Vi=class Ise extends pt{constructor(t,r,n,o,s){super(`${Ise.makeMessage(t,r,n)}`),this.status=t,this.headers=o,this.requestID=o?.get("request-id"),this.error=r,this.type=s??null}static makeMessage(t,r,n){const o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,r,n,o){if(!t||!o)return new Yv({message:n,cause:NE(r)});const s=r,i=s?.error?.type;return t===400?new JW(t,s,n,o,i):t===401?new YW(t,s,n,o,i):t===403?new ZW(t,s,n,o,i):t===404?new XW(t,s,n,o,i):t===409?new QW(t,s,n,o,i):t===422?new eK(t,s,n,o,i):t===429?new tK(t,s,n,o,i):t>=500?new rK(t,s,n,o,i):new Ise(t,s,n,o,i)}},oc=class extends Vi{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Yv=class extends Vi{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},KW=class extends Yv{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ayt=class extends pt{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},JW=class extends Vi{},YW=class extends Vi{},ZW=class extends Vi{},XW=class extends Vi{},QW=class extends Vi{},eK=class extends Vi{},tK=class extends Vi{},rK=class extends Vi{}}});function nK(e){return typeof e!="object"?{}:e??{}}function kyt(e){if(!e)return!0;for(const t in e)return!1;return!0}function $Sr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var Iyt,Ryt,ga,oK,Pyt,sK,Ld=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs"(){Xn(),Iyt=/^[a-z][a-z0-9+.-]*:/i,Ryt=e=>Iyt.test(e),ga=e=>(ga=Array.isArray,ga(e)),oK=ga,Pyt=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new pt(`${e} must be an integer`);if(t<0)throw new pt(`${e} must be a positive integer`);return t},sK=e=>{try{return JSON.parse(e)}catch{return}}}}),bm,LE=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"(){bm=(e,t)=>new Promise(r=>{if(t?.aborted)return r();const n=()=>{clearTimeout(o),r()},o=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}}),$d,GM=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/version.mjs"(){$d="0.102.0"}});function FSr(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function USr(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:r}of e){const n=r.exec(navigator.userAgent);if(n){const o=n[1]||0,s=n[2]||0,i=n[3]||0;return{browser:t,version:`${o}.${s}.${i}`}}}return null}var Myt,Dyt,iK,aK,Oyt,HM,lK=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs"(){GM(),Myt=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Dyt=()=>{const e=FSr();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$d,"X-Stainless-OS":aK(Deno.build.os),"X-Stainless-Arch":iK(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$d,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$d,"X-Stainless-OS":aK(globalThis.process.platform??"unknown"),"X-Stainless-Arch":iK(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=USr();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$d,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$d,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},iK=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",aK=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),HM=()=>Oyt??(Oyt=Dyt())}});function BSr(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Nyt(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Lyt(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Nyt({start(){},async pull(r){const{done:n,value:o}=await t.next();n?r.close():r.enqueue(o)},async cancel(){await t.return?.()}})}function cK(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){const r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function zSr(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}const t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var $E=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/shims.mjs"(){}}),$yt,jSr=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/request-options.mjs"(){$yt=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)})}}),uK,dK,pK,Fyt,Uyt=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs"(){uK="RFC3986",dK=e=>String(e),pK={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:dK},Fyt="RFC1738"}});function qSr(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Byt(e,t){if(ga(e)){const r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}var VM,Wc,WM,zyt,GSr=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs"(){Uyt(),Ld(),VM=(e,t)=>(VM=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),VM(e,t)),Wc=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),WM=1024,zyt=(e,t,r,n,o)=>{if(e.length===0)return e;let s=e;if(typeof e=="symbol"?s=Symbol.prototype.toString.call(e):typeof e!="string"&&(s=String(e)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=WM){const l=s.length>=WM?s.slice(a,a+WM):s,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===Fyt&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=Wc[d];continue}if(d<2048){c[c.length]=Wc[192|d>>6]+Wc[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=Wc[224|d>>12]+Wc[128|d>>6&63]+Wc[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=Wc[240|d>>18]+Wc[128|d>>12&63]+Wc[128|d>>6&63]+Wc[128|d&63]}i+=c.join("")}return i}}});function HSr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}function jyt(e,t,r,n,o,s,i,a,l,c,u,d,m,f,g,y,v,w){let b=e,T=w,x=0,k=!1;for(;(T=T.get(KM))!==void 0&&!k;){const M=T.get(e);if(x+=1,typeof M<"u"){if(M===x)throw new RangeError("Cyclic object value");k=!0}typeof T.get(KM)>"u"&&(x=0)}if(typeof c=="function"?b=c(t,b):b instanceof Date?b=m?.(b):r==="comma"&&ga(b)&&(b=Byt(b,function(M){return M instanceof Date?m?.(M):M})),b===null){if(s)return l&&!y?l(t,gs.encoder,v,"key",f):t;b=""}if(HSr(b)||qSr(b)){if(l){const M=y?t:l(t,gs.encoder,v,"key",f);return[g?.(M)+"="+g?.(l(b,gs.encoder,v,"value",f))]}return[g?.(t)+"="+g?.(String(b))]}const R=[];if(typeof b>"u")return R;let P;if(r==="comma"&&ga(b))y&&l&&(b=Byt(b,l)),P=[{value:b.length>0?b.join(",")||null:void 0}];else if(ga(c))P=c;else{const M=Object.keys(b);P=u?M.sort(u):M}const I=a?String(t).replace(/\./g,"%2E"):String(t),A=n&&ga(b)&&b.length===1?I+"[]":I;if(o&&ga(b)&&b.length===0)return A+"[]";for(let M=0;M<P.length;++M){const O=P[M],N=typeof O=="object"&&typeof O.value<"u"?O.value:b[O];if(i&&N===null)continue;const D=d&&a?O.replace(/\./g,"%2E"):O,F=ga(b)?typeof r=="function"?r(A,D):A:A+(d?"."+D:"["+D+"]");w.set(e,x);const U=new WeakMap;U.set(KM,w),hK(R,jyt(N,F,r,n,o,s,i,a,r==="comma"&&y&&ga(b)?null:l,c,u,d,m,f,g,y,v,U))}return R}function VSr(e=gs){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");const t=e.charset||gs.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=uK;if(typeof e.format<"u"){if(!VM(pK,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const n=pK[r];let o=gs.filter;(typeof e.filter=="function"||ga(e.filter))&&(o=e.filter);let s;if(e.arrayFormat&&e.arrayFormat in mK?s=e.arrayFormat:"indices"in e?s=e.indices?"indices":"repeat":s=gs.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:gs.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:gs.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:gs.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:gs.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?gs.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:gs.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:gs.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:gs.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:gs.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:gs.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:gs.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:gs.strictNullHandling}}function WSr(e,t={}){let r=e;const n=VSr(t);let o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ga(n.filter)&&(s=n.filter,o=s);const i=[];if(typeof r!="object"||r===null)return"";const a=mK[n.arrayFormat],l=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);const c=new WeakMap;for(let m=0;m<o.length;++m){const f=o[m];n.skipNulls&&r[f]===null||hK(i,jyt(r[f],f,a,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}const u=i.join(n.delimiter);let d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}var mK,hK,qyt,gs,KM,KSr=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs"(){GSr(),Uyt(),Ld(),mK={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},hK=function(e,t){Array.prototype.push.apply(e,ga(t)?t:[t])},gs={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:zyt,encodeValuesOnly:!1,format:uK,formatter:dK,indices:!1,serializeDate(e){return(qyt??(qyt=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},KM={}}});function JSr(e){return WSr(e,{arrayFormat:"brackets"})}var Gyt=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs"(){KSr()}});function Hyt(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new mn(`Invalid token endpoint base URL "${e}": ${n}`)}if(t.protocol==="https:")return;const r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(t.protocol==="http:"&&(r==="localhost"||r==="127.0.0.1"||r==="::1")))throw new mn(`Refusing to send credential over non-https token endpoint "${e}"`)}async function Vyt(e,t){const r=await YSr(e);let n;try{n=JSON.parse(r)}catch{throw new mn(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,sc(r),t)}if(!n.access_token)throw new mn(`Token endpoint response missing access_token: ${JSON.stringify(sc(n))}`,e.status,sc(n),t);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new mn(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,sc(n),t);return n}function sc(e){if(e==null)return e;if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{return e.length<=YM?e:e.slice(0,YM)+`... <${e.length-YM} more chars>`}return JSON.stringify(sc(t))}if(typeof e=="object"&&!Array.isArray(e)){const t={};for(const[r,n]of Object.entries(e))evt.has(r)&&(t[r]=n);return t}return null}async function Wyt(e,t=r=>console.warn(`anthropic-sdk: ${r}`)){if(typeof process>"u"||process.platform==="win32")return;const r=await Promise.resolve().then(()=>(Jo(),xd));let n=e,o;try{n=await r.promises.realpath(e),o=await r.promises.stat(n)}catch{return}const s=o.mode&511;if(s&18)throw new mn(`Credentials file at ${n} is group/world-writable (mode 0o${s.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${n}\`.`);if(s&36)throw new mn(`Credentials file at ${n} is group/world-readable (mode 0o${s.toString(8)}); run \`chmod 600 ${n}\` before retrying.`);typeof process.getuid=="function"&&o.uid!==process.getuid()&&t(`credentials file at ${n} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function Kyt(e,t){const r=await Promise.resolve().then(()=>(Jo(),xd)),o=(await Promise.resolve().then(()=>(Gr(),im))).dirname(e);await r.promises.mkdir(o,{recursive:!0,mode:448});const s=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const i=await r.promises.open(s,"w",384);try{await i.writeFile(JSON.stringify(t,null,2)),await i.sync()}finally{await i.close()}await r.promises.rename(s,e)}catch(i){throw await r.promises.unlink(s).catch(()=>{}),i}try{const i=await r.promises.open(o,"r");try{await i.sync()}finally{await i.close()}}catch{}}async function YSr(e){if(!e.body)return"";const t=e.body.getReader(),r=[];let n=0;for(;;){const{done:s,value:i}=await t.read();if(s)break;if(n+i.length>gK){const a=gK-n;a>0&&r.push(i.subarray(0,a)),await t.cancel();break}r.push(i),n+=i.length}let o;if(r.length===1)o=r[0];else{o=new Uint8Array(r.reduce((i,a)=>i+a.length,0));let s=0;for(const i of r)o.set(i,s),s+=i.length}return new TextDecoder("utf-8").decode(o)}var Jyt,Yyt,fK,FE,Zyt,Xyt,JM,Qyt,gK,YM,evt,mn,UE=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs"(){Xn(),Jyt="urn:ietf:params:oauth:grant-type:jwt-bearer",Yyt="refresh_token",fK="/v1/oauth/token",FE="oauth-2025-04-20",Zyt="oidc-federation-2026-04-01",Xyt=120,JM=30,Qyt=5,gK=1<<20,YM=2e3,evt=new Set(["error","error_description","error_uri"]),mn=class extends pt{constructor(e,t=null,r=null,n=null){super(e),this.statusCode=t,this.body=r,this.requestId=n}}}});function Lf(){return Math.floor(Date.now()/1e3)}var ZM=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/time.mjs"(){}}),tvt,ZSr=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs"(){UE(),ZM(),tvt=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){const e=this.nextForce;this.nextForce=!1;const t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;const r=t.expiresAt-Lf();return r>Xyt?t.token:r>JM?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||Lf()-this.lastAdvisoryError<Qyt||this.doRefresh().catch(e=>{this.lastAdvisoryError=Lf(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(t=>(this.cached=t,this.pendingRefresh=null,t),t=>{throw this.pendingRefresh=null,t}),this.pendingRefresh}}}}),Ir,XM=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs"(){Ir=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0}}});function XSr(e){let t=0;for(const o of e)t+=o.length;const r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function yK(e){let t;return(nvt??(t=new globalThis.TextEncoder,nvt=t.encode.bind(t)))(e)}function rvt(e){let t;return(ovt??(t=new globalThis.TextDecoder,ovt=t.decode.bind(t)))(e)}var nvt,ovt,vK=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs"(){}}),QSr=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs"(){Xn(),vK()}});function BE(){}function QM(e,t,r){return!t||zE[e]>zE[r]?BE:t[e].bind(t)}function Qn(e){const t=e.logger,r=e.logLevel??"off";if(!t)return svt;const n=wK.get(t);if(n&&n[0]===r)return n[1];const o={error:QM("error",t,r),warn:QM("warn",t,r),info:QM("info",t,r),debug:QM("debug",t,r)};return wK.set(t,[r,o]),o}var zE,_K,svt,wK,Fd,Em=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs"(){Ld(),zE={off:0,error:200,warn:300,info:400,debug:500},_K=(e,t,r)=>{if(e){if($Sr(zE,e))return e;Qn(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(zE))}`)}},svt={error:BE,warn:BE,info:BE,debug:BE},wK=new WeakMap,Fd=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="api-key"||t.toLowerCase()==="x-api-key"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e)}}),ivt=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils.mjs"(){Ld(),QSr(),XM(),Em(),WW(),LE(),Gyt()}});function avt(e){if(!e)throw new Error("profile name is empty");if(e==="."||e==="..")throw new Error(`profile name "${e}" is not allowed`);if(e.includes("/")||e.includes("\\"))throw new Error(`profile name "${e}" must not contain path separators`);if(!lvt.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var TK,lvt,cvt,uvt,eD,dvt,bK,pvt=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/credentials.mjs"(){lK(),ivt(),TK="1.0",lvt=/^[A-Za-z0-9_.-]+$/,cvt=async e=>{var t,r;const n=await eD();if(n===null)return null;const o=e??await bK();if(o===null)return null;avt(o);const s=await Promise.resolve().then(()=>(Jo(),xd)),a=(await Promise.resolve().then(()=>(Gr(),im))).join(n,"configs",`${o}.json`);let l;try{l=await s.promises.readFile(a,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${a}: ${d}`);l=null}if(l===null){const d=Ir("ANTHROPIC_ORGANIZATION_ID"),m=Ir("ANTHROPIC_IDENTITY_TOKEN_FILE"),f=Ir("ANTHROPIC_FEDERATION_RULE_ID");return f&&d?{fromFile:!1,config:{organization_id:d,workspace_id:Ir("ANTHROPIC_WORKSPACE_ID"),base_url:Ir("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:f,service_account_id:Ir("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:m?{source:"file",path:m}:void 0,scope:Ir("ANTHROPIC_SCOPE")}}}:null}let c;try{c=JSON.parse(l)}catch(d){throw new Error(`failed to parse config file ${a}: ${d}`)}if(!c.authentication)throw new Error(`config file ${a} is missing "authentication"`);const u=c.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw new Error(`authentication.type "${u}" is not a known authentication type`);if(c.organization_id??(c.organization_id=Ir("ANTHROPIC_ORGANIZATION_ID")),c.workspace_id??(c.workspace_id=Ir("ANTHROPIC_WORKSPACE_ID")),c.base_url??(c.base_url=Ir("ANTHROPIC_BASE_URL")),(t=c.authentication).scope??(t.scope=Ir("ANTHROPIC_SCOPE")),c.authentication.type==="oidc_federation"){if(!c.authentication.identity_token){const d=Ir("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(c.authentication.identity_token={source:"file",path:d})}c.authentication.federation_rule_id||(c.authentication.federation_rule_id=Ir("ANTHROPIC_FEDERATION_RULE_ID")??""),(r=c.authentication).service_account_id??(r.service_account_id=Ir("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:c,fromFile:!0}},uvt=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const r=await eD();if(!r)return null;const n=t??await bK();return n?(avt(n),(await Promise.resolve().then(()=>(Gr(),im))).join(r,"credentials",`${n}.json`)):null},eD=async()=>{if(!dvt())return null;const e=await Promise.resolve().then(()=>(Gr(),im)),t=Ir("ANTHROPIC_CONFIG_DIR");if(t)return t;if(HM()["X-Stainless-OS"]==="Windows"){const s=Ir("APPDATA");if(s)return e.join(s,"Anthropic");const i=Ir("USERPROFILE");return i?e.join(i,"AppData","Roaming","Anthropic"):null}const n=Ir("XDG_CONFIG_HOME");if(n)return e.join(n,"anthropic");const o=Ir("HOME");return o?e.join(o,".config","anthropic"):null},dvt=()=>{const e=HM()["X-Stainless-Runtime"];return e==="node"||e==="deno"},bK=async()=>{const e=await eD();if(!e)return null;const t=Ir("ANTHROPIC_PROFILE");if(t)return t;const r=await Promise.resolve().then(()=>(Jo(),xd)),o=(await Promise.resolve().then(()=>(Gr(),im))).join(e,"active_config");try{return(await r.promises.readFile(o,"utf-8")).trim()||"default"}catch(s){if(s?.code!=="ENOENT")throw new Error(`failed to read ${o}: ${s}`);return"default"}}}});function mvt(e){if(!e)throw new pt("Identity token file path is empty");return async()=>{const t=await Promise.resolve().then(()=>(Jo(),xd));let r;try{r=await t.promises.readFile(e,"utf-8")}catch(o){throw new pt(`Failed to read identity token file at ${e}: ${o}`)}const n=r.trim();if(!n)throw new pt(`Identity token file at ${e} is empty`);return n}}function eCr(e){if(!e)throw new pt("Identity token value is empty");return()=>e}var tCr=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs"(){Xn()}});function rCr(e){return async()=>{Hyt(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16*1024)throw new mn(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const r={grant_type:Jyt,assertion:t,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(r.service_account_id=e.serviceAccountId),e.workspaceId&&(r.workspace_id=e.workspaceId);const n=`${e.baseURL}${fK}`;let o;try{o=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${FE},${Zyt}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${$d} oidcFederationProvider`},body:JSON.stringify(r)})}catch(l){throw new mn(`Failed to reach token endpoint ${n}: ${l}`)}const s=o.headers.get("Request-Id");if(!o.ok){const l=await o.text().catch(()=>""),c=sc(l);let u="";throw o.status===401&&(u=` Ensure your federation rule matches your identity token. ${e.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new mn(`Token exchange failed with status ${o.status}${s?` (request-id ${s})`:""}: ${c}${u}`,o.status,c,s)}const i=await Vyt(o,s),a=Number(i.expires_in);if(!Number.isFinite(a))throw new mn(`Token endpoint response missing required fields: ${JSON.stringify(sc(i))}`,o.status,sc(i),s);return{token:i.access_token,expiresAt:Lf()+a}}}var nCr=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs"(){UE(),ZM(),GM()}});function oCr(e){return async t=>{const r=await Promise.resolve().then(()=>(Jo(),xd));await Wyt(e.credentialsPath,e.onSafetyWarning);let n;try{n=await r.promises.readFile(e.credentialsPath,"utf-8")}catch(v){throw new mn(`Credentials file not found at ${e.credentialsPath}: ${v}`)}let o;try{o=JSON.parse(n)}catch(v){throw new mn(`Credentials file at ${e.credentialsPath} is not valid JSON: ${v}`)}const s=o.access_token;if(!s)throw new mn(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const i=o.expires_at;if(!t?.forceRefresh&&(i==null||Lf()<i-JM))return{token:s,expiresAt:i??null};const a=o.refresh_token;if(!e.clientId||!a)throw new mn(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);Hyt(e.baseURL);const l={grant_type:Yyt,refresh_token:a,client_id:e.clientId},c=`${e.baseURL}${fK}`;let u;try{u=await e.fetch(c,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":FE,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${$d} userOAuthProvider`},body:JSON.stringify(l)})}catch(v){throw new mn(`User OAuth refresh failed to reach token endpoint: ${v}`)}const d=u.headers.get("Request-Id");if(!u.ok){const v=await u.text().catch(()=>"");throw new mn(`User OAuth refresh failed (HTTP ${u.status}): ${sc(v)}`,u.status,sc(v),d)}const m=await Vyt(u,d),f=Number(m.expires_in);if(!Number.isFinite(f))throw new mn(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(sc(m))}`,u.status,sc(m),d);const g=Lf()+f,y=m.refresh_token||a;return await Kyt(e.credentialsPath,{...o,version:TK,type:"oauth_token",access_token:m.access_token,expires_at:g,refresh_token:y}),{token:m.access_token,expiresAt:g}}}var sCr=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs"(){pvt(),UE(),ZM(),GM()}});function hvt(e,t){const r=e.authentication.credentials_path??null,n=(e.base_url||t.baseURL).replace(/\/+$/,""),o=aCr(e,r,n,t),s={};return e.workspace_id&&e.authentication.type==="user_oauth"&&(s["anthropic-workspace-id"]=e.workspace_id),{provider:o,extraHeaders:s,baseURL:e.base_url||void 0}}async function iCr(e,t){const r=await cvt(t);if(!r)return null;const{config:n,fromFile:o}=r,s=n.authentication.credentials_path||!o?n:{...n,authentication:{...n.authentication,credentials_path:await uvt(n,t)??void 0}};return hvt(s,e)}function aCr(e,t,r,n){switch(e.authentication.type){case"oidc_federation":{const o=e.authentication,s=lCr(o);if(!s)throw new mn("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!o.federation_rule_id)throw new mn("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!e.organization_id)throw new mn("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const i=rCr({identityTokenProvider:s,federationRuleId:o.federation_rule_id,organizationId:e.organization_id,serviceAccountId:o.service_account_id,workspaceId:e.workspace_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent});return t?cCr(i,t,n.onCacheWriteError,n.onSafetyWarning):i}case"user_oauth":{if(!t)throw new mn("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return oCr({credentialsPath:t,clientId:e.authentication.client_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent,onSafetyWarning:n.onSafetyWarning})}default:{const o=e.authentication.type;throw new mn(`authentication.type "${o}" is not a known authentication type`)}}}function lCr(e){if(e.identity_token){const n=e.identity_token.source;if(n!=="file")throw new mn(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new mn('identity_token.source "file" requires a non-empty path');return mvt(e.identity_token.path)}const t=Ir("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return mvt(t);const r=Ir("ANTHROPIC_IDENTITY_TOKEN");return r?eCr(r):null}function cCr(e,t,r,n){return async o=>{const s=await Promise.resolve().then(()=>(Jo(),xd));await Wyt(t,n);let i;try{const l=await s.promises.readFile(t,"utf-8");i=JSON.parse(l);const c=i?.access_token;if(c&&!o?.forceRefresh){const u=i?.expires_at;if(u==null||Lf()<u-JM)return{token:c,expiresAt:u??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&r?.(l)}const a=await e(o);try{await Kyt(t,{...i??{},version:TK,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(l){r?.(l)}return a}}var uCr=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs"(){XM(),pvt(),UE(),ZM(),tCr(),nCr(),sCr()}});function dCr(e,t){for(let o=t??0;o<e.length;o++){if(e[o]===10)return{preceding:o,index:o+1,carriage:!1};if(e[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function pCr(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var wl,Tl,Zv,fvt=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"(){_l(),vK(),Zv=class{constructor(){wl.set(this,void 0),Tl.set(this,void 0),Ge(this,wl,new Uint8Array,"f"),Ge(this,Tl,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?yK(e):e;Ge(this,wl,XSr([V(this,wl,"f"),t]),"f");const r=[];let n;for(;(n=dCr(V(this,wl,"f"),V(this,Tl,"f")))!=null;){if(n.carriage&&V(this,Tl,"f")==null){Ge(this,Tl,n.index,"f");continue}if(V(this,Tl,"f")!=null&&(n.index!==V(this,Tl,"f")+1||n.carriage)){r.push(rvt(V(this,wl,"f").subarray(0,V(this,Tl,"f")-1))),Ge(this,wl,V(this,wl,"f").subarray(V(this,Tl,"f")),"f"),Ge(this,Tl,null,"f");continue}const o=V(this,Tl,"f")!==null?n.preceding-1:n.preceding,s=rvt(V(this,wl,"f").subarray(0,o));r.push(s),Ge(this,wl,V(this,wl,"f").subarray(n.index),"f"),Ge(this,Tl,null,"f")}return r}flush(){return V(this,wl,"f").length?this.decode(`
|
|
1072
1072
|
`):[]}},wl=new WeakMap,Tl=new WeakMap,Zv.NEWLINE_CHARS=new Set([`
|
|
1073
1073
|
`,"\r"]),Zv.NEWLINE_REGEXP=/\r\n|[\n\r]/g}});async function*mCr(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new pt("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new pt("Attempted to iterate over a response with no body");const r=new gvt,n=new Zv,o=cK(e.body);for await(const s of hCr(o))for(const i of n.decode(s)){const a=r.decode(i);a&&(yield a)}for(const s of n.flush()){const i=r.decode(s);i&&(yield i)}}async function*hCr(e){let t=new Uint8Array;for await(const r of e){if(r==null)continue;const n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?yK(r):r;let o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let s;for(;(s=pCr(t))!==-1;)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}function fCr(e,t){const r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}var jE,$f,gvt,EK=C({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/streaming.mjs"(){_l(),Xn(),$E(),fvt(),$E(),Jv(),Ld(),vK(),Em(),Xn(),$f=class tA{constructor(t,r,n){this.iterator=t,jE.set(this,void 0),this.controller=r,Ge(this,jE,n,"f")}static fromSSEResponse(t,r,n){let o=!1;const s=n?Qn(n):console;async function*i(){if(o)throw new pt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(const l of mCr(t,r)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(c){throw s.error("Could not parse message into JSON:",l.data),s.error("From chunk:",l.raw),c}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="user.tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="session.updated"||l.event==="span.model_request_start"||l.event==="span.model_request_end"||l.event==="span.outcome_evaluation_start"||l.event==="span.outcome_evaluation_ongoing"||l.event==="span.outcome_evaluation_end"||l.event==="user.define_outcome"||l.event==="agent.thread_message_received"||l.event==="agent.thread_message_sent"||l.event==="agent.session_thread_message_received"||l.event==="agent.session_thread_message_sent"||l.event==="session.thread_created"||l.event==="session.thread_status_created"||l.event==="session.thread_status_running"||l.event==="session.thread_status_idle"||l.event==="session.thread_status_rescheduled"||l.event==="session.thread_status_terminated")try{yield JSON.parse(l.data)}catch(c){throw s.error("Could not parse message into JSON:",l.data),s.error("From chunk:",l.raw),c}if(l.event!=="ping"&&l.event==="error"){const c=sK(l.data)??l.data,u=c?.error?.type;throw new Vi(void 0,c,void 0,t.headers,u)}}a=!0}catch(l){if(Kv(l))return;throw l}finally{a||r.abort()}}return new tA(i,r,n)}static fromReadableStream(t,r,n){let o=!1;async function*s(){const a=new Zv,l=cK(t);for await(const c of l)for(const u of a.decode(c))yield u;for(const c of a.flush())yield c}async function*i(){if(o)throw new pt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(const l of s())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(Kv(l))return;throw l}finally{a||r.abort()}}return new tA(i,r,n)}[(jE=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],r=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){const i=n.next();t.push(i),r.push(i)}return s.shift()}});return[new tA(()=>o(t),this.controller,V(this,jE,"f")),new tA(()=>o(r),this.controller,V(this,jE,"f"))]}toReadableStream(){const t=this;let r;return Nyt({async start(){r=t[Symbol.asyncIterator]()},async pull(n){try{const{value:o,done:s}=await r.next();if(s)return n.close();const i=yK(JSON.stringify(o)+`
|
|
@@ -101,13 +101,19 @@ export function createGeminiLoopAdapter(config) {
|
|
|
101
101
|
},
|
|
102
102
|
async executeStep(request, channel, signal) {
|
|
103
103
|
const rawStream = await config.sendStep(request.raw, signal);
|
|
104
|
-
//
|
|
105
|
-
//
|
|
106
|
-
//
|
|
107
|
-
//
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
104
|
+
// The shared helper by default: it owns usage extraction and
|
|
105
|
+
// thought-signature preservation, and it wants a StreamChannel but only
|
|
106
|
+
// ever calls `.push`, so the engine's push-only channel satisfies it.
|
|
107
|
+
//
|
|
108
|
+
// A provider whose drain genuinely differs supplies `collectStep`
|
|
109
|
+
// instead. Vertex does: it folds cumulative usage counts as deltas in
|
|
110
|
+
// its own loop, and that behaviour is characterized, so it keeps its
|
|
111
|
+
// collector rather than being quietly switched to this one.
|
|
112
|
+
const collected = config.collectStep
|
|
113
|
+
? await config.collectStep(rawStream, channel)
|
|
114
|
+
: await collectStreamChunksIncremental(rawStream, {
|
|
115
|
+
push: (chunk) => channel.push(chunk),
|
|
116
|
+
});
|
|
111
117
|
// The provider's context guard calibrates from real per-step counts;
|
|
112
118
|
// `inputTokens` is this step's full prompt size, which is what it
|
|
113
119
|
// projects the next request from.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type Anthropic from "@anthropic-ai/sdk";
|
|
2
2
|
import type { Tool } from "./tools.js";
|
|
3
|
-
import type { NativeFunctionCall, NativeToolDeclarationsResult } from "./providers.js";
|
|
3
|
+
import type { CollectedChunkResult, NativeFunctionCall, NativeToolDeclarationsResult } from "./providers.js";
|
|
4
4
|
/**
|
|
5
5
|
* One chunk on the engine's stream.
|
|
6
6
|
*
|
|
@@ -240,6 +240,22 @@ export type GeminiLoopAdapterCoreConfig = {
|
|
|
240
240
|
* step with that step's real token counts.
|
|
241
241
|
*/
|
|
242
242
|
noteUsage?: (inputTokens: number, outputTokens: number) => void;
|
|
243
|
+
/**
|
|
244
|
+
* Fold one step's raw stream into the shape the adapter reports.
|
|
245
|
+
*
|
|
246
|
+
* Defaults to `collectStreamChunksIncremental`, which is what AI Studio and
|
|
247
|
+
* any provider sharing the googleNativeGemini3 helpers want. Vertex does
|
|
248
|
+
* NOT share them: its loop drains the stream itself, folding cumulative
|
|
249
|
+
* usage counts as deltas and capturing thought signatures in its own way,
|
|
250
|
+
* and that behaviour is characterized rather than incidental.
|
|
251
|
+
*
|
|
252
|
+
* So the collector is a hook rather than a hard-coded call. A provider
|
|
253
|
+
* whose drain differs supplies its own and keeps its measured behaviour;
|
|
254
|
+
* one that matches the shared helper passes nothing.
|
|
255
|
+
*/
|
|
256
|
+
collectStep?: (stream: unknown, channel: {
|
|
257
|
+
push(chunk: AgenticLoopChunk): void;
|
|
258
|
+
}) => Promise<CollectedChunkResult>;
|
|
243
259
|
};
|
|
244
260
|
/**
|
|
245
261
|
* Opt in to the single MALFORMED_FUNCTION_CALL retry.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "11.
|
|
3
|
+
"version": "11.15.0",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
|
|
6
6
|
"author": {
|