@juspay/neurolink 11.10.0 → 11.11.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 +6 -2
- package/dist/browser/neurolink.min.js +1 -1
- package/dist/core/loopEngine.js +7 -0
- package/dist/lib/core/loopEngine.js +7 -0
- package/dist/lib/providers/anthropic/loopAdapter.js +12 -2
- package/dist/lib/types/loopEngine.d.ts +14 -0
- package/dist/providers/anthropic/loopAdapter.js +12 -2
- package/dist/types/loopEngine.d.ts +14 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
|
-
## [11.
|
|
1
|
+
## [11.11.0](https://github.com/juspay/neurolink/compare/v11.10.0...v11.11.0) (2026-08-21)
|
|
2
2
|
|
|
3
3
|
### Features
|
|
4
4
|
|
|
5
|
-
- **(core):**
|
|
5
|
+
- **(core):** carry tool-call id and error on loop tool executions ([d5f0be6](https://github.com/juspay/neurolink/commit/d5f0be66ec1566eaa2de6e61aa8ab826a4f48334))
|
|
6
|
+
|
|
7
|
+
### Bug Fixes
|
|
8
|
+
|
|
9
|
+
- **(anthropic):** keep truncated final_result payloads verbatim in the loop adapter ([65c74e7](https://github.com/juspay/neurolink/commit/65c74e71fa1584c7f823a45133f9f2ae8d3278f3))
|
|
6
10
|
|
|
7
11
|
## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
|
|
8
12
|
|
|
@@ -1126,7 +1126,7 @@ ${t[0].text}`;let n=t.length-1;t[n].text=`${t[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.`});var $Be,Pq,zSr,BBe,jSr,GSr,zBe,jBe,qSr,GBe,Mse,qBe=E(()=>{"use strict";loe();gr();ro();_d();Qr();NE();eu();cs();hne();yse();gBe();so();_Be();Dt();ea();X();bse();$d();gi();Hr();_se();Dd();Xw();PBe();Ko();_l();yne();XB();Np();Pj();Ea();jj();Qm();DBe();dg();Ag();Kv();rG();kse();Bre();FBe();yse();$Be=()=>an(iye()),Pq=()=>ln("ANTHROPIC_MODEL","claude-sonnet-4-6"),zSr=pt.getTracer("neurolink.provider.anthropic"),BBe=()=>{try{let e=Fr(Op(),".neurolink","anthropic-credentials.json");if(to(e)){let t=Gc(e,"utf-8"),n=JSON.parse(t);if(n.type==="oauth"&&n.oauth?.accessToken)return g.debug("[AnthropicProvider] Using OAuth token from stored credentials file"),n.oauth}}catch(e){g.debug("[AnthropicProvider] Failed to read stored credentials:",e)}let r=process.env.ANTHROPIC_OAUTH_TOKEN||process.env.CLAUDE_OAUTH_TOKEN;if(!r)return null;try{let e=JSON.parse(r);if(typeof e=="object"&&e.accessToken)return e;if(typeof e=="string")return{accessToken:e}}catch{}return{accessToken:r}},jSr=r=>{let e=process.env.ANTHROPIC_SUBSCRIPTION_TIER?.toLowerCase();if(e){let t=["free","pro","max","max_5","max_20","api"];if(t.includes(e))return g.debug("[detectSubscriptionTier] Using environment override",{tier:e}),e;g.warn("[detectSubscriptionTier] Invalid ANTHROPIC_SUBSCRIPTION_TIER",{value:e,validTiers:t})}if(r){let t=r.scopes??[],n="pro";return t.includes("max_20")?n="max_20":t.includes("max_5")?n="max_5":t.includes("max")&&(n="max"),g.debug("[detectSubscriptionTier] Detected from OAuth token",{tier:n,scopes:t}),n}return g.debug("[detectSubscriptionTier] No OAuth token, defaulting to API tier"),"api"},GSr=r=>{let e=process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase();if(e==="api_key"||e==="apikey")return g.debug("[detectAuthMethod] Forced to api_key by ANTHROPIC_AUTH_METHOD env var"),"api_key";if(e==="oauth"){if(r)return g.debug("[detectAuthMethod] Forced to oauth by ANTHROPIC_AUTH_METHOD env var"),"oauth";g.warn("[detectAuthMethod] ANTHROPIC_AUTH_METHOD=oauth but no OAuth token found; falling through to auto-detection")}else e&&g.warn("[detectAuthMethod] Unrecognized ANTHROPIC_AUTH_METHOD value; falling through to auto-detection",{value:e});let t=r?"oauth":"api_key";return g.debug("[detectAuthMethod] Auth method resolved",{method:t,hasOAuthToken:!!r}),t},zBe=r=>{let e=[],t=[],n=i=>Array.isArray(i)?i:[i],o=(i,a)=>{let l=om(a);if(l&&i.length>0){let c=i[i.length-1];c.cache_control=l}};for(let i of r)switch(i.role){case"system":{let a=typeof i.content=="string"?i.content:n(i.content).map(c=>typeof c=="string"?c:String(c?.text??"")).join(`
|
|
1127
1127
|
`),l=om(i);e.push({type:"text",text:a,...l?{cache_control:l}:{}});break}case"user":{let a=[];for(let l of n(i.content)){if(typeof l=="string"){l.length>0&&a.push({type:"text",text:l});continue}let c=l;if(c?.type==="text"&&typeof c.text=="string"){let u=om(c);a.push({type:"text",text:c.text,...u?{cache_control:u}:{}})}else if(c?.type==="image"||c?.type==="image_url"){let u=pM(c.image??c.data??c.url);if(u){let p=om(c);a.push(p?{...u,cache_control:p}:u)}}else if(c?.type==="file"){let p=typeof c=="object"&&c!==null&&("mediaType"in c?typeof c.mediaType=="string":!0)?LBe(c):void 0;if(p){let m=om(c);m&&(p.cache_control=m),a.push(p)}}}a.length>0&&(o(a,i),t.push({role:"user",content:a}));break}case"assistant":{let a=[];for(let l of n(i.content)){if(typeof l=="string"){l.length>0&&a.push({type:"text",text:l});continue}let c=l;if(c?.type==="text"&&typeof c.text=="string"){if(c.text.length>0){let u=om(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),t.push({role:"assistant",content:a}));break}case"tool":{let a=[];if(Array.isArray(i.content))for(let l of i.content){let c=l;c?.type==="tool-result"&&a.push({type:"tool_result",tool_use_id:c.toolCallId??"",content:Ese(c.output)})}else typeof i.content=="string"&&a.push({type:"tool_result",tool_use_id:i.toolCallId??"",content:i.content});a.length>0&&t.push({role:"user",content:a});break}}let s=e.length===0?void 0:e.some(i=>i.cache_control)?e:e.map(i=>i.text).join(`
|
|
1128
1128
|
|
|
1129
|
-
`);return{...s!==void 0?{system:s}:{},messages:t}},jBe=r=>{if(!(!r||r==="auto")){if(r==="none")return{type:"none"};if(r==="required")return{type:"any"};if(typeof r=="object"){let e=r;if(e.type==="tool"&&e.toolName)return{type:"tool",name:e.toolName}}}},qSr=r=>{switch(r){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},GBe=6e5,Mse=class extends oo{client;authMethod;subscriptionTier;enableBetaFeatures;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,n,o){let s=!!(o?.apiKey&&!o?.oauthToken),i=s?null:(o?.oauthToken?{accessToken:o.oauthToken}:null)??n?.oauthToken??BBe(),a=s?"api_key":n?.authMethod??GSr(i),l=n?.subscriptionTier??(a==="oauth"?jSr(i):"api"),c=e||Pq(),u=c;!process.env.ANTHROPIC_BASE_URL&&l!=="api"&&!uM(c,l)&&(u=Sq(l),g.warn("Model not available for subscription tier, using recommended model",{requestedModel:c,subscriptionTier:l,recommendedModel:u})),super(u,"anthropic",t),this.enableBetaFeatures=n?.enableBetaFeatures??!0,this.oauthToken=i,this.subscriptionTier=l,this.authMethod=a;let m=this.getAuthHeaders(),f;if(g.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){g.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");let h=this.oauthToken,y=mBe(()=>h.accessToken,this.enableBetaFeatures,!1,!0);f=new Xd({apiKey:"oauth-authenticated",fetch:vse(y),timeout:GBe,maxRetries:0}),g.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),g.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{let h=o?.apiKey??n?.apiKey??$Be(),y=(()=>{let x=process.env.ANTHROPIC_BASE_URL;if(!x)return;let b=x.replace(/\/+$/,""),T=b.replace(/\/v\d+$/,"");return T!==b&&g.debug("[AnthropicProvider] Stripping the version suffix from ANTHROPIC_BASE_URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:Ir(x),rewrittenTo:Ir(T)}),T})();f=new Xd({apiKey:h,defaultHeaders:m,...y&&{baseURL:y},fetch:vse(yt()),timeout:GBe,maxRetries:0}),g.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.client=f,this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},g.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?Iq["anthropic-beta"]:"disabled"})}getAuthHeaders(){let e={},t=!!process.env.ANTHROPIC_BASE_URL;if(this.enableBetaFeatures)if(t){let n=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",o=[...hb,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];n&&o.push("context-1m-2025-08-07"),e["anthropic-beta"]=o.join(",")}else e["anthropic-beta"]=Iq["anthropic-beta"];return t&&(e["User-Agent"]=Yd),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return g.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;let t=uM(e,this.subscriptionTier);return t||g.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return wq(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){g.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){g.debug("Token has no expiry information, assuming valid");return}let e=Date.now(),t=this.oauthToken.expiresAt<=e,n=this.oauthToken.expiresAt<=e+3e5;if(!t&&!n){g.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new Mt("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);g.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}g.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});let o=this.oauthToken,s=o.refreshToken;this.refreshPromise=(async()=>{let a=new AbortController,l=setTimeout(()=>a.abort(),3e4),c=await fetch(ME,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Yd},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:s,client_id:bq}),signal:a.signal});if(clearTimeout(l),!c.ok){let m=await c.text();throw new Mt(`Failed to refresh OAuth token: ${c.status} ${m}`,this.providerName)}let u=await c.json();o.accessToken=u.access_token,o.refreshToken=u.refresh_token||o.refreshToken,o.expiresAt=u.expires_in?Date.now()+u.expires_in*1e3:void 0,o.tokenType=u.token_type||"Bearer";let p=o;try{let m=Fr(Op(),".neurolink");to(m)||lA(m,{recursive:!0});let f=Fr(m,"anthropic-credentials.json"),h=`${f}.tmp`,x={...to(f)?JSON.parse(Gc(f,"utf-8")):{},type:"oauth",oauth:p,updatedAt:Date.now()};aA(h,JSON.stringify(x,null,2),{mode:384}),iX(h,f),g.debug("Refreshed OAuth credentials persisted to disk")}catch(m){g.warn("Failed to persist refreshed OAuth token to disk",{error:m instanceof Error?m.message:String(m)})}g.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!u.refresh_token,expiresIn:u.expires_in})})();try{await this.refreshPromise}catch(i){throw i instanceof Mt?i:new Mt(`Failed to refresh OAuth token: ${i instanceof Error?i.message:String(i)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,n){this.lastResponseMetadata={rateLimit:e,...t?{requestId:t}:{}},this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),n&&(n.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=n.inputTokens,this.usageInfo.tokensUsed+=n.inputTokens),n.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=n.outputTokens,this.usageInfo.tokensUsed+=n.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&&g.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&&g.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return Pq()}getAISDKModel(){let e=this.client,t=this.providerName,n=this.modelName||Pq(),o=a=>this.getTimeout(a??{}),s=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:n,supportedUrls:{},doGenerate:async a=>{await s();let l=zBe(a.prompt),c=l.messages,u=l.system,p=(a.tools??[]).filter(F=>F.type==="function").map(F=>{let B=om(F);return{name:F.name,...F.description?{description:F.description}:{},input_schema:F.inputSchema??{type:"object",properties:{}},...B?{cache_control:B}:{}}});p&&p.length===0&&(p=void 0);let m=a.toolChoice?jBe(a.toolChoice.type==="tool"?{type:"tool",toolName:a.toolChoice.toolName}:a.toolChoice.type):void 0,f;if(a.responseFormat?.type==="json"){f=a.responseFormat.name??"json";let F=a.responseFormat.schema??{type:"object"};p=[{name:f,description:a.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:F}],m={type:"tool",name:f}}let h=a.providerOptions?.anthropic?.finalResultSchema,y=!1;if(!f&&h){let F=Ise(p,h);p=F.tools,y=F.applied,F.applied&&(u=Pse(u))}let x=a.providerOptions?.anthropic?.thinking,b=Sse({system:u,tools:p,messages:c}),T=wse(c,Aq-b),w=_a("anthropic",n,{...a.temperature!==void 0&&a.temperature!==null?{temperature:a.temperature}:{},...a.topP!==void 0&&a.topP!==null?{topP:a.topP}:{}},"anthropic.doGenerate"),C={model:n,messages:T,max_tokens:A_(n,a.maxOutputTokens),...u?{system:u}:{},...w.temperature!==void 0?{temperature:w.temperature}:{},...w.topP!==void 0?{top_p:w.topP}:{},...a.stopSequences&&a.stopSequences.length>0?{stop_sequences:a.stopSequences}:{},...p?{tools:p}:{},...m?{tool_choice:m}:{},...x?{thinking:x}:{}},R=a.timeout,k=R!=null,P=C.max_tokens>8192&&!k?Math.max(o(a),3e5):o(a),I=Ws(P,t,"generate"),A;try{A=await e.messages.create(C,{signal:Ux(a.abortSignal,I?.controller.signal)})}finally{I?.cleanup()}let M=[],U,$=[],L=!1;for(let F of A.content)F.type==="thinking"?M.push({type:"reasoning",text:F.thinking}):F.type==="text"?f?$.push(F.text):M.push({type:"text",text:F.text}):F.type==="tool_use"&&(f&&F.name===f?(L=!0,M.push({type:"text",text:xP(F.input)})):y&&F.name===mM?U=xP(F.input):M.push({type:"tool-call",toolCallId:F.id,toolName:F.name,input:xP(F.input)}));if(f&&!L&&$.length>0&&M.push({type:"text",text:$.join("")}),U!==void 0){let F=M.filter(B=>B.type==="reasoning");M.length=0,M.push(...F,{type:"text",text:U}),g.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:U.length})}let z=A.usage.cache_read_input_tokens??0,j=A.usage.cache_creation_input_tokens??0;return{content:M,finishReason:{unified:U!==void 0?"stop":qSr(A.stop_reason),raw:A.stop_reason??"stop"},usage:{inputTokens:{total:A.usage.input_tokens+z+j,noCache:A.usage.input_tokens,cacheRead:z,cacheWrite:j},outputTokens:{total:A.usage.output_tokens,text:A.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:C},response:{id:A.id,modelId:A.model,headers:bBe()??{},body:A}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}formatProviderError(e){return en(e,[{match:n=>n.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(n.message),errorClass:Mt,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:n=>n.statusCode===429||/rate limit|too_many_requests|429/i.test(n.message),errorClass:qr,message:"Anthropic rate limit exceeded. Please try again later."},{match:n=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(n.message),errorClass:cn,message:n=>`Connection error: ${n.message}`},{match:n=>/500|502|503|504|server error/i.test(n.message),errorClass:mt,message:n=>`Server error: ${n.message}`},{match:()=>!0,errorClass:mt,message:n=>`Anthropic error: ${n.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();let{result:n,snapshot:o}=await xBe(()=>super.generate(e,t));return n&&o&&(this.recordLimitSnapshot(o),n.limits=o,n.analytics&&(n.analytics.limits=o)),n}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),SBe(e),wBe(e,this.modelName)}async executeStream(e,t){return TBe(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);let n=this.getTimeout(e),o=Ws(n,this.providerName,"stream"),s=new AbortController,i=f1([e.abortSignal,o?.controller.signal,s.signal]).signal,a,l,c,u,p=!1;try{u=!e.disableTools&&this.supportsTools(),a=u?e.tools||await this.getAllTools():{},l=u?Rg(a,"input_schema"):void 0;let oe=await this.buildMessagesForStream(e);if(c=zBe(oe),e.schema&&l&&l.length>0){let Z=Ise(l,xn(e.schema));l=Z.tools,p=Z.applied,Z.applied&&(c.system=Pse(c.system))}}catch(oe){throw o?.cleanup(),this.handleProviderError(oe)}let m=this.modelName||Pq(),f=u&&l&&l.length>0?jBe(dG(e,a,u)):void 0,h=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,y=zSr.startSpan("neurolink.provider.streamText",{kind:br.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":m}}),x=e.maxSteps||Jo,b=this.neurolink?.getEventEmitter(),T=Fu(),{push:w}=T,{usagePromise:C,finishPromise:R,resolveUsage:k,resolveFinish:P}=lG();C.then(oe=>{y.setAttribute("gen_ai.usage.input_tokens",oe.promptTokens||0),y.setAttribute("gen_ai.usage.output_tokens",oe.completionTokens||0),oe.cacheReadTokens&&y.setAttribute("gen_ai.usage.cached_input_tokens",oe.cacheReadTokens);let Z=Us(this.providerName,this.modelName,{input:oe.promptTokens||0,output:oe.completionTokens||0,total:oe.totalTokens||0,...oe.cacheReadTokens?{cacheReadTokens:oe.cacheReadTokens}:{},...oe.cacheCreationTokens?{cacheCreationTokens:oe.cacheCreationTokens}:{}});Z&&Z>0&&y.setAttribute("neurolink.cost",Z)}).catch(()=>{}),R.then(oe=>{y.setAttribute("gen_ai.response.finish_reason",oe||"unknown"),y.end()}).catch(()=>{y.end()});let I,A=this.client,M=[],U=Date.now(),$=0,L=0,z=0,j=0,F=null,B=()=>({promptTokens:$,completionTokens:L,totalTokens:$+z+j+L,...z>0?{cacheReadTokens:z}:{},...j>0?{cacheCreationTokens:j}:{}}),O="",W,re=(oe,Z)=>{let we=ve=>{if(typeof ve=="string")return ve;try{return JSON.stringify(ve)??""}catch{return""}};return zt(we(oe),"anthropic")+zt(we(Z),"anthropic")},pe=(async()=>{let oe=c.messages.slice(),Z,we;for(let ve=0;ve<x;ve++){if(l){let ce=new Set(l.map(_=>_.name)),Ne=Object.fromEntries(Object.entries(a).filter(([_])=>!ce.has(_)));Object.keys(Ne).length>0&&(l.push(...Rg(Ne,"input_schema")??[]),g.info(`[Anthropic] ${Object.keys(Ne).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(Ne).join(", ")}`))}let ae=Rq({conversation:oe,availableInputTokens:mi("anthropic",m,e.maxTokens??void 0),fixedOverheadTokens:re(c.system,l),provider:"anthropic",observedPromptTokens:Z,previousSentEstimate:we,onSentEstimate:ce=>{we=ce}});if(ae){let ce=new Set(ae.drop),Ne=new Set(ae.truncate),_=[];for(let G=0;G<oe.length;G++){if(ce.has(G))continue;let Q=oe[G];if(Ne.has(G)&&Array.isArray(Q.content)){_.push({...Q,content:Q.content.map(q=>q.type==="tool_result"?{...q,content:Cq(typeof q.content=="string"?q.content:JSON.stringify(q.content)??"")}:q)});continue}_.push(Q)}if(ce.size>0){let G=_.findIndex(Q=>Array.isArray(Q.content)&&Q.content.some(q=>q.type==="tool_use"||q.type==="tool_result"));G<0&&(G=Math.min(1,_.length)),_.splice(G,0,{role:"user",content:[{type:"text",text:Eq}]})}oe.length=0,oe.push(..._)}let H=Sse({system:c.system,tools:l,messages:oe}),V=wse(oe,Aq-H),ne=_a("anthropic",m,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream"),N={model:m,messages:V,max_tokens:A_(m,e.maxTokens),stream:!0,...c.system?{system:c.system}:{},...ne.temperature!==void 0?{temperature:ne.temperature}:{},...l&&l.length>0?{tools:l}:{},...f?{tool_choice:f}:{},...h?{thinking:h}:{}},Y=await Ru(()=>A.messages.create(N,{signal:i??void 0}),pt.getActiveSpan()??void 0,`${this.providerName} stream`),ee=new Map,ie=new Map,le=new Map,ye=new Map,Fe=null,Ee=0;for await(let ce of Y)if(ce.type==="message_start"){$+=ce.message.usage.input_tokens??0;let Ne=ce.message.usage.output_tokens??0;L+=Ne-Ee,Ee=Ne,z+=ce.message.usage.cache_read_input_tokens??0,j+=ce.message.usage.cache_creation_input_tokens??0,Z=(ce.message.usage.input_tokens??0)+(ce.message.usage.cache_read_input_tokens??0)+(ce.message.usage.cache_creation_input_tokens??0)}else if(ce.type==="content_block_start")ee.set(ce.index,ce.content_block.type),ce.content_block.type==="tool_use"&&ye.set(ce.index,{id:ce.content_block.id,name:ce.content_block.name,inputJson:""});else if(ce.type==="content_block_delta"){let Ne=ce.delta;if(Ne.type==="text_delta")ie.set(ce.index,(ie.get(ce.index)??"")+Ne.text),p?O+=Ne.text:w({content:Ne.text});else if(Ne.type==="thinking_delta"){let _=le.get(ce.index)??{text:"",signature:""};_.text+=Ne.thinking,le.set(ce.index,_),w({content:"",reasoning:Ne.thinking})}else if(Ne.type==="signature_delta"){let _=le.get(ce.index)??{text:"",signature:""};_.signature+=Ne.signature,le.set(ce.index,_)}else if(Ne.type==="input_json_delta"){let _=ye.get(ce.index);_&&(_.inputJson+=Ne.partial_json)}}else if(ce.type==="message_delta"){Fe=ce.delta.stop_reason??Fe;let Ne=ce.usage?.output_tokens??Ee;L+=Ne-Ee,Ee=Ne}if(F=Fe,p){let ce=[...ye.values()].find(Ne=>Ne.name===mM);if(ce){W=UBe(ce.inputJson),F="end_turn",g.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:W.length});break}}if(Fe!=="tool_use"||ye.size===0)break;let Rt=[],Xe=[...ee.keys()].sort((ce,Ne)=>ce-Ne);for(let ce of Xe){let Ne=ee.get(ce);if(Ne==="thinking"){let _=le.get(ce);_&&_.text.length>0&&Rt.push({type:"thinking",thinking:_.text,signature:_.signature})}else if(Ne==="text"){let _=ie.get(ce);_&&_.length>0&&Rt.push({type:"text",text:_})}else if(Ne==="tool_use"){let _=ye.get(ce);if(_){let G;try{G=_.inputJson?JSON.parse(_.inputJson):{}}catch{G={}}Rt.push({type:"tool_use",id:_.id,name:_.name,input:G})}}}oe.push({role:"assistant",content:Rt});let ue=[],qe=[],Be=[];for(let ce of ye.values()){let Ne;try{Ne=ce.inputJson?JSON.parse(ce.inputJson):{}}catch{Ne={}}qe.push({type:"tool-call",toolCallId:ce.id,toolName:ce.name,args:Ne}),M.push(ce.name);let _=a[ce.name]??pI(a,ce.name);try{if(!_?.execute)throw new Error(`Tool not found: ${ce.name}`);let G=await _.execute(Ne,{toolCallId:ce.id,messages:[]});Be.push({type:"tool-result",toolCallId:ce.id,toolName:ce.name,result:G}),ue.push({type:"tool_result",tool_use_id:ce.id,content:Ese(G)})}catch(G){let Q=G instanceof Error?G.message:String(G);Be.push({type:"tool-result",toolCallId:ce.id,toolName:ce.name,error:Q}),ue.push({type:"tool_result",tool_use_id:ce.id,content:`Error: ${Q}`,is_error:!0})}}Yw(b,Be.map(ce=>({toolName:ce.toolName,result:ce.result,error:ce.error}))),this.handleToolExecutionStorage(qe,Be,e,new Date).catch(ce=>{g.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ce instanceof Error?ce.message:String(ce)})}),oe.push({role:"user",content:ue})}k(B()),P(F??"stop")})().catch(oe=>{throw I=oe,g.error("Anthropic: Stream error",{error:oe instanceof Error?oe.message:String(oe)}),k(B()),P("error"),this.formatProviderError(oe)}).finally(()=>{if(p){let oe=W??O;oe.length>0&&w({content:oe})}o?.cleanup(),T.close()});pe.catch(()=>{});let Ae=this.providerName;return{stream:async function*(){let oe=0;try{for await(let Z of T.iterable)"content"in Z&&typeof Z.content=="string"&&Z.content.length>0&&oe++,yield Z;if(await pe,oe===0&&M.length===0){g.warn(`${Ae}: Stream produced no output \u2014 emitting enriched sentinel`);let Z=new Ta({message:"Stream produced no output"}),we=await Zp(Z,void 0,I);Qp(we),yield we}}catch(Z){let we=await Zp(Z,void 0,I);if(Qp(we),yield we,!Ta.isInstance(Z))throw Z}finally{s.signal.aborted||s.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],analytics:R.then(async()=>{let oe=await uG.createAnalytics(this.providerName,m,{textStream:(async function*(){})(),usage:C,finishReason:R},Date.now()-U,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),Z=vBe();return Z&&oe&&(this.recordLimitSnapshot(Z),oe.limits=Z),oe})}}async isAvailable(){try{return BBe()||$Be(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}});var VBe={};de(VBe,{ANTHROPIC_BETA_HEADERS:()=>Iq,AnthropicProvider:()=>Mse,ModelAccessError:()=>jR,getModelCapabilities:()=>wq,getRecommendedModelForTier:()=>Sq,isModelAvailableForTier:()=>uM});var HBe=E(()=>{"use strict";qBe();kse()});var KBe={};de(KBe,{Agent:()=>kwr,BedrockClient:()=>HSr,BedrockRuntimeClient:()=>Ose,Blob:()=>Rwr,Client:()=>Iwr,ConverseCommand:()=>Nse,ConverseStreamCommand:()=>Lse,Cron:()=>cwr,Dispatcher:()=>Pwr,File:()=>Cwr,FlowProducer:()=>lwr,FormData:()=>Ewr,GoogleAuth:()=>YSr,HTTPException:()=>hwr,Headers:()=>_wr,Hippocampus:()=>twr,HippocampusConfig:()=>rwr,Hono:()=>gwr,ImageFormat:()=>DE,InvokeEndpointCommand:()=>JSr,InvokeEndpointWithResponseStreamCommand:()=>XSr,Job:()=>iwr,ListFoundationModelsCommand:()=>KSr,MockAgent:()=>Nwr,Pool:()=>Awr,Queue:()=>owr,QueueScheduler:()=>awr,Request:()=>Swr,Response:()=>wwr,SageMakerRuntimeClient:()=>WSr,TextToSpeechClient:()=>QSr,VertexAI:()=>ZSr,Webhook:()=>ewr,Worker:()=>swr,convertToHtml:()=>mwr,cors:()=>fwr,createClient:()=>nwr,default:()=>VSr,extractRawText:()=>pwr,fetch:()=>Twr,getGlobalDispatcher:()=>Owr,interceptors:()=>Lwr,logger:()=>ywr,parseBuffer:()=>uwr,request:()=>Dwr,secureHeaders:()=>xwr,selectCover:()=>dwr,setGlobalDispatcher:()=>Mwr,streamSSE:()=>vwr,timeout:()=>bwr});var LE,Mi,VSr,HSr,KSr,Ose,Nse,Lse,DE,WSr,JSr,XSr,YSr,ZSr,QSr,ewr,twr,rwr,nwr,owr,swr,iwr,awr,lwr,cwr,uwr,dwr,pwr,mwr,gwr,fwr,hwr,ywr,xwr,vwr,bwr,Twr,Swr,wwr,_wr,Ewr,Cwr,Rwr,kwr,Awr,Iwr,Pwr,Mwr,Owr,Nwr,Lwr,Dwr,Mq=E(()=>{LE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:LE.get}):new Proxy(function(...t){return new Proxy({},{get:LE.get})},{get:LE.get,apply(t,n,o){return new Proxy({},{get:LE.get})},construct(t,n){return new Proxy({},{get:LE.get})}})}},Mi=new Proxy({},LE),VSr=Mi,{BedrockClient:HSr,ListFoundationModelsCommand:KSr,BedrockRuntimeClient:Ose,ConverseCommand:Nse,ConverseStreamCommand:Lse,ImageFormat:DE}=Mi,{SageMakerRuntimeClient:WSr,InvokeEndpointCommand:JSr,InvokeEndpointWithResponseStreamCommand:XSr}=Mi,{GoogleAuth:YSr,VertexAI:ZSr,TextToSpeechClient:QSr}=Mi,{Webhook:ewr}=Mi,{Hippocampus:twr,HippocampusConfig:rwr}=Mi,{createClient:nwr}=Mi,{Queue:owr,Worker:swr,Job:iwr,QueueScheduler:awr,FlowProducer:lwr}=Mi,{Cron:cwr}=Mi,{parseBuffer:uwr,selectCover:dwr}=Mi,{extractRawText:pwr,convertToHtml:mwr}=Mi,{Hono:gwr}=Mi,{cors:fwr,HTTPException:hwr,logger:ywr,secureHeaders:xwr,streamSSE:vwr,timeout:bwr}=Mi,Twr=globalThis.fetch,Swr=globalThis.Request,wwr=globalThis.Response,_wr=globalThis.Headers,Ewr=globalThis.FormData,Cwr=globalThis.File,Rwr=globalThis.Blob,kwr=Mi.Agent,Awr=Mi.Pool,Iwr=Mi.Client,Pwr=Mi.Dispatcher,Mwr=()=>{},Owr=()=>Mi,Nwr=Mi.MockAgent,Lwr={redirect:()=>r=>r,retry:()=>r=>r},Dwr=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});function Uwr(r,e){return{inputTokens:r.inputTokens+e.inputTokens,outputTokens:r.outputTokens+e.outputTokens,cacheReadTokens:(r.cacheReadTokens??0)+(e.cacheReadTokens??0)||void 0,cacheWriteTokens:(r.cacheWriteTokens??0)+(e.cacheWriteTokens??0)||void 0,reasoningTokens:(r.reasoningTokens??0)+(e.reasoningTokens??0)||void 0}}function Dse(r,e,t){let n=Fu(),o=new AbortController,s=()=>o.abort();t.abortSignal?.addEventListener("abort",s),t.abortSignal?.aborted&&o.abort();let i=new Map,a=!1,l=(async()=>{let c=e,u={inputTokens:0,outputTokens:0},p="",m="",f,h=[],y=[],x=!1;try{for(let T=0;T<r.maxSteps&&!o.signal.aborted;T++){if(r.planReclaim){let I=r.planReclaim(c,T);I&&(c=I.conversation)}let w=r.buildStepRequest(c,T),C=!1,R={push:I=>{C=!0,n.push(I)}},k;try{k=await Ru(async()=>{C=!1;try{return await r.executeStep(w,R,o.signal)}catch(I){throw C?new Oq(I):I}},void 0,`${r.providerLabel}.step`)}catch(I){throw I instanceof Oq?I.cause:I}if(u=Uwr(u,k.usage),f=k.rawStopReason,m=k.text||m,r.isMalformedStep?.(k)&&!a&&!o.signal.aborted){a=!0,g.warn(`[${r.providerLabel}] Malformed function call at step ${T+1}/${r.maxSteps}; retrying once.`),c=r.buildMalformedRetryNote?.(c)??c;continue}if(k.toolCalls.length===0){p=k.text||p;break}T===r.maxSteps-1&&(x=!0);let P=[];for(let I of k.toolCalls){h.push(I);let A=r.toolFailureBreaker,M=A?i.get(I.name):void 0;if(A&&M&&M.count>=A.maxRetries){let L={error:`TOOL_PERMANENTLY_FAILED: "${I.name}" has failed ${M.count} times. Last error: ${M.lastError}.`,status:"permanently_failed",do_not_retry:!0};P.push({...I,output:L,error:L.error,permanentlyFailed:!0}),y.push({name:I.name,input:I.args,output:L});continue}let U=t.tools?.[I.name],$=U?.execute?U:r.resolveToolOnMiss?.(I.name)??U;if(!$?.execute){let L=A?{error:`TOOL_NOT_FOUND: "${I.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${I.name}`};P.push({...I,output:L,error:L.error,permanentlyFailed:!!A}),y.push({name:I.name,input:I.args,output:L});continue}try{let L=await $.execute(I.args,{toolCallId:I.id,abortSignal:o.signal});P.push({...I,output:L}),y.push({name:I.name,input:I.args,output:L})}catch(L){let z=L instanceof Error?L.message:String(L);if(A){let F=i.get(I.name)??{count:0,lastError:""};F.count++,F.lastError=z,i.set(I.name,F)}let j={error:z,status:"failed"};P.push({...I,output:j,error:z}),y.push({name:I.name,input:I.args,output:j})}}c=r.buildToolResultMessages(c,k,P)}let b=r.mapFinishReason(f,x);return{text:p||(x?m:""),toolCalls:h,toolExecutions:y,usage:u,finishReason:b,rawStopReason:f,conversation:c}}catch(b){throw n.error(b),b}finally{n.close(),t.abortSignal?.removeEventListener("abort",s)}})();return{stream:n.iterable,resultPromise:l}}var Oq,WBe=E(()=>{"use strict";Kv();X();Qm();Oq=class extends Error{constructor(t){super(t instanceof Error?t.message:String(t));this.cause=t}cause}});function $wr(r){if(/^(us|ca)-/.test(r))return"us";if(/^(eu|il|me|af)-/.test(r))return"eu";if(/^ap-northeast-[13]$/.test(r))return"jp";if(/^ap-southeast-[246]$/.test(r))return"au";if(/^ap-/.test(r))return"apac"}function Bwr(r){return/^(us|eu|au|jp|apac|global)\./.test(r)}function JBe(r){if(typeof r!="object"||r===null)return!1;let e=r,t=typeof e.name=="string"?e.name:"",n=typeof e.message=="string"?e.message:"";return!/ValidationException/i.test(t)&&!/ValidationException/i.test(n)?!1:/inference profile/i.test(n)&&/on-demand throughput/i.test(n)}function zwr(r,e){if(r.startsWith("arn:")||Bwr(r))return[];let t=[],n=$wr(e);return n&&t.push(`${n}.${r}`),t.push(`${Fwr}.${r}`),t}function YBe(r,e){return`${r}::${e}`}function jwr(r,e){return XBe.get(YBe(e,r))}function Gwr(r,e,t){XBe.set(YBe(e,r),t),g.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:e})}async function Use(r,e,t){let n=jwr(r,e);if(n&&n!==r)return t(n);try{return await t(r)}catch(o){if(!JBe(o))throw o;let s=zwr(r,e);if(s.length===0)throw o;g.warn("[Bedrock] Model requires a cross-region inference profile in this region; retrying with a prefixed id",{region:e,candidates:s.length});for(let i of s)try{let a=await t(i);return Gwr(r,e,i),a}catch(a){if(!JBe(a))throw a}throw o}}var Fwr,XBe,ZBe=E(()=>{"use strict";X();Fwr="global";XBe=new Map});function Nq(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function eze(r,e){if(r){if(r.toolUse&&r._inputBuffer){try{r.toolUse.input=JSON.parse(r._inputBuffer)}catch{r.toolUse.input={}}delete r._inputBuffer}e&&!r.toolUse&&(r.text=e)}}function tze(r){return r.filter(e=>e.toolUse).map(e=>({id:e.toolUse?.toolUseId??Nq(),name:e.toolUse?.name??"",args:e.toolUse?.input??{}}))}async function qwr(r,e,t){let n=[],o=new Map,s=new Map,i=h=>{let y=o.get(h);return y||(y={},o.set(h,y),n.push(y)),y},a="",l,c=0,u=0,p=0,m=0;if(r.stream)for await(let h of r.stream){if(t.aborted)break;let y=h;if(y.contentBlockStart&&i(y.contentBlockStart.contentBlockIndex??0),y.contentBlockDelta?.delta?.text){let x=y.contentBlockDelta.contentBlockIndex??0,b=y.contentBlockDelta.delta.text;i(x),a+=b,s.set(x,(s.get(x)??"")+b),e.push({content:b})}if(y.contentBlockStart?.start?.toolUse){let x=i(y.contentBlockStart.contentBlockIndex??0);x.toolUse={name:y.contentBlockStart.start.toolUse.name??"",input:{},toolUseId:y.contentBlockStart.start.toolUse.toolUseId??Nq()}}if(y.contentBlockDelta?.delta?.toolUse){let x=i(y.contentBlockDelta.contentBlockIndex??0);x.toolUse??={name:"",input:{},toolUseId:Nq()};let b=y.contentBlockDelta.delta.toolUse.input;typeof b=="string"?x._inputBuffer=(x._inputBuffer??"")+b:typeof b=="object"&&b!==null&&!Array.isArray(b)&&(x.toolUse.input={...x.toolUse.input??{},...b})}if(y.contentBlockStop){let x=y.contentBlockStop.contentBlockIndex??0;eze(o.get(x),s.get(x)??"")}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,p+=y.metadata.usage.cacheReadInputTokens??0,m+=y.metadata.usage.cacheWriteInputTokens??0;break}}for(let[h,y]of o)eze(y,s.get(h)??"");let f=n.filter(h=>h.text||h.toolUse||h.image||h.document);return{text:a,toolCalls:tze(f),usage:{inputTokens:c,outputTokens:u,cacheReadTokens:p,cacheWriteTokens:m},rawStopReason:l,raw:f}}function Vwr(r){let e=[],t="";for(let n of r.output?.message?.content??[]){let o={};"text"in n&&n.text&&(o.text=n.text,t+=t?` ${n.text}`:n.text),"toolUse"in n&&n.toolUse&&(o.toolUse={toolUseId:n.toolUse.toolUseId??Nq(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),e.push(o)}return{text:t,toolCalls:tze(e),usage:{inputTokens:r.usage?.inputTokens??0,outputTokens:r.usage?.outputTokens??0,cacheReadTokens:r.usage?.cacheReadInputTokens??0,cacheWriteTokens:r.usage?.cacheWriteInputTokens??0},rawStopReason:r.stopReason,raw:e}}function Fse(r){return{providerLabel:"bedrock",maxSteps:r.maxSteps,buildStepRequest(e,t){return{raw:r.buildCommandInput(e,t)}},async executeStep(e,t,n){let o=e.raw;if(!r.streaming){let i=await Use(o.modelId??"",r.region,a=>je(r.client.send(new Nse({...o,modelId:a})),QBe,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return Vwr(i)}let s=await Use(o.modelId??"",r.region,i=>je(r.client.send(new Lse({...o,modelId:i})),QBe,new Error("Bedrock streaming API call timed out")));return qwr(s,t,n)},buildToolResultMessages(e,t,n){let o={role:"assistant",content:t.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[...e,o,s]},mapFinishReason(e,t){switch(e){case"end_turn":case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return t?"tool-calls":"stop"}}}}var QBe,rze=E(()=>{"use strict";Mq();Tt();ZBe();QBe=12e4});function $se(r,e,t){return{input:{text:r.input?.text||"",images:r.input?.images,content:r.input?.content,files:r.input?.files,csvFiles:r.input?.csvFiles,pdfFiles:r.input?.pdfFiles,audioFiles:r.input?.audioFiles,videoFiles:r.input?.videoFiles},csvOptions:r.csvOptions,pdfOptions:r.pdfOptions,systemPrompt:r.systemPrompt,conversationHistory:r.conversationMessages,provider:e,model:t,temperature:r.temperature,maxTokens:r.maxTokens,enableAnalytics:r.enableAnalytics,enableEvaluation:r.enableEvaluation,context:r.context,fileRegistry:r.fileRegistry}}var nze=E(()=>{"use strict"});var Lq,Bse=E(()=>{"use strict";ac();Lq=Oe.provider});var oze={};de(oze,{Agent:()=>O_r,BedrockClient:()=>Kwr,BedrockRuntimeClient:()=>Jwr,Blob:()=>M_r,Client:()=>L_r,ConverseCommand:()=>Xwr,ConverseStreamCommand:()=>Ywr,Cron:()=>g_r,Dispatcher:()=>D_r,File:()=>P_r,FlowProducer:()=>m_r,FormData:()=>I_r,GoogleAuth:()=>r_r,HTTPException:()=>T_r,Headers:()=>A_r,Hippocampus:()=>i_r,HippocampusConfig:()=>a_r,Hono:()=>v_r,ImageFormat:()=>Zwr,InvokeEndpointCommand:()=>e_r,InvokeEndpointWithResponseStreamCommand:()=>t_r,Job:()=>d_r,ListFoundationModelsCommand:()=>Wwr,MockAgent:()=>$_r,Pool:()=>N_r,Queue:()=>c_r,QueueScheduler:()=>p_r,Request:()=>R_r,Response:()=>k_r,SageMakerRuntimeClient:()=>Qwr,TextToSpeechClient:()=>o_r,VertexAI:()=>n_r,Webhook:()=>s_r,Worker:()=>u_r,convertToHtml:()=>x_r,cors:()=>b_r,createClient:()=>l_r,default:()=>Hwr,extractRawText:()=>y_r,fetch:()=>C_r,getGlobalDispatcher:()=>F_r,interceptors:()=>B_r,logger:()=>S_r,parseBuffer:()=>f_r,request:()=>z_r,secureHeaders:()=>w_r,selectCover:()=>h_r,setGlobalDispatcher:()=>U_r,streamSSE:()=>__r,timeout:()=>E_r});var UE,Oi,Hwr,Kwr,Wwr,Jwr,Xwr,Ywr,Zwr,Qwr,e_r,t_r,r_r,n_r,o_r,s_r,i_r,a_r,l_r,c_r,u_r,d_r,p_r,m_r,g_r,f_r,h_r,y_r,x_r,v_r,b_r,T_r,S_r,w_r,__r,E_r,C_r,R_r,k_r,A_r,I_r,P_r,M_r,O_r,N_r,L_r,D_r,U_r,F_r,$_r,B_r,z_r,sze=E(()=>{UE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:UE.get}):new Proxy(function(...t){return new Proxy({},{get:UE.get})},{get:UE.get,apply(t,n,o){return new Proxy({},{get:UE.get})},construct(t,n){return new Proxy({},{get:UE.get})}})}},Oi=new Proxy({},UE),Hwr=Oi,{BedrockClient:Kwr,ListFoundationModelsCommand:Wwr,BedrockRuntimeClient:Jwr,ConverseCommand:Xwr,ConverseStreamCommand:Ywr,ImageFormat:Zwr}=Oi,{SageMakerRuntimeClient:Qwr,InvokeEndpointCommand:e_r,InvokeEndpointWithResponseStreamCommand:t_r}=Oi,{GoogleAuth:r_r,VertexAI:n_r,TextToSpeechClient:o_r}=Oi,{Webhook:s_r}=Oi,{Hippocampus:i_r,HippocampusConfig:a_r}=Oi,{createClient:l_r}=Oi,{Queue:c_r,Worker:u_r,Job:d_r,QueueScheduler:p_r,FlowProducer:m_r}=Oi,{Cron:g_r}=Oi,{parseBuffer:f_r,selectCover:h_r}=Oi,{extractRawText:y_r,convertToHtml:x_r}=Oi,{Hono:v_r}=Oi,{cors:b_r,HTTPException:T_r,logger:S_r,secureHeaders:w_r,streamSSE:__r,timeout:E_r}=Oi,C_r=globalThis.fetch,R_r=globalThis.Request,k_r=globalThis.Response,A_r=globalThis.Headers,I_r=globalThis.FormData,P_r=globalThis.File,M_r=globalThis.Blob,O_r=Oi.Agent,N_r=Oi.Pool,L_r=Oi.Client,D_r=Oi.Dispatcher,U_r=()=>{},F_r=()=>Oi,$_r=Oi.MockAgent,B_r={redirect:()=>r=>r,retry:()=>r=>r},z_r=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});async function Dq(){return await Promise.resolve().then(()=>(sze(),oze))}var zse=E(()=>{"use strict"});var jse,ize=E(()=>{"use strict";Mq();Qr();qw();eu();cs();WBe();rze();Dt();ea();Tt();X();dg();qI();nze();Ea();gr();Bse();zse();jse=class r extends oo{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(e){return e?e.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(e,t,n,o){super(e,"bedrock",t);let s=e||process.env.BEDROCK_MODEL||this.modelName,i=r.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",g.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),g.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{g.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new Ose({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),g.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw g.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){let{BedrockClient:e,ListFoundationModelsCommand:t}=await Dq(),n=new e({region:this.region});try{g.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");let o=new t({}),s=Date.now();await n.send(o);let i=Date.now()-s;g.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){let s=o instanceof Error?o.message:String(o);g.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(e){g.debug("[AmazonBedrockProvider] generate() called with conversation management");let t=Date.now(),n=typeof e=="string"?{prompt:e}:e;this.conversationHistory=[];let o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){g.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});let m=$se(n,this.providerName,this.modelName),f=await T_(m,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(f)}else{g.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");let p={role:"user",content:[{text:n.prompt}]};this.conversationHistory.push(p)}g.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(p){let m=this.neurolink?.getEventEmitter();throw m&&m.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-t,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:p instanceof Error?p.message:String(p)}),p}let u=this.neurolink?.getEventEmitter();return u&&u.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-t,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(e){let t=e.maxSteps||Jo,n=await this.resolveTurnTools(e.tools,e.disableTools),o=this.formatToolsForBedrock(n),s=_a(this.providerName,this.modelName||this.getDefaultModel(),{temperature:e.temperature??.7},"bedrock.converse"),i=Fse({client:this.bedrockClient,streaming:!1,region:this.region,maxSteps:t,buildCommandInput:a=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(a),system:[{text:e.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:e.maxTokens,...s.temperature!==void 0&&{temperature:s.temperature}},...o?{toolConfig:o}:{}})});try{let{resultPromise:a}=Dse(i,this.conversationHistory,{tools:this.toEngineTools(n),abortSignal:e.abortSignal}),l=await a;this.conversationHistory=l.conversation;let c=l.usage.inputTokens,u=l.usage.outputTokens,p=l.usage.cacheReadTokens??0,m=l.usage.cacheWriteTokens??0;return{text:l.text||"",usage:{input:c,output:u,total:c+p+m+u,...p>0&&{cacheReadTokens:p},...m>0&&{cacheCreationTokens:m}},finishReason:l.finishReason,rawFinishReason:l.rawStopReason}}catch(a){throw g.error("[AmazonBedrockProvider] Error in conversation loop:",a),this.handleProviderError(a)}}convertToAWSMessages(e){return e.map(t=>({role:t.role,content:t.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(e,t,n,o){return Lq.startActiveSpan("bedrock.tool.execute",{kind:br.CLIENT,attributes:{"gen_ai.tool.name":t,"gen_ai.system":"aws.bedrock"}},async s=>{try{if(g.debug(`[AmazonBedrockProvider] Executing single tool: ${t}`,{args:n}),!e[t])throw new Error(`Tool not found: ${t}`);let i=e[t];if(!i||!i.execute)throw new Error(`Tool ${t} does not have execute method`);let a=n||{};t==="list_directory"&&!a.path&&(a.path=".",g.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),g.debug("[AmazonBedrockProvider] Tool input parameters:",a);let l={};for(let[p,m]of Object.entries(a))(m===null||typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="object"&&m!==null)&&(l[p]=m);let c=await i.execute(l);g.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:t,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){let p=typeof c.error=="string"?c.error:c.error.message||"Tool execution failed";throw new Error(p)}else u="";else typeof c=="string"?u=c:typeof c=="object"?u=JSON.stringify(c,null,2):u=String(c);return s.setStatus({code:ze.OK}),u}catch(i){throw g.error("[AmazonBedrockProvider] Tool execution error:",{toolName:t,error:i}),s.setStatus({code:ze.ERROR,message:i.message}),s.recordException(i),i}finally{s.end()}})}async resolveTurnTools(e,t){if(t)return{};let n=e??await this.getAllTools();return this.convertAISDKToolsToToolDefinitions(n)}toEngineTools(e){let t={};for(let n of Object.keys(e))t[n]={execute:o=>this.executeSingleTool(e,n,o)};return t}convertAISDKToolsToToolDefinitions(e){let t={};for(let[n,o]of Object.entries(e))if("description"in o&&o.description){let i=o.parameters??o.inputSchema;t[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 t}formatToolsForBedrock(e){if(!e||Object.keys(e).length===0)return null;let t=Object.entries(e).map(([n,o])=>{let s;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?s=xn(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 g.debug(`[AmazonBedrockProvider] Formatted ${t.length} tools for Bedrock`),{tools:t}}convertToBedrockMessages(e){return e.map(t=>{let n={role:t.role==="system"?"user":t.role,content:[]};return typeof t.content=="string"?n.content.push({text:t.content}):t.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){let s=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image,i=o.mimeType?.split("/")[1]||"png";i==="jpg"&&(i="jpeg"),n.content.push({image:{format:i==="jpeg"?DE.JPEG:i==="png"?DE.PNG:i==="gif"?DE.GIF:DE.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"){let 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?wd.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(e){return g.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),g.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),Lq.startActiveSpan("bedrock.stream",{kind:br.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async t=>{try{if(g.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(e.input?.images?.length||e.input?.content?.length||e.input?.files?.length||e.input?.csvFiles?.length||e.input?.pdfFiles?.length)){g.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!e.input?.images?.length,imageCount:e.input?.images?.length||0,hasContent:!!e.input?.content?.length,contentCount:e.input?.content?.length||0,hasFiles:!!e.input?.files?.length,fileCount:e.input?.files?.length||0,hasCSVFiles:!!e.input?.csvFiles?.length,csvFileCount:e.input?.csvFiles?.length||0,hasPDFFiles:!!e.input?.pdfFiles?.length,pdfFileCount:e.input?.pdfFiles?.length||0});let s=$se(e,this.providerName,this.modelName),i=await T_(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{g.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");let s={role:"user",content:[{text:e.input.text}]};this.conversationHistory.push(s)}g.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),g.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");let o=await this.streamingConversationLoop(e,t);return g.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),t.setStatus({code:ze.OK}),t.end(),o}catch(n){g.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");let o=n,s=o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream");if(g.debug("[TRACE] executeStream CATCH - checking if permission error"),g.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){g.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),g.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),t.addEvent("stream.fallback_to_generate",{reason:o.message});let i=await this.generate({prompt:e.input.text,input:e.input,maxTokens:e.maxTokens,temperature:e.temperature,systemPrompt:e.systemPrompt});if(!i)throw t.setStatus({code:ze.ERROR,message:"Generate method returned null result"}),t.end(),new Error("Generate method returned null result");t.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),t.setStatus({code:ze.OK}),t.end();let a=new ReadableStream({start(c){let p=(i.content||"").split(/(\s+)/),m="";for(let f=0;f<p.length;f++)m+=p[f],(f===p.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](){let c=a.getReader();try{for(;;){let{done:u,value:p}=await c.read();if(u)break;yield p}}finally{c.releaseLock()}}},usage:i.usage,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw t.setStatus({code:ze.ERROR,message:o instanceof Error?o.message:String(o)}),t.recordException(o instanceof Error?o:new Error(String(o))),t.end(),n}})}async streamingConversationLoop(e,t){let n=Date.now(),o=e.maxSteps||Jo,s=await this.resolveTurnTools(e.tools,e.disableTools),i=this.formatToolsForBedrock(s),a=_a(this.providerName,this.modelName||this.getDefaultModel(),{temperature:e.temperature??.7},"bedrock.converseStream"),l=Fse({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:P=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(P),system:[{text:e.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:e.maxTokens,...a.temperature!==void 0&&{temperature:a.temperature}},...i?{toolConfig:i}:{}})}),c=!1,u,p=new Promise(P=>{u=()=>{c=!0,P()}}),m={...l,executeStep:async(P,I,A)=>{let M=await l.executeStep(P,I,A);return u(),M}};t.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});let{stream:f,resultPromise:h}=Dse(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:e.abortSignal}),y=h.then(P=>({result:P,error:void 0}),P=>({result:void 0,error:P}));if(await Promise.race([p,y]),!c){let P=await y;if(P.error)throw P.error}let x=this.neurolink?.getEventEmitter(),b=this,T={startTime:n,streamId:`bedrock-${Date.now()}`},w,C=new Promise(P=>{w=P}),R=P=>{let I=P?.inputTokens??0,A=P?.outputTokens??0,M=P?.cacheReadTokens??0,U=P?.cacheWriteTokens??0;return{input:I,output:A,total:I+M+U+A,...M>0&&{cacheReadTokens:M},...U>0&&{cacheCreationTokens:U}}};return y.then(P=>{w(Hp(this.providerName,this.modelName||this.getDefaultModel(),{usage:R(P.result?.usage)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let P=!1;try{yield*f}catch(I){throw P=!0,I}finally{let I=await y;I.error&&(P=!0);let A=R(I.result?.usage);I.result&&(b.conversationHistory=I.result.conversation,T.finishReason=I.result.finishReason,T.rawFinishReason=I.result.rawStopReason,t.setAttribute("gen_ai.response.stop_reason",I.result.rawStopReason??"unknown")),x&&x.emit("generation:end",{provider:b.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:A,model:b.modelName||b.getDefaultModel(),provider:b.providerName,finishReason:P?"error":I.result?.rawStopReason},success:!P})}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:C,metadata:T}}async checkBedrockHealth(){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await Dq(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{g.debug("[AmazonBedrockProvider] Starting health check...");let i=new o({}),l=(await s.send(i,{abortSignal:e.signal})).modelSummaries||[],c=l.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(g.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(t);let a=i;if(wr(i))throw new Error("Bedrock health check timed out after 10 seconds",{cause:i});let 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}):(g.error("[AmazonBedrockProvider] Health check failed:",i),new Error(`Bedrock health check failed: ${l||"Unknown error"}`,{cause:i}))}finally{clearTimeout(t);try{s.destroy()}catch{}}}formatProviderError(e){return en(e,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:Mt,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:qr,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:mt,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:mt,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(e,t){let n=t||"amazon.titan-embed-text-v2:0";g.debug("Generating embedding",{provider:this.providerName,model:n,textLength:e.length});try{let{InvokeModelCommand:o}=await Promise.resolve().then(()=>(Mq(),KBe)),s=JSON.stringify({inputText:e}),i=new o({modelId:n,contentType:"application/json",accept:"application/json",body:s}),a=await je(this.bedrockClient.send(i),6e4,new Error("Bedrock embedding API call timed out")),l=JSON.parse(new TextDecoder().decode(a.body));if(!l.embedding||!Array.isArray(l.embedding))throw new Error("Invalid embedding response from Bedrock");return g.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:l.embedding.length}),l.embedding}catch(o){throw g.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:e.length}),this.handleProviderError(o)}}async embedMany(e,t){let n=t||"amazon.titan-embed-text-v2:0";g.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:e.length});try{let o=await Promise.all(e.map(s=>this.embed(s,n)));return g.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw g.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:e.length}),this.handleProviderError(o)}}}});var aze={};de(aze,{AmazonBedrockProvider:()=>jse,bedrockTracer:()=>Lq,loadBedrockControl:()=>Dq});var lze=E(()=>{"use strict";ize();Bse();zse()});var cze={};de(cze,{AzureOpenAIProvider:()=>Gse});var Gse,uze=E(()=>{"use strict";Dt();X();ea();Ko();Kp();hc();Ag();Gse=class extends $n{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,n,o){let s=o?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",i=process.env.AZURE_OPENAI_ENDPOINT||"",a;if(i)try{a=new URL(i.includes("://")?i:`https://${i}`)}catch{a=void 0}let l=a?.hostname??"",c=a?.pathname&&a.pathname!=="/"?a.pathname.replace(/\/+$/,""):"",u=/\.(openai|cognitiveservices)\.azure\.com$/.test(l),p;u?p="/openai":p=/\/openai(?:\/v\d+)?$/.test(c)?c:`${c}/openai`;let m=a?.origin??"",f=o?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",h=o?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",y=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,x=o?.useMaxCompletionTokens??(y===void 0?void 0:/^(1|true|yes)$/i.test(y));s||an(uye()),m||an(dye()),super("azure",e,t,{baseURL:m,apiKey:s}),this.azureDeployment=f,this.azureApiVersion=h,this.azureResourceOrigin=m,this.azureDeploymentPathPrefix=p,this.useMaxCompletionTokensOverride=x,g.shouldLog("debug")&&g.debug("Azure OpenAI Provider initialized",jB({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){let t=[{match:n=>/401/.test(n.message),errorClass:Mt,message:"Invalid Azure OpenAI API key or endpoint."},...tn];return en(e,t,"azure",this.modelName)}getChatCompletionsURL(e){let t=e||this.azureDeployment,n=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${n}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){let n=this.useMaxCompletionTokensOverride??E1e(t);return e.max_tokens!==void 0&&n?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}});function dze(r){return r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71?"image/png":r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255?"image/jpeg":r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===69&&r[10]===66&&r[11]===80?"image/webp":r.length>=6&&r[0]===71&&r[1]===73&&r[2]===70?"image/gif":"image/png"}var pze=E(()=>{"use strict"});function qse(r){return r.map(e=>typeof e.content=="string"?{role:e.role,content:e.content}:{role:e.role,content:e.content.map(t=>t.type==="image"||t.type==="document"?{type:t.type,media_type:t.source.media_type,base64_chars:t.source.data.length}:t)})}var mze=E(()=>{"use strict"});var Uq,gze=E(()=>{Uq=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0}});var fze=E(()=>{fo()});function Fq(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var Vse,Hse,Kse=E(()=>{fze();Vse=r=>(Vse=Array.isArray,Vse(r)),Hse=Vse});function*j_r(r){if(!r)return;if(hze in r){let{values:n,nulls:o}=r;yield*n.entries();for(let s of o)yield[s,null];return}let e=!1,t;r instanceof Headers?t=r.entries():Hse(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=Hse(n[1])?n[1]:[n[1]],i=!1;for(let a of s)a!==void 0&&(e&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var hze,yze,xze=E(()=>{Kse();hze=Symbol.for("brand.privateNullableHeaders");yze=r=>{let e=new Headers,t=new Set;for(let n of r){let o=new Set;for(let[s,i]of j_r(n)){let a=s.toLowerCase();o.has(a)||(e.delete(s),o.add(a)),i===null?(e.delete(s),t.add(a)):(e.append(s,i),t.delete(a))}}return{[hze]:!0,values:e,nulls:t}}});function V_r(r){let e=new dm(r);return delete e.batches,e}function H_r(r){let e=new ti(r);return delete e.messages.batches,e}var G_r,q_r,$q,Wse=E(()=>{aM();use();P_();gze();Kse();xze();aM();G_r="vertex-2023-10-16",q_r=new Set(["/v1/messages","/v1/messages?beta=true"]),$q=class extends Jn{constructor({baseURL:e=Uq("ANTHROPIC_VERTEX_BASE_URL"),region:t=Uq("CLOUD_ML_REGION")??null,projectId:n=Uq("ANTHROPIC_VERTEX_PROJECT_ID")??null,...o}={}){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,...o}),this.messages=V_r(this),this.beta=H_r(this),this.region=t,this.projectId=n,this.accessToken=o.accessToken??null,o.authClient&&o.googleAuth)throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");o.authClient?this._authClientPromise=Promise.resolve(o.authClient):(this._auth=o.googleAuth??new iP({scopes:"https://www.googleapis.com/auth/cloud-platform"}),this._authClientPromise=this._auth.getClient())}validateHeaders(){}async prepareOptions(e){let t=await this._authClientPromise,n=await t.getRequestHeaders(),o=t.projectId??n["x-goog-user-project"];!this.projectId&&o&&(this.projectId=o),e.headers=yze([n,e.headers])}async buildRequest(e){if(Fq(e.body)&&(e.body={...e.body}),Fq(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=G_r)),q_r.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(!Fq(e.body))throw new Error("Expected request body to be an object for post /v1/messages");let t=e.body.model;e.body.model=void 0;let o=e.body.stream??!1?"streamRawPredict":"rawPredict";e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${t}:${o}`}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)}}});var Jse={};de(Jse,{AnthropicVertex:()=>$q,BaseAnthropic:()=>Jn,default:()=>$q});var Xse=E(()=>{Wse();Wse()});async function K_r(){return Yse||(Yse=await Promise.resolve().then(()=>(Xse(),Jse))),Yse}function J_r(r){let e=[],t=new Map,n=0,o=s=>{let i=`${n}:${s??"x"}`,a=t.get(i);return a||(a={type:"tool_step",callParts:[],resultParts:[]},t.set(i,a),e.push(a)),a};for(let s of r){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}let i=s.role==="assistant"?"assistant":s.role==="user"?"user":null;!i||!s.content||s.content.trim().length===0||(n++,e.push({type:"regular",role:i,parts:[s.content]}))}return e}function Zse(r,e,t){let n=r[r.length-1];n&&n.role===e&&Array.isArray(n.content)?n.content.push(...t):r.push({role:e,content:[...t]})}function X_r(r,e){let t=r.callParts,n=r.resultParts,o=Math.min(t.length,n.length);(o!==t.length||o!==n.length)&&g.debug("[GoogleVertex] Unbalanced tool step in Claude history replay",{calls:t.length,results:n.length,paired:o});let s=[],i=[];for(let a=0;a<o;a++){let l=`hist_${e}_${a}`;s.push({type:"tool_use",id:l,name:t[a].name,input:t[a].input}),i.push({type:"tool_result",tool_use_id:l,content:n[a]})}return{uses:s,results:i}}function Y_r(r){let e=t=>Array.isArray(t.content)&&t.content.length>0&&t.content.every(n=>n.type==="tool_result");for(;r.length>0&&(r[0].role!=="user"||e(r[0]));)r.shift()}function eie(r){let e=[],t=0;for(let n of J_r(r)){if(n.type==="regular"){Zse(e,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}let{uses:o,results:s}=X_r(n,t);o.length!==0&&(t++,Zse(e,"assistant",o),Zse(e,"user",s))}if(Y_r(e),g.shouldLog("debug")){let n=e.flatMap(o=>Array.isArray(o.content)?o.content:[]);g.debug("[GoogleVertex] Replayed Claude history with tool turns",{historyMessages:e.length,toolUseBlocks:n.filter(o=>o.type==="tool_use").length,toolResultBlocks:n.filter(o=>o.type==="tool_result").length})}return e}function tie(r,e){let t=r[r.length-1];if(t&&t.role==="user"){let n=Array.isArray(t.content)?t.content:[{type:"text",text:t.content}],o=Array.isArray(e)?e:[{type:"text",text:e}];t.content=[...n,...o];return}r.push({role:"user",content:e})}function py(r){if(!r||typeof r!="object")return;let e=["additionalProperties","default","$schema","$id","$ref","definitions","$defs","examples","errorMessage"];for(let n of e)n in r&&delete r[n];typeof r.exclusiveMinimum=="boolean"&&(r.exclusiveMinimum===!0&&typeof r.minimum=="number"?(r.exclusiveMinimum=r.minimum,delete r.minimum):delete r.exclusiveMinimum),typeof r.exclusiveMaximum=="boolean"&&(r.exclusiveMaximum===!0&&typeof r.maximum=="number"?(r.exclusiveMaximum=r.maximum,delete r.maximum):delete r.exclusiveMaximum);let t=2147483647;if(typeof r.maximum=="number"&&r.maximum>t&&delete r.maximum,typeof r.minimum=="number"&&r.minimum<-t&&delete r.minimum,r.properties&&typeof r.properties=="object")for(let n of Object.values(r.properties))n&&typeof n=="object"&&py(n);if(r.items&&typeof r.items=="object")if(Array.isArray(r.items))for(let n of r.items)n&&typeof n=="object"&&py(n);else py(r.items);for(let n of["allOf","anyOf","oneOf"])if(Array.isArray(r[n]))for(let o of r[n])o&&typeof o=="object"&&py(o)}function vze(r,e,t){let n=Zj({contents:r,availableInputTokens:mi("vertex",e),provider:"vertex",observedPromptTokens:t});if(!n)return!1;let o=new Set(n.drop),s=new Set(n.truncate),i=[];for(let a=0;a<r.length;a++){if(o.has(a))continue;let l=r[a];if(s.has(a)&&Array.isArray(l.parts)){i.push({...l,parts:l.parts.map(c=>{if(!("functionResponse"in c))return c;let u=c.functionResponse,p=JSON.stringify(u.response)??"";return p.length<=eEr?c:{functionResponse:{name:u.name,response:{result:cP(p)}}}})});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:Yj}]})}return r.length=0,r.push(...i),!0}function bze(r,e,t){let n=Rq({conversation:r,availableInputTokens:mi("vertex",e),fixedOverheadTokens:0,provider:"vertex",observedPromptTokens:t,observedDescribesCurrentPayload:!0});if(!n)return!1;let o=new Set(n.drop),s=new Set(n.truncate),i=[];for(let a=0;a<r.length;a++){if(o.has(a))continue;let l=r[a];if(s.has(a)&&Array.isArray(l.content)){i.push({...l,content:l.content.map(c=>{if(c.type!=="tool_result")return c;let u=typeof c.content=="string"?c.content:JSON.stringify(c.content)??"";return{...c,content:Cq(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:Eq}]})}return r.length=0,r.push(...i),!0}var Yse,W_r,rie,Bq,zq,gM,FE,Z_r,Q_r,Qse,eEr,nie,oie=E(()=>{"use strict";ro();Qr();eu();Pz();tG();tte();cs();Ph();nz();Hr();so();Dt();ea();Tt();_se();qte();qI();X();Ere();bse();zj();pze();jj();Ko();Ea();Cre();O_();_l();$re();Kv();rG();$d();Xw();ac();gr();Dd();Kp();cI();dg();mze();YI();Yse=null;W_r=()=>!0;rie=()=>an(zL()),Bq=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",zq=(r,e)=>{let t=e||Bq();if(!r)return t;let n=r.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||S2.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":t},gM=zq,FE=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",Z_r=()=>!!(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),Q_r=async(r,e)=>{let t=r||Bq();return{projectId:rie(),region:t,...e!==void 0&&{timeout:e},maxRetries:0}},Qse=r=>r.toLowerCase().includes("claude"),eEr=2048;nie=class r extends oo{projectId;location;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(e,t,n,o,s){super(e,"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))),Z_r()||an(Cye()),this.projectId=s?.projectId||rie(),this.location=o||s?.location||Bq(),g.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),g.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return FE()}async getAISDKModel(){throw new Le({code:tt.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(e){this.validateStreamOptions(e)}async preprocessNativeFileInput(e){if(e.input&&jI(e.input),e.input?.files?.length)try{await GI(e,100*1024*1024,this.providerName)}catch(t){g.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await Uv(e.input)}async executeStream(e,t){let n=e.model||this.modelName||FE();return KA({name:"neurolink.provider.stream",tracer:Oe.provider,attributes:{[Pe.GEN_AI_SYSTEM]:this.providerName,[Pe.GEN_AI_MODEL]:n,[Pe.GEN_AI_OPERATION]:"stream",[Pe.NL_PROVIDER]:this.providerName}},async o=>{let s=Date.now(),i=e.tools||{};await this.preprocessNativeFileInput(e);let l={...await Je({name:"neurolink.message.build",tracer:Oe.provider,attributes:{[Pe.NL_PROVIDER]:this.providerName,"message.count":1,"message.build.count":1,"message.build.path":"vertex.native.stream"}},async()=>this.processCSVFilesForNativeSDK(e)),tools:i};try{let c;Qse(n)?(g.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(i).length}),c=await this.executeNativeAnthropicStream(l)):(g.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);let u=this.wrapStreamResultWithLifecycle(e,c,s);return this.emitStreamEnd(n,s,!0,void 0,c.finishReason),u}catch(c){throw this.fireGenerateOnError(e,c,s),this.emitStreamEnd(n,s,!1,c),c}},o=>o.stream,(o,s)=>this.preserveStreamResultAccessors(o,{...o,stream:s}))}emitStreamEnd(e,t,n,o,s){let i=this.neurolink?.getEventEmitter();i&&i.emit("stream:end",{provider:this.providerName,responseTime:Date.now()-t,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:e,provider:this.providerName,finishReason:n?s??"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async createVertexGenAIClient(e){let t=rie(),n=e||this.location||Bq(),s=(await Promise.resolve().then(()=>(ww(),Sw))).GoogleGenAI;if(!s)throw new Le({code:tt.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});let i=s;return new i({vertexai:!0,project:t,location:n,httpOptions:{fetch:yt()}})}buildGeminiFunctionDeclaration(e,t){let n={name:e,description:t.description||`Tool: ${e}`},s=t.parameters||t.inputSchema;if(s){let i=xn(s,"openApi3"),a=pn(i);a.$schema&&delete a.$schema;let l=pi(a);py(l),n.parametersJsonSchema=l}return n}refreshGeminiToolDeclarations(e,t,n,o){if(!e||!t)return;let s=new Set(t.map(i=>i.name));for(let[i,a]of Object.entries(e))s.has(i)||(t.push(this.buildGeminiFunctionDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),g.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Gemini declarations.`))}resolveGeminiToolOnMiss(e,t,n,o,s){if(!n)return;let i=mI(t,e);if(i?.execute)return n.some(a=>a.name===e)||n.push(this.buildGeminiFunctionDeclaration(e,i)),o.set(e,i.execute),s.delete(e),g.info(`[GoogleVertex] Tool "${e}" resolved mid-turn via discovery \u2014 executing.`),o.get(e)}buildAnthropicToolDeclaration(e,t){let n={name:e,description:t.description||`Tool: ${e}`,input_schema:{type:"object"}},s=t.parameters||t.inputSchema;if(s){let i=xn(s),a=pn(i);n.input_schema={type:"object",properties:a.properties||{},required:a.required||[]}}return n}refreshAnthropicToolDeclarations(e,t,n,o){if(!e||!t)return;let s=new Set(t.map(i=>i.name));for(let[i,a]of Object.entries(e))s.has(i)||(t.push(this.buildAnthropicToolDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),g.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Anthropic declarations.`))}resolveAnthropicToolOnMiss(e,t,n,o,s){if(!n)return;let i=mI(t,e);if(i?.execute)return n.some(a=>a.name===e)||n.push(this.buildAnthropicToolDeclaration(e,i)),o.set(e,i.execute),s.delete(e),g.info(`[GoogleVertex] Tool "${e}" resolved mid-turn via discovery \u2014 executing.`),o.get(e)}async executeNativeGemini3Stream(e){let t=e.model||this.modelName||FE(),n=gM(t,e.region),o=await this.createVertexGenAIClient(n);g.debug("[GoogleVertex] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0,project:this.projectId,location:n});let s=[],i=[{text:e.input.text??""}],a=e.input;if(a?.pdfFiles&&a.pdfFiles.length>0){g.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(let ye of a.pdfFiles){let Fe;typeof ye=="string"?wn.existsSync(ye)?Fe=wn.readFileSync(ye):Fe=Buffer.from(ye,"base64"):Fe=ye;let Ee=Fe.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:Ee}})}}if(await eG(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){g.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(let ye of a.images){let Fe=i_(ye),Ee,Rt="image/jpeg";if(typeof Fe=="string")if(wn.existsSync(Fe)){Ee=wn.readFileSync(Fe);let ue=Ov(Fe);Rt=ue.startsWith("image/")?ue:this.detectImageType(Ee)}else if(Fe.startsWith("data:")){let ue=Fe.match(/^data:([^;]+);base64,(.+)$/);if(ue)Rt=ue[1],Ee=Buffer.from(ue[2],"base64");else continue}else if(Fe.startsWith("http://")||Fe.startsWith("https://"))try{let ue=await fetch(Fe);if(!ue.ok){g.warn(`[GoogleVertex] Image fetch failed: ${ue.status} ${ue.statusText}, skipping`,{url:Wr(Fe)});continue}let qe=await ue.arrayBuffer();Ee=Buffer.from(qe);let Be=ue.headers.get("content-type");Be&&Be.startsWith("image/")&&(Rt=Be.split(";")[0])}catch(ue){g.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${ue instanceof Error?ue.message:String(ue)}`,{url:Wr(Fe)});continue}else Ee=Buffer.from(Fe,"base64"),Rt=this.detectImageType(Ee);else Ee=Fe,Rt=this.detectImageType(Ee);let Xe=Ee.toString("base64");i.push({inlineData:{mimeType:Rt,data:Xe}})}}L_(s,e.conversationMessages),s.push({role:"user",parts:i});let l,c=new Hd;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){let ye=Rg(e.tools,"functionDeclarations");l=ye.toolsConfig;for(let[Fe,Ee]of ye.executeMap)c.set(Fe,Ee);g.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ye.toolsConfig[0].functionDeclarations.length,toolNames:ye.toolsConfig[0].functionDeclarations.map(Fe=>Fe.name)})}let u=e,p=!1;if(u.schema&&l){p=!0;let ye=xn(u.schema,"openApi3"),Fe=pn(ye);Fe.$schema&&delete Fe.$schema;let Ee=pi(Fe),Rt=l[0]?.functionDeclarations||[];Rt.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:Ee}),l=[{functionDeclarations:Rt}],g.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(Ee),totalTools:Rt.length})}let m=_a(this.providerName,t,{temperature:e.temperature??1,...e.topP!==void 0&&{topP:e.topP}},"vertex.gemini"),f={...m.temperature!==void 0&&{temperature:m.temperature},maxOutputTokens:e.maxTokens};nP(t)&&(f.maxOutputTokens&&f.maxOutputTokens>Nl&&(g.warn(`[GoogleVertex] Capping maxOutputTokens from ${f.maxOutputTokens} to ${Nl} for ${t}`),f.maxOutputTokens=Nl),f.maxOutputTokens||(f.maxOutputTokens=Nl)),m.topP!==void 0&&(f.topP=m.topP),e.topK!==void 0&&(f.topK=e.topK),e.stopSequences&&e.stopSequences.length>0&&(f.stopSequences=e.stopSequences),l&&(f.tools=l);let h=e.systemPrompt||"";p&&(h=h+`
|
|
1129
|
+
`);return{...s!==void 0?{system:s}:{},messages:t}},jBe=r=>{if(!(!r||r==="auto")){if(r==="none")return{type:"none"};if(r==="required")return{type:"any"};if(typeof r=="object"){let e=r;if(e.type==="tool"&&e.toolName)return{type:"tool",name:e.toolName}}}},qSr=r=>{switch(r){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},GBe=6e5,Mse=class extends oo{client;authMethod;subscriptionTier;enableBetaFeatures;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,n,o){let s=!!(o?.apiKey&&!o?.oauthToken),i=s?null:(o?.oauthToken?{accessToken:o.oauthToken}:null)??n?.oauthToken??BBe(),a=s?"api_key":n?.authMethod??GSr(i),l=n?.subscriptionTier??(a==="oauth"?jSr(i):"api"),c=e||Pq(),u=c;!process.env.ANTHROPIC_BASE_URL&&l!=="api"&&!uM(c,l)&&(u=Sq(l),g.warn("Model not available for subscription tier, using recommended model",{requestedModel:c,subscriptionTier:l,recommendedModel:u})),super(u,"anthropic",t),this.enableBetaFeatures=n?.enableBetaFeatures??!0,this.oauthToken=i,this.subscriptionTier=l,this.authMethod=a;let m=this.getAuthHeaders(),f;if(g.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){g.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");let h=this.oauthToken,y=mBe(()=>h.accessToken,this.enableBetaFeatures,!1,!0);f=new Xd({apiKey:"oauth-authenticated",fetch:vse(y),timeout:GBe,maxRetries:0}),g.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),g.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{let h=o?.apiKey??n?.apiKey??$Be(),y=(()=>{let x=process.env.ANTHROPIC_BASE_URL;if(!x)return;let b=x.replace(/\/+$/,""),T=b.replace(/\/v\d+$/,"");return T!==b&&g.debug("[AnthropicProvider] Stripping the version suffix from ANTHROPIC_BASE_URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:Ir(x),rewrittenTo:Ir(T)}),T})();f=new Xd({apiKey:h,defaultHeaders:m,...y&&{baseURL:y},fetch:vse(yt()),timeout:GBe,maxRetries:0}),g.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.client=f,this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},g.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?Iq["anthropic-beta"]:"disabled"})}getAuthHeaders(){let e={},t=!!process.env.ANTHROPIC_BASE_URL;if(this.enableBetaFeatures)if(t){let n=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",o=[...hb,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];n&&o.push("context-1m-2025-08-07"),e["anthropic-beta"]=o.join(",")}else e["anthropic-beta"]=Iq["anthropic-beta"];return t&&(e["User-Agent"]=Yd),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return g.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;let t=uM(e,this.subscriptionTier);return t||g.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return wq(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){g.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){g.debug("Token has no expiry information, assuming valid");return}let e=Date.now(),t=this.oauthToken.expiresAt<=e,n=this.oauthToken.expiresAt<=e+3e5;if(!t&&!n){g.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new Mt("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);g.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}g.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});let o=this.oauthToken,s=o.refreshToken;this.refreshPromise=(async()=>{let a=new AbortController,l=setTimeout(()=>a.abort(),3e4),c=await fetch(ME,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Yd},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:s,client_id:bq}),signal:a.signal});if(clearTimeout(l),!c.ok){let m=await c.text();throw new Mt(`Failed to refresh OAuth token: ${c.status} ${m}`,this.providerName)}let u=await c.json();o.accessToken=u.access_token,o.refreshToken=u.refresh_token||o.refreshToken,o.expiresAt=u.expires_in?Date.now()+u.expires_in*1e3:void 0,o.tokenType=u.token_type||"Bearer";let p=o;try{let m=Fr(Op(),".neurolink");to(m)||lA(m,{recursive:!0});let f=Fr(m,"anthropic-credentials.json"),h=`${f}.tmp`,x={...to(f)?JSON.parse(Gc(f,"utf-8")):{},type:"oauth",oauth:p,updatedAt:Date.now()};aA(h,JSON.stringify(x,null,2),{mode:384}),iX(h,f),g.debug("Refreshed OAuth credentials persisted to disk")}catch(m){g.warn("Failed to persist refreshed OAuth token to disk",{error:m instanceof Error?m.message:String(m)})}g.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!u.refresh_token,expiresIn:u.expires_in})})();try{await this.refreshPromise}catch(i){throw i instanceof Mt?i:new Mt(`Failed to refresh OAuth token: ${i instanceof Error?i.message:String(i)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,n){this.lastResponseMetadata={rateLimit:e,...t?{requestId:t}:{}},this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),n&&(n.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=n.inputTokens,this.usageInfo.tokensUsed+=n.inputTokens),n.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=n.outputTokens,this.usageInfo.tokensUsed+=n.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&&g.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&&g.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return Pq()}getAISDKModel(){let e=this.client,t=this.providerName,n=this.modelName||Pq(),o=a=>this.getTimeout(a??{}),s=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:n,supportedUrls:{},doGenerate:async a=>{await s();let l=zBe(a.prompt),c=l.messages,u=l.system,p=(a.tools??[]).filter(F=>F.type==="function").map(F=>{let B=om(F);return{name:F.name,...F.description?{description:F.description}:{},input_schema:F.inputSchema??{type:"object",properties:{}},...B?{cache_control:B}:{}}});p&&p.length===0&&(p=void 0);let m=a.toolChoice?jBe(a.toolChoice.type==="tool"?{type:"tool",toolName:a.toolChoice.toolName}:a.toolChoice.type):void 0,f;if(a.responseFormat?.type==="json"){f=a.responseFormat.name??"json";let F=a.responseFormat.schema??{type:"object"};p=[{name:f,description:a.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:F}],m={type:"tool",name:f}}let h=a.providerOptions?.anthropic?.finalResultSchema,y=!1;if(!f&&h){let F=Ise(p,h);p=F.tools,y=F.applied,F.applied&&(u=Pse(u))}let x=a.providerOptions?.anthropic?.thinking,b=Sse({system:u,tools:p,messages:c}),T=wse(c,Aq-b),w=_a("anthropic",n,{...a.temperature!==void 0&&a.temperature!==null?{temperature:a.temperature}:{},...a.topP!==void 0&&a.topP!==null?{topP:a.topP}:{}},"anthropic.doGenerate"),C={model:n,messages:T,max_tokens:A_(n,a.maxOutputTokens),...u?{system:u}:{},...w.temperature!==void 0?{temperature:w.temperature}:{},...w.topP!==void 0?{top_p:w.topP}:{},...a.stopSequences&&a.stopSequences.length>0?{stop_sequences:a.stopSequences}:{},...p?{tools:p}:{},...m?{tool_choice:m}:{},...x?{thinking:x}:{}},R=a.timeout,k=R!=null,P=C.max_tokens>8192&&!k?Math.max(o(a),3e5):o(a),I=Ws(P,t,"generate"),A;try{A=await e.messages.create(C,{signal:Ux(a.abortSignal,I?.controller.signal)})}finally{I?.cleanup()}let M=[],U,$=[],L=!1;for(let F of A.content)F.type==="thinking"?M.push({type:"reasoning",text:F.thinking}):F.type==="text"?f?$.push(F.text):M.push({type:"text",text:F.text}):F.type==="tool_use"&&(f&&F.name===f?(L=!0,M.push({type:"text",text:xP(F.input)})):y&&F.name===mM?U=xP(F.input):M.push({type:"tool-call",toolCallId:F.id,toolName:F.name,input:xP(F.input)}));if(f&&!L&&$.length>0&&M.push({type:"text",text:$.join("")}),U!==void 0){let F=M.filter(B=>B.type==="reasoning");M.length=0,M.push(...F,{type:"text",text:U}),g.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:U.length})}let z=A.usage.cache_read_input_tokens??0,j=A.usage.cache_creation_input_tokens??0;return{content:M,finishReason:{unified:U!==void 0?"stop":qSr(A.stop_reason),raw:A.stop_reason??"stop"},usage:{inputTokens:{total:A.usage.input_tokens+z+j,noCache:A.usage.input_tokens,cacheRead:z,cacheWrite:j},outputTokens:{total:A.usage.output_tokens,text:A.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:C},response:{id:A.id,modelId:A.model,headers:bBe()??{},body:A}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}formatProviderError(e){return en(e,[{match:n=>n.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(n.message),errorClass:Mt,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:n=>n.statusCode===429||/rate limit|too_many_requests|429/i.test(n.message),errorClass:qr,message:"Anthropic rate limit exceeded. Please try again later."},{match:n=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(n.message),errorClass:cn,message:n=>`Connection error: ${n.message}`},{match:n=>/500|502|503|504|server error/i.test(n.message),errorClass:mt,message:n=>`Server error: ${n.message}`},{match:()=>!0,errorClass:mt,message:n=>`Anthropic error: ${n.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();let{result:n,snapshot:o}=await xBe(()=>super.generate(e,t));return n&&o&&(this.recordLimitSnapshot(o),n.limits=o,n.analytics&&(n.analytics.limits=o)),n}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),SBe(e),wBe(e,this.modelName)}async executeStream(e,t){return TBe(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);let n=this.getTimeout(e),o=Ws(n,this.providerName,"stream"),s=new AbortController,i=f1([e.abortSignal,o?.controller.signal,s.signal]).signal,a,l,c,u,p=!1;try{u=!e.disableTools&&this.supportsTools(),a=u?e.tools||await this.getAllTools():{},l=u?Rg(a,"input_schema"):void 0;let oe=await this.buildMessagesForStream(e);if(c=zBe(oe),e.schema&&l&&l.length>0){let Z=Ise(l,xn(e.schema));l=Z.tools,p=Z.applied,Z.applied&&(c.system=Pse(c.system))}}catch(oe){throw o?.cleanup(),this.handleProviderError(oe)}let m=this.modelName||Pq(),f=u&&l&&l.length>0?jBe(dG(e,a,u)):void 0,h=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,y=zSr.startSpan("neurolink.provider.streamText",{kind:br.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":m}}),x=e.maxSteps||Jo,b=this.neurolink?.getEventEmitter(),T=Fu(),{push:w}=T,{usagePromise:C,finishPromise:R,resolveUsage:k,resolveFinish:P}=lG();C.then(oe=>{y.setAttribute("gen_ai.usage.input_tokens",oe.promptTokens||0),y.setAttribute("gen_ai.usage.output_tokens",oe.completionTokens||0),oe.cacheReadTokens&&y.setAttribute("gen_ai.usage.cached_input_tokens",oe.cacheReadTokens);let Z=Us(this.providerName,this.modelName,{input:oe.promptTokens||0,output:oe.completionTokens||0,total:oe.totalTokens||0,...oe.cacheReadTokens?{cacheReadTokens:oe.cacheReadTokens}:{},...oe.cacheCreationTokens?{cacheCreationTokens:oe.cacheCreationTokens}:{}});Z&&Z>0&&y.setAttribute("neurolink.cost",Z)}).catch(()=>{}),R.then(oe=>{y.setAttribute("gen_ai.response.finish_reason",oe||"unknown"),y.end()}).catch(()=>{y.end()});let I,A=this.client,M=[],U=Date.now(),$=0,L=0,z=0,j=0,F=null,B=()=>({promptTokens:$,completionTokens:L,totalTokens:$+z+j+L,...z>0?{cacheReadTokens:z}:{},...j>0?{cacheCreationTokens:j}:{}}),O="",W,re=(oe,Z)=>{let we=ve=>{if(typeof ve=="string")return ve;try{return JSON.stringify(ve)??""}catch{return""}};return zt(we(oe),"anthropic")+zt(we(Z),"anthropic")},pe=(async()=>{let oe=c.messages.slice(),Z,we;for(let ve=0;ve<x;ve++){if(l){let ce=new Set(l.map(_=>_.name)),Ne=Object.fromEntries(Object.entries(a).filter(([_])=>!ce.has(_)));Object.keys(Ne).length>0&&(l.push(...Rg(Ne,"input_schema")??[]),g.info(`[Anthropic] ${Object.keys(Ne).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(Ne).join(", ")}`))}let ae=Rq({conversation:oe,availableInputTokens:mi("anthropic",m,e.maxTokens??void 0),fixedOverheadTokens:re(c.system,l),provider:"anthropic",observedPromptTokens:Z,previousSentEstimate:we,onSentEstimate:ce=>{we=ce}});if(ae){let ce=new Set(ae.drop),Ne=new Set(ae.truncate),_=[];for(let G=0;G<oe.length;G++){if(ce.has(G))continue;let Q=oe[G];if(Ne.has(G)&&Array.isArray(Q.content)){_.push({...Q,content:Q.content.map(q=>q.type==="tool_result"?{...q,content:Cq(typeof q.content=="string"?q.content:JSON.stringify(q.content)??"")}:q)});continue}_.push(Q)}if(ce.size>0){let G=_.findIndex(Q=>Array.isArray(Q.content)&&Q.content.some(q=>q.type==="tool_use"||q.type==="tool_result"));G<0&&(G=Math.min(1,_.length)),_.splice(G,0,{role:"user",content:[{type:"text",text:Eq}]})}oe.length=0,oe.push(..._)}let H=Sse({system:c.system,tools:l,messages:oe}),V=wse(oe,Aq-H),ne=_a("anthropic",m,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream"),N={model:m,messages:V,max_tokens:A_(m,e.maxTokens),stream:!0,...c.system?{system:c.system}:{},...ne.temperature!==void 0?{temperature:ne.temperature}:{},...l&&l.length>0?{tools:l}:{},...f?{tool_choice:f}:{},...h?{thinking:h}:{}},Y=await Ru(()=>A.messages.create(N,{signal:i??void 0}),pt.getActiveSpan()??void 0,`${this.providerName} stream`),ee=new Map,ie=new Map,le=new Map,ye=new Map,Fe=null,Ee=0;for await(let ce of Y)if(ce.type==="message_start"){$+=ce.message.usage.input_tokens??0;let Ne=ce.message.usage.output_tokens??0;L+=Ne-Ee,Ee=Ne,z+=ce.message.usage.cache_read_input_tokens??0,j+=ce.message.usage.cache_creation_input_tokens??0,Z=(ce.message.usage.input_tokens??0)+(ce.message.usage.cache_read_input_tokens??0)+(ce.message.usage.cache_creation_input_tokens??0)}else if(ce.type==="content_block_start")ee.set(ce.index,ce.content_block.type),ce.content_block.type==="tool_use"&&ye.set(ce.index,{id:ce.content_block.id,name:ce.content_block.name,inputJson:""});else if(ce.type==="content_block_delta"){let Ne=ce.delta;if(Ne.type==="text_delta")ie.set(ce.index,(ie.get(ce.index)??"")+Ne.text),p?O+=Ne.text:w({content:Ne.text});else if(Ne.type==="thinking_delta"){let _=le.get(ce.index)??{text:"",signature:""};_.text+=Ne.thinking,le.set(ce.index,_),w({content:"",reasoning:Ne.thinking})}else if(Ne.type==="signature_delta"){let _=le.get(ce.index)??{text:"",signature:""};_.signature+=Ne.signature,le.set(ce.index,_)}else if(Ne.type==="input_json_delta"){let _=ye.get(ce.index);_&&(_.inputJson+=Ne.partial_json)}}else if(ce.type==="message_delta"){Fe=ce.delta.stop_reason??Fe;let Ne=ce.usage?.output_tokens??Ee;L+=Ne-Ee,Ee=Ne}if(F=Fe,p){let ce=[...ye.values()].find(Ne=>Ne.name===mM);if(ce){W=UBe(ce.inputJson),F="end_turn",g.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:W.length});break}}if(Fe!=="tool_use"||ye.size===0)break;let Rt=[],Xe=[...ee.keys()].sort((ce,Ne)=>ce-Ne);for(let ce of Xe){let Ne=ee.get(ce);if(Ne==="thinking"){let _=le.get(ce);_&&_.text.length>0&&Rt.push({type:"thinking",thinking:_.text,signature:_.signature})}else if(Ne==="text"){let _=ie.get(ce);_&&_.length>0&&Rt.push({type:"text",text:_})}else if(Ne==="tool_use"){let _=ye.get(ce);if(_){let G;try{G=_.inputJson?JSON.parse(_.inputJson):{}}catch{G={}}Rt.push({type:"tool_use",id:_.id,name:_.name,input:G})}}}oe.push({role:"assistant",content:Rt});let ue=[],qe=[],Be=[];for(let ce of ye.values()){let Ne;try{Ne=ce.inputJson?JSON.parse(ce.inputJson):{}}catch{Ne={}}qe.push({type:"tool-call",toolCallId:ce.id,toolName:ce.name,args:Ne}),M.push(ce.name);let _=a[ce.name]??pI(a,ce.name);try{if(!_?.execute)throw new Error(`Tool not found: ${ce.name}`);let G=await _.execute(Ne,{toolCallId:ce.id,messages:[]});Be.push({type:"tool-result",toolCallId:ce.id,toolName:ce.name,result:G}),ue.push({type:"tool_result",tool_use_id:ce.id,content:Ese(G)})}catch(G){let Q=G instanceof Error?G.message:String(G);Be.push({type:"tool-result",toolCallId:ce.id,toolName:ce.name,error:Q}),ue.push({type:"tool_result",tool_use_id:ce.id,content:`Error: ${Q}`,is_error:!0})}}Yw(b,Be.map(ce=>({toolName:ce.toolName,result:ce.result,error:ce.error}))),this.handleToolExecutionStorage(qe,Be,e,new Date).catch(ce=>{g.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ce instanceof Error?ce.message:String(ce)})}),oe.push({role:"user",content:ue})}k(B()),P(F??"stop")})().catch(oe=>{throw I=oe,g.error("Anthropic: Stream error",{error:oe instanceof Error?oe.message:String(oe)}),k(B()),P("error"),this.formatProviderError(oe)}).finally(()=>{if(p){let oe=W??O;oe.length>0&&w({content:oe})}o?.cleanup(),T.close()});pe.catch(()=>{});let Ae=this.providerName;return{stream:async function*(){let oe=0;try{for await(let Z of T.iterable)"content"in Z&&typeof Z.content=="string"&&Z.content.length>0&&oe++,yield Z;if(await pe,oe===0&&M.length===0){g.warn(`${Ae}: Stream produced no output \u2014 emitting enriched sentinel`);let Z=new Ta({message:"Stream produced no output"}),we=await Zp(Z,void 0,I);Qp(we),yield we}}catch(Z){let we=await Zp(Z,void 0,I);if(Qp(we),yield we,!Ta.isInstance(Z))throw Z}finally{s.signal.aborted||s.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],analytics:R.then(async()=>{let oe=await uG.createAnalytics(this.providerName,m,{textStream:(async function*(){})(),usage:C,finishReason:R},Date.now()-U,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),Z=vBe();return Z&&oe&&(this.recordLimitSnapshot(Z),oe.limits=Z),oe})}}async isAvailable(){try{return BBe()||$Be(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}});var VBe={};de(VBe,{ANTHROPIC_BETA_HEADERS:()=>Iq,AnthropicProvider:()=>Mse,ModelAccessError:()=>jR,getModelCapabilities:()=>wq,getRecommendedModelForTier:()=>Sq,isModelAvailableForTier:()=>uM});var HBe=E(()=>{"use strict";qBe();kse()});var KBe={};de(KBe,{Agent:()=>kwr,BedrockClient:()=>HSr,BedrockRuntimeClient:()=>Ose,Blob:()=>Rwr,Client:()=>Iwr,ConverseCommand:()=>Nse,ConverseStreamCommand:()=>Lse,Cron:()=>cwr,Dispatcher:()=>Pwr,File:()=>Cwr,FlowProducer:()=>lwr,FormData:()=>Ewr,GoogleAuth:()=>YSr,HTTPException:()=>hwr,Headers:()=>_wr,Hippocampus:()=>twr,HippocampusConfig:()=>rwr,Hono:()=>gwr,ImageFormat:()=>DE,InvokeEndpointCommand:()=>JSr,InvokeEndpointWithResponseStreamCommand:()=>XSr,Job:()=>iwr,ListFoundationModelsCommand:()=>KSr,MockAgent:()=>Nwr,Pool:()=>Awr,Queue:()=>owr,QueueScheduler:()=>awr,Request:()=>Swr,Response:()=>wwr,SageMakerRuntimeClient:()=>WSr,TextToSpeechClient:()=>QSr,VertexAI:()=>ZSr,Webhook:()=>ewr,Worker:()=>swr,convertToHtml:()=>mwr,cors:()=>fwr,createClient:()=>nwr,default:()=>VSr,extractRawText:()=>pwr,fetch:()=>Twr,getGlobalDispatcher:()=>Owr,interceptors:()=>Lwr,logger:()=>ywr,parseBuffer:()=>uwr,request:()=>Dwr,secureHeaders:()=>xwr,selectCover:()=>dwr,setGlobalDispatcher:()=>Mwr,streamSSE:()=>vwr,timeout:()=>bwr});var LE,Mi,VSr,HSr,KSr,Ose,Nse,Lse,DE,WSr,JSr,XSr,YSr,ZSr,QSr,ewr,twr,rwr,nwr,owr,swr,iwr,awr,lwr,cwr,uwr,dwr,pwr,mwr,gwr,fwr,hwr,ywr,xwr,vwr,bwr,Twr,Swr,wwr,_wr,Ewr,Cwr,Rwr,kwr,Awr,Iwr,Pwr,Mwr,Owr,Nwr,Lwr,Dwr,Mq=E(()=>{LE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:LE.get}):new Proxy(function(...t){return new Proxy({},{get:LE.get})},{get:LE.get,apply(t,n,o){return new Proxy({},{get:LE.get})},construct(t,n){return new Proxy({},{get:LE.get})}})}},Mi=new Proxy({},LE),VSr=Mi,{BedrockClient:HSr,ListFoundationModelsCommand:KSr,BedrockRuntimeClient:Ose,ConverseCommand:Nse,ConverseStreamCommand:Lse,ImageFormat:DE}=Mi,{SageMakerRuntimeClient:WSr,InvokeEndpointCommand:JSr,InvokeEndpointWithResponseStreamCommand:XSr}=Mi,{GoogleAuth:YSr,VertexAI:ZSr,TextToSpeechClient:QSr}=Mi,{Webhook:ewr}=Mi,{Hippocampus:twr,HippocampusConfig:rwr}=Mi,{createClient:nwr}=Mi,{Queue:owr,Worker:swr,Job:iwr,QueueScheduler:awr,FlowProducer:lwr}=Mi,{Cron:cwr}=Mi,{parseBuffer:uwr,selectCover:dwr}=Mi,{extractRawText:pwr,convertToHtml:mwr}=Mi,{Hono:gwr}=Mi,{cors:fwr,HTTPException:hwr,logger:ywr,secureHeaders:xwr,streamSSE:vwr,timeout:bwr}=Mi,Twr=globalThis.fetch,Swr=globalThis.Request,wwr=globalThis.Response,_wr=globalThis.Headers,Ewr=globalThis.FormData,Cwr=globalThis.File,Rwr=globalThis.Blob,kwr=Mi.Agent,Awr=Mi.Pool,Iwr=Mi.Client,Pwr=Mi.Dispatcher,Mwr=()=>{},Owr=()=>Mi,Nwr=Mi.MockAgent,Lwr={redirect:()=>r=>r,retry:()=>r=>r},Dwr=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});function Uwr(r,e){return{inputTokens:r.inputTokens+e.inputTokens,outputTokens:r.outputTokens+e.outputTokens,cacheReadTokens:(r.cacheReadTokens??0)+(e.cacheReadTokens??0)||void 0,cacheWriteTokens:(r.cacheWriteTokens??0)+(e.cacheWriteTokens??0)||void 0,reasoningTokens:(r.reasoningTokens??0)+(e.reasoningTokens??0)||void 0}}function Dse(r,e,t){let n=Fu(),o=new AbortController,s=()=>o.abort();t.abortSignal?.addEventListener("abort",s),t.abortSignal?.aborted&&o.abort();let i=new Map,a=!1,l=(async()=>{let c=e,u={inputTokens:0,outputTokens:0},p="",m="",f,h=[],y=[],x=!1;try{for(let T=0;T<r.maxSteps&&!o.signal.aborted;T++){if(r.planReclaim){let I=r.planReclaim(c,T);I&&(c=I.conversation)}let w=r.buildStepRequest(c,T),C=!1,R={push:I=>{C=!0,n.push(I)}},k;try{k=await Ru(async()=>{C=!1;try{return await r.executeStep(w,R,o.signal)}catch(I){throw C?new Oq(I):I}},void 0,`${r.providerLabel}.step`)}catch(I){throw I instanceof Oq?I.cause:I}if(u=Uwr(u,k.usage),f=k.rawStopReason,m=k.text||m,r.isMalformedStep?.(k)&&!a&&!o.signal.aborted){a=!0,g.warn(`[${r.providerLabel}] Malformed function call at step ${T+1}/${r.maxSteps}; retrying once.`),c=r.buildMalformedRetryNote?.(c)??c;continue}if(k.toolCalls.length===0){p=k.text||p;break}T===r.maxSteps-1&&(x=!0);let P=[];for(let I of k.toolCalls){h.push(I);let A=r.toolFailureBreaker,M=A?i.get(I.name):void 0;if(A&&M&&M.count>=A.maxRetries){let L={error:`TOOL_PERMANENTLY_FAILED: "${I.name}" has failed ${M.count} times. Last error: ${M.lastError}.`,status:"permanently_failed",do_not_retry:!0};P.push({...I,output:L,error:L.error,permanentlyFailed:!0}),y.push({id:I.id,name:I.name,input:I.args,output:L,error:L.error});continue}let U=t.tools?.[I.name],$=U?.execute?U:r.resolveToolOnMiss?.(I.name)??U;if(!$?.execute){let L=A?{error:`TOOL_NOT_FOUND: "${I.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${I.name}`};P.push({...I,output:L,error:L.error,permanentlyFailed:!!A}),y.push({id:I.id,name:I.name,input:I.args,output:L,error:L.error});continue}try{let L=await $.execute(I.args,{toolCallId:I.id,abortSignal:o.signal});P.push({...I,output:L}),y.push({id:I.id,name:I.name,input:I.args,output:L})}catch(L){let z=L instanceof Error?L.message:String(L);if(A){let F=i.get(I.name)??{count:0,lastError:""};F.count++,F.lastError=z,i.set(I.name,F)}let j={error:z,status:"failed"};P.push({...I,output:j,error:z}),y.push({id:I.id,name:I.name,input:I.args,output:j,error:z})}}c=r.buildToolResultMessages(c,k,P)}let b=r.mapFinishReason(f,x);return{text:p||(x?m:""),toolCalls:h,toolExecutions:y,usage:u,finishReason:b,rawStopReason:f,conversation:c}}catch(b){throw n.error(b),b}finally{n.close(),t.abortSignal?.removeEventListener("abort",s)}})();return{stream:n.iterable,resultPromise:l}}var Oq,WBe=E(()=>{"use strict";Kv();X();Qm();Oq=class extends Error{constructor(t){super(t instanceof Error?t.message:String(t));this.cause=t}cause}});function $wr(r){if(/^(us|ca)-/.test(r))return"us";if(/^(eu|il|me|af)-/.test(r))return"eu";if(/^ap-northeast-[13]$/.test(r))return"jp";if(/^ap-southeast-[246]$/.test(r))return"au";if(/^ap-/.test(r))return"apac"}function Bwr(r){return/^(us|eu|au|jp|apac|global)\./.test(r)}function JBe(r){if(typeof r!="object"||r===null)return!1;let e=r,t=typeof e.name=="string"?e.name:"",n=typeof e.message=="string"?e.message:"";return!/ValidationException/i.test(t)&&!/ValidationException/i.test(n)?!1:/inference profile/i.test(n)&&/on-demand throughput/i.test(n)}function zwr(r,e){if(r.startsWith("arn:")||Bwr(r))return[];let t=[],n=$wr(e);return n&&t.push(`${n}.${r}`),t.push(`${Fwr}.${r}`),t}function YBe(r,e){return`${r}::${e}`}function jwr(r,e){return XBe.get(YBe(e,r))}function Gwr(r,e,t){XBe.set(YBe(e,r),t),g.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:e})}async function Use(r,e,t){let n=jwr(r,e);if(n&&n!==r)return t(n);try{return await t(r)}catch(o){if(!JBe(o))throw o;let s=zwr(r,e);if(s.length===0)throw o;g.warn("[Bedrock] Model requires a cross-region inference profile in this region; retrying with a prefixed id",{region:e,candidates:s.length});for(let i of s)try{let a=await t(i);return Gwr(r,e,i),a}catch(a){if(!JBe(a))throw a}throw o}}var Fwr,XBe,ZBe=E(()=>{"use strict";X();Fwr="global";XBe=new Map});function Nq(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function eze(r,e){if(r){if(r.toolUse&&r._inputBuffer){try{r.toolUse.input=JSON.parse(r._inputBuffer)}catch{r.toolUse.input={}}delete r._inputBuffer}e&&!r.toolUse&&(r.text=e)}}function tze(r){return r.filter(e=>e.toolUse).map(e=>({id:e.toolUse?.toolUseId??Nq(),name:e.toolUse?.name??"",args:e.toolUse?.input??{}}))}async function qwr(r,e,t){let n=[],o=new Map,s=new Map,i=h=>{let y=o.get(h);return y||(y={},o.set(h,y),n.push(y)),y},a="",l,c=0,u=0,p=0,m=0;if(r.stream)for await(let h of r.stream){if(t.aborted)break;let y=h;if(y.contentBlockStart&&i(y.contentBlockStart.contentBlockIndex??0),y.contentBlockDelta?.delta?.text){let x=y.contentBlockDelta.contentBlockIndex??0,b=y.contentBlockDelta.delta.text;i(x),a+=b,s.set(x,(s.get(x)??"")+b),e.push({content:b})}if(y.contentBlockStart?.start?.toolUse){let x=i(y.contentBlockStart.contentBlockIndex??0);x.toolUse={name:y.contentBlockStart.start.toolUse.name??"",input:{},toolUseId:y.contentBlockStart.start.toolUse.toolUseId??Nq()}}if(y.contentBlockDelta?.delta?.toolUse){let x=i(y.contentBlockDelta.contentBlockIndex??0);x.toolUse??={name:"",input:{},toolUseId:Nq()};let b=y.contentBlockDelta.delta.toolUse.input;typeof b=="string"?x._inputBuffer=(x._inputBuffer??"")+b:typeof b=="object"&&b!==null&&!Array.isArray(b)&&(x.toolUse.input={...x.toolUse.input??{},...b})}if(y.contentBlockStop){let x=y.contentBlockStop.contentBlockIndex??0;eze(o.get(x),s.get(x)??"")}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,p+=y.metadata.usage.cacheReadInputTokens??0,m+=y.metadata.usage.cacheWriteInputTokens??0;break}}for(let[h,y]of o)eze(y,s.get(h)??"");let f=n.filter(h=>h.text||h.toolUse||h.image||h.document);return{text:a,toolCalls:tze(f),usage:{inputTokens:c,outputTokens:u,cacheReadTokens:p,cacheWriteTokens:m},rawStopReason:l,raw:f}}function Vwr(r){let e=[],t="";for(let n of r.output?.message?.content??[]){let o={};"text"in n&&n.text&&(o.text=n.text,t+=t?` ${n.text}`:n.text),"toolUse"in n&&n.toolUse&&(o.toolUse={toolUseId:n.toolUse.toolUseId??Nq(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),e.push(o)}return{text:t,toolCalls:tze(e),usage:{inputTokens:r.usage?.inputTokens??0,outputTokens:r.usage?.outputTokens??0,cacheReadTokens:r.usage?.cacheReadInputTokens??0,cacheWriteTokens:r.usage?.cacheWriteInputTokens??0},rawStopReason:r.stopReason,raw:e}}function Fse(r){return{providerLabel:"bedrock",maxSteps:r.maxSteps,buildStepRequest(e,t){return{raw:r.buildCommandInput(e,t)}},async executeStep(e,t,n){let o=e.raw;if(!r.streaming){let i=await Use(o.modelId??"",r.region,a=>je(r.client.send(new Nse({...o,modelId:a})),QBe,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return Vwr(i)}let s=await Use(o.modelId??"",r.region,i=>je(r.client.send(new Lse({...o,modelId:i})),QBe,new Error("Bedrock streaming API call timed out")));return qwr(s,t,n)},buildToolResultMessages(e,t,n){let o={role:"assistant",content:t.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[...e,o,s]},mapFinishReason(e,t){switch(e){case"end_turn":case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return t?"tool-calls":"stop"}}}}var QBe,rze=E(()=>{"use strict";Mq();Tt();ZBe();QBe=12e4});function $se(r,e,t){return{input:{text:r.input?.text||"",images:r.input?.images,content:r.input?.content,files:r.input?.files,csvFiles:r.input?.csvFiles,pdfFiles:r.input?.pdfFiles,audioFiles:r.input?.audioFiles,videoFiles:r.input?.videoFiles},csvOptions:r.csvOptions,pdfOptions:r.pdfOptions,systemPrompt:r.systemPrompt,conversationHistory:r.conversationMessages,provider:e,model:t,temperature:r.temperature,maxTokens:r.maxTokens,enableAnalytics:r.enableAnalytics,enableEvaluation:r.enableEvaluation,context:r.context,fileRegistry:r.fileRegistry}}var nze=E(()=>{"use strict"});var Lq,Bse=E(()=>{"use strict";ac();Lq=Oe.provider});var oze={};de(oze,{Agent:()=>O_r,BedrockClient:()=>Kwr,BedrockRuntimeClient:()=>Jwr,Blob:()=>M_r,Client:()=>L_r,ConverseCommand:()=>Xwr,ConverseStreamCommand:()=>Ywr,Cron:()=>g_r,Dispatcher:()=>D_r,File:()=>P_r,FlowProducer:()=>m_r,FormData:()=>I_r,GoogleAuth:()=>r_r,HTTPException:()=>T_r,Headers:()=>A_r,Hippocampus:()=>i_r,HippocampusConfig:()=>a_r,Hono:()=>v_r,ImageFormat:()=>Zwr,InvokeEndpointCommand:()=>e_r,InvokeEndpointWithResponseStreamCommand:()=>t_r,Job:()=>d_r,ListFoundationModelsCommand:()=>Wwr,MockAgent:()=>$_r,Pool:()=>N_r,Queue:()=>c_r,QueueScheduler:()=>p_r,Request:()=>R_r,Response:()=>k_r,SageMakerRuntimeClient:()=>Qwr,TextToSpeechClient:()=>o_r,VertexAI:()=>n_r,Webhook:()=>s_r,Worker:()=>u_r,convertToHtml:()=>x_r,cors:()=>b_r,createClient:()=>l_r,default:()=>Hwr,extractRawText:()=>y_r,fetch:()=>C_r,getGlobalDispatcher:()=>F_r,interceptors:()=>B_r,logger:()=>S_r,parseBuffer:()=>f_r,request:()=>z_r,secureHeaders:()=>w_r,selectCover:()=>h_r,setGlobalDispatcher:()=>U_r,streamSSE:()=>__r,timeout:()=>E_r});var UE,Oi,Hwr,Kwr,Wwr,Jwr,Xwr,Ywr,Zwr,Qwr,e_r,t_r,r_r,n_r,o_r,s_r,i_r,a_r,l_r,c_r,u_r,d_r,p_r,m_r,g_r,f_r,h_r,y_r,x_r,v_r,b_r,T_r,S_r,w_r,__r,E_r,C_r,R_r,k_r,A_r,I_r,P_r,M_r,O_r,N_r,L_r,D_r,U_r,F_r,$_r,B_r,z_r,sze=E(()=>{UE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:UE.get}):new Proxy(function(...t){return new Proxy({},{get:UE.get})},{get:UE.get,apply(t,n,o){return new Proxy({},{get:UE.get})},construct(t,n){return new Proxy({},{get:UE.get})}})}},Oi=new Proxy({},UE),Hwr=Oi,{BedrockClient:Kwr,ListFoundationModelsCommand:Wwr,BedrockRuntimeClient:Jwr,ConverseCommand:Xwr,ConverseStreamCommand:Ywr,ImageFormat:Zwr}=Oi,{SageMakerRuntimeClient:Qwr,InvokeEndpointCommand:e_r,InvokeEndpointWithResponseStreamCommand:t_r}=Oi,{GoogleAuth:r_r,VertexAI:n_r,TextToSpeechClient:o_r}=Oi,{Webhook:s_r}=Oi,{Hippocampus:i_r,HippocampusConfig:a_r}=Oi,{createClient:l_r}=Oi,{Queue:c_r,Worker:u_r,Job:d_r,QueueScheduler:p_r,FlowProducer:m_r}=Oi,{Cron:g_r}=Oi,{parseBuffer:f_r,selectCover:h_r}=Oi,{extractRawText:y_r,convertToHtml:x_r}=Oi,{Hono:v_r}=Oi,{cors:b_r,HTTPException:T_r,logger:S_r,secureHeaders:w_r,streamSSE:__r,timeout:E_r}=Oi,C_r=globalThis.fetch,R_r=globalThis.Request,k_r=globalThis.Response,A_r=globalThis.Headers,I_r=globalThis.FormData,P_r=globalThis.File,M_r=globalThis.Blob,O_r=Oi.Agent,N_r=Oi.Pool,L_r=Oi.Client,D_r=Oi.Dispatcher,U_r=()=>{},F_r=()=>Oi,$_r=Oi.MockAgent,B_r={redirect:()=>r=>r,retry:()=>r=>r},z_r=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});async function Dq(){return await Promise.resolve().then(()=>(sze(),oze))}var zse=E(()=>{"use strict"});var jse,ize=E(()=>{"use strict";Mq();Qr();qw();eu();cs();WBe();rze();Dt();ea();Tt();X();dg();qI();nze();Ea();gr();Bse();zse();jse=class r extends oo{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(e){return e?e.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(e,t,n,o){super(e,"bedrock",t);let s=e||process.env.BEDROCK_MODEL||this.modelName,i=r.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",g.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),g.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{g.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new Ose({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),g.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw g.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){let{BedrockClient:e,ListFoundationModelsCommand:t}=await Dq(),n=new e({region:this.region});try{g.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");let o=new t({}),s=Date.now();await n.send(o);let i=Date.now()-s;g.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){let s=o instanceof Error?o.message:String(o);g.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(e){g.debug("[AmazonBedrockProvider] generate() called with conversation management");let t=Date.now(),n=typeof e=="string"?{prompt:e}:e;this.conversationHistory=[];let o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){g.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});let m=$se(n,this.providerName,this.modelName),f=await T_(m,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(f)}else{g.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");let p={role:"user",content:[{text:n.prompt}]};this.conversationHistory.push(p)}g.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(p){let m=this.neurolink?.getEventEmitter();throw m&&m.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-t,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:p instanceof Error?p.message:String(p)}),p}let u=this.neurolink?.getEventEmitter();return u&&u.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-t,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(e){let t=e.maxSteps||Jo,n=await this.resolveTurnTools(e.tools,e.disableTools),o=this.formatToolsForBedrock(n),s=_a(this.providerName,this.modelName||this.getDefaultModel(),{temperature:e.temperature??.7},"bedrock.converse"),i=Fse({client:this.bedrockClient,streaming:!1,region:this.region,maxSteps:t,buildCommandInput:a=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(a),system:[{text:e.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:e.maxTokens,...s.temperature!==void 0&&{temperature:s.temperature}},...o?{toolConfig:o}:{}})});try{let{resultPromise:a}=Dse(i,this.conversationHistory,{tools:this.toEngineTools(n),abortSignal:e.abortSignal}),l=await a;this.conversationHistory=l.conversation;let c=l.usage.inputTokens,u=l.usage.outputTokens,p=l.usage.cacheReadTokens??0,m=l.usage.cacheWriteTokens??0;return{text:l.text||"",usage:{input:c,output:u,total:c+p+m+u,...p>0&&{cacheReadTokens:p},...m>0&&{cacheCreationTokens:m}},finishReason:l.finishReason,rawFinishReason:l.rawStopReason}}catch(a){throw g.error("[AmazonBedrockProvider] Error in conversation loop:",a),this.handleProviderError(a)}}convertToAWSMessages(e){return e.map(t=>({role:t.role,content:t.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(e,t,n,o){return Lq.startActiveSpan("bedrock.tool.execute",{kind:br.CLIENT,attributes:{"gen_ai.tool.name":t,"gen_ai.system":"aws.bedrock"}},async s=>{try{if(g.debug(`[AmazonBedrockProvider] Executing single tool: ${t}`,{args:n}),!e[t])throw new Error(`Tool not found: ${t}`);let i=e[t];if(!i||!i.execute)throw new Error(`Tool ${t} does not have execute method`);let a=n||{};t==="list_directory"&&!a.path&&(a.path=".",g.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),g.debug("[AmazonBedrockProvider] Tool input parameters:",a);let l={};for(let[p,m]of Object.entries(a))(m===null||typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="object"&&m!==null)&&(l[p]=m);let c=await i.execute(l);g.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:t,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){let p=typeof c.error=="string"?c.error:c.error.message||"Tool execution failed";throw new Error(p)}else u="";else typeof c=="string"?u=c:typeof c=="object"?u=JSON.stringify(c,null,2):u=String(c);return s.setStatus({code:ze.OK}),u}catch(i){throw g.error("[AmazonBedrockProvider] Tool execution error:",{toolName:t,error:i}),s.setStatus({code:ze.ERROR,message:i.message}),s.recordException(i),i}finally{s.end()}})}async resolveTurnTools(e,t){if(t)return{};let n=e??await this.getAllTools();return this.convertAISDKToolsToToolDefinitions(n)}toEngineTools(e){let t={};for(let n of Object.keys(e))t[n]={execute:o=>this.executeSingleTool(e,n,o)};return t}convertAISDKToolsToToolDefinitions(e){let t={};for(let[n,o]of Object.entries(e))if("description"in o&&o.description){let i=o.parameters??o.inputSchema;t[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 t}formatToolsForBedrock(e){if(!e||Object.keys(e).length===0)return null;let t=Object.entries(e).map(([n,o])=>{let s;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?s=xn(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 g.debug(`[AmazonBedrockProvider] Formatted ${t.length} tools for Bedrock`),{tools:t}}convertToBedrockMessages(e){return e.map(t=>{let n={role:t.role==="system"?"user":t.role,content:[]};return typeof t.content=="string"?n.content.push({text:t.content}):t.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){let s=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image,i=o.mimeType?.split("/")[1]||"png";i==="jpg"&&(i="jpeg"),n.content.push({image:{format:i==="jpeg"?DE.JPEG:i==="png"?DE.PNG:i==="gif"?DE.GIF:DE.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"){let 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?wd.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(e){return g.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),g.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),Lq.startActiveSpan("bedrock.stream",{kind:br.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async t=>{try{if(g.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(e.input?.images?.length||e.input?.content?.length||e.input?.files?.length||e.input?.csvFiles?.length||e.input?.pdfFiles?.length)){g.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!e.input?.images?.length,imageCount:e.input?.images?.length||0,hasContent:!!e.input?.content?.length,contentCount:e.input?.content?.length||0,hasFiles:!!e.input?.files?.length,fileCount:e.input?.files?.length||0,hasCSVFiles:!!e.input?.csvFiles?.length,csvFileCount:e.input?.csvFiles?.length||0,hasPDFFiles:!!e.input?.pdfFiles?.length,pdfFileCount:e.input?.pdfFiles?.length||0});let s=$se(e,this.providerName,this.modelName),i=await T_(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{g.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");let s={role:"user",content:[{text:e.input.text}]};this.conversationHistory.push(s)}g.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),g.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");let o=await this.streamingConversationLoop(e,t);return g.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),t.setStatus({code:ze.OK}),t.end(),o}catch(n){g.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");let o=n,s=o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream");if(g.debug("[TRACE] executeStream CATCH - checking if permission error"),g.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){g.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),g.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),t.addEvent("stream.fallback_to_generate",{reason:o.message});let i=await this.generate({prompt:e.input.text,input:e.input,maxTokens:e.maxTokens,temperature:e.temperature,systemPrompt:e.systemPrompt});if(!i)throw t.setStatus({code:ze.ERROR,message:"Generate method returned null result"}),t.end(),new Error("Generate method returned null result");t.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),t.setStatus({code:ze.OK}),t.end();let a=new ReadableStream({start(c){let p=(i.content||"").split(/(\s+)/),m="";for(let f=0;f<p.length;f++)m+=p[f],(f===p.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](){let c=a.getReader();try{for(;;){let{done:u,value:p}=await c.read();if(u)break;yield p}}finally{c.releaseLock()}}},usage:i.usage,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw t.setStatus({code:ze.ERROR,message:o instanceof Error?o.message:String(o)}),t.recordException(o instanceof Error?o:new Error(String(o))),t.end(),n}})}async streamingConversationLoop(e,t){let n=Date.now(),o=e.maxSteps||Jo,s=await this.resolveTurnTools(e.tools,e.disableTools),i=this.formatToolsForBedrock(s),a=_a(this.providerName,this.modelName||this.getDefaultModel(),{temperature:e.temperature??.7},"bedrock.converseStream"),l=Fse({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:P=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(P),system:[{text:e.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:e.maxTokens,...a.temperature!==void 0&&{temperature:a.temperature}},...i?{toolConfig:i}:{}})}),c=!1,u,p=new Promise(P=>{u=()=>{c=!0,P()}}),m={...l,executeStep:async(P,I,A)=>{let M=await l.executeStep(P,I,A);return u(),M}};t.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});let{stream:f,resultPromise:h}=Dse(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:e.abortSignal}),y=h.then(P=>({result:P,error:void 0}),P=>({result:void 0,error:P}));if(await Promise.race([p,y]),!c){let P=await y;if(P.error)throw P.error}let x=this.neurolink?.getEventEmitter(),b=this,T={startTime:n,streamId:`bedrock-${Date.now()}`},w,C=new Promise(P=>{w=P}),R=P=>{let I=P?.inputTokens??0,A=P?.outputTokens??0,M=P?.cacheReadTokens??0,U=P?.cacheWriteTokens??0;return{input:I,output:A,total:I+M+U+A,...M>0&&{cacheReadTokens:M},...U>0&&{cacheCreationTokens:U}}};return y.then(P=>{w(Hp(this.providerName,this.modelName||this.getDefaultModel(),{usage:R(P.result?.usage)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let P=!1;try{yield*f}catch(I){throw P=!0,I}finally{let I=await y;I.error&&(P=!0);let A=R(I.result?.usage);I.result&&(b.conversationHistory=I.result.conversation,T.finishReason=I.result.finishReason,T.rawFinishReason=I.result.rawStopReason,t.setAttribute("gen_ai.response.stop_reason",I.result.rawStopReason??"unknown")),x&&x.emit("generation:end",{provider:b.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:A,model:b.modelName||b.getDefaultModel(),provider:b.providerName,finishReason:P?"error":I.result?.rawStopReason},success:!P})}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:C,metadata:T}}async checkBedrockHealth(){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await Dq(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{g.debug("[AmazonBedrockProvider] Starting health check...");let i=new o({}),l=(await s.send(i,{abortSignal:e.signal})).modelSummaries||[],c=l.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(g.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(t);let a=i;if(wr(i))throw new Error("Bedrock health check timed out after 10 seconds",{cause:i});let 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}):(g.error("[AmazonBedrockProvider] Health check failed:",i),new Error(`Bedrock health check failed: ${l||"Unknown error"}`,{cause:i}))}finally{clearTimeout(t);try{s.destroy()}catch{}}}formatProviderError(e){return en(e,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:Mt,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:qr,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:mt,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:mt,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(e,t){let n=t||"amazon.titan-embed-text-v2:0";g.debug("Generating embedding",{provider:this.providerName,model:n,textLength:e.length});try{let{InvokeModelCommand:o}=await Promise.resolve().then(()=>(Mq(),KBe)),s=JSON.stringify({inputText:e}),i=new o({modelId:n,contentType:"application/json",accept:"application/json",body:s}),a=await je(this.bedrockClient.send(i),6e4,new Error("Bedrock embedding API call timed out")),l=JSON.parse(new TextDecoder().decode(a.body));if(!l.embedding||!Array.isArray(l.embedding))throw new Error("Invalid embedding response from Bedrock");return g.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:l.embedding.length}),l.embedding}catch(o){throw g.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:e.length}),this.handleProviderError(o)}}async embedMany(e,t){let n=t||"amazon.titan-embed-text-v2:0";g.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:e.length});try{let o=await Promise.all(e.map(s=>this.embed(s,n)));return g.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw g.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:e.length}),this.handleProviderError(o)}}}});var aze={};de(aze,{AmazonBedrockProvider:()=>jse,bedrockTracer:()=>Lq,loadBedrockControl:()=>Dq});var lze=E(()=>{"use strict";ize();Bse();zse()});var cze={};de(cze,{AzureOpenAIProvider:()=>Gse});var Gse,uze=E(()=>{"use strict";Dt();X();ea();Ko();Kp();hc();Ag();Gse=class extends $n{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,n,o){let s=o?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",i=process.env.AZURE_OPENAI_ENDPOINT||"",a;if(i)try{a=new URL(i.includes("://")?i:`https://${i}`)}catch{a=void 0}let l=a?.hostname??"",c=a?.pathname&&a.pathname!=="/"?a.pathname.replace(/\/+$/,""):"",u=/\.(openai|cognitiveservices)\.azure\.com$/.test(l),p;u?p="/openai":p=/\/openai(?:\/v\d+)?$/.test(c)?c:`${c}/openai`;let m=a?.origin??"",f=o?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",h=o?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",y=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,x=o?.useMaxCompletionTokens??(y===void 0?void 0:/^(1|true|yes)$/i.test(y));s||an(uye()),m||an(dye()),super("azure",e,t,{baseURL:m,apiKey:s}),this.azureDeployment=f,this.azureApiVersion=h,this.azureResourceOrigin=m,this.azureDeploymentPathPrefix=p,this.useMaxCompletionTokensOverride=x,g.shouldLog("debug")&&g.debug("Azure OpenAI Provider initialized",jB({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){let t=[{match:n=>/401/.test(n.message),errorClass:Mt,message:"Invalid Azure OpenAI API key or endpoint."},...tn];return en(e,t,"azure",this.modelName)}getChatCompletionsURL(e){let t=e||this.azureDeployment,n=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${n}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){let n=this.useMaxCompletionTokensOverride??E1e(t);return e.max_tokens!==void 0&&n?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}});function dze(r){return r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71?"image/png":r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255?"image/jpeg":r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===69&&r[10]===66&&r[11]===80?"image/webp":r.length>=6&&r[0]===71&&r[1]===73&&r[2]===70?"image/gif":"image/png"}var pze=E(()=>{"use strict"});function qse(r){return r.map(e=>typeof e.content=="string"?{role:e.role,content:e.content}:{role:e.role,content:e.content.map(t=>t.type==="image"||t.type==="document"?{type:t.type,media_type:t.source.media_type,base64_chars:t.source.data.length}:t)})}var mze=E(()=>{"use strict"});var Uq,gze=E(()=>{Uq=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0}});var fze=E(()=>{fo()});function Fq(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var Vse,Hse,Kse=E(()=>{fze();Vse=r=>(Vse=Array.isArray,Vse(r)),Hse=Vse});function*j_r(r){if(!r)return;if(hze in r){let{values:n,nulls:o}=r;yield*n.entries();for(let s of o)yield[s,null];return}let e=!1,t;r instanceof Headers?t=r.entries():Hse(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=Hse(n[1])?n[1]:[n[1]],i=!1;for(let a of s)a!==void 0&&(e&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var hze,yze,xze=E(()=>{Kse();hze=Symbol.for("brand.privateNullableHeaders");yze=r=>{let e=new Headers,t=new Set;for(let n of r){let o=new Set;for(let[s,i]of j_r(n)){let a=s.toLowerCase();o.has(a)||(e.delete(s),o.add(a)),i===null?(e.delete(s),t.add(a)):(e.append(s,i),t.delete(a))}}return{[hze]:!0,values:e,nulls:t}}});function V_r(r){let e=new dm(r);return delete e.batches,e}function H_r(r){let e=new ti(r);return delete e.messages.batches,e}var G_r,q_r,$q,Wse=E(()=>{aM();use();P_();gze();Kse();xze();aM();G_r="vertex-2023-10-16",q_r=new Set(["/v1/messages","/v1/messages?beta=true"]),$q=class extends Jn{constructor({baseURL:e=Uq("ANTHROPIC_VERTEX_BASE_URL"),region:t=Uq("CLOUD_ML_REGION")??null,projectId:n=Uq("ANTHROPIC_VERTEX_PROJECT_ID")??null,...o}={}){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,...o}),this.messages=V_r(this),this.beta=H_r(this),this.region=t,this.projectId=n,this.accessToken=o.accessToken??null,o.authClient&&o.googleAuth)throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");o.authClient?this._authClientPromise=Promise.resolve(o.authClient):(this._auth=o.googleAuth??new iP({scopes:"https://www.googleapis.com/auth/cloud-platform"}),this._authClientPromise=this._auth.getClient())}validateHeaders(){}async prepareOptions(e){let t=await this._authClientPromise,n=await t.getRequestHeaders(),o=t.projectId??n["x-goog-user-project"];!this.projectId&&o&&(this.projectId=o),e.headers=yze([n,e.headers])}async buildRequest(e){if(Fq(e.body)&&(e.body={...e.body}),Fq(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=G_r)),q_r.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(!Fq(e.body))throw new Error("Expected request body to be an object for post /v1/messages");let t=e.body.model;e.body.model=void 0;let o=e.body.stream??!1?"streamRawPredict":"rawPredict";e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${t}:${o}`}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)}}});var Jse={};de(Jse,{AnthropicVertex:()=>$q,BaseAnthropic:()=>Jn,default:()=>$q});var Xse=E(()=>{Wse();Wse()});async function K_r(){return Yse||(Yse=await Promise.resolve().then(()=>(Xse(),Jse))),Yse}function J_r(r){let e=[],t=new Map,n=0,o=s=>{let i=`${n}:${s??"x"}`,a=t.get(i);return a||(a={type:"tool_step",callParts:[],resultParts:[]},t.set(i,a),e.push(a)),a};for(let s of r){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}let i=s.role==="assistant"?"assistant":s.role==="user"?"user":null;!i||!s.content||s.content.trim().length===0||(n++,e.push({type:"regular",role:i,parts:[s.content]}))}return e}function Zse(r,e,t){let n=r[r.length-1];n&&n.role===e&&Array.isArray(n.content)?n.content.push(...t):r.push({role:e,content:[...t]})}function X_r(r,e){let t=r.callParts,n=r.resultParts,o=Math.min(t.length,n.length);(o!==t.length||o!==n.length)&&g.debug("[GoogleVertex] Unbalanced tool step in Claude history replay",{calls:t.length,results:n.length,paired:o});let s=[],i=[];for(let a=0;a<o;a++){let l=`hist_${e}_${a}`;s.push({type:"tool_use",id:l,name:t[a].name,input:t[a].input}),i.push({type:"tool_result",tool_use_id:l,content:n[a]})}return{uses:s,results:i}}function Y_r(r){let e=t=>Array.isArray(t.content)&&t.content.length>0&&t.content.every(n=>n.type==="tool_result");for(;r.length>0&&(r[0].role!=="user"||e(r[0]));)r.shift()}function eie(r){let e=[],t=0;for(let n of J_r(r)){if(n.type==="regular"){Zse(e,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}let{uses:o,results:s}=X_r(n,t);o.length!==0&&(t++,Zse(e,"assistant",o),Zse(e,"user",s))}if(Y_r(e),g.shouldLog("debug")){let n=e.flatMap(o=>Array.isArray(o.content)?o.content:[]);g.debug("[GoogleVertex] Replayed Claude history with tool turns",{historyMessages:e.length,toolUseBlocks:n.filter(o=>o.type==="tool_use").length,toolResultBlocks:n.filter(o=>o.type==="tool_result").length})}return e}function tie(r,e){let t=r[r.length-1];if(t&&t.role==="user"){let n=Array.isArray(t.content)?t.content:[{type:"text",text:t.content}],o=Array.isArray(e)?e:[{type:"text",text:e}];t.content=[...n,...o];return}r.push({role:"user",content:e})}function py(r){if(!r||typeof r!="object")return;let e=["additionalProperties","default","$schema","$id","$ref","definitions","$defs","examples","errorMessage"];for(let n of e)n in r&&delete r[n];typeof r.exclusiveMinimum=="boolean"&&(r.exclusiveMinimum===!0&&typeof r.minimum=="number"?(r.exclusiveMinimum=r.minimum,delete r.minimum):delete r.exclusiveMinimum),typeof r.exclusiveMaximum=="boolean"&&(r.exclusiveMaximum===!0&&typeof r.maximum=="number"?(r.exclusiveMaximum=r.maximum,delete r.maximum):delete r.exclusiveMaximum);let t=2147483647;if(typeof r.maximum=="number"&&r.maximum>t&&delete r.maximum,typeof r.minimum=="number"&&r.minimum<-t&&delete r.minimum,r.properties&&typeof r.properties=="object")for(let n of Object.values(r.properties))n&&typeof n=="object"&&py(n);if(r.items&&typeof r.items=="object")if(Array.isArray(r.items))for(let n of r.items)n&&typeof n=="object"&&py(n);else py(r.items);for(let n of["allOf","anyOf","oneOf"])if(Array.isArray(r[n]))for(let o of r[n])o&&typeof o=="object"&&py(o)}function vze(r,e,t){let n=Zj({contents:r,availableInputTokens:mi("vertex",e),provider:"vertex",observedPromptTokens:t});if(!n)return!1;let o=new Set(n.drop),s=new Set(n.truncate),i=[];for(let a=0;a<r.length;a++){if(o.has(a))continue;let l=r[a];if(s.has(a)&&Array.isArray(l.parts)){i.push({...l,parts:l.parts.map(c=>{if(!("functionResponse"in c))return c;let u=c.functionResponse,p=JSON.stringify(u.response)??"";return p.length<=eEr?c:{functionResponse:{name:u.name,response:{result:cP(p)}}}})});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:Yj}]})}return r.length=0,r.push(...i),!0}function bze(r,e,t){let n=Rq({conversation:r,availableInputTokens:mi("vertex",e),fixedOverheadTokens:0,provider:"vertex",observedPromptTokens:t,observedDescribesCurrentPayload:!0});if(!n)return!1;let o=new Set(n.drop),s=new Set(n.truncate),i=[];for(let a=0;a<r.length;a++){if(o.has(a))continue;let l=r[a];if(s.has(a)&&Array.isArray(l.content)){i.push({...l,content:l.content.map(c=>{if(c.type!=="tool_result")return c;let u=typeof c.content=="string"?c.content:JSON.stringify(c.content)??"";return{...c,content:Cq(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:Eq}]})}return r.length=0,r.push(...i),!0}var Yse,W_r,rie,Bq,zq,gM,FE,Z_r,Q_r,Qse,eEr,nie,oie=E(()=>{"use strict";ro();Qr();eu();Pz();tG();tte();cs();Ph();nz();Hr();so();Dt();ea();Tt();_se();qte();qI();X();Ere();bse();zj();pze();jj();Ko();Ea();Cre();O_();_l();$re();Kv();rG();$d();Xw();ac();gr();Dd();Kp();cI();dg();mze();YI();Yse=null;W_r=()=>!0;rie=()=>an(zL()),Bq=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",zq=(r,e)=>{let t=e||Bq();if(!r)return t;let n=r.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||S2.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":t},gM=zq,FE=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",Z_r=()=>!!(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),Q_r=async(r,e)=>{let t=r||Bq();return{projectId:rie(),region:t,...e!==void 0&&{timeout:e},maxRetries:0}},Qse=r=>r.toLowerCase().includes("claude"),eEr=2048;nie=class r extends oo{projectId;location;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(e,t,n,o,s){super(e,"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))),Z_r()||an(Cye()),this.projectId=s?.projectId||rie(),this.location=o||s?.location||Bq(),g.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),g.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return FE()}async getAISDKModel(){throw new Le({code:tt.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(e){this.validateStreamOptions(e)}async preprocessNativeFileInput(e){if(e.input&&jI(e.input),e.input?.files?.length)try{await GI(e,100*1024*1024,this.providerName)}catch(t){g.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await Uv(e.input)}async executeStream(e,t){let n=e.model||this.modelName||FE();return KA({name:"neurolink.provider.stream",tracer:Oe.provider,attributes:{[Pe.GEN_AI_SYSTEM]:this.providerName,[Pe.GEN_AI_MODEL]:n,[Pe.GEN_AI_OPERATION]:"stream",[Pe.NL_PROVIDER]:this.providerName}},async o=>{let s=Date.now(),i=e.tools||{};await this.preprocessNativeFileInput(e);let l={...await Je({name:"neurolink.message.build",tracer:Oe.provider,attributes:{[Pe.NL_PROVIDER]:this.providerName,"message.count":1,"message.build.count":1,"message.build.path":"vertex.native.stream"}},async()=>this.processCSVFilesForNativeSDK(e)),tools:i};try{let c;Qse(n)?(g.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(i).length}),c=await this.executeNativeAnthropicStream(l)):(g.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);let u=this.wrapStreamResultWithLifecycle(e,c,s);return this.emitStreamEnd(n,s,!0,void 0,c.finishReason),u}catch(c){throw this.fireGenerateOnError(e,c,s),this.emitStreamEnd(n,s,!1,c),c}},o=>o.stream,(o,s)=>this.preserveStreamResultAccessors(o,{...o,stream:s}))}emitStreamEnd(e,t,n,o,s){let i=this.neurolink?.getEventEmitter();i&&i.emit("stream:end",{provider:this.providerName,responseTime:Date.now()-t,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:e,provider:this.providerName,finishReason:n?s??"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async createVertexGenAIClient(e){let t=rie(),n=e||this.location||Bq(),s=(await Promise.resolve().then(()=>(ww(),Sw))).GoogleGenAI;if(!s)throw new Le({code:tt.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});let i=s;return new i({vertexai:!0,project:t,location:n,httpOptions:{fetch:yt()}})}buildGeminiFunctionDeclaration(e,t){let n={name:e,description:t.description||`Tool: ${e}`},s=t.parameters||t.inputSchema;if(s){let i=xn(s,"openApi3"),a=pn(i);a.$schema&&delete a.$schema;let l=pi(a);py(l),n.parametersJsonSchema=l}return n}refreshGeminiToolDeclarations(e,t,n,o){if(!e||!t)return;let s=new Set(t.map(i=>i.name));for(let[i,a]of Object.entries(e))s.has(i)||(t.push(this.buildGeminiFunctionDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),g.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Gemini declarations.`))}resolveGeminiToolOnMiss(e,t,n,o,s){if(!n)return;let i=mI(t,e);if(i?.execute)return n.some(a=>a.name===e)||n.push(this.buildGeminiFunctionDeclaration(e,i)),o.set(e,i.execute),s.delete(e),g.info(`[GoogleVertex] Tool "${e}" resolved mid-turn via discovery \u2014 executing.`),o.get(e)}buildAnthropicToolDeclaration(e,t){let n={name:e,description:t.description||`Tool: ${e}`,input_schema:{type:"object"}},s=t.parameters||t.inputSchema;if(s){let i=xn(s),a=pn(i);n.input_schema={type:"object",properties:a.properties||{},required:a.required||[]}}return n}refreshAnthropicToolDeclarations(e,t,n,o){if(!e||!t)return;let s=new Set(t.map(i=>i.name));for(let[i,a]of Object.entries(e))s.has(i)||(t.push(this.buildAnthropicToolDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),g.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Anthropic declarations.`))}resolveAnthropicToolOnMiss(e,t,n,o,s){if(!n)return;let i=mI(t,e);if(i?.execute)return n.some(a=>a.name===e)||n.push(this.buildAnthropicToolDeclaration(e,i)),o.set(e,i.execute),s.delete(e),g.info(`[GoogleVertex] Tool "${e}" resolved mid-turn via discovery \u2014 executing.`),o.get(e)}async executeNativeGemini3Stream(e){let t=e.model||this.modelName||FE(),n=gM(t,e.region),o=await this.createVertexGenAIClient(n);g.debug("[GoogleVertex] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0,project:this.projectId,location:n});let s=[],i=[{text:e.input.text??""}],a=e.input;if(a?.pdfFiles&&a.pdfFiles.length>0){g.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(let ye of a.pdfFiles){let Fe;typeof ye=="string"?wn.existsSync(ye)?Fe=wn.readFileSync(ye):Fe=Buffer.from(ye,"base64"):Fe=ye;let Ee=Fe.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:Ee}})}}if(await eG(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){g.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(let ye of a.images){let Fe=i_(ye),Ee,Rt="image/jpeg";if(typeof Fe=="string")if(wn.existsSync(Fe)){Ee=wn.readFileSync(Fe);let ue=Ov(Fe);Rt=ue.startsWith("image/")?ue:this.detectImageType(Ee)}else if(Fe.startsWith("data:")){let ue=Fe.match(/^data:([^;]+);base64,(.+)$/);if(ue)Rt=ue[1],Ee=Buffer.from(ue[2],"base64");else continue}else if(Fe.startsWith("http://")||Fe.startsWith("https://"))try{let ue=await fetch(Fe);if(!ue.ok){g.warn(`[GoogleVertex] Image fetch failed: ${ue.status} ${ue.statusText}, skipping`,{url:Wr(Fe)});continue}let qe=await ue.arrayBuffer();Ee=Buffer.from(qe);let Be=ue.headers.get("content-type");Be&&Be.startsWith("image/")&&(Rt=Be.split(";")[0])}catch(ue){g.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${ue instanceof Error?ue.message:String(ue)}`,{url:Wr(Fe)});continue}else Ee=Buffer.from(Fe,"base64"),Rt=this.detectImageType(Ee);else Ee=Fe,Rt=this.detectImageType(Ee);let Xe=Ee.toString("base64");i.push({inlineData:{mimeType:Rt,data:Xe}})}}L_(s,e.conversationMessages),s.push({role:"user",parts:i});let l,c=new Hd;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){let ye=Rg(e.tools,"functionDeclarations");l=ye.toolsConfig;for(let[Fe,Ee]of ye.executeMap)c.set(Fe,Ee);g.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ye.toolsConfig[0].functionDeclarations.length,toolNames:ye.toolsConfig[0].functionDeclarations.map(Fe=>Fe.name)})}let u=e,p=!1;if(u.schema&&l){p=!0;let ye=xn(u.schema,"openApi3"),Fe=pn(ye);Fe.$schema&&delete Fe.$schema;let Ee=pi(Fe),Rt=l[0]?.functionDeclarations||[];Rt.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:Ee}),l=[{functionDeclarations:Rt}],g.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(Ee),totalTools:Rt.length})}let m=_a(this.providerName,t,{temperature:e.temperature??1,...e.topP!==void 0&&{topP:e.topP}},"vertex.gemini"),f={...m.temperature!==void 0&&{temperature:m.temperature},maxOutputTokens:e.maxTokens};nP(t)&&(f.maxOutputTokens&&f.maxOutputTokens>Nl&&(g.warn(`[GoogleVertex] Capping maxOutputTokens from ${f.maxOutputTokens} to ${Nl} for ${t}`),f.maxOutputTokens=Nl),f.maxOutputTokens||(f.maxOutputTokens=Nl)),m.topP!==void 0&&(f.topP=m.topP),e.topK!==void 0&&(f.topK=e.topK),e.stopSequences&&e.stopSequences.length>0&&(f.stopSequences=e.stopSequences),l&&(f.tools=l);let h=e.systemPrompt||"";p&&(h=h+`
|
|
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.`),h&&(f.systemInstruction=h);let y=uP(e.thinkingConfig);if(y&&(f.thinkingConfig=y),(u.output?.format==="json"||u.schema)&&!p&&!l&&(f.responseMimeType="application/json",u.schema)){let ye=xn(u.schema,"openApi3"),Fe=pn(ye);Fe.$schema&&delete Fe.$schema;let Ee=pi(Fe);py(Ee),f.responseSchema=Ee,g.debug("[GoogleVertex] Added responseSchema for JSON output (stream)",{schemaKeys:Object.keys(Ee)})}let x=Date.now(),b=e.maxSteps||Jo,T=Number.isFinite(b)&&b>0?Math.min(Math.floor(b),100):Math.min(Jo,100),w=[...s],C="",R,k=[],P=[],I=0,A,M=new Map,U=ey(Fd("vertex",t)),$=!1,L=0,z=0,j=0,F=0,B=[],O=sl(e.timeout)??_w,W=e.toolTimeoutMs??Ew,re=e.turnTimeoutMs??O,te=new AbortController,pe=()=>te.abort();e.abortSignal?.addEventListener("abort",pe);let Ae=mP({turnTimeoutMs:e.turnTimeoutMs,defaultTurnTimeoutMs:O,stallTimeoutMs:e.stallTimeoutMs,wrapupTimeLeadMs:e.wrapupTimeLeadMs,onDeadline:ye=>{g.warn(ye==="timeout"?`[GoogleVertex] Native Gemini turn exceeded its ${re}ms time budget \u2014 aborting`:`[GoogleVertex] Native Gemini turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),te.abort()}}),J=te.signal;e.abortSignal?.aborted&&te.abort();let oe=!1,Z=0,we=!1,ve=!1;try{for(;I<T;){if(J.aborted){oe=!0;break}if(U.shouldStop())if(vze(w,t,U.projectedNextPromptTokens))U.resetAfterReclaim();else{$=!0,g.warn(`[GoogleVertex] Gemini turn stopped by the context guard: projected prompt ~${U.projectedNextPromptTokens} tokens >= threshold ${U.thresholdTokens} (step ${I}) \u2014 synthesizing a final answer.`);break}I++,Ae.noteProgress(),this.refreshGeminiToolDeclarations(e.tools,l?.[0]?.functionDeclarations,c,M),g.debug(`[GoogleVertex] Native SDK step ${I}/${T}`);try{let ye=await o.models.generateContentStream({model:t,contents:w,config:{...f,abortSignal:J}}),Fe=[],Ee=[],Rt,Xe=0,ue=0,qe=0,Be=0;for await(let Q of ye){Ae.noteProgress();let q=Q,Ce=q.candidates?.[0],D=Ce?.finishReason;typeof D=="string"&&D&&(R=D,Rt=D);let ge=Ce?.content;if(ge&&Array.isArray(ge.parts))for(let se of ge.parts)Ee.push(se),typeof se.text=="string"&&se.text.length>0&&B.push(se.text);Q.functionCalls&&Fe.push(...Q.functionCalls);let Se=q.usageMetadata;if(Se){if(Se.promptTokenCount!==void 0&&Se.promptTokenCount>0){L+=Se.promptTokenCount-Xe,Xe=Se.promptTokenCount,U.noteUsage(Se.promptTokenCount,Se.candidatesTokenCount??0);let se=Math.min(Se.cachedContentTokenCount??0,Se.promptTokenCount);j+=se-qe,qe=se}Se.candidatesTokenCount!==void 0&&Se.candidatesTokenCount>0&&(z+=Se.candidatesTokenCount-ue,ue=Se.candidatesTokenCount),Se.thoughtsTokenCount!==void 0&&Se.thoughtsTokenCount>0&&(F+=Se.thoughtsTokenCount-Be,Be=Se.thoughtsTokenCount)}}let ce=Ee.filter(Q=>typeof Q.text=="string").map(Q=>Q.text).join("");if(Fe.length===0&&!ce&&Rt==="MALFORMED_FUNCTION_CALL"&&Z<1&&!J.aborted){Z++,g.warn(`[GoogleVertex] Model returned MALFORMED_FUNCTION_CALL at step ${I}/${T}; retrying once with a corrective note.`),this.emitTurnEvent({phase:"malformed-retry",step:I,maxSteps:T}),Ee.length>0&&w.push({role:"model",parts:Ee}),w.push({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."}]});continue}if(Fe.length===0){C=ce;break}if(p){let Q=Fe.find(q=>q.name==="final_result");if(Q){A=Q.args,g.debug("[GoogleVertex] Received final_result tool call with structured output (stream)",{outputKeys:Object.keys(A)}),C=JSON.stringify(A);break}}g.debug(`[GoogleVertex] Executing ${Fe.length} function calls`),w.push({role:"model",parts:Ee.length>0?Ee:Fe.map(Q=>({functionCall:Q}))});let Ne=[],_=[],G=[];for(let Q of Fe){if(J.aborted){oe=!0;break}k.push({toolName:Q.name,args:Q.args}),_.push({toolName:Q.name,args:Q.args});let q=M.get(Q.name);if(q&&q.count>=Kn){g.warn(`[GoogleVertex] Tool "${Q.name}" has exceeded retry limit (${Kn}), skipping execution`);let Ce={error:`TOOL_PERMANENTLY_FAILED: The tool "${Q.name}" has failed ${q.count} times and will not be retried. Last error: ${q.lastError}. Please proceed without using this tool or inform the user that this functionality is unavailable.`,status:"permanently_failed",do_not_retry:!0};Ne.push({functionResponse:{name:Q.name,response:Ce}}),P.push({name:Q.name,input:Q.args,output:Ce}),G.push({toolName:Q.name,output:Ce});continue}let he=c.get(Q.name);if(he||(he=this.resolveGeminiToolOnMiss(Q.name,e.tools,l?.[0]?.functionDeclarations,c,M)),he)try{let Ce={toolCallId:`${Q.name}-${Date.now()}`,messages:[],abortSignal:J};Ae.noteProgress();let D=await ht(Sh(Promise.resolve(he(Q.args,Ce)),J),W,`Tool "${Q.name}" execution timed out after ${W}ms`);Ae.noteProgress();let ge=XI(D);if(ge){let Se=M.get(Q.name)||{count:0,lastError:""};Se.count++,Se.lastError=ge,M.set(Q.name,Se)}else M.delete(Q.name);P.push({name:Q.name,input:Q.args,output:D}),Ne.push({functionResponse:{name:Q.name,response:{result:D}}}),G.push({toolName:Q.name,output:D})}catch(Ce){if(J.aborted||tu(Ce)){oe=!0;break}Ae.noteProgress(),Ce instanceof na&&this.emitTurnEvent({phase:"tool-timeout",step:I,maxSteps:T,toolName:Q.name});let D=Ce instanceof Error?Ce.message:"Unknown error",ge=M.get(Q.name)||{count:0,lastError:""};ge.count++,ge.lastError=D,M.set(Q.name,ge),g.warn(`[GoogleVertex] Tool "${Q.name}" failed (attempt ${ge.count}/${Kn}): ${D}`);let Se=ge.count>=Kn,se={error:Se?`TOOL_PERMANENTLY_FAILED: The tool "${Q.name}" has failed ${ge.count} times with error: ${D}. This tool will not be retried. Please proceed without using this tool or inform the user that this functionality is unavailable.`:`TOOL_EXECUTION_ERROR: ${D}. Retry attempt ${ge.count}/${Kn}.`,status:Se?"permanently_failed":"failed",do_not_retry:Se,retry_count:ge.count,max_retries:Kn};Ne.push({functionResponse:{name:Q.name,response:se}}),P.push({name:Q.name,input:Q.args,output:se}),G.push({toolName:Q.name,output:se})}else{let Ce={error:`TOOL_NOT_FOUND: The tool "${Q.name}" does not exist. Do not attempt to call this tool again.`,status:"permanently_failed",do_not_retry:!0},D=M.get(Q.name)||{count:0,lastError:""};D.count++,D.lastError=Ce.error,M.set(Q.name,D),Ne.push({functionResponse:{name:Q.name,response:Ce}}),P.push({name:Q.name,input:Q.args,output:Ce}),G.push({toolName:Q.name,output:Ce})}}if(oe)break;if(_.length>0||G.length>0){let Q=N_(Ee);ht(this.handleToolExecutionStorage(_.map((q,he)=>({...q,...he===0&&Q?{thoughtSignature:Q}:{},stepIndex:I})),G.map(q=>({...q,stepIndex:I})),e,new Date),sg,"tool storage write timed out").catch(q=>{g.warn("[GoogleVertex] Failed to store native Gemini stream tool executions",{error:q instanceof Error?q.message:String(q)})})}Ae.shouldNudgeWrapup()&&Ne.push({text:dP(p)}),w.push({role:"user",parts:Ne});try{U.noteAppendedChars(JSON.stringify(Ne).length)}catch{}}catch(ye){if(J.aborted||tu(ye)){oe=!0;break}throw g.error("[GoogleVertex] Native SDK error",ye),this.handleProviderError(ye)}}if(!C&&(I>=T||oe||$)){we=I>=T&&!oe;let ye=k.filter(Fe=>Fe.toolName!=="final_result").length;if(B.length>0)g.warn($?"[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(oe)g.warn(`[GoogleVertex] Tool call loop ended mid-turn (${Ae.timedOut?"turn time limit":Ae.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),C=this.buildLoopExitMessage({turnClock:Ae,wasAborted:oe,stallTimeoutMs:e.stallTimeoutMs,maxSteps:T,toolCallCount:ye});else{g.warn($?"[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.`);let Fe=await this.synthesizeFinalAnswerWithoutTools(o,t,f,w,p,sl(e.timeout)??_w,J);Fe.text?(ve=!0,C=Fe.text,B.push(Fe.text),L+=Fe.inputTokens,z+=Fe.outputTokens,F+=Fe.reasoningTokens??0,Fe.finishReason&&(R=Fe.finishReason)):C=$?ru(ye):Cg(T,ye)}}}finally{Ae.dispose(),e.abortSignal?.removeEventListener("abort",pe)}let ae=we&&!ve?"tool-calls":Pre(R),H=pP({timedOut:Ae.timedOut,stalled:Ae.stalled,wasAborted:oe,cappedWithoutAnswer:we&&!ve,contextCappedWithoutAnswer:$&&!ve,finishReason:ae});H!=="completed"&&this.emitTurnEvent({phase:H,step:I,maxSteps:T,toolCallCount:k.filter(ye=>ye.toolName!=="final_result").length,elapsedMs:Ae.elapsedMs()});let V=Date.now()-x,ne=A?[C]:B.length>0?B:[C];async function*N(){for(let ye of ne)ye.length>0&&(yield{content:ye})}let Y=k.filter(ye=>ye.toolName!=="final_result"),ee=P.filter(ye=>ye.name!=="final_result"),ie=Math.max(0,L-j),le={stream:N(),provider:this.providerName,model:t,finishReason:ae,stopReason:H,rawFinishReason:R,usage:{input:ie,output:z+F,total:ie+j+z+F,...j>0&&{cacheReadTokens:j},...F>0&&{reasoning:F}},toolCalls:Y.map(ye=>({toolName:ye.toolName,args:ye.args})),toolsUsed:Y.map(ye=>ye.toolName),toolExecutions:Tv(ee),metadata:{streamId:`native-vertex-${Date.now()}`,startTime:x,responseTime:V,totalToolExecutions:Y.length,stopReason:H,rawFinishReason:R,stepsUsed:I}};return A&&(le.structuredOutput=A),le}async executeNativeGemini3Generate(e){let t=e.model||this.modelName||FE(),n=gM(t,e.region),o=await this.createVertexGenAIClient(n);g.debug("[GoogleVertex] Using native @google/genai for Gemini 3 generate",{model:t,project:this.projectId,location:n});let s=e.input?.text||e.prompt||"Please respond.",i=[],a=[{text:s}],l=e.input;if(l?.pdfFiles&&l.pdfFiles.length>0){g.debug(`[GoogleVertex] Processing ${l.pdfFiles.length} PDF file(s) for native generate`);for(let le of l.pdfFiles){let ye;typeof le=="string"?wn.existsSync(le)?ye=wn.readFileSync(le):ye=Buffer.from(le,"base64"):ye=le;let Fe=ye.toString("base64");a.push({inlineData:{mimeType:"application/pdf",data:Fe}})}}if(await eG(a,l?.nativeAudioFiles,"[GoogleVertex]"),l?.images&&l.images.length>0){g.debug(`[GoogleVertex] Processing ${l.images.length} image(s) for native generate`);for(let le of l.images){let ye=i_(le),Fe,Ee="image/jpeg";if(typeof ye=="string")if(wn.existsSync(ye)){Fe=wn.readFileSync(ye);let Xe=Ov(ye);Ee=Xe.startsWith("image/")?Xe:this.detectImageType(Fe)}else if(ye.startsWith("data:")){let Xe=ye.match(/^data:([^;]+);base64,(.+)$/);if(Xe)Ee=Xe[1],Fe=Buffer.from(Xe[2],"base64");else continue}else if(ye.startsWith("http://")||ye.startsWith("https://"))try{let Xe=await fetch(ye);if(!Xe.ok){g.warn(`[GoogleVertex] Image fetch failed: ${Xe.status} ${Xe.statusText}, skipping`,{url:Wr(ye)});continue}let ue=await Xe.arrayBuffer();Fe=Buffer.from(ue);let qe=Xe.headers.get("content-type");qe&&qe.startsWith("image/")&&(Ee=qe.split(";")[0])}catch(Xe){g.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${Xe instanceof Error?Xe.message:String(Xe)}`,{url:Wr(ye)});continue}else Fe=Buffer.from(ye,"base64"),Ee=this.detectImageType(Fe);else Fe=ye,Ee=this.detectImageType(Fe);let Rt=Fe.toString("base64");a.push({inlineData:{mimeType:Ee,data:Rt}})}}L_(i,e.conversationMessages),i.push({role:"user",parts:a});let c=e.disableTools?{}:e.tools||{},u,p=new Hd;if(Object.keys(c).length>0){let le=Rg(c,"functionDeclarations");u=le.toolsConfig;for(let[ye,Fe]of le.executeMap)p.set(ye,Fe);g.debug("[GoogleVertex] Converted tools for native SDK generate",{toolCount:le.toolsConfig[0].functionDeclarations.length,toolNames:le.toolsConfig[0].functionDeclarations.map(ye=>ye.name)})}let m=!1;if(e.schema&&u){m=!0;let le=xn(e.schema,"openApi3"),ye=pn(le);ye.$schema&&delete ye.$schema;let Fe=pi(ye),Ee=u[0]?.functionDeclarations||[];Ee.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:Fe}),u=[{functionDeclarations:Ee}],g.debug("[GoogleVertex] Added final_result tool for structured output with tools (generate)",{schemaKeys:Object.keys(Fe),totalTools:Ee.length})}let f=_a(this.providerName,t,{temperature:e.temperature??1,...e.topP!==void 0&&{topP:e.topP}},"vertex.gemini"),h={...f.temperature!==void 0&&{temperature:f.temperature},maxOutputTokens:e.maxTokens};nP(t)&&(h.maxOutputTokens&&h.maxOutputTokens>Nl&&(g.warn(`[GoogleVertex] Capping maxOutputTokens from ${h.maxOutputTokens} to ${Nl} for ${t}`),h.maxOutputTokens=Nl),h.maxOutputTokens||(h.maxOutputTokens=Nl)),f.topP!==void 0&&(h.topP=f.topP),e.topK!==void 0&&(h.topK=e.topK),e.stopSequences&&e.stopSequences.length>0&&(h.stopSequences=e.stopSequences),u&&(h.tools=u);let y=e.systemPrompt||"";m&&(y=y+`
|
|
1132
1132
|
|
package/dist/core/loopEngine.js
CHANGED
|
@@ -150,9 +150,11 @@ export function runAgenticLoop(adapter, initialConversation, options) {
|
|
|
150
150
|
permanentlyFailed: true,
|
|
151
151
|
});
|
|
152
152
|
allToolExecutions.push({
|
|
153
|
+
id: call.id,
|
|
153
154
|
name: call.name,
|
|
154
155
|
input: call.args,
|
|
155
156
|
output,
|
|
157
|
+
error: output.error,
|
|
156
158
|
});
|
|
157
159
|
continue;
|
|
158
160
|
}
|
|
@@ -181,9 +183,11 @@ export function runAgenticLoop(adapter, initialConversation, options) {
|
|
|
181
183
|
permanentlyFailed: !!breaker,
|
|
182
184
|
});
|
|
183
185
|
allToolExecutions.push({
|
|
186
|
+
id: call.id,
|
|
184
187
|
name: call.name,
|
|
185
188
|
input: call.args,
|
|
186
189
|
output,
|
|
190
|
+
error: output.error,
|
|
187
191
|
});
|
|
188
192
|
continue;
|
|
189
193
|
}
|
|
@@ -194,6 +198,7 @@ export function runAgenticLoop(adapter, initialConversation, options) {
|
|
|
194
198
|
});
|
|
195
199
|
toolResults.push({ ...call, output });
|
|
196
200
|
allToolExecutions.push({
|
|
201
|
+
id: call.id,
|
|
197
202
|
name: call.name,
|
|
198
203
|
input: call.args,
|
|
199
204
|
output,
|
|
@@ -213,9 +218,11 @@ export function runAgenticLoop(adapter, initialConversation, options) {
|
|
|
213
218
|
const output = { error: message, status: "failed" };
|
|
214
219
|
toolResults.push({ ...call, output, error: message });
|
|
215
220
|
allToolExecutions.push({
|
|
221
|
+
id: call.id,
|
|
216
222
|
name: call.name,
|
|
217
223
|
input: call.args,
|
|
218
224
|
output,
|
|
225
|
+
error: message,
|
|
219
226
|
});
|
|
220
227
|
}
|
|
221
228
|
}
|
|
@@ -150,9 +150,11 @@ export function runAgenticLoop(adapter, initialConversation, options) {
|
|
|
150
150
|
permanentlyFailed: true,
|
|
151
151
|
});
|
|
152
152
|
allToolExecutions.push({
|
|
153
|
+
id: call.id,
|
|
153
154
|
name: call.name,
|
|
154
155
|
input: call.args,
|
|
155
156
|
output,
|
|
157
|
+
error: output.error,
|
|
156
158
|
});
|
|
157
159
|
continue;
|
|
158
160
|
}
|
|
@@ -181,9 +183,11 @@ export function runAgenticLoop(adapter, initialConversation, options) {
|
|
|
181
183
|
permanentlyFailed: !!breaker,
|
|
182
184
|
});
|
|
183
185
|
allToolExecutions.push({
|
|
186
|
+
id: call.id,
|
|
184
187
|
name: call.name,
|
|
185
188
|
input: call.args,
|
|
186
189
|
output,
|
|
190
|
+
error: output.error,
|
|
187
191
|
});
|
|
188
192
|
continue;
|
|
189
193
|
}
|
|
@@ -194,6 +198,7 @@ export function runAgenticLoop(adapter, initialConversation, options) {
|
|
|
194
198
|
});
|
|
195
199
|
toolResults.push({ ...call, output });
|
|
196
200
|
allToolExecutions.push({
|
|
201
|
+
id: call.id,
|
|
197
202
|
name: call.name,
|
|
198
203
|
input: call.args,
|
|
199
204
|
output,
|
|
@@ -213,9 +218,11 @@ export function runAgenticLoop(adapter, initialConversation, options) {
|
|
|
213
218
|
const output = { error: message, status: "failed" };
|
|
214
219
|
toolResults.push({ ...call, output, error: message });
|
|
215
220
|
allToolExecutions.push({
|
|
221
|
+
id: call.id,
|
|
216
222
|
name: call.name,
|
|
217
223
|
input: call.args,
|
|
218
224
|
output,
|
|
225
|
+
error: message,
|
|
219
226
|
});
|
|
220
227
|
}
|
|
221
228
|
}
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { resolveDeferredTool } from "../../tools/toolDiscovery.js";
|
|
25
25
|
import { stringifyAnthropicToolOutput } from "./toolOutput.js";
|
|
26
|
+
import { stringifyFinalResultInput } from "./structuredOutput.js";
|
|
26
27
|
/** Map Anthropic's stop_reason onto the unified finish reason. */
|
|
27
28
|
function mapAnthropicFinishReason(rawStopReason, hadToolCallsAtCap) {
|
|
28
29
|
switch (rawStopReason) {
|
|
@@ -271,10 +272,19 @@ export function createAnthropicLoopAdapter(config) {
|
|
|
271
272
|
// never dispatched, never counted against the breaker, and never shows
|
|
272
273
|
// up as a tool execution.
|
|
273
274
|
const terminal = config.finalResultToolName
|
|
274
|
-
?
|
|
275
|
+
? [...toolByIndex.values()].find((pending) => pending.name === config.finalResultToolName)
|
|
275
276
|
: undefined;
|
|
276
277
|
const toolCalls = terminal ? [] : allCalls;
|
|
277
|
-
|
|
278
|
+
// The RAW accumulated input_json, never the parsed-then-restringified
|
|
279
|
+
// args. `parseArgs` yields {} for a payload the token cap cut off
|
|
280
|
+
// mid-string, so re-stringifying would turn a truncated answer into
|
|
281
|
+
// "{}" and lose it outright. `stringifyFinalResultInput` canonicalizes
|
|
282
|
+
// when the JSON parses and returns it verbatim when it does not, which
|
|
283
|
+
// is what lets the caller's coercion layer repair a partial payload
|
|
284
|
+
// into a partial object instead of nothing.
|
|
285
|
+
const finalText = terminal
|
|
286
|
+
? stringifyFinalResultInput(terminal.inputJson)
|
|
287
|
+
: text;
|
|
278
288
|
return {
|
|
279
289
|
text: finalText,
|
|
280
290
|
...(reasoning ? { reasoning } : {}),
|
|
@@ -271,10 +271,24 @@ export type AgenticLoopOptions = {
|
|
|
271
271
|
export type AgenticLoopResult<TConversation> = {
|
|
272
272
|
text: string;
|
|
273
273
|
toolCalls: AgenticLoopToolCall[];
|
|
274
|
+
/**
|
|
275
|
+
* Every tool dispatch the loop performed, in order, including the ones that
|
|
276
|
+
* failed.
|
|
277
|
+
*
|
|
278
|
+
* `id` and `error` are carried because providers persist tool activity as
|
|
279
|
+
* paired call/result records keyed by the provider's own tool-call id, and
|
|
280
|
+
* a result that failed is stored differently from one that succeeded. A
|
|
281
|
+
* shape with only name/input/output cannot reconstruct either, so a
|
|
282
|
+
* provider migrating its hand-rolled loop onto this engine would have to
|
|
283
|
+
* silently drop both from its history — which is a behaviour change, not a
|
|
284
|
+
* refactor.
|
|
285
|
+
*/
|
|
274
286
|
toolExecutions: Array<{
|
|
287
|
+
id: string;
|
|
275
288
|
name: string;
|
|
276
289
|
input: Record<string, unknown>;
|
|
277
290
|
output: unknown;
|
|
291
|
+
error?: string;
|
|
278
292
|
}>;
|
|
279
293
|
usage: AgenticLoopUsage;
|
|
280
294
|
finishReason: string;
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { resolveDeferredTool } from "../../tools/toolDiscovery.js";
|
|
25
25
|
import { stringifyAnthropicToolOutput } from "./toolOutput.js";
|
|
26
|
+
import { stringifyFinalResultInput } from "./structuredOutput.js";
|
|
26
27
|
/** Map Anthropic's stop_reason onto the unified finish reason. */
|
|
27
28
|
function mapAnthropicFinishReason(rawStopReason, hadToolCallsAtCap) {
|
|
28
29
|
switch (rawStopReason) {
|
|
@@ -271,10 +272,19 @@ export function createAnthropicLoopAdapter(config) {
|
|
|
271
272
|
// never dispatched, never counted against the breaker, and never shows
|
|
272
273
|
// up as a tool execution.
|
|
273
274
|
const terminal = config.finalResultToolName
|
|
274
|
-
?
|
|
275
|
+
? [...toolByIndex.values()].find((pending) => pending.name === config.finalResultToolName)
|
|
275
276
|
: undefined;
|
|
276
277
|
const toolCalls = terminal ? [] : allCalls;
|
|
277
|
-
|
|
278
|
+
// The RAW accumulated input_json, never the parsed-then-restringified
|
|
279
|
+
// args. `parseArgs` yields {} for a payload the token cap cut off
|
|
280
|
+
// mid-string, so re-stringifying would turn a truncated answer into
|
|
281
|
+
// "{}" and lose it outright. `stringifyFinalResultInput` canonicalizes
|
|
282
|
+
// when the JSON parses and returns it verbatim when it does not, which
|
|
283
|
+
// is what lets the caller's coercion layer repair a partial payload
|
|
284
|
+
// into a partial object instead of nothing.
|
|
285
|
+
const finalText = terminal
|
|
286
|
+
? stringifyFinalResultInput(terminal.inputJson)
|
|
287
|
+
: text;
|
|
278
288
|
return {
|
|
279
289
|
text: finalText,
|
|
280
290
|
...(reasoning ? { reasoning } : {}),
|
|
@@ -271,10 +271,24 @@ export type AgenticLoopOptions = {
|
|
|
271
271
|
export type AgenticLoopResult<TConversation> = {
|
|
272
272
|
text: string;
|
|
273
273
|
toolCalls: AgenticLoopToolCall[];
|
|
274
|
+
/**
|
|
275
|
+
* Every tool dispatch the loop performed, in order, including the ones that
|
|
276
|
+
* failed.
|
|
277
|
+
*
|
|
278
|
+
* `id` and `error` are carried because providers persist tool activity as
|
|
279
|
+
* paired call/result records keyed by the provider's own tool-call id, and
|
|
280
|
+
* a result that failed is stored differently from one that succeeded. A
|
|
281
|
+
* shape with only name/input/output cannot reconstruct either, so a
|
|
282
|
+
* provider migrating its hand-rolled loop onto this engine would have to
|
|
283
|
+
* silently drop both from its history — which is a behaviour change, not a
|
|
284
|
+
* refactor.
|
|
285
|
+
*/
|
|
274
286
|
toolExecutions: Array<{
|
|
287
|
+
id: string;
|
|
275
288
|
name: string;
|
|
276
289
|
input: Record<string, unknown>;
|
|
277
290
|
output: unknown;
|
|
291
|
+
error?: string;
|
|
278
292
|
}>;
|
|
279
293
|
usage: AgenticLoopUsage;
|
|
280
294
|
finishReason: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "11.
|
|
3
|
+
"version": "11.11.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": {
|