@juspay/neurolink 11.15.9 → 11.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
## [11.
|
|
1
|
+
## [11.16.0](https://github.com/juspay/neurolink/compare/v11.15.9...v11.16.0) (2026-08-22)
|
|
2
|
+
|
|
3
|
+
### Features
|
|
4
|
+
|
|
5
|
+
- **(googleVertex):** reach Claude models with an API key and a base URL ([df52026](https://github.com/juspay/neurolink/commit/df520265bbeb3865a520e62abcd3cdf7187d27eb))
|
|
2
6
|
|
|
3
7
|
## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
|
|
4
8
|
|
|
@@ -1126,13 +1126,13 @@ ${r[0].text}`;const n=r.length-1;r[n].text=`${r[n].text}
|
|
|
1126
1126
|
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 wkr(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 Tkr(e){return{providerLabel:"anthropic",maxSteps:e.maxSteps,...e.toolFailureBreaker?{toolFailureBreaker:e.toolFailureBreaker}:{},...e.planReclaim?{planReclaim:(t,r)=>{const n=e.planReclaim?.(t,r);return n?{conversation:n}:void 0}}:{},resolveToolOnMiss:t=>{const n=dH(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,f=0,g=0,y=0,v=0,w=0;for await(const A of s){if(n.aborted)break;const M=A;if(M.type==="message_start"){const N=M.message?.usage;f+=N?.input_tokens??0;const O=N?.output_tokens??0;g+=O-w,w=O,y+=N?.cache_read_input_tokens??0,v+=N?.cache_creation_input_tokens??0,e.noteObservedPromptTokens?.((N?.input_tokens??0)+(N?.cache_read_input_tokens??0)+(N?.cache_creation_input_tokens??0));continue}if(M.type==="content_block_start"){const N=M.index??0;if(M.content_block?.type==="redacted_thinking"){const O=M.content_block.data;typeof O=="string"&&c.set(N,O)}M.content_block?.type==="tool_use"&&a.set(N,{id:M.content_block.id??"",name:M.content_block.name??"",inputJson:""});continue}if(M.type==="content_block_delta"){const N=M.index??0,O=M.delta;if(O?.type==="text_delta"&&O.text)u+=O.text,i.set(N,(i.get(N)??"")+O.text),r.push({content:O.text});else if(O?.type==="thinking_delta"&&O.thinking){const D=l.get(N)??{text:"",signature:""};D.text+=O.thinking,l.set(N,D),d+=O.thinking,r.push({content:"",reasoning:O.thinking})}else if(O?.type==="signature_delta"&&O.signature){const D=l.get(N)??{text:"",signature:""};D.signature+=O.signature,l.set(N,D)}else if(O?.type==="input_json_delta"&&O.partial_json){const D=a.get(N);D&&(D.inputJson+=O.partial_json)}continue}if(M.type==="message_delta"){m=M.delta?.stop_reason??m;const N=M.usage?.output_tokens??w;g+=N-w,w=N}}const b=A=>{if(!A)return{};try{const M=JSON.parse(A);return typeof M=="object"&&M!==null&&!Array.isArray(M)?M:{}}catch{return{}}},T=[],x=new Set([...i.keys(),...a.keys(),...l.keys(),...c.keys()]);for(const A of[...x].sort((M,N)=>M-N)){const M=c.get(A);M&&T.push({type:"redacted_thinking",data:M});const N=l.get(A);N?.text&&N.signature&&T.push({type:"thinking",thinking:N.text,signature:N.signature});const O=i.get(A);O&&T.push({type:"text",text:O});const D=a.get(A);D&&T.push({type:"tool_use",id:D.id,name:D.name,input:b(D.inputJson)})}const k=[...a.values()].map(A=>({id:A.id,name:A.name,args:b(A.inputJson)})),I=e.finalResultToolName?[...a.values()].find(A=>A.name===e.finalResultToolName):void 0,R=I?[]:k,P=I?_kr(I.inputJson):u;return I&&e.onTerminalResult?.(P),{text:P,...d?{reasoning:d}:{},toolCalls:R,usage:{inputTokens:f,outputTokens:g,cacheReadTokens:y,cacheWriteTokens:v},rawStopReason:m,raw:T}},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw},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}`:rY(i.output),...i.error?{is_error:!0}:{}}))};return[...t,o,s]},mapFinishReason:wkr}}var bkr=C({"src/lib/providers/anthropic/loopAdapter.ts"(){"use strict";G1(),Gbt(),Kbt()}});function nY(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 oO(e,t){if(e instanceof ArrayBuffer)return oO(new Uint8Array(e),t);if(e instanceof Uint8Array)return{type:"image",source:{type:"base64",media_type:sO(t)??nY(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=sO(n[1])??sY(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:sO(t)??sY(r)??"image/png",data:r}}}function Ekr(e){const t=e?.data;if(t==null)return;const r=typeof e.mediaType=="string"?e.mediaType.toLowerCase().split(";")[0].trim():"";if(oY.has(r)||r==="image/jpg")return oO(t,r);if(r==="application/pdf")return iY(t);const n=t instanceof ArrayBuffer?new Uint8Array(t):t instanceof Uint8Array?t:void 0;if(n&&nY(n))return oO(n)}var oY,sO,Jbt,sY,iY,Skr=C({"src/lib/providers/anthropicImageBlocks.ts"(){"use strict";oY=new Set(["image/jpeg","image/png","image/gif","image/webp"]),sO=e=>{if(!e)return;const t=e.toLowerCase().split(";")[0].trim();return t==="image/jpg"?"image/jpeg":oY.has(t)?t:void 0},Jbt=32,sY=e=>{try{return nY(Buffer.from(e.slice(0,Jbt),"base64"))}catch{return}},iY=e=>{if(e instanceof ArrayBuffer)return iY(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}}}}}}),iO,Ybt=C({"src/lib/providers/anthropic/constants.ts"(){"use strict";iO={"anthropic-beta":["claude-code-20250219","fine-grained-tool-streaming-2025-05-14"].join(",")}}}),aY,CS,Zbt,lY,Xbt,Qbt,cY,uY,eEt,dY,tEt,Ckr=C({"src/lib/providers/anthropic/client.ts"(){"use strict";z_t(),Xt(),Wn(),fd(),Xr(),bS(),T$(),tc(),$o(),_yt(),xbt(),nkr(),Zn(),mkr(),Ct(),_i(),V(),Ubt(),Ru(),Xs(),kr(),qbt(),Bc(),Gbt(),bkr(),UM(),jo(),Ra(),Tyt(),vH(),vd(),M9(),ji(),Q9(),Skr(),em(),Tm(),Vv(),wW(),Ybt(),bgt(),Kbt(),xbt(),aY=()=>Pi(tQt()),CS=()=>Mi("ANTHROPIC_MODEL","claude-sonnet-4-6"),Zbt=vt.getTracer("neurolink.provider.anthropic"),lY=()=>{try{const t=jr(xh(),".neurolink","anthropic-credentials.json");if(As(t)){const r=hd(t,"utf-8"),n=JSON.parse(r);if(n.type==="oauth"&&n.oauth?.accessToken)return h.debug("[AnthropicProvider] Using OAuth token from stored credentials file"),n.oauth}}catch(t){h.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}},Xbt=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 h.debug("[detectSubscriptionTier] Using environment override",{tier:t}),t;h.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"),h.debug("[detectSubscriptionTier] Detected from OAuth token",{tier:n,scopes:r}),n}return h.debug("[detectSubscriptionTier] No OAuth token, defaulting to API tier"),"api"},Qbt=e=>{const t=process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase();if(t==="api_key"||t==="apikey")return h.debug("[detectAuthMethod] Forced to api_key by ANTHROPIC_AUTH_METHOD env var"),"api_key";if(t==="oauth"){if(e)return h.debug("[detectAuthMethod] Forced to oauth by ANTHROPIC_AUTH_METHOD env var"),"oauth";h.warn("[detectAuthMethod] ANTHROPIC_AUTH_METHOD=oauth but no OAuth token found; falling through to auto-detection")}else t&&h.warn("[detectAuthMethod] Unrecognized ANTHROPIC_AUTH_METHOD value; falling through to auto-detection",{value:t});const r=e?"oauth":"api_key";return h.debug("[detectAuthMethod] Auth method resolved",{method:r,hasOAuthToken:!!e}),r},cY=e=>{const t=[],r=[],n=i=>Array.isArray(i)?i:[i],o=(i,a)=>{const l=Dd(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(`
|
|
1127
1127
|
`),l=Dd(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=Dd(c);a.push({type:"text",text:c.text,...u?{cache_control:u}:{}})}else if(c?.type==="image"||c?.type==="image_url"){const u=oO(c.image??c.data??c.url);if(u){const d=Dd(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)?Ekr(c):void 0;if(d){const m=Dd(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=Dd(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:rY(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(`
|
|
1128
1128
|
|
|
1129
|
-
`);return{...s!==void 0?{system:s}:{},messages:r}},uY=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}}}},eEt=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},dY=6e5,tEt=class extends fl{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??lY(),i=o?"api_key":r?.authMethod??Qbt(s),a=r?.subscriptionTier??(i==="oauth"?Xbt(s):"api"),l=e||CS();let c=l;!process.env.ANTHROPIC_BASE_URL&&a!=="api"&&!JJ(l,a)&&(c=ZJ(a),h.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(h.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){h.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");const f=this.oauthToken,g=rkr(()=>f.accessToken,this.enableBetaFeatures,!1,!0);m=new Vf({apiKey:"oauth-authenticated",fetch:Pbt(g),timeout:dY,maxRetries:0}),h.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),h.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 f=n?.apiKey??r?.apiKey??aY(),g=(()=>{const y=process.env.ANTHROPIC_BASE_URL;if(!y)return;const v=y.replace(/\/+$/,""),w=v.replace(/\/v\d+$/,"");return w!==v&&h.debug("[AnthropicProvider] Stripping the version suffix from ANTHROPIC_BASE_URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:lo(y),rewrittenTo:lo(w)}),w})();m=new Vf({apiKey:f,defaultHeaders:d,...g&&{baseURL:g},fetch:Pbt(Bt()),timeout:dY,maxRetries:0}),h.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},h.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?iO["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=[...TS,"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"]=iO["anthropic-beta"];return t&&(e["User-Agent"]=Wf),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return h.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;const t=JJ(e,this.subscriptionTier);return t||h.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return XJ(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){h.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){h.debug("Token has no expiry information, assuming valid");return}const e=Date.now(),t=this.oauthToken.expiresAt<=e,r=this.oauthToken.expiresAt<=e+Eie;if(!t&&!r){h.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new dr("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);h.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}h.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(wS,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Wf},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:WJ}),signal:i.signal});if(clearTimeout(a),!l.ok){const d=await l.text();throw new dr(`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=jr(xh(),".neurolink");As(d)||HI(d,{recursive:!0});const m=jr(d,"anthropic-credentials.json"),f=`${m}.tmp`,y={...As(m)?JSON.parse(hd(m,"utf-8")):{},type:"oauth",oauth:u,updatedAt:Date.now()};qI(f,JSON.stringify(y,null,2),{mode:384}),N5(f,m),h.debug("Refreshed OAuth credentials persisted to disk")}catch(d){h.warn("Failed to persist refreshed OAuth token to disk",{error:d instanceof Error?d.message:String(d)})}h.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!c.refresh_token,expiresIn:c.expires_in})})();try{await this.refreshPromise}catch(s){throw s instanceof dr?s:new dr(`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&&h.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&&h.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return CS()}getAISDKModel(){const e=this.client,t=this.providerName,r=this.modelName||CS(),n=i=>this.getTimeout(i??{}),o=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:r,supportedUrls:{},doGenerate:async i=>{await o();const a=cY(i.prompt),l=a.messages;let c=a.system,u=(i.tools??[]).filter(F=>F.type==="function").map(F=>{const L=Dd(F);return{name:F.name,...F.description?{description:F.description}:{},input_schema:F.inputSchema??{type:"object",properties:{}},...L?{cache_control:L}:{}}});u&&u.length===0&&(u=void 0);let d=i.toolChoice?uY(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 F=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:F}],d={type:"tool",name:m}}const f=i.providerOptions?.anthropic?.finalResultSchema;let g=!1;if(!m&&f){const F=Hbt(u,f);u=F.tools,g=F.applied,F.applied&&(c=Vbt(c))}const y=i.providerOptions?.anthropic?.thinking,v=Bbt({system:c,tools:u,messages:l}),w=zbt(l,tO-v),b=Fc("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:w,max_tokens:SM(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,k=x!=null,I=T.max_tokens>8192&&!k?Math.max(n(i),3e5):n(i),R=Ul(I,t,"generate");let P;try{P=await e.messages.create(T,{signal:SI(i.abortSignal,R?.controller.signal)})}finally{R?.cleanup()}const A=[];let M;const N=[];let O=!1;for(const F of P.content)F.type==="thinking"?A.push({type:"reasoning",text:F.thinking}):F.type==="text"?m?N.push(F.text):A.push({type:"text",text:F.text}):F.type==="tool_use"&&(m&&F.name===m?(O=!0,A.push({type:"text",text:PE(F.input)})):g&&F.name===SS?M=PE(F.input):A.push({type:"tool-call",toolCallId:F.id,toolName:F.name,input:PE(F.input)}));if(m&&!O&&N.length>0&&A.push({type:"text",text:N.join("")}),M!==void 0){const F=A.filter(L=>L.type==="reasoning");A.length=0,A.push(...F,{type:"text",text:M}),h.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:M.length})}const D=P.usage.cache_read_input_tokens??0,$=P.usage.cache_creation_input_tokens??0;return{content:A,finishReason:{unified:M!==void 0?"stop":eEt(P.stop_reason),raw:P.stop_reason??"stop"},usage:{inputTokens:{total:P.usage.input_tokens+D+$,noCache:P.usage.input_tokens,cacheRead:D,cacheWrite:$},outputTokens:{total:P.usage.output_tokens,text:P.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:T},response:{id:P.id,modelId:P.model,headers:ckr()??{},body:P}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}formatProviderError(e){return Bi(e,[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(r.message),errorClass:dr,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:Vs,message:"Anthropic rate limit exceeded. Please try again later."},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(r.message),errorClass:qo,message:r=>`Connection error: ${r.message}`},{match:r=>/500|502|503|504|server error/i.test(r.message),errorClass:bt,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:bt,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await akr(()=>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),dkr(e),pkr(e,this.modelName)}async executeStream(e,t){return ukr(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);const r=this.getTimeout(e),n=Ul(r,this.providerName,"stream"),o=new AbortController,s=Qpe([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?Wv(i,"input_schema"):void 0;const Q=await this.buildMessagesForStream(e);if(l=cY(Q),e.schema&&a&&a.length>0){const Z=Hbt(a,Ls(e.schema));a=Z.tools,u=Z.applied,Z.applied&&(l.system=Vbt(l.system))}}catch(Q){throw n?.cleanup(),this.handleProviderError(Q)}const d=this.modelName||CS(),m=c&&a&&a.length>0?uY(wyt(e,i,c)):void 0,f=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,g=Zbt.startSpan("neurolink.provider.streamText",{kind:$r.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":d}}),y=e.maxSteps||Ys,v=this.neurolink?.getEventEmitter(),w=Hv(),{push:b}=w,{usagePromise:T,finishPromise:x,resolveUsage:k,resolveFinish:I}=BW();T.then(Q=>{g.setAttribute("gen_ai.usage.input_tokens",Q.promptTokens||0),g.setAttribute("gen_ai.usage.output_tokens",Q.completionTokens||0),Q.cacheReadTokens&&g.setAttribute("gen_ai.usage.cached_input_tokens",Q.cacheReadTokens);const Z=ul(this.providerName,this.modelName,{input:Q.promptTokens||0,output:Q.completionTokens||0,total:Q.totalTokens||0,...Q.cacheReadTokens?{cacheReadTokens:Q.cacheReadTokens}:{},...Q.cacheCreationTokens?{cacheCreationTokens:Q.cacheCreationTokens}:{}});Z&&Z>0&&g.setAttribute("neurolink.cost",Z)}).catch(()=>{}),x.then(Q=>{g.setAttribute("gen_ai.response.finish_reason",Q||"unknown"),g.end()}).catch(()=>{g.end()});let R;const P=this.client,A=[],M=Date.now();let N=0,O=0,D=0,$=0,F=null;const L=()=>({promptTokens:N,completionTokens:O,totalTokens:N+D+$+O,...D>0?{cacheReadTokens:D}:{},...$>0?{cacheCreationTokens:$}:{}});let B="",z;const j=(Q,Z)=>{const ee=Re=>{if(typeof Re=="string")return Re;try{return JSON.stringify(Re)??""}catch{return""}};return pr(ee(Q),"anthropic")+pr(ee(Z),"anthropic")},Y=(async()=>{let Q,Z;const we=Tkr({client:P,maxSteps:y,toolsRecord:i,buildParams:fe=>{if(a){const te=new Set(a.map(ie=>ie.name)),ke=Object.fromEntries(Object.entries(i).filter(([ie])=>!te.has(ie)));if(Object.keys(ke).length>0){const ie=Wv(ke,"input_schema");ie&&ie.length>0&&(a=[...a,...ie])}}const ne=Bbt({system:l.system,tools:a,messages:fe}),xe=zbt(fe,tO-ne),ae=Fc("anthropic",d,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream");return{model:d,messages:xe,max_tokens:SM(d,e.maxTokens),stream:!0,...l.system?{system:l.system}:{},...ae.temperature!==void 0?{temperature:ae.temperature}:{},...a&&a.length>0?{tools:a}:{},...m?{tool_choice:m}:{},...f?{thinking:f}:{}}},planReclaim:fe=>{const ne=Fbt({conversation:fe,availableInputTokens:zc("anthropic",d,e.maxTokens??void 0),fixedOverheadTokens:j(l.system,a),provider:"anthropic",observedPromptTokens:Q,previousSentEstimate:Z,onSentEstimate:ke=>{Z=ke}});if(!ne)return;const xe=new Set(ne.drop),ae=new Set(ne.truncate),te=[];for(let ke=0;ke<fe.length;ke++){if(xe.has(ke))continue;const ie=fe[ke];if(ae.has(ke)&&Array.isArray(ie.content)){te.push({...ie,content:ie.content.map(W=>W.type==="tool_result"?{...W,content:$bt(typeof W.content=="string"?W.content:JSON.stringify(W.content)??"")}:W)});continue}te.push(ie)}if(xe.size>0){let ke=te.findIndex(ie=>Array.isArray(ie.content)&&ie.content.some(W=>W.type==="tool_use"||W.type==="tool_result"));ke<0&&(ke=Math.min(1,te.length)),te.splice(ke,0,{role:"user",content:[{type:"text",text:tY}]})}return te},noteObservedPromptTokens:fe=>{Q=fe},...u?{finalResultToolName:SS,onTerminalResult:fe=>{z=fe,h.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:fe.length})}}:{}}),pe={...we,buildToolResultMessages:(fe,ne,xe,ae)=>{for(const ie of xe)A.push(ie.name);const te=xe.map(ie=>({type:"tool-call",toolCallId:ie.id,toolName:ie.name,args:ie.args})),ke=xe.map(ie=>ie.error?{type:"tool-result",toolCallId:ie.id,toolName:ie.name,error:ie.error}:{type:"tool-result",toolCallId:ie.id,toolName:ie.name,result:ie.output});return yH(v,ke.map(ie=>({toolName:ie.toolName,result:"result"in ie?ie.result:void 0,error:"error"in ie?ie.error:void 0}))),this.handleToolExecutionStorage(te,ke,e,new Date).catch(ie=>{h.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ie instanceof Error?ie.message:String(ie)})}),we.buildToolResultMessages(fe,ne,xe,ae)}},G={};for(const[fe,ne]of Object.entries(i)){const xe=ne.execute;xe&&(G[fe]={execute:async(ae,te)=>{const ke=te;return xe(ae,{toolCallId:ke.toolCallId??"",...ke.abortSignal?{abortSignal:ke.abortSignal}:{},messages:[]})}})}const re=vt.getActiveSpan(),{stream:ye,resultPromise:J}=Pf(pe,l.messages.slice(),{tools:G,...s?{abortSignal:s}:{},...re?{span:re}:{}}),oe=(async()=>{for await(const fe of ye)fe.reasoning&&b({content:"",reasoning:fe.reasoning}),fe.content&&(u?B+=fe.content:b({content:fe.content}))})(),Ae=await J;await oe,N+=Ae.usage.inputTokens,O+=Ae.usage.outputTokens,D+=Ae.usage.cacheReadTokens??0,$+=Ae.usage.cacheWriteTokens??0,F=Ae.rawStopReason??F,k(L()),I(F??"stop")})().catch(Q=>{throw R=Q,h.error("Anthropic: Stream error",{error:Q instanceof Error?Q.message:String(Q)}),k(L()),I("error"),this.formatProviderError(Q)}).finally(()=>{if(u){const Q=z??B;Q.length>0&&b({content:Q})}n?.cleanup(),w.close()});Y.catch(()=>{});const le=this.providerName;return{stream:async function*(){let Q=0;try{for await(const Z of w.iterable)"content"in Z&&typeof Z.content=="string"&&Z.content.length>0&&Q++,yield Z;if(await Y,Q===0&&A.length===0){h.warn(`${le}: Stream produced no output \u2014 emitting enriched sentinel`);const Z=new ql({message:"Stream produced no output"}),ee=await Cf(Z,void 0,R);xf(ee),yield ee}}catch(Z){const ee=await Cf(Z,void 0,R);if(xf(ee),yield ee,!ql.isInstance(Z))throw Z}finally{o.signal.aborted||o.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],analytics:x.then(async()=>{const Q=await WW.createAnalytics(this.providerName,d,{textStream:(async function*(){})(),usage:T,finishReason:x},Date.now()-M,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),Z=lkr();return Z&&Q&&(this.recordLimitSnapshot(Z),Q.limits=Z),Q})}}async isAvailable(){try{return lY()||aY(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),rEt={};ue(rEt,{ANTHROPIC_BETA_HEADERS:()=>iO,AnthropicProvider:()=>tEt,ModelAccessError:()=>Q$,getModelCapabilities:()=>XJ,getRecommendedModelForTier:()=>ZJ,isModelAvailableForTier:()=>JJ});var xkr=C({"src/lib/providers/anthropic/index.ts"(){"use strict";Ckr(),Ybt()}}),Kf,ti,Akr,kkr,nEt,oEt,sEt,xS,iEt,Ikr,Rkr,Pkr,Mkr,Dkr,Okr,Nkr,Lkr,$kr,Fkr,Ukr,Bkr,zkr,jkr,qkr,Gkr,Hkr,Vkr,Wkr,Kkr,Jkr,Ykr,Zkr,Xkr,Qkr,eIr,tIr,rIr,nIr,oIr,sIr,iIr,aIr,lIr,cIr,uIr,dIr,pIr,mIr,aEt=C({"npm-stub:@aws-sdk/client-bedrock-runtime"(){Kf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Kf.get}):new Proxy(function(...r){return new Proxy({},{get:Kf.get})},{get:Kf.get,apply(r,n,o){return new Proxy({},{get:Kf.get})},construct(r,n){return new Proxy({},{get:Kf.get})}})}},ti=new Proxy({},Kf),{BedrockClient:Akr,ListFoundationModelsCommand:kkr,BedrockRuntimeClient:nEt,ConverseCommand:oEt,ConverseStreamCommand:sEt,ImageFormat:xS,InvokeModelCommand:iEt}=ti,{SageMakerRuntimeClient:Ikr,InvokeEndpointCommand:Rkr,InvokeEndpointWithResponseStreamCommand:Pkr}=ti,{GoogleAuth:Mkr,VertexAI:Dkr,TextToSpeechClient:Okr}=ti,{Webhook:Nkr}=ti,{Hippocampus:Lkr,HippocampusConfig:$kr}=ti,{createClient:Fkr}=ti,{Queue:Ukr,Worker:Bkr,Job:zkr,QueueScheduler:jkr,FlowProducer:qkr}=ti,{Cron:Gkr}=ti,{parseBuffer:Hkr,selectCover:Vkr}=ti,{extractRawText:Wkr,convertToHtml:Kkr}=ti,{Hono:Jkr}=ti,{cors:Ykr,HTTPException:Zkr,logger:Xkr,secureHeaders:Qkr,streamSSE:eIr,timeout:tIr}=ti,rIr=globalThis.fetch,nIr=globalThis.Request,oIr=globalThis.Response,sIr=globalThis.Headers,iIr=globalThis.FormData,aIr=globalThis.File,lIr=globalThis.Blob,cIr=ti.Agent,uIr=ti.Pool,dIr=ti.Client,pIr=ti.Dispatcher,mIr=ti.MockAgent}});function hIr(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 fIr(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function lEt(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 gIr(e,t){if(e.startsWith("arn:")||fIr(e))return[];const r=[],n=hIr(t);return n&&r.push(`${n}.${e}`),r.push(`${dEt}.${e}`),r}function cEt(e,t){return`${e}::${t}`}function yIr(e,t){return pY.get(cEt(t,e))}function vIr(e,t,r){pY.set(cEt(t,e),r),h.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function uEt(e,t,r){const n=yIr(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!lEt(o))throw o;const s=gIr(e,t);if(s.length===0)throw o;h.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 vIr(e,t,i),a}catch(a){if(!lEt(a))throw a}throw o}}var dEt,pY,_Ir=C({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";V(),dEt="global",pY=new Map}});function aO(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function pEt(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 mEt(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??aO(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function wIr(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,w=y.contentBlockDelta.delta.text;i(v),a+=w,s.set(v,(s.get(v)??"")+w),t.push({content:w})}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??aO()}}if(y.contentBlockDelta?.delta?.toolUse){const v=i(y.contentBlockDelta.contentBlockIndex??0);v.toolUse??={name:"",input:{},toolUseId:aO()};const w=y.contentBlockDelta.delta.toolUse.input;typeof w=="string"?v._inputBuffer=(v._inputBuffer??"")+w:typeof w=="object"&&w!==null&&!Array.isArray(w)&&(v.toolUse.input={...v.toolUse.input??{},...w})}if(y.contentBlockStop){const v=y.contentBlockStop.contentBlockIndex??0;pEt(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)pEt(y,s.get(g)??"");const f=n.filter(g=>g.text||g.toolUse||g.image||g.document);return{text:a,toolCalls:mEt(f),usage:{inputTokens:c,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:m},rawStopReason:l,raw:f}}function TIr(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??aO(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:mEt(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 hEt(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 uEt(o.modelId??"",e.region,a=>Ze(e.client.send(new oEt({...o,modelId:a})),mY,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return TIr(i)}const s=await uEt(o.modelId??"",e.region,i=>Ze(e.client.send(new sEt({...o,modelId:i})),mY,new Error("Bedrock streaming API call timed out")));return wIr(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 mY,bIr=C({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";aEt(),ct(),_Ir(),mY=12e4}});function fEt(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 EIr=C({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),lO,gEt=C({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";cl(),lO=Ve.provider}}),yEt={};ue(yEt,{Agent:()=>iSt,BedrockClient:()=>_Et,BedrockRuntimeClient:()=>TEt,Blob:()=>sSt,Client:()=>lSt,ConverseCommand:()=>bEt,ConverseStreamCommand:()=>EEt,Cron:()=>zEt,Dispatcher:()=>cSt,File:()=>oSt,FlowProducer:()=>BEt,FormData:()=>nSt,GoogleAuth:()=>IEt,HTTPException:()=>KEt,Headers:()=>rSt,Hippocampus:()=>DEt,HippocampusConfig:()=>OEt,Hono:()=>VEt,ImageFormat:()=>SEt,InvokeEndpointCommand:()=>AEt,InvokeEndpointWithResponseStreamCommand:()=>kEt,InvokeModelCommand:()=>CEt,Job:()=>FEt,ListFoundationModelsCommand:()=>wEt,MockAgent:()=>pSt,Pool:()=>aSt,Queue:()=>LEt,QueueScheduler:()=>UEt,Request:()=>eSt,Response:()=>tSt,SageMakerRuntimeClient:()=>xEt,TextToSpeechClient:()=>PEt,VertexAI:()=>REt,Webhook:()=>MEt,Worker:()=>$Et,convertToHtml:()=>HEt,cors:()=>WEt,createClient:()=>NEt,default:()=>vEt,extractRawText:()=>GEt,fetch:()=>QEt,getGlobalDispatcher:()=>dSt,interceptors:()=>mSt,logger:()=>JEt,parseBuffer:()=>jEt,request:()=>hSt,secureHeaders:()=>YEt,selectCover:()=>qEt,setGlobalDispatcher:()=>uSt,streamSSE:()=>ZEt,timeout:()=>XEt});var Jf,gs,vEt,_Et,wEt,TEt,bEt,EEt,SEt,CEt,xEt,AEt,kEt,IEt,REt,PEt,MEt,DEt,OEt,NEt,LEt,$Et,FEt,UEt,BEt,zEt,jEt,qEt,GEt,HEt,VEt,WEt,KEt,JEt,YEt,ZEt,XEt,QEt,eSt,tSt,rSt,nSt,oSt,sSt,iSt,aSt,lSt,cSt,uSt,dSt,pSt,mSt,hSt,SIr=C({"npm-stub:@aws-sdk/client-bedrock"(){Jf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Jf.get}):new Proxy(function(...r){return new Proxy({},{get:Jf.get})},{get:Jf.get,apply(r,n,o){return new Proxy({},{get:Jf.get})},construct(r,n){return new Proxy({},{get:Jf.get})}})}},gs=new Proxy({},Jf),vEt=gs,{BedrockClient:_Et,ListFoundationModelsCommand:wEt,BedrockRuntimeClient:TEt,ConverseCommand:bEt,ConverseStreamCommand:EEt,ImageFormat:SEt,InvokeModelCommand:CEt}=gs,{SageMakerRuntimeClient:xEt,InvokeEndpointCommand:AEt,InvokeEndpointWithResponseStreamCommand:kEt}=gs,{GoogleAuth:IEt,VertexAI:REt,TextToSpeechClient:PEt}=gs,{Webhook:MEt}=gs,{Hippocampus:DEt,HippocampusConfig:OEt}=gs,{createClient:NEt}=gs,{Queue:LEt,Worker:$Et,Job:FEt,QueueScheduler:UEt,FlowProducer:BEt}=gs,{Cron:zEt}=gs,{parseBuffer:jEt,selectCover:qEt}=gs,{extractRawText:GEt,convertToHtml:HEt}=gs,{Hono:VEt}=gs,{cors:WEt,HTTPException:KEt,logger:JEt,secureHeaders:YEt,streamSSE:ZEt,timeout:XEt}=gs,QEt=globalThis.fetch,eSt=globalThis.Request,tSt=globalThis.Response,rSt=globalThis.Headers,nSt=globalThis.FormData,oSt=globalThis.File,sSt=globalThis.Blob,iSt=gs.Agent,aSt=gs.Pool,lSt=gs.Client,cSt=gs.Dispatcher,uSt=()=>{},dSt=()=>gs,pSt=gs.MockAgent,mSt={redirect:()=>e=>e,retry:()=>e=>e},hSt=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 hY(){return await Promise.resolve().then(()=>(SIr(),yEt))}var fSt=C({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}}),gSt,CIr=C({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";aEt(),Xr(),Ib(),tc(),$o(),UM(),bIr(),Ct(),_i(),ct(),V(),em(),nM(),EIr(),ji(),Xt(),gEt(),fSt(),gSt=class $Xt extends fl{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=$Xt.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",h.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),h.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{h.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new nEt({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),h.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw h.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){const{BedrockClient:t,ListFoundationModelsCommand:r}=await hY(),n=new t({region:this.region});try{h.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;h.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){const s=o instanceof Error?o.message:String(o);h.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){h.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)){h.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=fEt(n,this.providerName,this.modelName),f=await eM(m,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(f)}else{h.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const d={role:"user",content:[{text:n.prompt}]};this.conversationHistory.push(d)}h.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||Ys,n=await this.resolveTurnTools(t.tools,t.disableTools),o=this.formatToolsForBedrock(n),s=Fc(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converse"),i=hEt({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}=Pf(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 h.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 lO.startActiveSpan("bedrock.tool.execute",{kind:$r.CLIENT,attributes:{"gen_ai.tool.name":r,"gen_ai.system":"aws.bedrock"}},async s=>{try{if(h.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=".",h.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),h.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);h.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:je.OK}),u}catch(i){throw h.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:i}),s.setStatus({code:je.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=Ls(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 h.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"?xS.JPEG:i==="png"?xS.PNG:i==="gif"?xS.GIF:xS.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?Bp.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 h.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),h.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),lO.startActiveSpan("bedrock.stream",{kind:$r.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async r=>{try{if(h.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)){h.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=fEt(t,this.providerName,this.modelName),i=await eM(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{h.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");const s={role:"user",content:[{text:t.input.text}]};this.conversationHistory.push(s)}h.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),h.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");const o=await this.streamingConversationLoop(t,r);return h.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),r.setStatus({code:je.OK}),r.end(),o}catch(n){h.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(h.debug("[TRACE] executeStream CATCH - checking if permission error"),h.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){h.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),h.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:je.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:je.OK}),r.end();const a=new ReadableStream({start(c){const d=(i.content||"").split(/(\s+)/);let m="";for(let f=0;f<d.length;f++)m+=d[f],(f===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:je.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||Ys,s=await this.resolveTurnTools(t.tools,t.disableTools),i=this.formatToolsForBedrock(s),a=Fc(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converseStream"),l=hEt({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:R=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(R),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(R=>{u=()=>{c=!0,R()}}),m={...l,executeStep:async(R,P,A)=>{const M=await l.executeStep(R,P,A);return u(),M}};r.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});const{stream:f,resultPromise:g}=Pf(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:t.abortSignal}),y=g.then(R=>({result:R,error:void 0}),R=>({result:void 0,error:R}));if(await Promise.race([d,y]),!c){const R=await y;if(R.error)throw R.error}const v=this.neurolink?.getEventEmitter(),w=this,b={startTime:n,streamId:`bedrock-${Date.now()}`};let T;const x=new Promise(R=>{T=R}),k=R=>{const P=R?.inputTokens??0,A=R?.outputTokens??0,M=R?.cacheReadTokens??0,N=R?.cacheWriteTokens??0;return{input:P,output:A,total:P+M+N+A,...M>0&&{cacheReadTokens:M},...N>0&&{cacheCreationTokens:N}}};return y.then(R=>{T(fv(this.providerName,this.modelName||this.getDefaultModel(),{usage:k(R.result?.usage)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let R=!1;try{yield*f}catch(P){throw R=!0,P}finally{const P=await y;P.error&&(R=!0);const A=k(P.result?.usage);P.result&&(w.conversationHistory=P.result.conversation,b.finishReason=P.result.finishReason,b.rawFinishReason=P.result.rawStopReason,r.setAttribute("gen_ai.response.stop_reason",P.result.rawStopReason??"unknown")),v&&v.emit("generation:end",{provider:w.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:A,model:w.modelName||w.getDefaultModel(),provider:w.providerName,finishReason:R?"error":P.result?.rawStopReason},success:!R})}}},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 hY(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{h.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(h.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(Ur(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}):(h.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 Bi(t,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:dr,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:Vs,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:bt,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:bt,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(t,r){const n=r||"amazon.titan-embed-text-v2:0";h.debug("Generating embedding",{provider:this.providerName,model:n,textLength:t.length});try{const o=JSON.stringify({inputText:t}),s=new iEt({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 h.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.embedding.length}),a.embedding}catch(o){throw h.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";h.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 h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw h.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:t.length}),this.handleProviderError(o)}}}}}),ySt={};ue(ySt,{AmazonBedrockProvider:()=>gSt,bedrockTracer:()=>lO,loadBedrockControl:()=>hY});var xIr=C({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";CIr(),gEt(),fSt()}}),vSt={};ue(vSt,{AzureOpenAIProvider:()=>_St});var _St,AIr=C({"src/lib/providers/azureOpenai.ts"(){"use strict";Ct(),V(),_i(),jo(),Sd(),yl(),Tm(),_St=class extends Fa{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",f=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||Pi(sQt()),d||Pi(iQt()),super("azure",e,t,{baseURL:d,apiKey:o}),this.azureDeployment=m,this.azureApiVersion=f,this.azureResourceOrigin=d,this.azureDeploymentPathPrefix=u,this.useMaxCompletionTokensOverride=y,h.shouldLog("debug")&&h.debug("Azure OpenAI Provider initialized",L5e({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:dr,message:"Invalid Azure OpenAI API key or endpoint."},...ns];return Bi(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??pyt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function kIr(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 IIr=C({"src/lib/utils/imageDetection.ts"(){"use strict"}});function wSt(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 RIr=C({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),cO,PIr=C({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs"(){cO=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}}}),MIr=C({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs"(){Xn()}});function fY(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var uO,gY,TSt=C({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs"(){MIr(),uO=e=>(uO=Array.isArray,uO(e)),gY=uO}});function*DIr(e){if(!e)return;if(yY 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():gY(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=gY(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 yY,bSt,OIr=C({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){TSt(),yY=Symbol.for("brand.privateNullableHeaders"),bSt=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[s,i]of DIr(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{[yY]:!0,values:t,nulls:r}}}});function NIr(e){const t=new gS(e);return delete t.batches,t}function LIr(e){const t=new ya(e);return delete t.messages.batches,t}var ESt,SSt,vY,CSt=C({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){XD(),$_t(),xM(),PIr(),TSt(),OIr(),XD(),ESt="vertex-2023-10-16",SSt=new Set(["/v1/messages","/v1/messages?beta=true"]),vY=class extends So{constructor({baseURL:e=cO("ANTHROPIC_VERTEX_BASE_URL"),region:t=cO("CLOUD_ML_REGION")??null,projectId:r=cO("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=NIr(this),this.beta=LIr(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 tW({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=bSt([r,e.headers])}async buildRequest(e){if(fY(e.body)&&(e.body={...e.body}),fY(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=ESt)),SSt.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(!fY(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)}}}}),_Y={};ue(_Y,{AnthropicVertex:()=>vY,BaseAnthropic:()=>So,default:()=>vY});var xSt=C({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){CSt(),CSt()}});async function $Ir(){return dO||(dO=await Promise.resolve().then(()=>(xSt(),_Y))),dO}function FIr(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 wY(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 UIr(e,t){const r=e.callParts,n=e.resultParts,o=Math.min(r.length,n.length);(o!==r.length||o!==n.length)&&h.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 BIr(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 TY(e){const t=[];let r=0;for(const n of FIr(e)){if(n.type==="regular"){wY(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:s}=UIr(n,r);o.length!==0&&(r++,wY(t,"assistant",o),wY(t,"user",s))}if(BIr(t),h.shouldLog("debug")){const n=t.flatMap(o=>Array.isArray(o.content)?o.content:[]);h.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 bY(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 Im(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"&&Im(n);if(e.items&&typeof e.items=="object")if(Array.isArray(e.items))for(const n of e.items)n&&typeof n=="object"&&Im(n);else Im(e.items);for(const n of["allOf","anyOf","oneOf"])if(Array.isArray(e[n]))for(const o of e[n])o&&typeof o=="object"&&Im(o)}function ASt(e,t,r){const n=vgt({contents:e,availableInputTokens:zc("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<=DSt?c:{functionResponse:{name:u.name,response:{result:yW(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:_W}]})}return e.length=0,e.push(...i),!0}function kSt(e,t,r){const n=Fbt({conversation:e,availableInputTokens:zc("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:$bt(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:tY}]})}return e.length=0,e.push(...i),!0}async function ISt(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,f=d.candidates?.[0],g=f?.finishReason;typeof g=="string"&&g&&(s=g);const y=f?.content;if(y&&Array.isArray(y.parts))for(const w of y.parts)n.push(w),typeof w.text=="string"&&w.text.length>0&&t.push({content:w.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 w=Math.min(v.cachedContentTokenCount??0,v.promptTokenCount);r.onUsageDelta?.("cacheRead",w-l),l=w}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 dO,RSt,pO,AS,EY,w0,Yf,PSt,MSt,mO,DSt,SY,zIr=C({"src/lib/providers/googleVertex/client.ts"(){"use strict";Wn(),Xr(),tc(),z7(),$M(),Ntt(),$o(),Zh(),PH(),kr(),Zn(),Ct(),_i(),ct(),qbt(),emt(),nM(),V(),wgt(),Ubt(),X9(),IIr(),Q9(),jo(),ji(),ogt(),jv(),Ra(),Tgt(),mgt(),UM(),Vv(),wW(),Ru(),G1(),cl(),Xt(),Bc(),Sd(),U1(),em(),RIr(),fM(),dO=null,RSt=()=>!0,pO=()=>Pi(TQt()),AS=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",EY=(e,t)=>{const r=t||AS();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||KR.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},w0=EY,Yf=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",PSt=()=>!!(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),MSt=async(e,t)=>{const r=e||AS();return{projectId:pO(),region:r,...t!==void 0&&{timeout:t},maxRetries:0}},mO=e=>e.toLowerCase().includes("claude"),DSt=2048,SY=class rn extends fl{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||PSt()||Pi(bQt()),this.projectId=s?.projectId||(i?"":pO()),this.location=o||s?.location||AS(),h.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),h.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return Yf()}async getAISDKModel(){throw new $e({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&&g9(t.input),t.input?.files?.length)try{await y9(t,100*1024*1024,this.providerName)}catch(r){h.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${r instanceof Error?r.message:String(r)}`)}await _E(t.input)}async executeStream(t,r){const n=t.model||this.modelName||Yf();return Y$e({name:"neurolink.provider.stream",tracer:Ve.provider,attributes:{[Oe.GEN_AI_SYSTEM]:this.providerName,[Oe.GEN_AI_MODEL]:n,[Oe.GEN_AI_OPERATION]:"stream",[Oe.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:Ve.provider,attributes:{[Oe.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;mO(n)?(h.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(i).length}),c=await this.executeNativeAnthropicStream(l)):(h.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){kgt("GoogleVertex");const r=this.resolveExpressApiKey(),n=r?"":pO(),o=t||this.location||AS(),i=(await Promise.resolve().then(()=>(HT(),Yy))).GoogleGenAI;if(!i)throw new $e({code:Xe.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const 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=Ls(s,"openApi3"),a=ln(i);a.$schema&&delete a.$schema;const l=Ti(a);Im(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),h.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=hje(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),h.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=Ls(s),a=ln(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),h.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=hje(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),h.info(`[GoogleVertex] Tool "${t}" resolved mid-turn via discovery \u2014 executing.`),o.get(t)}async executeNativeGemini3Stream(t){const r=t.model||this.modelName||Yf(),n=w0(r,t.region),o=await this.createVertexGenAIClient(n);h.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){h.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(const ne of a.pdfFiles){let xe;typeof ne=="string"?Lo.existsSync(ne)?xe=Lo.readFileSync(ne):xe=Buffer.from(ne,"base64"):xe=ne;const ae=xe.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:ae}})}}if(await pW(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){h.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(const ne of a.images){const xe=oE(ne);let ae,te="image/jpeg";if(typeof xe=="string")if(Lo.existsSync(xe)){ae=Lo.readFileSync(xe);const ie=aE(xe);te=ie.startsWith("image/")?ie:this.detectImageType(ae)}else if(xe.startsWith("data:")){const ie=xe.match(/^data:([^;]+);base64,(.+)$/);if(ie)te=ie[1],ae=Buffer.from(ie[2],"base64");else continue}else if(xe.startsWith("http://")||xe.startsWith("https://"))try{const ie=await fetch(xe);if(!ie.ok){h.warn(`[GoogleVertex] Image fetch failed: ${ie.status} ${ie.statusText}, skipping`,{url:sn(xe)});continue}const W=await ie.arrayBuffer();ae=Buffer.from(W);const ve=ie.headers.get("content-type");ve&&ve.startsWith("image/")&&(te=ve.split(";")[0])}catch(ie){h.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${ie instanceof Error?ie.message:String(ie)}`,{url:sn(xe)});continue}else ae=Buffer.from(xe,"base64"),te=this.detectImageType(ae);else ae=xe,te=this.detectImageType(ae);const ke=ae.toString("base64");i.push({inlineData:{mimeType:te,data:ke}})}}NM(s,t.conversationMessages),s.push({role:"user",parts:i});let l;const c=new Gv;let u;if(t.tools&&Object.keys(t.tools).length>0&&!t.disableTools){const ne=Wv(t.tools,"functionDeclarations");u=ne,l=ne.toolsConfig;for(const[xe,ae]of ne.executeMap)c.set(xe,ae);h.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ne.toolsConfig[0].functionDeclarations.length,toolNames:ne.toolsConfig[0].functionDeclarations.map(xe=>xe.name)})}const d=t;let m=!1;if(d.schema&&l){m=!0;const ne=Ls(d.schema,"openApi3"),xe=ln(ne);xe.$schema&&delete xe.$schema;const ae=Ti(xe),te=l[0]?.functionDeclarations||[];te.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:te}],h.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(ae),totalTools:te.length})}const f=Fc(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),g={...f.temperature!==void 0&&{temperature:f.temperature},maxOutputTokens:t.maxTokens};Z9(r)&&(g.maxOutputTokens&&g.maxOutputTokens>Na&&(h.warn(`[GoogleVertex] Capping maxOutputTokens from ${g.maxOutputTokens} to ${Na} for ${r}`),g.maxOutputTokens=Na),g.maxOutputTokens||(g.maxOutputTokens=Na)),f.topP!==void 0&&(g.topP=f.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+`
|
|
1129
|
+
`);return{...s!==void 0?{system:s}:{},messages:r}},uY=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}}}},eEt=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},dY=6e5,tEt=class extends fl{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??lY(),i=o?"api_key":r?.authMethod??Qbt(s),a=r?.subscriptionTier??(i==="oauth"?Xbt(s):"api"),l=e||CS();let c=l;!process.env.ANTHROPIC_BASE_URL&&a!=="api"&&!JJ(l,a)&&(c=ZJ(a),h.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(h.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){h.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");const f=this.oauthToken,g=rkr(()=>f.accessToken,this.enableBetaFeatures,!1,!0);m=new Vf({apiKey:"oauth-authenticated",fetch:Pbt(g),timeout:dY,maxRetries:0}),h.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),h.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 f=n?.apiKey??r?.apiKey??aY(),g=(()=>{const y=process.env.ANTHROPIC_BASE_URL;if(!y)return;const v=y.replace(/\/+$/,""),w=v.replace(/\/v\d+$/,"");return w!==v&&h.debug("[AnthropicProvider] Stripping the version suffix from ANTHROPIC_BASE_URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:lo(y),rewrittenTo:lo(w)}),w})();m=new Vf({apiKey:f,defaultHeaders:d,...g&&{baseURL:g},fetch:Pbt(Bt()),timeout:dY,maxRetries:0}),h.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},h.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?iO["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=[...TS,"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"]=iO["anthropic-beta"];return t&&(e["User-Agent"]=Wf),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return h.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;const t=JJ(e,this.subscriptionTier);return t||h.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return XJ(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){h.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){h.debug("Token has no expiry information, assuming valid");return}const e=Date.now(),t=this.oauthToken.expiresAt<=e,r=this.oauthToken.expiresAt<=e+Eie;if(!t&&!r){h.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new dr("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);h.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}h.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(wS,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Wf},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:WJ}),signal:i.signal});if(clearTimeout(a),!l.ok){const d=await l.text();throw new dr(`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=jr(xh(),".neurolink");As(d)||HI(d,{recursive:!0});const m=jr(d,"anthropic-credentials.json"),f=`${m}.tmp`,y={...As(m)?JSON.parse(hd(m,"utf-8")):{},type:"oauth",oauth:u,updatedAt:Date.now()};qI(f,JSON.stringify(y,null,2),{mode:384}),N5(f,m),h.debug("Refreshed OAuth credentials persisted to disk")}catch(d){h.warn("Failed to persist refreshed OAuth token to disk",{error:d instanceof Error?d.message:String(d)})}h.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!c.refresh_token,expiresIn:c.expires_in})})();try{await this.refreshPromise}catch(s){throw s instanceof dr?s:new dr(`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&&h.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&&h.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return CS()}getAISDKModel(){const e=this.client,t=this.providerName,r=this.modelName||CS(),n=i=>this.getTimeout(i??{}),o=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:r,supportedUrls:{},doGenerate:async i=>{await o();const a=cY(i.prompt),l=a.messages;let c=a.system,u=(i.tools??[]).filter(F=>F.type==="function").map(F=>{const L=Dd(F);return{name:F.name,...F.description?{description:F.description}:{},input_schema:F.inputSchema??{type:"object",properties:{}},...L?{cache_control:L}:{}}});u&&u.length===0&&(u=void 0);let d=i.toolChoice?uY(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 F=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:F}],d={type:"tool",name:m}}const f=i.providerOptions?.anthropic?.finalResultSchema;let g=!1;if(!m&&f){const F=Hbt(u,f);u=F.tools,g=F.applied,F.applied&&(c=Vbt(c))}const y=i.providerOptions?.anthropic?.thinking,v=Bbt({system:c,tools:u,messages:l}),w=zbt(l,tO-v),b=Fc("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:w,max_tokens:SM(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,k=x!=null,I=T.max_tokens>8192&&!k?Math.max(n(i),3e5):n(i),R=Ul(I,t,"generate");let P;try{P=await e.messages.create(T,{signal:SI(i.abortSignal,R?.controller.signal)})}finally{R?.cleanup()}const A=[];let M;const N=[];let O=!1;for(const F of P.content)F.type==="thinking"?A.push({type:"reasoning",text:F.thinking}):F.type==="text"?m?N.push(F.text):A.push({type:"text",text:F.text}):F.type==="tool_use"&&(m&&F.name===m?(O=!0,A.push({type:"text",text:PE(F.input)})):g&&F.name===SS?M=PE(F.input):A.push({type:"tool-call",toolCallId:F.id,toolName:F.name,input:PE(F.input)}));if(m&&!O&&N.length>0&&A.push({type:"text",text:N.join("")}),M!==void 0){const F=A.filter(L=>L.type==="reasoning");A.length=0,A.push(...F,{type:"text",text:M}),h.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:M.length})}const D=P.usage.cache_read_input_tokens??0,$=P.usage.cache_creation_input_tokens??0;return{content:A,finishReason:{unified:M!==void 0?"stop":eEt(P.stop_reason),raw:P.stop_reason??"stop"},usage:{inputTokens:{total:P.usage.input_tokens+D+$,noCache:P.usage.input_tokens,cacheRead:D,cacheWrite:$},outputTokens:{total:P.usage.output_tokens,text:P.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:T},response:{id:P.id,modelId:P.model,headers:ckr()??{},body:P}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}formatProviderError(e){return Bi(e,[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(r.message),errorClass:dr,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:Vs,message:"Anthropic rate limit exceeded. Please try again later."},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(r.message),errorClass:qo,message:r=>`Connection error: ${r.message}`},{match:r=>/500|502|503|504|server error/i.test(r.message),errorClass:bt,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:bt,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await akr(()=>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),dkr(e),pkr(e,this.modelName)}async executeStream(e,t){return ukr(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);const r=this.getTimeout(e),n=Ul(r,this.providerName,"stream"),o=new AbortController,s=Qpe([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?Wv(i,"input_schema"):void 0;const Q=await this.buildMessagesForStream(e);if(l=cY(Q),e.schema&&a&&a.length>0){const Z=Hbt(a,Ls(e.schema));a=Z.tools,u=Z.applied,Z.applied&&(l.system=Vbt(l.system))}}catch(Q){throw n?.cleanup(),this.handleProviderError(Q)}const d=this.modelName||CS(),m=c&&a&&a.length>0?uY(wyt(e,i,c)):void 0,f=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,g=Zbt.startSpan("neurolink.provider.streamText",{kind:$r.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":d}}),y=e.maxSteps||Ys,v=this.neurolink?.getEventEmitter(),w=Hv(),{push:b}=w,{usagePromise:T,finishPromise:x,resolveUsage:k,resolveFinish:I}=BW();T.then(Q=>{g.setAttribute("gen_ai.usage.input_tokens",Q.promptTokens||0),g.setAttribute("gen_ai.usage.output_tokens",Q.completionTokens||0),Q.cacheReadTokens&&g.setAttribute("gen_ai.usage.cached_input_tokens",Q.cacheReadTokens);const Z=ul(this.providerName,this.modelName,{input:Q.promptTokens||0,output:Q.completionTokens||0,total:Q.totalTokens||0,...Q.cacheReadTokens?{cacheReadTokens:Q.cacheReadTokens}:{},...Q.cacheCreationTokens?{cacheCreationTokens:Q.cacheCreationTokens}:{}});Z&&Z>0&&g.setAttribute("neurolink.cost",Z)}).catch(()=>{}),x.then(Q=>{g.setAttribute("gen_ai.response.finish_reason",Q||"unknown"),g.end()}).catch(()=>{g.end()});let R;const P=this.client,A=[],M=Date.now();let N=0,O=0,D=0,$=0,F=null;const L=()=>({promptTokens:N,completionTokens:O,totalTokens:N+D+$+O,...D>0?{cacheReadTokens:D}:{},...$>0?{cacheCreationTokens:$}:{}});let B="",z;const j=(Q,Z)=>{const ee=Re=>{if(typeof Re=="string")return Re;try{return JSON.stringify(Re)??""}catch{return""}};return pr(ee(Q),"anthropic")+pr(ee(Z),"anthropic")},Y=(async()=>{let Q,Z;const we=Tkr({client:P,maxSteps:y,toolsRecord:i,buildParams:fe=>{if(a){const te=new Set(a.map(ie=>ie.name)),ke=Object.fromEntries(Object.entries(i).filter(([ie])=>!te.has(ie)));if(Object.keys(ke).length>0){const ie=Wv(ke,"input_schema");ie&&ie.length>0&&(a=[...a,...ie])}}const ne=Bbt({system:l.system,tools:a,messages:fe}),xe=zbt(fe,tO-ne),ae=Fc("anthropic",d,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream");return{model:d,messages:xe,max_tokens:SM(d,e.maxTokens),stream:!0,...l.system?{system:l.system}:{},...ae.temperature!==void 0?{temperature:ae.temperature}:{},...a&&a.length>0?{tools:a}:{},...m?{tool_choice:m}:{},...f?{thinking:f}:{}}},planReclaim:fe=>{const ne=Fbt({conversation:fe,availableInputTokens:zc("anthropic",d,e.maxTokens??void 0),fixedOverheadTokens:j(l.system,a),provider:"anthropic",observedPromptTokens:Q,previousSentEstimate:Z,onSentEstimate:ke=>{Z=ke}});if(!ne)return;const xe=new Set(ne.drop),ae=new Set(ne.truncate),te=[];for(let ke=0;ke<fe.length;ke++){if(xe.has(ke))continue;const ie=fe[ke];if(ae.has(ke)&&Array.isArray(ie.content)){te.push({...ie,content:ie.content.map(W=>W.type==="tool_result"?{...W,content:$bt(typeof W.content=="string"?W.content:JSON.stringify(W.content)??"")}:W)});continue}te.push(ie)}if(xe.size>0){let ke=te.findIndex(ie=>Array.isArray(ie.content)&&ie.content.some(W=>W.type==="tool_use"||W.type==="tool_result"));ke<0&&(ke=Math.min(1,te.length)),te.splice(ke,0,{role:"user",content:[{type:"text",text:tY}]})}return te},noteObservedPromptTokens:fe=>{Q=fe},...u?{finalResultToolName:SS,onTerminalResult:fe=>{z=fe,h.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:fe.length})}}:{}}),pe={...we,buildToolResultMessages:(fe,ne,xe,ae)=>{for(const ie of xe)A.push(ie.name);const te=xe.map(ie=>({type:"tool-call",toolCallId:ie.id,toolName:ie.name,args:ie.args})),ke=xe.map(ie=>ie.error?{type:"tool-result",toolCallId:ie.id,toolName:ie.name,error:ie.error}:{type:"tool-result",toolCallId:ie.id,toolName:ie.name,result:ie.output});return yH(v,ke.map(ie=>({toolName:ie.toolName,result:"result"in ie?ie.result:void 0,error:"error"in ie?ie.error:void 0}))),this.handleToolExecutionStorage(te,ke,e,new Date).catch(ie=>{h.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ie instanceof Error?ie.message:String(ie)})}),we.buildToolResultMessages(fe,ne,xe,ae)}},G={};for(const[fe,ne]of Object.entries(i)){const xe=ne.execute;xe&&(G[fe]={execute:async(ae,te)=>{const ke=te;return xe(ae,{toolCallId:ke.toolCallId??"",...ke.abortSignal?{abortSignal:ke.abortSignal}:{},messages:[]})}})}const re=vt.getActiveSpan(),{stream:ye,resultPromise:J}=Pf(pe,l.messages.slice(),{tools:G,...s?{abortSignal:s}:{},...re?{span:re}:{}}),oe=(async()=>{for await(const fe of ye)fe.reasoning&&b({content:"",reasoning:fe.reasoning}),fe.content&&(u?B+=fe.content:b({content:fe.content}))})(),Ae=await J;await oe,N+=Ae.usage.inputTokens,O+=Ae.usage.outputTokens,D+=Ae.usage.cacheReadTokens??0,$+=Ae.usage.cacheWriteTokens??0,F=Ae.rawStopReason??F,k(L()),I(F??"stop")})().catch(Q=>{throw R=Q,h.error("Anthropic: Stream error",{error:Q instanceof Error?Q.message:String(Q)}),k(L()),I("error"),this.formatProviderError(Q)}).finally(()=>{if(u){const Q=z??B;Q.length>0&&b({content:Q})}n?.cleanup(),w.close()});Y.catch(()=>{});const le=this.providerName;return{stream:async function*(){let Q=0;try{for await(const Z of w.iterable)"content"in Z&&typeof Z.content=="string"&&Z.content.length>0&&Q++,yield Z;if(await Y,Q===0&&A.length===0){h.warn(`${le}: Stream produced no output \u2014 emitting enriched sentinel`);const Z=new ql({message:"Stream produced no output"}),ee=await Cf(Z,void 0,R);xf(ee),yield ee}}catch(Z){const ee=await Cf(Z,void 0,R);if(xf(ee),yield ee,!ql.isInstance(Z))throw Z}finally{o.signal.aborted||o.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],analytics:x.then(async()=>{const Q=await WW.createAnalytics(this.providerName,d,{textStream:(async function*(){})(),usage:T,finishReason:x},Date.now()-M,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),Z=lkr();return Z&&Q&&(this.recordLimitSnapshot(Z),Q.limits=Z),Q})}}async isAvailable(){try{return lY()||aY(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),rEt={};ue(rEt,{ANTHROPIC_BETA_HEADERS:()=>iO,AnthropicProvider:()=>tEt,ModelAccessError:()=>Q$,getModelCapabilities:()=>XJ,getRecommendedModelForTier:()=>ZJ,isModelAvailableForTier:()=>JJ});var xkr=C({"src/lib/providers/anthropic/index.ts"(){"use strict";Ckr(),Ybt()}}),Kf,ti,Akr,kkr,nEt,oEt,sEt,xS,iEt,Ikr,Rkr,Pkr,Mkr,Dkr,Okr,Nkr,Lkr,$kr,Fkr,Ukr,Bkr,zkr,jkr,qkr,Gkr,Hkr,Vkr,Wkr,Kkr,Jkr,Ykr,Zkr,Xkr,Qkr,eIr,tIr,rIr,nIr,oIr,sIr,iIr,aIr,lIr,cIr,uIr,dIr,pIr,mIr,aEt=C({"npm-stub:@aws-sdk/client-bedrock-runtime"(){Kf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Kf.get}):new Proxy(function(...r){return new Proxy({},{get:Kf.get})},{get:Kf.get,apply(r,n,o){return new Proxy({},{get:Kf.get})},construct(r,n){return new Proxy({},{get:Kf.get})}})}},ti=new Proxy({},Kf),{BedrockClient:Akr,ListFoundationModelsCommand:kkr,BedrockRuntimeClient:nEt,ConverseCommand:oEt,ConverseStreamCommand:sEt,ImageFormat:xS,InvokeModelCommand:iEt}=ti,{SageMakerRuntimeClient:Ikr,InvokeEndpointCommand:Rkr,InvokeEndpointWithResponseStreamCommand:Pkr}=ti,{GoogleAuth:Mkr,VertexAI:Dkr,TextToSpeechClient:Okr}=ti,{Webhook:Nkr}=ti,{Hippocampus:Lkr,HippocampusConfig:$kr}=ti,{createClient:Fkr}=ti,{Queue:Ukr,Worker:Bkr,Job:zkr,QueueScheduler:jkr,FlowProducer:qkr}=ti,{Cron:Gkr}=ti,{parseBuffer:Hkr,selectCover:Vkr}=ti,{extractRawText:Wkr,convertToHtml:Kkr}=ti,{Hono:Jkr}=ti,{cors:Ykr,HTTPException:Zkr,logger:Xkr,secureHeaders:Qkr,streamSSE:eIr,timeout:tIr}=ti,rIr=globalThis.fetch,nIr=globalThis.Request,oIr=globalThis.Response,sIr=globalThis.Headers,iIr=globalThis.FormData,aIr=globalThis.File,lIr=globalThis.Blob,cIr=ti.Agent,uIr=ti.Pool,dIr=ti.Client,pIr=ti.Dispatcher,mIr=ti.MockAgent}});function hIr(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 fIr(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function lEt(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 gIr(e,t){if(e.startsWith("arn:")||fIr(e))return[];const r=[],n=hIr(t);return n&&r.push(`${n}.${e}`),r.push(`${dEt}.${e}`),r}function cEt(e,t){return`${e}::${t}`}function yIr(e,t){return pY.get(cEt(t,e))}function vIr(e,t,r){pY.set(cEt(t,e),r),h.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function uEt(e,t,r){const n=yIr(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!lEt(o))throw o;const s=gIr(e,t);if(s.length===0)throw o;h.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 vIr(e,t,i),a}catch(a){if(!lEt(a))throw a}throw o}}var dEt,pY,_Ir=C({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";V(),dEt="global",pY=new Map}});function aO(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function pEt(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 mEt(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??aO(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function wIr(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,w=y.contentBlockDelta.delta.text;i(v),a+=w,s.set(v,(s.get(v)??"")+w),t.push({content:w})}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??aO()}}if(y.contentBlockDelta?.delta?.toolUse){const v=i(y.contentBlockDelta.contentBlockIndex??0);v.toolUse??={name:"",input:{},toolUseId:aO()};const w=y.contentBlockDelta.delta.toolUse.input;typeof w=="string"?v._inputBuffer=(v._inputBuffer??"")+w:typeof w=="object"&&w!==null&&!Array.isArray(w)&&(v.toolUse.input={...v.toolUse.input??{},...w})}if(y.contentBlockStop){const v=y.contentBlockStop.contentBlockIndex??0;pEt(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)pEt(y,s.get(g)??"");const f=n.filter(g=>g.text||g.toolUse||g.image||g.document);return{text:a,toolCalls:mEt(f),usage:{inputTokens:c,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:m},rawStopReason:l,raw:f}}function TIr(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??aO(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:mEt(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 hEt(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 uEt(o.modelId??"",e.region,a=>Ze(e.client.send(new oEt({...o,modelId:a})),mY,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return TIr(i)}const s=await uEt(o.modelId??"",e.region,i=>Ze(e.client.send(new sEt({...o,modelId:i})),mY,new Error("Bedrock streaming API call timed out")));return wIr(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 mY,bIr=C({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";aEt(),ct(),_Ir(),mY=12e4}});function fEt(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 EIr=C({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),lO,gEt=C({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";cl(),lO=Ve.provider}}),yEt={};ue(yEt,{Agent:()=>iSt,BedrockClient:()=>_Et,BedrockRuntimeClient:()=>TEt,Blob:()=>sSt,Client:()=>lSt,ConverseCommand:()=>bEt,ConverseStreamCommand:()=>EEt,Cron:()=>zEt,Dispatcher:()=>cSt,File:()=>oSt,FlowProducer:()=>BEt,FormData:()=>nSt,GoogleAuth:()=>IEt,HTTPException:()=>KEt,Headers:()=>rSt,Hippocampus:()=>DEt,HippocampusConfig:()=>OEt,Hono:()=>VEt,ImageFormat:()=>SEt,InvokeEndpointCommand:()=>AEt,InvokeEndpointWithResponseStreamCommand:()=>kEt,InvokeModelCommand:()=>CEt,Job:()=>FEt,ListFoundationModelsCommand:()=>wEt,MockAgent:()=>pSt,Pool:()=>aSt,Queue:()=>LEt,QueueScheduler:()=>UEt,Request:()=>eSt,Response:()=>tSt,SageMakerRuntimeClient:()=>xEt,TextToSpeechClient:()=>PEt,VertexAI:()=>REt,Webhook:()=>MEt,Worker:()=>$Et,convertToHtml:()=>HEt,cors:()=>WEt,createClient:()=>NEt,default:()=>vEt,extractRawText:()=>GEt,fetch:()=>QEt,getGlobalDispatcher:()=>dSt,interceptors:()=>mSt,logger:()=>JEt,parseBuffer:()=>jEt,request:()=>hSt,secureHeaders:()=>YEt,selectCover:()=>qEt,setGlobalDispatcher:()=>uSt,streamSSE:()=>ZEt,timeout:()=>XEt});var Jf,gs,vEt,_Et,wEt,TEt,bEt,EEt,SEt,CEt,xEt,AEt,kEt,IEt,REt,PEt,MEt,DEt,OEt,NEt,LEt,$Et,FEt,UEt,BEt,zEt,jEt,qEt,GEt,HEt,VEt,WEt,KEt,JEt,YEt,ZEt,XEt,QEt,eSt,tSt,rSt,nSt,oSt,sSt,iSt,aSt,lSt,cSt,uSt,dSt,pSt,mSt,hSt,SIr=C({"npm-stub:@aws-sdk/client-bedrock"(){Jf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Jf.get}):new Proxy(function(...r){return new Proxy({},{get:Jf.get})},{get:Jf.get,apply(r,n,o){return new Proxy({},{get:Jf.get})},construct(r,n){return new Proxy({},{get:Jf.get})}})}},gs=new Proxy({},Jf),vEt=gs,{BedrockClient:_Et,ListFoundationModelsCommand:wEt,BedrockRuntimeClient:TEt,ConverseCommand:bEt,ConverseStreamCommand:EEt,ImageFormat:SEt,InvokeModelCommand:CEt}=gs,{SageMakerRuntimeClient:xEt,InvokeEndpointCommand:AEt,InvokeEndpointWithResponseStreamCommand:kEt}=gs,{GoogleAuth:IEt,VertexAI:REt,TextToSpeechClient:PEt}=gs,{Webhook:MEt}=gs,{Hippocampus:DEt,HippocampusConfig:OEt}=gs,{createClient:NEt}=gs,{Queue:LEt,Worker:$Et,Job:FEt,QueueScheduler:UEt,FlowProducer:BEt}=gs,{Cron:zEt}=gs,{parseBuffer:jEt,selectCover:qEt}=gs,{extractRawText:GEt,convertToHtml:HEt}=gs,{Hono:VEt}=gs,{cors:WEt,HTTPException:KEt,logger:JEt,secureHeaders:YEt,streamSSE:ZEt,timeout:XEt}=gs,QEt=globalThis.fetch,eSt=globalThis.Request,tSt=globalThis.Response,rSt=globalThis.Headers,nSt=globalThis.FormData,oSt=globalThis.File,sSt=globalThis.Blob,iSt=gs.Agent,aSt=gs.Pool,lSt=gs.Client,cSt=gs.Dispatcher,uSt=()=>{},dSt=()=>gs,pSt=gs.MockAgent,mSt={redirect:()=>e=>e,retry:()=>e=>e},hSt=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 hY(){return await Promise.resolve().then(()=>(SIr(),yEt))}var fSt=C({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}}),gSt,CIr=C({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";aEt(),Xr(),Ib(),tc(),$o(),UM(),bIr(),Ct(),_i(),ct(),V(),em(),nM(),EIr(),ji(),Xt(),gEt(),fSt(),gSt=class $Xt extends fl{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=$Xt.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",h.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),h.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{h.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new nEt({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),h.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw h.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){const{BedrockClient:t,ListFoundationModelsCommand:r}=await hY(),n=new t({region:this.region});try{h.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;h.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){const s=o instanceof Error?o.message:String(o);h.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){h.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)){h.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=fEt(n,this.providerName,this.modelName),f=await eM(m,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(f)}else{h.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const d={role:"user",content:[{text:n.prompt}]};this.conversationHistory.push(d)}h.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||Ys,n=await this.resolveTurnTools(t.tools,t.disableTools),o=this.formatToolsForBedrock(n),s=Fc(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converse"),i=hEt({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}=Pf(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 h.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 lO.startActiveSpan("bedrock.tool.execute",{kind:$r.CLIENT,attributes:{"gen_ai.tool.name":r,"gen_ai.system":"aws.bedrock"}},async s=>{try{if(h.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=".",h.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),h.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);h.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:je.OK}),u}catch(i){throw h.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:i}),s.setStatus({code:je.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=Ls(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 h.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"?xS.JPEG:i==="png"?xS.PNG:i==="gif"?xS.GIF:xS.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?Bp.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 h.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),h.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),lO.startActiveSpan("bedrock.stream",{kind:$r.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async r=>{try{if(h.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)){h.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=fEt(t,this.providerName,this.modelName),i=await eM(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{h.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");const s={role:"user",content:[{text:t.input.text}]};this.conversationHistory.push(s)}h.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),h.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");const o=await this.streamingConversationLoop(t,r);return h.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),r.setStatus({code:je.OK}),r.end(),o}catch(n){h.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(h.debug("[TRACE] executeStream CATCH - checking if permission error"),h.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){h.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),h.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:je.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:je.OK}),r.end();const a=new ReadableStream({start(c){const d=(i.content||"").split(/(\s+)/);let m="";for(let f=0;f<d.length;f++)m+=d[f],(f===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:je.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||Ys,s=await this.resolveTurnTools(t.tools,t.disableTools),i=this.formatToolsForBedrock(s),a=Fc(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converseStream"),l=hEt({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:R=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(R),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(R=>{u=()=>{c=!0,R()}}),m={...l,executeStep:async(R,P,A)=>{const M=await l.executeStep(R,P,A);return u(),M}};r.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});const{stream:f,resultPromise:g}=Pf(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:t.abortSignal}),y=g.then(R=>({result:R,error:void 0}),R=>({result:void 0,error:R}));if(await Promise.race([d,y]),!c){const R=await y;if(R.error)throw R.error}const v=this.neurolink?.getEventEmitter(),w=this,b={startTime:n,streamId:`bedrock-${Date.now()}`};let T;const x=new Promise(R=>{T=R}),k=R=>{const P=R?.inputTokens??0,A=R?.outputTokens??0,M=R?.cacheReadTokens??0,N=R?.cacheWriteTokens??0;return{input:P,output:A,total:P+M+N+A,...M>0&&{cacheReadTokens:M},...N>0&&{cacheCreationTokens:N}}};return y.then(R=>{T(fv(this.providerName,this.modelName||this.getDefaultModel(),{usage:k(R.result?.usage)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let R=!1;try{yield*f}catch(P){throw R=!0,P}finally{const P=await y;P.error&&(R=!0);const A=k(P.result?.usage);P.result&&(w.conversationHistory=P.result.conversation,b.finishReason=P.result.finishReason,b.rawFinishReason=P.result.rawStopReason,r.setAttribute("gen_ai.response.stop_reason",P.result.rawStopReason??"unknown")),v&&v.emit("generation:end",{provider:w.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:A,model:w.modelName||w.getDefaultModel(),provider:w.providerName,finishReason:R?"error":P.result?.rawStopReason},success:!R})}}},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 hY(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{h.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(h.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(Ur(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}):(h.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 Bi(t,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:dr,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:Vs,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:bt,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:bt,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(t,r){const n=r||"amazon.titan-embed-text-v2:0";h.debug("Generating embedding",{provider:this.providerName,model:n,textLength:t.length});try{const o=JSON.stringify({inputText:t}),s=new iEt({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 h.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.embedding.length}),a.embedding}catch(o){throw h.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";h.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 h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw h.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:t.length}),this.handleProviderError(o)}}}}}),ySt={};ue(ySt,{AmazonBedrockProvider:()=>gSt,bedrockTracer:()=>lO,loadBedrockControl:()=>hY});var xIr=C({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";CIr(),gEt(),fSt()}}),vSt={};ue(vSt,{AzureOpenAIProvider:()=>_St});var _St,AIr=C({"src/lib/providers/azureOpenai.ts"(){"use strict";Ct(),V(),_i(),jo(),Sd(),yl(),Tm(),_St=class extends Fa{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",f=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||Pi(sQt()),d||Pi(iQt()),super("azure",e,t,{baseURL:d,apiKey:o}),this.azureDeployment=m,this.azureApiVersion=f,this.azureResourceOrigin=d,this.azureDeploymentPathPrefix=u,this.useMaxCompletionTokensOverride=y,h.shouldLog("debug")&&h.debug("Azure OpenAI Provider initialized",L5e({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:dr,message:"Invalid Azure OpenAI API key or endpoint."},...ns];return Bi(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??pyt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function kIr(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 IIr=C({"src/lib/utils/imageDetection.ts"(){"use strict"}});function wSt(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 RIr=C({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),cO,PIr=C({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs"(){cO=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}}}),MIr=C({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs"(){Xn()}});function fY(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var uO,gY,TSt=C({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs"(){MIr(),uO=e=>(uO=Array.isArray,uO(e)),gY=uO}});function*DIr(e){if(!e)return;if(yY 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():gY(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=gY(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 yY,bSt,OIr=C({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){TSt(),yY=Symbol.for("brand.privateNullableHeaders"),bSt=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[s,i]of DIr(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{[yY]:!0,values:t,nulls:r}}}});function NIr(e){const t=new gS(e);return delete t.batches,t}function LIr(e){const t=new ya(e);return delete t.messages.batches,t}var ESt,SSt,vY,CSt=C({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){XD(),$_t(),xM(),PIr(),TSt(),OIr(),XD(),ESt="vertex-2023-10-16",SSt=new Set(["/v1/messages","/v1/messages?beta=true"]),vY=class extends So{constructor({baseURL:e=cO("ANTHROPIC_VERTEX_BASE_URL"),region:t=cO("CLOUD_ML_REGION")??null,projectId:r=cO("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=NIr(this),this.beta=LIr(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 tW({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=bSt([r,e.headers])}async buildRequest(e){if(fY(e.body)&&(e.body={...e.body}),fY(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=ESt)),SSt.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(!fY(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)}}}}),_Y={};ue(_Y,{AnthropicVertex:()=>vY,BaseAnthropic:()=>So,default:()=>vY});var xSt=C({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){CSt(),CSt()}});async function $Ir(){return dO||(dO=await Promise.resolve().then(()=>(xSt(),_Y))),dO}function FIr(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 wY(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 UIr(e,t){const r=e.callParts,n=e.resultParts,o=Math.min(r.length,n.length);(o!==r.length||o!==n.length)&&h.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 BIr(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 TY(e){const t=[];let r=0;for(const n of FIr(e)){if(n.type==="regular"){wY(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:s}=UIr(n,r);o.length!==0&&(r++,wY(t,"assistant",o),wY(t,"user",s))}if(BIr(t),h.shouldLog("debug")){const n=t.flatMap(o=>Array.isArray(o.content)?o.content:[]);h.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 bY(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 Im(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"&&Im(n);if(e.items&&typeof e.items=="object")if(Array.isArray(e.items))for(const n of e.items)n&&typeof n=="object"&&Im(n);else Im(e.items);for(const n of["allOf","anyOf","oneOf"])if(Array.isArray(e[n]))for(const o of e[n])o&&typeof o=="object"&&Im(o)}function ASt(e,t,r){const n=vgt({contents:e,availableInputTokens:zc("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<=DSt?c:{functionResponse:{name:u.name,response:{result:yW(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:_W}]})}return e.length=0,e.push(...i),!0}function kSt(e,t,r){const n=Fbt({conversation:e,availableInputTokens:zc("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:$bt(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:tY}]})}return e.length=0,e.push(...i),!0}async function ISt(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,f=d.candidates?.[0],g=f?.finishReason;typeof g=="string"&&g&&(s=g);const y=f?.content;if(y&&Array.isArray(y.parts))for(const w of y.parts)n.push(w),typeof w.text=="string"&&w.text.length>0&&t.push({content:w.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 w=Math.min(v.cachedContentTokenCount??0,v.promptTokenCount);r.onUsageDelta?.("cacheRead",w-l),l=w}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 dO,RSt,pO,AS,EY,w0,Yf,PSt,MSt,mO,DSt,SY,zIr=C({"src/lib/providers/googleVertex/client.ts"(){"use strict";Wn(),Xr(),tc(),z7(),$M(),Ntt(),$o(),Zh(),PH(),kr(),Zn(),Ct(),_i(),ct(),qbt(),emt(),nM(),V(),wgt(),Ubt(),X9(),IIr(),Q9(),jo(),ji(),ogt(),jv(),Ra(),Tgt(),mgt(),UM(),Vv(),wW(),Ru(),G1(),cl(),Xt(),Bc(),Sd(),U1(),em(),RIr(),fM(),dO=null,RSt=()=>!0,pO=()=>Pi(TQt()),AS=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",EY=(e,t)=>{const r=t||AS();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||KR.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},w0=EY,Yf=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",PSt=()=>!!(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),MSt=async(e,t,r,n)=>{const o=e||AS();return{projectId:r?r.projectId?.trim()||"express":pO(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},mO=e=>e.toLowerCase().includes("claude"),DSt=2048,SY=class rn extends fl{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||PSt()||Pi(bQt()),this.projectId=s?.projectId||(i?"":pO()),this.location=o||s?.location||AS(),h.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),h.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return Yf()}async getAISDKModel(){throw new $e({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&&g9(t.input),t.input?.files?.length)try{await y9(t,100*1024*1024,this.providerName)}catch(r){h.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${r instanceof Error?r.message:String(r)}`)}await _E(t.input)}async executeStream(t,r){const n=t.model||this.modelName||Yf();return Y$e({name:"neurolink.provider.stream",tracer:Ve.provider,attributes:{[Oe.GEN_AI_SYSTEM]:this.providerName,[Oe.GEN_AI_MODEL]:n,[Oe.GEN_AI_OPERATION]:"stream",[Oe.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:Ve.provider,attributes:{[Oe.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;mO(n)?(h.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(i).length}),c=await this.executeNativeAnthropicStream(l)):(h.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){kgt("GoogleVertex");const r=this.resolveExpressApiKey(),n=r?"":pO(),o=t||this.location||AS(),i=(await Promise.resolve().then(()=>(HT(),Yy))).GoogleGenAI;if(!i)throw new $e({code:Xe.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const 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=Ls(s,"openApi3"),a=ln(i);a.$schema&&delete a.$schema;const l=Ti(a);Im(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),h.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=hje(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),h.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=Ls(s),a=ln(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),h.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=hje(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),h.info(`[GoogleVertex] Tool "${t}" resolved mid-turn via discovery \u2014 executing.`),o.get(t)}async executeNativeGemini3Stream(t){const r=t.model||this.modelName||Yf(),n=w0(r,t.region),o=await this.createVertexGenAIClient(n);h.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){h.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(const ne of a.pdfFiles){let xe;typeof ne=="string"?Lo.existsSync(ne)?xe=Lo.readFileSync(ne):xe=Buffer.from(ne,"base64"):xe=ne;const ae=xe.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:ae}})}}if(await pW(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){h.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(const ne of a.images){const xe=oE(ne);let ae,te="image/jpeg";if(typeof xe=="string")if(Lo.existsSync(xe)){ae=Lo.readFileSync(xe);const ie=aE(xe);te=ie.startsWith("image/")?ie:this.detectImageType(ae)}else if(xe.startsWith("data:")){const ie=xe.match(/^data:([^;]+);base64,(.+)$/);if(ie)te=ie[1],ae=Buffer.from(ie[2],"base64");else continue}else if(xe.startsWith("http://")||xe.startsWith("https://"))try{const ie=await fetch(xe);if(!ie.ok){h.warn(`[GoogleVertex] Image fetch failed: ${ie.status} ${ie.statusText}, skipping`,{url:sn(xe)});continue}const W=await ie.arrayBuffer();ae=Buffer.from(W);const ve=ie.headers.get("content-type");ve&&ve.startsWith("image/")&&(te=ve.split(";")[0])}catch(ie){h.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${ie instanceof Error?ie.message:String(ie)}`,{url:sn(xe)});continue}else ae=Buffer.from(xe,"base64"),te=this.detectImageType(ae);else ae=xe,te=this.detectImageType(ae);const ke=ae.toString("base64");i.push({inlineData:{mimeType:te,data:ke}})}}NM(s,t.conversationMessages),s.push({role:"user",parts:i});let l;const c=new Gv;let u;if(t.tools&&Object.keys(t.tools).length>0&&!t.disableTools){const ne=Wv(t.tools,"functionDeclarations");u=ne,l=ne.toolsConfig;for(const[xe,ae]of ne.executeMap)c.set(xe,ae);h.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ne.toolsConfig[0].functionDeclarations.length,toolNames:ne.toolsConfig[0].functionDeclarations.map(xe=>xe.name)})}const d=t;let m=!1;if(d.schema&&l){m=!0;const ne=Ls(d.schema,"openApi3"),xe=ln(ne);xe.$schema&&delete xe.$schema;const ae=Ti(xe),te=l[0]?.functionDeclarations||[];te.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:te}],h.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(ae),totalTools:te.length})}const f=Fc(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),g={...f.temperature!==void 0&&{temperature:f.temperature},maxOutputTokens:t.maxTokens};Z9(r)&&(g.maxOutputTokens&&g.maxOutputTokens>Na&&(h.warn(`[GoogleVertex] Capping maxOutputTokens from ${g.maxOutputTokens} to ${Na} for ${r}`),g.maxOutputTokens=Na),g.maxOutputTokens||(g.maxOutputTokens=Na)),f.topP!==void 0&&(g.topP=f.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+`
|
|
1130
1130
|
|
|
1131
1131
|
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=uW(t.thinkingConfig);if(v&&(g.thinkingConfig=v),(d.output?.format==="json"||d.schema)&&!m&&!l&&(g.responseMimeType="application/json",d.schema)){const ne=Ls(d.schema,"openApi3"),xe=ln(ne);xe.$schema&&delete xe.$schema;const ae=Ti(xe);Im(ae),g.responseSchema=ae,h.debug("[GoogleVertex] Added responseSchema for JSON output (stream)",{schemaKeys:Object.keys(ae)})}const w=Date.now(),b=t.maxSteps||Ys,T=Number.isFinite(b)&&b>0?Math.min(Math.floor(b),100):Math.min(Ys,100),x=[...s];let k="",I;const R=[],P=[];let A;const M=qv(Cd("vertex",r));let N=!1,O=0,D=0,$=0,F=0;const L=[],B=Fl(t.timeout)??sv,z=t.toolTimeoutMs??iv,j=t.turnTimeoutMs??B,K=new AbortController,Y=()=>K.abort();t.abortSignal?.addEventListener("abort",Y);const le=OM({turnTimeoutMs:t.turnTimeoutMs,defaultTurnTimeoutMs:B,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:ne=>{h.warn(ne==="timeout"?`[GoogleVertex] Native Gemini turn exceeded its ${j}ms time budget \u2014 aborting`:`[GoogleVertex] Native Gemini turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),K.abort()}}),Ce=K.signal;t.abortSignal?.aborted&&K.abort();let Q=!1,Z=!1,ee=!1,Re=0;try{const ne=FM({providerLabel:"GoogleVertex",maxSteps:T,toolFailureBreaker:{maxRetries:Hl,consecutive:!0,classifyResultFailure:ve=>hM(ve)??void 0},liveTools:t.tools??{},...u?{declarations:u}:{},...m?{finalResultToolName:"final_result",onTerminalResult:ve=>{try{A=JSON.parse(ve)}catch{}}}:{},enableMalformedRetry:!0,buildMalformedRetryNote:(ve,Ee)=>(this.emitTurnEvent({phase:"malformed-retry",step:Ee+1,maxSteps:T}),[...ve,{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:(ve,Ee)=>ISt(ve,Ee,{onProgress:()=>le.noteProgress(),onUsage:(Te,Ue)=>M.noteUsage(Te,Ue),onUsageDelta:(Te,Ue)=>{Te==="input"?O+=Ue:Te==="output"?D+=Ue:Te==="cacheRead"?$+=Ue:F+=Ue}}),planReclaim:ve=>{if(!M.shouldStop())return;const Ee=[...ve];return ASt(Ee,r,M.projectedNextPromptTokens)?(M.resetAfterReclaim(),{conversation:Ee}):(N=!0,h.warn(`[GoogleVertex] Gemini turn stopped by the context guard: projected prompt ~${M.projectedNextPromptTokens} tokens >= threshold ${M.thresholdTokens} \u2014 synthesizing a final answer.`),{stop:!0})},buildRequest:ve=>({model:r,contents:ve,config:{...g,...l?{tools:l}:{}}}),sendStep:async(ve,Ee)=>{le.noteProgress();const Te=ve;return o.models.generateContentStream({model:Te.model,contents:Te.contents,config:{...Te.config??{},abortSignal:Ee}})}}),xe={...ne,buildStepRequest:(ve,Ee)=>(Re=Ee+1,ne.buildStepRequest(ve,Ee)),buildToolResultMessages:(ve,Ee,Te,Ue)=>{const S=ne.buildToolResultMessages(ve,Ee,Te,Ue);if(le.shouldNudgeWrapup()){const me=S[S.length-1];me&&Array.isArray(me.parts)&&me.parts.push({text:MM(m)})}const q=PM(Ee.raw.rawResponseParts);Ft(this.handleToolExecutionStorage(Te.map((me,X)=>({toolName:me.name,args:me.args,...X===0&&q?{thoughtSignature:q}:{},stepIndex:Ue+1})),Te.map(me=>({toolName:me.name,output:me.output,stepIndex:Ue+1})),t,new Date),Kp,"tool storage write timed out").catch(me=>{h.warn("[GoogleVertex] Failed to store native Gemini stream tool executions",{error:me instanceof Error?me.message:String(me)})});try{const me=S[S.length-1];M.noteAppendedChars(JSON.stringify(me?.parts??[]).length)}catch{}return S}},{stream:ae,resultPromise:te}=Pf(xe,x,{tools:RM(u,t.tools,{toolTimeoutMs:z,abortSignal:Ce,onProgress:()=>le.noteProgress()}),abortSignal:Ce}),ke=(async()=>{for await(const ve of ae)ve.content&&L.push(ve.content)})();let ie,W;try{ie=await te}catch(ve){W=ve}if(await ke.catch(()=>{}),W!==void 0)if(Ce.aborted||Lu(W))Q=!0;else throw h.error("[GoogleVertex] Native SDK error",W),this.handleProviderError(W);if(ie){k=ie.text,I=ie.rawStopReason??I;for(const ve of ie.toolCalls)R.push({toolName:ve.name,args:ve.args});for(const ve of ie.toolExecutions)P.push({name:ve.name,input:ve.input,output:ve.output});x.length=0,x.push(...ie.conversation)}if(Ce.aborted&&(Q=!0),!k&&(Re>=T||Q||N)){Z=Re>=T&&!Q;const ve=R.filter(Ee=>Ee.toolName!=="final_result").length;if(L.length>0)h.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(Q)h.warn(`[GoogleVertex] Tool call loop ended mid-turn (${le.timedOut?"turn time limit":le.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),k=this.buildLoopExitMessage({turnClock:le,wasAborted:Q,stallTimeoutMs:t.stallTimeoutMs,maxSteps:T,toolCallCount:ve});else{h.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 Ee=await this.synthesizeFinalAnswerWithoutTools(o,r,g,x,m,Fl(t.timeout)??sv,Ce);Ee.text?(ee=!0,k=Ee.text,L.push(Ee.text),O+=Ee.inputTokens,D+=Ee.outputTokens,F+=Ee.reasoningTokens??0,Ee.finishReason&&(I=Ee.finishReason)):k=N?rc(ve):wm(T,ve)}}}finally{le.dispose(),t.abortSignal?.removeEventListener("abort",Y)}const we=Z&&!ee?"tool-calls":dW(I),pe=DM({timedOut:le.timedOut,stalled:le.stalled,wasAborted:Q,cappedWithoutAnswer:Z&&!ee,contextCappedWithoutAnswer:N&&!ee,finishReason:we});pe!=="completed"&&this.emitTurnEvent({phase:pe,step:Re,maxSteps:T,toolCallCount:R.filter(ne=>ne.toolName!=="final_result").length,elapsedMs:le.elapsedMs()});const G=Date.now()-w,re=A?[k]:L.length>0?L:[k];async function*ye(){for(const ne of re)ne.length>0&&(yield{content:ne})}const J=R.filter(ne=>ne.toolName!=="final_result"),oe=P.filter(ne=>ne.name!=="final_result"),Ae=Math.max(0,O-$),fe={stream:ye(),provider:this.providerName,model:r,finishReason:we,stopReason:pe,rawFinishReason:I,usage:{input:Ae,output:D+F,total:Ae+$+D+F,...$>0&&{cacheReadTokens:$},...F>0&&{reasoning:F}},toolCalls:J.map(ne=>({toolName:ne.toolName,args:ne.args})),toolsUsed:J.map(ne=>ne.toolName),toolExecutions:O1(oe),metadata:{streamId:`native-vertex-${Date.now()}`,startTime:w,responseTime:G,totalToolExecutions:J.length,stopReason:pe,rawFinishReason:I,stepsUsed:Re}};return A&&(fe.structuredOutput=A),fe}async executeNativeGemini3Generate(t){const r=t.model||this.modelName||Yf(),n=w0(r,t.region),o=await this.createVertexGenAIClient(n);h.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){h.debug(`[GoogleVertex] Processing ${l.pdfFiles.length} PDF file(s) for native generate`);for(const fe of l.pdfFiles){let ne;typeof fe=="string"?Lo.existsSync(fe)?ne=Lo.readFileSync(fe):ne=Buffer.from(fe,"base64"):ne=fe;const xe=ne.toString("base64");a.push({inlineData:{mimeType:"application/pdf",data:xe}})}}if(await pW(a,l?.nativeAudioFiles,"[GoogleVertex]"),l?.images&&l.images.length>0){h.debug(`[GoogleVertex] Processing ${l.images.length} image(s) for native generate`);for(const fe of l.images){const ne=oE(fe);let xe,ae="image/jpeg";if(typeof ne=="string")if(Lo.existsSync(ne)){xe=Lo.readFileSync(ne);const ke=aE(ne);ae=ke.startsWith("image/")?ke:this.detectImageType(xe)}else if(ne.startsWith("data:")){const ke=ne.match(/^data:([^;]+);base64,(.+)$/);if(ke)ae=ke[1],xe=Buffer.from(ke[2],"base64");else continue}else if(ne.startsWith("http://")||ne.startsWith("https://"))try{const ke=await fetch(ne);if(!ke.ok){h.warn(`[GoogleVertex] Image fetch failed: ${ke.status} ${ke.statusText}, skipping`,{url:sn(ne)});continue}const ie=await ke.arrayBuffer();xe=Buffer.from(ie);const W=ke.headers.get("content-type");W&&W.startsWith("image/")&&(ae=W.split(";")[0])}catch(ke){h.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${ke instanceof Error?ke.message:String(ke)}`,{url:sn(ne)});continue}else xe=Buffer.from(ne,"base64"),ae=this.detectImageType(xe);else xe=ne,ae=this.detectImageType(xe);const te=xe.toString("base64");a.push({inlineData:{mimeType:ae,data:te}})}}NM(i,t.conversationMessages),i.push({role:"user",parts:a});const c=t.disableTools?{}:t.tools||{};let u;const d=new Gv;let m;if(Object.keys(c).length>0){const fe=Wv(c,"functionDeclarations");m=fe,u=fe.toolsConfig;for(const[ne,xe]of fe.executeMap)d.set(ne,xe);h.debug("[GoogleVertex] Converted tools for native SDK generate",{toolCount:fe.toolsConfig[0].functionDeclarations.length,toolNames:fe.toolsConfig[0].functionDeclarations.map(ne=>ne.name)})}let f=!1;if(t.schema&&u){f=!0;const fe=Ls(t.schema,"openApi3"),ne=ln(fe);ne.$schema&&delete ne.$schema;const xe=Ti(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:xe}),u=[{functionDeclarations:ae}],h.debug("[GoogleVertex] Added final_result tool for structured output with tools (generate)",{schemaKeys:Object.keys(xe),totalTools:ae.length})}const g=Fc(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};Z9(r)&&(y.maxOutputTokens&&y.maxOutputTokens>Na&&(h.warn(`[GoogleVertex] Capping maxOutputTokens from ${y.maxOutputTokens} to ${Na} for ${r}`),y.maxOutputTokens=Na),y.maxOutputTokens||(y.maxOutputTokens=Na)),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||"";f&&(v=v+`
|
|
1132
1132
|
|
|
1133
1133
|
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.`),v&&(y.systemInstruction=v);const w=uW(t.thinkingConfig);if(w&&(y.thinkingConfig=w),(t.output?.format==="json"||t.schema)&&!f&&!u&&(y.responseMimeType="application/json",t.schema)){const fe=Ls(t.schema,"openApi3"),ne=ln(fe);ne.$schema&&delete ne.$schema;const xe=Ti(ne);Im(xe),y.responseSchema=xe,h.debug("[GoogleVertex] Added responseSchema for JSON output (generate)",{schemaKeys:Object.keys(xe)})}const b=Date.now(),T=t.maxSteps||Ys,x=Number.isFinite(T)&&T>0?Math.min(Math.floor(T),100):Math.min(Ys,100),k=[...i];let I="",R="",P;const A=[],M=[];let N;const O=qv(Cd("vertex",r));let D=!1,$=0,F=0,L=0,B=0;const z=Fl(t.timeout)??sv,j=t.toolTimeoutMs??iv,K=t.turnTimeoutMs??z,Y=new AbortController,le=()=>Y.abort();t.abortSignal?.addEventListener("abort",le);const Ce=OM({turnTimeoutMs:t.turnTimeoutMs,defaultTurnTimeoutMs:z,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:fe=>{h.warn(fe==="timeout"?`[GoogleVertex] Native Gemini turn exceeded its ${K}ms time budget \u2014 aborting`:`[GoogleVertex] Native Gemini turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),Y.abort()}}),Q=Y.signal;t.abortSignal?.aborted&&Y.abort();let Z=!1,ee=!1,Re=!1,we=0;try{const fe=FM({providerLabel:"GoogleVertex",maxSteps:x,toolFailureBreaker:{maxRetries:Hl,consecutive:!0,classifyResultFailure:ie=>hM(ie)??void 0},liveTools:t.tools??{},...m?{declarations:m}:{},...f?{finalResultToolName:"final_result",onTerminalResult:ie=>{try{N=JSON.parse(ie)}catch{}}}:{},enableMalformedRetry:!0,buildMalformedRetryNote:(ie,W)=>(this.emitTurnEvent({phase:"malformed-retry",step:W+1,maxSteps:x}),[...ie,{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:(ie,W)=>ISt(ie,W,{onProgress:()=>Ce.noteProgress(),onUsage:(ve,Ee)=>O.noteUsage(ve,Ee),onUsageDelta:(ve,Ee)=>{ve==="input"?$+=Ee:ve==="output"?F+=Ee:ve==="cacheRead"?L+=Ee:B+=Ee}}),planReclaim:ie=>{if(!O.shouldStop())return;const W=[...ie];return ASt(W,r,O.projectedNextPromptTokens)?(O.resetAfterReclaim(),{conversation:W}):(D=!0,h.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:ie=>({model:r,contents:ie,config:{...y,...u?{tools:u}:{}}}),sendStep:async(ie,W)=>{Ce.noteProgress();const ve=ie;return o.models.generateContentStream({model:ve.model,contents:ve.contents,config:{...ve.config??{},abortSignal:W}})}}),ne={...fe,buildStepRequest:(ie,W)=>(we=W+1,fe.buildStepRequest(ie,W)),buildToolResultMessages:(ie,W,ve,Ee)=>{const Te=fe.buildToolResultMessages(ie,W,ve,Ee);if(Ce.shouldNudgeWrapup()){const S=Te[Te.length-1];S&&Array.isArray(S.parts)&&S.parts.push({text:MM(f)})}const Ue=PM(W.raw.rawResponseParts);Ft(this.handleToolExecutionStorage(ve.map((S,q)=>({toolName:S.name,args:S.args,...q===0&&Ue?{thoughtSignature:Ue}:{},stepIndex:Ee+1})),ve.map(S=>({toolName:S.name,output:S.output,stepIndex:Ee+1})),t,new Date),Kp,"tool storage write timed out").catch(S=>{h.warn("[GoogleVertex] Failed to store native Gemini stream tool executions",{error:S instanceof Error?S.message:String(S)})});try{const S=Te[Te.length-1];O.noteAppendedChars(JSON.stringify(S?.parts??[]).length)}catch{}return Te}},{stream:xe,resultPromise:ae}=Pf(ne,k,{tools:RM(m,t.tools,{toolTimeoutMs:j,abortSignal:Q,onProgress:()=>Ce.noteProgress()}),abortSignal:Q}),te=(async()=>{for await(const ie of xe);})();let ke;try{ke=await ae}catch(ie){if(await te.catch(()=>{}),Q.aborted||Lu(ie))Z=!0;else throw h.error("[GoogleVertex] Native SDK error",ie),this.handleProviderError(ie)}if(await te,ke){I=ke.text,P=ke.rawStopReason??P;for(const ie of ke.toolCalls)A.push({toolName:ie.name,args:ie.args});for(const ie of ke.toolExecutions)M.push({name:ie.name,input:ie.input,output:ie.output});k.length=0,k.push(...ke.conversation)}if(Q.aborted&&(Z=!0),!I&&(we>=x||Z||D)){ee=we>=x&&!Z;const ie=A.filter(W=>W.toolName!=="final_result").length;if(R)h.warn(D?"[GoogleVertex] Generate tool call loop stopped by the context guard; returning text already gathered from prior steps.":`[GoogleVertex] Generate tool call loop terminated after reaching maxSteps (${x}); returning text already gathered from prior steps.`),I=R;else if(Z)h.warn(`[GoogleVertex] Generate tool call loop ended mid-turn (${Ce.timedOut?"turn time limit":Ce.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),I=this.buildLoopExitMessage({turnClock:Ce,wasAborted:Z,stallTimeoutMs:t.stallTimeoutMs,maxSteps:x,toolCallCount:ie});else{h.warn(D?"[GoogleVertex] Generate tool call loop stopped by the context guard with no text; synthesizing a final answer with tools disabled.":`[GoogleVertex] Generate tool call loop terminated after reaching maxSteps (${x}) with no text; synthesizing a final answer with tools disabled.`);const W=await this.synthesizeFinalAnswerWithoutTools(o,r,y,k,f,Fl(t.timeout)??sv,Q);W.text?(Re=!0,I=W.text,$+=W.inputTokens,F+=W.outputTokens,B+=W.reasoningTokens??0,W.finishReason&&(P=W.finishReason)):I=D?rc(ie):wm(x,ie)}}}finally{Ce.dispose(),t.abortSignal?.removeEventListener("abort",le)}const pe=ee&&!Re?"tool-calls":dW(P),G=DM({timedOut:Ce.timedOut,stalled:Ce.stalled,wasAborted:Z,cappedWithoutAnswer:ee&&!Re,contextCappedWithoutAnswer:D&&!Re,finishReason:pe});G!=="completed"&&this.emitTurnEvent({phase:G,step:we,maxSteps:x,toolCallCount:A.filter(fe=>fe.toolName!=="final_result").length,elapsedMs:Ce.elapsedMs()});const re=Date.now()-b,ye=A.filter(fe=>fe.toolName!=="final_result"),J=M.filter(fe=>fe.name!=="final_result"),oe=Math.max(0,$-L),Ae={content:I,provider:this.providerName,model:r,finishReason:pe,stopReason:G,rawFinishReason:P,stepsUsed:we,usage:{input:oe,output:F+B,total:oe+L+F+B,...L>0&&{cacheReadTokens:L},...B>0&&{reasoning:B}},...B>0&&{reasoningTokens:B},responseTime:re,toolsUsed:ye.map(fe=>fe.toolName),toolExecutions:$1(t,J),enhancedWithTools:ye.length>0};return N&&(Ae.structuredOutput=N),this.enhanceResult(Ae,t,b)}async synthesizeFinalAnswerWithoutTools(t,r,n,o,s,i,a){if(a?.aborted)return{text:"",inputTokens:0,outputTokens:0,reasoningTokens:0};try{const l={...n,...a?{abortSignal:a}:{}};if(delete l.tools,s){const c=typeof l.systemInstruction=="string"?l.systemInstruction:"";l.systemInstruction=c+`
|
|
1134
1134
|
|
|
1135
|
-
The final_result tool is no longer available. Provide your final answer directly as plain text now, using the information gathered so far.`}return await Ft((async()=>{const c=await t.models.generateContentStream({model:r,contents:o,config:l}),u=[];let d,m=0,f=0,g=0;for await(const v of c){const w=v,T=w.candidates?.[0],x=T?.finishReason;typeof x=="string"&&x&&(d=x);const k=T?.content;k&&Array.isArray(k.parts)&&u.push(...k.parts);const I=w.usageMetadata;I&&(I.promptTokenCount!==void 0&&I.promptTokenCount>0&&(m=I.promptTokenCount),I.candidatesTokenCount!==void 0&&I.candidatesTokenCount>0&&(f=I.candidatesTokenCount),I.thoughtsTokenCount!==void 0&&I.thoughtsTokenCount>0&&(g=I.thoughtsTokenCount))}return{text:u.filter(v=>typeof v.text=="string").map(v=>v.text).join(""),finishReason:d,inputTokens:m,outputTokens:f,reasoningTokens:g}})(),i,"Gemini synthesis call timed out")}catch(l){return h.warn("[GoogleVertex] Tools-disabled synthesis call failed; falling back to placeholder",{error:l instanceof Error?l.message:String(l)}),{text:"",inputTokens:0,outputTokens:0,reasoningTokens:0}}}async createAnthropicVertexClient(t){const r=await $Ir(),n=await MSt(this.location,t),
|
|
1135
|
+
The final_result tool is no longer available. Provide your final answer directly as plain text now, using the information gathered so far.`}return await Ft((async()=>{const c=await t.models.generateContentStream({model:r,contents:o,config:l}),u=[];let d,m=0,f=0,g=0;for await(const v of c){const w=v,T=w.candidates?.[0],x=T?.finishReason;typeof x=="string"&&x&&(d=x);const k=T?.content;k&&Array.isArray(k.parts)&&u.push(...k.parts);const I=w.usageMetadata;I&&(I.promptTokenCount!==void 0&&I.promptTokenCount>0&&(m=I.promptTokenCount),I.candidatesTokenCount!==void 0&&I.candidatesTokenCount>0&&(f=I.candidatesTokenCount),I.thoughtsTokenCount!==void 0&&I.thoughtsTokenCount>0&&(g=I.thoughtsTokenCount))}return{text:u.filter(v=>typeof v.text=="string").map(v=>v.text).join(""),finishReason:d,inputTokens:m,outputTokens:f,reasoningTokens:g}})(),i,"Gemini synthesis call timed out")}catch(l){return h.warn("[GoogleVertex] Tools-disabled synthesis call failed; falling back to placeholder",{error:l instanceof Error?l.message:String(l)}),{text:"",inputTokens:0,outputTokens:0,reasoningTokens:0}}}async createAnthropicVertexClient(t){const r=await $Ir(),n=this.resolveExpressApiKey(),o=this.baseURL?.trim()||process.env.GOOGLE_VERTEX_BASE_URL?.trim(),s=await MSt(this.location,t,n?{apiKey:n,...this.projectId?{projectId:this.projectId}:{}}:void 0,o),i=new r.AnthropicVertex(s),a=i;if("_authClientPromise"in a){const l=a._authClientPromise;l instanceof Promise&&l.catch(()=>{})}return i}async executeNativeAnthropicStream(t){const r=Uht(t.model||this.modelName||"claude-sonnet-4-5@20250929"),n=Date.now(),o=Fl(t.timeout)??3e5,s=await this.createAnthropicVertexClient(o);h.debug("[GoogleVertex] Using native @anthropic-ai/vertex-sdk for Claude stream",{model:r,project:this.projectId,location:this.location});const i=[];if(t.conversationMessages&&t.conversationMessages.length>0)i.push(...TY(t.conversationMessages));else if(t.conversationHistory&&t.conversationHistory.length>0)for(const pe of t.conversationHistory)(pe.role==="user"||pe.role==="assistant")&&i.push({role:pe.role,content:qp(pe.content)});const a=t.input,l=[];if(a?.pdfFiles&&a.pdfFiles.length>0){h.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native Anthropic stream`);for(const pe of a.pdfFiles){let G;typeof pe=="string"?Lo.existsSync(pe)?G=Lo.readFileSync(pe):G=Buffer.from(pe,"base64"):G=pe;const re=G.toString("base64");l.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:re}})}}if(a?.images&&a.images.length>0){h.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native Anthropic stream`);for(const pe of a.images){const G=oE(pe);let re,ye="image/jpeg";if(typeof G=="string")if(Lo.existsSync(G)){re=Lo.readFileSync(G);const oe=aE(G);ye=oe.startsWith("image/")?oe:this.detectImageType(re)}else if(G.startsWith("data:")){const oe=G.match(/^data:([^;]+);base64,(.+)$/);if(oe)ye=oe[1],re=Buffer.from(oe[2],"base64");else continue}else if(G.startsWith("http://")||G.startsWith("https://"))try{const oe=await fetch(G);if(!oe.ok){h.warn(`[GoogleVertex] Image fetch failed: ${oe.status} ${oe.statusText}, skipping`,{url:sn(G)});continue}const Ae=await oe.arrayBuffer();re=Buffer.from(Ae);const fe=oe.headers.get("content-type");fe&&fe.startsWith("image/")&&(ye=fe.split(";")[0])}catch(oe){h.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${oe instanceof Error?oe.message:String(oe)}`,{url:sn(G)});continue}else re=Buffer.from(G,"base64"),ye=this.detectImageType(re);else re=G,ye=this.detectImageType(re);const J=re.toString("base64");l.push({type:"image",source:{type:"base64",media_type:ye,data:J}})}}l.push({type:"text",text:a.text}),bY(i,l.length===1&&l[0].type==="text"?a.text:l);let c;const u=new Gv;if(t.tools&&Object.keys(t.tools).length>0&&!t.disableTools){c=[];for(const[pe,G]of Object.entries(t.tools))c.push(this.buildAnthropicToolDeclaration(pe,G)),G.execute&&u.set(pe,G.execute);h.debug("[GoogleVertex] Converted tools for native Anthropic SDK",{toolCount:c.length,toolNames:c.map(pe=>pe.name)})}const d=t;let m=!1,f="";if(d.schema){m=!0;const pe=Ls(d.schema),G=ln(pe);G.$schema&&delete G.$schema;const re=Ti(G),ye={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.",input_schema:{type:"object",properties:re.properties||re,required:re.required||[]}};c||(c=[]),c.push(ye),f=`
|
|
1136
1136
|
|
|
1137
1137
|
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.`,h.debug("[GoogleVertex] Added final_result tool for Anthropic structured output (stream)",{schemaKeys:Object.keys(re),totalTools:c.length})}const g=t.systemPrompt?t.systemPrompt+f:f?f.trim():void 0,y=Fc(this.providerName,r,{...t.temperature!==void 0&&{temperature:t.temperature},...t.topP!==void 0&&{topP:t.topP}},"vertex.anthropic.stream"),v={model:r,max_tokens:SM(r,t.maxTokens),messages:i,...c&&c.length>0&&{tools:c},...m&&{tool_choice:{type:"any"}},...g&&{system:g},...y.temperature!==void 0&&{temperature:y.temperature},...y.topP!==void 0&&{top_p:y.topP},...t.stopSequences&&t.stopSequences.length>0&&{stop_sequences:t.stopSequences}},w=t.maxSteps||Ys,b=m?Math.max(w-1,0):w,T=[],x=[],k=Hv(),I={input:0,output:0,total:0},R={streamId:`native-anthropic-vertex-${Date.now()}`,startTime:n,responseTime:0,totalToolExecutions:0},P=[],A={},M={},N={},O={},D=(c??[]).map(pe=>pe.name),$=ss({system:g,messages:wSt(i)}),F=Ve.provider.startSpan("anthropic.vertex.stream",{kind:$r.CLIENT,attributes:{[an.OBSERVATION_TYPE]:"span",[Oe.GEN_AI_SYSTEM]:"anthropic",[Oe.GEN_AI_MODEL]:r,[Oe.GEN_AI_OPERATION]:"stream",[Oe.NL_PROVIDER]:this.providerName,[Oe.NL_TOOL_COUNT]:D.length,[an.OBSERVATION_INPUT]:$,[an.TRACE_INPUT]:$,[an.OBSERVATION_METADATA]:ss({toolsOffered:D,toolCount:D.length,maxSteps:w,structuredOutput:m})}}),L=vt.setSpan(Tr.active(),F);let B="",z=0;const j={read:0,creation:0,creation5m:0,creation1h:0};let K;const Y=()=>{try{K?.controller.abort()}catch{}},le=new AbortController;le.signal.addEventListener("abort",Y);const Ce=()=>le.abort();t.abortSignal?.addEventListener("abort",Ce),t.abortSignal?.aborted&&le.abort();const Q=t.toolTimeoutMs??iv,Z=t.turnTimeoutMs??o,ee=OM({turnTimeoutMs:t.turnTimeoutMs,defaultTurnTimeoutMs:o,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:pe=>{h.warn(pe==="timeout"?`[GoogleVertex] Anthropic stream turn exceeded its ${Z}ms time budget \u2014 aborting`:`[GoogleVertex] Anthropic stream turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),le.abort()}});(async()=>{let pe=0;const G=[...i];let re=!1,ye=!1,J=!1,oe=!1,Ae=!1,fe;const ne=qv(Cd("vertex",r)),xe=new Map;try{for(;pe<b;){if(le.signal.aborted){re=!0;break}if(ne.shouldStop())if(kSt(G,r,ne.projectedNextPromptTokens))ne.resetAfterReclaim();else{J=!0,h.warn(`[GoogleVertex] Anthropic stream turn stopped by the context guard: projected prompt ~${ne.projectedNextPromptTokens} tokens >= threshold ${ne.thresholdTokens} (step ${pe}) \u2014 synthesizing a final answer.`);break}pe++,ee.noteProgress(),this.refreshAnthropicToolDeclarations(t.tools,c,u,xe);const W=Ve.generation.startSpan("anthropic.messages.stream",{kind:$r.CLIENT,attributes:{[an.OBSERVATION_TYPE]:"generation",[an.OBSERVATION_MODEL_NAME]:r,[an.OBSERVATION_MODEL_PARAMETERS]:ss({max_tokens:v.max_tokens,temperature:v.temperature,top_p:v.top_p}),[an.OBSERVATION_INPUT]:ss({system:g,messages:wSt(G)}),[an.OBSERVATION_METADATA]:ss({step:pe,toolsOffered:D.length}),[Oe.GEN_AI_SYSTEM]:"anthropic",[Oe.GEN_AI_MODEL]:r,[Oe.GEN_AI_OPERATION]:"chat"}},L);let ve;try{const X=_0({system:g,tools:c,messages:G}),ge=await s.messages.stream({...v,...X.system!==void 0&&{system:X.system},...X.tools&&X.tools.length>0&&{tools:X.tools},messages:X.messages});K=ge;let Ie=!1;ge.on("text",U=>{ee.noteProgress(),U.length>0&&(Ie||(Ie=!0,W.setAttribute(an.OBSERVATION_COMPLETION_START_TIME,new Date().toISOString())),k.push({content:U}),z+=U.length)}),ve=await ge.finalMessage()}catch(X){if(W.setStatus({code:je.ERROR,message:X instanceof Error?X.message:String(X)}),X instanceof Error&&W.recordException(X),W.end(),le.signal.aborted||Lu(X)){K=void 0,re=!0;break}throw X}K=void 0;try{const X=ve.usage?.cache_read_input_tokens??0,ge=ve.usage?.cache_creation_input_tokens??0,Ie=ve.usage?.cache_creation?.ephemeral_5m_input_tokens??0,U=ve.usage?.cache_creation?.ephemeral_1h_input_tokens??0;j.read+=X,j.creation+=ge,j.creation5m+=Ie,j.creation1h+=U,I.input+=ve.usage?.input_tokens||0,I.output+=ve.usage?.output_tokens||0,I.total=I.input+I.output+j.read+j.creation,fe=ve.stop_reason,ne.noteUsage((ve.usage?.input_tokens||0)+X+ge,ve.usage?.output_tokens||0);for(const he of ve.content)he.type==="text"&&typeof he.text=="string"&&(B+=he.text);W.setAttribute(an.OBSERVATION_OUTPUT,ss(ve.content)),W.setAttribute(an.OBSERVATION_USAGE_DETAILS,ss({input:ve.usage?.input_tokens??0,output:ve.usage?.output_tokens??0,input_cached_tokens:X,input_cache_creation_5m:Ie,input_cache_creation_1h:U,total:(ve.usage?.input_tokens??0)+(ve.usage?.output_tokens??0)+X+Ie+U})),W.setAttribute(Oe.GEN_AI_INPUT_TOKENS,ve.usage?.input_tokens??0),W.setAttribute(Oe.GEN_AI_OUTPUT_TOKENS,ve.usage?.output_tokens??0),ve.stop_reason&&W.setAttribute(Oe.GEN_AI_FINISH_REASON,ve.stop_reason),W.setStatus({code:je.OK})}finally{W.end()}const Ee=ve.content.filter(X=>X.type==="tool_use");if(m){const X=Ee.find(ge=>ge.name==="final_result");if(X){A.value=X.input,k.push({content:JSON.stringify(X.input)}),Ae=!0,h.debug("[GoogleVertex] Extracted structured output from final_result tool (stream)",{keys:Object.keys(X.input)});break}}if(Ee.length===0){Ae=!0;break}const Te=[],Ue=[],S=[];for(const X of Ee){if(le.signal.aborted){re=!0;break}T.push({toolName:X.name,args:X.input}),P.push(X.name),Ue.push({toolCallId:X.id,toolName:X.name,args:X.input});const ge=xe.get(X.name);if(ge&&ge.count>=Hl){h.warn(`[GoogleVertex] Tool "${X.name}" has exceeded retry limit (${Hl}), skipping execution`);const Me=`TOOL_PERMANENTLY_FAILED: The tool "${X.name}" has failed ${ge.count} times and will not be retried. Last error: ${ge.lastError}. Please proceed without using this tool or inform the user that this functionality is unavailable.`,se={error:Me};x.push({name:X.name,input:X.input,output:se}),Te.push({type:"tool_result",tool_use_id:X.id,content:Me}),S.push({toolCallId:X.id,toolName:X.name,output:se});continue}const Ie=Ve.mcp.startSpan("ai.toolCall",{kind:$r.INTERNAL,attributes:{[an.OBSERVATION_TYPE]:"tool",[Oe.GEN_AI_TOOL_NAME]:X.name,"ai.toolCall.name":X.name,"ai.toolCall.id":X.id,"ai.toolCall.args":ss(X.input,2e4),[an.OBSERVATION_INPUT]:ss(X.input,2e4),[an.OBSERVATION_METADATA]:ss({step:pe})}},L),U=(Me,se)=>{Ie.setAttribute("ai.toolCall.result",ss(Me)),Ie.setAttribute(an.OBSERVATION_OUTPUT,ss(Me)),se?(Ie.setAttribute(an.OBSERVATION_LEVEL,"ERROR"),Ie.setAttribute(an.OBSERVATION_STATUS_MESSAGE,se),Ie.setStatus({code:je.ERROR,message:se})):Ie.setStatus({code:je.OK}),Ie.end()};let he=u.get(X.name);if(he||(he=this.resolveAnthropicToolOnMiss(X.name,t.tools,c,u,xe)),he)try{const Me={toolCallId:X.id,messages:[],abortSignal:le.signal};ee.noteProgress();const se=await Ft(dR(Tr.with(vt.setSpan(L,Ie),()=>Promise.resolve(he(X.input,Me))),le.signal),Q,`Tool "${X.name}" execution timed out after ${Q}ms`);ee.noteProgress(),U(se,Vmt(se));const Se=hM(se);if(Se){const De=xe.get(X.name)||{count:0,lastError:""};De.count++,De.lastError=Se,xe.set(X.name,De)}else xe.delete(X.name);x.push({name:X.name,input:X.input,output:se});const Pe=typeof se=="string"?se:qp(se??null);Te.push({type:"tool_result",tool_use_id:X.id,content:Pe}),S.push({toolCallId:X.id,toolName:X.name,output:se})}catch(Me){if(le.signal.aborted||Lu(Me)){U({aborted:!0}),S.push({toolCallId:X.id,toolName:X.name,output:{aborted:!0}}),re=!0;break}ee.noteProgress(),Me instanceof _d&&this.emitTurnEvent({phase:"tool-timeout",step:pe,maxSteps:w,toolName:X.name});const se=Me instanceof Error?Me.message:String(Me),Se=xe.get(X.name)||{count:0,lastError:""};Se.count++,Se.lastError=se,xe.set(X.name,Se),h.warn(`[GoogleVertex] Tool "${X.name}" failed (attempt ${Se.count}/${Hl}): ${se}`);const Pe=`Error executing tool "${X.name}": ${se}`,De={error:Pe};U(De,Pe),x.push({name:X.name,input:X.input,output:De}),Te.push({type:"tool_result",tool_use_id:X.id,content:Pe}),S.push({toolCallId:X.id,toolName:X.name,output:De})}else{const Me=`TOOL_NOT_FOUND: The tool "${X.name}" does not exist.`,se={error:Me},Se=xe.get(X.name)||{count:0,lastError:""};Se.count++,Se.lastError=Me,xe.set(X.name,Se),U(se,Me),x.push({name:X.name,input:X.input,output:se}),Te.push({type:"tool_result",tool_use_id:X.id,content:Me}),S.push({toolCallId:X.id,toolName:X.name,output:se})}}if((Ue.length>0||S.length>0)&&Ft(this.handleToolExecutionStorage(Ue.map(X=>({...X,stepIndex:pe})),S.map(X=>({...X,stepIndex:pe})),t,new Date),Kp,"tool storage write timed out").catch(X=>{h.warn("[GoogleVertex] Failed to store native Anthropic stream tool executions",{error:X instanceof Error?X.message:String(X)})}),re)break;const q=b-pe;q>0&&q<=3?Te.push({type:"text",text:`NOTE: Only ${q} tool step(s) remain. Consolidate what you have and `+(m?"call final_result with your best answer.":"provide your final answer.")}):ee.shouldNudgeWrapup()&&Te.push({type:"text",text:MM(m)});const me=ve.content.filter(X=>X.type!=="server_tool_use");G.push({role:"assistant",content:me}),G.push({role:"user",content:Te}),ne.noteAppendedChars(Te.reduce((X,ge)=>X+("content"in ge?ge.content.length:ge.text.length),0))}if(!Ae){le.signal.aborted&&(re=!0);const W=T.filter(Ee=>Ee.toolName!=="final_result").length,ve=Math.max(1024,Math.min(v.max_tokens,Cd("vertex",r)-ne.projectedNextPromptTokens-4e3));if(re){if(h.warn(`[GoogleVertex] Native Anthropic stream loop ended mid-turn (${ee.timedOut?"turn time limit":ee.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),B.length===0&&z===0&&!A.value){const Ee=this.buildLoopExitMessage({turnClock:ee,wasAborted:re,stallTimeoutMs:t.stallTimeoutMs,maxSteps:w,toolCallCount:W});k.push({content:Ee}),B=Ee}}else if(m){J||(ye=!0),h.warn(J?"[GoogleVertex] Native Anthropic stream loop stopped by the context guard without final_result; forcing a finalization call.":`[GoogleVertex] Native Anthropic stream loop reached maxSteps (${w}) without final_result; forcing a finalization call.`);try{const Ee=_0({system:g,tools:c,messages:G}),Te=await s.messages.stream({...v,max_tokens:ve,tool_choice:{type:"tool",name:"final_result"},...Ee.system!==void 0&&{system:Ee.system},...Ee.tools&&Ee.tools.length>0&&{tools:Ee.tools},messages:Ee.messages});K=Te;const Ue=await Te.finalMessage();K=void 0,I.input+=Ue.usage?.input_tokens||0,I.output+=Ue.usage?.output_tokens||0,j.read+=Ue.usage?.cache_read_input_tokens??0,j.creation+=Ue.usage?.cache_creation_input_tokens??0,j.creation5m+=Ue.usage?.cache_creation?.ephemeral_5m_input_tokens??0,j.creation1h+=Ue.usage?.cache_creation?.ephemeral_1h_input_tokens??0,I.total=I.input+I.output+j.read+j.creation,fe=Ue.stop_reason;const S=Ue.content.find(q=>q.type==="tool_use"&&q.name==="final_result");if(S)A.value=S.input,k.push({content:JSON.stringify(S.input)}),oe=!0,h.debug("[GoogleVertex] Forced finalization returned structured output (stream)",{keys:Object.keys(S.input)});else{const q=J?rc(W):wm(w,W);k.push({content:q}),B+=q}}catch(Ee){K=void 0,(le.signal.aborted||Lu(Ee))&&(ye=!1,re=!0),h.warn("[GoogleVertex] Forced finalization call failed; falling back to a terminal message",{error:Ee instanceof Error?Ee.message:String(Ee)});const Te=J&&!re?rc(W):this.buildLoopExitMessage({turnClock:ee,wasAborted:re,stallTimeoutMs:t.stallTimeoutMs,maxSteps:w,toolCallCount:W});k.push({content:Te}),B+=Te}}else if(J||(ye=!0),B.length===0){h.warn(J?"[GoogleVertex] Native Anthropic stream loop stopped by the context guard with no text; synthesizing a final answer with tools disabled.":`[GoogleVertex] Native Anthropic stream loop reached maxSteps (${w}) with no text; synthesizing a final answer with tools disabled.`);try{const Ee=(g?g+`
|
|
1138
1138
|
|
|
@@ -373,9 +373,19 @@ const hasGoogleCredentials = () => {
|
|
|
373
373
|
process.env.GOOGLE_AUTH_PRIVATE_KEY));
|
|
374
374
|
};
|
|
375
375
|
// Create Anthropic-specific Vertex settings for native @anthropic-ai/vertex-sdk
|
|
376
|
-
const createVertexAnthropicSettings = async (region, timeoutMs) => {
|
|
376
|
+
const createVertexAnthropicSettings = async (region, timeoutMs, direct, baseURL) => {
|
|
377
377
|
const location = region || getVertexLocation();
|
|
378
|
-
|
|
378
|
+
// Express-style auth carries its own credentials, so the ADC-derived project
|
|
379
|
+
// is neither available nor needed; asking for it would throw before the
|
|
380
|
+
// request is ever built. It cannot be EMPTY either — the SDK rejects a
|
|
381
|
+
// falsy projectId outright ("No projectId was given and it could not be
|
|
382
|
+
// resolved from credentials") — so a configured project is used when there
|
|
383
|
+
// is one and a placeholder stands in otherwise. The value only ever appears
|
|
384
|
+
// in the request path, which an endpoint reached this way is expected to
|
|
385
|
+
// route on its own.
|
|
386
|
+
const project = direct
|
|
387
|
+
? direct.projectId?.trim() || "express"
|
|
388
|
+
: getVertexProjectId();
|
|
379
389
|
return {
|
|
380
390
|
projectId: project,
|
|
381
391
|
region: location,
|
|
@@ -384,6 +394,26 @@ const createVertexAnthropicSettings = async (region, timeoutMs) => {
|
|
|
384
394
|
// bound (a 429 with retry-after: 8549 sleeps 2.4h per retry, invisible
|
|
385
395
|
// to fallback orchestration). Retries are the orchestrator's job.
|
|
386
396
|
maxRetries: 0,
|
|
397
|
+
// Outside the express branch too: an endpoint override is about WHERE the
|
|
398
|
+
// request goes, not how it is authenticated, so a caller using ADC against
|
|
399
|
+
// a gateway needs it just as much.
|
|
400
|
+
...(baseURL ? { baseURL } : {}),
|
|
401
|
+
...(direct
|
|
402
|
+
? {
|
|
403
|
+
// The token goes on the request directly. `accessToken` on the SDK's
|
|
404
|
+
// own options looks like it should do this and does not — the client
|
|
405
|
+
// stores it and never reads it for auth, so prepareOptions() still
|
|
406
|
+
// awaits Application Default Credentials and the call fails with a
|
|
407
|
+
// credentials error that names nothing useful. `authClient` is the
|
|
408
|
+
// option the SDK actually consults.
|
|
409
|
+
authClient: {
|
|
410
|
+
getRequestHeaders: async () => ({
|
|
411
|
+
Authorization: `Bearer ${direct.apiKey}`,
|
|
412
|
+
}),
|
|
413
|
+
projectId: null,
|
|
414
|
+
},
|
|
415
|
+
}
|
|
416
|
+
: {}),
|
|
387
417
|
};
|
|
388
418
|
};
|
|
389
419
|
// Helper function to determine if a model is an Anthropic model
|
|
@@ -2844,7 +2874,20 @@ export class GoogleVertexProvider extends BaseProvider {
|
|
|
2844
2874
|
*/
|
|
2845
2875
|
async createAnthropicVertexClient(timeoutMs) {
|
|
2846
2876
|
const mod = await getAnthropicVertexModule();
|
|
2847
|
-
const
|
|
2877
|
+
const expressApiKey = this.resolveExpressApiKey();
|
|
2878
|
+
const directBaseURL = this.baseURL?.trim() || process.env.GOOGLE_VERTEX_BASE_URL?.trim();
|
|
2879
|
+
const settings = await createVertexAnthropicSettings(this.location, timeoutMs, expressApiKey
|
|
2880
|
+
? {
|
|
2881
|
+
apiKey: expressApiKey,
|
|
2882
|
+
...(this.projectId ? { projectId: this.projectId } : {}),
|
|
2883
|
+
}
|
|
2884
|
+
: undefined, directBaseURL);
|
|
2885
|
+
// One assertion, at the one place the shapes genuinely differ. The SDK
|
|
2886
|
+
// declares `authClient` as its full `AuthClient` (24-plus members) while
|
|
2887
|
+
// `prepareOptions()` only ever calls `getRequestHeaders()` and reads
|
|
2888
|
+
// `projectId`. Naming the narrow surface in our own type and widening it
|
|
2889
|
+
// here is the honest version of that gap; the alternative is standing up a
|
|
2890
|
+
// real AuthClient to satisfy a contract the SDK does not exercise.
|
|
2848
2891
|
const client = new mod.AnthropicVertex(settings);
|
|
2849
2892
|
// The vertex SDK eagerly starts Google ADC resolution in its constructor
|
|
2850
2893
|
// (`this._authClientPromise = this._auth.getClient()`) and only awaits it
|
|
@@ -1052,6 +1052,18 @@ export type GoogleVertexProviderSettings = {
|
|
|
1052
1052
|
* Anthropic Vertex AI settings for Claude models on Vertex
|
|
1053
1053
|
* Used with @anthropic-ai/vertex-sdk
|
|
1054
1054
|
*/
|
|
1055
|
+
/**
|
|
1056
|
+
* The two members `@anthropic-ai/vertex-sdk` actually uses off an auth client.
|
|
1057
|
+
*
|
|
1058
|
+
* Its declared `AuthClient` is far wider, but `prepareOptions()` only ever
|
|
1059
|
+
* awaits `getRequestHeaders()` and reads `projectId` (client.js:109-111).
|
|
1060
|
+
* Naming that narrow surface is what lets a caller supply a token directly
|
|
1061
|
+
* instead of standing up Application Default Credentials.
|
|
1062
|
+
*/
|
|
1063
|
+
export type VertexAnthropicAuthClient = {
|
|
1064
|
+
getRequestHeaders: () => Promise<Record<string, string>>;
|
|
1065
|
+
projectId?: string | null;
|
|
1066
|
+
};
|
|
1055
1067
|
export type AnthropicVertexSettings = {
|
|
1056
1068
|
/** Google Cloud project ID */
|
|
1057
1069
|
projectId: string;
|
|
@@ -1061,6 +1073,22 @@ export type AnthropicVertexSettings = {
|
|
|
1061
1073
|
timeout?: number;
|
|
1062
1074
|
/** SDK-internal retry budget (transport retries are the orchestrator's job) */
|
|
1063
1075
|
maxRetries?: number;
|
|
1076
|
+
/**
|
|
1077
|
+
* Endpoint override. The SDK derives
|
|
1078
|
+
* `https://${region}-aiplatform.googleapis.com/v1` by default; a gateway or
|
|
1079
|
+
* a compatible endpoint is reached by setting this instead.
|
|
1080
|
+
*/
|
|
1081
|
+
baseURL?: string;
|
|
1082
|
+
/**
|
|
1083
|
+
* Supply the request credentials directly, bypassing Application Default
|
|
1084
|
+
* Credentials.
|
|
1085
|
+
*
|
|
1086
|
+
* Note that `accessToken` on the SDK's own options does NOT do this: the
|
|
1087
|
+
* client stores it and never reads it for auth, so `prepareOptions()` still
|
|
1088
|
+
* awaits ADC and a token-only caller fails with a credentials error that
|
|
1089
|
+
* names nothing useful. `authClient` is the option that actually works.
|
|
1090
|
+
*/
|
|
1091
|
+
authClient?: VertexAnthropicAuthClient;
|
|
1064
1092
|
};
|
|
1065
1093
|
/**
|
|
1066
1094
|
* OpenAI-compatible models endpoint response structure
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "11.
|
|
3
|
+
"version": "11.16.0",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
|
|
6
6
|
"author": {
|
|
@@ -211,7 +211,8 @@
|
|
|
211
211
|
"test:sagemaker-streaming": "tsx test/continuous-test-suite-sagemaker-streaming.ts",
|
|
212
212
|
"test:anthropic-loop-characterization": "tsx test/continuous-test-suite-anthropic-loop-characterization.ts",
|
|
213
213
|
"test:aistudio-loop-characterization": "tsx test/continuous-test-suite-aistudio-loop-characterization.ts",
|
|
214
|
-
"test:docs-mcp": "npx tsx test/continuous-test-suite-docs-mcp.ts"
|
|
214
|
+
"test:docs-mcp": "npx tsx test/continuous-test-suite-docs-mcp.ts",
|
|
215
|
+
"test:vertex-claude-characterization": "tsx test/continuous-test-suite-vertex-claude-characterization.ts"
|
|
215
216
|
},
|
|
216
217
|
"files": [
|
|
217
218
|
"dist",
|