@juspay/neurolink 12.14.11 → 12.14.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,8 +1,8 @@
1
- ## [12.14.11](https://github.com/juspay/neurolink/compare/v12.14.10...v12.14.11) (2026-09-16)
1
+ ## [12.14.12](https://github.com/juspay/neurolink/compare/v12.14.11...v12.14.12) (2026-09-17)
2
2
 
3
3
  ### Bug Fixes
4
4
 
5
- - **(providers):** ask for JSON when tools suppress response_format ([7012e72](https://github.com/juspay/neurolink/commit/7012e72cdc22bab1e7e6590d4b249f25455eba22))
5
+ - **(bedrock):** honour input.text in the native generate path ([705615f](https://github.com/juspay/neurolink/commit/705615f33427143d984ff4ad9a30309722adb2a3))
6
6
 
7
7
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
8
8
 
@@ -1071,7 +1071,7 @@ ${r[0].text}`;const n=r.length-1;r[n].text=`${r[n].text}
1071
1071
  IMPORTANT: You MUST call the 'final_result' tool to return your response in the required structured format. Do not respond with plain text - always use the final_result tool.`}});function PRr(e,t){switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return t?"tool-calls":"stop"}}async function DRr({params:e,client:t,channel:r,stepSignal:n,requestTimeoutSignal:o,noteObservedPromptTokens:s,finalResultToolName:i,onTerminalResult:a,requireTerminalEvent:c}){const l=await t.messages.create({...e,stream:!0},{signal:n}),u=new Map,d=new Map,m=new Map,h=new Map;let f="",g="",y,w=0,E=0,_=0,b=0,A=0,k=0,R=0,I=!1;for await(const F of l){if(n.aborted)break;const z=F;if(z.type==="message_start"){const q=z.message?.usage;w+=q?.input_tokens??0;const j=q?.output_tokens??0;E+=j-R,R=j,_+=q?.cache_read_input_tokens??0,b+=q?.cache_creation_input_tokens??0,A+=q?.cache_creation?.ephemeral_5m_input_tokens??0,k+=q?.cache_creation?.ephemeral_1h_input_tokens??0,s?.((q?.input_tokens??0)+(q?.cache_read_input_tokens??0)+(q?.cache_creation_input_tokens??0));continue}if(z.type==="content_block_start"){const q=z.index??0;if(z.content_block?.type==="redacted_thinking"){const j=z.content_block.data;typeof j=="string"&&h.set(q,j)}z.content_block?.type==="tool_use"&&d.set(q,{id:z.content_block.id??"",name:z.content_block.name??"",inputJson:""});continue}if(z.type==="content_block_delta"){const q=z.index??0,j=z.delta;if(j?.type==="text_delta"&&j.text)f+=j.text,u.set(q,(u.get(q)??"")+j.text),r.push({content:j.text});else if(j?.type==="thinking_delta"&&j.thinking){const W=m.get(q)??{text:"",signature:""};W.text+=j.thinking,m.set(q,W),g+=j.thinking,r.push({content:"",reasoning:j.thinking})}else if(j?.type==="signature_delta"&&j.signature){const W=m.get(q)??{text:"",signature:""};W.signature+=j.signature,m.set(q,W)}else if(j?.type==="input_json_delta"&&j.partial_json){const W=d.get(q);W&&(W.inputJson+=j.partial_json)}continue}if(z.type==="message_delta"){y=z.delta?.stop_reason??y;const q=z.usage?.output_tokens??R;E+=q-R,R=q;continue}z.type==="message_stop"&&(I=!0)}if(o?.aborted)throw o.reason;if(c&&!I&&!n.aborted)throw new be({code:"ANTHROPIC_STREAM_TRUNCATED",message:"Anthropic stream ended before its terminal message_stop event; the turn is incomplete and its content blocks were not dispatched.",category:"network",severity:"high",retriable:!1,context:{provider:"anthropic",rawStopReason:y}});const x=F=>{if(!F)return{};try{const z=JSON.parse(F);return typeof z=="object"&&z!==null&&!Array.isArray(z)?z:{}}catch{return{}}},M=[],N=new Set([...u.keys(),...d.keys(),...m.keys(),...h.keys()]);for(const F of[...N].sort((z,q)=>z-q)){const z=h.get(F);z&&M.push({type:"redacted_thinking",data:z});const q=m.get(F);q?.text&&q.signature&&M.push({type:"thinking",thinking:q.text,signature:q.signature});const j=u.get(F);j&&M.push({type:"text",text:j});const W=d.get(F);W&&M.push({type:"tool_use",id:W.id,name:W.name,input:x(W.inputJson)})}const U=[...d.values()].map(F=>({id:F.id,name:F.name,args:x(F.inputJson)})),P=i?[...d.values()].find(F=>F.name===i):void 0,D=P?[]:U,$=P?MRr(P.inputJson):f;return P&&a?.($),{text:$,...g?{reasoning:g}:{},toolCalls:D,usage:{inputTokens:w,outputTokens:E,cacheReadTokens:_,cacheWriteTokens:b,...A?{cacheWrite5mTokens:A}:{},...k?{cacheWrite1hTokens:k}:{}},rawStopReason:y,raw:M}}function GK(e){return{providerLabel:"anthropic",maxSteps:e.maxSteps,...e.toolFailureBreaker?{toolFailureBreaker:e.toolFailureBreaker}:{},...e.planReclaim?{planReclaim:(t,r)=>e.planReclaim?.(t,r)}:{},resolveToolOnMiss:t=>{const n=q8(e.toolsRecord,t)?.execute;if(n)return{execute:async(o,s)=>n(o,s)}},buildStepRequest(t,r){return{raw:e.buildParams(t,r)}},async executeStep(t,r,n){const o=t.raw,s=e.requestTimeoutMs?sa(e.requestTimeoutMs,"anthropic","stream"):null,i=r5(n,s?.controller.signal);try{return await DRr({params:o,client:e.client,channel:r,stepSignal:i.signal??n,requestTimeoutSignal:s?.controller.signal,...e.noteObservedPromptTokens?{noteObservedPromptTokens:e.noteObservedPromptTokens}:{},...e.finalResultToolName?{finalResultToolName:e.finalResultToolName}:{},...e.onTerminalResult?{onTerminalResult:e.onTerminalResult}:{},...e.requireTerminalEvent?{requireTerminalEvent:e.requireTerminalEvent}:{}})}finally{i.dispose(),s?.cleanup()}},appendPlanningNudge(t,r){const n={type:"text",text:r},o=t[t.length-1];if(o?.role==="user"&&Array.isArray(o.content)){const i={...o,content:[...o.content,n]};return[...t.slice(0,-1),i]}const s={role:"user",content:[n]};return[...t,s]},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw.filter(i=>i.type!=="server_tool_use")},s={role:"user",content:n.map(i=>({type:"tool_result",tool_use_id:i.id,content:i.error?`Error executing tool ${i.name}: ${i.error}`:zK(i.output),...i.error?{is_error:!0}:{}}))};return[...t,o,s]},mapFinishReason:PRr}}var Nwt=S({"src/lib/providers/anthropic/loopAdapter.ts"(){"use strict";zS(),Rwt(),Owt(),ia(),tt()}});function qK(e){if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return"image/png";if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70)return"image/gif";if(e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80)return"image/webp"}function J4(e,t){if(e instanceof ArrayBuffer)return J4(new Uint8Array(e),t);if(e instanceof Uint8Array)return{type:"image",source:{type:"base64",media_type:Y4(t)??qK(e)??"image/png",data:Buffer.from(e).toString("base64")}};if(typeof e!="string"&&!(e instanceof URL))return;const r=e instanceof URL?e.toString():e,n=r.match(/^data:(image\/[a-z0-9+.-]+);base64,(.+)$/i);if(n){const s=Y4(n[1])??HK(n[2]);return s?{type:"image",source:{type:"base64",media_type:s,data:n[2]}}:void 0}return/^https?:\/\//i.test(r)?{type:"image",source:{type:"url",url:r}}:{type:"image",source:{type:"base64",media_type:Y4(t)??HK(r)??"image/png",data:r}}}function ORr(e){const t=e?.data;if(t==null)return;const r=typeof e.mediaType=="string"?e.mediaType.toLowerCase().split(";")[0].trim():"";if(jK.has(r)||r==="image/jpg")return J4(t,r);if(r==="application/pdf")return VK(t);const n=t instanceof ArrayBuffer?new Uint8Array(t):t instanceof Uint8Array?t:void 0;if(n&&qK(n))return J4(n)}var jK,Y4,Lwt,HK,VK,NRr=S({"src/lib/providers/anthropicImageBlocks.ts"(){"use strict";jK=new Set(["image/jpeg","image/png","image/gif","image/webp"]),Y4=e=>{if(!e)return;const t=e.toLowerCase().split(";")[0].trim();return t==="image/jpg"?"image/jpeg":jK.has(t)?t:void 0},Lwt=32,HK=e=>{try{return qK(Buffer.from(e.slice(0,Lwt),"base64"))}catch{return}},VK=e=>{if(e instanceof ArrayBuffer)return VK(new Uint8Array(e));if(e instanceof Uint8Array)return{type:"document",source:{type:"base64",media_type:"application/pdf",data:Buffer.from(e).toString("base64")}};if(e instanceof URL)return{type:"document",source:{type:"url",url:e.toString()}};if(typeof e=="string"){const t=e.match(/^data:application\/pdf;base64,(.+)$/i);return t?{type:"document",source:{type:"base64",media_type:"application/pdf",data:t[1]}}:/^https?:\/\//i.test(e)?{type:"document",source:{type:"url",url:e}}:{type:"document",source:{type:"base64",media_type:"application/pdf",data:e}}}}}}),Z4,Fwt=S({"src/lib/providers/anthropic/constants.ts"(){"use strict";Z4={"anthropic-beta":["claude-code-20250219","fine-grained-tool-streaming-2025-05-14"].join(",")}}}),WK,H0,$wt,KK,Uwt,Bwt,JK,YK,zwt,ZK,Gwt,LRr=S({"src/lib/providers/anthropic/client.ts"(){"use strict";vyt(),Kt(),Cn(),bi(),hr(),Db(),ZF(),Sc(),Lo(),Tpt(),mwt(),fRr(),Wn(),CRr(),ut(),Qs(),B(),_9(),Cwt(),nd(),ni(),Qt(),Iwt(),tl(),Rwt(),Nwt(),ad(),CP(),SV(),zu(),fh(),Eh(),nl(),Vo(),ia(),Wh(),Xpt(),Spt(),hm(),U7(),ti(),m9(),NRr(),hh(),Vm(),g0(),F9(),Fwt(),Tmt(),Owt(),mwt(),WK=()=>yi(Wlr()),H0=()=>vi("ANTHROPIC_MODEL","claude-sonnet-4-6"),$wt=lt.getTracer("neurolink.provider.anthropic"),KK=()=>{try{const t=Ct(_i(),".neurolink","anthropic-credentials.json");if(Ms(t)){const r=Hu(t,"utf-8"),n=JSON.parse(r);if(n.type==="oauth"&&n.oauth?.accessToken)return p.debug("[AnthropicProvider] Using OAuth token from stored credentials file"),n.oauth}}catch(t){p.debug("[AnthropicProvider] Failed to read stored credentials:",t)}const e=process.env.ANTHROPIC_OAUTH_TOKEN||process.env.CLAUDE_OAUTH_TOKEN;if(!e)return null;try{const t=JSON.parse(e);if(typeof t=="object"&&t.accessToken)return t;if(typeof t=="string")return{accessToken:t}}catch{}return{accessToken:e}},Uwt=e=>{const t=process.env.ANTHROPIC_SUBSCRIPTION_TIER?.toLowerCase();if(t){const r=["free","pro","max","max_5","max_20","api"];if(r.includes(t))return p.debug("[detectSubscriptionTier] Using environment override",{tier:t}),t;p.warn("[detectSubscriptionTier] Invalid ANTHROPIC_SUBSCRIPTION_TIER",{value:t,validTiers:r})}if(e){const r=e.scopes??[];let n="pro";return r.includes("max_20")?n="max_20":r.includes("max_5")?n="max_5":r.includes("max")&&(n="max"),p.debug("[detectSubscriptionTier] Detected from OAuth token",{tier:n,scopes:r}),n}return p.debug("[detectSubscriptionTier] No OAuth token, defaulting to API tier"),"api"},Bwt=e=>{const t=process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase();if(t==="api_key"||t==="apikey")return p.debug("[detectAuthMethod] Forced to api_key by ANTHROPIC_AUTH_METHOD env var"),"api_key";if(t==="oauth"){if(e)return p.debug("[detectAuthMethod] Forced to oauth by ANTHROPIC_AUTH_METHOD env var"),"oauth";p.warn("[detectAuthMethod] ANTHROPIC_AUTH_METHOD=oauth but no OAuth token found; falling through to auto-detection")}else t&&p.warn("[detectAuthMethod] Unrecognized ANTHROPIC_AUTH_METHOD value; falling through to auto-detection",{value:t});const r=e?"oauth":"api_key";return p.debug("[detectAuthMethod] Auth method resolved",{method:r,hasOAuthToken:!!e}),r},JK=e=>{const t=[],r=[],n=i=>Array.isArray(i)?i:[i],o=(i,a)=>{const c=md(a);if(c&&i.length>0){const l=i[i.length-1];l.cache_control=c}};for(const i of e)switch(i.role){case"system":{const a=typeof i.content=="string"?i.content:n(i.content).map(l=>typeof l=="string"?l:String(l?.text??"")).join(`
1072
1072
  `),c=md(i);t.push({type:"text",text:a,...c?{cache_control:c}:{}});break}case"user":{const a=[];for(const c of n(i.content)){if(typeof c=="string"){c.length>0&&a.push({type:"text",text:c});continue}const l=c;if(l?.type==="text"&&typeof l.text=="string"){const u=md(l);a.push({type:"text",text:l.text,...u?{cache_control:u}:{}})}else if(l?.type==="image"||l?.type==="image_url"){const u=J4(l.image??l.data??l.url);if(u){const d=md(l);a.push(d?{...u,cache_control:d}:u)}}else if(l?.type==="file"){const d=typeof l=="object"&&l!==null&&("mediaType"in l?typeof l.mediaType=="string":!0)?ORr(l):void 0;if(d){const m=md(l);m&&(d.cache_control=m),a.push(d)}}}a.length>0&&(o(a,i),r.push({role:"user",content:a}));break}case"assistant":{const a=[];for(const c of n(i.content)){if(typeof c=="string"){c.length>0&&a.push({type:"text",text:c});continue}const l=c;if(l?.type==="reasoning"){const u=l.providerOptions?.anthropic,d=u?.redactedData;if(typeof d=="string"&&d.length>0){a.push({type:"redacted_thinking",data:d});continue}const m=u?.signature;typeof m=="string"&&m.length>0&&typeof l.text=="string"&&l.text.length>0&&a.push({type:"thinking",thinking:l.text,signature:m});continue}if(l?.type==="text"&&typeof l.text=="string"){if(l.text.length>0){const u=md(l);a.push({type:"text",text:l.text,...u?{cache_control:u}:{}})}}else if(l?.type==="tool-call"){let u=l.input;if(typeof u=="string")try{u=JSON.parse(u)}catch{u={}}a.push({type:"tool_use",id:l.toolCallId??"",name:l.toolName??"",input:u??{}})}}a.length>0&&(o(a,i),r.push({role:"assistant",content:a}));break}case"tool":{const a=[];if(Array.isArray(i.content))for(const c of i.content){const l=c;l?.type==="tool-result"&&a.push({type:"tool_result",tool_use_id:l.toolCallId??"",content:zK(l.output)})}else typeof i.content=="string"&&a.push({type:"tool_result",tool_use_id:i.toolCallId??"",content:i.content});a.length>0&&r.push({role:"user",content:a});break}}const s=t.length===0?void 0:t.some(i=>i.cache_control)?t:t.map(i=>i.text).join(`
1073
1073
 
1074
- `);return{...s!==void 0?{system:s}:{},messages:r}},YK=e=>{if(!(!e||e==="auto")){if(e==="none")return{type:"none"};if(e==="required")return{type:"any"};if(typeof e=="object"){const t=e;if(t.type==="tool"&&t.toolName)return{type:"tool",name:t.toolName}}}},zwt=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},ZK=6e5,Gwt=class extends ja{client;authMethod;subscriptionTier;enableBetaFeatures;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,r,n){const o=!!(n?.apiKey&&!n?.oauthToken),s=o?null:(n?.oauthToken?{accessToken:n.oauthToken}:null)??r?.oauthToken??KK(),i=o?"api_key":r?.authMethod??Bwt(s),a=r?.subscriptionTier??(i==="oauth"?Uwt(s):"api"),c=e||H0();let l=c;!process.env.ANTHROPIC_BASE_URL&&a!=="api"&&!NK(c,a)&&(l=LK(a),p.warn("Model not available for subscription tier, using recommended model",{requestedModel:c,subscriptionTier:a,recommendedModel:l})),super(l,"anthropic",t),this.enableBetaFeatures=r?.enableBetaFeatures??!0,this.oauthToken=s,this.subscriptionTier=a,this.authMethod=i;const d=this.getAuthHeaders();let m;if(p.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){p.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");const h=this.oauthToken,f=hRr(()=>h.accessToken,this.enableBetaFeatures,!1,!0);m=new hf({apiKey:"oauth-authenticated",fetch:ywt(f),timeout:ZK,maxRetries:0}),p.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),p.debug("Anthropic Provider initialized with OAuth",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,hasRefreshToken:!!this.oauthToken.refreshToken,tokenExpiry:this.oauthToken.expiresAt?new Date(this.oauthToken.expiresAt).toISOString():"none"})}else{const h=n?.apiKey??r?.apiKey??WK(),f=(()=>{const g=process.env.ANTHROPIC_BASE_URL;if(!g)return;const y=g.replace(/\/+$/,""),w=y.replace(/\/v\d+$/,"");return w!==y&&p.debug("[AnthropicProvider] Stripping the version suffix from ANTHROPIC_BASE_URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:zn(g),rewrittenTo:zn(w)}),w})();m=new hf({apiKey:h,defaultHeaders:d,...f&&{baseURL:f},fetch:ywt(Mt()),timeout:ZK,maxRetries:0}),p.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.client=m,this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},p.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?Z4["anthropic-beta"]:"disabled"})}getAuthHeaders(){const e={},t=!!process.env.ANTHROPIC_BASE_URL;if(this.enableBetaFeatures)if(t){const r=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",n=[...Pb,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];r&&n.push("context-1m-2025-08-07"),e["anthropic-beta"]=n.join(",")}else e["anthropic-beta"]=Z4["anthropic-beta"];return t&&(e["User-Agent"]=ff),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return p.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;const t=NK(e,this.subscriptionTier);return t||p.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return FK(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){p.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){p.debug("Token has no expiry information, assuming valid");return}const e=Date.now(),t=this.oauthToken.expiresAt<=e,r=this.oauthToken.expiresAt<=e+cae;if(!t&&!r){p.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new _r("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);p.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}p.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});const n=this.oauthToken,o=n.refreshToken;this.refreshPromise=(async()=>{const i=new AbortController,a=setTimeout(()=>i.abort(),3e4),c=await fetch(Mb,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":ff},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:DK}),signal:i.signal});if(clearTimeout(a),!c.ok){const d=await c.text();throw new _r(`Failed to refresh OAuth token: ${c.status} ${d}`,this.providerName)}const l=await c.json();n.accessToken=l.access_token,n.refreshToken=l.refresh_token||n.refreshToken,n.expiresAt=l.expires_in?Date.now()+l.expires_in*1e3:void 0,n.tokenType=l.token_type||"Bearer";const u=n;try{const d=Ct(_i(),".neurolink");Ms(d)||O5(d,{recursive:!0});const m=Ct(d,"anthropic-credentials.json"),h=`${m}.tmp`,g={...Ms(m)?JSON.parse(Hu(m,"utf-8")):{},type:"oauth",oauth:u,updatedAt:Date.now()};iR(h,JSON.stringify(g,null,2),{mode:384}),L5(h,m),p.debug("Refreshed OAuth credentials persisted to disk")}catch(d){p.warn("Failed to persist refreshed OAuth token to disk",{error:d instanceof Error?d.message:String(d)})}p.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!l.refresh_token,expiresIn:l.expires_in})})();try{await this.refreshPromise}catch(s){throw s instanceof _r?s:new _r(`Failed to refresh OAuth token: ${s instanceof Error?s.message:String(s)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,r){this.lastResponseMetadata={rateLimit:e,...t?{requestId:t}:{}},this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),r&&(r.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=r.inputTokens,this.usageInfo.tokensUsed+=r.inputTokens),r.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=r.outputTokens,this.usageInfo.tokensUsed+=r.outputTokens)),e?.requestsRemaining!==void 0&&(this.usageInfo.messagesRemaining=e.requestsRemaining),e?.tokensRemaining!==void 0&&(this.usageInfo.tokensRemaining=e.tokensRemaining),e?.requestsLimit&&e.requestsLimit>0&&(this.usageInfo.messageQuotaPercent=Math.round((e.requestsLimit-(e.requestsRemaining??0))/e.requestsLimit*100)),e?.tokensLimit&&e.tokensLimit>0&&(this.usageInfo.tokenQuotaPercent=Math.round((e.tokensLimit-(e.tokensRemaining??0))/e.tokensLimit*100)),e?.retryAfter!==void 0?(this.usageInfo.isRateLimited=!0,this.usageInfo.rateLimitExpiresAt=Date.now()+e.retryAfter*1e3):(this.usageInfo.isRateLimited=!1,this.usageInfo.rateLimitExpiresAt=void 0)),e?.requestsRemaining!==void 0&&e.requestsRemaining<=5&&p.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&&p.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return H0()}getAISDKModel(){const e=this.client,t=this.providerName,r=this.modelName||H0(),n=i=>this.getTimeout(i??{}),o=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:r,supportedUrls:{},doGenerate:async i=>{await o();const a=JK(i.prompt),c=a.messages;let l=a.system,u=(i.tools??[]).filter(F=>F.type==="function").map(F=>{const z=md(F);return{name:F.name,...F.description?{description:F.description}:{},input_schema:F.inputSchema??{type:"object",properties:{}},...z?{cache_control:z}:{}}});u&&u.length===0&&(u=void 0);let d=i.toolChoice?YK(i.toolChoice.type==="tool"?{type:"tool",toolName:i.toolChoice.toolName}:i.toolChoice.type):void 0,m;if(i.responseFormat?.type==="json"){m=i.responseFormat.name??"json";const F=i.responseFormat.schema??{type:"object"};u=[{name:m,description:i.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:F}],d={type:"tool",name:m}}const h=i.providerOptions?.anthropic?.finalResultSchema;let f=!1;if(!m&&h){const F=Mwt(u,h);u=F.tools,f=F.applied,F.applied&&(l=Pwt(l))}const g=i.providerOptions?.anthropic?.thinking;u=L9(u);const y=kwt({system:l,tools:u,messages:c}),w=Awt(c,V4-y),E=Ql("anthropic",r,{...i.temperature!==void 0&&i.temperature!==null?{temperature:i.temperature}:{},...i.topP!==void 0&&i.topP!==null?{topP:i.topP}:{}},"anthropic.doGenerate");g&&(E.temperature!==void 0||E.topP!==void 0)&&p.debug("[anthropic] extended thinking is enabled, so temperature/top_p are omitted \u2014 Anthropic rejects any temperature but 1 while thinking is set");const _={model:r,messages:w,max_tokens:iP(r,i.maxOutputTokens),...l?{system:l}:{},...!g&&E.temperature!==void 0?{temperature:E.temperature}:{},...!g&&E.topP!==void 0?{top_p:E.topP}:{},...i.stopSequences&&i.stopSequences.length>0?{stop_sequences:i.stopSequences}:{},...u?{tools:u}:{},...d?{tool_choice:d}:{},...g?{thinking:g}:{}},b=i.providerOptions?.neurolink,A=typeof b?.timeoutMs=="number"&&Number.isFinite(b.timeoutMs)&&b.timeoutMs>0?b.timeoutMs:void 0,k=A!==void 0?A:_.max_tokens>8192?Math.max(n(i),3e5):n(i),R=sa(k,t,"generate"),I=WI(i.abortSignal,R?.controller.signal);let x;try{x=await e.messages.create(_,{signal:I})}catch(F){const z=I?.aborted?I.reason:void 0;throw z instanceof Da?z:F}finally{R?.cleanup()}const M=[];let N;const U=[];let P=!1;for(const F of x.content)F.type==="thinking"?M.push({type:"reasoning",text:F.thinking,providerOptions:{anthropic:{signature:F.signature}}}):F.type==="redacted_thinking"?M.push({type:"reasoning",text:"",providerOptions:{anthropic:{redactedData:F.data}}}):F.type==="text"?m?U.push(F.text):M.push({type:"text",text:F.text}):F.type==="tool_use"&&(m&&F.name===m?(P=!0,M.push({type:"text",text:U_(F.input)})):f&&F.name===Nb?N=U_(F.input):M.push({type:"tool-call",toolCallId:F.id,toolName:F.name,input:U_(F.input)}));if(m&&!P&&U.length>0&&M.push({type:"text",text:U.join("")}),N!==void 0){const F=M.filter(z=>z.type==="reasoning");M.length=0,M.push(...F,{type:"text",text:N}),p.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:N.length})}const D=x.usage.cache_read_input_tokens??0,$=x.usage.cache_creation_input_tokens??0;return{content:M,finishReason:{unified:N!==void 0?"stop":zwt(x.stop_reason),raw:x.stop_reason??"stop"},usage:{inputTokens:{total:x.usage.input_tokens+D+$,noCache:x.usage.input_tokens,cacheRead:D,cacheWrite:$},outputTokens:{total:x.usage.output_tokens,text:x.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:_},response:{id:x.id,modelId:x.model,headers:ERr()??{},body:x}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model. NeuroLink streams through executeStream, reached via NeuroLink.stream() \u2014 use that (the browser bundle exports the NeuroLink class) rather than calling doStream on a model handle.`)}}}formatProviderError(e){return gi(e,[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(r.message),errorClass:_r,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:r=>r.statusCode===429||/rate limit|too_many_requests|429/i.test(r.message),errorClass:ms,message:"Anthropic rate limit exceeded. Please try again later."},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(r.message),errorClass:Xn,message:r=>`Connection error: ${r.message}`},{match:r=>/500|502|503|504|server error/i.test(r.message),errorClass:dt,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:dt,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await wRr(()=>this.dispatchGenerate(e,t));return r&&n&&(this.recordLimitSnapshot(n),r.limits=n,r.analytics&&(r.analytics.limits=n)),r}async dispatchGenerate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if(Zu(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),s=>this.executeNativeGenerate(s)),o)}async executeNativeGenerate(e){const t=Date.now(),r=this.modelName||H0(),n=await this.getAISDKModelWithMiddleware(e);if(!PP(n))throw this.handleProviderError(new Error("anthropic: model handle exposes no doGenerate()"));const o=n.doGenerate.bind(n),i=!e.disableTools&&this.supportsTools()?e.tools||{}:{},a=Object.entries(i).map(([E,_])=>{const b=_;return{type:"function",name:E,description:b.description??"",inputSchema:b.inputSchema?Mo(b.inputSchema):{type:"object",properties:{}}}}),c=a.length>0,l=e.schema?Mo(e.schema):void 0,u=l&&!c?{type:"json",schema:l}:void 0,d={};l&&c&&(d.finalResultSchema=l),e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens&&(d.thinking={type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens});const m={};Object.keys(d).length>0&&(m.anthropic=d),typeof e.timeout=="number"&&(m.neurolink={timeoutMs:e.timeout});const h=Object.keys(m).length>0?m:void 0,f=await this.buildMessagesForStream(e),g=[],y=await TV({doGenerate:o,conversation:f,...c?{tools:a}:{},toolsRecord:i,...c&&e.toolChoice?{toolChoice:NP(e,i,!0)}:{},...u?{responseFormat:u}:{},...h?{providerOptions:h}:{},maxSteps:e.maxSteps||Ds,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:E=>py(E,lt.getActiveSpan()??void 0,"anthropic generate").catch(_=>{throw this.handleProviderError(_)})},g),w={content:y.text,provider:this.providerName,model:r,finishReason:y.finishReason,...y.rawFinishReason?{rawFinishReason:y.rawFinishReason}:{},...y.reasoning?{reasoning:y.reasoning}:{},usage:{input:y.inputTokens,output:y.outputTokens,total:y.inputTokens+y.outputTokens,...y.cacheReadTokens?{cacheReadTokens:y.cacheReadTokens}:{},...y.cacheWriteTokens?{cacheCreationTokens:y.cacheWriteTokens}:{}},responseTime:Date.now()-t,toolsUsed:y.toolsUsed,toolCalls:A8(g),toolExecutions:Gy(e,Th(g)),enhancedWithTools:y.toolsUsed.length>0};return this.finalizeNativeGenerate(w,e,t)}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),_Rr(e),bRr(e,this.modelName)}supportsExecutionControl(){return!0}async executeStream(e,t){return SRr(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);const r=e.executionControl,n=typeof e.turnTimeoutMs=="number"&&Number.isFinite(e.turnTimeoutMs)&&e.turnTimeoutMs>0,o=r&&r.lifetimeTimeoutMs!==void 0?r.lifetimeTimeoutMs??void 0:n?e.turnTimeoutMs:this.getTimeout(e),s=sa(o,this.providerName,"stream"),i=new AbortController,a=Qpe([e.abortSignal,s?.controller.signal,i.signal]).signal;let c,l,u,d,m=!1;try{d=!e.disableTools&&this.supportsTools(),c=d?e.tools||await this.getAllTools():{},l=d?y0(c,"input_schema"):void 0;const ye=await this.buildMessagesForStream(e);if(u=JK(ye),e.schema&&l&&l.length>0){const Se=Mwt(l,Mo(e.schema));l=Se.tools,m=Se.applied,Se.applied&&(u.system=Pwt(u.system))}}catch(ye){throw s?.cleanup(),this.handleProviderError(ye)}const h=this.modelName||H0(),f=d&&l&&l.length>0?YK(NP(e,c,d)):void 0,g=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,y=$wt.startSpan("neurolink.provider.streamText",{kind:Fr.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":h}}),w=e.maxSteps||Ds,E=this.neurolink?.getEventEmitter(),_=f0(),{push:b}=_,{usagePromise:A,finishPromise:k,resolveUsage:R,resolveFinish:I}=mV();A.then(ye=>{y.setAttribute("gen_ai.usage.input_tokens",ye.promptTokens||0),y.setAttribute("gen_ai.usage.output_tokens",ye.completionTokens||0),ye.cacheReadTokens&&y.setAttribute("gen_ai.usage.cached_input_tokens",ye.cacheReadTokens);const Se=Ba(this.providerName,this.modelName,{input:ye.promptTokens||0,output:ye.completionTokens||0,total:ye.totalTokens||0,...ye.cacheReadTokens?{cacheReadTokens:ye.cacheReadTokens}:{},...ye.cacheCreationTokens?{cacheCreationTokens:ye.cacheCreationTokens}:{}});Se&&Se>0&&y.setAttribute("neurolink.cost",Se)}).catch(()=>{}),k.then(ye=>{y.setAttribute("gen_ai.response.finish_reason",ye||"unknown"),y.end()}).catch(()=>{y.end()});let x;const M=this.client,N=[],U=Date.now(),P={};let D=0,$=0,F=0,z=0,q=null;const j=()=>({promptTokens:D,completionTokens:$,totalTokens:D+F+z+$,...F>0?{cacheReadTokens:F}:{},...z>0?{cacheCreationTokens:z}:{}});let W="",H;const se=(ye,Se)=>{const xe=Te=>{if(typeof Te=="string")return Te;try{return JSON.stringify(Te)??""}catch{return""}};return gr(xe(ye),"anthropic")+gr(xe(Se),"anthropic")},ue=(async()=>{let ye,Se;const Fe=GK({client:M,maxSteps:w,toolsRecord:c,buildParams:Q=>{if(l){const ce=new Set(l.map(Oe=>Oe.name)),Ae=Object.fromEntries(Object.entries(c).filter(([Oe])=>!ce.has(Oe)));if(Object.keys(Ae).length>0){const Oe=y0(Ae,"input_schema");Oe&&Oe.length>0&&(l=[...l,...Oe])}}const K=L9(l),J=kwt({system:u.system,tools:K,messages:Q}),ie=Awt(Q,V4-J),pe=Ql("anthropic",h,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream");return g&&pe.temperature!==void 0&&p.debug("[anthropic] extended thinking is enabled, so temperature is omitted on the stream path \u2014 Anthropic rejects any temperature but 1 while thinking is set"),{model:h,messages:ie,max_tokens:iP(h,e.maxTokens),...u.system?{system:u.system}:{},...!g&&pe.temperature!==void 0?{temperature:pe.temperature}:{},...K&&K.length>0?{tools:K}:{},...f?{tool_choice:f}:{},...g?{thinking:g}:{}}},planReclaim:Q=>{const K=bwt({conversation:Q,availableInputTokens:nu("anthropic",h,e.maxTokens??void 0),fixedOverheadTokens:se(u.system,l),provider:"anthropic",observedPromptTokens:ye,previousSentEstimate:Se,onSentEstimate:ce=>{Se=ce}});if(!K)return;const J=new Set(K.drop),ie=new Set(K.truncate),pe=[];for(let ce=0;ce<Q.length;ce++){if(J.has(ce))continue;const Ae=Q[ce];if(ie.has(ce)&&Array.isArray(Ae.content)){pe.push({...Ae,content:Ae.content.map(Oe=>Oe.type==="tool_result"?{...Oe,content:_wt(typeof Oe.content=="string"?Oe.content:JSON.stringify(Oe.content)??"")}:Oe)});continue}pe.push(Ae)}if(J.size>0){let ce=pe.findIndex(Ae=>Array.isArray(Ae.content)&&Ae.content.some(Oe=>Oe.type==="tool_use"||Oe.type==="tool_result"));ce<0&&(ce=Math.min(1,pe.length)),pe.splice(ce,0,{role:"user",content:[{type:"text",text:BK}]})}return{conversation:pe}},...r?{requestTimeoutMs:r.requestTimeoutMs,requireTerminalEvent:!0}:{},noteObservedPromptTokens:Q=>{ye=Q},...m?{finalResultToolName:Nb,onTerminalResult:Q=>{H=Q,p.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:Q.length})}}:{}}),De={...Fe,buildToolResultMessages:(Q,K,J,ie)=>{for(const Ae of J)N.push(Ae.name);const pe=J.map(Ae=>({type:"tool-call",toolCallId:Ae.id,toolName:Ae.name,args:Ae.args})),ce=J.map(Ae=>Ae.error?{type:"tool-result",toolCallId:Ae.id,toolName:Ae.name,error:Ae.error}:{type:"tool-result",toolCallId:Ae.id,toolName:Ae.name,result:Ae.output});return Ept(E,ce.map(Ae=>({toolName:Ae.toolName,result:"result"in Ae?Ae.result:void 0,error:"error"in Ae?Ae.error:void 0}))),this.handleToolExecutionStorage(pe,ce,e,new Date).catch(Ae=>{p.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:Ae instanceof Error?Ae.message:String(Ae)})}),Fe.buildToolResultMessages(Q,K,J,ie)}},We={};for(const[Q,K]of Object.entries(c)){const J=K.execute;J&&(We[Q]={execute:async(ie,pe)=>{const ce=pe;return J(ie,{toolCallId:ce.toolCallId??"",...ce.abortSignal?{abortSignal:ce.abortSignal}:{},messages:[]})}})}const Ze=lt.getActiveSpan(),Pt=r?.beforeStep,Me=Pt?async Q=>{const K=r?.beforeStepTimeoutMs??$7,J=sa(K,this.providerName,"stream"),ie=r5(Q.signal,J?.controller.signal);try{return await t5(Promise.resolve(Pt({...Q,signal:ie.signal??Q.signal})),ie.signal??Q.signal)}catch(pe){p.warn("[Anthropic] executionControl.beforeStep failed or timed out; the step cap stands",{error:pe instanceof Error?pe.message:String(pe),stepsCompleted:Q.stepsCompleted});return}finally{ie.dispose(),J?.cleanup()}}:void 0,{stream:ke,resultPromise:Ke}=dd(De,u.messages.slice(),{tools:We,...a?{abortSignal:a}:{},...Ze?{span:Ze}:{},...Me?{beforeStep:Me}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}}),oe=(async()=>{for await(const Q of ke)Q.reasoning&&b({content:"",reasoning:Q.reasoning}),Q.content&&(m?W+=Q.content:b({content:Q.content}))})();let Y;try{Y=await Ke}catch(Q){throw await Vh(oe,"Anthropic"),Q}if(await oe,D+=Y.usage.inputTokens,$+=Y.usage.outputTokens,F+=Y.usage.cacheReadTokens??0,z+=Y.usage.cacheWriteTokens??0,q=Y.rawStopReason??q,Y.aborted){const Q=a?.aborted?a.reason:void 0;P.stopReason=Q instanceof Da?"time-limit":"aborted",P.finishReason="other",Y.rawStopReason&&(P.rawFinishReason=Y.rawStopReason),R(j()),I("other");return}P.finishReason=Y.finishReason,Y.rawStopReason&&(P.rawFinishReason=Y.rawStopReason),Y.finishReason==="tool-calls"&&H===void 0&&(P.stopReason="step-cap"),R(j()),I(q??"stop")})().catch(ye=>{throw x=ye,p.error("Anthropic: Stream error",{error:ye instanceof Error?ye.message:String(ye)}),R(j()),I("error"),this.formatProviderError(ye)}).finally(()=>{if(m){const ye=H??W;ye.length>0&&b({content:ye})}s?.cleanup(),_.close()});ue.catch(()=>{});const V=this.providerName;return{stream:async function*(){let ye=0;try{for await(const Se of _.iterable)"content"in Se&&typeof Se.content=="string"&&Se.content.length>0&&ye++,yield Se;if(await ue,ye===0&&N.length===0){p.warn(`${V}: Stream produced no output \u2014 emitting enriched sentinel`);const Se=new Gl({message:"Stream produced no output"}),xe=await zh(Se,void 0,x);Gh(xe),yield xe}}catch(Se){const xe=await zh(Se,void 0,x);if(Gh(xe),yield xe,!Gl.isInstance(Se))throw Se}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],metadata:P,analytics:k.then(async()=>{const ye=await wV.createAnalytics(this.providerName,h,{textStream:(async function*(){})(),usage:A,finishReason:k},Date.now()-U,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),Se=TRr();return Se&&ye&&(this.recordLimitSnapshot(Se),ye.limits=Se),ye})}}async isAvailable(){try{return KK()||WK(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),qwt={};ne(qwt,{ANTHROPIC_BETA_HEADERS:()=>Z4,AnthropicProvider:()=>Gwt,ModelAccessError:()=>A$,getModelCapabilities:()=>FK,getRecommendedModelForTier:()=>LK,isModelAvailableForTier:()=>NK});var FRr=S({"src/lib/providers/anthropic/index.ts"(){"use strict";LRr(),Fwt()}}),gf,$s,$Rr,URr,jwt,Hwt,Vwt,Lb,Wwt,BRr,zRr,GRr,qRr,jRr,HRr,VRr,WRr,KRr,JRr,YRr,ZRr,XRr,QRr,e1r,t1r,r1r,n1r,o1r,s1r,i1r,a1r,c1r,l1r,u1r,d1r,m1r,p1r,h1r,f1r,g1r,y1r,v1r,w1r,T1r,E1r,S1r,_1r,b1r,Kwt=S({"npm-stub:@aws-sdk/client-bedrock-runtime"(){gf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:gf.get}):new Proxy(function(...r){return new Proxy({},{get:gf.get})},{get:gf.get,apply(r,n,o){return new Proxy({},{get:gf.get})},construct(r,n){return new Proxy({},{get:gf.get})}})}},$s=new Proxy({},gf),{BedrockClient:$Rr,ListFoundationModelsCommand:URr,BedrockRuntimeClient:jwt,ConverseCommand:Hwt,ConverseStreamCommand:Vwt,ImageFormat:Lb,InvokeModelCommand:Wwt}=$s,{SageMakerRuntimeClient:BRr,InvokeEndpointCommand:zRr,InvokeEndpointWithResponseStreamCommand:GRr}=$s,{GoogleAuth:qRr,VertexAI:jRr,TextToSpeechClient:HRr}=$s,{Webhook:VRr}=$s,{Hippocampus:WRr,HippocampusConfig:KRr}=$s,{createClient:JRr}=$s,{Queue:YRr,Worker:ZRr,Job:XRr,QueueScheduler:QRr,FlowProducer:e1r}=$s,{Cron:t1r}=$s,{parseBuffer:r1r,selectCover:n1r}=$s,{extractRawText:o1r,convertToHtml:s1r}=$s,{Hono:i1r}=$s,{cors:a1r,HTTPException:c1r,logger:l1r,secureHeaders:u1r,streamSSE:d1r,timeout:m1r}=$s,p1r=globalThis.fetch,h1r=globalThis.Request,f1r=globalThis.Response,g1r=globalThis.Headers,y1r=globalThis.FormData,v1r=globalThis.File,w1r=globalThis.Blob,T1r=$s.Agent,E1r=$s.Pool,S1r=$s.Client,_1r=$s.Dispatcher,b1r=$s.MockAgent}});function C1r(e){if(/^(us|ca)-/.test(e))return"us";if(/^(eu|il|me|af)-/.test(e))return"eu";if(/^ap-northeast-[13]$/.test(e))return"jp";if(/^ap-southeast-[246]$/.test(e))return"au";if(/^ap-/.test(e))return"apac"}function k1r(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function Jwt(e){if(typeof e!="object"||e===null)return!1;const t=e,r=typeof t.name=="string"?t.name:"",n=typeof t.message=="string"?t.message:"";return!/ValidationException/i.test(r)&&!/ValidationException/i.test(n)?!1:/inference profile/i.test(n)&&/on-demand throughput/i.test(n)}function A1r(e,t){if(e.startsWith("arn:")||k1r(e))return[];const r=[],n=C1r(t);return n&&r.push(`${n}.${e}`),r.push(`${Xwt}.${e}`),r}function Ywt(e,t){return`${e}::${t}`}function x1r(e,t){return XK.get(Ywt(t,e))}function I1r(e,t,r){XK.set(Ywt(t,e),r),p.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function Zwt(e,t,r){const n=x1r(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!Jwt(o))throw o;const s=A1r(e,t);if(s.length===0)throw o;p.warn("[Bedrock] Model requires a cross-region inference profile in this region; retrying with a prefixed id",{region:t,candidates:s.length});for(const i of s)try{const a=await r(i);return I1r(e,t,i),a}catch(a){if(!Jwt(a))throw a}throw o}}var Xwt,XK,R1r=S({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";B(),Xwt="global",XK=new Map}});function X4(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Qwt(e,t){if(e){if(e.toolUse&&e._inputBuffer){try{e.toolUse.input=JSON.parse(e._inputBuffer)}catch{e.toolUse.input={}}delete e._inputBuffer}t&&!e.toolUse&&(e.text=t)}}function eTt(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??X4(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function M1r(e,t,r){const n=[],o=new Map,s=new Map,i=f=>{let g=o.get(f);return g||(g={},o.set(f,g),n.push(g)),g};let a="",c,l=0,u=0,d=0,m=0;if(e.stream)for await(const f of e.stream){if(r.aborted)break;const g=f;if(g.contentBlockStart&&i(g.contentBlockStart.contentBlockIndex??0),g.contentBlockDelta?.delta?.text){const y=g.contentBlockDelta.contentBlockIndex??0,w=g.contentBlockDelta.delta.text;i(y),a+=w,s.set(y,(s.get(y)??"")+w),t.push({content:w})}if(g.contentBlockStart?.start?.toolUse){const y=i(g.contentBlockStart.contentBlockIndex??0);y.toolUse={name:g.contentBlockStart.start.toolUse.name??"",input:{},toolUseId:g.contentBlockStart.start.toolUse.toolUseId??X4()}}if(g.contentBlockDelta?.delta?.toolUse){const y=i(g.contentBlockDelta.contentBlockIndex??0);y.toolUse??={name:"",input:{},toolUseId:X4()};const w=g.contentBlockDelta.delta.toolUse.input;typeof w=="string"?y._inputBuffer=(y._inputBuffer??"")+w:typeof w=="object"&&w!==null&&!Array.isArray(w)&&(y.toolUse.input={...y.toolUse.input??{},...w})}if(g.contentBlockStop){const y=g.contentBlockStop.contentBlockIndex??0;Qwt(o.get(y),s.get(y)??"")}if(g.messageStop){c=g.messageStop.stopReason??"end_turn";continue}if(g.metadata?.usage){l+=g.metadata.usage.inputTokens??0,u+=g.metadata.usage.outputTokens??0,d+=g.metadata.usage.cacheReadInputTokens??0,m+=g.metadata.usage.cacheWriteInputTokens??0;break}}for(const[f,g]of o)Qwt(g,s.get(f)??"");const h=n.filter(f=>f.text||f.toolUse||f.image||f.document);return{text:a,toolCalls:eTt(h),usage:{inputTokens:l,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:m},rawStopReason:c,raw:h}}function P1r(e){const t=[];let r="";for(const n of e.output?.message?.content??[]){const o={};"text"in n&&n.text&&(o.text=n.text,r+=r?` ${n.text}`:n.text),"toolUse"in n&&n.toolUse&&(o.toolUse={toolUseId:n.toolUse.toolUseId??X4(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:eTt(t),usage:{inputTokens:e.usage?.inputTokens??0,outputTokens:e.usage?.outputTokens??0,cacheReadTokens:e.usage?.cacheReadInputTokens??0,cacheWriteTokens:e.usage?.cacheWriteInputTokens??0},rawStopReason:e.stopReason,raw:t}}function tTt(e){return{providerLabel:"bedrock",maxSteps:e.maxSteps,buildStepRequest(t,r){return{raw:e.buildCommandInput(t,r)}},async executeStep(t,r,n){const o=t.raw;if(!e.streaming){const i=await Zwt(o.modelId??"",e.region,a=>Be(e.client.send(new Hwt({...o,modelId:a}),{abortSignal:n}),QK,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return P1r(i)}const s=await Zwt(o.modelId??"",e.region,i=>Be(e.client.send(new Vwt({...o,modelId:i}),{abortSignal:n}),QK,new Error("Bedrock streaming API call timed out")));return M1r(s,r,n)},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw},s={role:"user",content:n.map(i=>({toolResult:{toolUseId:i.id,content:[{text:i.error?`Error executing tool ${i.name}: ${i.error}`:String(typeof i.output=="string"?i.output:JSON.stringify(i.output))}],status:i.error?"error":"success"}}))};return[...t,o,s]},mapFinishReason(t,r){switch(t){case"end_turn":case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return r?"tool-calls":"stop"}}}}var QK,D1r=S({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";Kwt(),tt(),R1r(),QK=12e4}});function rTt(e,t,r){return{input:{text:e.input?.text||"",images:e.input?.images,content:e.input?.content,files:e.input?.files,csvFiles:e.input?.csvFiles,pdfFiles:e.input?.pdfFiles,audioFiles:e.input?.audioFiles,videoFiles:e.input?.videoFiles},csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,systemPrompt:e.systemPrompt,conversationHistory:e.conversationMessages,provider:t,model:r,temperature:e.temperature,maxTokens:e.maxTokens,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,fileRegistry:e.fileRegistry}}var O1r=S({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),Q4,nTt=S({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";Ua(),Q4=Le.provider}}),oTt={};ne(oTt,{Agent:()=>WTt,BedrockClient:()=>iTt,BedrockRuntimeClient:()=>cTt,Blob:()=>VTt,Client:()=>JTt,ConverseCommand:()=>lTt,ConverseStreamCommand:()=>uTt,Cron:()=>xTt,Dispatcher:()=>YTt,File:()=>HTt,FlowProducer:()=>ATt,FormData:()=>jTt,GoogleAuth:()=>gTt,HTTPException:()=>NTt,Headers:()=>qTt,Hippocampus:()=>TTt,HippocampusConfig:()=>ETt,Hono:()=>DTt,ImageFormat:()=>dTt,InvokeEndpointCommand:()=>hTt,InvokeEndpointWithResponseStreamCommand:()=>fTt,InvokeModelCommand:()=>mTt,Job:()=>CTt,ListFoundationModelsCommand:()=>aTt,MockAgent:()=>QTt,Pool:()=>KTt,Queue:()=>_Tt,QueueScheduler:()=>kTt,Request:()=>zTt,Response:()=>GTt,SageMakerRuntimeClient:()=>pTt,TextToSpeechClient:()=>vTt,VertexAI:()=>yTt,Webhook:()=>wTt,Worker:()=>bTt,convertToHtml:()=>PTt,cors:()=>OTt,createClient:()=>STt,default:()=>sTt,extractRawText:()=>MTt,fetch:()=>BTt,getGlobalDispatcher:()=>XTt,interceptors:()=>eEt,logger:()=>LTt,parseBuffer:()=>ITt,request:()=>tEt,secureHeaders:()=>FTt,selectCover:()=>RTt,setGlobalDispatcher:()=>ZTt,streamSSE:()=>$Tt,timeout:()=>UTt});var yf,os,sTt,iTt,aTt,cTt,lTt,uTt,dTt,mTt,pTt,hTt,fTt,gTt,yTt,vTt,wTt,TTt,ETt,STt,_Tt,bTt,CTt,kTt,ATt,xTt,ITt,RTt,MTt,PTt,DTt,OTt,NTt,LTt,FTt,$Tt,UTt,BTt,zTt,GTt,qTt,jTt,HTt,VTt,WTt,KTt,JTt,YTt,ZTt,XTt,QTt,eEt,tEt,N1r=S({"npm-stub:@aws-sdk/client-bedrock"(){yf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:yf.get}):new Proxy(function(...r){return new Proxy({},{get:yf.get})},{get:yf.get,apply(r,n,o){return new Proxy({},{get:yf.get})},construct(r,n){return new Proxy({},{get:yf.get})}})}},os=new Proxy({},yf),sTt=os,{BedrockClient:iTt,ListFoundationModelsCommand:aTt,BedrockRuntimeClient:cTt,ConverseCommand:lTt,ConverseStreamCommand:uTt,ImageFormat:dTt,InvokeModelCommand:mTt}=os,{SageMakerRuntimeClient:pTt,InvokeEndpointCommand:hTt,InvokeEndpointWithResponseStreamCommand:fTt}=os,{GoogleAuth:gTt,VertexAI:yTt,TextToSpeechClient:vTt}=os,{Webhook:wTt}=os,{Hippocampus:TTt,HippocampusConfig:ETt}=os,{createClient:STt}=os,{Queue:_Tt,Worker:bTt,Job:CTt,QueueScheduler:kTt,FlowProducer:ATt}=os,{Cron:xTt}=os,{parseBuffer:ITt,selectCover:RTt}=os,{extractRawText:MTt,convertToHtml:PTt}=os,{Hono:DTt}=os,{cors:OTt,HTTPException:NTt,logger:LTt,secureHeaders:FTt,streamSSE:$Tt,timeout:UTt}=os,BTt=globalThis.fetch,zTt=globalThis.Request,GTt=globalThis.Response,qTt=globalThis.Headers,jTt=globalThis.FormData,HTt=globalThis.File,VTt=globalThis.Blob,WTt=os.Agent,KTt=os.Pool,JTt=os.Client,YTt=os.Dispatcher,ZTt=()=>{},XTt=()=>os,QTt=os.MockAgent,eEt={redirect:()=>e=>e,retry:()=>e=>e},tEt=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}});async function eJ(){return await Promise.resolve().then(()=>(N1r(),oTt))}var rEt=S({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}}),nEt,L1r=S({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";Kwt(),hr(),OS(),Sc(),Lo(),CP(),D1r(),ut(),Qs(),tt(),B(),hh(),BM(),O1r(),ti(),Kt(),nTt(),rEt(),nEt=class crr extends ja{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(t){return t?t.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(t,r,n,o){super(t,"bedrock",r);const s=t||process.env.BEDROCK_MODEL||this.modelName,i=crr.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",p.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),p.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{p.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new jwt({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),p.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw p.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){const{BedrockClient:t,ListFoundationModelsCommand:r}=await eJ(),n=new t({region:this.region});try{p.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");const o=new r({}),s=Date.now();await n.send(o);const i=Date.now()-s;p.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){const s=o instanceof Error?o.message:String(o);p.error("[AmazonBedrockProvider] Health check FAILED - this will cause production failures:",{error:s,errorType:o instanceof Error?o.constructor.name:"Unknown",region:process.env.AWS_REGION||"us-east-1",hasAccessKey:!!process.env.AWS_ACCESS_KEY_ID,hasSecretKey:!!process.env.AWS_SECRET_ACCESS_KEY})}finally{try{n.destroy()}catch{}}}getAISDKModel(){throw new Error("AmazonBedrockProvider does not use AI SDK models")}getProviderName(){return"bedrock"}getDefaultModel(){return process.env.BEDROCK_MODEL||"anthropic.claude-sonnet-4-6"}getDefaultEmbeddingModel(){return process.env.BEDROCK_EMBEDDING_MODEL||process.env.AWS_EMBEDDING_MODEL||"amazon.titan-embed-text-v2:0"}async generate(t){p.debug("[AmazonBedrockProvider] generate() called with conversation management");const r=Date.now(),n=typeof t=="string"?{prompt:t}:t;this.conversationHistory=[];const o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){p.debug("[AmazonBedrockProvider] Detected multimodal input in generate(), using multimodal message builder",{hasImages:!!o?.images?.length,imageCount:o?.images?.length||0,hasContent:!!o?.content?.length,contentCount:o?.content?.length||0,hasFiles:!!o?.files?.length,fileCount:o?.files?.length||0,hasCSVFiles:!!o?.csvFiles?.length,csvFileCount:o?.csvFiles?.length||0,hasPDFFiles:!!o?.pdfFiles?.length,pdfFileCount:o?.pdfFiles?.length||0});const m=rTt(n,this.providerName,this.modelName),h=await FM(m,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(h)}else{p.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const d={role:"user",content:[{text:n.prompt}]};this.conversationHistory.push(d)}p.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let i,a,c,l;try{({text:i,usage:a,finishReason:c,rawFinishReason:l}=await this.conversationLoop(n))}catch(d){const m=this.neurolink?.getEventEmitter();throw m&&m.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:"error"},success:!1,error:d instanceof Error?d.message:String(d)}),d}const u=this.neurolink?.getEventEmitter();return u&&u.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:c},success:!0}),{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),...c!==void 0&&{finishReason:c},...l!==void 0&&{rawFinishReason:l}}}async conversationLoop(t){const r=t.maxSteps||Ds,n=await this.resolveTurnTools(t.tools,t.disableTools),o=this.formatToolsForBedrock(n),s=Ql(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converse"),i=tTt({client:this.bedrockClient,streaming:!1,region:this.region,maxSteps:r,buildCommandInput:a=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(a),system:[{text:t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:t.maxTokens,...s.temperature!==void 0&&{temperature:s.temperature}},...o?{toolConfig:o}:{}})});try{const{resultPromise:a}=dd(i,this.conversationHistory,{tools:this.toEngineTools(n),abortSignal:t.abortSignal,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}}),c=await a;this.conversationHistory=c.conversation;const l=c.usage.inputTokens,u=c.usage.outputTokens,d=c.usage.cacheReadTokens??0,m=c.usage.cacheWriteTokens??0;return{text:c.text||"",usage:{input:l,output:u,total:l+d+m+u,...d>0&&{cacheReadTokens:d},...m>0&&{cacheCreationTokens:m}},finishReason:c.finishReason,rawFinishReason:c.rawStopReason}}catch(a){throw p.error("[AmazonBedrockProvider] Error in conversation loop:",a),this.handleProviderError(a)}}convertToAWSMessages(t){return t.map(r=>({role:r.role,content:r.content.map(n=>n.text?{text:n.text}:n.image?{image:n.image}:n.document?{document:n.document}:n.toolUse?{toolUse:{toolUseId:n.toolUse.toolUseId,name:n.toolUse.name,input:n.toolUse.input}}:n.toolResult?{toolResult:{toolUseId:n.toolResult.toolUseId,content:n.toolResult.content,status:n.toolResult.status}}:{text:""})}))}async executeSingleTool(t,r,n,o){return Q4.startActiveSpan("bedrock.tool.execute",{kind:Fr.CLIENT,attributes:{"gen_ai.tool.name":r,"gen_ai.system":"aws.bedrock"}},async s=>{try{if(p.debug(`[AmazonBedrockProvider] Executing single tool: ${r}`,{args:n}),!t[r])throw new Error(`Tool not found: ${r}`);const i=t[r];if(!i||!i.execute)throw new Error(`Tool ${r} does not have execute method`);const a=n||{};r==="list_directory"&&!a.path&&(a.path=".",p.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),p.debug("[AmazonBedrockProvider] Tool input parameters:",a);const c={};for(const[d,m]of Object.entries(a))(m===null||typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="object"&&m!==null)&&(c[d]=m);const l=await i.execute(c);p.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:r,result:l});let u;if(l&&typeof l=="object"&&"success"in l)if(l.success&&l.data!==void 0)typeof l.data=="string"?u=l.data:typeof l.data=="object"?u=JSON.stringify(l.data,null,2):u=String(l.data);else if(l.error){const d=typeof l.error=="string"?l.error:l.error.message||"Tool execution failed";throw new Error(d)}else u="";else typeof l=="string"?u=l:typeof l=="object"?u=JSON.stringify(l,null,2):u=String(l);return s.setStatus({code:Ne.OK}),u}catch(i){throw p.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:i}),s.setStatus({code:Ne.ERROR,message:i.message}),s.recordException(i),i}finally{s.end()}})}async resolveTurnTools(t,r){if(r)return{};const n=t??await this.getAllTools();return this.convertAISDKToolsToToolDefinitions(n)}toEngineTools(t){const r={};for(const n of Object.keys(t))r[n]={execute:o=>this.executeSingleTool(t,n,o)};return r}convertAISDKToolsToToolDefinitions(t){const r={};for(const[n,o]of Object.entries(t))if("description"in o&&o.description){const i=o.parameters??o.inputSchema;r[n]={description:o.description,parameters:i,execute:async a=>{if("execute"in o&&o.execute)return{success:!0,data:await o.execute(a,{toolCallId:`tool_${Date.now()}`,messages:[]})};throw new Error(`Tool ${n} has no execute method`)}}}return r}formatToolsForBedrock(t){if(!t||Object.keys(t).length===0)return null;const r=Object.entries(t).map(([n,o])=>{let s;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?s=Mo(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 p.debug(`[AmazonBedrockProvider] Formatted ${r.length} tools for Bedrock`),{tools:r}}convertToBedrockMessages(t){return t.map(r=>{const n={role:r.role==="system"?"user":r.role,content:[]};return typeof r.content=="string"?n.content.push({text:r.content}):r.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){const s=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image;let i=o.mimeType?.split("/")[1]||"png";i==="jpg"&&(i="jpeg"),n.content.push({image:{format:i==="jpeg"?Lb.JPEG:i==="png"?Lb.PNG:i==="gif"?Lb.GIF:Lb.WEBP,source:{bytes:s}}})}else if(o.type==="document"||o.type==="pdf"||o.type==="file"&&o.mimeType?.toLowerCase().startsWith("application/pdf")){let s;if(typeof o.data=="string"){const a=o.data.replace(/^data:application\/pdf;base64,/i,"");s=Buffer.from(a,"base64")}else s=o.data;let i=typeof o.name=="string"&&o.name?gm.basename(o.name):"document-pdf";i=i.replace(/\.[^.]+$/,""),i=i.replace(/[^a-zA-Z0-9\s\-()[\]]/g,"-"),i=i.replace(/-+/g,"-").trim().replace(/^-+|-+$/g,""),i=i||"document",n.content.push({document:{format:"pdf",name:i,source:{bytes:s}}})}}),n})}getBedrockClient(){return this.bedrockClient}async executeStream(t){return p.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),p.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),Q4.startActiveSpan("bedrock.stream",{kind:Fr.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async r=>{try{if(p.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(t.input?.images?.length||t.input?.content?.length||t.input?.files?.length||t.input?.csvFiles?.length||t.input?.pdfFiles?.length)){p.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!t.input?.images?.length,imageCount:t.input?.images?.length||0,hasContent:!!t.input?.content?.length,contentCount:t.input?.content?.length||0,hasFiles:!!t.input?.files?.length,fileCount:t.input?.files?.length||0,hasCSVFiles:!!t.input?.csvFiles?.length,csvFileCount:t.input?.csvFiles?.length||0,hasPDFFiles:!!t.input?.pdfFiles?.length,pdfFileCount:t.input?.pdfFiles?.length||0});const s=rTt(t,this.providerName,this.modelName),i=await FM(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{p.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");const s={role:"user",content:[{text:t.input.text}]};this.conversationHistory.push(s)}p.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),p.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");const o=await this.streamingConversationLoop(t,r);return p.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),r.setStatus({code:Ne.OK}),r.end(),o}catch(n){p.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");const o=n,s=o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream");if(p.debug("[TRACE] executeStream CATCH - checking if permission error"),p.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){p.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),p.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),r.addEvent("stream.fallback_to_generate",{reason:o.message});const i=await this.generate({prompt:t.input.text,input:t.input,maxTokens:t.maxTokens,temperature:t.temperature,systemPrompt:t.systemPrompt});if(!i)throw r.setStatus({code:Ne.ERROR,message:"Generate method returned null result"}),r.end(),new Error("Generate method returned null result");r.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),r.setStatus({code:Ne.OK}),r.end();const a=new ReadableStream({start(l){const d=(i.content||"").split(/(\s+)/);let m="";for(let h=0;h<d.length;h++)m+=d[h],(h===d.length-1||m.length>50||/[.!?;,]\s*$/.test(m))&&m.length>0&&(l.enqueue({content:m}),m="");m.length>0&&l.enqueue({content:m}),l.close()}});return{stream:{async*[Symbol.asyncIterator](){const l=a.getReader();try{for(;;){const{done:u,value:d}=await l.read();if(u)break;yield d}}finally{l.releaseLock()}}},usage:i.usage,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw r.setStatus({code:Ne.ERROR,message:o instanceof Error?o.message:String(o)}),r.recordException(o instanceof Error?o:new Error(String(o))),r.end(),n}})}async streamingConversationLoop(t,r){const n=Date.now(),o=t.maxSteps||Ds,s=await this.resolveTurnTools(t.tools,t.disableTools),i=this.formatToolsForBedrock(s),a=Ql(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converseStream"),c=tTt({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:R=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(R),system:[{text:t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:t.maxTokens,...a.temperature!==void 0&&{temperature:a.temperature}},...i?{toolConfig:i}:{}})});let l=!1,u;const d=new Promise(R=>{u=()=>{l=!0,R()}}),m={...c,executeStep:async(R,I,x)=>{const M=await c.executeStep(R,I,x);return u(),M}};r.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});const{stream:h,resultPromise:f}=dd(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:t.abortSignal,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}}),g=f.then(R=>({result:R,error:void 0}),R=>({result:void 0,error:R}));if(await Promise.race([d,g]),!l){const R=await g;if(R.error)throw R.error}const y=this.neurolink?.getEventEmitter(),w=this,E={startTime:n,streamId:`bedrock-${Date.now()}`};let _;const b=new Promise(R=>{_=R}),A=R=>{const I=R?.inputTokens??0,x=R?.outputTokens??0,M=R?.cacheReadTokens??0,N=R?.cacheWriteTokens??0;return{input:I,output:x,total:I+M+N+x,...M>0&&{cacheReadTokens:M},...N>0&&{cacheCreationTokens:N}}};return g.then(R=>{_(Ly(this.providerName,this.modelName||this.getDefaultModel(),{usage:A(R.result?.usage)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let R=!1;try{yield*h}catch(I){throw R=!0,I}finally{const I=await g;I.error&&(R=!0);const x=A(I.result?.usage);I.result&&(w.conversationHistory=I.result.conversation,E.finishReason=I.result.finishReason,E.rawFinishReason=I.result.rawStopReason,r.setAttribute("gen_ai.response.stop_reason",I.result.rawStopReason??"unknown")),y&&y.emit("generation:end",{provider:w.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:x,model:w.modelName||w.getDefaultModel(),provider:w.providerName,finishReason:R?"error":I.result?.rawStopReason},success:!R})}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:b,metadata:E}}async checkBedrockHealth(){const t=new AbortController,r=setTimeout(()=>t.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await eJ(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{p.debug("[AmazonBedrockProvider] Starting health check...");const i=new o({}),c=(await s.send(i,{abortSignal:t.signal})).modelSummaries||[],l=c.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(p.debug(`[AmazonBedrockProvider] Health check passed - Found ${l.length} active models out of ${c.length} total models`),l.length===0)throw new Error("No active foundation models available in the region")}catch(i){clearTimeout(r);const a=i;if(or(i))throw new Error("Bedrock health check timed out after 10 seconds",{cause:i});const c=typeof a.message=="string"?a.message:"";throw c.includes("UnauthorizedOperation")||c.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}):(p.error("[AmazonBedrockProvider] Health check failed:",i),new Error(`Bedrock health check failed: ${c||"Unknown error"}`,{cause:i}))}finally{clearTimeout(r);try{s.destroy()}catch{}}}formatProviderError(t){return gi(t,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:_r,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:ms,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:dt,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:dt,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(t,r){const n=r||"amazon.titan-embed-text-v2:0";p.debug("Generating embedding",{provider:this.providerName,model:n,textLength:t.length});try{const o=JSON.stringify({inputText:t}),s=new Wwt({modelId:n,contentType:"application/json",accept:"application/json",body:o}),i=await Be(this.bedrockClient.send(s),6e4,new Error("Bedrock embedding API call timed out")),a=JSON.parse(new TextDecoder().decode(i.body));if(!a.embedding||!Array.isArray(a.embedding))throw new Error("Invalid embedding response from Bedrock");return p.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.embedding.length}),a.embedding}catch(o){throw p.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:t.length}),this.handleProviderError(o)}}async embedMany(t,r){const n=r||"amazon.titan-embed-text-v2:0";p.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:t.length});try{const o=await Promise.all(t.map(s=>this.embed(s,n)));return p.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw p.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:t.length}),this.handleProviderError(o)}}}}}),oEt={};ne(oEt,{AmazonBedrockProvider:()=>nEt,bedrockTracer:()=>Q4,loadBedrockControl:()=>eJ});var F1r=S({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";L1r(),nTt(),rEt()}}),sEt={};ne(sEt,{AzureOpenAIProvider:()=>iEt});var iEt,$1r=S({"src/lib/providers/azureOpenai.ts"(){"use strict";ut(),B(),Qs(),Vo(),nl(),Va(),Vm(),iEt=class extends fa{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,r,n){const o=n?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",s=process.env.AZURE_OPENAI_ENDPOINT||"";let i;if(s)try{i=new URL(s.includes("://")?s:`https://${s}`)}catch{i=void 0}const a=i?.hostname??"",c=i?.pathname&&i.pathname!=="/"?i.pathname.replace(/\/+$/,""):"",l=/\.(openai|cognitiveservices)\.azure\.com$/.test(a);let u;l?u="/openai":u=/\/openai(?:\/v\d+)?$/.test(c)?c:`${c}/openai`;const d=i?.origin??"",m=n?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",h=n?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",f=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,g=n?.useMaxCompletionTokens??(f===void 0?void 0:/^(1|true|yes)$/i.test(f));o||yi(Ylr()),d||yi(Zlr()),super("azure",e,t,{baseURL:d,apiKey:o}),this.azureDeployment=m,this.azureApiVersion=h,this.azureResourceOrigin=d,this.azureDeploymentPathPrefix=u,this.useMaxCompletionTokensOverride=g,p.shouldLog("debug")&&p.debug("Azure OpenAI Provider initialized",k$e({deployment:this.azureDeployment,resourceOrigin:this.azureResourceOrigin,deploymentPathPrefix:this.azureDeploymentPathPrefix,apiVersion:this.azureApiVersion,provider:"azure"}))}suppressResponseFormatWithTools(){return!1}getProviderName(){return"azure"}getDefaultModel(){return this.azureDeployment}formatProviderError(e){const t=[{match:r=>/401/.test(r.message),errorClass:_r,message:"Invalid Azure OpenAI API key or endpoint."},...aa];return gi(e,t,this.providerName,this.modelName)}getChatCompletionsURL(e){const t=e||this.azureDeployment,r=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${r}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){const r=this.useMaxCompletionTokensOverride??hpt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function U1r(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70?"image/gif":"image/png"}var B1r=S({"src/lib/utils/imageDetection.ts"(){"use strict"}});function aEt(e){return e.map(t=>typeof t.content=="string"?{role:t.role,content:t.content}:{role:t.role,content:t.content.map(r=>r.type==="image"||r.type==="document"?{type:r.type,media_type:r.source.media_type,base64_chars:r.source.data.length}:r)})}var z1r=S({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),eD,G1r=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs"(){eD=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0}}}),q1r=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs"(){Kn()}});function tJ(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var tD,rJ,cEt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs"(){q1r(),tD=e=>(tD=Array.isArray,tD(e)),rJ=tD}});function*j1r(e){if(!e)return;if(nJ in e){const{values:n,nulls:o}=e;yield*n.entries();for(const s of o)yield[s,null];return}let t=!1,r;e instanceof Headers?r=e.entries():rJ(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){const o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");const s=rJ(n[1])?n[1]:[n[1]];let i=!1;for(const a of s)a!==void 0&&(t&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var nJ,lEt,H1r=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){cEt(),nJ=Symbol.for("brand.privateNullableHeaders"),lEt=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[s,i]of j1r(n)){const a=s.toLowerCase();o.has(a)||(t.delete(s),o.add(a)),i===null?(t.delete(s),r.add(a)):(t.append(s,i),r.delete(a))}}return{[nJ]:!0,values:t,nulls:r}}}});function V1r(e){const t=new Ab(e);return delete t.batches,t}function W1r(e){const t=new Hi(e);return delete t.messages.batches,t}var uEt,dEt,oJ,mEt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){G4(),hyt(),lP(),G1r(),cEt(),H1r(),G4(),uEt="vertex-2023-10-16",dEt=new Set(["/v1/messages","/v1/messages?beta=true"]),oJ=class extends vo{constructor({baseURL:e=eD("ANTHROPIC_VERTEX_BASE_URL"),region:t=eD("CLOUD_ML_REGION")??null,projectId:r=eD("ANTHROPIC_VERTEX_PROJECT_ID")??null,...n}={}){if(!t)throw new Error("No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.");if(!e)switch(t){case"global":e="https://aiplatform.googleapis.com/v1";break;case"us":e="https://aiplatform.us.rep.googleapis.com/v1";break;case"eu":e="https://aiplatform.eu.rep.googleapis.com/v1";break;default:e=`https://${t}-aiplatform.googleapis.com/v1`}if(super({baseURL:e,...n}),this.messages=V1r(this),this.beta=W1r(this),this.region=t,this.projectId=r,this.accessToken=n.accessToken??null,n.authClient&&n.googleAuth)throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");n.authClient?this._authClientPromise=Promise.resolve(n.authClient):(this._auth=n.googleAuth??new v9({scopes:"https://www.googleapis.com/auth/cloud-platform"}),this._authClientPromise=this._auth.getClient())}validateHeaders(){}async prepareOptions(e){const t=await this._authClientPromise,r=await t.getRequestHeaders(),n=t.projectId??r["x-goog-user-project"];!this.projectId&&n&&(this.projectId=n),e.headers=lEt([r,e.headers])}async buildRequest(e){if(tJ(e.body)&&(e.body={...e.body}),tJ(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=uEt)),dEt.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(!tJ(e.body))throw new Error("Expected request body to be an object for post /v1/messages");const t=e.body.model;e.body.model=void 0;const n=e.body.stream??!1?"streamRawPredict":"rawPredict";e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${t}:${n}`}if(e.path==="/v1/messages/count_tokens"||e.path=="/v1/messages/count_tokens?beta=true"&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`}return super.buildRequest(e)}}}}),sJ={};ne(sJ,{AnthropicVertex:()=>oJ,BaseAnthropic:()=>vo,default:()=>oJ});var pEt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){mEt(),mEt()}});async function K1r(){return rD||(rD=await Promise.resolve().then(()=>(pEt(),sJ))),rD}function J1r(e){const t=[],r=new Map;let n=0;const o=s=>{const i=`${n}:${s??"x"}`;let a=r.get(i);return a||(a={type:"tool_step",callParts:[],resultParts:[]},r.set(i,a),t.push(a)),a};for(const s of e){if(s.role==="tool_call"){o(s.metadata?.stepIndex).callParts.push({name:s.tool||"unknown",input:s.args||{}});continue}if(s.role==="tool_result"){o(s.metadata?.stepIndex).resultParts.push(s.content&&s.content.length>0?s.content:"(no output)");continue}const i=s.role==="assistant"?"assistant":s.role==="user"?"user":null;!i||!s.content||s.content.trim().length===0||(n++,t.push({type:"regular",role:i,parts:[s.content]}))}return t}function iJ(e,t,r){const n=e[e.length-1];n&&n.role===t&&Array.isArray(n.content)?n.content.push(...r):e.push({role:t,content:[...r]})}function Y1r(e,t){const r=e.callParts,n=e.resultParts,o=Math.min(r.length,n.length);(o!==r.length||o!==n.length)&&p.debug("[GoogleVertex] Unbalanced tool step in Claude history replay",{calls:r.length,results:n.length,paired:o});const s=[],i=[];for(let a=0;a<o;a++){const c=`hist_${t}_${a}`;s.push({type:"tool_use",id:c,name:r[a].name,input:r[a].input}),i.push({type:"tool_result",tool_use_id:c,content:n[a]})}return{uses:s,results:i}}function Z1r(e){const t=r=>Array.isArray(r.content)&&r.content.length>0&&r.content.every(n=>n.type==="tool_result");for(;e.length>0&&(e[0].role!=="user"||t(e[0]));)e.shift()}function aJ(e){const t=[];let r=0;for(const n of J1r(e)){if(n.type==="regular"){iJ(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:s}=Y1r(n,r);o.length!==0&&(r++,iJ(t,"assistant",o),iJ(t,"user",s))}if(Z1r(t),p.shouldLog("debug")){const n=t.flatMap(o=>Array.isArray(o.content)?o.content:[]);p.debug("[GoogleVertex] Replayed Claude history with tool turns",{historyMessages:t.length,toolUseBlocks:n.filter(o=>o.type==="tool_use").length,toolResultBlocks:n.filter(o=>o.type==="tool_result").length})}return t}function cJ(e,t){const r=e[e.length-1];if(r&&r.role==="user"){const n=Array.isArray(r.content)?r.content:[{type:"text",text:r.content}],o=Array.isArray(t)?t:[{type:"text",text:t}];r.content=[...n,...o];return}e.push({role:"user",content:t})}function vf(e){if(!e||typeof e!="object")return;const t=["additionalProperties","default","$schema","$id","$ref","definitions","$defs","examples","errorMessage"];for(const n of t)n in e&&delete e[n];typeof e.exclusiveMinimum=="boolean"&&(e.exclusiveMinimum===!0&&typeof e.minimum=="number"?(e.exclusiveMinimum=e.minimum,delete e.minimum):delete e.exclusiveMinimum),typeof e.exclusiveMaximum=="boolean"&&(e.exclusiveMaximum===!0&&typeof e.maximum=="number"?(e.exclusiveMaximum=e.maximum,delete e.maximum):delete e.exclusiveMaximum);const r=2147483647;if(typeof e.maximum=="number"&&e.maximum>r&&delete e.maximum,typeof e.minimum=="number"&&e.minimum<-r&&delete e.minimum,e.properties&&typeof e.properties=="object")for(const n of Object.values(e.properties))n&&typeof n=="object"&&vf(n);if(e.items&&typeof e.items=="object")if(Array.isArray(e.items))for(const n of e.items)n&&typeof n=="object"&&vf(n);else vf(e.items);for(const n of["allOf","anyOf","oneOf"])if(Array.isArray(e[n]))for(const o of e[n])o&&typeof o=="object"&&vf(o)}function hEt(e,t,r){const n=gmt({contents:e,availableInputTokens:nu("vertex",t),provider:"vertex",observedPromptTokens:r});if(!n)return!1;const o=new Set(n.drop),s=new Set(n.truncate),i=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const c=e[a];if(s.has(a)&&Array.isArray(c.parts)){i.push({...c,parts:c.parts.map(l=>{if(!("functionResponse"in l))return l;const u=l.functionResponse,d=JSON.stringify(u.response)??"";return d.length<=TEt?l:{functionResponse:{name:u.name,response:{result:D9(d)}}}})});continue}i.push(c)}if(o.size>0){let a=i.findIndex(c=>Array.isArray(c.parts)&&c.parts.some(l=>!!l.functionCall||!!l.functionResponse));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",parts:[{text:N9}]})}return e.length=0,e.push(...i),!0}function fEt(e,t,r){const n=bwt({conversation:e,availableInputTokens:nu("vertex",t),fixedOverheadTokens:0,provider:"vertex",observedPromptTokens:r,observedDescribesCurrentPayload:!0});if(!n)return!1;const o=new Set(n.drop),s=new Set(n.truncate),i=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const c=e[a];if(s.has(a)&&Array.isArray(c.content)){i.push({...c,content:c.content.map(l=>{if(l.type!=="tool_result")return l;const u=typeof l.content=="string"?l.content:JSON.stringify(l.content)??"";return{...l,content:_wt(u)}})});continue}i.push(c)}if(o.size>0){let a=i.findIndex(c=>Array.isArray(c.content)&&c.content.some(l=>l.type==="tool_use"||l.type==="tool_result"));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",content:[{type:"text",text:BK}]})}return e.length=0,e.push(...i),!0}async function gEt(e,t,r={}){const n=[],o=[];let s,i=0,a=0,c=0,l=0;for await(const u of e){r.onProgress?.();const d=u,h=d.candidates?.[0],f=h?.finishReason;typeof f=="string"&&f&&(s=f);const g=h?.content;if(g&&Array.isArray(g.parts))for(const w of g.parts)n.push(w),typeof w.text=="string"&&w.text.length>0&&t.push({content:w.text});u.functionCalls&&o.push(...u.functionCalls);const y=d.usageMetadata;if(y){if(y.promptTokenCount!==void 0&&y.promptTokenCount>0){r.onUsageDelta?.("input",y.promptTokenCount-i),i=y.promptTokenCount,r.onUsage?.(y.promptTokenCount,y.candidatesTokenCount??0);const w=Math.min(y.cachedContentTokenCount??0,y.promptTokenCount);r.onUsageDelta?.("cacheRead",w-c),c=w}y.candidatesTokenCount!==void 0&&y.candidatesTokenCount>0&&(r.onUsageDelta?.("output",y.candidatesTokenCount-a),a=y.candidatesTokenCount),y.thoughtsTokenCount!==void 0&&y.thoughtsTokenCount>0&&(r.onUsageDelta?.("reasoning",y.thoughtsTokenCount-l),l=y.thoughtsTokenCount)}}return{rawResponseParts:n,stepFunctionCalls:o,...s?{finishReason:s}:{},inputTokens:i,outputTokens:a,...c?{cacheReadTokens:c}:{},...l?{reasoningTokens:l}:{}}}var rD,yEt,lJ,Fb,uJ,V0,wf,vEt,wEt,nD,TEt,dJ,X1r=S({"src/lib/providers/googleVertex/client.ts"(){"use strict";Cn(),fP(),hr(),Sc(),Wj(),_P(),tYe(),Lo(),fh(),vh(),R9(),Qt(),Wn(),ut(),Qs(),tt(),Iwt(),Mct(),BM(),B(),_9(),vmt(),Cwt(),d9(),B1r(),m9(),Vo(),ti(),tmt(),Wh(),ia(),wmt(),umt(),CP(),Nwt(),I_(),g0(),F9(),nd(),zS(),Ua(),Kt(),tl(),nl(),Eh(),hh(),z1r(),I_(),rD=null,yEt=()=>!0,lJ=()=>yi(iur()),Fb=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",uJ=(e,t)=>{const r=t||Fb();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||Vq.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},V0=uJ,wf=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",vEt=()=>!!(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),wEt=async(e,t,r,n)=>{const o=e||Fb();return{projectId:r?r.projectId?.trim()||"express":lJ(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},nD=e=>e.toLowerCase().includes("claude"),TEt=2048,dJ=class Wr extends ja{projectId;location;expressApiKey;baseURL;registeredTools=new Map;toolContext={};static modelConfigCache=new Map;static modelConfigCacheTime=0;static CACHE_DURATION=300*1e3;static MAX_CACHE_SIZE=50;static maxTokensCache=new Map;static maxTokensCacheTime=0;constructor(t,r,n,o,s){super(t,"vertex",n),s&&(s.projectId&&(process.env.GOOGLE_CLOUD_PROJECT=String(s.projectId)),s.location&&(process.env.GOOGLE_CLOUD_LOCATION=String(s.location)),s.apiKey&&(process.env.GOOGLE_API_KEY=String(s.apiKey),!s.projectId&&!s.location&&(this.expressApiKey=String(s.apiKey))),s.baseURL&&(this.baseURL=String(s.baseURL)));const i=!!this.resolveExpressApiKey();i||vEt()||yi(aur()),this.projectId=s?.projectId||(i?"":lJ()),this.location=o||s?.location||Fb(),p.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),p.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return wf()}async getAISDKModel(){throw new be({code:ze.INVALID_CONFIGURATION,message:"GoogleVertexProvider no longer uses @ai-sdk/google-vertex. All models use native SDKs: @google/genai for Gemini, @anthropic-ai/vertex-sdk for Claude.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}validateStreamOptionsOnly(t){this.validateStreamOptions(t)}async preprocessNativeFileInput(t){if(t.input&&S7(t.input),t.input?.files?.length)try{await _7(t,100*1024*1024,this.providerName)}catch(r){p.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${r instanceof Error?r.message:String(r)}`)}await b_(t.input)}async executeStream(t,r){const n=t.model||this.modelName||wf();return FPe({name:"neurolink.provider.stream",tracer:Le.provider,attributes:{[we.GEN_AI_SYSTEM]:this.providerName,[we.GEN_AI_MODEL]:n,[we.GEN_AI_OPERATION]:"stream",[we.NL_PROVIDER]:this.providerName}},async o=>{const s=Date.now(),i=t.tools||{};await this.preprocessNativeFileInput(t);const c={...await ct({name:"neurolink.message.build",tracer:Le.provider,attributes:{[we.NL_PROVIDER]:this.providerName,"message.count":1,"message.build.count":1,"message.build.path":"vertex.native.stream"}},async()=>this.processCSVFilesForNativeSDK(t)),tools:i};try{let l;nD(n)?(p.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(i).length}),l=await this.executeNativeAnthropicStream(c)):(p.info("[GoogleVertex] Routing Gemini model to native @google/genai",{model:n,totalToolCount:Object.keys(i).length}),l=await this.executeNativeGemini3Stream(c)),this.attachUsageAndCostAttributes(o,n,l?.usage);const u=this.wrapStreamResultWithLifecycle(t,l,s);return this.emitStreamEnd(n,s,!0,void 0,l.finishReason),u}catch(l){throw this.fireGenerateOnError(t,l,s),this.emitStreamEnd(n,s,!1,l),l}},o=>o.stream,(o,s)=>this.preserveStreamResultAccessors(o,{...o,stream:s}))}emitStreamEnd(t,r,n,o,s){const i=this.neurolink?.getEventEmitter();i&&i.emit("stream:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:t,provider:this.providerName,finishReason:n?s??"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async createVertexGenAIClient(t){kmt("GoogleVertex");const r=this.resolveExpressApiKey(),n=r?"":this.projectId,o=t||this.location||Fb(),i=(await Promise.resolve().then(()=>(WE(),Ey))).GoogleGenAI;if(!i)throw new be({code:ze.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const a=i,c=this.resolveBaseURL(),l={...c?{baseUrl:c}:{}};return r?new a({vertexai:!0,apiKey:r,httpOptions:l}):new a({vertexai:!0,project:n,location:o,httpOptions:l})}resolveBaseURL(){const t=this.baseURL?.trim()||process.env.GOOGLE_VERTEX_BASE_URL?.trim();return t&&t.length>0?t:void 0}resolveExpressApiKey(){const t=this.expressApiKey?.trim();if(t)return t;const r=process.env.GOOGLE_VERTEX_API_KEY?.trim();return r?["GOOGLE_CLOUD_PROJECT_ID","VERTEX_PROJECT_ID","GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT"].some(o=>(process.env[o]??"").trim().length>0)?void 0:r:void 0}buildAnthropicToolDeclaration(t,r){const n={name:t,description:r.description||`Tool: ${t}`,input_schema:{type:"object"}},s=r.parameters||r.inputSchema;if(s){const i=Mo(s),a=On(i);n.input_schema={type:"object",properties:a.properties||{},required:a.required||[]}}return n}refreshAnthropicToolDeclarations(t,r,n,o){if(!t||!r)return;const s=new Set(r.map(i=>i.name));for(const[i,a]of Object.entries(t))s.has(i)||(r.push(this.buildAnthropicToolDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),p.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Anthropic declarations.`))}resolveAnthropicToolOnMiss(t,r,n,o,s){if(!n)return;const i=cUe(r,t);if(i?.execute)return n.some(a=>a.name===t)||n.push(this.buildAnthropicToolDeclaration(t,i)),o.set(t,i.execute),s.delete(t),p.info(`[GoogleVertex] Tool "${t}" resolved mid-turn via discovery \u2014 executing.`),o.get(t)}buildFinalResultTool(t){const r=Mo(t),n=On(r);n.$schema&&delete n.$schema;const o=Fi(n);return{name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",input_schema:{type:"object",properties:o.properties||o,required:o.required||[]}}}async executeNativeGemini3Stream(t){const r=t.model||this.modelName||wf(),n=V0(r,t.region),o=await this.createVertexGenAIClient(n);p.debug("[GoogleVertex] Using native @google/genai for Gemini 3",{model:r,hasTools:!!t.tools&&Object.keys(t.tools).length>0,project:this.projectId,location:n});const s=[],i=[{text:t.input.text??""}],a=t.input;if(a?.pdfFiles&&a.pdfFiles.length>0){p.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(const ke of a.pdfFiles){let Ke;typeof ke=="string"?Ro.existsSync(ke)?Ke=Ro.readFileSync(ke):Ke=Buffer.from(ke,"base64"):Ke=ke;const oe=Ke.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:oe}})}}if(await k9(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){p.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(const ke of a.images){const Ke=s_(ke);let oe,Y="image/jpeg";if(typeof Ke=="string")if(Ro.existsSync(Ke)){oe=Ro.readFileSync(Ke);const K=u_(Ke);Y=K.startsWith("image/")?K:this.detectImageType(oe)}else if(Ke.startsWith("data:")){const K=Ke.match(/^data:([^;]+);base64,(.+)$/);if(K)Y=K[1],oe=Buffer.from(K[2],"base64");else continue}else if(Ke.startsWith("http://")||Ke.startsWith("https://"))try{const K=await fetch(Ke);if(!K.ok){p.warn(`[GoogleVertex] Image fetch failed: ${K.status} ${K.statusText}, skipping`,{url:Qr(Ke)});continue}const J=await K.arrayBuffer();oe=Buffer.from(J);const ie=K.headers.get("content-type");ie&&ie.startsWith("image/")&&(Y=ie.split(";")[0])}catch(K){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${K instanceof Error?K.message:String(K)}`,{url:Qr(Ke)});continue}else oe=Buffer.from(Ke,"base64"),Y=this.detectImageType(oe);else oe=Ke,Y=this.detectImageType(oe);const Q=oe.toString("base64");i.push({inlineData:{mimeType:Y,data:Q}})}}EP(s,t.conversationMessages),s.push({role:"user",parts:i});let c;const l=new h0;let u;if(t.tools&&Object.keys(t.tools).length>0&&!t.disableTools){const ke=y0(t.tools,"functionDeclarations");u=ke,c=ke.toolsConfig;for(const[Ke,oe]of ke.executeMap)l.set(Ke,oe);p.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ke.toolsConfig[0].functionDeclarations.length,toolNames:ke.toolsConfig[0].functionDeclarations.map(Ke=>Ke.name)})}const d=t;let m=!1;if(d.schema&&c){m=!0;const ke=Mo(d.schema,"openApi3"),Ke=On(ke);Ke.$schema&&delete Ke.$schema;const oe=Fi(Ke),Y=c[0]?.functionDeclarations||[];Y.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:oe}),c=[{functionDeclarations:Y}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(oe),totalTools:Y.length})}const h=Ql(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),f={...h.temperature!==void 0&&{temperature:h.temperature},maxOutputTokens:t.maxTokens};u9(r)&&(f.maxOutputTokens&&f.maxOutputTokens>ma&&(p.warn(`[GoogleVertex] Capping maxOutputTokens from ${f.maxOutputTokens} to ${ma} for ${r}`),f.maxOutputTokens=ma),f.maxOutputTokens||(f.maxOutputTokens=ma)),h.topP!==void 0&&(f.topP=h.topP),t.topK!==void 0&&(f.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(f.stopSequences=t.stopSequences),c&&(f.tools=c);let g=t.systemPrompt||"";m&&(g=g+`
1074
+ `);return{...s!==void 0?{system:s}:{},messages:r}},YK=e=>{if(!(!e||e==="auto")){if(e==="none")return{type:"none"};if(e==="required")return{type:"any"};if(typeof e=="object"){const t=e;if(t.type==="tool"&&t.toolName)return{type:"tool",name:t.toolName}}}},zwt=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},ZK=6e5,Gwt=class extends ja{client;authMethod;subscriptionTier;enableBetaFeatures;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,r,n){const o=!!(n?.apiKey&&!n?.oauthToken),s=o?null:(n?.oauthToken?{accessToken:n.oauthToken}:null)??r?.oauthToken??KK(),i=o?"api_key":r?.authMethod??Bwt(s),a=r?.subscriptionTier??(i==="oauth"?Uwt(s):"api"),c=e||H0();let l=c;!process.env.ANTHROPIC_BASE_URL&&a!=="api"&&!NK(c,a)&&(l=LK(a),p.warn("Model not available for subscription tier, using recommended model",{requestedModel:c,subscriptionTier:a,recommendedModel:l})),super(l,"anthropic",t),this.enableBetaFeatures=r?.enableBetaFeatures??!0,this.oauthToken=s,this.subscriptionTier=a,this.authMethod=i;const d=this.getAuthHeaders();let m;if(p.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){p.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");const h=this.oauthToken,f=hRr(()=>h.accessToken,this.enableBetaFeatures,!1,!0);m=new hf({apiKey:"oauth-authenticated",fetch:ywt(f),timeout:ZK,maxRetries:0}),p.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),p.debug("Anthropic Provider initialized with OAuth",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,hasRefreshToken:!!this.oauthToken.refreshToken,tokenExpiry:this.oauthToken.expiresAt?new Date(this.oauthToken.expiresAt).toISOString():"none"})}else{const h=n?.apiKey??r?.apiKey??WK(),f=(()=>{const g=process.env.ANTHROPIC_BASE_URL;if(!g)return;const y=g.replace(/\/+$/,""),w=y.replace(/\/v\d+$/,"");return w!==y&&p.debug("[AnthropicProvider] Stripping the version suffix from ANTHROPIC_BASE_URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:zn(g),rewrittenTo:zn(w)}),w})();m=new hf({apiKey:h,defaultHeaders:d,...f&&{baseURL:f},fetch:ywt(Mt()),timeout:ZK,maxRetries:0}),p.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.client=m,this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},p.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?Z4["anthropic-beta"]:"disabled"})}getAuthHeaders(){const e={},t=!!process.env.ANTHROPIC_BASE_URL;if(this.enableBetaFeatures)if(t){const r=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",n=[...Pb,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];r&&n.push("context-1m-2025-08-07"),e["anthropic-beta"]=n.join(",")}else e["anthropic-beta"]=Z4["anthropic-beta"];return t&&(e["User-Agent"]=ff),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return p.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;const t=NK(e,this.subscriptionTier);return t||p.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return FK(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){p.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){p.debug("Token has no expiry information, assuming valid");return}const e=Date.now(),t=this.oauthToken.expiresAt<=e,r=this.oauthToken.expiresAt<=e+cae;if(!t&&!r){p.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new _r("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);p.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}p.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});const n=this.oauthToken,o=n.refreshToken;this.refreshPromise=(async()=>{const i=new AbortController,a=setTimeout(()=>i.abort(),3e4),c=await fetch(Mb,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":ff},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:DK}),signal:i.signal});if(clearTimeout(a),!c.ok){const d=await c.text();throw new _r(`Failed to refresh OAuth token: ${c.status} ${d}`,this.providerName)}const l=await c.json();n.accessToken=l.access_token,n.refreshToken=l.refresh_token||n.refreshToken,n.expiresAt=l.expires_in?Date.now()+l.expires_in*1e3:void 0,n.tokenType=l.token_type||"Bearer";const u=n;try{const d=Ct(_i(),".neurolink");Ms(d)||O5(d,{recursive:!0});const m=Ct(d,"anthropic-credentials.json"),h=`${m}.tmp`,g={...Ms(m)?JSON.parse(Hu(m,"utf-8")):{},type:"oauth",oauth:u,updatedAt:Date.now()};iR(h,JSON.stringify(g,null,2),{mode:384}),L5(h,m),p.debug("Refreshed OAuth credentials persisted to disk")}catch(d){p.warn("Failed to persist refreshed OAuth token to disk",{error:d instanceof Error?d.message:String(d)})}p.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!l.refresh_token,expiresIn:l.expires_in})})();try{await this.refreshPromise}catch(s){throw s instanceof _r?s:new _r(`Failed to refresh OAuth token: ${s instanceof Error?s.message:String(s)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,r){this.lastResponseMetadata={rateLimit:e,...t?{requestId:t}:{}},this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),r&&(r.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=r.inputTokens,this.usageInfo.tokensUsed+=r.inputTokens),r.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=r.outputTokens,this.usageInfo.tokensUsed+=r.outputTokens)),e?.requestsRemaining!==void 0&&(this.usageInfo.messagesRemaining=e.requestsRemaining),e?.tokensRemaining!==void 0&&(this.usageInfo.tokensRemaining=e.tokensRemaining),e?.requestsLimit&&e.requestsLimit>0&&(this.usageInfo.messageQuotaPercent=Math.round((e.requestsLimit-(e.requestsRemaining??0))/e.requestsLimit*100)),e?.tokensLimit&&e.tokensLimit>0&&(this.usageInfo.tokenQuotaPercent=Math.round((e.tokensLimit-(e.tokensRemaining??0))/e.tokensLimit*100)),e?.retryAfter!==void 0?(this.usageInfo.isRateLimited=!0,this.usageInfo.rateLimitExpiresAt=Date.now()+e.retryAfter*1e3):(this.usageInfo.isRateLimited=!1,this.usageInfo.rateLimitExpiresAt=void 0)),e?.requestsRemaining!==void 0&&e.requestsRemaining<=5&&p.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&&p.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return H0()}getAISDKModel(){const e=this.client,t=this.providerName,r=this.modelName||H0(),n=i=>this.getTimeout(i??{}),o=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:r,supportedUrls:{},doGenerate:async i=>{await o();const a=JK(i.prompt),c=a.messages;let l=a.system,u=(i.tools??[]).filter(F=>F.type==="function").map(F=>{const z=md(F);return{name:F.name,...F.description?{description:F.description}:{},input_schema:F.inputSchema??{type:"object",properties:{}},...z?{cache_control:z}:{}}});u&&u.length===0&&(u=void 0);let d=i.toolChoice?YK(i.toolChoice.type==="tool"?{type:"tool",toolName:i.toolChoice.toolName}:i.toolChoice.type):void 0,m;if(i.responseFormat?.type==="json"){m=i.responseFormat.name??"json";const F=i.responseFormat.schema??{type:"object"};u=[{name:m,description:i.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:F}],d={type:"tool",name:m}}const h=i.providerOptions?.anthropic?.finalResultSchema;let f=!1;if(!m&&h){const F=Mwt(u,h);u=F.tools,f=F.applied,F.applied&&(l=Pwt(l))}const g=i.providerOptions?.anthropic?.thinking;u=L9(u);const y=kwt({system:l,tools:u,messages:c}),w=Awt(c,V4-y),E=Ql("anthropic",r,{...i.temperature!==void 0&&i.temperature!==null?{temperature:i.temperature}:{},...i.topP!==void 0&&i.topP!==null?{topP:i.topP}:{}},"anthropic.doGenerate");g&&(E.temperature!==void 0||E.topP!==void 0)&&p.debug("[anthropic] extended thinking is enabled, so temperature/top_p are omitted \u2014 Anthropic rejects any temperature but 1 while thinking is set");const _={model:r,messages:w,max_tokens:iP(r,i.maxOutputTokens),...l?{system:l}:{},...!g&&E.temperature!==void 0?{temperature:E.temperature}:{},...!g&&E.topP!==void 0?{top_p:E.topP}:{},...i.stopSequences&&i.stopSequences.length>0?{stop_sequences:i.stopSequences}:{},...u?{tools:u}:{},...d?{tool_choice:d}:{},...g?{thinking:g}:{}},b=i.providerOptions?.neurolink,A=typeof b?.timeoutMs=="number"&&Number.isFinite(b.timeoutMs)&&b.timeoutMs>0?b.timeoutMs:void 0,k=A!==void 0?A:_.max_tokens>8192?Math.max(n(i),3e5):n(i),R=sa(k,t,"generate"),I=WI(i.abortSignal,R?.controller.signal);let x;try{x=await e.messages.create(_,{signal:I})}catch(F){const z=I?.aborted?I.reason:void 0;throw z instanceof Da?z:F}finally{R?.cleanup()}const M=[];let N;const U=[];let P=!1;for(const F of x.content)F.type==="thinking"?M.push({type:"reasoning",text:F.thinking,providerOptions:{anthropic:{signature:F.signature}}}):F.type==="redacted_thinking"?M.push({type:"reasoning",text:"",providerOptions:{anthropic:{redactedData:F.data}}}):F.type==="text"?m?U.push(F.text):M.push({type:"text",text:F.text}):F.type==="tool_use"&&(m&&F.name===m?(P=!0,M.push({type:"text",text:U_(F.input)})):f&&F.name===Nb?N=U_(F.input):M.push({type:"tool-call",toolCallId:F.id,toolName:F.name,input:U_(F.input)}));if(m&&!P&&U.length>0&&M.push({type:"text",text:U.join("")}),N!==void 0){const F=M.filter(z=>z.type==="reasoning");M.length=0,M.push(...F,{type:"text",text:N}),p.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:N.length})}const D=x.usage.cache_read_input_tokens??0,$=x.usage.cache_creation_input_tokens??0;return{content:M,finishReason:{unified:N!==void 0?"stop":zwt(x.stop_reason),raw:x.stop_reason??"stop"},usage:{inputTokens:{total:x.usage.input_tokens+D+$,noCache:x.usage.input_tokens,cacheRead:D,cacheWrite:$},outputTokens:{total:x.usage.output_tokens,text:x.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:_},response:{id:x.id,modelId:x.model,headers:ERr()??{},body:x}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model. NeuroLink streams through executeStream, reached via NeuroLink.stream() \u2014 use that (the browser bundle exports the NeuroLink class) rather than calling doStream on a model handle.`)}}}formatProviderError(e){return gi(e,[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(r.message),errorClass:_r,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:r=>r.statusCode===429||/rate limit|too_many_requests|429/i.test(r.message),errorClass:ms,message:"Anthropic rate limit exceeded. Please try again later."},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(r.message),errorClass:Xn,message:r=>`Connection error: ${r.message}`},{match:r=>/500|502|503|504|server error/i.test(r.message),errorClass:dt,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:dt,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await wRr(()=>this.dispatchGenerate(e,t));return r&&n&&(this.recordLimitSnapshot(n),r.limits=n,r.analytics&&(r.analytics.limits=n)),r}async dispatchGenerate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if(Zu(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),s=>this.executeNativeGenerate(s)),o)}async executeNativeGenerate(e){const t=Date.now(),r=this.modelName||H0(),n=await this.getAISDKModelWithMiddleware(e);if(!PP(n))throw this.handleProviderError(new Error("anthropic: model handle exposes no doGenerate()"));const o=n.doGenerate.bind(n),i=!e.disableTools&&this.supportsTools()?e.tools||{}:{},a=Object.entries(i).map(([E,_])=>{const b=_;return{type:"function",name:E,description:b.description??"",inputSchema:b.inputSchema?Mo(b.inputSchema):{type:"object",properties:{}}}}),c=a.length>0,l=e.schema?Mo(e.schema):void 0,u=l&&!c?{type:"json",schema:l}:void 0,d={};l&&c&&(d.finalResultSchema=l),e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens&&(d.thinking={type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens});const m={};Object.keys(d).length>0&&(m.anthropic=d),typeof e.timeout=="number"&&(m.neurolink={timeoutMs:e.timeout});const h=Object.keys(m).length>0?m:void 0,f=await this.buildMessagesForStream(e),g=[],y=await TV({doGenerate:o,conversation:f,...c?{tools:a}:{},toolsRecord:i,...c&&e.toolChoice?{toolChoice:NP(e,i,!0)}:{},...u?{responseFormat:u}:{},...h?{providerOptions:h}:{},maxSteps:e.maxSteps||Ds,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:E=>py(E,lt.getActiveSpan()??void 0,"anthropic generate").catch(_=>{throw this.handleProviderError(_)})},g),w={content:y.text,provider:this.providerName,model:r,finishReason:y.finishReason,...y.rawFinishReason?{rawFinishReason:y.rawFinishReason}:{},...y.reasoning?{reasoning:y.reasoning}:{},usage:{input:y.inputTokens,output:y.outputTokens,total:y.inputTokens+y.outputTokens,...y.cacheReadTokens?{cacheReadTokens:y.cacheReadTokens}:{},...y.cacheWriteTokens?{cacheCreationTokens:y.cacheWriteTokens}:{}},responseTime:Date.now()-t,toolsUsed:y.toolsUsed,toolCalls:A8(g),toolExecutions:Gy(e,Th(g)),enhancedWithTools:y.toolsUsed.length>0};return this.finalizeNativeGenerate(w,e,t)}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),_Rr(e),bRr(e,this.modelName)}supportsExecutionControl(){return!0}async executeStream(e,t){return SRr(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);const r=e.executionControl,n=typeof e.turnTimeoutMs=="number"&&Number.isFinite(e.turnTimeoutMs)&&e.turnTimeoutMs>0,o=r&&r.lifetimeTimeoutMs!==void 0?r.lifetimeTimeoutMs??void 0:n?e.turnTimeoutMs:this.getTimeout(e),s=sa(o,this.providerName,"stream"),i=new AbortController,a=Qpe([e.abortSignal,s?.controller.signal,i.signal]).signal;let c,l,u,d,m=!1;try{d=!e.disableTools&&this.supportsTools(),c=d?e.tools||await this.getAllTools():{},l=d?y0(c,"input_schema"):void 0;const ye=await this.buildMessagesForStream(e);if(u=JK(ye),e.schema&&l&&l.length>0){const Se=Mwt(l,Mo(e.schema));l=Se.tools,m=Se.applied,Se.applied&&(u.system=Pwt(u.system))}}catch(ye){throw s?.cleanup(),this.handleProviderError(ye)}const h=this.modelName||H0(),f=d&&l&&l.length>0?YK(NP(e,c,d)):void 0,g=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,y=$wt.startSpan("neurolink.provider.streamText",{kind:Fr.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":h}}),w=e.maxSteps||Ds,E=this.neurolink?.getEventEmitter(),_=f0(),{push:b}=_,{usagePromise:A,finishPromise:k,resolveUsage:R,resolveFinish:I}=mV();A.then(ye=>{y.setAttribute("gen_ai.usage.input_tokens",ye.promptTokens||0),y.setAttribute("gen_ai.usage.output_tokens",ye.completionTokens||0),ye.cacheReadTokens&&y.setAttribute("gen_ai.usage.cached_input_tokens",ye.cacheReadTokens);const Se=Ba(this.providerName,this.modelName,{input:ye.promptTokens||0,output:ye.completionTokens||0,total:ye.totalTokens||0,...ye.cacheReadTokens?{cacheReadTokens:ye.cacheReadTokens}:{},...ye.cacheCreationTokens?{cacheCreationTokens:ye.cacheCreationTokens}:{}});Se&&Se>0&&y.setAttribute("neurolink.cost",Se)}).catch(()=>{}),k.then(ye=>{y.setAttribute("gen_ai.response.finish_reason",ye||"unknown"),y.end()}).catch(()=>{y.end()});let x;const M=this.client,N=[],U=Date.now(),P={};let D=0,$=0,F=0,z=0,q=null;const j=()=>({promptTokens:D,completionTokens:$,totalTokens:D+F+z+$,...F>0?{cacheReadTokens:F}:{},...z>0?{cacheCreationTokens:z}:{}});let W="",H;const se=(ye,Se)=>{const xe=Te=>{if(typeof Te=="string")return Te;try{return JSON.stringify(Te)??""}catch{return""}};return gr(xe(ye),"anthropic")+gr(xe(Se),"anthropic")},ue=(async()=>{let ye,Se;const Fe=GK({client:M,maxSteps:w,toolsRecord:c,buildParams:Q=>{if(l){const ce=new Set(l.map(Oe=>Oe.name)),Ae=Object.fromEntries(Object.entries(c).filter(([Oe])=>!ce.has(Oe)));if(Object.keys(Ae).length>0){const Oe=y0(Ae,"input_schema");Oe&&Oe.length>0&&(l=[...l,...Oe])}}const K=L9(l),J=kwt({system:u.system,tools:K,messages:Q}),ie=Awt(Q,V4-J),pe=Ql("anthropic",h,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream");return g&&pe.temperature!==void 0&&p.debug("[anthropic] extended thinking is enabled, so temperature is omitted on the stream path \u2014 Anthropic rejects any temperature but 1 while thinking is set"),{model:h,messages:ie,max_tokens:iP(h,e.maxTokens),...u.system?{system:u.system}:{},...!g&&pe.temperature!==void 0?{temperature:pe.temperature}:{},...K&&K.length>0?{tools:K}:{},...f?{tool_choice:f}:{},...g?{thinking:g}:{}}},planReclaim:Q=>{const K=bwt({conversation:Q,availableInputTokens:nu("anthropic",h,e.maxTokens??void 0),fixedOverheadTokens:se(u.system,l),provider:"anthropic",observedPromptTokens:ye,previousSentEstimate:Se,onSentEstimate:ce=>{Se=ce}});if(!K)return;const J=new Set(K.drop),ie=new Set(K.truncate),pe=[];for(let ce=0;ce<Q.length;ce++){if(J.has(ce))continue;const Ae=Q[ce];if(ie.has(ce)&&Array.isArray(Ae.content)){pe.push({...Ae,content:Ae.content.map(Oe=>Oe.type==="tool_result"?{...Oe,content:_wt(typeof Oe.content=="string"?Oe.content:JSON.stringify(Oe.content)??"")}:Oe)});continue}pe.push(Ae)}if(J.size>0){let ce=pe.findIndex(Ae=>Array.isArray(Ae.content)&&Ae.content.some(Oe=>Oe.type==="tool_use"||Oe.type==="tool_result"));ce<0&&(ce=Math.min(1,pe.length)),pe.splice(ce,0,{role:"user",content:[{type:"text",text:BK}]})}return{conversation:pe}},...r?{requestTimeoutMs:r.requestTimeoutMs,requireTerminalEvent:!0}:{},noteObservedPromptTokens:Q=>{ye=Q},...m?{finalResultToolName:Nb,onTerminalResult:Q=>{H=Q,p.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:Q.length})}}:{}}),De={...Fe,buildToolResultMessages:(Q,K,J,ie)=>{for(const Ae of J)N.push(Ae.name);const pe=J.map(Ae=>({type:"tool-call",toolCallId:Ae.id,toolName:Ae.name,args:Ae.args})),ce=J.map(Ae=>Ae.error?{type:"tool-result",toolCallId:Ae.id,toolName:Ae.name,error:Ae.error}:{type:"tool-result",toolCallId:Ae.id,toolName:Ae.name,result:Ae.output});return Ept(E,ce.map(Ae=>({toolName:Ae.toolName,result:"result"in Ae?Ae.result:void 0,error:"error"in Ae?Ae.error:void 0}))),this.handleToolExecutionStorage(pe,ce,e,new Date).catch(Ae=>{p.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:Ae instanceof Error?Ae.message:String(Ae)})}),Fe.buildToolResultMessages(Q,K,J,ie)}},We={};for(const[Q,K]of Object.entries(c)){const J=K.execute;J&&(We[Q]={execute:async(ie,pe)=>{const ce=pe;return J(ie,{toolCallId:ce.toolCallId??"",...ce.abortSignal?{abortSignal:ce.abortSignal}:{},messages:[]})}})}const Ze=lt.getActiveSpan(),Pt=r?.beforeStep,Me=Pt?async Q=>{const K=r?.beforeStepTimeoutMs??$7,J=sa(K,this.providerName,"stream"),ie=r5(Q.signal,J?.controller.signal);try{return await t5(Promise.resolve(Pt({...Q,signal:ie.signal??Q.signal})),ie.signal??Q.signal)}catch(pe){p.warn("[Anthropic] executionControl.beforeStep failed or timed out; the step cap stands",{error:pe instanceof Error?pe.message:String(pe),stepsCompleted:Q.stepsCompleted});return}finally{ie.dispose(),J?.cleanup()}}:void 0,{stream:ke,resultPromise:Ke}=dd(De,u.messages.slice(),{tools:We,...a?{abortSignal:a}:{},...Ze?{span:Ze}:{},...Me?{beforeStep:Me}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}}),oe=(async()=>{for await(const Q of ke)Q.reasoning&&b({content:"",reasoning:Q.reasoning}),Q.content&&(m?W+=Q.content:b({content:Q.content}))})();let Y;try{Y=await Ke}catch(Q){throw await Vh(oe,"Anthropic"),Q}if(await oe,D+=Y.usage.inputTokens,$+=Y.usage.outputTokens,F+=Y.usage.cacheReadTokens??0,z+=Y.usage.cacheWriteTokens??0,q=Y.rawStopReason??q,Y.aborted){const Q=a?.aborted?a.reason:void 0;P.stopReason=Q instanceof Da?"time-limit":"aborted",P.finishReason="other",Y.rawStopReason&&(P.rawFinishReason=Y.rawStopReason),R(j()),I("other");return}P.finishReason=Y.finishReason,Y.rawStopReason&&(P.rawFinishReason=Y.rawStopReason),Y.finishReason==="tool-calls"&&H===void 0&&(P.stopReason="step-cap"),R(j()),I(q??"stop")})().catch(ye=>{throw x=ye,p.error("Anthropic: Stream error",{error:ye instanceof Error?ye.message:String(ye)}),R(j()),I("error"),this.formatProviderError(ye)}).finally(()=>{if(m){const ye=H??W;ye.length>0&&b({content:ye})}s?.cleanup(),_.close()});ue.catch(()=>{});const V=this.providerName;return{stream:async function*(){let ye=0;try{for await(const Se of _.iterable)"content"in Se&&typeof Se.content=="string"&&Se.content.length>0&&ye++,yield Se;if(await ue,ye===0&&N.length===0){p.warn(`${V}: Stream produced no output \u2014 emitting enriched sentinel`);const Se=new Gl({message:"Stream produced no output"}),xe=await zh(Se,void 0,x);Gh(xe),yield xe}}catch(Se){const xe=await zh(Se,void 0,x);if(Gh(xe),yield xe,!Gl.isInstance(Se))throw Se}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],metadata:P,analytics:k.then(async()=>{const ye=await wV.createAnalytics(this.providerName,h,{textStream:(async function*(){})(),usage:A,finishReason:k},Date.now()-U,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),Se=TRr();return Se&&ye&&(this.recordLimitSnapshot(Se),ye.limits=Se),ye})}}async isAvailable(){try{return KK()||WK(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),qwt={};ne(qwt,{ANTHROPIC_BETA_HEADERS:()=>Z4,AnthropicProvider:()=>Gwt,ModelAccessError:()=>A$,getModelCapabilities:()=>FK,getRecommendedModelForTier:()=>LK,isModelAvailableForTier:()=>NK});var FRr=S({"src/lib/providers/anthropic/index.ts"(){"use strict";LRr(),Fwt()}}),gf,$s,$Rr,URr,jwt,Hwt,Vwt,Lb,Wwt,BRr,zRr,GRr,qRr,jRr,HRr,VRr,WRr,KRr,JRr,YRr,ZRr,XRr,QRr,e1r,t1r,r1r,n1r,o1r,s1r,i1r,a1r,c1r,l1r,u1r,d1r,m1r,p1r,h1r,f1r,g1r,y1r,v1r,w1r,T1r,E1r,S1r,_1r,b1r,Kwt=S({"npm-stub:@aws-sdk/client-bedrock-runtime"(){gf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:gf.get}):new Proxy(function(...r){return new Proxy({},{get:gf.get})},{get:gf.get,apply(r,n,o){return new Proxy({},{get:gf.get})},construct(r,n){return new Proxy({},{get:gf.get})}})}},$s=new Proxy({},gf),{BedrockClient:$Rr,ListFoundationModelsCommand:URr,BedrockRuntimeClient:jwt,ConverseCommand:Hwt,ConverseStreamCommand:Vwt,ImageFormat:Lb,InvokeModelCommand:Wwt}=$s,{SageMakerRuntimeClient:BRr,InvokeEndpointCommand:zRr,InvokeEndpointWithResponseStreamCommand:GRr}=$s,{GoogleAuth:qRr,VertexAI:jRr,TextToSpeechClient:HRr}=$s,{Webhook:VRr}=$s,{Hippocampus:WRr,HippocampusConfig:KRr}=$s,{createClient:JRr}=$s,{Queue:YRr,Worker:ZRr,Job:XRr,QueueScheduler:QRr,FlowProducer:e1r}=$s,{Cron:t1r}=$s,{parseBuffer:r1r,selectCover:n1r}=$s,{extractRawText:o1r,convertToHtml:s1r}=$s,{Hono:i1r}=$s,{cors:a1r,HTTPException:c1r,logger:l1r,secureHeaders:u1r,streamSSE:d1r,timeout:m1r}=$s,p1r=globalThis.fetch,h1r=globalThis.Request,f1r=globalThis.Response,g1r=globalThis.Headers,y1r=globalThis.FormData,v1r=globalThis.File,w1r=globalThis.Blob,T1r=$s.Agent,E1r=$s.Pool,S1r=$s.Client,_1r=$s.Dispatcher,b1r=$s.MockAgent}});function C1r(e){if(/^(us|ca)-/.test(e))return"us";if(/^(eu|il|me|af)-/.test(e))return"eu";if(/^ap-northeast-[13]$/.test(e))return"jp";if(/^ap-southeast-[246]$/.test(e))return"au";if(/^ap-/.test(e))return"apac"}function k1r(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function Jwt(e){if(typeof e!="object"||e===null)return!1;const t=e,r=typeof t.name=="string"?t.name:"",n=typeof t.message=="string"?t.message:"";return!/ValidationException/i.test(r)&&!/ValidationException/i.test(n)?!1:/inference profile/i.test(n)&&/on-demand throughput/i.test(n)}function A1r(e,t){if(e.startsWith("arn:")||k1r(e))return[];const r=[],n=C1r(t);return n&&r.push(`${n}.${e}`),r.push(`${Xwt}.${e}`),r}function Ywt(e,t){return`${e}::${t}`}function x1r(e,t){return XK.get(Ywt(t,e))}function I1r(e,t,r){XK.set(Ywt(t,e),r),p.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function Zwt(e,t,r){const n=x1r(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!Jwt(o))throw o;const s=A1r(e,t);if(s.length===0)throw o;p.warn("[Bedrock] Model requires a cross-region inference profile in this region; retrying with a prefixed id",{region:t,candidates:s.length});for(const i of s)try{const a=await r(i);return I1r(e,t,i),a}catch(a){if(!Jwt(a))throw a}throw o}}var Xwt,XK,R1r=S({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";B(),Xwt="global",XK=new Map}});function X4(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Qwt(e,t){if(e){if(e.toolUse&&e._inputBuffer){try{e.toolUse.input=JSON.parse(e._inputBuffer)}catch{e.toolUse.input={}}delete e._inputBuffer}t&&!e.toolUse&&(e.text=t)}}function eTt(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??X4(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function M1r(e,t,r){const n=[],o=new Map,s=new Map,i=f=>{let g=o.get(f);return g||(g={},o.set(f,g),n.push(g)),g};let a="",c,l=0,u=0,d=0,m=0;if(e.stream)for await(const f of e.stream){if(r.aborted)break;const g=f;if(g.contentBlockStart&&i(g.contentBlockStart.contentBlockIndex??0),g.contentBlockDelta?.delta?.text){const y=g.contentBlockDelta.contentBlockIndex??0,w=g.contentBlockDelta.delta.text;i(y),a+=w,s.set(y,(s.get(y)??"")+w),t.push({content:w})}if(g.contentBlockStart?.start?.toolUse){const y=i(g.contentBlockStart.contentBlockIndex??0);y.toolUse={name:g.contentBlockStart.start.toolUse.name??"",input:{},toolUseId:g.contentBlockStart.start.toolUse.toolUseId??X4()}}if(g.contentBlockDelta?.delta?.toolUse){const y=i(g.contentBlockDelta.contentBlockIndex??0);y.toolUse??={name:"",input:{},toolUseId:X4()};const w=g.contentBlockDelta.delta.toolUse.input;typeof w=="string"?y._inputBuffer=(y._inputBuffer??"")+w:typeof w=="object"&&w!==null&&!Array.isArray(w)&&(y.toolUse.input={...y.toolUse.input??{},...w})}if(g.contentBlockStop){const y=g.contentBlockStop.contentBlockIndex??0;Qwt(o.get(y),s.get(y)??"")}if(g.messageStop){c=g.messageStop.stopReason??"end_turn";continue}if(g.metadata?.usage){l+=g.metadata.usage.inputTokens??0,u+=g.metadata.usage.outputTokens??0,d+=g.metadata.usage.cacheReadInputTokens??0,m+=g.metadata.usage.cacheWriteInputTokens??0;break}}for(const[f,g]of o)Qwt(g,s.get(f)??"");const h=n.filter(f=>f.text||f.toolUse||f.image||f.document);return{text:a,toolCalls:eTt(h),usage:{inputTokens:l,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:m},rawStopReason:c,raw:h}}function P1r(e){const t=[];let r="";for(const n of e.output?.message?.content??[]){const o={};"text"in n&&n.text&&(o.text=n.text,r+=r?` ${n.text}`:n.text),"toolUse"in n&&n.toolUse&&(o.toolUse={toolUseId:n.toolUse.toolUseId??X4(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:eTt(t),usage:{inputTokens:e.usage?.inputTokens??0,outputTokens:e.usage?.outputTokens??0,cacheReadTokens:e.usage?.cacheReadInputTokens??0,cacheWriteTokens:e.usage?.cacheWriteInputTokens??0},rawStopReason:e.stopReason,raw:t}}function tTt(e){return{providerLabel:"bedrock",maxSteps:e.maxSteps,buildStepRequest(t,r){return{raw:e.buildCommandInput(t,r)}},async executeStep(t,r,n){const o=t.raw;if(!e.streaming){const i=await Zwt(o.modelId??"",e.region,a=>Be(e.client.send(new Hwt({...o,modelId:a}),{abortSignal:n}),QK,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return P1r(i)}const s=await Zwt(o.modelId??"",e.region,i=>Be(e.client.send(new Vwt({...o,modelId:i}),{abortSignal:n}),QK,new Error("Bedrock streaming API call timed out")));return M1r(s,r,n)},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw},s={role:"user",content:n.map(i=>({toolResult:{toolUseId:i.id,content:[{text:i.error?`Error executing tool ${i.name}: ${i.error}`:String(typeof i.output=="string"?i.output:JSON.stringify(i.output))}],status:i.error?"error":"success"}}))};return[...t,o,s]},mapFinishReason(t,r){switch(t){case"end_turn":case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return r?"tool-calls":"stop"}}}}var QK,D1r=S({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";Kwt(),tt(),R1r(),QK=12e4}});function rTt(e,t,r){return{input:{text:e.input?.text||"",images:e.input?.images,content:e.input?.content,files:e.input?.files,csvFiles:e.input?.csvFiles,pdfFiles:e.input?.pdfFiles,audioFiles:e.input?.audioFiles,videoFiles:e.input?.videoFiles},csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,systemPrompt:e.systemPrompt,conversationHistory:e.conversationMessages,provider:t,model:r,temperature:e.temperature,maxTokens:e.maxTokens,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,fileRegistry:e.fileRegistry}}var O1r=S({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),Q4,nTt=S({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";Ua(),Q4=Le.provider}}),oTt={};ne(oTt,{Agent:()=>WTt,BedrockClient:()=>iTt,BedrockRuntimeClient:()=>cTt,Blob:()=>VTt,Client:()=>JTt,ConverseCommand:()=>lTt,ConverseStreamCommand:()=>uTt,Cron:()=>xTt,Dispatcher:()=>YTt,File:()=>HTt,FlowProducer:()=>ATt,FormData:()=>jTt,GoogleAuth:()=>gTt,HTTPException:()=>NTt,Headers:()=>qTt,Hippocampus:()=>TTt,HippocampusConfig:()=>ETt,Hono:()=>DTt,ImageFormat:()=>dTt,InvokeEndpointCommand:()=>hTt,InvokeEndpointWithResponseStreamCommand:()=>fTt,InvokeModelCommand:()=>mTt,Job:()=>CTt,ListFoundationModelsCommand:()=>aTt,MockAgent:()=>QTt,Pool:()=>KTt,Queue:()=>_Tt,QueueScheduler:()=>kTt,Request:()=>zTt,Response:()=>GTt,SageMakerRuntimeClient:()=>pTt,TextToSpeechClient:()=>vTt,VertexAI:()=>yTt,Webhook:()=>wTt,Worker:()=>bTt,convertToHtml:()=>PTt,cors:()=>OTt,createClient:()=>STt,default:()=>sTt,extractRawText:()=>MTt,fetch:()=>BTt,getGlobalDispatcher:()=>XTt,interceptors:()=>eEt,logger:()=>LTt,parseBuffer:()=>ITt,request:()=>tEt,secureHeaders:()=>FTt,selectCover:()=>RTt,setGlobalDispatcher:()=>ZTt,streamSSE:()=>$Tt,timeout:()=>UTt});var yf,os,sTt,iTt,aTt,cTt,lTt,uTt,dTt,mTt,pTt,hTt,fTt,gTt,yTt,vTt,wTt,TTt,ETt,STt,_Tt,bTt,CTt,kTt,ATt,xTt,ITt,RTt,MTt,PTt,DTt,OTt,NTt,LTt,FTt,$Tt,UTt,BTt,zTt,GTt,qTt,jTt,HTt,VTt,WTt,KTt,JTt,YTt,ZTt,XTt,QTt,eEt,tEt,N1r=S({"npm-stub:@aws-sdk/client-bedrock"(){yf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:yf.get}):new Proxy(function(...r){return new Proxy({},{get:yf.get})},{get:yf.get,apply(r,n,o){return new Proxy({},{get:yf.get})},construct(r,n){return new Proxy({},{get:yf.get})}})}},os=new Proxy({},yf),sTt=os,{BedrockClient:iTt,ListFoundationModelsCommand:aTt,BedrockRuntimeClient:cTt,ConverseCommand:lTt,ConverseStreamCommand:uTt,ImageFormat:dTt,InvokeModelCommand:mTt}=os,{SageMakerRuntimeClient:pTt,InvokeEndpointCommand:hTt,InvokeEndpointWithResponseStreamCommand:fTt}=os,{GoogleAuth:gTt,VertexAI:yTt,TextToSpeechClient:vTt}=os,{Webhook:wTt}=os,{Hippocampus:TTt,HippocampusConfig:ETt}=os,{createClient:STt}=os,{Queue:_Tt,Worker:bTt,Job:CTt,QueueScheduler:kTt,FlowProducer:ATt}=os,{Cron:xTt}=os,{parseBuffer:ITt,selectCover:RTt}=os,{extractRawText:MTt,convertToHtml:PTt}=os,{Hono:DTt}=os,{cors:OTt,HTTPException:NTt,logger:LTt,secureHeaders:FTt,streamSSE:$Tt,timeout:UTt}=os,BTt=globalThis.fetch,zTt=globalThis.Request,GTt=globalThis.Response,qTt=globalThis.Headers,jTt=globalThis.FormData,HTt=globalThis.File,VTt=globalThis.Blob,WTt=os.Agent,KTt=os.Pool,JTt=os.Client,YTt=os.Dispatcher,ZTt=()=>{},XTt=()=>os,QTt=os.MockAgent,eEt={redirect:()=>e=>e,retry:()=>e=>e},tEt=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}});async function eJ(){return await Promise.resolve().then(()=>(N1r(),oTt))}var rEt=S({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}}),nEt,L1r=S({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";Kwt(),hr(),OS(),Sc(),Lo(),CP(),D1r(),ut(),Qs(),tt(),B(),hh(),BM(),O1r(),ti(),Kt(),nTt(),rEt(),nEt=class crr extends ja{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(t){return t?t.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(t,r,n,o){super(t,"bedrock",r);const s=t||process.env.BEDROCK_MODEL||this.modelName,i=crr.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",p.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),p.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{p.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new jwt({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),p.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw p.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){const{BedrockClient:t,ListFoundationModelsCommand:r}=await eJ(),n=new t({region:this.region});try{p.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");const o=new r({}),s=Date.now();await n.send(o);const i=Date.now()-s;p.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){const s=o instanceof Error?o.message:String(o);p.error("[AmazonBedrockProvider] Health check FAILED - this will cause production failures:",{error:s,errorType:o instanceof Error?o.constructor.name:"Unknown",region:process.env.AWS_REGION||"us-east-1",hasAccessKey:!!process.env.AWS_ACCESS_KEY_ID,hasSecretKey:!!process.env.AWS_SECRET_ACCESS_KEY})}finally{try{n.destroy()}catch{}}}getAISDKModel(){throw new Error("AmazonBedrockProvider does not use AI SDK models")}getProviderName(){return"bedrock"}getDefaultModel(){return process.env.BEDROCK_MODEL||"anthropic.claude-sonnet-4-6"}getDefaultEmbeddingModel(){return process.env.BEDROCK_EMBEDDING_MODEL||process.env.AWS_EMBEDDING_MODEL||"amazon.titan-embed-text-v2:0"}async generate(t){p.debug("[AmazonBedrockProvider] generate() called with conversation management");const r=Date.now(),n=typeof t=="string"?{prompt:t}:t;this.conversationHistory=[];const o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){p.debug("[AmazonBedrockProvider] Detected multimodal input in generate(), using multimodal message builder",{hasImages:!!o?.images?.length,imageCount:o?.images?.length||0,hasContent:!!o?.content?.length,contentCount:o?.content?.length||0,hasFiles:!!o?.files?.length,fileCount:o?.files?.length||0,hasCSVFiles:!!o?.csvFiles?.length,csvFileCount:o?.csvFiles?.length||0,hasPDFFiles:!!o?.pdfFiles?.length,pdfFileCount:o?.pdfFiles?.length||0});const m=rTt(n,this.providerName,this.modelName),h=await FM(m,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(h)}else{p.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const d={role:"user",content:[{text:n.prompt||o?.text||""}]};this.conversationHistory.push(d)}p.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let i,a,c,l;try{({text:i,usage:a,finishReason:c,rawFinishReason:l}=await this.conversationLoop(n))}catch(d){const m=this.neurolink?.getEventEmitter();throw m&&m.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:"error"},success:!1,error:d instanceof Error?d.message:String(d)}),d}const u=this.neurolink?.getEventEmitter();return u&&u.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:c},success:!0}),{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),...c!==void 0&&{finishReason:c},...l!==void 0&&{rawFinishReason:l}}}async conversationLoop(t){const r=t.maxSteps||Ds,n=await this.resolveTurnTools(t.tools,t.disableTools),o=this.formatToolsForBedrock(n),s=Ql(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converse"),i=tTt({client:this.bedrockClient,streaming:!1,region:this.region,maxSteps:r,buildCommandInput:a=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(a),system:[{text:t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:t.maxTokens,...s.temperature!==void 0&&{temperature:s.temperature}},...o?{toolConfig:o}:{}})});try{const{resultPromise:a}=dd(i,this.conversationHistory,{tools:this.toEngineTools(n),abortSignal:t.abortSignal,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}}),c=await a;this.conversationHistory=c.conversation;const l=c.usage.inputTokens,u=c.usage.outputTokens,d=c.usage.cacheReadTokens??0,m=c.usage.cacheWriteTokens??0;return{text:c.text||"",usage:{input:l,output:u,total:l+d+m+u,...d>0&&{cacheReadTokens:d},...m>0&&{cacheCreationTokens:m}},finishReason:c.finishReason,rawFinishReason:c.rawStopReason}}catch(a){throw p.error("[AmazonBedrockProvider] Error in conversation loop:",a),this.handleProviderError(a)}}convertToAWSMessages(t){return t.map(r=>({role:r.role,content:r.content.map(n=>n.text?{text:n.text}:n.image?{image:n.image}:n.document?{document:n.document}:n.toolUse?{toolUse:{toolUseId:n.toolUse.toolUseId,name:n.toolUse.name,input:n.toolUse.input}}:n.toolResult?{toolResult:{toolUseId:n.toolResult.toolUseId,content:n.toolResult.content,status:n.toolResult.status}}:{text:""})}))}async executeSingleTool(t,r,n,o){return Q4.startActiveSpan("bedrock.tool.execute",{kind:Fr.CLIENT,attributes:{"gen_ai.tool.name":r,"gen_ai.system":"aws.bedrock"}},async s=>{try{if(p.debug(`[AmazonBedrockProvider] Executing single tool: ${r}`,{args:n}),!t[r])throw new Error(`Tool not found: ${r}`);const i=t[r];if(!i||!i.execute)throw new Error(`Tool ${r} does not have execute method`);const a=n||{};r==="list_directory"&&!a.path&&(a.path=".",p.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),p.debug("[AmazonBedrockProvider] Tool input parameters:",a);const c={};for(const[d,m]of Object.entries(a))(m===null||typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="object"&&m!==null)&&(c[d]=m);const l=await i.execute(c);p.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:r,result:l});let u;if(l&&typeof l=="object"&&"success"in l)if(l.success&&l.data!==void 0)typeof l.data=="string"?u=l.data:typeof l.data=="object"?u=JSON.stringify(l.data,null,2):u=String(l.data);else if(l.error){const d=typeof l.error=="string"?l.error:l.error.message||"Tool execution failed";throw new Error(d)}else u="";else typeof l=="string"?u=l:typeof l=="object"?u=JSON.stringify(l,null,2):u=String(l);return s.setStatus({code:Ne.OK}),u}catch(i){throw p.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:i}),s.setStatus({code:Ne.ERROR,message:i.message}),s.recordException(i),i}finally{s.end()}})}async resolveTurnTools(t,r){if(r)return{};const n=t??await this.getAllTools();return this.convertAISDKToolsToToolDefinitions(n)}toEngineTools(t){const r={};for(const n of Object.keys(t))r[n]={execute:o=>this.executeSingleTool(t,n,o)};return r}convertAISDKToolsToToolDefinitions(t){const r={};for(const[n,o]of Object.entries(t))if("description"in o&&o.description){const i=o.parameters??o.inputSchema;r[n]={description:o.description,parameters:i,execute:async a=>{if("execute"in o&&o.execute)return{success:!0,data:await o.execute(a,{toolCallId:`tool_${Date.now()}`,messages:[]})};throw new Error(`Tool ${n} has no execute method`)}}}return r}formatToolsForBedrock(t){if(!t||Object.keys(t).length===0)return null;const r=Object.entries(t).map(([n,o])=>{let s;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?s=Mo(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 p.debug(`[AmazonBedrockProvider] Formatted ${r.length} tools for Bedrock`),{tools:r}}convertToBedrockMessages(t){return t.map(r=>{const n={role:r.role==="system"?"user":r.role,content:[]};return typeof r.content=="string"?n.content.push({text:r.content}):r.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){const s=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image;let i=o.mimeType?.split("/")[1]||"png";i==="jpg"&&(i="jpeg"),n.content.push({image:{format:i==="jpeg"?Lb.JPEG:i==="png"?Lb.PNG:i==="gif"?Lb.GIF:Lb.WEBP,source:{bytes:s}}})}else if(o.type==="document"||o.type==="pdf"||o.type==="file"&&o.mimeType?.toLowerCase().startsWith("application/pdf")){let s;if(typeof o.data=="string"){const a=o.data.replace(/^data:application\/pdf;base64,/i,"");s=Buffer.from(a,"base64")}else s=o.data;let i=typeof o.name=="string"&&o.name?gm.basename(o.name):"document-pdf";i=i.replace(/\.[^.]+$/,""),i=i.replace(/[^a-zA-Z0-9\s\-()[\]]/g,"-"),i=i.replace(/-+/g,"-").trim().replace(/^-+|-+$/g,""),i=i||"document",n.content.push({document:{format:"pdf",name:i,source:{bytes:s}}})}}),n})}getBedrockClient(){return this.bedrockClient}async executeStream(t){return p.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),p.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),Q4.startActiveSpan("bedrock.stream",{kind:Fr.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async r=>{try{if(p.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(t.input?.images?.length||t.input?.content?.length||t.input?.files?.length||t.input?.csvFiles?.length||t.input?.pdfFiles?.length)){p.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!t.input?.images?.length,imageCount:t.input?.images?.length||0,hasContent:!!t.input?.content?.length,contentCount:t.input?.content?.length||0,hasFiles:!!t.input?.files?.length,fileCount:t.input?.files?.length||0,hasCSVFiles:!!t.input?.csvFiles?.length,csvFileCount:t.input?.csvFiles?.length||0,hasPDFFiles:!!t.input?.pdfFiles?.length,pdfFileCount:t.input?.pdfFiles?.length||0});const s=rTt(t,this.providerName,this.modelName),i=await FM(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{p.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");const s={role:"user",content:[{text:t.input.text}]};this.conversationHistory.push(s)}p.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),p.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");const o=await this.streamingConversationLoop(t,r);return p.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),r.setStatus({code:Ne.OK}),r.end(),o}catch(n){p.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");const o=n,s=o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream");if(p.debug("[TRACE] executeStream CATCH - checking if permission error"),p.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){p.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),p.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),r.addEvent("stream.fallback_to_generate",{reason:o.message});const i=await this.generate({prompt:t.input.text,input:t.input,maxTokens:t.maxTokens,temperature:t.temperature,systemPrompt:t.systemPrompt});if(!i)throw r.setStatus({code:Ne.ERROR,message:"Generate method returned null result"}),r.end(),new Error("Generate method returned null result");r.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),r.setStatus({code:Ne.OK}),r.end();const a=new ReadableStream({start(l){const d=(i.content||"").split(/(\s+)/);let m="";for(let h=0;h<d.length;h++)m+=d[h],(h===d.length-1||m.length>50||/[.!?;,]\s*$/.test(m))&&m.length>0&&(l.enqueue({content:m}),m="");m.length>0&&l.enqueue({content:m}),l.close()}});return{stream:{async*[Symbol.asyncIterator](){const l=a.getReader();try{for(;;){const{done:u,value:d}=await l.read();if(u)break;yield d}}finally{l.releaseLock()}}},usage:i.usage,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw r.setStatus({code:Ne.ERROR,message:o instanceof Error?o.message:String(o)}),r.recordException(o instanceof Error?o:new Error(String(o))),r.end(),n}})}async streamingConversationLoop(t,r){const n=Date.now(),o=t.maxSteps||Ds,s=await this.resolveTurnTools(t.tools,t.disableTools),i=this.formatToolsForBedrock(s),a=Ql(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converseStream"),c=tTt({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:R=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(R),system:[{text:t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:t.maxTokens,...a.temperature!==void 0&&{temperature:a.temperature}},...i?{toolConfig:i}:{}})});let l=!1,u;const d=new Promise(R=>{u=()=>{l=!0,R()}}),m={...c,executeStep:async(R,I,x)=>{const M=await c.executeStep(R,I,x);return u(),M}};r.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});const{stream:h,resultPromise:f}=dd(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:t.abortSignal,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}}),g=f.then(R=>({result:R,error:void 0}),R=>({result:void 0,error:R}));if(await Promise.race([d,g]),!l){const R=await g;if(R.error)throw R.error}const y=this.neurolink?.getEventEmitter(),w=this,E={startTime:n,streamId:`bedrock-${Date.now()}`};let _;const b=new Promise(R=>{_=R}),A=R=>{const I=R?.inputTokens??0,x=R?.outputTokens??0,M=R?.cacheReadTokens??0,N=R?.cacheWriteTokens??0;return{input:I,output:x,total:I+M+N+x,...M>0&&{cacheReadTokens:M},...N>0&&{cacheCreationTokens:N}}};return g.then(R=>{_(Ly(this.providerName,this.modelName||this.getDefaultModel(),{usage:A(R.result?.usage)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let R=!1;try{yield*h}catch(I){throw R=!0,I}finally{const I=await g;I.error&&(R=!0);const x=A(I.result?.usage);I.result&&(w.conversationHistory=I.result.conversation,E.finishReason=I.result.finishReason,E.rawFinishReason=I.result.rawStopReason,r.setAttribute("gen_ai.response.stop_reason",I.result.rawStopReason??"unknown")),y&&y.emit("generation:end",{provider:w.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:x,model:w.modelName||w.getDefaultModel(),provider:w.providerName,finishReason:R?"error":I.result?.rawStopReason},success:!R})}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:b,metadata:E}}async checkBedrockHealth(){const t=new AbortController,r=setTimeout(()=>t.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await eJ(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{p.debug("[AmazonBedrockProvider] Starting health check...");const i=new o({}),c=(await s.send(i,{abortSignal:t.signal})).modelSummaries||[],l=c.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(p.debug(`[AmazonBedrockProvider] Health check passed - Found ${l.length} active models out of ${c.length} total models`),l.length===0)throw new Error("No active foundation models available in the region")}catch(i){clearTimeout(r);const a=i;if(or(i))throw new Error("Bedrock health check timed out after 10 seconds",{cause:i});const c=typeof a.message=="string"?a.message:"";throw c.includes("UnauthorizedOperation")||c.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}):(p.error("[AmazonBedrockProvider] Health check failed:",i),new Error(`Bedrock health check failed: ${c||"Unknown error"}`,{cause:i}))}finally{clearTimeout(r);try{s.destroy()}catch{}}}formatProviderError(t){return gi(t,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:_r,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:ms,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:dt,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:dt,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(t,r){const n=r||"amazon.titan-embed-text-v2:0";p.debug("Generating embedding",{provider:this.providerName,model:n,textLength:t.length});try{const o=JSON.stringify({inputText:t}),s=new Wwt({modelId:n,contentType:"application/json",accept:"application/json",body:o}),i=await Be(this.bedrockClient.send(s),6e4,new Error("Bedrock embedding API call timed out")),a=JSON.parse(new TextDecoder().decode(i.body));if(!a.embedding||!Array.isArray(a.embedding))throw new Error("Invalid embedding response from Bedrock");return p.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.embedding.length}),a.embedding}catch(o){throw p.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:t.length}),this.handleProviderError(o)}}async embedMany(t,r){const n=r||"amazon.titan-embed-text-v2:0";p.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:t.length});try{const o=await Promise.all(t.map(s=>this.embed(s,n)));return p.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw p.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:t.length}),this.handleProviderError(o)}}}}}),oEt={};ne(oEt,{AmazonBedrockProvider:()=>nEt,bedrockTracer:()=>Q4,loadBedrockControl:()=>eJ});var F1r=S({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";L1r(),nTt(),rEt()}}),sEt={};ne(sEt,{AzureOpenAIProvider:()=>iEt});var iEt,$1r=S({"src/lib/providers/azureOpenai.ts"(){"use strict";ut(),B(),Qs(),Vo(),nl(),Va(),Vm(),iEt=class extends fa{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,r,n){const o=n?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",s=process.env.AZURE_OPENAI_ENDPOINT||"";let i;if(s)try{i=new URL(s.includes("://")?s:`https://${s}`)}catch{i=void 0}const a=i?.hostname??"",c=i?.pathname&&i.pathname!=="/"?i.pathname.replace(/\/+$/,""):"",l=/\.(openai|cognitiveservices)\.azure\.com$/.test(a);let u;l?u="/openai":u=/\/openai(?:\/v\d+)?$/.test(c)?c:`${c}/openai`;const d=i?.origin??"",m=n?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",h=n?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",f=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,g=n?.useMaxCompletionTokens??(f===void 0?void 0:/^(1|true|yes)$/i.test(f));o||yi(Ylr()),d||yi(Zlr()),super("azure",e,t,{baseURL:d,apiKey:o}),this.azureDeployment=m,this.azureApiVersion=h,this.azureResourceOrigin=d,this.azureDeploymentPathPrefix=u,this.useMaxCompletionTokensOverride=g,p.shouldLog("debug")&&p.debug("Azure OpenAI Provider initialized",k$e({deployment:this.azureDeployment,resourceOrigin:this.azureResourceOrigin,deploymentPathPrefix:this.azureDeploymentPathPrefix,apiVersion:this.azureApiVersion,provider:"azure"}))}suppressResponseFormatWithTools(){return!1}getProviderName(){return"azure"}getDefaultModel(){return this.azureDeployment}formatProviderError(e){const t=[{match:r=>/401/.test(r.message),errorClass:_r,message:"Invalid Azure OpenAI API key or endpoint."},...aa];return gi(e,t,this.providerName,this.modelName)}getChatCompletionsURL(e){const t=e||this.azureDeployment,r=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${r}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){const r=this.useMaxCompletionTokensOverride??hpt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function U1r(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70?"image/gif":"image/png"}var B1r=S({"src/lib/utils/imageDetection.ts"(){"use strict"}});function aEt(e){return e.map(t=>typeof t.content=="string"?{role:t.role,content:t.content}:{role:t.role,content:t.content.map(r=>r.type==="image"||r.type==="document"?{type:r.type,media_type:r.source.media_type,base64_chars:r.source.data.length}:r)})}var z1r=S({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),eD,G1r=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs"(){eD=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0}}}),q1r=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs"(){Kn()}});function tJ(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var tD,rJ,cEt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs"(){q1r(),tD=e=>(tD=Array.isArray,tD(e)),rJ=tD}});function*j1r(e){if(!e)return;if(nJ in e){const{values:n,nulls:o}=e;yield*n.entries();for(const s of o)yield[s,null];return}let t=!1,r;e instanceof Headers?r=e.entries():rJ(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){const o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");const s=rJ(n[1])?n[1]:[n[1]];let i=!1;for(const a of s)a!==void 0&&(t&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var nJ,lEt,H1r=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){cEt(),nJ=Symbol.for("brand.privateNullableHeaders"),lEt=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[s,i]of j1r(n)){const a=s.toLowerCase();o.has(a)||(t.delete(s),o.add(a)),i===null?(t.delete(s),r.add(a)):(t.append(s,i),r.delete(a))}}return{[nJ]:!0,values:t,nulls:r}}}});function V1r(e){const t=new Ab(e);return delete t.batches,t}function W1r(e){const t=new Hi(e);return delete t.messages.batches,t}var uEt,dEt,oJ,mEt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){G4(),hyt(),lP(),G1r(),cEt(),H1r(),G4(),uEt="vertex-2023-10-16",dEt=new Set(["/v1/messages","/v1/messages?beta=true"]),oJ=class extends vo{constructor({baseURL:e=eD("ANTHROPIC_VERTEX_BASE_URL"),region:t=eD("CLOUD_ML_REGION")??null,projectId:r=eD("ANTHROPIC_VERTEX_PROJECT_ID")??null,...n}={}){if(!t)throw new Error("No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.");if(!e)switch(t){case"global":e="https://aiplatform.googleapis.com/v1";break;case"us":e="https://aiplatform.us.rep.googleapis.com/v1";break;case"eu":e="https://aiplatform.eu.rep.googleapis.com/v1";break;default:e=`https://${t}-aiplatform.googleapis.com/v1`}if(super({baseURL:e,...n}),this.messages=V1r(this),this.beta=W1r(this),this.region=t,this.projectId=r,this.accessToken=n.accessToken??null,n.authClient&&n.googleAuth)throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");n.authClient?this._authClientPromise=Promise.resolve(n.authClient):(this._auth=n.googleAuth??new v9({scopes:"https://www.googleapis.com/auth/cloud-platform"}),this._authClientPromise=this._auth.getClient())}validateHeaders(){}async prepareOptions(e){const t=await this._authClientPromise,r=await t.getRequestHeaders(),n=t.projectId??r["x-goog-user-project"];!this.projectId&&n&&(this.projectId=n),e.headers=lEt([r,e.headers])}async buildRequest(e){if(tJ(e.body)&&(e.body={...e.body}),tJ(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=uEt)),dEt.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(!tJ(e.body))throw new Error("Expected request body to be an object for post /v1/messages");const t=e.body.model;e.body.model=void 0;const n=e.body.stream??!1?"streamRawPredict":"rawPredict";e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${t}:${n}`}if(e.path==="/v1/messages/count_tokens"||e.path=="/v1/messages/count_tokens?beta=true"&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`}return super.buildRequest(e)}}}}),sJ={};ne(sJ,{AnthropicVertex:()=>oJ,BaseAnthropic:()=>vo,default:()=>oJ});var pEt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){mEt(),mEt()}});async function K1r(){return rD||(rD=await Promise.resolve().then(()=>(pEt(),sJ))),rD}function J1r(e){const t=[],r=new Map;let n=0;const o=s=>{const i=`${n}:${s??"x"}`;let a=r.get(i);return a||(a={type:"tool_step",callParts:[],resultParts:[]},r.set(i,a),t.push(a)),a};for(const s of e){if(s.role==="tool_call"){o(s.metadata?.stepIndex).callParts.push({name:s.tool||"unknown",input:s.args||{}});continue}if(s.role==="tool_result"){o(s.metadata?.stepIndex).resultParts.push(s.content&&s.content.length>0?s.content:"(no output)");continue}const i=s.role==="assistant"?"assistant":s.role==="user"?"user":null;!i||!s.content||s.content.trim().length===0||(n++,t.push({type:"regular",role:i,parts:[s.content]}))}return t}function iJ(e,t,r){const n=e[e.length-1];n&&n.role===t&&Array.isArray(n.content)?n.content.push(...r):e.push({role:t,content:[...r]})}function Y1r(e,t){const r=e.callParts,n=e.resultParts,o=Math.min(r.length,n.length);(o!==r.length||o!==n.length)&&p.debug("[GoogleVertex] Unbalanced tool step in Claude history replay",{calls:r.length,results:n.length,paired:o});const s=[],i=[];for(let a=0;a<o;a++){const c=`hist_${t}_${a}`;s.push({type:"tool_use",id:c,name:r[a].name,input:r[a].input}),i.push({type:"tool_result",tool_use_id:c,content:n[a]})}return{uses:s,results:i}}function Z1r(e){const t=r=>Array.isArray(r.content)&&r.content.length>0&&r.content.every(n=>n.type==="tool_result");for(;e.length>0&&(e[0].role!=="user"||t(e[0]));)e.shift()}function aJ(e){const t=[];let r=0;for(const n of J1r(e)){if(n.type==="regular"){iJ(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:s}=Y1r(n,r);o.length!==0&&(r++,iJ(t,"assistant",o),iJ(t,"user",s))}if(Z1r(t),p.shouldLog("debug")){const n=t.flatMap(o=>Array.isArray(o.content)?o.content:[]);p.debug("[GoogleVertex] Replayed Claude history with tool turns",{historyMessages:t.length,toolUseBlocks:n.filter(o=>o.type==="tool_use").length,toolResultBlocks:n.filter(o=>o.type==="tool_result").length})}return t}function cJ(e,t){const r=e[e.length-1];if(r&&r.role==="user"){const n=Array.isArray(r.content)?r.content:[{type:"text",text:r.content}],o=Array.isArray(t)?t:[{type:"text",text:t}];r.content=[...n,...o];return}e.push({role:"user",content:t})}function vf(e){if(!e||typeof e!="object")return;const t=["additionalProperties","default","$schema","$id","$ref","definitions","$defs","examples","errorMessage"];for(const n of t)n in e&&delete e[n];typeof e.exclusiveMinimum=="boolean"&&(e.exclusiveMinimum===!0&&typeof e.minimum=="number"?(e.exclusiveMinimum=e.minimum,delete e.minimum):delete e.exclusiveMinimum),typeof e.exclusiveMaximum=="boolean"&&(e.exclusiveMaximum===!0&&typeof e.maximum=="number"?(e.exclusiveMaximum=e.maximum,delete e.maximum):delete e.exclusiveMaximum);const r=2147483647;if(typeof e.maximum=="number"&&e.maximum>r&&delete e.maximum,typeof e.minimum=="number"&&e.minimum<-r&&delete e.minimum,e.properties&&typeof e.properties=="object")for(const n of Object.values(e.properties))n&&typeof n=="object"&&vf(n);if(e.items&&typeof e.items=="object")if(Array.isArray(e.items))for(const n of e.items)n&&typeof n=="object"&&vf(n);else vf(e.items);for(const n of["allOf","anyOf","oneOf"])if(Array.isArray(e[n]))for(const o of e[n])o&&typeof o=="object"&&vf(o)}function hEt(e,t,r){const n=gmt({contents:e,availableInputTokens:nu("vertex",t),provider:"vertex",observedPromptTokens:r});if(!n)return!1;const o=new Set(n.drop),s=new Set(n.truncate),i=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const c=e[a];if(s.has(a)&&Array.isArray(c.parts)){i.push({...c,parts:c.parts.map(l=>{if(!("functionResponse"in l))return l;const u=l.functionResponse,d=JSON.stringify(u.response)??"";return d.length<=TEt?l:{functionResponse:{name:u.name,response:{result:D9(d)}}}})});continue}i.push(c)}if(o.size>0){let a=i.findIndex(c=>Array.isArray(c.parts)&&c.parts.some(l=>!!l.functionCall||!!l.functionResponse));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",parts:[{text:N9}]})}return e.length=0,e.push(...i),!0}function fEt(e,t,r){const n=bwt({conversation:e,availableInputTokens:nu("vertex",t),fixedOverheadTokens:0,provider:"vertex",observedPromptTokens:r,observedDescribesCurrentPayload:!0});if(!n)return!1;const o=new Set(n.drop),s=new Set(n.truncate),i=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const c=e[a];if(s.has(a)&&Array.isArray(c.content)){i.push({...c,content:c.content.map(l=>{if(l.type!=="tool_result")return l;const u=typeof l.content=="string"?l.content:JSON.stringify(l.content)??"";return{...l,content:_wt(u)}})});continue}i.push(c)}if(o.size>0){let a=i.findIndex(c=>Array.isArray(c.content)&&c.content.some(l=>l.type==="tool_use"||l.type==="tool_result"));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",content:[{type:"text",text:BK}]})}return e.length=0,e.push(...i),!0}async function gEt(e,t,r={}){const n=[],o=[];let s,i=0,a=0,c=0,l=0;for await(const u of e){r.onProgress?.();const d=u,h=d.candidates?.[0],f=h?.finishReason;typeof f=="string"&&f&&(s=f);const g=h?.content;if(g&&Array.isArray(g.parts))for(const w of g.parts)n.push(w),typeof w.text=="string"&&w.text.length>0&&t.push({content:w.text});u.functionCalls&&o.push(...u.functionCalls);const y=d.usageMetadata;if(y){if(y.promptTokenCount!==void 0&&y.promptTokenCount>0){r.onUsageDelta?.("input",y.promptTokenCount-i),i=y.promptTokenCount,r.onUsage?.(y.promptTokenCount,y.candidatesTokenCount??0);const w=Math.min(y.cachedContentTokenCount??0,y.promptTokenCount);r.onUsageDelta?.("cacheRead",w-c),c=w}y.candidatesTokenCount!==void 0&&y.candidatesTokenCount>0&&(r.onUsageDelta?.("output",y.candidatesTokenCount-a),a=y.candidatesTokenCount),y.thoughtsTokenCount!==void 0&&y.thoughtsTokenCount>0&&(r.onUsageDelta?.("reasoning",y.thoughtsTokenCount-l),l=y.thoughtsTokenCount)}}return{rawResponseParts:n,stepFunctionCalls:o,...s?{finishReason:s}:{},inputTokens:i,outputTokens:a,...c?{cacheReadTokens:c}:{},...l?{reasoningTokens:l}:{}}}var rD,yEt,lJ,Fb,uJ,V0,wf,vEt,wEt,nD,TEt,dJ,X1r=S({"src/lib/providers/googleVertex/client.ts"(){"use strict";Cn(),fP(),hr(),Sc(),Wj(),_P(),tYe(),Lo(),fh(),vh(),R9(),Qt(),Wn(),ut(),Qs(),tt(),Iwt(),Mct(),BM(),B(),_9(),vmt(),Cwt(),d9(),B1r(),m9(),Vo(),ti(),tmt(),Wh(),ia(),wmt(),umt(),CP(),Nwt(),I_(),g0(),F9(),nd(),zS(),Ua(),Kt(),tl(),nl(),Eh(),hh(),z1r(),I_(),rD=null,yEt=()=>!0,lJ=()=>yi(iur()),Fb=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",uJ=(e,t)=>{const r=t||Fb();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||Vq.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},V0=uJ,wf=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",vEt=()=>!!(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),wEt=async(e,t,r,n)=>{const o=e||Fb();return{projectId:r?r.projectId?.trim()||"express":lJ(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},nD=e=>e.toLowerCase().includes("claude"),TEt=2048,dJ=class Wr extends ja{projectId;location;expressApiKey;baseURL;registeredTools=new Map;toolContext={};static modelConfigCache=new Map;static modelConfigCacheTime=0;static CACHE_DURATION=300*1e3;static MAX_CACHE_SIZE=50;static maxTokensCache=new Map;static maxTokensCacheTime=0;constructor(t,r,n,o,s){super(t,"vertex",n),s&&(s.projectId&&(process.env.GOOGLE_CLOUD_PROJECT=String(s.projectId)),s.location&&(process.env.GOOGLE_CLOUD_LOCATION=String(s.location)),s.apiKey&&(process.env.GOOGLE_API_KEY=String(s.apiKey),!s.projectId&&!s.location&&(this.expressApiKey=String(s.apiKey))),s.baseURL&&(this.baseURL=String(s.baseURL)));const i=!!this.resolveExpressApiKey();i||vEt()||yi(aur()),this.projectId=s?.projectId||(i?"":lJ()),this.location=o||s?.location||Fb(),p.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),p.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return wf()}async getAISDKModel(){throw new be({code:ze.INVALID_CONFIGURATION,message:"GoogleVertexProvider no longer uses @ai-sdk/google-vertex. All models use native SDKs: @google/genai for Gemini, @anthropic-ai/vertex-sdk for Claude.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}validateStreamOptionsOnly(t){this.validateStreamOptions(t)}async preprocessNativeFileInput(t){if(t.input&&S7(t.input),t.input?.files?.length)try{await _7(t,100*1024*1024,this.providerName)}catch(r){p.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${r instanceof Error?r.message:String(r)}`)}await b_(t.input)}async executeStream(t,r){const n=t.model||this.modelName||wf();return FPe({name:"neurolink.provider.stream",tracer:Le.provider,attributes:{[we.GEN_AI_SYSTEM]:this.providerName,[we.GEN_AI_MODEL]:n,[we.GEN_AI_OPERATION]:"stream",[we.NL_PROVIDER]:this.providerName}},async o=>{const s=Date.now(),i=t.tools||{};await this.preprocessNativeFileInput(t);const c={...await ct({name:"neurolink.message.build",tracer:Le.provider,attributes:{[we.NL_PROVIDER]:this.providerName,"message.count":1,"message.build.count":1,"message.build.path":"vertex.native.stream"}},async()=>this.processCSVFilesForNativeSDK(t)),tools:i};try{let l;nD(n)?(p.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(i).length}),l=await this.executeNativeAnthropicStream(c)):(p.info("[GoogleVertex] Routing Gemini model to native @google/genai",{model:n,totalToolCount:Object.keys(i).length}),l=await this.executeNativeGemini3Stream(c)),this.attachUsageAndCostAttributes(o,n,l?.usage);const u=this.wrapStreamResultWithLifecycle(t,l,s);return this.emitStreamEnd(n,s,!0,void 0,l.finishReason),u}catch(l){throw this.fireGenerateOnError(t,l,s),this.emitStreamEnd(n,s,!1,l),l}},o=>o.stream,(o,s)=>this.preserveStreamResultAccessors(o,{...o,stream:s}))}emitStreamEnd(t,r,n,o,s){const i=this.neurolink?.getEventEmitter();i&&i.emit("stream:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:t,provider:this.providerName,finishReason:n?s??"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async createVertexGenAIClient(t){kmt("GoogleVertex");const r=this.resolveExpressApiKey(),n=r?"":this.projectId,o=t||this.location||Fb(),i=(await Promise.resolve().then(()=>(WE(),Ey))).GoogleGenAI;if(!i)throw new be({code:ze.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const a=i,c=this.resolveBaseURL(),l={...c?{baseUrl:c}:{}};return r?new a({vertexai:!0,apiKey:r,httpOptions:l}):new a({vertexai:!0,project:n,location:o,httpOptions:l})}resolveBaseURL(){const t=this.baseURL?.trim()||process.env.GOOGLE_VERTEX_BASE_URL?.trim();return t&&t.length>0?t:void 0}resolveExpressApiKey(){const t=this.expressApiKey?.trim();if(t)return t;const r=process.env.GOOGLE_VERTEX_API_KEY?.trim();return r?["GOOGLE_CLOUD_PROJECT_ID","VERTEX_PROJECT_ID","GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT"].some(o=>(process.env[o]??"").trim().length>0)?void 0:r:void 0}buildAnthropicToolDeclaration(t,r){const n={name:t,description:r.description||`Tool: ${t}`,input_schema:{type:"object"}},s=r.parameters||r.inputSchema;if(s){const i=Mo(s),a=On(i);n.input_schema={type:"object",properties:a.properties||{},required:a.required||[]}}return n}refreshAnthropicToolDeclarations(t,r,n,o){if(!t||!r)return;const s=new Set(r.map(i=>i.name));for(const[i,a]of Object.entries(t))s.has(i)||(r.push(this.buildAnthropicToolDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),p.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Anthropic declarations.`))}resolveAnthropicToolOnMiss(t,r,n,o,s){if(!n)return;const i=cUe(r,t);if(i?.execute)return n.some(a=>a.name===t)||n.push(this.buildAnthropicToolDeclaration(t,i)),o.set(t,i.execute),s.delete(t),p.info(`[GoogleVertex] Tool "${t}" resolved mid-turn via discovery \u2014 executing.`),o.get(t)}buildFinalResultTool(t){const r=Mo(t),n=On(r);n.$schema&&delete n.$schema;const o=Fi(n);return{name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",input_schema:{type:"object",properties:o.properties||o,required:o.required||[]}}}async executeNativeGemini3Stream(t){const r=t.model||this.modelName||wf(),n=V0(r,t.region),o=await this.createVertexGenAIClient(n);p.debug("[GoogleVertex] Using native @google/genai for Gemini 3",{model:r,hasTools:!!t.tools&&Object.keys(t.tools).length>0,project:this.projectId,location:n});const s=[],i=[{text:t.input.text??""}],a=t.input;if(a?.pdfFiles&&a.pdfFiles.length>0){p.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(const ke of a.pdfFiles){let Ke;typeof ke=="string"?Ro.existsSync(ke)?Ke=Ro.readFileSync(ke):Ke=Buffer.from(ke,"base64"):Ke=ke;const oe=Ke.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:oe}})}}if(await k9(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){p.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(const ke of a.images){const Ke=s_(ke);let oe,Y="image/jpeg";if(typeof Ke=="string")if(Ro.existsSync(Ke)){oe=Ro.readFileSync(Ke);const K=u_(Ke);Y=K.startsWith("image/")?K:this.detectImageType(oe)}else if(Ke.startsWith("data:")){const K=Ke.match(/^data:([^;]+);base64,(.+)$/);if(K)Y=K[1],oe=Buffer.from(K[2],"base64");else continue}else if(Ke.startsWith("http://")||Ke.startsWith("https://"))try{const K=await fetch(Ke);if(!K.ok){p.warn(`[GoogleVertex] Image fetch failed: ${K.status} ${K.statusText}, skipping`,{url:Qr(Ke)});continue}const J=await K.arrayBuffer();oe=Buffer.from(J);const ie=K.headers.get("content-type");ie&&ie.startsWith("image/")&&(Y=ie.split(";")[0])}catch(K){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${K instanceof Error?K.message:String(K)}`,{url:Qr(Ke)});continue}else oe=Buffer.from(Ke,"base64"),Y=this.detectImageType(oe);else oe=Ke,Y=this.detectImageType(oe);const Q=oe.toString("base64");i.push({inlineData:{mimeType:Y,data:Q}})}}EP(s,t.conversationMessages),s.push({role:"user",parts:i});let c;const l=new h0;let u;if(t.tools&&Object.keys(t.tools).length>0&&!t.disableTools){const ke=y0(t.tools,"functionDeclarations");u=ke,c=ke.toolsConfig;for(const[Ke,oe]of ke.executeMap)l.set(Ke,oe);p.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ke.toolsConfig[0].functionDeclarations.length,toolNames:ke.toolsConfig[0].functionDeclarations.map(Ke=>Ke.name)})}const d=t;let m=!1;if(d.schema&&c){m=!0;const ke=Mo(d.schema,"openApi3"),Ke=On(ke);Ke.$schema&&delete Ke.$schema;const oe=Fi(Ke),Y=c[0]?.functionDeclarations||[];Y.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:oe}),c=[{functionDeclarations:Y}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(oe),totalTools:Y.length})}const h=Ql(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),f={...h.temperature!==void 0&&{temperature:h.temperature},maxOutputTokens:t.maxTokens};u9(r)&&(f.maxOutputTokens&&f.maxOutputTokens>ma&&(p.warn(`[GoogleVertex] Capping maxOutputTokens from ${f.maxOutputTokens} to ${ma} for ${r}`),f.maxOutputTokens=ma),f.maxOutputTokens||(f.maxOutputTokens=ma)),h.topP!==void 0&&(f.topP=h.topP),t.topK!==void 0&&(f.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(f.stopSequences=t.stopSequences),c&&(f.tools=c);let g=t.systemPrompt||"";m&&(g=g+`
1075
1075
 
1076
1076
  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.`),g&&(f.systemInstruction=g);const y=b9(t.thinkingConfig);if(y&&(f.thinkingConfig=y),(d.output?.format==="json"||d.schema)&&!m&&!c&&(f.responseMimeType="application/json",d.schema)){const ke=Mo(d.schema,"openApi3"),Ke=On(ke);Ke.$schema&&delete Ke.$schema;const oe=Fi(Ke);vf(oe),f.responseSchema=oe,p.debug("[GoogleVertex] Added responseSchema for JSON output (stream)",{schemaKeys:Object.keys(oe)})}const w=Date.now(),E=t.maxSteps||Ds,_=Number.isFinite(E)&&E>0?Math.min(Math.floor(E),100):Math.min(Ds,100),b=[...s];let A="",k;const R=[],I=[];let x;const M=p0(rd("vertex",r));let N=!1,U=0,P=0,D=0,$=0;const F=[],z=Jc(t.timeout)??kS,q=bS(t.toolTimeoutMs),j=t.turnTimeoutMs??z,W=new AbortController,H=()=>W.abort();t.abortSignal?.addEventListener("abort",H);const se=TP({turnTimeoutMs:t.turnTimeoutMs,defaultTurnTimeoutMs:z,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:ke=>{p.warn(ke==="timeout"?`[GoogleVertex] Native Gemini turn exceeded its ${j}ms time budget \u2014 aborting`:`[GoogleVertex] Native Gemini turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),W.abort()}}),fe=W.signal;t.abortSignal?.aborted&&W.abort();let ue=!1,V=!1,ge=!1,ye=0;try{const ke=bP({providerLabel:"GoogleVertex",maxSteps:_,toolFailureBreaker:{maxRetries:mh,consecutive:!0,classifyResultFailure:ie=>ZM(ie)??void 0},liveTools:t.tools??{},toolGuards:{toolTimeoutMs:q,abortSignal:fe,onProgress:()=>se.noteProgress()},...u?{declarations:u}:{},...m?{finalResultToolName:"final_result",onTerminalResult:ie=>{try{x=JSON.parse(ie)}catch{}}}:{},enableMalformedRetry:!0,buildMalformedRetryNote:(ie,pe)=>(this.emitTurnEvent({phase:"malformed-retry",step:pe+1,maxSteps:_}),[...ie,{role:"user",parts:[{text:"Your previous function call was malformed and could not be parsed. Re-issue it as a single valid function call, or answer in plain text."}]}]),collectStep:(ie,pe)=>gEt(ie,pe,{onProgress:()=>se.noteProgress(),onUsage:(ce,Ae)=>M.noteUsage(ce,Ae),onUsageDelta:(ce,Ae)=>{ce==="input"?U+=Ae:ce==="output"?P+=Ae:ce==="cacheRead"?D+=Ae:$+=Ae}}),planReclaim:ie=>{if(!M.shouldStop())return;const pe=[...ie];return hEt(pe,r,M.projectedNextPromptTokens)?(M.resetAfterReclaim(),{conversation:pe}):(N=!0,p.warn(`[GoogleVertex] Gemini turn stopped by the context guard: projected prompt ~${M.projectedNextPromptTokens} tokens >= threshold ${M.thresholdTokens} \u2014 synthesizing a final answer.`),{stop:!0})},buildRequest:ie=>({model:r,contents:ie,config:{...f,...c?{tools:c}:{}}}),sendStep:async(ie,pe)=>{se.noteProgress();const ce=ie;return o.models.generateContentStream({model:ce.model,contents:ce.contents,config:{...ce.config??{},abortSignal:pe}})}}),Ke={...ke,buildStepRequest:(ie,pe)=>(ye=pe+1,ke.buildStepRequest(ie,pe)),buildToolResultMessages:(ie,pe,ce,Ae)=>{const Oe=ke.buildToolResultMessages(ie,pe,ce,Ae);if(se.shouldNudgeWrapup()){const re=Oe[Oe.length-1];re&&Array.isArray(re.parts)&&re.parts.push({text:vP(m)})}const C=yP(pe.raw.rawResponseParts);xt(this.handleToolExecutionStorage(ce.map((re,Ee)=>({toolName:re.name,args:re.args,...Ee===0&&C?{thoughtSignature:C}:{},stepIndex:Ae+1})),ce.map(re=>({toolName:re.name,output:re.output,stepIndex:Ae+1})),t,new Date),ph,"tool storage write timed out").catch(re=>{p.warn("[GoogleVertex] Failed to store native Gemini stream tool executions",{error:re instanceof Error?re.message:String(re)})});try{const re=Oe[Oe.length-1];M.noteAppendedChars(JSON.stringify(re?.parts??[]).length)}catch{}return Oe}},{stream:oe,resultPromise:Y}=dd(Ke,b,{tools:gP(u,t.tools,{toolTimeoutMs:q,abortSignal:fe,onProgress:()=>se.noteProgress()}),abortSignal:fe,toolTimeoutMs:q}),Q=(async()=>{for await(const ie of oe)ie.content&&F.push(ie.content)})();let K,J;try{K=await Y}catch(ie){J=ie}if(await Vh(Q,"GoogleVertex"),J!==void 0)if(fe.aborted||qm(J))ue=!0;else throw p.error("[GoogleVertex] Native SDK error",J),this.handleProviderError(J);if(K){A=K.text,k=K.rawStopReason??k;for(const ie of K.toolCalls)R.push({toolName:ie.name,args:ie.args});for(const ie of K.toolExecutions)I.push({name:ie.name,input:ie.input,output:ie.output});b.length=0,b.push(...K.conversation)}if(fe.aborted&&(ue=!0),!A&&(ye>=_||ue||N)){V=ye>=_&&!ue;const ie=R.filter(pe=>pe.toolName!=="final_result").length;if(F.length>0)p.warn(N?"[GoogleVertex] Tool call loop stopped by the context guard; returning text already gathered from prior steps.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${_}); returning text already gathered from prior steps.`);else if(ue)p.warn(`[GoogleVertex] Tool call loop ended mid-turn (${se.timedOut?"turn time limit":se.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),A=this.buildLoopExitMessage({turnClock:se,wasAborted:ue,stallTimeoutMs:t.stallTimeoutMs,maxSteps:_,toolCallCount:ie});else{p.warn(N?"[GoogleVertex] Tool call loop stopped by the context guard with no text; synthesizing a final answer with tools disabled.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${_}) with no text; synthesizing a final answer with tools disabled.`);const pe=await this.synthesizeFinalAnswerWithoutTools(o,r,f,b,m,Jc(t.timeout)??kS,fe);pe.text?(ge=!0,A=pe.text,F.push(pe.text),U+=pe.inputTokens,P+=pe.outputTokens,$+=pe.reasoningTokens??0,pe.finishReason&&(k=pe.finishReason)):A=N?_c(ie):jm(_,ie)}}}finally{se.dispose(),t.abortSignal?.removeEventListener("abort",H)}const Se=V&&!ge?"tool-calls":C9(k),xe=wP({timedOut:se.timedOut,stalled:se.stalled,wasAborted:ue,cappedWithoutAnswer:V&&!ge,contextCappedWithoutAnswer:N&&!ge,finishReason:Se});xe!=="completed"&&this.emitTurnEvent({phase:xe,step:ye,maxSteps:_,toolCallCount:R.filter(ke=>ke.toolName!=="final_result").length,elapsedMs:se.elapsedMs()});const Te=Date.now()-w,Fe=x?[A]:F.length>0?F:[A];async function*De(){for(const ke of Fe)ke.length>0&&(yield{content:ke})}const We=R.filter(ke=>ke.toolName!=="final_result"),Ze=I.filter(ke=>ke.name!=="final_result"),Pt=Math.max(0,U-D),Me={stream:De(),provider:this.providerName,model:r,finishReason:Se,stopReason:xe,rawFinishReason:k,usage:{input:Pt,output:P+$,total:Pt+D+P+$,...D>0&&{cacheReadTokens:D},...$>0&&{reasoning:$}},toolCalls:We.map(ke=>({toolName:ke.toolName,args:ke.args})),toolsUsed:We.map(ke=>ke.toolName),toolExecutions:Th(Ze),metadata:{streamId:`native-vertex-${Date.now()}`,startTime:w,responseTime:Te,totalToolExecutions:We.length,stopReason:xe,rawFinishReason:k,stepsUsed:ye}};return x&&(Me.structuredOutput=x),Me}async executeNativeGemini3Generate(t){const r=t.model||this.modelName||wf(),n=V0(r,t.region),o=await this.createVertexGenAIClient(n);p.debug("[GoogleVertex] Using native @google/genai for Gemini 3 generate",{model:r,project:this.projectId,location:n});const s=t.input?.text||t.prompt||"Please respond.",i=[],a=[{text:s}],c=t.input;if(c?.pdfFiles&&c.pdfFiles.length>0){p.debug(`[GoogleVertex] Processing ${c.pdfFiles.length} PDF file(s) for native generate`);for(const Me of c.pdfFiles){let ke;typeof Me=="string"?Ro.existsSync(Me)?ke=Ro.readFileSync(Me):ke=Buffer.from(Me,"base64"):ke=Me;const Ke=ke.toString("base64");a.push({inlineData:{mimeType:"application/pdf",data:Ke}})}}if(await k9(a,c?.nativeAudioFiles,"[GoogleVertex]"),c?.images&&c.images.length>0){p.debug(`[GoogleVertex] Processing ${c.images.length} image(s) for native generate`);for(const Me of c.images){const ke=s_(Me);let Ke,oe="image/jpeg";if(typeof ke=="string")if(Ro.existsSync(ke)){Ke=Ro.readFileSync(ke);const Q=u_(ke);oe=Q.startsWith("image/")?Q:this.detectImageType(Ke)}else if(ke.startsWith("data:")){const Q=ke.match(/^data:([^;]+);base64,(.+)$/);if(Q)oe=Q[1],Ke=Buffer.from(Q[2],"base64");else continue}else if(ke.startsWith("http://")||ke.startsWith("https://"))try{const Q=await fetch(ke);if(!Q.ok){p.warn(`[GoogleVertex] Image fetch failed: ${Q.status} ${Q.statusText}, skipping`,{url:Qr(ke)});continue}const K=await Q.arrayBuffer();Ke=Buffer.from(K);const J=Q.headers.get("content-type");J&&J.startsWith("image/")&&(oe=J.split(";")[0])}catch(Q){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${Q instanceof Error?Q.message:String(Q)}`,{url:Qr(ke)});continue}else Ke=Buffer.from(ke,"base64"),oe=this.detectImageType(Ke);else Ke=ke,oe=this.detectImageType(Ke);const Y=Ke.toString("base64");a.push({inlineData:{mimeType:oe,data:Y}})}}EP(i,t.conversationMessages),i.push({role:"user",parts:a});const l=t.disableTools?{}:t.tools||{};let u;const d=new h0;let m;if(Object.keys(l).length>0){const Me=y0(l,"functionDeclarations");m=Me,u=Me.toolsConfig;for(const[ke,Ke]of Me.executeMap)d.set(ke,Ke);p.debug("[GoogleVertex] Converted tools for native SDK generate",{toolCount:Me.toolsConfig[0].functionDeclarations.length,toolNames:Me.toolsConfig[0].functionDeclarations.map(ke=>ke.name)})}let h=!1;if(t.schema&&u){h=!0;const Me=Mo(t.schema,"openApi3"),ke=On(Me);ke.$schema&&delete ke.$schema;const Ke=Fi(ke),oe=u[0]?.functionDeclarations||[];oe.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:Ke}),u=[{functionDeclarations:oe}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (generate)",{schemaKeys:Object.keys(Ke),totalTools:oe.length})}const f=Ql(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),g={...f.temperature!==void 0&&{temperature:f.temperature},maxOutputTokens:t.maxTokens};u9(r)&&(g.maxOutputTokens&&g.maxOutputTokens>ma&&(p.warn(`[GoogleVertex] Capping maxOutputTokens from ${g.maxOutputTokens} to ${ma} for ${r}`),g.maxOutputTokens=ma),g.maxOutputTokens||(g.maxOutputTokens=ma)),f.topP!==void 0&&(g.topP=f.topP),t.topK!==void 0&&(g.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(g.stopSequences=t.stopSequences),u&&(g.tools=u);let y=t.systemPrompt||"";h&&(y=y+`
1077
1077
 
@@ -183,10 +183,19 @@ export class AmazonBedrockProvider extends BaseProvider {
183
183
  }
184
184
  else {
185
185
  logger.debug(`[AmazonBedrockProvider] Text-only input in generate(), using simple message builder`);
186
- // Add user message to conversation - simple text-only case
186
+ // Add user message to conversation - simple text-only case.
187
+ // The public generate contract accepts either `prompt` or `input.text`
188
+ // (see BaseProvider); reading only `prompt` here sent an empty user
189
+ // message whenever a caller used the `input.text` shape.
190
+ //
191
+ // `||`, not `??`, to match the canonical resolution in
192
+ // `Utilities.normalizeTextOptions`. This provider overrides `generate()`
193
+ // outright, so normalization never runs and the caller's raw options
194
+ // land here — an empty `prompt` must fall through to `input.text`
195
+ // rather than win by virtue of not being nullish.
187
196
  const userMessage = {
188
197
  role: "user",
189
- content: [{ text: options.prompt }],
198
+ content: [{ text: options.prompt || input?.text || "" }],
190
199
  };
191
200
  this.conversationHistory.push(userMessage);
192
201
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "12.14.11",
3
+ "version": "12.14.12",
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": {