@juspay/neurolink 12.5.1 → 12.5.3

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,4 +1,8 @@
1
- ## [12.5.1](https://github.com/juspay/neurolink/compare/v12.5.0...v12.5.1) (2026-08-29)
1
+ ## [12.5.3](https://github.com/juspay/neurolink/compare/v12.5.2...v12.5.3) (2026-08-29)
2
+
3
+ ### Bug Fixes
4
+
5
+ - **(bedrock):** pass abortSignal to the transport, not just to the loop ([20f27ff](https://github.com/juspay/neurolink/commit/20f27fff990979bb12bb336b5e4e577711cb7ae9))
2
6
 
3
7
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
4
8
 
@@ -1118,7 +1118,7 @@ ${r[0].text}`;const n=r.length-1;r[n].text=`${r[n].text}
1118
1118
  IMPORTANT: You MUST call the 'final_result' tool to return your response in the required structured format. Do not respond with plain text - always use the final_result tool.`}});function r$r(e,t){switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return t?"tool-calls":"stop"}}function kX(e){return{providerLabel:"anthropic",maxSteps:e.maxSteps,...e.toolFailureBreaker?{toolFailureBreaker:e.toolFailureBreaker}:{},...e.planReclaim?{planReclaim:(t,r)=>e.planReclaim?.(t,r)}:{},resolveToolOnMiss:t=>{const n=OV(e.toolsRecord,t)?.execute;if(n)return{execute:async(o,s)=>n(o,s)}},buildStepRequest(t,r){return{raw:e.buildParams(t,r)}},async executeStep(t,r,n){const o=t.raw,s=await e.client.messages.create({...o,stream:!0},{signal:n}),i=new Map,a=new Map,l=new Map,c=new Map;let u="",d="",m,h=0,g=0,y=0,v=0,_=0,b=0,T=0;for await(const N of s){if(n.aborted)break;const P=N;if(P.type==="message_start"){const D=P.message?.usage;h+=D?.input_tokens??0;const L=D?.output_tokens??0;g+=L-T,T=L,y+=D?.cache_read_input_tokens??0,v+=D?.cache_creation_input_tokens??0,_+=D?.cache_creation?.ephemeral_5m_input_tokens??0,b+=D?.cache_creation?.ephemeral_1h_input_tokens??0,e.noteObservedPromptTokens?.((D?.input_tokens??0)+(D?.cache_read_input_tokens??0)+(D?.cache_creation_input_tokens??0));continue}if(P.type==="content_block_start"){const D=P.index??0;if(P.content_block?.type==="redacted_thinking"){const L=P.content_block.data;typeof L=="string"&&c.set(D,L)}P.content_block?.type==="tool_use"&&a.set(D,{id:P.content_block.id??"",name:P.content_block.name??"",inputJson:""});continue}if(P.type==="content_block_delta"){const D=P.index??0,L=P.delta;if(L?.type==="text_delta"&&L.text)u+=L.text,i.set(D,(i.get(D)??"")+L.text),r.push({content:L.text});else if(L?.type==="thinking_delta"&&L.thinking){const $=l.get(D)??{text:"",signature:""};$.text+=L.thinking,l.set(D,$),d+=L.thinking,r.push({content:"",reasoning:L.thinking})}else if(L?.type==="signature_delta"&&L.signature){const $=l.get(D)??{text:"",signature:""};$.signature+=L.signature,l.set(D,$)}else if(L?.type==="input_json_delta"&&L.partial_json){const $=a.get(D);$&&($.inputJson+=L.partial_json)}continue}if(P.type==="message_delta"){m=P.delta?.stop_reason??m;const D=P.usage?.output_tokens??T;g+=D-T,T=D}}const x=N=>{if(!N)return{};try{const P=JSON.parse(N);return typeof P=="object"&&P!==null&&!Array.isArray(P)?P:{}}catch{return{}}},A=[],I=new Set([...i.keys(),...a.keys(),...l.keys(),...c.keys()]);for(const N of[...I].sort((P,D)=>P-D)){const P=c.get(N);P&&A.push({type:"redacted_thinking",data:P});const D=l.get(N);D?.text&&D.signature&&A.push({type:"thinking",thinking:D.text,signature:D.signature});const L=i.get(N);L&&A.push({type:"text",text:L});const $=a.get(N);$&&A.push({type:"tool_use",id:$.id,name:$.name,input:x($.inputJson)})}const M=[...a.values()].map(N=>({id:N.id,name:N.name,args:x(N.inputJson)})),R=e.finalResultToolName?[...a.values()].find(N=>N.name===e.finalResultToolName):void 0,k=R?[]:M,O=R?t$r(R.inputJson):u;return R&&e.onTerminalResult?.(O),{text:O,...d?{reasoning:d}:{},toolCalls:k,usage:{inputTokens:h,outputTokens:g,cacheReadTokens:y,cacheWriteTokens:v,..._?{cacheWrite5mTokens:_}:{},...b?{cacheWrite1hTokens:b}:{}},rawStopReason:m,raw:A}},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw.filter(i=>i.type!=="server_tool_use")},s={role:"user",content:n.map(i=>({type:"tool_result",tool_use_id:i.id,content:i.error?`Error executing tool ${i.name}: ${i.error}`:xX(i.output),...i.error?{is_error:!0}:{}}))};return[...t,o,s]},mapFinishReason:r$r}}var oAt=S({"src/lib/providers/anthropic/loopAdapter.ts"(){"use strict";lS(),Qkt(),nAt()}});function AX(e){if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return"image/png";if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70)return"image/gif";if(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)return"image/webp"}function NO(e,t){if(e instanceof ArrayBuffer)return NO(new Uint8Array(e),t);if(e instanceof Uint8Array)return{type:"image",source:{type:"base64",media_type:LO(t)??AX(e)??"image/png",data:Buffer.from(e).toString("base64")}};if(typeof e!="string"&&!(e instanceof URL))return;const r=e instanceof URL?e.toString():e,n=r.match(/^data:(image\/[a-z0-9+.-]+);base64,(.+)$/i);if(n){const s=LO(n[1])??RX(n[2]);return s?{type:"image",source:{type:"base64",media_type:s,data:n[2]}}:void 0}return/^https?:\/\//i.test(r)?{type:"image",source:{type:"url",url:r}}:{type:"image",source:{type:"base64",media_type:LO(t)??RX(r)??"image/png",data:r}}}function n$r(e){const t=e?.data;if(t==null)return;const r=typeof e.mediaType=="string"?e.mediaType.toLowerCase().split(";")[0].trim():"";if(IX.has(r)||r==="image/jpg")return NO(t,r);if(r==="application/pdf")return MX(t);const n=t instanceof ArrayBuffer?new Uint8Array(t):t instanceof Uint8Array?t:void 0;if(n&&AX(n))return NO(n)}var IX,LO,sAt,RX,MX,o$r=S({"src/lib/providers/anthropicImageBlocks.ts"(){"use strict";IX=new Set(["image/jpeg","image/png","image/gif","image/webp"]),LO=e=>{if(!e)return;const t=e.toLowerCase().split(";")[0].trim();return t==="image/jpg"?"image/jpeg":IX.has(t)?t:void 0},sAt=32,RX=e=>{try{return AX(Buffer.from(e.slice(0,sAt),"base64"))}catch{return}},MX=e=>{if(e instanceof ArrayBuffer)return MX(new Uint8Array(e));if(e instanceof Uint8Array)return{type:"document",source:{type:"base64",media_type:"application/pdf",data:Buffer.from(e).toString("base64")}};if(e instanceof URL)return{type:"document",source:{type:"url",url:e.toString()}};if(typeof e=="string"){const t=e.match(/^data:application\/pdf;base64,(.+)$/i);return t?{type:"document",source:{type:"base64",media_type:"application/pdf",data:t[1]}}:/^https?:\/\//i.test(e)?{type:"document",source:{type:"url",url:e}}:{type:"document",source:{type:"base64",media_type:"application/pdf",data:e}}}}}}),$O,iAt=S({"src/lib/providers/anthropic/constants.ts"(){"use strict";$O={"anthropic-beta":["claude-code-20250219","fine-grained-tool-streaming-2025-05-14"].join(",")}}}),PX,ex,aAt,DX,lAt,cAt,OX,NX,uAt,LX,dAt,s$r=S({"src/lib/providers/anthropic/client.ts"(){"use strict";HSt(),er(),gn(),ic(),Lr(),ZC(),RF(),vc(),Xo(),Ebt(),Nkt(),U2r(),no(),J2r(),yt(),xi(),q(),MJ(),Kkt(),Yu(),oi(),vr(),Xkt(),uc(),Qkt(),oAt(),f4(),us(),Fa(),Cbt(),jV(),Bd(),nJ(),Ji(),SJ(),o$r(),Im(),Ym(),U0(),qJ(),iAt(),Awt(),nAt(),Nkt(),PX=()=>Vi(Bvr()),ex=()=>Wi("ANTHROPIC_MODEL","claude-sonnet-4-6"),aAt=vt.getTracer("neurolink.provider.anthropic"),DX=()=>{try{const t=Sr(Uu(),".neurolink","anthropic-credentials.json");if(Os(t)){const r=$d(t,"utf-8"),n=JSON.parse(r);if(n.type==="oauth"&&n.oauth?.accessToken)return f.debug("[AnthropicProvider] Using OAuth token from stored credentials file"),n.oauth}}catch(t){f.debug("[AnthropicProvider] Failed to read stored credentials:",t)}const e=process.env.ANTHROPIC_OAUTH_TOKEN||process.env.CLAUDE_OAUTH_TOKEN;if(!e)return null;try{const t=JSON.parse(e);if(typeof t=="object"&&t.accessToken)return t;if(typeof t=="string")return{accessToken:t}}catch{}return{accessToken:e}},lAt=e=>{const t=process.env.ANTHROPIC_SUBSCRIPTION_TIER?.toLowerCase();if(t){const r=["free","pro","max","max_5","max_20","api"];if(r.includes(t))return f.debug("[detectSubscriptionTier] Using environment override",{tier:t}),t;f.warn("[detectSubscriptionTier] Invalid ANTHROPIC_SUBSCRIPTION_TIER",{value:t,validTiers:r})}if(e){const r=e.scopes??[];let n="pro";return r.includes("max_20")?n="max_20":r.includes("max_5")?n="max_5":r.includes("max")&&(n="max"),f.debug("[detectSubscriptionTier] Detected from OAuth token",{tier:n,scopes:r}),n}return f.debug("[detectSubscriptionTier] No OAuth token, defaulting to API tier"),"api"},cAt=e=>{const t=process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase();if(t==="api_key"||t==="apikey")return f.debug("[detectAuthMethod] Forced to api_key by ANTHROPIC_AUTH_METHOD env var"),"api_key";if(t==="oauth"){if(e)return f.debug("[detectAuthMethod] Forced to oauth by ANTHROPIC_AUTH_METHOD env var"),"oauth";f.warn("[detectAuthMethod] ANTHROPIC_AUTH_METHOD=oauth but no OAuth token found; falling through to auto-detection")}else t&&f.warn("[detectAuthMethod] Unrecognized ANTHROPIC_AUTH_METHOD value; falling through to auto-detection",{value:t});const r=e?"oauth":"api_key";return f.debug("[detectAuthMethod] Auth method resolved",{method:r,hasOAuthToken:!!e}),r},OX=e=>{const t=[],r=[],n=i=>Array.isArray(i)?i:[i],o=(i,a)=>{const l=ip(a);if(l&&i.length>0){const c=i[i.length-1];c.cache_control=l}};for(const i of e)switch(i.role){case"system":{const a=typeof i.content=="string"?i.content:n(i.content).map(c=>typeof c=="string"?c:String(c?.text??"")).join(`
1119
1119
  `),l=ip(i);t.push({type:"text",text:a,...l?{cache_control:l}:{}});break}case"user":{const a=[];for(const l of n(i.content)){if(typeof l=="string"){l.length>0&&a.push({type:"text",text:l});continue}const c=l;if(c?.type==="text"&&typeof c.text=="string"){const u=ip(c);a.push({type:"text",text:c.text,...u?{cache_control:u}:{}})}else if(c?.type==="image"||c?.type==="image_url"){const u=NO(c.image??c.data??c.url);if(u){const d=ip(c);a.push(d?{...u,cache_control:d}:u)}}else if(c?.type==="file"){const d=typeof c=="object"&&c!==null&&("mediaType"in c?typeof c.mediaType=="string":!0)?n$r(c):void 0;if(d){const m=ip(c);m&&(d.cache_control=m),a.push(d)}}}a.length>0&&(o(a,i),r.push({role:"user",content:a}));break}case"assistant":{const a=[];for(const l of n(i.content)){if(typeof l=="string"){l.length>0&&a.push({type:"text",text:l});continue}const c=l;if(c?.type==="text"&&typeof c.text=="string"){if(c.text.length>0){const u=ip(c);a.push({type:"text",text:c.text,...u?{cache_control:u}:{}})}}else if(c?.type==="tool-call"){let u=c.input;if(typeof u=="string")try{u=JSON.parse(u)}catch{u={}}a.push({type:"tool_use",id:c.toolCallId??"",name:c.toolName??"",input:u??{}})}}a.length>0&&(o(a,i),r.push({role:"assistant",content:a}));break}case"tool":{const a=[];if(Array.isArray(i.content))for(const l of i.content){const c=l;c?.type==="tool-result"&&a.push({type:"tool_result",tool_use_id:c.toolCallId??"",content:xX(c.output)})}else typeof i.content=="string"&&a.push({type:"tool_result",tool_use_id:i.toolCallId??"",content:i.content});a.length>0&&r.push({role:"user",content:a});break}}const s=t.length===0?void 0:t.some(i=>i.cache_control)?t:t.map(i=>i.text).join(`
1120
1120
 
1121
- `);return{...s!==void 0?{system:s}:{},messages:r}},NX=e=>{if(!(!e||e==="auto")){if(e==="none")return{type:"none"};if(e==="required")return{type:"any"};if(typeof e=="object"){const t=e;if(t.type==="tool"&&t.toolName)return{type:"tool",name:t.toolName}}}},uAt=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},LX=6e5,dAt=class extends Il{client;authMethod;subscriptionTier;enableBetaFeatures;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,r,n){const o=!!(n?.apiKey&&!n?.oauthToken),s=o?null:(n?.oauthToken?{accessToken:n.oauthToken}:null)??r?.oauthToken??DX(),i=o?"api_key":r?.authMethod??cAt(s),a=r?.subscriptionTier??(i==="oauth"?lAt(s):"api"),l=e||ex();let c=l;!process.env.ANTHROPIC_BASE_URL&&a!=="api"&&!wX(l,a)&&(c=bX(a),f.warn("Model not available for subscription tier, using recommended model",{requestedModel:l,subscriptionTier:a,recommendedModel:c})),super(c,"anthropic",t),this.enableBetaFeatures=r?.enableBetaFeatures??!0,this.oauthToken=s,this.subscriptionTier=a,this.authMethod=i;const d=this.getAuthHeaders();let m;if(f.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){f.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");const h=this.oauthToken,g=F2r(()=>h.accessToken,this.enableBetaFeatures,!1,!0);m=new Tg({apiKey:"oauth-authenticated",fetch:Bkt(g),timeout:LX,maxRetries:0}),f.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),f.debug("Anthropic Provider initialized with OAuth",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,hasRefreshToken:!!this.oauthToken.refreshToken,tokenExpiry:this.oauthToken.expiresAt?new Date(this.oauthToken.expiresAt).toISOString():"none"})}else{const h=n?.apiKey??r?.apiKey??PX(),g=(()=>{const y=process.env.ANTHROPIC_BASE_URL;if(!y)return;const v=y.replace(/\/+$/,""),_=v.replace(/\/v\d+$/,"");return _!==v&&f.debug("[AnthropicProvider] Stripping the version suffix from ANTHROPIC_BASE_URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:Xn(y),rewrittenTo:Xn(_)}),_})();m=new Tg({apiKey:h,defaultHeaders:d,...g&&{baseURL:g},fetch:Bkt(Bt()),timeout:LX,maxRetries:0}),f.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.client=m,this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},f.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?$O["anthropic-beta"]:"disabled"})}getAuthHeaders(){const e={},t=!!process.env.ANTHROPIC_BASE_URL;if(this.enableBetaFeatures)if(t){const r=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",n=[...YC,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];r&&n.push("context-1m-2025-08-07"),e["anthropic-beta"]=n.join(",")}else e["anthropic-beta"]=$O["anthropic-beta"];return t&&(e["User-Agent"]=Eg),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return f.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;const t=wX(e,this.subscriptionTier);return t||f.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return TX(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){f.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){f.debug("Token has no expiry information, assuming valid");return}const e=Date.now(),t=this.oauthToken.expiresAt<=e,r=this.oauthToken.expiresAt<=e+wue;if(!t&&!r){f.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new Pr("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);f.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}f.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});const n=this.oauthToken,o=n.refreshToken;this.refreshPromise=(async()=>{const i=new AbortController,a=setTimeout(()=>i.abort(),3e4),l=await fetch(JC,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Eg},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:vX}),signal:i.signal});if(clearTimeout(a),!l.ok){const d=await l.text();throw new Pr(`Failed to refresh OAuth token: ${l.status} ${d}`,this.providerName)}const c=await l.json();n.accessToken=c.access_token,n.refreshToken=c.refresh_token||n.refreshToken,n.expiresAt=c.expires_in?Date.now()+c.expires_in*1e3:void 0,n.tokenType=c.token_type||"Bearer";const u=n;try{const d=Sr(Uu(),".neurolink");Os(d)||k1(d,{recursive:!0});const m=Sr(d,"anthropic-credentials.json"),h=`${m}.tmp`,y={...Os(m)?JSON.parse($d(m,"utf-8")):{},type:"oauth",oauth:u,updatedAt:Date.now()};C1(h,JSON.stringify(y,null,2),{mode:384}),qz(h,m),f.debug("Refreshed OAuth credentials persisted to disk")}catch(d){f.warn("Failed to persist refreshed OAuth token to disk",{error:d instanceof Error?d.message:String(d)})}f.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!c.refresh_token,expiresIn:c.expires_in})})();try{await this.refreshPromise}catch(s){throw s instanceof Pr?s:new Pr(`Failed to refresh OAuth token: ${s instanceof Error?s.message:String(s)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,r){this.lastResponseMetadata={rateLimit:e,...t?{requestId:t}:{}},this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),r&&(r.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=r.inputTokens,this.usageInfo.tokensUsed+=r.inputTokens),r.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=r.outputTokens,this.usageInfo.tokensUsed+=r.outputTokens)),e?.requestsRemaining!==void 0&&(this.usageInfo.messagesRemaining=e.requestsRemaining),e?.tokensRemaining!==void 0&&(this.usageInfo.tokensRemaining=e.tokensRemaining),e?.requestsLimit&&e.requestsLimit>0&&(this.usageInfo.messageQuotaPercent=Math.round((e.requestsLimit-(e.requestsRemaining??0))/e.requestsLimit*100)),e?.tokensLimit&&e.tokensLimit>0&&(this.usageInfo.tokenQuotaPercent=Math.round((e.tokensLimit-(e.tokensRemaining??0))/e.tokensLimit*100)),e?.retryAfter!==void 0?(this.usageInfo.isRateLimited=!0,this.usageInfo.rateLimitExpiresAt=Date.now()+e.retryAfter*1e3):(this.usageInfo.isRateLimited=!1,this.usageInfo.rateLimitExpiresAt=void 0)),e?.requestsRemaining!==void 0&&e.requestsRemaining<=5&&f.warn("Approaching Anthropic request rate limit",{remaining:e.requestsRemaining,limit:e.requestsLimit,reset:e.requestsReset}),e?.tokensRemaining!==void 0&&e.tokensLimit&&e.tokensRemaining<e.tokensLimit*.1&&f.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return ex()}getAISDKModel(){const e=this.client,t=this.providerName,r=this.modelName||ex(),n=i=>this.getTimeout(i??{}),o=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:r,supportedUrls:{},doGenerate:async i=>{await o();const a=OX(i.prompt),l=a.messages;let c=a.system,u=(i.tools??[]).filter($=>$.type==="function").map($=>{const U=ip($);return{name:$.name,...$.description?{description:$.description}:{},input_schema:$.inputSchema??{type:"object",properties:{}},...U?{cache_control:U}:{}}});u&&u.length===0&&(u=void 0);let d=i.toolChoice?NX(i.toolChoice.type==="tool"?{type:"tool",toolName:i.toolChoice.toolName}:i.toolChoice.type):void 0,m;if(i.responseFormat?.type==="json"){m=i.responseFormat.name??"json";const $=i.responseFormat.schema??{type:"object"};u=[{name:m,description:i.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:$}],d={type:"tool",name:m}}const h=i.providerOptions?.anthropic?.finalResultSchema;let g=!1;if(!m&&h){const $=eAt(u,h);u=$.tools,g=$.applied,$.applied&&(c=tAt(c))}const y=i.providerOptions?.anthropic?.thinking,v=Jkt({system:c,tools:u,messages:l}),_=Ykt(l,PO-v),b=eu("anthropic",r,{...i.temperature!==void 0&&i.temperature!==null?{temperature:i.temperature}:{},...i.topP!==void 0&&i.topP!==null?{topP:i.topP}:{}},"anthropic.doGenerate"),T={model:r,messages:_,max_tokens:QD(r,i.maxOutputTokens),...c?{system:c}:{},...b.temperature!==void 0?{temperature:b.temperature}:{},...b.topP!==void 0?{top_p:b.topP}:{},...i.stopSequences&&i.stopSequences.length>0?{stop_sequences:i.stopSequences}:{},...u?{tools:u}:{},...d?{tool_choice:d}:{},...y?{thinking:y}:{}},x=i.timeout,A=x!=null,I=T.max_tokens>8192&&!A?Math.max(n(i),3e5):n(i),M=rc(I,t,"generate");let R;try{R=await e.messages.create(T,{signal:i1(i.abortSignal,M?.controller.signal)})}finally{M?.cleanup()}const k=[];let O;const N=[];let P=!1;for(const $ of R.content)$.type==="thinking"?k.push({type:"reasoning",text:$.thinking}):$.type==="text"?m?N.push($.text):k.push({type:"text",text:$.text}):$.type==="tool_use"&&(m&&$.name===m?(P=!0,k.push({type:"text",text:iC($.input)})):g&&$.name===QC?O=iC($.input):k.push({type:"tool-call",toolCallId:$.id,toolName:$.name,input:iC($.input)}));if(m&&!P&&N.length>0&&k.push({type:"text",text:N.join("")}),O!==void 0){const $=k.filter(U=>U.type==="reasoning");k.length=0,k.push(...$,{type:"text",text:O}),f.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:O.length})}const D=R.usage.cache_read_input_tokens??0,L=R.usage.cache_creation_input_tokens??0;return{content:k,finishReason:{unified:O!==void 0?"stop":uAt(R.stop_reason),raw:R.stop_reason??"stop"},usage:{inputTokens:{total:R.usage.input_tokens+D+L,noCache:R.usage.input_tokens,cacheRead:D,cacheWrite:L},outputTokens:{total:R.usage.output_tokens,text:R.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:T},response:{id:R.id,modelId:R.model,headers:H2r()??{},body:R}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}formatProviderError(e){return Hi(e,[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(r.message),errorClass:Pr,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:r=>r.statusCode===429||/rate limit|too_many_requests|429/i.test(r.message),errorClass:Ms,message:"Anthropic rate limit exceeded. Please try again later."},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(r.message),errorClass:co,message:r=>`Connection error: ${r.message}`},{match:r=>/500|502|503|504|server error/i.test(r.message),errorClass:_t,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:_t,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await q2r(()=>super.generate(e,t));return r&&n&&(this.recordLimitSnapshot(n),r.limits=n,r.analytics&&(r.analytics.limits=n)),r}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),W2r(e),K2r(e,this.modelName)}async executeStream(e,t){return V2r(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);const r=this.getTimeout(e),n=rc(r,this.providerName,"stream"),o=new AbortController,s=sye([e.abortSignal,n?.controller.signal,o.signal]).signal;let i,a,l,c,u=!1;try{c=!e.disableTools&&this.supportsTools(),i=c?e.tools||await this.getAllTools():{},a=c?B0(i,"input_schema"):void 0;const G=await this.buildMessagesForStream(e);if(l=OX(G),e.schema&&a&&a.length>0){const K=eAt(a,js(e.schema));a=K.tools,u=K.applied,K.applied&&(l.system=tAt(l.system))}}catch(G){throw n?.cleanup(),this.handleProviderError(G)}const d=this.modelName||ex(),m=c&&a&&a.length>0?NX(Sbt(e,i,c)):void 0,h=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,g=aAt.startSpan("neurolink.provider.streamText",{kind:Br.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":d}}),y=e.maxSteps||ki,v=this.neurolink?.getEventEmitter(),_=F0(),{push:b}=_,{usagePromise:T,finishPromise:x,resolveUsage:A,resolveFinish:I}=dY();T.then(G=>{g.setAttribute("gen_ai.usage.input_tokens",G.promptTokens||0),g.setAttribute("gen_ai.usage.output_tokens",G.completionTokens||0),G.cacheReadTokens&&g.setAttribute("gen_ai.usage.cached_input_tokens",G.cacheReadTokens);const K=Ga(this.providerName,this.modelName,{input:G.promptTokens||0,output:G.completionTokens||0,total:G.totalTokens||0,...G.cacheReadTokens?{cacheReadTokens:G.cacheReadTokens}:{},...G.cacheCreationTokens?{cacheCreationTokens:G.cacheCreationTokens}:{}});K&&K>0&&g.setAttribute("neurolink.cost",K)}).catch(()=>{}),x.then(G=>{g.setAttribute("gen_ai.response.finish_reason",G||"unknown"),g.end()}).catch(()=>{g.end()});let M;const R=this.client,k=[],O=Date.now(),N={};let P=0,D=0,L=0,$=0,U=null;const j=()=>({promptTokens:P,completionTokens:D,totalTokens:P+L+$+D,...L>0?{cacheReadTokens:L}:{},...$>0?{cacheCreationTokens:$}:{}});let B="",z;const J=(G,K)=>{const Ce=be=>{if(typeof be=="string")return be;try{return JSON.stringify(be)??""}catch{return""}};return pr(Ce(G),"anthropic")+pr(Ce(K),"anthropic")},ie=(async()=>{let G,K;const ge=kX({client:R,maxSteps:y,toolsRecord:i,buildParams:ne=>{if(a){const pe=new Set(a.map(Z=>Z.name)),X=Object.fromEntries(Object.entries(i).filter(([Z])=>!pe.has(Z)));if(Object.keys(X).length>0){const Z=B0(X,"input_schema");Z&&Z.length>0&&(a=[...a,...Z])}}const Fe=Jkt({system:l.system,tools:a,messages:ne}),ae=Ykt(ne,PO-Fe),oe=eu("anthropic",d,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream");return{model:d,messages:ae,max_tokens:QD(d,e.maxTokens),...l.system?{system:l.system}:{},...oe.temperature!==void 0?{temperature:oe.temperature}:{},...a&&a.length>0?{tools:a}:{},...m?{tool_choice:m}:{},...h?{thinking:h}:{}}},planReclaim:ne=>{const Fe=Wkt({conversation:ne,availableInputTokens:ou("anthropic",d,e.maxTokens??void 0),fixedOverheadTokens:J(l.system,a),provider:"anthropic",observedPromptTokens:G,previousSentEstimate:K,onSentEstimate:X=>{K=X}});if(!Fe)return;const ae=new Set(Fe.drop),oe=new Set(Fe.truncate),pe=[];for(let X=0;X<ne.length;X++){if(ae.has(X))continue;const Z=ne[X];if(oe.has(X)&&Array.isArray(Z.content)){pe.push({...Z,content:Z.content.map(_e=>_e.type==="tool_result"?{..._e,content:Vkt(typeof _e.content=="string"?_e.content:JSON.stringify(_e.content)??"")}:_e)});continue}pe.push(Z)}if(ae.size>0){let X=pe.findIndex(Z=>Array.isArray(Z.content)&&Z.content.some(_e=>_e.type==="tool_use"||_e.type==="tool_result"));X<0&&(X=Math.min(1,pe.length)),pe.splice(X,0,{role:"user",content:[{type:"text",text:CX}]})}return{conversation:pe}},noteObservedPromptTokens:ne=>{G=ne},...u?{finalResultToolName:QC,onTerminalResult:ne=>{z=ne,f.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:ne.length})}}:{}}),H={...ge,buildToolResultMessages:(ne,Fe,ae,oe)=>{for(const Z of ae)k.push(Z.name);const pe=ae.map(Z=>({type:"tool-call",toolCallId:Z.id,toolName:Z.name,args:Z.args})),X=ae.map(Z=>Z.error?{type:"tool-result",toolCallId:Z.id,toolName:Z.name,error:Z.error}:{type:"tool-result",toolCallId:Z.id,toolName:Z.name,result:Z.output});return zV(v,X.map(Z=>({toolName:Z.toolName,result:"result"in Z?Z.result:void 0,error:"error"in Z?Z.error:void 0}))),this.handleToolExecutionStorage(pe,X,e,new Date).catch(Z=>{f.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:Z instanceof Error?Z.message:String(Z)})}),ge.buildToolResultMessages(ne,Fe,ae,oe)}},se={};for(const[ne,Fe]of Object.entries(i)){const ae=Fe.execute;ae&&(se[ne]={execute:async(oe,pe)=>{const X=pe;return ae(oe,{toolCallId:X.toolCallId??"",...X.abortSignal?{abortSignal:X.abortSignal}:{},messages:[]})}})}const ye=vt.getActiveSpan(),{stream:Q,resultPromise:me}=sp(H,l.messages.slice(),{tools:se,...s?{abortSignal:s}:{},...ye?{span:ye}:{}}),$e=(async()=>{for await(const ne of Q)ne.reasoning&&b({content:"",reasoning:ne.reasoning}),ne.content&&(u?B+=ne.content:b({content:ne.content}))})();let Se;try{Se=await me}catch(ne){throw await ag($e,"Anthropic"),ne}await $e,P+=Se.usage.inputTokens,D+=Se.usage.outputTokens,L+=Se.usage.cacheReadTokens??0,$+=Se.usage.cacheWriteTokens??0,U=Se.rawStopReason??U,N.finishReason=Se.finishReason,Se.rawStopReason&&(N.rawFinishReason=Se.rawStopReason),Se.finishReason==="tool-calls"&&z===void 0&&(N.stopReason="step-cap"),A(j()),I(U??"stop")})().catch(G=>{throw M=G,f.error("Anthropic: Stream error",{error:G instanceof Error?G.message:String(G)}),A(j()),I("error"),this.formatProviderError(G)}).finally(()=>{if(u){const G=z??B;G.length>0&&b({content:G})}n?.cleanup(),_.close()});ie.catch(()=>{});const ce=this.providerName;return{stream:async function*(){let G=0;try{for await(const K of _.iterable)"content"in K&&typeof K.content=="string"&&K.content.length>0&&G++,yield K;if(await ie,G===0&&k.length===0){f.warn(`${ce}: Stream produced no output \u2014 emitting enriched sentinel`);const K=new ac({message:"Stream produced no output"}),Ce=await rg(K,void 0,M);ng(Ce),yield Ce}}catch(K){const Ce=await rg(K,void 0,M);if(ng(Ce),yield Ce,!ac.isInstance(K))throw K}finally{o.signal.aborted||o.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],metadata:N,analytics:x.then(async()=>{const G=await vY.createAnalytics(this.providerName,d,{textStream:(async function*(){})(),usage:T,finishReason:x},Date.now()-O,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),K=G2r();return K&&G&&(this.recordLimitSnapshot(K),G.limits=K),G})}}async isAvailable(){try{return DX()||PX(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),pAt={};he(pAt,{ANTHROPIC_BETA_HEADERS:()=>$O,AnthropicProvider:()=>dAt,ModelAccessError:()=>i3,getModelCapabilities:()=>TX,getRecommendedModelForTier:()=>bX,isModelAvailableForTier:()=>wX});var i$r=S({"src/lib/providers/anthropic/index.ts"(){"use strict";s$r(),iAt()}}),Sg,li,a$r,l$r,mAt,hAt,fAt,tx,gAt,c$r,u$r,d$r,p$r,m$r,h$r,f$r,g$r,y$r,v$r,_$r,w$r,b$r,T$r,E$r,S$r,C$r,x$r,k$r,A$r,I$r,R$r,M$r,P$r,D$r,O$r,N$r,L$r,$$r,F$r,U$r,B$r,z$r,j$r,q$r,G$r,H$r,V$r,W$r,yAt=S({"npm-stub:@aws-sdk/client-bedrock-runtime"(){Sg={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Sg.get}):new Proxy(function(...r){return new Proxy({},{get:Sg.get})},{get:Sg.get,apply(r,n,o){return new Proxy({},{get:Sg.get})},construct(r,n){return new Proxy({},{get:Sg.get})}})}},li=new Proxy({},Sg),{BedrockClient:a$r,ListFoundationModelsCommand:l$r,BedrockRuntimeClient:mAt,ConverseCommand:hAt,ConverseStreamCommand:fAt,ImageFormat:tx,InvokeModelCommand:gAt}=li,{SageMakerRuntimeClient:c$r,InvokeEndpointCommand:u$r,InvokeEndpointWithResponseStreamCommand:d$r}=li,{GoogleAuth:p$r,VertexAI:m$r,TextToSpeechClient:h$r}=li,{Webhook:f$r}=li,{Hippocampus:g$r,HippocampusConfig:y$r}=li,{createClient:v$r}=li,{Queue:_$r,Worker:w$r,Job:b$r,QueueScheduler:T$r,FlowProducer:E$r}=li,{Cron:S$r}=li,{parseBuffer:C$r,selectCover:x$r}=li,{extractRawText:k$r,convertToHtml:A$r}=li,{Hono:I$r}=li,{cors:R$r,HTTPException:M$r,logger:P$r,secureHeaders:D$r,streamSSE:O$r,timeout:N$r}=li,L$r=globalThis.fetch,$$r=globalThis.Request,F$r=globalThis.Response,U$r=globalThis.Headers,B$r=globalThis.FormData,z$r=globalThis.File,j$r=globalThis.Blob,q$r=li.Agent,G$r=li.Pool,H$r=li.Client,V$r=li.Dispatcher,W$r=li.MockAgent}});function K$r(e){if(/^(us|ca)-/.test(e))return"us";if(/^(eu|il|me|af)-/.test(e))return"eu";if(/^ap-northeast-[13]$/.test(e))return"jp";if(/^ap-southeast-[246]$/.test(e))return"au";if(/^ap-/.test(e))return"apac"}function J$r(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function vAt(e){if(typeof e!="object"||e===null)return!1;const t=e,r=typeof t.name=="string"?t.name:"",n=typeof t.message=="string"?t.message:"";return!/ValidationException/i.test(r)&&!/ValidationException/i.test(n)?!1:/inference profile/i.test(n)&&/on-demand throughput/i.test(n)}function Y$r(e,t){if(e.startsWith("arn:")||J$r(e))return[];const r=[],n=K$r(t);return n&&r.push(`${n}.${e}`),r.push(`${bAt}.${e}`),r}function _At(e,t){return`${e}::${t}`}function Z$r(e,t){return $X.get(_At(t,e))}function X$r(e,t,r){$X.set(_At(t,e),r),f.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function wAt(e,t,r){const n=Z$r(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!vAt(o))throw o;const s=Y$r(e,t);if(s.length===0)throw o;f.warn("[Bedrock] Model requires a cross-region inference profile in this region; retrying with a prefixed id",{region:t,candidates:s.length});for(const i of s)try{const a=await r(i);return X$r(e,t,i),a}catch(a){if(!vAt(a))throw a}throw o}}var bAt,$X,Q$r=S({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";q(),bAt="global",$X=new Map}});function FO(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function TAt(e,t){if(e){if(e.toolUse&&e._inputBuffer){try{e.toolUse.input=JSON.parse(e._inputBuffer)}catch{e.toolUse.input={}}delete e._inputBuffer}t&&!e.toolUse&&(e.text=t)}}function EAt(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??FO(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function eFr(e,t,r){const n=[],o=new Map,s=new Map,i=g=>{let y=o.get(g);return y||(y={},o.set(g,y),n.push(y)),y};let a="",l,c=0,u=0,d=0,m=0;if(e.stream)for await(const g of e.stream){if(r.aborted)break;const y=g;if(y.contentBlockStart&&i(y.contentBlockStart.contentBlockIndex??0),y.contentBlockDelta?.delta?.text){const v=y.contentBlockDelta.contentBlockIndex??0,_=y.contentBlockDelta.delta.text;i(v),a+=_,s.set(v,(s.get(v)??"")+_),t.push({content:_})}if(y.contentBlockStart?.start?.toolUse){const v=i(y.contentBlockStart.contentBlockIndex??0);v.toolUse={name:y.contentBlockStart.start.toolUse.name??"",input:{},toolUseId:y.contentBlockStart.start.toolUse.toolUseId??FO()}}if(y.contentBlockDelta?.delta?.toolUse){const v=i(y.contentBlockDelta.contentBlockIndex??0);v.toolUse??={name:"",input:{},toolUseId:FO()};const _=y.contentBlockDelta.delta.toolUse.input;typeof _=="string"?v._inputBuffer=(v._inputBuffer??"")+_:typeof _=="object"&&_!==null&&!Array.isArray(_)&&(v.toolUse.input={...v.toolUse.input??{},..._})}if(y.contentBlockStop){const v=y.contentBlockStop.contentBlockIndex??0;TAt(o.get(v),s.get(v)??"")}if(y.messageStop){l=y.messageStop.stopReason??"end_turn";continue}if(y.metadata?.usage){c+=y.metadata.usage.inputTokens??0,u+=y.metadata.usage.outputTokens??0,d+=y.metadata.usage.cacheReadInputTokens??0,m+=y.metadata.usage.cacheWriteInputTokens??0;break}}for(const[g,y]of o)TAt(y,s.get(g)??"");const h=n.filter(g=>g.text||g.toolUse||g.image||g.document);return{text:a,toolCalls:EAt(h),usage:{inputTokens:c,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:m},rawStopReason:l,raw:h}}function tFr(e){const t=[];let r="";for(const n of e.output?.message?.content??[]){const o={};"text"in n&&n.text&&(o.text=n.text,r+=r?` ${n.text}`:n.text),"toolUse"in n&&n.toolUse&&(o.toolUse={toolUseId:n.toolUse.toolUseId??FO(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:EAt(t),usage:{inputTokens:e.usage?.inputTokens??0,outputTokens:e.usage?.outputTokens??0,cacheReadTokens:e.usage?.cacheReadInputTokens??0,cacheWriteTokens:e.usage?.cacheWriteInputTokens??0},rawStopReason:e.stopReason,raw:t}}function SAt(e){return{providerLabel:"bedrock",maxSteps:e.maxSteps,buildStepRequest(t,r){return{raw:e.buildCommandInput(t,r)}},async executeStep(t,r,n){const o=t.raw;if(!e.streaming){const i=await wAt(o.modelId??"",e.region,a=>Ze(e.client.send(new hAt({...o,modelId:a})),FX,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return tFr(i)}const s=await wAt(o.modelId??"",e.region,i=>Ze(e.client.send(new fAt({...o,modelId:i})),FX,new Error("Bedrock streaming API call timed out")));return eFr(s,r,n)},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw},s={role:"user",content:n.map(i=>({toolResult:{toolUseId:i.id,content:[{text:i.error?`Error executing tool ${i.name}: ${i.error}`:String(typeof i.output=="string"?i.output:JSON.stringify(i.output))}],status:i.error?"error":"success"}}))};return[...t,o,s]},mapFinishReason(t,r){switch(t){case"end_turn":case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return r?"tool-calls":"stop"}}}}var FX,rFr=S({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";yAt(),ct(),Q$r(),FX=12e4}});function CAt(e,t,r){return{input:{text:e.input?.text||"",images:e.input?.images,content:e.input?.content,files:e.input?.files,csvFiles:e.input?.csvFiles,pdfFiles:e.input?.pdfFiles,audioFiles:e.input?.audioFiles,videoFiles:e.input?.videoFiles},csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,systemPrompt:e.systemPrompt,conversationHistory:e.conversationMessages,provider:t,model:r,temperature:e.temperature,maxTokens:e.maxTokens,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,fileRegistry:e.fileRegistry}}var nFr=S({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),UO,xAt=S({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";Cl(),UO=He.provider}}),kAt={};he(kAt,{Agent:()=>gIt,BedrockClient:()=>IAt,BedrockRuntimeClient:()=>MAt,Blob:()=>fIt,Client:()=>vIt,ConverseCommand:()=>PAt,ConverseStreamCommand:()=>DAt,Cron:()=>ZAt,Dispatcher:()=>_It,File:()=>hIt,FlowProducer:()=>YAt,FormData:()=>mIt,GoogleAuth:()=>UAt,HTTPException:()=>oIt,Headers:()=>pIt,Hippocampus:()=>qAt,HippocampusConfig:()=>GAt,Hono:()=>rIt,ImageFormat:()=>OAt,InvokeEndpointCommand:()=>$At,InvokeEndpointWithResponseStreamCommand:()=>FAt,InvokeModelCommand:()=>NAt,Job:()=>KAt,ListFoundationModelsCommand:()=>RAt,MockAgent:()=>TIt,Pool:()=>yIt,Queue:()=>VAt,QueueScheduler:()=>JAt,Request:()=>uIt,Response:()=>dIt,SageMakerRuntimeClient:()=>LAt,TextToSpeechClient:()=>zAt,VertexAI:()=>BAt,Webhook:()=>jAt,Worker:()=>WAt,convertToHtml:()=>tIt,cors:()=>nIt,createClient:()=>HAt,default:()=>AAt,extractRawText:()=>eIt,fetch:()=>cIt,getGlobalDispatcher:()=>bIt,interceptors:()=>EIt,logger:()=>sIt,parseBuffer:()=>XAt,request:()=>SIt,secureHeaders:()=>iIt,selectCover:()=>QAt,setGlobalDispatcher:()=>wIt,streamSSE:()=>aIt,timeout:()=>lIt});var Cg,Ts,AAt,IAt,RAt,MAt,PAt,DAt,OAt,NAt,LAt,$At,FAt,UAt,BAt,zAt,jAt,qAt,GAt,HAt,VAt,WAt,KAt,JAt,YAt,ZAt,XAt,QAt,eIt,tIt,rIt,nIt,oIt,sIt,iIt,aIt,lIt,cIt,uIt,dIt,pIt,mIt,hIt,fIt,gIt,yIt,vIt,_It,wIt,bIt,TIt,EIt,SIt,oFr=S({"npm-stub:@aws-sdk/client-bedrock"(){Cg={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Cg.get}):new Proxy(function(...r){return new Proxy({},{get:Cg.get})},{get:Cg.get,apply(r,n,o){return new Proxy({},{get:Cg.get})},construct(r,n){return new Proxy({},{get:Cg.get})}})}},Ts=new Proxy({},Cg),AAt=Ts,{BedrockClient:IAt,ListFoundationModelsCommand:RAt,BedrockRuntimeClient:MAt,ConverseCommand:PAt,ConverseStreamCommand:DAt,ImageFormat:OAt,InvokeModelCommand:NAt}=Ts,{SageMakerRuntimeClient:LAt,InvokeEndpointCommand:$At,InvokeEndpointWithResponseStreamCommand:FAt}=Ts,{GoogleAuth:UAt,VertexAI:BAt,TextToSpeechClient:zAt}=Ts,{Webhook:jAt}=Ts,{Hippocampus:qAt,HippocampusConfig:GAt}=Ts,{createClient:HAt}=Ts,{Queue:VAt,Worker:WAt,Job:KAt,QueueScheduler:JAt,FlowProducer:YAt}=Ts,{Cron:ZAt}=Ts,{parseBuffer:XAt,selectCover:QAt}=Ts,{extractRawText:eIt,convertToHtml:tIt}=Ts,{Hono:rIt}=Ts,{cors:nIt,HTTPException:oIt,logger:sIt,secureHeaders:iIt,streamSSE:aIt,timeout:lIt}=Ts,cIt=globalThis.fetch,uIt=globalThis.Request,dIt=globalThis.Response,pIt=globalThis.Headers,mIt=globalThis.FormData,hIt=globalThis.File,fIt=globalThis.Blob,gIt=Ts.Agent,yIt=Ts.Pool,vIt=Ts.Client,_It=Ts.Dispatcher,wIt=()=>{},bIt=()=>Ts,TIt=Ts.MockAgent,EIt={redirect:()=>e=>e,retry:()=>e=>e},SIt=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}});async function UX(){return await Promise.resolve().then(()=>(oFr(),kAt))}var CIt=S({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}}),xIt,sFr=S({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";yAt(),Lr(),tS(),vc(),Xo(),f4(),rFr(),yt(),xi(),ct(),q(),Im(),DD(),nFr(),Ji(),er(),xAt(),CIt(),xIt=class bcr extends Il{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(t){return t?t.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(t,r,n,o){super(t,"bedrock",r);const s=t||process.env.BEDROCK_MODEL||this.modelName,i=bcr.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",f.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),f.debug(`[AmazonBedrockProvider] Environment check: AWS_REGION=${process.env.AWS_REGION||"undefined"}, AWS_ACCESS_KEY_ID=${process.env.AWS_ACCESS_KEY_ID?"SET":"undefined"}, AWS_SECRET_ACCESS_KEY=${process.env.AWS_SECRET_ACCESS_KEY?"SET":"undefined"}`);try{f.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new mAt({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),f.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw f.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){const{BedrockClient:t,ListFoundationModelsCommand:r}=await UX(),n=new t({region:this.region});try{f.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");const o=new r({}),s=Date.now();await n.send(o);const i=Date.now()-s;f.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){const s=o instanceof Error?o.message:String(o);f.error("[AmazonBedrockProvider] Health check FAILED - this will cause production failures:",{error:s,errorType:o instanceof Error?o.constructor.name:"Unknown",region:process.env.AWS_REGION||"us-east-1",hasAccessKey:!!process.env.AWS_ACCESS_KEY_ID,hasSecretKey:!!process.env.AWS_SECRET_ACCESS_KEY})}finally{try{n.destroy()}catch{}}}getAISDKModel(){throw new Error("AmazonBedrockProvider does not use AI SDK models")}getProviderName(){return"bedrock"}getDefaultModel(){return process.env.BEDROCK_MODEL||"anthropic.claude-sonnet-4-6"}getDefaultEmbeddingModel(){return process.env.BEDROCK_EMBEDDING_MODEL||process.env.AWS_EMBEDDING_MODEL||"amazon.titan-embed-text-v2:0"}async generate(t){f.debug("[AmazonBedrockProvider] generate() called with conversation management");const r=Date.now(),n=typeof t=="string"?{prompt:t}:t;this.conversationHistory=[];const o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){f.debug("[AmazonBedrockProvider] Detected multimodal input in generate(), using multimodal message builder",{hasImages:!!o?.images?.length,imageCount:o?.images?.length||0,hasContent:!!o?.content?.length,contentCount:o?.content?.length||0,hasFiles:!!o?.files?.length,fileCount:o?.files?.length||0,hasCSVFiles:!!o?.csvFiles?.length,csvFileCount:o?.csvFiles?.length||0,hasPDFFiles:!!o?.pdfFiles?.length,pdfFileCount:o?.pdfFiles?.length||0});const m=CAt(n,this.providerName,this.modelName),h=await RD(m,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(h)}else{f.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const d={role:"user",content:[{text:n.prompt}]};this.conversationHistory.push(d)}f.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let i,a,l,c;try{({text:i,usage:a,finishReason:l,rawFinishReason:c}=await this.conversationLoop(n))}catch(d){const m=this.neurolink?.getEventEmitter();throw m&&m.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:"error"},success:!1,error:d instanceof Error?d.message:String(d)}),d}const u=this.neurolink?.getEventEmitter();return u&&u.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:l},success:!0}),{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),...l!==void 0&&{finishReason:l},...c!==void 0&&{rawFinishReason:c}}}async conversationLoop(t){const r=t.maxSteps||ki,n=await this.resolveTurnTools(t.tools,t.disableTools),o=this.formatToolsForBedrock(n),s=eu(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converse"),i=SAt({client:this.bedrockClient,streaming:!1,region:this.region,maxSteps:r,buildCommandInput:a=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(a),system:[{text:t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:t.maxTokens,...s.temperature!==void 0&&{temperature:s.temperature}},...o?{toolConfig:o}:{}})});try{const{resultPromise:a}=sp(i,this.conversationHistory,{tools:this.toEngineTools(n),abortSignal:t.abortSignal}),l=await a;this.conversationHistory=l.conversation;const c=l.usage.inputTokens,u=l.usage.outputTokens,d=l.usage.cacheReadTokens??0,m=l.usage.cacheWriteTokens??0;return{text:l.text||"",usage:{input:c,output:u,total:c+d+m+u,...d>0&&{cacheReadTokens:d},...m>0&&{cacheCreationTokens:m}},finishReason:l.finishReason,rawFinishReason:l.rawStopReason}}catch(a){throw f.error("[AmazonBedrockProvider] Error in conversation loop:",a),this.handleProviderError(a)}}convertToAWSMessages(t){return t.map(r=>({role:r.role,content:r.content.map(n=>n.text?{text:n.text}:n.image?{image:n.image}:n.document?{document:n.document}:n.toolUse?{toolUse:{toolUseId:n.toolUse.toolUseId,name:n.toolUse.name,input:n.toolUse.input}}:n.toolResult?{toolResult:{toolUseId:n.toolResult.toolUseId,content:n.toolResult.content,status:n.toolResult.status}}:{text:""})}))}async executeSingleTool(t,r,n,o){return UO.startActiveSpan("bedrock.tool.execute",{kind:Br.CLIENT,attributes:{"gen_ai.tool.name":r,"gen_ai.system":"aws.bedrock"}},async s=>{try{if(f.debug(`[AmazonBedrockProvider] Executing single tool: ${r}`,{args:n}),!t[r])throw new Error(`Tool not found: ${r}`);const i=t[r];if(!i||!i.execute)throw new Error(`Tool ${r} does not have execute method`);const a=n||{};r==="list_directory"&&!a.path&&(a.path=".",f.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),f.debug("[AmazonBedrockProvider] Tool input parameters:",a);const l={};for(const[d,m]of Object.entries(a))(m===null||typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="object"&&m!==null)&&(l[d]=m);const c=await i.execute(l);f.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:r,result:c});let u;if(c&&typeof c=="object"&&"success"in c)if(c.success&&c.data!==void 0)typeof c.data=="string"?u=c.data:typeof c.data=="object"?u=JSON.stringify(c.data,null,2):u=String(c.data);else if(c.error){const d=typeof c.error=="string"?c.error:c.error.message||"Tool execution failed";throw new Error(d)}else u="";else typeof c=="string"?u=c:typeof c=="object"?u=JSON.stringify(c,null,2):u=String(c);return s.setStatus({code:qe.OK}),u}catch(i){throw f.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:i}),s.setStatus({code:qe.ERROR,message:i.message}),s.recordException(i),i}finally{s.end()}})}async resolveTurnTools(t,r){if(r)return{};const n=t??await this.getAllTools();return this.convertAISDKToolsToToolDefinitions(n)}toEngineTools(t){const r={};for(const n of Object.keys(t))r[n]={execute:o=>this.executeSingleTool(t,n,o)};return r}convertAISDKToolsToToolDefinitions(t){const r={};for(const[n,o]of Object.entries(t))if("description"in o&&o.description){const i=o.parameters??o.inputSchema;r[n]={description:o.description,parameters:i,execute:async a=>{if("execute"in o&&o.execute)return{success:!0,data:await o.execute(a,{toolCallId:`tool_${Date.now()}`,messages:[]})};throw new Error(`Tool ${n} has no execute method`)}}}return r}formatToolsForBedrock(t){if(!t||Object.keys(t).length===0)return null;const r=Object.entries(t).map(([n,o])=>{let s;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?s=js(o.parameters):s=o.parameters:s={type:"object",properties:{},required:[]},(!s.type||s.type!=="object")&&(s={type:"object",properties:s.properties||{},required:s.required||[]}),{toolSpec:{name:n,description:o.description,inputSchema:{json:s}}}});return f.debug(`[AmazonBedrockProvider] Formatted ${r.length} tools for Bedrock`),{tools:r}}convertToBedrockMessages(t){return t.map(r=>{const n={role:r.role==="system"?"user":r.role,content:[]};return typeof r.content=="string"?n.content.push({text:r.content}):r.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){const s=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image;let i=o.mimeType?.split("/")[1]||"png";i==="jpg"&&(i="jpeg"),n.content.push({image:{format:i==="jpeg"?tx.JPEG:i==="png"?tx.PNG:i==="gif"?tx.GIF:tx.WEBP,source:{bytes:s}}})}else if(o.type==="document"||o.type==="pdf"||o.type==="file"&&o.mimeType?.toLowerCase().startsWith("application/pdf")){let s;if(typeof o.data=="string"){const a=o.data.replace(/^data:application\/pdf;base64,/i,"");s=Buffer.from(a,"base64")}else s=o.data;let i=typeof o.name=="string"&&o.name?fm.basename(o.name):"document-pdf";i=i.replace(/\.[^.]+$/,""),i=i.replace(/[^a-zA-Z0-9\s\-()[\]]/g,"-"),i=i.replace(/-+/g,"-").trim().replace(/^-+|-+$/g,""),i=i||"document",n.content.push({document:{format:"pdf",name:i,source:{bytes:s}}})}}),n})}getBedrockClient(){return this.bedrockClient}async executeStream(t){return f.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),f.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),UO.startActiveSpan("bedrock.stream",{kind:Br.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async r=>{try{if(f.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(t.input?.images?.length||t.input?.content?.length||t.input?.files?.length||t.input?.csvFiles?.length||t.input?.pdfFiles?.length)){f.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!t.input?.images?.length,imageCount:t.input?.images?.length||0,hasContent:!!t.input?.content?.length,contentCount:t.input?.content?.length||0,hasFiles:!!t.input?.files?.length,fileCount:t.input?.files?.length||0,hasCSVFiles:!!t.input?.csvFiles?.length,csvFileCount:t.input?.csvFiles?.length||0,hasPDFFiles:!!t.input?.pdfFiles?.length,pdfFileCount:t.input?.pdfFiles?.length||0});const s=CAt(t,this.providerName,this.modelName),i=await RD(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{f.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");const s={role:"user",content:[{text:t.input.text}]};this.conversationHistory.push(s)}f.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),f.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");const o=await this.streamingConversationLoop(t,r);return f.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),r.setStatus({code:qe.OK}),r.end(),o}catch(n){f.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");const o=n,s=o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream");if(f.debug("[TRACE] executeStream CATCH - checking if permission error"),f.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){f.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),f.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),r.addEvent("stream.fallback_to_generate",{reason:o.message});const i=await this.generate({prompt:t.input.text,input:t.input,maxTokens:t.maxTokens,temperature:t.temperature,systemPrompt:t.systemPrompt});if(!i)throw r.setStatus({code:qe.ERROR,message:"Generate method returned null result"}),r.end(),new Error("Generate method returned null result");r.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),r.setStatus({code:qe.OK}),r.end();const a=new ReadableStream({start(c){const d=(i.content||"").split(/(\s+)/);let m="";for(let h=0;h<d.length;h++)m+=d[h],(h===d.length-1||m.length>50||/[.!?;,]\s*$/.test(m))&&m.length>0&&(c.enqueue({content:m}),m="");m.length>0&&c.enqueue({content:m}),c.close()}});return{stream:{async*[Symbol.asyncIterator](){const c=a.getReader();try{for(;;){const{done:u,value:d}=await c.read();if(u)break;yield d}}finally{c.releaseLock()}}},usage:i.usage,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw r.setStatus({code:qe.ERROR,message:o instanceof Error?o.message:String(o)}),r.recordException(o instanceof Error?o:new Error(String(o))),r.end(),n}})}async streamingConversationLoop(t,r){const n=Date.now(),o=t.maxSteps||ki,s=await this.resolveTurnTools(t.tools,t.disableTools),i=this.formatToolsForBedrock(s),a=eu(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converseStream"),l=SAt({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:M=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(M),system:[{text:t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:t.maxTokens,...a.temperature!==void 0&&{temperature:a.temperature}},...i?{toolConfig:i}:{}})});let c=!1,u;const d=new Promise(M=>{u=()=>{c=!0,M()}}),m={...l,executeStep:async(M,R,k)=>{const O=await l.executeStep(M,R,k);return u(),O}};r.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});const{stream:h,resultPromise:g}=sp(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:t.abortSignal}),y=g.then(M=>({result:M,error:void 0}),M=>({result:void 0,error:M}));if(await Promise.race([d,y]),!c){const M=await y;if(M.error)throw M.error}const v=this.neurolink?.getEventEmitter(),_=this,b={startTime:n,streamId:`bedrock-${Date.now()}`};let T;const x=new Promise(M=>{T=M}),A=M=>{const R=M?.inputTokens??0,k=M?.outputTokens??0,O=M?.cacheReadTokens??0,N=M?.cacheWriteTokens??0;return{input:R,output:k,total:R+O+N+k,...O>0&&{cacheReadTokens:O},...N>0&&{cacheCreationTokens:N}}};return y.then(M=>{T(s0(this.providerName,this.modelName||this.getDefaultModel(),{usage:A(M.result?.usage)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let M=!1;try{yield*h}catch(R){throw M=!0,R}finally{const R=await y;R.error&&(M=!0);const k=A(R.result?.usage);R.result&&(_.conversationHistory=R.result.conversation,b.finishReason=R.result.finishReason,b.rawFinishReason=R.result.rawStopReason,r.setAttribute("gen_ai.response.stop_reason",R.result.rawStopReason??"unknown")),v&&v.emit("generation:end",{provider:_.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:k,model:_.modelName||_.getDefaultModel(),provider:_.providerName,finishReason:M?"error":R.result?.rawStopReason},success:!M})}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:x,metadata:b}}async checkBedrockHealth(){const t=new AbortController,r=setTimeout(()=>t.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await UX(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{f.debug("[AmazonBedrockProvider] Starting health check...");const i=new o({}),l=(await s.send(i,{abortSignal:t.signal})).modelSummaries||[],c=l.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(f.debug(`[AmazonBedrockProvider] Health check passed - Found ${c.length} active models out of ${l.length} total models`),c.length===0)throw new Error("No active foundation models available in the region")}catch(i){clearTimeout(r);const a=i;if(qr(i))throw new Error("Bedrock health check timed out after 10 seconds",{cause:i});const l=typeof a.message=="string"?a.message:"";throw l.includes("UnauthorizedOperation")||l.includes("AccessDenied")?new Error("Bedrock access denied. Check your AWS credentials and IAM permissions for bedrock:ListFoundationModels",{cause:i}):a.code==="ECONNREFUSED"||a.code==="ENOTFOUND"?new Error("Unable to connect to Bedrock service. Check your network connectivity and AWS region configuration",{cause:i}):(f.error("[AmazonBedrockProvider] Health check failed:",i),new Error(`Bedrock health check failed: ${l||"Unknown error"}`,{cause:i}))}finally{clearTimeout(r);try{s.destroy()}catch{}}}formatProviderError(t){return Hi(t,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:Pr,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:Ms,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:_t,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:_t,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(t,r){const n=r||"amazon.titan-embed-text-v2:0";f.debug("Generating embedding",{provider:this.providerName,model:n,textLength:t.length});try{const o=JSON.stringify({inputText:t}),s=new gAt({modelId:n,contentType:"application/json",accept:"application/json",body:o}),i=await Ze(this.bedrockClient.send(s),6e4,new Error("Bedrock embedding API call timed out")),a=JSON.parse(new TextDecoder().decode(i.body));if(!a.embedding||!Array.isArray(a.embedding))throw new Error("Invalid embedding response from Bedrock");return f.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.embedding.length}),a.embedding}catch(o){throw f.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:t.length}),this.handleProviderError(o)}}async embedMany(t,r){const n=r||"amazon.titan-embed-text-v2:0";f.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:t.length});try{const o=await Promise.all(t.map(s=>this.embed(s,n)));return f.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw f.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:t.length}),this.handleProviderError(o)}}}}}),kIt={};he(kIt,{AmazonBedrockProvider:()=>xIt,bedrockTracer:()=>UO,loadBedrockControl:()=>UX});var iFr=S({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";sFr(),xAt(),CIt()}}),AIt={};he(AIt,{AzureOpenAIProvider:()=>IIt});var IIt,aFr=S({"src/lib/providers/azureOpenai.ts"(){"use strict";yt(),q(),xi(),us(),Kd(),Ml(),Ym(),IIt=class extends Za{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,r,n){const o=n?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",s=process.env.AZURE_OPENAI_ENDPOINT||"";let i;if(s)try{i=new URL(s.includes("://")?s:`https://${s}`)}catch{i=void 0}const a=i?.hostname??"",l=i?.pathname&&i.pathname!=="/"?i.pathname.replace(/\/+$/,""):"",c=/\.(openai|cognitiveservices)\.azure\.com$/.test(a);let u;c?u="/openai":u=/\/openai(?:\/v\d+)?$/.test(l)?l:`${l}/openai`;const d=i?.origin??"",m=n?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",h=n?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",g=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,y=n?.useMaxCompletionTokens??(g===void 0?void 0:/^(1|true|yes)$/i.test(g));o||Vi(qvr()),d||Vi(Gvr()),super("azure",e,t,{baseURL:d,apiKey:o}),this.azureDeployment=m,this.azureApiVersion=h,this.azureResourceOrigin=d,this.azureDeploymentPathPrefix=u,this.useMaxCompletionTokensOverride=y,f.shouldLog("debug")&&f.debug("Azure OpenAI Provider initialized",FGe({deployment:this.azureDeployment,resourceOrigin:this.azureResourceOrigin,deploymentPathPrefix:this.azureDeploymentPathPrefix,apiVersion:this.azureApiVersion,provider:"azure"}))}suppressResponseFormatWithTools(){return!1}getProviderName(){return"azure"}getDefaultModel(){return this.azureDeployment}formatProviderError(e){const t=[{match:r=>/401/.test(r.message),errorClass:Pr,message:"Invalid Azure OpenAI API key or endpoint."},...ja];return Hi(e,t,"azure",this.modelName)}getChatCompletionsURL(e){const t=e||this.azureDeployment,r=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${r}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){const r=this.useMaxCompletionTokensOverride??ybt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function lFr(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"}var cFr=S({"src/lib/utils/imageDetection.ts"(){"use strict"}});function RIt(e){return e.map(t=>typeof t.content=="string"?{role:t.role,content:t.content}:{role:t.role,content:t.content.map(r=>r.type==="image"||r.type==="document"?{type:r.type,media_type:r.source.media_type,base64_chars:r.source.data.length}:r)})}var uFr=S({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),BO,dFr=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs"(){BO=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}}}),pFr=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs"(){oo()}});function BX(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var zO,zX,MIt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs"(){pFr(),zO=e=>(zO=Array.isArray,zO(e)),zX=zO}});function*mFr(e){if(!e)return;if(jX in e){const{values:n,nulls:o}=e;yield*n.entries();for(const s of o)yield[s,null];return}let t=!1,r;e instanceof Headers?r=e.entries():zX(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){const o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");const s=zX(n[1])?n[1]:[n[1]];let i=!1;for(const a of s)a!==void 0&&(t&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var jX,PIt,hFr=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){MIt(),jX=Symbol.for("brand.privateNullableHeaders"),PIt=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[s,i]of mFr(n)){const a=s.toLowerCase();o.has(a)||(t.delete(s),o.add(a)),i===null?(t.delete(s),r.add(a)):(t.append(s,i),r.delete(a))}}return{[jX]:!0,values:t,nulls:r}}}});function fFr(e){const t=new HC(e);return delete t.batches,t}function gFr(e){const t=new Sa(e);return delete t.messages.batches,t}var DIt,OIt,qX,NIt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){AO(),zSt(),t4(),dFr(),MIt(),hFr(),AO(),DIt="vertex-2023-10-16",OIt=new Set(["/v1/messages","/v1/messages?beta=true"]),qX=class extends Mo{constructor({baseURL:e=BO("ANTHROPIC_VERTEX_BASE_URL"),region:t=BO("CLOUD_ML_REGION")??null,projectId:r=BO("ANTHROPIC_VERTEX_PROJECT_ID")??null,...n}={}){if(!t)throw new Error("No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.");if(!e)switch(t){case"global":e="https://aiplatform.googleapis.com/v1";break;case"us":e="https://aiplatform.us.rep.googleapis.com/v1";break;case"eu":e="https://aiplatform.eu.rep.googleapis.com/v1";break;default:e=`https://${t}-aiplatform.googleapis.com/v1`}if(super({baseURL:e,...n}),this.messages=fFr(this),this.beta=gFr(this),this.region=t,this.projectId=r,this.accessToken=n.accessToken??null,n.authClient&&n.googleAuth)throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");n.authClient?this._authClientPromise=Promise.resolve(n.authClient):(this._auth=n.googleAuth??new xJ({scopes:"https://www.googleapis.com/auth/cloud-platform"}),this._authClientPromise=this._auth.getClient())}validateHeaders(){}async prepareOptions(e){const t=await this._authClientPromise,r=await t.getRequestHeaders(),n=t.projectId??r["x-goog-user-project"];!this.projectId&&n&&(this.projectId=n),e.headers=PIt([r,e.headers])}async buildRequest(e){if(BX(e.body)&&(e.body={...e.body}),BX(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=DIt)),OIt.has(e.path)&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");if(!BX(e.body))throw new Error("Expected request body to be an object for post /v1/messages");const t=e.body.model;e.body.model=void 0;const n=e.body.stream??!1?"streamRawPredict":"rawPredict";e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${t}:${n}`}if(e.path==="/v1/messages/count_tokens"||e.path=="/v1/messages/count_tokens?beta=true"&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`}return super.buildRequest(e)}}}}),GX={};he(GX,{AnthropicVertex:()=>qX,BaseAnthropic:()=>Mo,default:()=>qX});var LIt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){NIt(),NIt()}});async function yFr(){return jO||(jO=await Promise.resolve().then(()=>(LIt(),GX))),jO}function vFr(e){const t=[],r=new Map;let n=0;const o=s=>{const i=`${n}:${s??"x"}`;let a=r.get(i);return a||(a={type:"tool_step",callParts:[],resultParts:[]},r.set(i,a),t.push(a)),a};for(const s of e){if(s.role==="tool_call"){o(s.metadata?.stepIndex).callParts.push({name:s.tool||"unknown",input:s.args||{}});continue}if(s.role==="tool_result"){o(s.metadata?.stepIndex).resultParts.push(s.content&&s.content.length>0?s.content:"(no output)");continue}const i=s.role==="assistant"?"assistant":s.role==="user"?"user":null;!i||!s.content||s.content.trim().length===0||(n++,t.push({type:"regular",role:i,parts:[s.content]}))}return t}function HX(e,t,r){const n=e[e.length-1];n&&n.role===t&&Array.isArray(n.content)?n.content.push(...r):e.push({role:t,content:[...r]})}function _Fr(e,t){const r=e.callParts,n=e.resultParts,o=Math.min(r.length,n.length);(o!==r.length||o!==n.length)&&f.debug("[GoogleVertex] Unbalanced tool step in Claude history replay",{calls:r.length,results:n.length,paired:o});const s=[],i=[];for(let a=0;a<o;a++){const l=`hist_${t}_${a}`;s.push({type:"tool_use",id:l,name:r[a].name,input:r[a].input}),i.push({type:"tool_result",tool_use_id:l,content:n[a]})}return{uses:s,results:i}}function wFr(e){const t=r=>Array.isArray(r.content)&&r.content.length>0&&r.content.every(n=>n.type==="tool_result");for(;e.length>0&&(e[0].role!=="user"||t(e[0]));)e.shift()}function VX(e){const t=[];let r=0;for(const n of vFr(e)){if(n.type==="regular"){HX(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:s}=_Fr(n,r);o.length!==0&&(r++,HX(t,"assistant",o),HX(t,"user",s))}if(wFr(t),f.shouldLog("debug")){const n=t.flatMap(o=>Array.isArray(o.content)?o.content:[]);f.debug("[GoogleVertex] Replayed Claude history with tool turns",{historyMessages:t.length,toolUseBlocks:n.filter(o=>o.type==="tool_use").length,toolResultBlocks:n.filter(o=>o.type==="tool_result").length})}return t}function WX(e,t){const r=e[e.length-1];if(r&&r.role==="user"){const n=Array.isArray(r.content)?r.content:[{type:"text",text:r.content}],o=Array.isArray(t)?t:[{type:"text",text:t}];r.content=[...n,...o];return}e.push({role:"user",content:t})}function oh(e){if(!e||typeof e!="object")return;const t=["additionalProperties","default","$schema","$id","$ref","definitions","$defs","examples","errorMessage"];for(const n of t)n in e&&delete e[n];typeof e.exclusiveMinimum=="boolean"&&(e.exclusiveMinimum===!0&&typeof e.minimum=="number"?(e.exclusiveMinimum=e.minimum,delete e.minimum):delete e.exclusiveMinimum),typeof e.exclusiveMaximum=="boolean"&&(e.exclusiveMaximum===!0&&typeof e.maximum=="number"?(e.exclusiveMaximum=e.maximum,delete e.maximum):delete e.exclusiveMaximum);const r=2147483647;if(typeof e.maximum=="number"&&e.maximum>r&&delete e.maximum,typeof e.minimum=="number"&&e.minimum<-r&&delete e.minimum,e.properties&&typeof e.properties=="object")for(const n of Object.values(e.properties))n&&typeof n=="object"&&oh(n);if(e.items&&typeof e.items=="object")if(Array.isArray(e.items))for(const n of e.items)n&&typeof n=="object"&&oh(n);else oh(e.items);for(const n of["allOf","anyOf","oneOf"])if(Array.isArray(e[n]))for(const o of e[n])o&&typeof o=="object"&&oh(o)}function $It(e,t,r){const n=Swt({contents:e,availableInputTokens:ou("vertex",t),provider:"vertex",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=>{if(!("functionResponse"in c))return c;const u=c.functionResponse,d=JSON.stringify(u.response)??"";return d.length<=qIt?c:{functionResponse:{name:u.name,response:{result:BJ(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:jJ}]})}return e.length=0,e.push(...i),!0}function FIt(e,t,r){const n=Wkt({conversation:e,availableInputTokens:ou("vertex",t),fixedOverheadTokens:0,provider:"vertex",observedPromptTokens:r,observedDescribesCurrentPayload:!0});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.content)){i.push({...l,content:l.content.map(c=>{if(c.type!=="tool_result")return c;const u=typeof c.content=="string"?c.content:JSON.stringify(c.content)??"";return{...c,content:Vkt(u)}})});continue}i.push(l)}if(o.size>0){let a=i.findIndex(l=>Array.isArray(l.content)&&l.content.some(c=>c.type==="tool_use"||c.type==="tool_result"));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",content:[{type:"text",text:CX}]})}return e.length=0,e.push(...i),!0}async function UIt(e,t,r={}){const n=[],o=[];let s,i=0,a=0,l=0,c=0;for await(const u of e){r.onProgress?.();const d=u,h=d.candidates?.[0],g=h?.finishReason;typeof g=="string"&&g&&(s=g);const y=h?.content;if(y&&Array.isArray(y.parts))for(const _ of y.parts)n.push(_),typeof _.text=="string"&&_.text.length>0&&t.push({content:_.text});u.functionCalls&&o.push(...u.functionCalls);const v=d.usageMetadata;if(v){if(v.promptTokenCount!==void 0&&v.promptTokenCount>0){r.onUsageDelta?.("input",v.promptTokenCount-i),i=v.promptTokenCount,r.onUsage?.(v.promptTokenCount,v.candidatesTokenCount??0);const _=Math.min(v.cachedContentTokenCount??0,v.promptTokenCount);r.onUsageDelta?.("cacheRead",_-l),l=_}v.candidatesTokenCount!==void 0&&v.candidatesTokenCount>0&&(r.onUsageDelta?.("output",v.candidatesTokenCount-a),a=v.candidatesTokenCount),v.thoughtsTokenCount!==void 0&&v.thoughtsTokenCount>0&&(r.onUsageDelta?.("reasoning",v.thoughtsTokenCount-c),c=v.thoughtsTokenCount)}}return{rawResponseParts:n,stepFunctionCalls:o,...s?{finishReason:s}:{},inputTokens:i,outputTokens:a,...l?{cacheReadTokens:l}:{},...c?{reasoningTokens:c}:{}}}var jO,BIt,qO,rx,KX,m_,xg,zIt,jIt,GO,qIt,JX,bFr=S({"src/lib/providers/googleVertex/client.ts"(){"use strict";gn(),PJ(),Lr(),vc(),pW(),m4(),Lit(),Xo(),sP(),If(),t9(),vr(),no(),yt(),xi(),ct(),Xkt(),tvt(),DD(),q(),MJ(),xwt(),Kkt(),EJ(),cFr(),SJ(),us(),Ji(),uwt(),O0(),Fa(),kwt(),_wt(),f4(),oAt(),YS(),U0(),qJ(),Yu(),lS(),Cl(),er(),uc(),Kd(),bP(),Im(),uFr(),YS(),jO=null,BIt=()=>!0,qO=()=>Vi(Qvr()),rx=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",KX=(e,t)=>{const r=t||rx();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||F7.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},m_=KX,xg=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",zIt=()=>!!(process.env.GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK||process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.GOOGLE_SERVICE_ACCOUNT_KEY||process.env.GOOGLE_AUTH_CLIENT_EMAIL&&process.env.GOOGLE_AUTH_PRIVATE_KEY),jIt=async(e,t,r,n)=>{const o=e||rx();return{projectId:r?r.projectId?.trim()||"express":qO(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},GO=e=>e.toLowerCase().includes("claude"),qIt=2048,JX=class ln extends Il{projectId;location;expressApiKey;baseURL;registeredTools=new Map;toolContext={};static modelConfigCache=new Map;static modelConfigCacheTime=0;static CACHE_DURATION=300*1e3;static MAX_CACHE_SIZE=50;static maxTokensCache=new Map;static maxTokensCacheTime=0;constructor(t,r,n,o,s){super(t,"vertex",n),s&&(s.projectId&&(process.env.GOOGLE_CLOUD_PROJECT=String(s.projectId)),s.location&&(process.env.GOOGLE_CLOUD_LOCATION=String(s.location)),s.apiKey&&(process.env.GOOGLE_API_KEY=String(s.apiKey),!s.projectId&&!s.location&&(this.expressApiKey=String(s.apiKey))),s.baseURL&&(this.baseURL=String(s.baseURL)));const i=!!this.resolveExpressApiKey();i||zIt()||Vi(e0r()),this.projectId=s?.projectId||(i?"":qO()),this.location=o||s?.location||rx(),f.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),f.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return xg()}async getAISDKModel(){throw new Ne({code:Xe.INVALID_CONFIGURATION,message:"GoogleVertexProvider no longer uses @ai-sdk/google-vertex. All models use native SDKs: @google/genai for Gemini, @anthropic-ai/vertex-sdk for Claude.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}validateStreamOptionsOnly(t){this.validateStreamOptions(t)}async preprocessNativeFileInput(t){if(t.input&&jK(t.input),t.input?.files?.length)try{await qK(t,100*1024*1024,this.providerName)}catch(r){f.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${r instanceof Error?r.message:String(r)}`)}await VS(t.input)}async executeStream(t,r){const n=t.model||this.modelName||xg();return QUe({name:"neurolink.provider.stream",tracer:He.provider,attributes:{[Pe.GEN_AI_SYSTEM]:this.providerName,[Pe.GEN_AI_MODEL]:n,[Pe.GEN_AI_OPERATION]:"stream",[Pe.NL_PROVIDER]:this.providerName}},async o=>{const s=Date.now(),i=t.tools||{};await this.preprocessNativeFileInput(t);const l={...await gt({name:"neurolink.message.build",tracer:He.provider,attributes:{[Pe.NL_PROVIDER]:this.providerName,"message.count":1,"message.build.count":1,"message.build.path":"vertex.native.stream"}},async()=>this.processCSVFilesForNativeSDK(t)),tools:i};try{let c;GO(n)?(f.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(i).length}),c=await this.executeNativeAnthropicStream(l)):(f.info("[GoogleVertex] Routing Gemini model to native @google/genai",{model:n,totalToolCount:Object.keys(i).length}),c=await this.executeNativeGemini3Stream(l)),this.attachUsageAndCostAttributes(o,n,c?.usage);const u=this.wrapStreamResultWithLifecycle(t,c,s);return this.emitStreamEnd(n,s,!0,void 0,c.finishReason),u}catch(c){throw this.fireGenerateOnError(t,c,s),this.emitStreamEnd(n,s,!1,c),c}},o=>o.stream,(o,s)=>this.preserveStreamResultAccessors(o,{...o,stream:s}))}emitStreamEnd(t,r,n,o,s){const i=this.neurolink?.getEventEmitter();i&&i.emit("stream:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:t,provider:this.providerName,finishReason:n?s??"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async createVertexGenAIClient(t){Owt("GoogleVertex");const r=this.resolveExpressApiKey(),n=r?"":qO(),o=t||this.location||rx(),i=(await Promise.resolve().then(()=>(pE(),zv))).GoogleGenAI;if(!i)throw new Ne({code:Xe.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const a=i,l=this.resolveBaseURL(),c={...l?{baseUrl:l}:{}};return r?new a({vertexai:!0,apiKey:r,httpOptions:c}):new a({vertexai:!0,project:n,location:o,httpOptions:c})}resolveBaseURL(){const t=this.baseURL?.trim()||process.env.GOOGLE_VERTEX_BASE_URL?.trim();return t&&t.length>0?t:void 0}resolveExpressApiKey(){const t=this.expressApiKey?.trim();if(t)return t;const r=process.env.GOOGLE_VERTEX_API_KEY?.trim();return r?["GOOGLE_CLOUD_PROJECT_ID","VERTEX_PROJECT_ID","GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT"].some(o=>(process.env[o]??"").trim().length>0)?void 0:r:void 0}buildGeminiFunctionDeclaration(t,r){const n={name:t,description:r.description||`Tool: ${t}`},s=r.parameters||r.inputSchema;if(s){const i=js(s,"openApi3"),a=dn(i);a.$schema&&delete a.$schema;const l=Ai(a);oh(l),n.parametersJsonSchema=l}return n}refreshGeminiToolDeclarations(t,r,n,o){if(!t||!r)return;const s=new Set(r.map(i=>i.name));for(const[i,a]of Object.entries(t))s.has(i)||(r.push(this.buildGeminiFunctionDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),f.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Gemini declarations.`))}resolveGeminiToolOnMiss(t,r,n,o,s){if(!n)return;const i=NV(r,t);if(i?.execute)return n.some(a=>a.name===t)||n.push(this.buildGeminiFunctionDeclaration(t,i)),o.set(t,i.execute),s.delete(t),f.info(`[GoogleVertex] Tool "${t}" resolved mid-turn via discovery \u2014 executing.`),o.get(t)}buildAnthropicToolDeclaration(t,r){const n={name:t,description:r.description||`Tool: ${t}`,input_schema:{type:"object"}},s=r.parameters||r.inputSchema;if(s){const i=js(s),a=dn(i);n.input_schema={type:"object",properties:a.properties||{},required:a.required||[]}}return n}refreshAnthropicToolDeclarations(t,r,n,o){if(!t||!r)return;const s=new Set(r.map(i=>i.name));for(const[i,a]of Object.entries(t))s.has(i)||(r.push(this.buildAnthropicToolDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),f.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Anthropic declarations.`))}resolveAnthropicToolOnMiss(t,r,n,o,s){if(!n)return;const i=NV(r,t);if(i?.execute)return n.some(a=>a.name===t)||n.push(this.buildAnthropicToolDeclaration(t,i)),o.set(t,i.execute),s.delete(t),f.info(`[GoogleVertex] Tool "${t}" resolved mid-turn via discovery \u2014 executing.`),o.get(t)}async executeNativeGemini3Stream(t){const r=t.model||this.modelName||xg(),n=m_(r,t.region),o=await this.createVertexGenAIClient(n);f.debug("[GoogleVertex] Using native @google/genai for Gemini 3",{model:r,hasTools:!!t.tools&&Object.keys(t.tools).length>0,project:this.projectId,location:n});const s=[],i=[{text:t.input.text??""}],a=t.input;if(a?.pdfFiles&&a.pdfFiles.length>0){f.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(const ne of a.pdfFiles){let Fe;typeof ne=="string"?Go.existsSync(ne)?Fe=Go.readFileSync(ne):Fe=Buffer.from(ne,"base64"):Fe=ne;const ae=Fe.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:ae}})}}if(await NJ(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){f.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(const ne of a.images){const Fe=RS(ne);let ae,oe="image/jpeg";if(typeof Fe=="string")if(Go.existsSync(Fe)){ae=Go.readFileSync(Fe);const X=OS(Fe);oe=X.startsWith("image/")?X:this.detectImageType(ae)}else if(Fe.startsWith("data:")){const X=Fe.match(/^data:([^;]+);base64,(.+)$/);if(X)oe=X[1],ae=Buffer.from(X[2],"base64");else continue}else if(Fe.startsWith("http://")||Fe.startsWith("https://"))try{const X=await fetch(Fe);if(!X.ok){f.warn(`[GoogleVertex] Image fetch failed: ${X.status} ${X.statusText}, skipping`,{url:un(Fe)});continue}const Z=await X.arrayBuffer();ae=Buffer.from(Z);const _e=X.headers.get("content-type");_e&&_e.startsWith("image/")&&(oe=_e.split(";")[0])}catch(X){f.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${X instanceof Error?X.message:String(X)}`,{url:un(Fe)});continue}else ae=Buffer.from(Fe,"base64"),oe=this.detectImageType(ae);else ae=Fe,oe=this.detectImageType(ae);const pe=ae.toString("base64");i.push({inlineData:{mimeType:oe,data:pe}})}}d4(s,t.conversationMessages),s.push({role:"user",parts:i});let l;const c=new $0;let u;if(t.tools&&Object.keys(t.tools).length>0&&!t.disableTools){const ne=B0(t.tools,"functionDeclarations");u=ne,l=ne.toolsConfig;for(const[Fe,ae]of ne.executeMap)c.set(Fe,ae);f.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ne.toolsConfig[0].functionDeclarations.length,toolNames:ne.toolsConfig[0].functionDeclarations.map(Fe=>Fe.name)})}const d=t;let m=!1;if(d.schema&&l){m=!0;const ne=js(d.schema,"openApi3"),Fe=dn(ne);Fe.$schema&&delete Fe.$schema;const ae=Ai(Fe),oe=l[0]?.functionDeclarations||[];oe.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:ae}),l=[{functionDeclarations:oe}],f.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(ae),totalTools:oe.length})}const h=eu(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),g={...h.temperature!==void 0&&{temperature:h.temperature},maxOutputTokens:t.maxTokens};TJ(r)&&(g.maxOutputTokens&&g.maxOutputTokens>Ka&&(f.warn(`[GoogleVertex] Capping maxOutputTokens from ${g.maxOutputTokens} to ${Ka} for ${r}`),g.maxOutputTokens=Ka),g.maxOutputTokens||(g.maxOutputTokens=Ka)),h.topP!==void 0&&(g.topP=h.topP),t.topK!==void 0&&(g.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(g.stopSequences=t.stopSequences),l&&(g.tools=l);let y=t.systemPrompt||"";m&&(y=y+`
1121
+ `);return{...s!==void 0?{system:s}:{},messages:r}},NX=e=>{if(!(!e||e==="auto")){if(e==="none")return{type:"none"};if(e==="required")return{type:"any"};if(typeof e=="object"){const t=e;if(t.type==="tool"&&t.toolName)return{type:"tool",name:t.toolName}}}},uAt=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},LX=6e5,dAt=class extends Il{client;authMethod;subscriptionTier;enableBetaFeatures;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,r,n){const o=!!(n?.apiKey&&!n?.oauthToken),s=o?null:(n?.oauthToken?{accessToken:n.oauthToken}:null)??r?.oauthToken??DX(),i=o?"api_key":r?.authMethod??cAt(s),a=r?.subscriptionTier??(i==="oauth"?lAt(s):"api"),l=e||ex();let c=l;!process.env.ANTHROPIC_BASE_URL&&a!=="api"&&!wX(l,a)&&(c=bX(a),f.warn("Model not available for subscription tier, using recommended model",{requestedModel:l,subscriptionTier:a,recommendedModel:c})),super(c,"anthropic",t),this.enableBetaFeatures=r?.enableBetaFeatures??!0,this.oauthToken=s,this.subscriptionTier=a,this.authMethod=i;const d=this.getAuthHeaders();let m;if(f.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){f.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");const h=this.oauthToken,g=F2r(()=>h.accessToken,this.enableBetaFeatures,!1,!0);m=new Tg({apiKey:"oauth-authenticated",fetch:Bkt(g),timeout:LX,maxRetries:0}),f.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),f.debug("Anthropic Provider initialized with OAuth",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,hasRefreshToken:!!this.oauthToken.refreshToken,tokenExpiry:this.oauthToken.expiresAt?new Date(this.oauthToken.expiresAt).toISOString():"none"})}else{const h=n?.apiKey??r?.apiKey??PX(),g=(()=>{const y=process.env.ANTHROPIC_BASE_URL;if(!y)return;const v=y.replace(/\/+$/,""),_=v.replace(/\/v\d+$/,"");return _!==v&&f.debug("[AnthropicProvider] Stripping the version suffix from ANTHROPIC_BASE_URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:Xn(y),rewrittenTo:Xn(_)}),_})();m=new Tg({apiKey:h,defaultHeaders:d,...g&&{baseURL:g},fetch:Bkt(Bt()),timeout:LX,maxRetries:0}),f.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.client=m,this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},f.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?$O["anthropic-beta"]:"disabled"})}getAuthHeaders(){const e={},t=!!process.env.ANTHROPIC_BASE_URL;if(this.enableBetaFeatures)if(t){const r=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",n=[...YC,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];r&&n.push("context-1m-2025-08-07"),e["anthropic-beta"]=n.join(",")}else e["anthropic-beta"]=$O["anthropic-beta"];return t&&(e["User-Agent"]=Eg),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return f.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;const t=wX(e,this.subscriptionTier);return t||f.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return TX(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){f.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){f.debug("Token has no expiry information, assuming valid");return}const e=Date.now(),t=this.oauthToken.expiresAt<=e,r=this.oauthToken.expiresAt<=e+wue;if(!t&&!r){f.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new Pr("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);f.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}f.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});const n=this.oauthToken,o=n.refreshToken;this.refreshPromise=(async()=>{const i=new AbortController,a=setTimeout(()=>i.abort(),3e4),l=await fetch(JC,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Eg},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:vX}),signal:i.signal});if(clearTimeout(a),!l.ok){const d=await l.text();throw new Pr(`Failed to refresh OAuth token: ${l.status} ${d}`,this.providerName)}const c=await l.json();n.accessToken=c.access_token,n.refreshToken=c.refresh_token||n.refreshToken,n.expiresAt=c.expires_in?Date.now()+c.expires_in*1e3:void 0,n.tokenType=c.token_type||"Bearer";const u=n;try{const d=Sr(Uu(),".neurolink");Os(d)||k1(d,{recursive:!0});const m=Sr(d,"anthropic-credentials.json"),h=`${m}.tmp`,y={...Os(m)?JSON.parse($d(m,"utf-8")):{},type:"oauth",oauth:u,updatedAt:Date.now()};C1(h,JSON.stringify(y,null,2),{mode:384}),qz(h,m),f.debug("Refreshed OAuth credentials persisted to disk")}catch(d){f.warn("Failed to persist refreshed OAuth token to disk",{error:d instanceof Error?d.message:String(d)})}f.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!c.refresh_token,expiresIn:c.expires_in})})();try{await this.refreshPromise}catch(s){throw s instanceof Pr?s:new Pr(`Failed to refresh OAuth token: ${s instanceof Error?s.message:String(s)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,r){this.lastResponseMetadata={rateLimit:e,...t?{requestId:t}:{}},this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),r&&(r.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=r.inputTokens,this.usageInfo.tokensUsed+=r.inputTokens),r.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=r.outputTokens,this.usageInfo.tokensUsed+=r.outputTokens)),e?.requestsRemaining!==void 0&&(this.usageInfo.messagesRemaining=e.requestsRemaining),e?.tokensRemaining!==void 0&&(this.usageInfo.tokensRemaining=e.tokensRemaining),e?.requestsLimit&&e.requestsLimit>0&&(this.usageInfo.messageQuotaPercent=Math.round((e.requestsLimit-(e.requestsRemaining??0))/e.requestsLimit*100)),e?.tokensLimit&&e.tokensLimit>0&&(this.usageInfo.tokenQuotaPercent=Math.round((e.tokensLimit-(e.tokensRemaining??0))/e.tokensLimit*100)),e?.retryAfter!==void 0?(this.usageInfo.isRateLimited=!0,this.usageInfo.rateLimitExpiresAt=Date.now()+e.retryAfter*1e3):(this.usageInfo.isRateLimited=!1,this.usageInfo.rateLimitExpiresAt=void 0)),e?.requestsRemaining!==void 0&&e.requestsRemaining<=5&&f.warn("Approaching Anthropic request rate limit",{remaining:e.requestsRemaining,limit:e.requestsLimit,reset:e.requestsReset}),e?.tokensRemaining!==void 0&&e.tokensLimit&&e.tokensRemaining<e.tokensLimit*.1&&f.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return ex()}getAISDKModel(){const e=this.client,t=this.providerName,r=this.modelName||ex(),n=i=>this.getTimeout(i??{}),o=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:r,supportedUrls:{},doGenerate:async i=>{await o();const a=OX(i.prompt),l=a.messages;let c=a.system,u=(i.tools??[]).filter($=>$.type==="function").map($=>{const U=ip($);return{name:$.name,...$.description?{description:$.description}:{},input_schema:$.inputSchema??{type:"object",properties:{}},...U?{cache_control:U}:{}}});u&&u.length===0&&(u=void 0);let d=i.toolChoice?NX(i.toolChoice.type==="tool"?{type:"tool",toolName:i.toolChoice.toolName}:i.toolChoice.type):void 0,m;if(i.responseFormat?.type==="json"){m=i.responseFormat.name??"json";const $=i.responseFormat.schema??{type:"object"};u=[{name:m,description:i.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:$}],d={type:"tool",name:m}}const h=i.providerOptions?.anthropic?.finalResultSchema;let g=!1;if(!m&&h){const $=eAt(u,h);u=$.tools,g=$.applied,$.applied&&(c=tAt(c))}const y=i.providerOptions?.anthropic?.thinking,v=Jkt({system:c,tools:u,messages:l}),_=Ykt(l,PO-v),b=eu("anthropic",r,{...i.temperature!==void 0&&i.temperature!==null?{temperature:i.temperature}:{},...i.topP!==void 0&&i.topP!==null?{topP:i.topP}:{}},"anthropic.doGenerate"),T={model:r,messages:_,max_tokens:QD(r,i.maxOutputTokens),...c?{system:c}:{},...b.temperature!==void 0?{temperature:b.temperature}:{},...b.topP!==void 0?{top_p:b.topP}:{},...i.stopSequences&&i.stopSequences.length>0?{stop_sequences:i.stopSequences}:{},...u?{tools:u}:{},...d?{tool_choice:d}:{},...y?{thinking:y}:{}},x=i.timeout,A=x!=null,I=T.max_tokens>8192&&!A?Math.max(n(i),3e5):n(i),M=rc(I,t,"generate");let R;try{R=await e.messages.create(T,{signal:i1(i.abortSignal,M?.controller.signal)})}finally{M?.cleanup()}const k=[];let O;const N=[];let P=!1;for(const $ of R.content)$.type==="thinking"?k.push({type:"reasoning",text:$.thinking}):$.type==="text"?m?N.push($.text):k.push({type:"text",text:$.text}):$.type==="tool_use"&&(m&&$.name===m?(P=!0,k.push({type:"text",text:iC($.input)})):g&&$.name===QC?O=iC($.input):k.push({type:"tool-call",toolCallId:$.id,toolName:$.name,input:iC($.input)}));if(m&&!P&&N.length>0&&k.push({type:"text",text:N.join("")}),O!==void 0){const $=k.filter(U=>U.type==="reasoning");k.length=0,k.push(...$,{type:"text",text:O}),f.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:O.length})}const D=R.usage.cache_read_input_tokens??0,L=R.usage.cache_creation_input_tokens??0;return{content:k,finishReason:{unified:O!==void 0?"stop":uAt(R.stop_reason),raw:R.stop_reason??"stop"},usage:{inputTokens:{total:R.usage.input_tokens+D+L,noCache:R.usage.input_tokens,cacheRead:D,cacheWrite:L},outputTokens:{total:R.usage.output_tokens,text:R.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:T},response:{id:R.id,modelId:R.model,headers:H2r()??{},body:R}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}formatProviderError(e){return Hi(e,[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(r.message),errorClass:Pr,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:r=>r.statusCode===429||/rate limit|too_many_requests|429/i.test(r.message),errorClass:Ms,message:"Anthropic rate limit exceeded. Please try again later."},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(r.message),errorClass:co,message:r=>`Connection error: ${r.message}`},{match:r=>/500|502|503|504|server error/i.test(r.message),errorClass:_t,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:_t,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await q2r(()=>super.generate(e,t));return r&&n&&(this.recordLimitSnapshot(n),r.limits=n,r.analytics&&(r.analytics.limits=n)),r}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),W2r(e),K2r(e,this.modelName)}async executeStream(e,t){return V2r(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);const r=this.getTimeout(e),n=rc(r,this.providerName,"stream"),o=new AbortController,s=sye([e.abortSignal,n?.controller.signal,o.signal]).signal;let i,a,l,c,u=!1;try{c=!e.disableTools&&this.supportsTools(),i=c?e.tools||await this.getAllTools():{},a=c?B0(i,"input_schema"):void 0;const G=await this.buildMessagesForStream(e);if(l=OX(G),e.schema&&a&&a.length>0){const K=eAt(a,js(e.schema));a=K.tools,u=K.applied,K.applied&&(l.system=tAt(l.system))}}catch(G){throw n?.cleanup(),this.handleProviderError(G)}const d=this.modelName||ex(),m=c&&a&&a.length>0?NX(Sbt(e,i,c)):void 0,h=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,g=aAt.startSpan("neurolink.provider.streamText",{kind:Br.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":d}}),y=e.maxSteps||ki,v=this.neurolink?.getEventEmitter(),_=F0(),{push:b}=_,{usagePromise:T,finishPromise:x,resolveUsage:A,resolveFinish:I}=dY();T.then(G=>{g.setAttribute("gen_ai.usage.input_tokens",G.promptTokens||0),g.setAttribute("gen_ai.usage.output_tokens",G.completionTokens||0),G.cacheReadTokens&&g.setAttribute("gen_ai.usage.cached_input_tokens",G.cacheReadTokens);const K=Ga(this.providerName,this.modelName,{input:G.promptTokens||0,output:G.completionTokens||0,total:G.totalTokens||0,...G.cacheReadTokens?{cacheReadTokens:G.cacheReadTokens}:{},...G.cacheCreationTokens?{cacheCreationTokens:G.cacheCreationTokens}:{}});K&&K>0&&g.setAttribute("neurolink.cost",K)}).catch(()=>{}),x.then(G=>{g.setAttribute("gen_ai.response.finish_reason",G||"unknown"),g.end()}).catch(()=>{g.end()});let M;const R=this.client,k=[],O=Date.now(),N={};let P=0,D=0,L=0,$=0,U=null;const j=()=>({promptTokens:P,completionTokens:D,totalTokens:P+L+$+D,...L>0?{cacheReadTokens:L}:{},...$>0?{cacheCreationTokens:$}:{}});let B="",z;const J=(G,K)=>{const Ce=be=>{if(typeof be=="string")return be;try{return JSON.stringify(be)??""}catch{return""}};return pr(Ce(G),"anthropic")+pr(Ce(K),"anthropic")},ie=(async()=>{let G,K;const ge=kX({client:R,maxSteps:y,toolsRecord:i,buildParams:ne=>{if(a){const pe=new Set(a.map(Z=>Z.name)),X=Object.fromEntries(Object.entries(i).filter(([Z])=>!pe.has(Z)));if(Object.keys(X).length>0){const Z=B0(X,"input_schema");Z&&Z.length>0&&(a=[...a,...Z])}}const Fe=Jkt({system:l.system,tools:a,messages:ne}),ae=Ykt(ne,PO-Fe),oe=eu("anthropic",d,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream");return{model:d,messages:ae,max_tokens:QD(d,e.maxTokens),...l.system?{system:l.system}:{},...oe.temperature!==void 0?{temperature:oe.temperature}:{},...a&&a.length>0?{tools:a}:{},...m?{tool_choice:m}:{},...h?{thinking:h}:{}}},planReclaim:ne=>{const Fe=Wkt({conversation:ne,availableInputTokens:ou("anthropic",d,e.maxTokens??void 0),fixedOverheadTokens:J(l.system,a),provider:"anthropic",observedPromptTokens:G,previousSentEstimate:K,onSentEstimate:X=>{K=X}});if(!Fe)return;const ae=new Set(Fe.drop),oe=new Set(Fe.truncate),pe=[];for(let X=0;X<ne.length;X++){if(ae.has(X))continue;const Z=ne[X];if(oe.has(X)&&Array.isArray(Z.content)){pe.push({...Z,content:Z.content.map(_e=>_e.type==="tool_result"?{..._e,content:Vkt(typeof _e.content=="string"?_e.content:JSON.stringify(_e.content)??"")}:_e)});continue}pe.push(Z)}if(ae.size>0){let X=pe.findIndex(Z=>Array.isArray(Z.content)&&Z.content.some(_e=>_e.type==="tool_use"||_e.type==="tool_result"));X<0&&(X=Math.min(1,pe.length)),pe.splice(X,0,{role:"user",content:[{type:"text",text:CX}]})}return{conversation:pe}},noteObservedPromptTokens:ne=>{G=ne},...u?{finalResultToolName:QC,onTerminalResult:ne=>{z=ne,f.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:ne.length})}}:{}}),H={...ge,buildToolResultMessages:(ne,Fe,ae,oe)=>{for(const Z of ae)k.push(Z.name);const pe=ae.map(Z=>({type:"tool-call",toolCallId:Z.id,toolName:Z.name,args:Z.args})),X=ae.map(Z=>Z.error?{type:"tool-result",toolCallId:Z.id,toolName:Z.name,error:Z.error}:{type:"tool-result",toolCallId:Z.id,toolName:Z.name,result:Z.output});return zV(v,X.map(Z=>({toolName:Z.toolName,result:"result"in Z?Z.result:void 0,error:"error"in Z?Z.error:void 0}))),this.handleToolExecutionStorage(pe,X,e,new Date).catch(Z=>{f.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:Z instanceof Error?Z.message:String(Z)})}),ge.buildToolResultMessages(ne,Fe,ae,oe)}},se={};for(const[ne,Fe]of Object.entries(i)){const ae=Fe.execute;ae&&(se[ne]={execute:async(oe,pe)=>{const X=pe;return ae(oe,{toolCallId:X.toolCallId??"",...X.abortSignal?{abortSignal:X.abortSignal}:{},messages:[]})}})}const ye=vt.getActiveSpan(),{stream:Q,resultPromise:me}=sp(H,l.messages.slice(),{tools:se,...s?{abortSignal:s}:{},...ye?{span:ye}:{}}),$e=(async()=>{for await(const ne of Q)ne.reasoning&&b({content:"",reasoning:ne.reasoning}),ne.content&&(u?B+=ne.content:b({content:ne.content}))})();let Se;try{Se=await me}catch(ne){throw await ag($e,"Anthropic"),ne}await $e,P+=Se.usage.inputTokens,D+=Se.usage.outputTokens,L+=Se.usage.cacheReadTokens??0,$+=Se.usage.cacheWriteTokens??0,U=Se.rawStopReason??U,N.finishReason=Se.finishReason,Se.rawStopReason&&(N.rawFinishReason=Se.rawStopReason),Se.finishReason==="tool-calls"&&z===void 0&&(N.stopReason="step-cap"),A(j()),I(U??"stop")})().catch(G=>{throw M=G,f.error("Anthropic: Stream error",{error:G instanceof Error?G.message:String(G)}),A(j()),I("error"),this.formatProviderError(G)}).finally(()=>{if(u){const G=z??B;G.length>0&&b({content:G})}n?.cleanup(),_.close()});ie.catch(()=>{});const ce=this.providerName;return{stream:async function*(){let G=0;try{for await(const K of _.iterable)"content"in K&&typeof K.content=="string"&&K.content.length>0&&G++,yield K;if(await ie,G===0&&k.length===0){f.warn(`${ce}: Stream produced no output \u2014 emitting enriched sentinel`);const K=new ac({message:"Stream produced no output"}),Ce=await rg(K,void 0,M);ng(Ce),yield Ce}}catch(K){const Ce=await rg(K,void 0,M);if(ng(Ce),yield Ce,!ac.isInstance(K))throw K}finally{o.signal.aborted||o.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],metadata:N,analytics:x.then(async()=>{const G=await vY.createAnalytics(this.providerName,d,{textStream:(async function*(){})(),usage:T,finishReason:x},Date.now()-O,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),K=G2r();return K&&G&&(this.recordLimitSnapshot(K),G.limits=K),G})}}async isAvailable(){try{return DX()||PX(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),pAt={};he(pAt,{ANTHROPIC_BETA_HEADERS:()=>$O,AnthropicProvider:()=>dAt,ModelAccessError:()=>i3,getModelCapabilities:()=>TX,getRecommendedModelForTier:()=>bX,isModelAvailableForTier:()=>wX});var i$r=S({"src/lib/providers/anthropic/index.ts"(){"use strict";s$r(),iAt()}}),Sg,li,a$r,l$r,mAt,hAt,fAt,tx,gAt,c$r,u$r,d$r,p$r,m$r,h$r,f$r,g$r,y$r,v$r,_$r,w$r,b$r,T$r,E$r,S$r,C$r,x$r,k$r,A$r,I$r,R$r,M$r,P$r,D$r,O$r,N$r,L$r,$$r,F$r,U$r,B$r,z$r,j$r,q$r,G$r,H$r,V$r,W$r,yAt=S({"npm-stub:@aws-sdk/client-bedrock-runtime"(){Sg={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Sg.get}):new Proxy(function(...r){return new Proxy({},{get:Sg.get})},{get:Sg.get,apply(r,n,o){return new Proxy({},{get:Sg.get})},construct(r,n){return new Proxy({},{get:Sg.get})}})}},li=new Proxy({},Sg),{BedrockClient:a$r,ListFoundationModelsCommand:l$r,BedrockRuntimeClient:mAt,ConverseCommand:hAt,ConverseStreamCommand:fAt,ImageFormat:tx,InvokeModelCommand:gAt}=li,{SageMakerRuntimeClient:c$r,InvokeEndpointCommand:u$r,InvokeEndpointWithResponseStreamCommand:d$r}=li,{GoogleAuth:p$r,VertexAI:m$r,TextToSpeechClient:h$r}=li,{Webhook:f$r}=li,{Hippocampus:g$r,HippocampusConfig:y$r}=li,{createClient:v$r}=li,{Queue:_$r,Worker:w$r,Job:b$r,QueueScheduler:T$r,FlowProducer:E$r}=li,{Cron:S$r}=li,{parseBuffer:C$r,selectCover:x$r}=li,{extractRawText:k$r,convertToHtml:A$r}=li,{Hono:I$r}=li,{cors:R$r,HTTPException:M$r,logger:P$r,secureHeaders:D$r,streamSSE:O$r,timeout:N$r}=li,L$r=globalThis.fetch,$$r=globalThis.Request,F$r=globalThis.Response,U$r=globalThis.Headers,B$r=globalThis.FormData,z$r=globalThis.File,j$r=globalThis.Blob,q$r=li.Agent,G$r=li.Pool,H$r=li.Client,V$r=li.Dispatcher,W$r=li.MockAgent}});function K$r(e){if(/^(us|ca)-/.test(e))return"us";if(/^(eu|il|me|af)-/.test(e))return"eu";if(/^ap-northeast-[13]$/.test(e))return"jp";if(/^ap-southeast-[246]$/.test(e))return"au";if(/^ap-/.test(e))return"apac"}function J$r(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function vAt(e){if(typeof e!="object"||e===null)return!1;const t=e,r=typeof t.name=="string"?t.name:"",n=typeof t.message=="string"?t.message:"";return!/ValidationException/i.test(r)&&!/ValidationException/i.test(n)?!1:/inference profile/i.test(n)&&/on-demand throughput/i.test(n)}function Y$r(e,t){if(e.startsWith("arn:")||J$r(e))return[];const r=[],n=K$r(t);return n&&r.push(`${n}.${e}`),r.push(`${bAt}.${e}`),r}function _At(e,t){return`${e}::${t}`}function Z$r(e,t){return $X.get(_At(t,e))}function X$r(e,t,r){$X.set(_At(t,e),r),f.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function wAt(e,t,r){const n=Z$r(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!vAt(o))throw o;const s=Y$r(e,t);if(s.length===0)throw o;f.warn("[Bedrock] Model requires a cross-region inference profile in this region; retrying with a prefixed id",{region:t,candidates:s.length});for(const i of s)try{const a=await r(i);return X$r(e,t,i),a}catch(a){if(!vAt(a))throw a}throw o}}var bAt,$X,Q$r=S({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";q(),bAt="global",$X=new Map}});function FO(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function TAt(e,t){if(e){if(e.toolUse&&e._inputBuffer){try{e.toolUse.input=JSON.parse(e._inputBuffer)}catch{e.toolUse.input={}}delete e._inputBuffer}t&&!e.toolUse&&(e.text=t)}}function EAt(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??FO(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function eFr(e,t,r){const n=[],o=new Map,s=new Map,i=g=>{let y=o.get(g);return y||(y={},o.set(g,y),n.push(y)),y};let a="",l,c=0,u=0,d=0,m=0;if(e.stream)for await(const g of e.stream){if(r.aborted)break;const y=g;if(y.contentBlockStart&&i(y.contentBlockStart.contentBlockIndex??0),y.contentBlockDelta?.delta?.text){const v=y.contentBlockDelta.contentBlockIndex??0,_=y.contentBlockDelta.delta.text;i(v),a+=_,s.set(v,(s.get(v)??"")+_),t.push({content:_})}if(y.contentBlockStart?.start?.toolUse){const v=i(y.contentBlockStart.contentBlockIndex??0);v.toolUse={name:y.contentBlockStart.start.toolUse.name??"",input:{},toolUseId:y.contentBlockStart.start.toolUse.toolUseId??FO()}}if(y.contentBlockDelta?.delta?.toolUse){const v=i(y.contentBlockDelta.contentBlockIndex??0);v.toolUse??={name:"",input:{},toolUseId:FO()};const _=y.contentBlockDelta.delta.toolUse.input;typeof _=="string"?v._inputBuffer=(v._inputBuffer??"")+_:typeof _=="object"&&_!==null&&!Array.isArray(_)&&(v.toolUse.input={...v.toolUse.input??{},..._})}if(y.contentBlockStop){const v=y.contentBlockStop.contentBlockIndex??0;TAt(o.get(v),s.get(v)??"")}if(y.messageStop){l=y.messageStop.stopReason??"end_turn";continue}if(y.metadata?.usage){c+=y.metadata.usage.inputTokens??0,u+=y.metadata.usage.outputTokens??0,d+=y.metadata.usage.cacheReadInputTokens??0,m+=y.metadata.usage.cacheWriteInputTokens??0;break}}for(const[g,y]of o)TAt(y,s.get(g)??"");const h=n.filter(g=>g.text||g.toolUse||g.image||g.document);return{text:a,toolCalls:EAt(h),usage:{inputTokens:c,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:m},rawStopReason:l,raw:h}}function tFr(e){const t=[];let r="";for(const n of e.output?.message?.content??[]){const o={};"text"in n&&n.text&&(o.text=n.text,r+=r?` ${n.text}`:n.text),"toolUse"in n&&n.toolUse&&(o.toolUse={toolUseId:n.toolUse.toolUseId??FO(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:EAt(t),usage:{inputTokens:e.usage?.inputTokens??0,outputTokens:e.usage?.outputTokens??0,cacheReadTokens:e.usage?.cacheReadInputTokens??0,cacheWriteTokens:e.usage?.cacheWriteInputTokens??0},rawStopReason:e.stopReason,raw:t}}function SAt(e){return{providerLabel:"bedrock",maxSteps:e.maxSteps,buildStepRequest(t,r){return{raw:e.buildCommandInput(t,r)}},async executeStep(t,r,n){const o=t.raw;if(!e.streaming){const i=await wAt(o.modelId??"",e.region,a=>Ze(e.client.send(new hAt({...o,modelId:a}),{abortSignal:n}),FX,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return tFr(i)}const s=await wAt(o.modelId??"",e.region,i=>Ze(e.client.send(new fAt({...o,modelId:i}),{abortSignal:n}),FX,new Error("Bedrock streaming API call timed out")));return eFr(s,r,n)},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw},s={role:"user",content:n.map(i=>({toolResult:{toolUseId:i.id,content:[{text:i.error?`Error executing tool ${i.name}: ${i.error}`:String(typeof i.output=="string"?i.output:JSON.stringify(i.output))}],status:i.error?"error":"success"}}))};return[...t,o,s]},mapFinishReason(t,r){switch(t){case"end_turn":case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return r?"tool-calls":"stop"}}}}var FX,rFr=S({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";yAt(),ct(),Q$r(),FX=12e4}});function CAt(e,t,r){return{input:{text:e.input?.text||"",images:e.input?.images,content:e.input?.content,files:e.input?.files,csvFiles:e.input?.csvFiles,pdfFiles:e.input?.pdfFiles,audioFiles:e.input?.audioFiles,videoFiles:e.input?.videoFiles},csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,systemPrompt:e.systemPrompt,conversationHistory:e.conversationMessages,provider:t,model:r,temperature:e.temperature,maxTokens:e.maxTokens,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,fileRegistry:e.fileRegistry}}var nFr=S({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),UO,xAt=S({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";Cl(),UO=He.provider}}),kAt={};he(kAt,{Agent:()=>gIt,BedrockClient:()=>IAt,BedrockRuntimeClient:()=>MAt,Blob:()=>fIt,Client:()=>vIt,ConverseCommand:()=>PAt,ConverseStreamCommand:()=>DAt,Cron:()=>ZAt,Dispatcher:()=>_It,File:()=>hIt,FlowProducer:()=>YAt,FormData:()=>mIt,GoogleAuth:()=>UAt,HTTPException:()=>oIt,Headers:()=>pIt,Hippocampus:()=>qAt,HippocampusConfig:()=>GAt,Hono:()=>rIt,ImageFormat:()=>OAt,InvokeEndpointCommand:()=>$At,InvokeEndpointWithResponseStreamCommand:()=>FAt,InvokeModelCommand:()=>NAt,Job:()=>KAt,ListFoundationModelsCommand:()=>RAt,MockAgent:()=>TIt,Pool:()=>yIt,Queue:()=>VAt,QueueScheduler:()=>JAt,Request:()=>uIt,Response:()=>dIt,SageMakerRuntimeClient:()=>LAt,TextToSpeechClient:()=>zAt,VertexAI:()=>BAt,Webhook:()=>jAt,Worker:()=>WAt,convertToHtml:()=>tIt,cors:()=>nIt,createClient:()=>HAt,default:()=>AAt,extractRawText:()=>eIt,fetch:()=>cIt,getGlobalDispatcher:()=>bIt,interceptors:()=>EIt,logger:()=>sIt,parseBuffer:()=>XAt,request:()=>SIt,secureHeaders:()=>iIt,selectCover:()=>QAt,setGlobalDispatcher:()=>wIt,streamSSE:()=>aIt,timeout:()=>lIt});var Cg,Ts,AAt,IAt,RAt,MAt,PAt,DAt,OAt,NAt,LAt,$At,FAt,UAt,BAt,zAt,jAt,qAt,GAt,HAt,VAt,WAt,KAt,JAt,YAt,ZAt,XAt,QAt,eIt,tIt,rIt,nIt,oIt,sIt,iIt,aIt,lIt,cIt,uIt,dIt,pIt,mIt,hIt,fIt,gIt,yIt,vIt,_It,wIt,bIt,TIt,EIt,SIt,oFr=S({"npm-stub:@aws-sdk/client-bedrock"(){Cg={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Cg.get}):new Proxy(function(...r){return new Proxy({},{get:Cg.get})},{get:Cg.get,apply(r,n,o){return new Proxy({},{get:Cg.get})},construct(r,n){return new Proxy({},{get:Cg.get})}})}},Ts=new Proxy({},Cg),AAt=Ts,{BedrockClient:IAt,ListFoundationModelsCommand:RAt,BedrockRuntimeClient:MAt,ConverseCommand:PAt,ConverseStreamCommand:DAt,ImageFormat:OAt,InvokeModelCommand:NAt}=Ts,{SageMakerRuntimeClient:LAt,InvokeEndpointCommand:$At,InvokeEndpointWithResponseStreamCommand:FAt}=Ts,{GoogleAuth:UAt,VertexAI:BAt,TextToSpeechClient:zAt}=Ts,{Webhook:jAt}=Ts,{Hippocampus:qAt,HippocampusConfig:GAt}=Ts,{createClient:HAt}=Ts,{Queue:VAt,Worker:WAt,Job:KAt,QueueScheduler:JAt,FlowProducer:YAt}=Ts,{Cron:ZAt}=Ts,{parseBuffer:XAt,selectCover:QAt}=Ts,{extractRawText:eIt,convertToHtml:tIt}=Ts,{Hono:rIt}=Ts,{cors:nIt,HTTPException:oIt,logger:sIt,secureHeaders:iIt,streamSSE:aIt,timeout:lIt}=Ts,cIt=globalThis.fetch,uIt=globalThis.Request,dIt=globalThis.Response,pIt=globalThis.Headers,mIt=globalThis.FormData,hIt=globalThis.File,fIt=globalThis.Blob,gIt=Ts.Agent,yIt=Ts.Pool,vIt=Ts.Client,_It=Ts.Dispatcher,wIt=()=>{},bIt=()=>Ts,TIt=Ts.MockAgent,EIt={redirect:()=>e=>e,retry:()=>e=>e},SIt=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}});async function UX(){return await Promise.resolve().then(()=>(oFr(),kAt))}var CIt=S({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}}),xIt,sFr=S({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";yAt(),Lr(),tS(),vc(),Xo(),f4(),rFr(),yt(),xi(),ct(),q(),Im(),DD(),nFr(),Ji(),er(),xAt(),CIt(),xIt=class bcr extends Il{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(t){return t?t.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(t,r,n,o){super(t,"bedrock",r);const s=t||process.env.BEDROCK_MODEL||this.modelName,i=bcr.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",f.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),f.debug(`[AmazonBedrockProvider] Environment check: AWS_REGION=${process.env.AWS_REGION||"undefined"}, AWS_ACCESS_KEY_ID=${process.env.AWS_ACCESS_KEY_ID?"SET":"undefined"}, AWS_SECRET_ACCESS_KEY=${process.env.AWS_SECRET_ACCESS_KEY?"SET":"undefined"}`);try{f.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new mAt({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),f.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw f.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){const{BedrockClient:t,ListFoundationModelsCommand:r}=await UX(),n=new t({region:this.region});try{f.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");const o=new r({}),s=Date.now();await n.send(o);const i=Date.now()-s;f.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){const s=o instanceof Error?o.message:String(o);f.error("[AmazonBedrockProvider] Health check FAILED - this will cause production failures:",{error:s,errorType:o instanceof Error?o.constructor.name:"Unknown",region:process.env.AWS_REGION||"us-east-1",hasAccessKey:!!process.env.AWS_ACCESS_KEY_ID,hasSecretKey:!!process.env.AWS_SECRET_ACCESS_KEY})}finally{try{n.destroy()}catch{}}}getAISDKModel(){throw new Error("AmazonBedrockProvider does not use AI SDK models")}getProviderName(){return"bedrock"}getDefaultModel(){return process.env.BEDROCK_MODEL||"anthropic.claude-sonnet-4-6"}getDefaultEmbeddingModel(){return process.env.BEDROCK_EMBEDDING_MODEL||process.env.AWS_EMBEDDING_MODEL||"amazon.titan-embed-text-v2:0"}async generate(t){f.debug("[AmazonBedrockProvider] generate() called with conversation management");const r=Date.now(),n=typeof t=="string"?{prompt:t}:t;this.conversationHistory=[];const o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){f.debug("[AmazonBedrockProvider] Detected multimodal input in generate(), using multimodal message builder",{hasImages:!!o?.images?.length,imageCount:o?.images?.length||0,hasContent:!!o?.content?.length,contentCount:o?.content?.length||0,hasFiles:!!o?.files?.length,fileCount:o?.files?.length||0,hasCSVFiles:!!o?.csvFiles?.length,csvFileCount:o?.csvFiles?.length||0,hasPDFFiles:!!o?.pdfFiles?.length,pdfFileCount:o?.pdfFiles?.length||0});const m=CAt(n,this.providerName,this.modelName),h=await RD(m,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(h)}else{f.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const d={role:"user",content:[{text:n.prompt}]};this.conversationHistory.push(d)}f.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let i,a,l,c;try{({text:i,usage:a,finishReason:l,rawFinishReason:c}=await this.conversationLoop(n))}catch(d){const m=this.neurolink?.getEventEmitter();throw m&&m.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:"error"},success:!1,error:d instanceof Error?d.message:String(d)}),d}const u=this.neurolink?.getEventEmitter();return u&&u.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:l},success:!0}),{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),...l!==void 0&&{finishReason:l},...c!==void 0&&{rawFinishReason:c}}}async conversationLoop(t){const r=t.maxSteps||ki,n=await this.resolveTurnTools(t.tools,t.disableTools),o=this.formatToolsForBedrock(n),s=eu(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converse"),i=SAt({client:this.bedrockClient,streaming:!1,region:this.region,maxSteps:r,buildCommandInput:a=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(a),system:[{text:t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:t.maxTokens,...s.temperature!==void 0&&{temperature:s.temperature}},...o?{toolConfig:o}:{}})});try{const{resultPromise:a}=sp(i,this.conversationHistory,{tools:this.toEngineTools(n),abortSignal:t.abortSignal}),l=await a;this.conversationHistory=l.conversation;const c=l.usage.inputTokens,u=l.usage.outputTokens,d=l.usage.cacheReadTokens??0,m=l.usage.cacheWriteTokens??0;return{text:l.text||"",usage:{input:c,output:u,total:c+d+m+u,...d>0&&{cacheReadTokens:d},...m>0&&{cacheCreationTokens:m}},finishReason:l.finishReason,rawFinishReason:l.rawStopReason}}catch(a){throw f.error("[AmazonBedrockProvider] Error in conversation loop:",a),this.handleProviderError(a)}}convertToAWSMessages(t){return t.map(r=>({role:r.role,content:r.content.map(n=>n.text?{text:n.text}:n.image?{image:n.image}:n.document?{document:n.document}:n.toolUse?{toolUse:{toolUseId:n.toolUse.toolUseId,name:n.toolUse.name,input:n.toolUse.input}}:n.toolResult?{toolResult:{toolUseId:n.toolResult.toolUseId,content:n.toolResult.content,status:n.toolResult.status}}:{text:""})}))}async executeSingleTool(t,r,n,o){return UO.startActiveSpan("bedrock.tool.execute",{kind:Br.CLIENT,attributes:{"gen_ai.tool.name":r,"gen_ai.system":"aws.bedrock"}},async s=>{try{if(f.debug(`[AmazonBedrockProvider] Executing single tool: ${r}`,{args:n}),!t[r])throw new Error(`Tool not found: ${r}`);const i=t[r];if(!i||!i.execute)throw new Error(`Tool ${r} does not have execute method`);const a=n||{};r==="list_directory"&&!a.path&&(a.path=".",f.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),f.debug("[AmazonBedrockProvider] Tool input parameters:",a);const l={};for(const[d,m]of Object.entries(a))(m===null||typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="object"&&m!==null)&&(l[d]=m);const c=await i.execute(l);f.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:r,result:c});let u;if(c&&typeof c=="object"&&"success"in c)if(c.success&&c.data!==void 0)typeof c.data=="string"?u=c.data:typeof c.data=="object"?u=JSON.stringify(c.data,null,2):u=String(c.data);else if(c.error){const d=typeof c.error=="string"?c.error:c.error.message||"Tool execution failed";throw new Error(d)}else u="";else typeof c=="string"?u=c:typeof c=="object"?u=JSON.stringify(c,null,2):u=String(c);return s.setStatus({code:qe.OK}),u}catch(i){throw f.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:i}),s.setStatus({code:qe.ERROR,message:i.message}),s.recordException(i),i}finally{s.end()}})}async resolveTurnTools(t,r){if(r)return{};const n=t??await this.getAllTools();return this.convertAISDKToolsToToolDefinitions(n)}toEngineTools(t){const r={};for(const n of Object.keys(t))r[n]={execute:o=>this.executeSingleTool(t,n,o)};return r}convertAISDKToolsToToolDefinitions(t){const r={};for(const[n,o]of Object.entries(t))if("description"in o&&o.description){const i=o.parameters??o.inputSchema;r[n]={description:o.description,parameters:i,execute:async a=>{if("execute"in o&&o.execute)return{success:!0,data:await o.execute(a,{toolCallId:`tool_${Date.now()}`,messages:[]})};throw new Error(`Tool ${n} has no execute method`)}}}return r}formatToolsForBedrock(t){if(!t||Object.keys(t).length===0)return null;const r=Object.entries(t).map(([n,o])=>{let s;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?s=js(o.parameters):s=o.parameters:s={type:"object",properties:{},required:[]},(!s.type||s.type!=="object")&&(s={type:"object",properties:s.properties||{},required:s.required||[]}),{toolSpec:{name:n,description:o.description,inputSchema:{json:s}}}});return f.debug(`[AmazonBedrockProvider] Formatted ${r.length} tools for Bedrock`),{tools:r}}convertToBedrockMessages(t){return t.map(r=>{const n={role:r.role==="system"?"user":r.role,content:[]};return typeof r.content=="string"?n.content.push({text:r.content}):r.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){const s=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image;let i=o.mimeType?.split("/")[1]||"png";i==="jpg"&&(i="jpeg"),n.content.push({image:{format:i==="jpeg"?tx.JPEG:i==="png"?tx.PNG:i==="gif"?tx.GIF:tx.WEBP,source:{bytes:s}}})}else if(o.type==="document"||o.type==="pdf"||o.type==="file"&&o.mimeType?.toLowerCase().startsWith("application/pdf")){let s;if(typeof o.data=="string"){const a=o.data.replace(/^data:application\/pdf;base64,/i,"");s=Buffer.from(a,"base64")}else s=o.data;let i=typeof o.name=="string"&&o.name?fm.basename(o.name):"document-pdf";i=i.replace(/\.[^.]+$/,""),i=i.replace(/[^a-zA-Z0-9\s\-()[\]]/g,"-"),i=i.replace(/-+/g,"-").trim().replace(/^-+|-+$/g,""),i=i||"document",n.content.push({document:{format:"pdf",name:i,source:{bytes:s}}})}}),n})}getBedrockClient(){return this.bedrockClient}async executeStream(t){return f.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),f.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),UO.startActiveSpan("bedrock.stream",{kind:Br.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async r=>{try{if(f.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(t.input?.images?.length||t.input?.content?.length||t.input?.files?.length||t.input?.csvFiles?.length||t.input?.pdfFiles?.length)){f.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!t.input?.images?.length,imageCount:t.input?.images?.length||0,hasContent:!!t.input?.content?.length,contentCount:t.input?.content?.length||0,hasFiles:!!t.input?.files?.length,fileCount:t.input?.files?.length||0,hasCSVFiles:!!t.input?.csvFiles?.length,csvFileCount:t.input?.csvFiles?.length||0,hasPDFFiles:!!t.input?.pdfFiles?.length,pdfFileCount:t.input?.pdfFiles?.length||0});const s=CAt(t,this.providerName,this.modelName),i=await RD(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{f.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");const s={role:"user",content:[{text:t.input.text}]};this.conversationHistory.push(s)}f.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),f.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");const o=await this.streamingConversationLoop(t,r);return f.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),r.setStatus({code:qe.OK}),r.end(),o}catch(n){f.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");const o=n,s=o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream");if(f.debug("[TRACE] executeStream CATCH - checking if permission error"),f.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){f.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),f.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),r.addEvent("stream.fallback_to_generate",{reason:o.message});const i=await this.generate({prompt:t.input.text,input:t.input,maxTokens:t.maxTokens,temperature:t.temperature,systemPrompt:t.systemPrompt});if(!i)throw r.setStatus({code:qe.ERROR,message:"Generate method returned null result"}),r.end(),new Error("Generate method returned null result");r.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),r.setStatus({code:qe.OK}),r.end();const a=new ReadableStream({start(c){const d=(i.content||"").split(/(\s+)/);let m="";for(let h=0;h<d.length;h++)m+=d[h],(h===d.length-1||m.length>50||/[.!?;,]\s*$/.test(m))&&m.length>0&&(c.enqueue({content:m}),m="");m.length>0&&c.enqueue({content:m}),c.close()}});return{stream:{async*[Symbol.asyncIterator](){const c=a.getReader();try{for(;;){const{done:u,value:d}=await c.read();if(u)break;yield d}}finally{c.releaseLock()}}},usage:i.usage,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw r.setStatus({code:qe.ERROR,message:o instanceof Error?o.message:String(o)}),r.recordException(o instanceof Error?o:new Error(String(o))),r.end(),n}})}async streamingConversationLoop(t,r){const n=Date.now(),o=t.maxSteps||ki,s=await this.resolveTurnTools(t.tools,t.disableTools),i=this.formatToolsForBedrock(s),a=eu(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converseStream"),l=SAt({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:M=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(M),system:[{text:t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:t.maxTokens,...a.temperature!==void 0&&{temperature:a.temperature}},...i?{toolConfig:i}:{}})});let c=!1,u;const d=new Promise(M=>{u=()=>{c=!0,M()}}),m={...l,executeStep:async(M,R,k)=>{const O=await l.executeStep(M,R,k);return u(),O}};r.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});const{stream:h,resultPromise:g}=sp(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:t.abortSignal}),y=g.then(M=>({result:M,error:void 0}),M=>({result:void 0,error:M}));if(await Promise.race([d,y]),!c){const M=await y;if(M.error)throw M.error}const v=this.neurolink?.getEventEmitter(),_=this,b={startTime:n,streamId:`bedrock-${Date.now()}`};let T;const x=new Promise(M=>{T=M}),A=M=>{const R=M?.inputTokens??0,k=M?.outputTokens??0,O=M?.cacheReadTokens??0,N=M?.cacheWriteTokens??0;return{input:R,output:k,total:R+O+N+k,...O>0&&{cacheReadTokens:O},...N>0&&{cacheCreationTokens:N}}};return y.then(M=>{T(s0(this.providerName,this.modelName||this.getDefaultModel(),{usage:A(M.result?.usage)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let M=!1;try{yield*h}catch(R){throw M=!0,R}finally{const R=await y;R.error&&(M=!0);const k=A(R.result?.usage);R.result&&(_.conversationHistory=R.result.conversation,b.finishReason=R.result.finishReason,b.rawFinishReason=R.result.rawStopReason,r.setAttribute("gen_ai.response.stop_reason",R.result.rawStopReason??"unknown")),v&&v.emit("generation:end",{provider:_.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:k,model:_.modelName||_.getDefaultModel(),provider:_.providerName,finishReason:M?"error":R.result?.rawStopReason},success:!M})}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:x,metadata:b}}async checkBedrockHealth(){const t=new AbortController,r=setTimeout(()=>t.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await UX(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{f.debug("[AmazonBedrockProvider] Starting health check...");const i=new o({}),l=(await s.send(i,{abortSignal:t.signal})).modelSummaries||[],c=l.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(f.debug(`[AmazonBedrockProvider] Health check passed - Found ${c.length} active models out of ${l.length} total models`),c.length===0)throw new Error("No active foundation models available in the region")}catch(i){clearTimeout(r);const a=i;if(qr(i))throw new Error("Bedrock health check timed out after 10 seconds",{cause:i});const l=typeof a.message=="string"?a.message:"";throw l.includes("UnauthorizedOperation")||l.includes("AccessDenied")?new Error("Bedrock access denied. Check your AWS credentials and IAM permissions for bedrock:ListFoundationModels",{cause:i}):a.code==="ECONNREFUSED"||a.code==="ENOTFOUND"?new Error("Unable to connect to Bedrock service. Check your network connectivity and AWS region configuration",{cause:i}):(f.error("[AmazonBedrockProvider] Health check failed:",i),new Error(`Bedrock health check failed: ${l||"Unknown error"}`,{cause:i}))}finally{clearTimeout(r);try{s.destroy()}catch{}}}formatProviderError(t){return Hi(t,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:Pr,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:Ms,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:_t,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:_t,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(t,r){const n=r||"amazon.titan-embed-text-v2:0";f.debug("Generating embedding",{provider:this.providerName,model:n,textLength:t.length});try{const o=JSON.stringify({inputText:t}),s=new gAt({modelId:n,contentType:"application/json",accept:"application/json",body:o}),i=await Ze(this.bedrockClient.send(s),6e4,new Error("Bedrock embedding API call timed out")),a=JSON.parse(new TextDecoder().decode(i.body));if(!a.embedding||!Array.isArray(a.embedding))throw new Error("Invalid embedding response from Bedrock");return f.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.embedding.length}),a.embedding}catch(o){throw f.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:t.length}),this.handleProviderError(o)}}async embedMany(t,r){const n=r||"amazon.titan-embed-text-v2:0";f.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:t.length});try{const o=await Promise.all(t.map(s=>this.embed(s,n)));return f.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw f.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:t.length}),this.handleProviderError(o)}}}}}),kIt={};he(kIt,{AmazonBedrockProvider:()=>xIt,bedrockTracer:()=>UO,loadBedrockControl:()=>UX});var iFr=S({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";sFr(),xAt(),CIt()}}),AIt={};he(AIt,{AzureOpenAIProvider:()=>IIt});var IIt,aFr=S({"src/lib/providers/azureOpenai.ts"(){"use strict";yt(),q(),xi(),us(),Kd(),Ml(),Ym(),IIt=class extends Za{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,r,n){const o=n?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",s=process.env.AZURE_OPENAI_ENDPOINT||"";let i;if(s)try{i=new URL(s.includes("://")?s:`https://${s}`)}catch{i=void 0}const a=i?.hostname??"",l=i?.pathname&&i.pathname!=="/"?i.pathname.replace(/\/+$/,""):"",c=/\.(openai|cognitiveservices)\.azure\.com$/.test(a);let u;c?u="/openai":u=/\/openai(?:\/v\d+)?$/.test(l)?l:`${l}/openai`;const d=i?.origin??"",m=n?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",h=n?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",g=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,y=n?.useMaxCompletionTokens??(g===void 0?void 0:/^(1|true|yes)$/i.test(g));o||Vi(qvr()),d||Vi(Gvr()),super("azure",e,t,{baseURL:d,apiKey:o}),this.azureDeployment=m,this.azureApiVersion=h,this.azureResourceOrigin=d,this.azureDeploymentPathPrefix=u,this.useMaxCompletionTokensOverride=y,f.shouldLog("debug")&&f.debug("Azure OpenAI Provider initialized",FGe({deployment:this.azureDeployment,resourceOrigin:this.azureResourceOrigin,deploymentPathPrefix:this.azureDeploymentPathPrefix,apiVersion:this.azureApiVersion,provider:"azure"}))}suppressResponseFormatWithTools(){return!1}getProviderName(){return"azure"}getDefaultModel(){return this.azureDeployment}formatProviderError(e){const t=[{match:r=>/401/.test(r.message),errorClass:Pr,message:"Invalid Azure OpenAI API key or endpoint."},...ja];return Hi(e,t,"azure",this.modelName)}getChatCompletionsURL(e){const t=e||this.azureDeployment,r=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${r}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){const r=this.useMaxCompletionTokensOverride??ybt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function lFr(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"}var cFr=S({"src/lib/utils/imageDetection.ts"(){"use strict"}});function RIt(e){return e.map(t=>typeof t.content=="string"?{role:t.role,content:t.content}:{role:t.role,content:t.content.map(r=>r.type==="image"||r.type==="document"?{type:r.type,media_type:r.source.media_type,base64_chars:r.source.data.length}:r)})}var uFr=S({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),BO,dFr=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs"(){BO=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}}}),pFr=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs"(){oo()}});function BX(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var zO,zX,MIt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs"(){pFr(),zO=e=>(zO=Array.isArray,zO(e)),zX=zO}});function*mFr(e){if(!e)return;if(jX in e){const{values:n,nulls:o}=e;yield*n.entries();for(const s of o)yield[s,null];return}let t=!1,r;e instanceof Headers?r=e.entries():zX(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){const o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");const s=zX(n[1])?n[1]:[n[1]];let i=!1;for(const a of s)a!==void 0&&(t&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var jX,PIt,hFr=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){MIt(),jX=Symbol.for("brand.privateNullableHeaders"),PIt=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[s,i]of mFr(n)){const a=s.toLowerCase();o.has(a)||(t.delete(s),o.add(a)),i===null?(t.delete(s),r.add(a)):(t.append(s,i),r.delete(a))}}return{[jX]:!0,values:t,nulls:r}}}});function fFr(e){const t=new HC(e);return delete t.batches,t}function gFr(e){const t=new Sa(e);return delete t.messages.batches,t}var DIt,OIt,qX,NIt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){AO(),zSt(),t4(),dFr(),MIt(),hFr(),AO(),DIt="vertex-2023-10-16",OIt=new Set(["/v1/messages","/v1/messages?beta=true"]),qX=class extends Mo{constructor({baseURL:e=BO("ANTHROPIC_VERTEX_BASE_URL"),region:t=BO("CLOUD_ML_REGION")??null,projectId:r=BO("ANTHROPIC_VERTEX_PROJECT_ID")??null,...n}={}){if(!t)throw new Error("No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.");if(!e)switch(t){case"global":e="https://aiplatform.googleapis.com/v1";break;case"us":e="https://aiplatform.us.rep.googleapis.com/v1";break;case"eu":e="https://aiplatform.eu.rep.googleapis.com/v1";break;default:e=`https://${t}-aiplatform.googleapis.com/v1`}if(super({baseURL:e,...n}),this.messages=fFr(this),this.beta=gFr(this),this.region=t,this.projectId=r,this.accessToken=n.accessToken??null,n.authClient&&n.googleAuth)throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");n.authClient?this._authClientPromise=Promise.resolve(n.authClient):(this._auth=n.googleAuth??new xJ({scopes:"https://www.googleapis.com/auth/cloud-platform"}),this._authClientPromise=this._auth.getClient())}validateHeaders(){}async prepareOptions(e){const t=await this._authClientPromise,r=await t.getRequestHeaders(),n=t.projectId??r["x-goog-user-project"];!this.projectId&&n&&(this.projectId=n),e.headers=PIt([r,e.headers])}async buildRequest(e){if(BX(e.body)&&(e.body={...e.body}),BX(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=DIt)),OIt.has(e.path)&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");if(!BX(e.body))throw new Error("Expected request body to be an object for post /v1/messages");const t=e.body.model;e.body.model=void 0;const n=e.body.stream??!1?"streamRawPredict":"rawPredict";e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${t}:${n}`}if(e.path==="/v1/messages/count_tokens"||e.path=="/v1/messages/count_tokens?beta=true"&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`}return super.buildRequest(e)}}}}),GX={};he(GX,{AnthropicVertex:()=>qX,BaseAnthropic:()=>Mo,default:()=>qX});var LIt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){NIt(),NIt()}});async function yFr(){return jO||(jO=await Promise.resolve().then(()=>(LIt(),GX))),jO}function vFr(e){const t=[],r=new Map;let n=0;const o=s=>{const i=`${n}:${s??"x"}`;let a=r.get(i);return a||(a={type:"tool_step",callParts:[],resultParts:[]},r.set(i,a),t.push(a)),a};for(const s of e){if(s.role==="tool_call"){o(s.metadata?.stepIndex).callParts.push({name:s.tool||"unknown",input:s.args||{}});continue}if(s.role==="tool_result"){o(s.metadata?.stepIndex).resultParts.push(s.content&&s.content.length>0?s.content:"(no output)");continue}const i=s.role==="assistant"?"assistant":s.role==="user"?"user":null;!i||!s.content||s.content.trim().length===0||(n++,t.push({type:"regular",role:i,parts:[s.content]}))}return t}function HX(e,t,r){const n=e[e.length-1];n&&n.role===t&&Array.isArray(n.content)?n.content.push(...r):e.push({role:t,content:[...r]})}function _Fr(e,t){const r=e.callParts,n=e.resultParts,o=Math.min(r.length,n.length);(o!==r.length||o!==n.length)&&f.debug("[GoogleVertex] Unbalanced tool step in Claude history replay",{calls:r.length,results:n.length,paired:o});const s=[],i=[];for(let a=0;a<o;a++){const l=`hist_${t}_${a}`;s.push({type:"tool_use",id:l,name:r[a].name,input:r[a].input}),i.push({type:"tool_result",tool_use_id:l,content:n[a]})}return{uses:s,results:i}}function wFr(e){const t=r=>Array.isArray(r.content)&&r.content.length>0&&r.content.every(n=>n.type==="tool_result");for(;e.length>0&&(e[0].role!=="user"||t(e[0]));)e.shift()}function VX(e){const t=[];let r=0;for(const n of vFr(e)){if(n.type==="regular"){HX(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:s}=_Fr(n,r);o.length!==0&&(r++,HX(t,"assistant",o),HX(t,"user",s))}if(wFr(t),f.shouldLog("debug")){const n=t.flatMap(o=>Array.isArray(o.content)?o.content:[]);f.debug("[GoogleVertex] Replayed Claude history with tool turns",{historyMessages:t.length,toolUseBlocks:n.filter(o=>o.type==="tool_use").length,toolResultBlocks:n.filter(o=>o.type==="tool_result").length})}return t}function WX(e,t){const r=e[e.length-1];if(r&&r.role==="user"){const n=Array.isArray(r.content)?r.content:[{type:"text",text:r.content}],o=Array.isArray(t)?t:[{type:"text",text:t}];r.content=[...n,...o];return}e.push({role:"user",content:t})}function oh(e){if(!e||typeof e!="object")return;const t=["additionalProperties","default","$schema","$id","$ref","definitions","$defs","examples","errorMessage"];for(const n of t)n in e&&delete e[n];typeof e.exclusiveMinimum=="boolean"&&(e.exclusiveMinimum===!0&&typeof e.minimum=="number"?(e.exclusiveMinimum=e.minimum,delete e.minimum):delete e.exclusiveMinimum),typeof e.exclusiveMaximum=="boolean"&&(e.exclusiveMaximum===!0&&typeof e.maximum=="number"?(e.exclusiveMaximum=e.maximum,delete e.maximum):delete e.exclusiveMaximum);const r=2147483647;if(typeof e.maximum=="number"&&e.maximum>r&&delete e.maximum,typeof e.minimum=="number"&&e.minimum<-r&&delete e.minimum,e.properties&&typeof e.properties=="object")for(const n of Object.values(e.properties))n&&typeof n=="object"&&oh(n);if(e.items&&typeof e.items=="object")if(Array.isArray(e.items))for(const n of e.items)n&&typeof n=="object"&&oh(n);else oh(e.items);for(const n of["allOf","anyOf","oneOf"])if(Array.isArray(e[n]))for(const o of e[n])o&&typeof o=="object"&&oh(o)}function $It(e,t,r){const n=Swt({contents:e,availableInputTokens:ou("vertex",t),provider:"vertex",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=>{if(!("functionResponse"in c))return c;const u=c.functionResponse,d=JSON.stringify(u.response)??"";return d.length<=qIt?c:{functionResponse:{name:u.name,response:{result:BJ(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:jJ}]})}return e.length=0,e.push(...i),!0}function FIt(e,t,r){const n=Wkt({conversation:e,availableInputTokens:ou("vertex",t),fixedOverheadTokens:0,provider:"vertex",observedPromptTokens:r,observedDescribesCurrentPayload:!0});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.content)){i.push({...l,content:l.content.map(c=>{if(c.type!=="tool_result")return c;const u=typeof c.content=="string"?c.content:JSON.stringify(c.content)??"";return{...c,content:Vkt(u)}})});continue}i.push(l)}if(o.size>0){let a=i.findIndex(l=>Array.isArray(l.content)&&l.content.some(c=>c.type==="tool_use"||c.type==="tool_result"));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",content:[{type:"text",text:CX}]})}return e.length=0,e.push(...i),!0}async function UIt(e,t,r={}){const n=[],o=[];let s,i=0,a=0,l=0,c=0;for await(const u of e){r.onProgress?.();const d=u,h=d.candidates?.[0],g=h?.finishReason;typeof g=="string"&&g&&(s=g);const y=h?.content;if(y&&Array.isArray(y.parts))for(const _ of y.parts)n.push(_),typeof _.text=="string"&&_.text.length>0&&t.push({content:_.text});u.functionCalls&&o.push(...u.functionCalls);const v=d.usageMetadata;if(v){if(v.promptTokenCount!==void 0&&v.promptTokenCount>0){r.onUsageDelta?.("input",v.promptTokenCount-i),i=v.promptTokenCount,r.onUsage?.(v.promptTokenCount,v.candidatesTokenCount??0);const _=Math.min(v.cachedContentTokenCount??0,v.promptTokenCount);r.onUsageDelta?.("cacheRead",_-l),l=_}v.candidatesTokenCount!==void 0&&v.candidatesTokenCount>0&&(r.onUsageDelta?.("output",v.candidatesTokenCount-a),a=v.candidatesTokenCount),v.thoughtsTokenCount!==void 0&&v.thoughtsTokenCount>0&&(r.onUsageDelta?.("reasoning",v.thoughtsTokenCount-c),c=v.thoughtsTokenCount)}}return{rawResponseParts:n,stepFunctionCalls:o,...s?{finishReason:s}:{},inputTokens:i,outputTokens:a,...l?{cacheReadTokens:l}:{},...c?{reasoningTokens:c}:{}}}var jO,BIt,qO,rx,KX,m_,xg,zIt,jIt,GO,qIt,JX,bFr=S({"src/lib/providers/googleVertex/client.ts"(){"use strict";gn(),PJ(),Lr(),vc(),pW(),m4(),Lit(),Xo(),sP(),If(),t9(),vr(),no(),yt(),xi(),ct(),Xkt(),tvt(),DD(),q(),MJ(),xwt(),Kkt(),EJ(),cFr(),SJ(),us(),Ji(),uwt(),O0(),Fa(),kwt(),_wt(),f4(),oAt(),YS(),U0(),qJ(),Yu(),lS(),Cl(),er(),uc(),Kd(),bP(),Im(),uFr(),YS(),jO=null,BIt=()=>!0,qO=()=>Vi(Qvr()),rx=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",KX=(e,t)=>{const r=t||rx();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||F7.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},m_=KX,xg=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",zIt=()=>!!(process.env.GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK||process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.GOOGLE_SERVICE_ACCOUNT_KEY||process.env.GOOGLE_AUTH_CLIENT_EMAIL&&process.env.GOOGLE_AUTH_PRIVATE_KEY),jIt=async(e,t,r,n)=>{const o=e||rx();return{projectId:r?r.projectId?.trim()||"express":qO(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},GO=e=>e.toLowerCase().includes("claude"),qIt=2048,JX=class ln extends Il{projectId;location;expressApiKey;baseURL;registeredTools=new Map;toolContext={};static modelConfigCache=new Map;static modelConfigCacheTime=0;static CACHE_DURATION=300*1e3;static MAX_CACHE_SIZE=50;static maxTokensCache=new Map;static maxTokensCacheTime=0;constructor(t,r,n,o,s){super(t,"vertex",n),s&&(s.projectId&&(process.env.GOOGLE_CLOUD_PROJECT=String(s.projectId)),s.location&&(process.env.GOOGLE_CLOUD_LOCATION=String(s.location)),s.apiKey&&(process.env.GOOGLE_API_KEY=String(s.apiKey),!s.projectId&&!s.location&&(this.expressApiKey=String(s.apiKey))),s.baseURL&&(this.baseURL=String(s.baseURL)));const i=!!this.resolveExpressApiKey();i||zIt()||Vi(e0r()),this.projectId=s?.projectId||(i?"":qO()),this.location=o||s?.location||rx(),f.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),f.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return xg()}async getAISDKModel(){throw new Ne({code:Xe.INVALID_CONFIGURATION,message:"GoogleVertexProvider no longer uses @ai-sdk/google-vertex. All models use native SDKs: @google/genai for Gemini, @anthropic-ai/vertex-sdk for Claude.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}validateStreamOptionsOnly(t){this.validateStreamOptions(t)}async preprocessNativeFileInput(t){if(t.input&&jK(t.input),t.input?.files?.length)try{await qK(t,100*1024*1024,this.providerName)}catch(r){f.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${r instanceof Error?r.message:String(r)}`)}await VS(t.input)}async executeStream(t,r){const n=t.model||this.modelName||xg();return QUe({name:"neurolink.provider.stream",tracer:He.provider,attributes:{[Pe.GEN_AI_SYSTEM]:this.providerName,[Pe.GEN_AI_MODEL]:n,[Pe.GEN_AI_OPERATION]:"stream",[Pe.NL_PROVIDER]:this.providerName}},async o=>{const s=Date.now(),i=t.tools||{};await this.preprocessNativeFileInput(t);const l={...await gt({name:"neurolink.message.build",tracer:He.provider,attributes:{[Pe.NL_PROVIDER]:this.providerName,"message.count":1,"message.build.count":1,"message.build.path":"vertex.native.stream"}},async()=>this.processCSVFilesForNativeSDK(t)),tools:i};try{let c;GO(n)?(f.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(i).length}),c=await this.executeNativeAnthropicStream(l)):(f.info("[GoogleVertex] Routing Gemini model to native @google/genai",{model:n,totalToolCount:Object.keys(i).length}),c=await this.executeNativeGemini3Stream(l)),this.attachUsageAndCostAttributes(o,n,c?.usage);const u=this.wrapStreamResultWithLifecycle(t,c,s);return this.emitStreamEnd(n,s,!0,void 0,c.finishReason),u}catch(c){throw this.fireGenerateOnError(t,c,s),this.emitStreamEnd(n,s,!1,c),c}},o=>o.stream,(o,s)=>this.preserveStreamResultAccessors(o,{...o,stream:s}))}emitStreamEnd(t,r,n,o,s){const i=this.neurolink?.getEventEmitter();i&&i.emit("stream:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:t,provider:this.providerName,finishReason:n?s??"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async createVertexGenAIClient(t){Owt("GoogleVertex");const r=this.resolveExpressApiKey(),n=r?"":qO(),o=t||this.location||rx(),i=(await Promise.resolve().then(()=>(pE(),zv))).GoogleGenAI;if(!i)throw new Ne({code:Xe.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const a=i,l=this.resolveBaseURL(),c={...l?{baseUrl:l}:{}};return r?new a({vertexai:!0,apiKey:r,httpOptions:c}):new a({vertexai:!0,project:n,location:o,httpOptions:c})}resolveBaseURL(){const t=this.baseURL?.trim()||process.env.GOOGLE_VERTEX_BASE_URL?.trim();return t&&t.length>0?t:void 0}resolveExpressApiKey(){const t=this.expressApiKey?.trim();if(t)return t;const r=process.env.GOOGLE_VERTEX_API_KEY?.trim();return r?["GOOGLE_CLOUD_PROJECT_ID","VERTEX_PROJECT_ID","GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT"].some(o=>(process.env[o]??"").trim().length>0)?void 0:r:void 0}buildGeminiFunctionDeclaration(t,r){const n={name:t,description:r.description||`Tool: ${t}`},s=r.parameters||r.inputSchema;if(s){const i=js(s,"openApi3"),a=dn(i);a.$schema&&delete a.$schema;const l=Ai(a);oh(l),n.parametersJsonSchema=l}return n}refreshGeminiToolDeclarations(t,r,n,o){if(!t||!r)return;const s=new Set(r.map(i=>i.name));for(const[i,a]of Object.entries(t))s.has(i)||(r.push(this.buildGeminiFunctionDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),f.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Gemini declarations.`))}resolveGeminiToolOnMiss(t,r,n,o,s){if(!n)return;const i=NV(r,t);if(i?.execute)return n.some(a=>a.name===t)||n.push(this.buildGeminiFunctionDeclaration(t,i)),o.set(t,i.execute),s.delete(t),f.info(`[GoogleVertex] Tool "${t}" resolved mid-turn via discovery \u2014 executing.`),o.get(t)}buildAnthropicToolDeclaration(t,r){const n={name:t,description:r.description||`Tool: ${t}`,input_schema:{type:"object"}},s=r.parameters||r.inputSchema;if(s){const i=js(s),a=dn(i);n.input_schema={type:"object",properties:a.properties||{},required:a.required||[]}}return n}refreshAnthropicToolDeclarations(t,r,n,o){if(!t||!r)return;const s=new Set(r.map(i=>i.name));for(const[i,a]of Object.entries(t))s.has(i)||(r.push(this.buildAnthropicToolDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),f.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Anthropic declarations.`))}resolveAnthropicToolOnMiss(t,r,n,o,s){if(!n)return;const i=NV(r,t);if(i?.execute)return n.some(a=>a.name===t)||n.push(this.buildAnthropicToolDeclaration(t,i)),o.set(t,i.execute),s.delete(t),f.info(`[GoogleVertex] Tool "${t}" resolved mid-turn via discovery \u2014 executing.`),o.get(t)}async executeNativeGemini3Stream(t){const r=t.model||this.modelName||xg(),n=m_(r,t.region),o=await this.createVertexGenAIClient(n);f.debug("[GoogleVertex] Using native @google/genai for Gemini 3",{model:r,hasTools:!!t.tools&&Object.keys(t.tools).length>0,project:this.projectId,location:n});const s=[],i=[{text:t.input.text??""}],a=t.input;if(a?.pdfFiles&&a.pdfFiles.length>0){f.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(const ne of a.pdfFiles){let Fe;typeof ne=="string"?Go.existsSync(ne)?Fe=Go.readFileSync(ne):Fe=Buffer.from(ne,"base64"):Fe=ne;const ae=Fe.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:ae}})}}if(await NJ(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){f.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(const ne of a.images){const Fe=RS(ne);let ae,oe="image/jpeg";if(typeof Fe=="string")if(Go.existsSync(Fe)){ae=Go.readFileSync(Fe);const X=OS(Fe);oe=X.startsWith("image/")?X:this.detectImageType(ae)}else if(Fe.startsWith("data:")){const X=Fe.match(/^data:([^;]+);base64,(.+)$/);if(X)oe=X[1],ae=Buffer.from(X[2],"base64");else continue}else if(Fe.startsWith("http://")||Fe.startsWith("https://"))try{const X=await fetch(Fe);if(!X.ok){f.warn(`[GoogleVertex] Image fetch failed: ${X.status} ${X.statusText}, skipping`,{url:un(Fe)});continue}const Z=await X.arrayBuffer();ae=Buffer.from(Z);const _e=X.headers.get("content-type");_e&&_e.startsWith("image/")&&(oe=_e.split(";")[0])}catch(X){f.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${X instanceof Error?X.message:String(X)}`,{url:un(Fe)});continue}else ae=Buffer.from(Fe,"base64"),oe=this.detectImageType(ae);else ae=Fe,oe=this.detectImageType(ae);const pe=ae.toString("base64");i.push({inlineData:{mimeType:oe,data:pe}})}}d4(s,t.conversationMessages),s.push({role:"user",parts:i});let l;const c=new $0;let u;if(t.tools&&Object.keys(t.tools).length>0&&!t.disableTools){const ne=B0(t.tools,"functionDeclarations");u=ne,l=ne.toolsConfig;for(const[Fe,ae]of ne.executeMap)c.set(Fe,ae);f.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ne.toolsConfig[0].functionDeclarations.length,toolNames:ne.toolsConfig[0].functionDeclarations.map(Fe=>Fe.name)})}const d=t;let m=!1;if(d.schema&&l){m=!0;const ne=js(d.schema,"openApi3"),Fe=dn(ne);Fe.$schema&&delete Fe.$schema;const ae=Ai(Fe),oe=l[0]?.functionDeclarations||[];oe.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:ae}),l=[{functionDeclarations:oe}],f.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(ae),totalTools:oe.length})}const h=eu(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),g={...h.temperature!==void 0&&{temperature:h.temperature},maxOutputTokens:t.maxTokens};TJ(r)&&(g.maxOutputTokens&&g.maxOutputTokens>Ka&&(f.warn(`[GoogleVertex] Capping maxOutputTokens from ${g.maxOutputTokens} to ${Ka} for ${r}`),g.maxOutputTokens=Ka),g.maxOutputTokens||(g.maxOutputTokens=Ka)),h.topP!==void 0&&(g.topP=h.topP),t.topK!==void 0&&(g.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(g.stopSequences=t.stopSequences),l&&(g.tools=l);let y=t.systemPrompt||"";m&&(y=y+`
1122
1122
 
1123
1123
  IMPORTANT: When you have gathered all necessary information and are ready to provide your final answer, you MUST call the 'final_result' tool with the structured data. Do not return the final answer as plain text - always use the final_result tool.`),y&&(g.systemInstruction=y);const v=DJ(t.thinkingConfig);if(v&&(g.thinkingConfig=v),(d.output?.format==="json"||d.schema)&&!m&&!l&&(g.responseMimeType="application/json",d.schema)){const ne=js(d.schema,"openApi3"),Fe=dn(ne);Fe.$schema&&delete Fe.$schema;const ae=Ai(Fe);oh(ae),g.responseSchema=ae,f.debug("[GoogleVertex] Added responseSchema for JSON output (stream)",{schemaKeys:Object.keys(ae)})}const _=Date.now(),b=t.maxSteps||ki,T=Number.isFinite(b)&&b>0?Math.min(Math.floor(b),100):Math.min(ki,100),x=[...s];let A="",I;const M=[],R=[];let k;const O=L0(Jd("vertex",r));let N=!1,P=0,D=0,L=0,$=0;const U=[],j=tc(t.timeout)??GE,B=t.toolTimeoutMs??HE,z=t.turnTimeoutMs??j,J=new AbortController,Y=()=>J.abort();t.abortSignal?.addEventListener("abort",Y);const ie=u4({turnTimeoutMs:t.turnTimeoutMs,defaultTurnTimeoutMs:j,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:ne=>{f.warn(ne==="timeout"?`[GoogleVertex] Native Gemini turn exceeded its ${z}ms time budget \u2014 aborting`:`[GoogleVertex] Native Gemini turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),J.abort()}}),ce=J.signal;t.abortSignal?.aborted&&J.abort();let re=!1,G=!1,K=!1,Ce=0;try{const ne=h4({providerLabel:"GoogleVertex",maxSteps:T,toolFailureBreaker:{maxRetries:Cf,consecutive:!0,classifyResultFailure:_e=>GD(_e)??void 0},liveTools:t.tools??{},toolGuards:{toolTimeoutMs:B,abortSignal:ce,onProgress:()=>ie.noteProgress()},...u?{declarations:u}:{},...m?{finalResultToolName:"final_result",onTerminalResult:_e=>{try{k=JSON.parse(_e)}catch{}}}:{},enableMalformedRetry:!0,buildMalformedRetryNote:(_e,Re)=>(this.emitTurnEvent({phase:"malformed-retry",step:Re+1,maxSteps:T}),[..._e,{role:"user",parts:[{text:"Your previous function call was malformed and could not be parsed. Re-issue it as a single valid function call, or answer in plain text."}]}]),collectStep:(_e,Re)=>UIt(_e,Re,{onProgress:()=>ie.noteProgress(),onUsage:(we,Je)=>O.noteUsage(we,Je),onUsageDelta:(we,Je)=>{we==="input"?P+=Je:we==="output"?D+=Je:we==="cacheRead"?L+=Je:$+=Je}}),planReclaim:_e=>{if(!O.shouldStop())return;const Re=[..._e];return $It(Re,r,O.projectedNextPromptTokens)?(O.resetAfterReclaim(),{conversation:Re}):(N=!0,f.warn(`[GoogleVertex] Gemini turn stopped by the context guard: projected prompt ~${O.projectedNextPromptTokens} tokens >= threshold ${O.thresholdTokens} \u2014 synthesizing a final answer.`),{stop:!0})},buildRequest:_e=>({model:r,contents:_e,config:{...g,...l?{tools:l}:{}}}),sendStep:async(_e,Re)=>{ie.noteProgress();const we=_e;return o.models.generateContentStream({model:we.model,contents:we.contents,config:{...we.config??{},abortSignal:Re}})}}),Fe={...ne,buildStepRequest:(_e,Re)=>(Ce=Re+1,ne.buildStepRequest(_e,Re)),buildToolResultMessages:(_e,Re,we,Je)=>{const C=ne.buildToolResultMessages(_e,Re,we,Je);if(ie.shouldNudgeWrapup()){const ve=C[C.length-1];ve&&Array.isArray(ve.parts)&&ve.parts.push({text:l4(m)})}const W=a4(Re.raw.rawResponseParts);zt(this.handleToolExecutionStorage(we.map((ve,Ee)=>({toolName:ve.name,args:ve.args,...Ee===0&&W?{thoughtSignature:W}:{},stepIndex:Je+1})),we.map(ve=>({toolName:ve.name,output:ve.output,stepIndex:Je+1})),t,new Date),xf,"tool storage write timed out").catch(ve=>{f.warn("[GoogleVertex] Failed to store native Gemini stream tool executions",{error:ve instanceof Error?ve.message:String(ve)})});try{const ve=C[C.length-1];O.noteAppendedChars(JSON.stringify(ve?.parts??[]).length)}catch{}return C}},{stream:ae,resultPromise:oe}=sp(Fe,x,{tools:i4(u,t.tools,{toolTimeoutMs:B,abortSignal:ce,onProgress:()=>ie.noteProgress()}),abortSignal:ce}),pe=(async()=>{for await(const _e of ae)_e.content&&U.push(_e.content)})();let X,Z;try{X=await oe}catch(_e){Z=_e}if(await ag(pe,"GoogleVertex"),Z!==void 0)if(ce.aborted||Km(Z))re=!0;else throw f.error("[GoogleVertex] Native SDK error",Z),this.handleProviderError(Z);if(X){A=X.text,I=X.rawStopReason??I;for(const _e of X.toolCalls)M.push({toolName:_e.name,args:_e.args});for(const _e of X.toolExecutions)R.push({name:_e.name,input:_e.input,output:_e.output});x.length=0,x.push(...X.conversation)}if(ce.aborted&&(re=!0),!A&&(Ce>=T||re||N)){G=Ce>=T&&!re;const _e=M.filter(Re=>Re.toolName!=="final_result").length;if(U.length>0)f.warn(N?"[GoogleVertex] Tool call loop stopped by the context guard; returning text already gathered from prior steps.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${T}); returning text already gathered from prior steps.`);else if(re)f.warn(`[GoogleVertex] Tool call loop ended mid-turn (${ie.timedOut?"turn time limit":ie.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),A=this.buildLoopExitMessage({turnClock:ie,wasAborted:re,stallTimeoutMs:t.stallTimeoutMs,maxSteps:T,toolCallCount:_e});else{f.warn(N?"[GoogleVertex] Tool call loop stopped by the context guard with no text; synthesizing a final answer with tools disabled.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${T}) with no text; synthesizing a final answer with tools disabled.`);const Re=await this.synthesizeFinalAnswerWithoutTools(o,r,g,x,m,tc(t.timeout)??GE,ce);Re.text?(K=!0,A=Re.text,U.push(Re.text),P+=Re.inputTokens,D+=Re.outputTokens,$+=Re.reasoningTokens??0,Re.finishReason&&(I=Re.finishReason)):A=N?_c(_e):Jm(T,_e)}}}finally{ie.dispose(),t.abortSignal?.removeEventListener("abort",Y)}const be=G&&!K?"tool-calls":OJ(I),ge=c4({timedOut:ie.timedOut,stalled:ie.stalled,wasAborted:re,cappedWithoutAnswer:G&&!K,contextCappedWithoutAnswer:N&&!K,finishReason:be});ge!=="completed"&&this.emitTurnEvent({phase:ge,step:Ce,maxSteps:T,toolCallCount:M.filter(ne=>ne.toolName!=="final_result").length,elapsedMs:ie.elapsedMs()});const H=Date.now()-_,se=k?[A]:U.length>0?U:[A];async function*ye(){for(const ne of se)ne.length>0&&(yield{content:ne})}const Q=M.filter(ne=>ne.toolName!=="final_result"),me=R.filter(ne=>ne.name!=="final_result"),$e=Math.max(0,P-L),Se={stream:ye(),provider:this.providerName,model:r,finishReason:be,stopReason:ge,rawFinishReason:I,usage:{input:$e,output:D+$,total:$e+L+D+$,...L>0&&{cacheReadTokens:L},...$>0&&{reasoning:$}},toolCalls:Q.map(ne=>({toolName:ne.toolName,args:ne.args})),toolsUsed:Q.map(ne=>ne.toolName),toolExecutions:gP(me),metadata:{streamId:`native-vertex-${Date.now()}`,startTime:_,responseTime:H,totalToolExecutions:Q.length,stopReason:ge,rawFinishReason:I,stepsUsed:Ce}};return k&&(Se.structuredOutput=k),Se}async executeNativeGemini3Generate(t){const r=t.model||this.modelName||xg(),n=m_(r,t.region),o=await this.createVertexGenAIClient(n);f.debug("[GoogleVertex] Using native @google/genai for Gemini 3 generate",{model:r,project:this.projectId,location:n});const s=t.input?.text||t.prompt||"Please respond.",i=[],a=[{text:s}],l=t.input;if(l?.pdfFiles&&l.pdfFiles.length>0){f.debug(`[GoogleVertex] Processing ${l.pdfFiles.length} PDF file(s) for native generate`);for(const Se of l.pdfFiles){let ne;typeof Se=="string"?Go.existsSync(Se)?ne=Go.readFileSync(Se):ne=Buffer.from(Se,"base64"):ne=Se;const Fe=ne.toString("base64");a.push({inlineData:{mimeType:"application/pdf",data:Fe}})}}if(await NJ(a,l?.nativeAudioFiles,"[GoogleVertex]"),l?.images&&l.images.length>0){f.debug(`[GoogleVertex] Processing ${l.images.length} image(s) for native generate`);for(const Se of l.images){const ne=RS(Se);let Fe,ae="image/jpeg";if(typeof ne=="string")if(Go.existsSync(ne)){Fe=Go.readFileSync(ne);const pe=OS(ne);ae=pe.startsWith("image/")?pe:this.detectImageType(Fe)}else if(ne.startsWith("data:")){const pe=ne.match(/^data:([^;]+);base64,(.+)$/);if(pe)ae=pe[1],Fe=Buffer.from(pe[2],"base64");else continue}else if(ne.startsWith("http://")||ne.startsWith("https://"))try{const pe=await fetch(ne);if(!pe.ok){f.warn(`[GoogleVertex] Image fetch failed: ${pe.status} ${pe.statusText}, skipping`,{url:un(ne)});continue}const X=await pe.arrayBuffer();Fe=Buffer.from(X);const Z=pe.headers.get("content-type");Z&&Z.startsWith("image/")&&(ae=Z.split(";")[0])}catch(pe){f.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${pe instanceof Error?pe.message:String(pe)}`,{url:un(ne)});continue}else Fe=Buffer.from(ne,"base64"),ae=this.detectImageType(Fe);else Fe=ne,ae=this.detectImageType(Fe);const oe=Fe.toString("base64");a.push({inlineData:{mimeType:ae,data:oe}})}}d4(i,t.conversationMessages),i.push({role:"user",parts:a});const c=t.disableTools?{}:t.tools||{};let u;const d=new $0;let m;if(Object.keys(c).length>0){const Se=B0(c,"functionDeclarations");m=Se,u=Se.toolsConfig;for(const[ne,Fe]of Se.executeMap)d.set(ne,Fe);f.debug("[GoogleVertex] Converted tools for native SDK generate",{toolCount:Se.toolsConfig[0].functionDeclarations.length,toolNames:Se.toolsConfig[0].functionDeclarations.map(ne=>ne.name)})}let h=!1;if(t.schema&&u){h=!0;const Se=js(t.schema,"openApi3"),ne=dn(Se);ne.$schema&&delete ne.$schema;const Fe=Ai(ne),ae=u[0]?.functionDeclarations||[];ae.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:Fe}),u=[{functionDeclarations:ae}],f.debug("[GoogleVertex] Added final_result tool for structured output with tools (generate)",{schemaKeys:Object.keys(Fe),totalTools:ae.length})}const g=eu(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),y={...g.temperature!==void 0&&{temperature:g.temperature},maxOutputTokens:t.maxTokens};TJ(r)&&(y.maxOutputTokens&&y.maxOutputTokens>Ka&&(f.warn(`[GoogleVertex] Capping maxOutputTokens from ${y.maxOutputTokens} to ${Ka} for ${r}`),y.maxOutputTokens=Ka),y.maxOutputTokens||(y.maxOutputTokens=Ka)),g.topP!==void 0&&(y.topP=g.topP),t.topK!==void 0&&(y.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(y.stopSequences=t.stopSequences),u&&(y.tools=u);let v=t.systemPrompt||"";h&&(v=v+`
1124
1124
 
@@ -146,13 +146,26 @@ async function readSnapshotFile(filePath) {
146
146
  * provider block.
147
147
  */
148
148
  async function resolveOpenCodeSnapshot(inFileLegacy) {
149
+ // An in-file legacy record outranks everything, because its presence means
150
+ // more than "here is a snapshot": the config still carries `__proxy_*` keys,
151
+ // so the previous migration did not complete. That record is the only one
152
+ // that predates the proxy, and on a migration run it is guaranteed to
153
+ // disagree with a scoped snapshot — the old writer's block has `models: {}`
154
+ // while the new writer's `written` carries the full map, so valuesMatch() is
155
+ // always false and shouldCaptureSnapshot() re-captures. Re-capturing there
156
+ // adopts the proxy's OWN block as the user's "original" and discards the
157
+ // real one, silently and permanently.
158
+ //
159
+ // Reachable whenever apply() wrote the scoped snapshot and then failed to
160
+ // write opencode.json: applyAllClients() catches per-client errors, so the
161
+ // retry runs against a config still holding the legacy keys.
162
+ if (inFileLegacy !== null) {
163
+ return { snapshot: inFileLegacy, source: "in-file" };
164
+ }
149
165
  const scoped = await readSnapshotFile(getOpenCodeSnapshotPath());
150
166
  if (scoped !== null) {
151
167
  return { snapshot: scoped, source: "scoped" };
152
168
  }
153
- if (inFileLegacy !== null) {
154
- return { snapshot: inFileLegacy, source: "in-file" };
155
- }
156
169
  const unscoped = await readSnapshotFile(getLegacyOpenCodeSnapshotPath());
157
170
  return unscoped === null
158
171
  ? { snapshot: null, source: null }
@@ -223,7 +223,15 @@ export function createBedrockLoopAdapter(config) {
223
223
  const response = await withInferenceProfileFallback(commandInput.modelId ?? "", config.region, (effectiveModelId) => withTimeout(config.client.send(new ConverseCommand({
224
224
  ...commandInput,
225
225
  modelId: effectiveModelId,
226
- })), STEP_TIMEOUT_MS, new Error("Bedrock API call timed out")));
226
+ }),
227
+ // Hand the signal to the transport, not just to the loop.
228
+ // `abortSignal` is documented public API, and loopEngine
229
+ // already honours it — but only *between* steps. Without this
230
+ // the HTTP request stays in flight after an abort until it
231
+ // answers or STEP_TIMEOUT_MS (120s) elapses, because nothing
232
+ // ever told the socket. `@smithy/types` HttpHandlerOptions
233
+ // takes the same AbortSignal the adapter is already given.
234
+ { abortSignal: signal }), STEP_TIMEOUT_MS, new Error("Bedrock API call timed out")));
227
235
  if (!response.output?.message) {
228
236
  throw new Error("Invalid response structure from Bedrock API");
229
237
  }
@@ -232,7 +240,11 @@ export function createBedrockLoopAdapter(config) {
232
240
  const response = await withInferenceProfileFallback(commandInput.modelId ?? "", config.region, (effectiveModelId) => withTimeout(config.client.send(new ConverseStreamCommand({
233
241
  ...commandInput,
234
242
  modelId: effectiveModelId,
235
- })), STEP_TIMEOUT_MS, new Error("Bedrock streaming API call timed out")));
243
+ }),
244
+ // As above: the streaming send needs the signal too, so an
245
+ // abort tears down the eventstream connection rather than
246
+ // leaving it open for the rest of the step budget.
247
+ { abortSignal: signal }), STEP_TIMEOUT_MS, new Error("Bedrock streaming API call timed out")));
236
248
  return readStreamedStep(response, channel, signal);
237
249
  },
238
250
  buildToolResultMessages(conversation, stepResult, toolResults) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "12.5.1",
3
+ "version": "12.5.3",
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": {