@juspay/neurolink 12.14.16 → 12.14.18

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,11 +1,8 @@
1
- ## [12.14.16](https://github.com/juspay/neurolink/compare/v12.14.15...v12.14.16) (2026-09-17)
1
+ ## [12.14.18](https://github.com/juspay/neurolink/compare/v12.14.17...v12.14.18) (2026-09-18)
2
2
 
3
3
  ### Bug Fixes
4
4
 
5
- - **(gemini):** translate thinkingLevel to a numeric budget for Gemini 2.5 ([e157558](https://github.com/juspay/neurolink/commit/e1575587a8c2967197fd04ad00ca59108c9a2596))
6
- - **(streaming):** keep toolsUsed/toolExecutions live through nl.stream() ([8aa8b5f](https://github.com/juspay/neurolink/commit/8aa8b5f4ca2c13048b6a1120ff1fc2c368dfd4f0))
7
- - **(vertex):** stop dropping Claude extended-thinking output on Vertex ([033a488](https://github.com/juspay/neurolink/commit/033a4881271a1dd833ec0bf719a4b002beca167f))
8
- - **(vertex):** stop suggesting the model that just failed ([ce2de34](https://github.com/juspay/neurolink/commit/ce2de3484085bcc4ad1fd73a8fa9b03a3a6ca2ca))
5
+ - **(proxy):** handle Claude Code tool additions in Codex fallback ([5a52baf](https://github.com/juspay/neurolink/commit/5a52baf19da76f3896949f3fefe0026032bc9b83))
9
6
 
10
7
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
11
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 HRr(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 VRr({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=0,x=0,M=!1;for await(const j of l){if(n.aborted)break;const H=j;if(H.type==="message_start"){const W=H.message?.usage;w+=W?.input_tokens??0;const G=W?.output_tokens??0;E+=G-R,R=G;const ee=W?.output_tokens_details?.thinking_tokens??0;I+=ee-x,x=ee,_+=W?.cache_read_input_tokens??0,b+=W?.cache_creation_input_tokens??0,A+=W?.cache_creation?.ephemeral_5m_input_tokens??0,k+=W?.cache_creation?.ephemeral_1h_input_tokens??0,s?.((W?.input_tokens??0)+(W?.cache_read_input_tokens??0)+(W?.cache_creation_input_tokens??0));continue}if(H.type==="content_block_start"){const W=H.index??0;if(H.content_block?.type==="redacted_thinking"){const G=H.content_block.data;typeof G=="string"&&h.set(W,G)}H.content_block?.type==="tool_use"&&d.set(W,{id:H.content_block.id??"",name:H.content_block.name??"",inputJson:""});continue}if(H.type==="content_block_delta"){const W=H.index??0,G=H.delta;if(G?.type==="text_delta"&&G.text)f+=G.text,u.set(W,(u.get(W)??"")+G.text),r.push({content:G.text});else if(G?.type==="thinking_delta"&&G.thinking){const ee=m.get(W)??{text:"",signature:""};ee.text+=G.thinking,m.set(W,ee),g+=G.thinking,r.push({content:"",reasoning:G.thinking})}else if(G?.type==="signature_delta"&&G.signature){const ee=m.get(W)??{text:"",signature:""};ee.signature+=G.signature,m.set(W,ee)}else if(G?.type==="input_json_delta"&&G.partial_json){const ee=d.get(W);ee&&(ee.inputJson+=G.partial_json)}continue}if(H.type==="message_delta"){y=H.delta?.stop_reason??y;const W=H.usage?.output_tokens??R;E+=W-R,R=W;const G=H.usage?.output_tokens_details?.thinking_tokens??x;I+=G-x,x=G;continue}H.type==="message_stop"&&(M=!0)}if(o?.aborted)throw o.reason;if(c&&!M&&!n.aborted)throw new Ae({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 O=j=>{if(!j)return{};try{const H=JSON.parse(j);return typeof H=="object"&&H!==null&&!Array.isArray(H)?H:{}}catch{return{}}},U=[],P=new Set([...u.keys(),...d.keys(),...m.keys(),...h.keys()]);for(const j of[...P].sort((H,W)=>H-W)){const H=h.get(j);H&&U.push({type:"redacted_thinking",data:H});const W=m.get(j);W?.text&&W.signature&&U.push({type:"thinking",thinking:W.text,signature:W.signature});const G=u.get(j);G&&U.push({type:"text",text:G});const ee=d.get(j);ee&&U.push({type:"tool_use",id:ee.id,name:ee.name,input:O(ee.inputJson)})}const N=[...d.values()].map(j=>({id:j.id,name:j.name,args:O(j.inputJson)})),$=i?[...d.values()].find(j=>j.name===i):void 0,F=$?[]:N,q=$?jRr($.inputJson):f;return $&&a?.(q),{text:q,...g?{reasoning:g}:{},toolCalls:F,usage:{inputTokens:w,outputTokens:E,cacheReadTokens:_,cacheWriteTokens:b,...A?{cacheWrite5mTokens:A}:{},...k?{cacheWrite1hTokens:k}:{},...I?{reasoningTokens:I}:{}},rawStopReason:y,raw:U}}function VK(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=H8(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=o5(n,s?.controller.signal);try{return await VRr({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}`:HK(i.output),...i.error?{is_error:!0}:{}}))};return[...t,o,s]},mapFinishReason:HRr}}var jwt=S({"src/lib/providers/anthropic/loopAdapter.ts"(){"use strict";zS(),Uwt(),qwt(),ia(),et()}});function WK(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 Z4(e,t){if(e instanceof ArrayBuffer)return Z4(new Uint8Array(e),t);if(e instanceof Uint8Array)return{type:"image",source:{type:"base64",media_type:X4(t)??WK(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=X4(n[1])??JK(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:X4(t)??JK(r)??"image/png",data:r}}}function WRr(e){const t=e?.data;if(t==null)return;const r=typeof e.mediaType=="string"?e.mediaType.toLowerCase().split(";")[0].trim():"";if(KK.has(r)||r==="image/jpg")return Z4(t,r);if(r==="application/pdf")return YK(t);const n=t instanceof ArrayBuffer?new Uint8Array(t):t instanceof Uint8Array?t:void 0;if(n&&WK(n))return Z4(n)}var KK,X4,Hwt,JK,YK,KRr=S({"src/lib/providers/anthropicImageBlocks.ts"(){"use strict";KK=new Set(["image/jpeg","image/png","image/gif","image/webp"]),X4=e=>{if(!e)return;const t=e.toLowerCase().split(";")[0].trim();return t==="image/jpg"?"image/jpeg":KK.has(t)?t:void 0},Hwt=32,JK=e=>{try{return WK(Buffer.from(e.slice(0,Hwt),"base64"))}catch{return}},YK=e=>{if(e instanceof ArrayBuffer)return YK(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}}}}}}),Q4,Vwt=S({"src/lib/providers/anthropic/constants.ts"(){"use strict";Q4={"anthropic-beta":["claude-code-20250219","fine-grained-tool-streaming-2025-05-14"].join(",")}}}),ZK,H0,Wwt,XK,Kwt,Jwt,QK,eJ,tJ,rJ,Ywt,JRr=S({"src/lib/providers/anthropic/client.ts"(){"use strict";Ayt(),Kt(),Cn(),bi(),hr(),Db(),QF(),_c(),Lo(),Ipt(),Ewt(),xRr(),Wn(),$Rr(),dt(),Qs(),B(),k9(),Owt(),od(),ni(),Qt(),$wt(),rl(),Uwt(),jwt(),cd(),AP(),kV(),zu(),yh(),Am(),vc(),Vo(),ia(),Kh(),aht(),Mpt(),fm(),z7(),ti(),p9(),KRr(),gh(),Km(),g0(),z9(),Vwt(),Imt(),qwt(),Ewt(),ZK=()=>yi(our()),H0=()=>vi("ANTHROPIC_MODEL","claude-sonnet-4-6"),Wwt=lt.getTracer("neurolink.provider.anthropic"),XK=()=>{try{const t=kt(_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}},Kwt=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"},Jwt=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},QK=e=>{const t=[],r=[],n=i=>Array.isArray(i)?i:[i],o=(i,a)=>{const c=pd(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=pd(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=pd(l);a.push({type:"text",text:l.text,...u?{cache_control:u}:{}})}else if(l?.type==="image"||l?.type==="image_url"){const u=Z4(l.image??l.data??l.url);if(u){const d=pd(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)?WRr(l):void 0;if(d){const m=pd(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=pd(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:HK(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}},eJ=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}}}},tJ=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},rJ=6e5,Ywt=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??XK(),i=o?"api_key":r?.authMethod??Jwt(s),a=r?.subscriptionTier??(i==="oauth"?Kwt(s):"api"),c=e||H0();let l=c;!process.env.ANTHROPIC_BASE_URL&&a!=="api"&&!UK(c,a)&&(l=BK(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=ARr(()=>h.accessToken,this.enableBetaFeatures,!1,!0);m=new ff({apiKey:"oauth-authenticated",fetch:kwt(f),timeout:rJ,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??ZK(),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 ff({apiKey:h,defaultHeaders:d,...f&&{baseURL:f},fetch:kwt(Pt()),timeout:rJ,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?Q4["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"]=Q4["anthropic-beta"];return t&&(e["User-Agent"]=gf),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=UK(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 zK(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+pae;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":gf},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:FK}),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=kt(_i(),".neurolink");Ms(d)||L5(d,{recursive:!0});const m=kt(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}),$5(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=QK(i.prompt),c=a.messages;let l=a.system,u=(i.tools??[]).filter(F=>F.type==="function").map(F=>{const q=pd(F);return{name:F.name,...F.description?{description:F.description}:{},input_schema:F.inputSchema??{type:"object",properties:{}},...q?{cache_control:q}:{}}});u&&u.length===0&&(u=void 0);let d=i.toolChoice?eJ(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=Bwt(u,h);u=F.tools,f=F.applied,F.applied&&(l=zwt(l))}const g=i.providerOptions?.anthropic?.thinking;u=B9(u);const y=Nwt({system:l,tools:u,messages:c}),w=Lwt(c,K4-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:cP(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 q=I?.aborted?I.reason:void 0;throw q instanceof Da?q:F}finally{R?.cleanup()}const M=[];let O;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?O=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("")}),O!==void 0){const F=M.filter(q=>q.type==="reasoning");M.length=0,M.push(...F,{type:"text",text:O}),p.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:O.length})}const N=x.usage.cache_read_input_tokens??0,$=x.usage.cache_creation_input_tokens??0;return{content:M,finishReason:{unified:O!==void 0&&tJ(x.stop_reason)==="tool-calls"?"stop":tJ(x.stop_reason),raw:x.stop_reason??"stop"},usage:{inputTokens:{total:x.usage.input_tokens+N+$,noCache:x.usage.input_tokens,cacheRead:N,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:ORr()??{},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:mt,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:mt,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await PRr(()=>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(!OP(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 bV({doGenerate:o,conversation:f,...c?{tools:a}:{},toolsRecord:i,...c&&e.toolChoice?{toolChoice:FP(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=>hy(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:I8(g),toolExecutions:Sh(e,Xu(g)),enhancedWithTools:y.toolsUsed.length>0};return this.finalizeNativeGenerate(w,e,t)}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),LRr(e),FRr(e,this.modelName)}supportsExecutionControl(){return!0}async executeStream(e,t){return NRr(()=>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=ohe([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 Te=await this.buildMessagesForStream(e);if(u=QK(Te),e.schema&&l&&l.length>0){const ve=Bwt(l,Mo(e.schema));l=ve.tools,m=ve.applied,ve.applied&&(u.system=zwt(u.system))}}catch(Te){throw s?.cleanup(),this.handleProviderError(Te)}const h=this.modelName||H0(),f=d&&l&&l.length>0?eJ(FP(e,c,d)):void 0,g=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,y=Wwt.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}=gV();A.then(Te=>{y.setAttribute("gen_ai.usage.input_tokens",Te.promptTokens||0),y.setAttribute("gen_ai.usage.output_tokens",Te.completionTokens||0),Te.cacheReadTokens&&y.setAttribute("gen_ai.usage.cached_input_tokens",Te.cacheReadTokens);const ve=Ba(this.providerName,this.modelName,{input:Te.promptTokens||0,output:Te.completionTokens||0,total:Te.totalTokens||0,...Te.cacheReadTokens?{cacheReadTokens:Te.cacheReadTokens}:{},...Te.cacheCreationTokens?{cacheCreationTokens:Te.cacheCreationTokens}:{}});ve&&ve>0&&y.setAttribute("neurolink.cost",ve)}).catch(()=>{}),k.then(Te=>{y.setAttribute("gen_ai.response.finish_reason",Te||"unknown"),y.end()}).catch(()=>{y.end()});let x;const M=this.client,O=[],U=Date.now(),P={};let N=0,$=0,F=0,q=0,j=null;const H=()=>({promptTokens:N,completionTokens:$,totalTokens:N+F+q+$,...F>0?{cacheReadTokens:F}:{},...q>0?{cacheCreationTokens:q}:{}});let W="",G;const ee=(Te,ve)=>{const Fe=Pe=>{if(typeof Pe=="string")return Pe;try{return JSON.stringify(Pe)??""}catch{return""}};return gr(Fe(Te),"anthropic")+gr(Fe(ve),"anthropic")},le=(async()=>{let Te,ve;const Ne=VK({client:M,maxSteps:w,toolsRecord:c,buildParams:fe=>{if(l){const se=new Set(l.map(Ie=>Ie.name)),ge=Object.fromEntries(Object.entries(c).filter(([Ie])=>!se.has(Ie)));if(Object.keys(ge).length>0){const Ie=y0(ge,"input_schema");Ie&&Ie.length>0&&(l=[...l,...Ie])}}const oe=B9(l),re=Nwt({system:u.system,tools:oe,messages:fe}),pe=Lwt(fe,K4-re),Q=Ql("anthropic",h,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream");return g&&Q.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:pe,max_tokens:cP(h,e.maxTokens),...u.system?{system:u.system}:{},...!g&&Q.temperature!==void 0?{temperature:Q.temperature}:{},...oe&&oe.length>0?{tools:oe}:{},...f?{tool_choice:f}:{},...g?{thinking:g}:{}}},planReclaim:fe=>{const oe=Dwt({conversation:fe,availableInputTokens:nu("anthropic",h,e.maxTokens??void 0),fixedOverheadTokens:ee(u.system,l),provider:"anthropic",observedPromptTokens:Te,previousSentEstimate:ve,onSentEstimate:se=>{ve=se}});if(!oe)return;const re=new Set(oe.drop),pe=new Set(oe.truncate),Q=[];for(let se=0;se<fe.length;se++){if(re.has(se))continue;const ge=fe[se];if(pe.has(se)&&Array.isArray(ge.content)){Q.push({...ge,content:ge.content.map(Ie=>Ie.type==="tool_result"?{...Ie,content:Pwt(typeof Ie.content=="string"?Ie.content:JSON.stringify(Ie.content)??"")}:Ie)});continue}Q.push(ge)}if(re.size>0){let se=Q.findIndex(ge=>Array.isArray(ge.content)&&ge.content.some(Ie=>Ie.type==="tool_use"||Ie.type==="tool_result"));se<0&&(se=Math.min(1,Q.length)),Q.splice(se,0,{role:"user",content:[{type:"text",text:jK}]})}return{conversation:Q}},...r?{requestTimeoutMs:r.requestTimeoutMs,requireTerminalEvent:!0}:{},noteObservedPromptTokens:fe=>{Te=fe},...m?{finalResultToolName:Nb,onTerminalResult:fe=>{G=fe,p.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:fe.length})}}:{}}),xe={...Ne,buildToolResultMessages:(fe,oe,re,pe)=>{for(const ge of re)O.push(ge.name);const Q=re.map(ge=>({type:"tool-call",toolCallId:ge.id,toolName:ge.name,args:ge.args})),se=re.map(ge=>ge.error?{type:"tool-result",toolCallId:ge.id,toolName:ge.name,error:ge.error}:{type:"tool-result",toolCallId:ge.id,toolName:ge.name,result:ge.output});return Rpt(E,se.map(ge=>({toolName:ge.toolName,result:"result"in ge?ge.result:void 0,error:"error"in ge?ge.error:void 0}))),this.handleToolExecutionStorage(Q,se,e,new Date).catch(ge=>{p.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ge instanceof Error?ge.message:String(ge)})}),Ne.buildToolResultMessages(fe,oe,re,pe)}},Ke={};for(const[fe,oe]of Object.entries(c)){const re=oe.execute;re&&(Ke[fe]={execute:async(pe,Q)=>{const se=Q;return re(pe,{toolCallId:se.toolCallId??"",...se.abortSignal?{abortSignal:se.abortSignal}:{},messages:[]})}})}const ut=lt.getActiveSpan(),Tt=r?.beforeStep,Re=Tt?async fe=>{const oe=r?.beforeStepTimeoutMs??B7,re=sa(oe,this.providerName,"stream"),pe=o5(fe.signal,re?.controller.signal);try{return await n5(Promise.resolve(Tt({...fe,signal:pe.signal??fe.signal})),pe.signal??fe.signal)}catch(Q){p.warn("[Anthropic] executionControl.beforeStep failed or timed out; the step cap stands",{error:Q instanceof Error?Q.message:String(Q),stepsCompleted:fe.stepsCompleted});return}finally{pe.dispose(),re?.cleanup()}}:void 0,{stream:ke,resultPromise:qe}=md(xe,u.messages.slice(),{tools:Ke,...a?{abortSignal:a}:{},...ut?{span:ut}:{},...Re?{beforeStep:Re}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}}),ne=(async()=>{for await(const fe of ke)fe.reasoning&&b({content:"",reasoning:fe.reasoning}),fe.content&&(m?W+=fe.content:b({content:fe.content}))})();let J;try{J=await qe}catch(fe){throw await Wh(ne,"Anthropic"),fe}if(await ne,N+=J.usage.inputTokens,$+=J.usage.outputTokens,F+=J.usage.cacheReadTokens??0,q+=J.usage.cacheWriteTokens??0,j=J.rawStopReason??j,J.aborted){const fe=a?.aborted?a.reason:void 0;P.stopReason=fe instanceof Da?"time-limit":"aborted",P.finishReason="other",J.rawStopReason&&(P.rawFinishReason=J.rawStopReason),R(H()),I("other");return}P.finishReason=J.finishReason,J.rawStopReason&&(P.rawFinishReason=J.rawStopReason),J.finishReason==="tool-calls"&&G===void 0&&(P.stopReason="step-cap"),R(H()),I(j??"stop")})().catch(Te=>{throw x=Te,p.error("Anthropic: Stream error",{error:Te instanceof Error?Te.message:String(Te)}),R(H()),I("error"),this.formatProviderError(Te)}).finally(()=>{if(m){const Te=G??W;Te.length>0&&b({content:Te})}s?.cleanup(),_.close()});le.catch(()=>{});const Y=this.providerName;return{stream:async function*(){let Te=0;try{for await(const ve of _.iterable)"content"in ve&&typeof ve.content=="string"&&ve.content.length>0&&Te++,yield ve;if(await le,Te===0&&O.length===0){p.warn(`${Y}: Stream produced no output \u2014 emitting enriched sentinel`);const ve=new Gl({message:"Stream produced no output"}),Fe=await Gh(ve,void 0,x);qh(Fe),yield Fe}}catch(ve){const Fe=await Gh(ve,void 0,x);if(qh(Fe),yield Fe,!Gl.isInstance(ve))throw ve}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],metadata:P,analytics:k.then(async()=>{const Te=await _V.createAnalytics(this.providerName,h,{textStream:(async function*(){})(),usage:A,finishReason:k},Date.now()-U,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),ve=DRr();return ve&&Te&&(this.recordLimitSnapshot(ve),Te.limits=ve),Te})}}async isAvailable(){try{return XK()||ZK(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),Zwt={};te(Zwt,{ANTHROPIC_BETA_HEADERS:()=>Q4,AnthropicProvider:()=>Ywt,ModelAccessError:()=>I$,getModelCapabilities:()=>zK,getRecommendedModelForTier:()=>BK,isModelAvailableForTier:()=>UK});var YRr=S({"src/lib/providers/anthropic/index.ts"(){"use strict";JRr(),Vwt()}}),yf,$s,ZRr,XRr,Xwt,Qwt,eTt,Lb,tTt,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,C1r,k1r,A1r,x1r,I1r,R1r,M1r,P1r,D1r,O1r,N1r,L1r,F1r,rTt=S({"npm-stub:@aws-sdk/client-bedrock-runtime"(){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})}})}},$s=new Proxy({},yf),{BedrockClient:ZRr,ListFoundationModelsCommand:XRr,BedrockRuntimeClient:Xwt,ConverseCommand:Qwt,ConverseStreamCommand:eTt,ImageFormat:Lb,InvokeModelCommand:tTt}=$s,{SageMakerRuntimeClient:QRr,InvokeEndpointCommand:e1r,InvokeEndpointWithResponseStreamCommand:t1r}=$s,{GoogleAuth:r1r,VertexAI:n1r,TextToSpeechClient:o1r}=$s,{Webhook:s1r}=$s,{Hippocampus:i1r,HippocampusConfig:a1r}=$s,{createClient:c1r}=$s,{Queue:l1r,Worker:u1r,Job:d1r,QueueScheduler:m1r,FlowProducer:p1r}=$s,{Cron:h1r}=$s,{parseBuffer:f1r,selectCover:g1r}=$s,{extractRawText:y1r,convertToHtml:v1r}=$s,{Hono:w1r}=$s,{cors:T1r,HTTPException:E1r,logger:S1r,secureHeaders:_1r,streamSSE:b1r,timeout:C1r}=$s,k1r=globalThis.fetch,A1r=globalThis.Request,x1r=globalThis.Response,I1r=globalThis.Headers,R1r=globalThis.FormData,M1r=globalThis.File,P1r=globalThis.Blob,D1r=$s.Agent,O1r=$s.Pool,N1r=$s.Client,L1r=$s.Dispatcher,F1r=$s.MockAgent}});function $1r(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 U1r(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function nTt(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 B1r(e,t){if(e.startsWith("arn:")||U1r(e))return[];const r=[],n=$1r(t);return n&&r.push(`${n}.${e}`),r.push(`${iTt}.${e}`),r}function oTt(e,t){return`${e}::${t}`}function z1r(e,t){return nJ.get(oTt(t,e))}function G1r(e,t,r){nJ.set(oTt(t,e),r),p.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function sTt(e,t,r){const n=z1r(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!nTt(o))throw o;const s=B1r(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 G1r(e,t,i),a}catch(a){if(!nTt(a))throw a}throw o}}var iTt,nJ,q1r=S({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";B(),iTt="global",nJ=new Map}});function eD(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function aTt(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 cTt(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??eD(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function j1r(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??eD()}}if(g.contentBlockDelta?.delta?.toolUse){const y=i(g.contentBlockDelta.contentBlockIndex??0);y.toolUse??={name:"",input:{},toolUseId:eD()};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;aTt(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)aTt(g,s.get(f)??"");const h=n.filter(f=>f.text||f.toolUse||f.image||f.document);return{text:a,toolCalls:cTt(h),usage:{inputTokens:l,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:m},rawStopReason:c,raw:h}}function H1r(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??eD(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:cTt(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 lTt(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 sTt(o.modelId??"",e.region,a=>ze(e.client.send(new Qwt({...o,modelId:a}),{abortSignal:n}),oJ,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return H1r(i)}const s=await sTt(o.modelId??"",e.region,i=>ze(e.client.send(new eTt({...o,modelId:i}),{abortSignal:n}),oJ,new Error("Bedrock streaming API call timed out")));return j1r(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 oJ,V1r=S({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";rTt(),et(),q1r(),oJ=12e4}});function uTt(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 W1r=S({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),tD,dTt=S({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";Ua(),tD=$e.provider}}),mTt={};te(mTt,{Agent:()=>tEt,BedrockClient:()=>hTt,BedrockRuntimeClient:()=>gTt,Blob:()=>eEt,Client:()=>nEt,ConverseCommand:()=>yTt,ConverseStreamCommand:()=>vTt,Cron:()=>LTt,Dispatcher:()=>oEt,File:()=>QTt,FlowProducer:()=>NTt,FormData:()=>XTt,GoogleAuth:()=>bTt,HTTPException:()=>qTt,Headers:()=>ZTt,Hippocampus:()=>xTt,HippocampusConfig:()=>ITt,Hono:()=>zTt,ImageFormat:()=>wTt,InvokeEndpointCommand:()=>STt,InvokeEndpointWithResponseStreamCommand:()=>_Tt,InvokeModelCommand:()=>TTt,Job:()=>DTt,ListFoundationModelsCommand:()=>fTt,MockAgent:()=>aEt,Pool:()=>rEt,Queue:()=>MTt,QueueScheduler:()=>OTt,Request:()=>JTt,Response:()=>YTt,SageMakerRuntimeClient:()=>ETt,TextToSpeechClient:()=>kTt,VertexAI:()=>CTt,Webhook:()=>ATt,Worker:()=>PTt,convertToHtml:()=>BTt,cors:()=>GTt,createClient:()=>RTt,default:()=>pTt,extractRawText:()=>UTt,fetch:()=>KTt,getGlobalDispatcher:()=>iEt,interceptors:()=>cEt,logger:()=>jTt,parseBuffer:()=>FTt,request:()=>lEt,secureHeaders:()=>HTt,selectCover:()=>$Tt,setGlobalDispatcher:()=>sEt,streamSSE:()=>VTt,timeout:()=>WTt});var vf,os,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,rEt,nEt,oEt,sEt,iEt,aEt,cEt,lEt,K1r=S({"npm-stub:@aws-sdk/client-bedrock"(){vf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:vf.get}):new Proxy(function(...r){return new Proxy({},{get:vf.get})},{get:vf.get,apply(r,n,o){return new Proxy({},{get:vf.get})},construct(r,n){return new Proxy({},{get:vf.get})}})}},os=new Proxy({},vf),pTt=os,{BedrockClient:hTt,ListFoundationModelsCommand:fTt,BedrockRuntimeClient:gTt,ConverseCommand:yTt,ConverseStreamCommand:vTt,ImageFormat:wTt,InvokeModelCommand:TTt}=os,{SageMakerRuntimeClient:ETt,InvokeEndpointCommand:STt,InvokeEndpointWithResponseStreamCommand:_Tt}=os,{GoogleAuth:bTt,VertexAI:CTt,TextToSpeechClient:kTt}=os,{Webhook:ATt}=os,{Hippocampus:xTt,HippocampusConfig:ITt}=os,{createClient:RTt}=os,{Queue:MTt,Worker:PTt,Job:DTt,QueueScheduler:OTt,FlowProducer:NTt}=os,{Cron:LTt}=os,{parseBuffer:FTt,selectCover:$Tt}=os,{extractRawText:UTt,convertToHtml:BTt}=os,{Hono:zTt}=os,{cors:GTt,HTTPException:qTt,logger:jTt,secureHeaders:HTt,streamSSE:VTt,timeout:WTt}=os,KTt=globalThis.fetch,JTt=globalThis.Request,YTt=globalThis.Response,ZTt=globalThis.Headers,XTt=globalThis.FormData,QTt=globalThis.File,eEt=globalThis.Blob,tEt=os.Agent,rEt=os.Pool,nEt=os.Client,oEt=os.Dispatcher,sEt=()=>{},iEt=()=>os,aEt=os.MockAgent,cEt={redirect:()=>e=>e,retry:()=>e=>e},lEt=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 sJ(){return await Promise.resolve().then(()=>(K1r(),mTt))}var uEt=S({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}}),dEt,J1r=S({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";rTt(),hr(),OS(),_c(),Lo(),AP(),Am(),vc(),V1r(),dt(),Qs(),et(),B(),gh(),BM(),W1r(),ti(),Kt(),dTt(),uEt(),dEt=class wrr 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=wrr.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 Xwt({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 sJ(),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 h=uTt(n,this.providerName,this.modelName),f=await FM(h,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(f)}else{p.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const m={role:"user",content:[{text:n.prompt||o?.text||""}]};this.conversationHistory.push(m)}p.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let i,a,c,l,u;try{({text:i,usage:a,finishReason:c,rawFinishReason:l,toolExecutions:u}=await this.conversationLoop(n))}catch(m){const h=this.neurolink?.getEventEmitter();throw h&&h.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:m instanceof Error?m.message:String(m)}),m}const d=this.neurolink?.getEventEmitter();return d&&d.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},toolsUsed:u.map(m=>m.name),toolCalls:u.map(m=>({toolCallId:m.id,toolName:m.name,args:m.input})),toolExecutions:Sh(n,Xu(u)),enhancedWithTools:u.length>0}}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=lTt({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}=md(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,toolExecutions:c.toolExecutions}}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 tD.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:Le.OK}),u}catch(i){throw p.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:i}),s.setStatus({code:Le.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?ym.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"),tD.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=uTt(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:Le.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:Le.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:Le.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:Le.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=lTt({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}=md(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,O=R?.cacheWriteTokens??0;return{input:I,output:x,total:I+M+O+x,...M>0&&{cacheReadTokens:M},...O>0&&{cacheCreationTokens:O}}};return g.then(R=>{_(Fy(this.providerName,this.modelName||this.getDefaultModel(),{usage:A(R.result?.usage),toolExecutions:R.result?.toolExecutions??[],toolsUsed:(R.result?.toolExecutions??[]).map(I=>I.name)},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 sJ(),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:mt,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:mt,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 tTt({modelId:n,contentType:"application/json",accept:"application/json",body:o}),i=await ze(this.bedrockClient.send(s),6e4,new Error("Bedrock embedding API call timed out")),a=JSON.parse(new TextDecoder().decode(i.body));if(!a.embedding||!Array.isArray(a.embedding))throw new Error("Invalid embedding response from Bedrock");return 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)}}}}}),mEt={};te(mEt,{AmazonBedrockProvider:()=>dEt,bedrockTracer:()=>tD,loadBedrockControl:()=>sJ});var Y1r=S({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";J1r(),dTt(),uEt()}}),pEt={};te(pEt,{AzureOpenAIProvider:()=>hEt});var hEt,Z1r=S({"src/lib/providers/azureOpenai.ts"(){"use strict";dt(),B(),Qs(),Vo(),vc(),Va(),Km(),hEt=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(aur()),d||yi(cur()),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",M$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??_pt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function X1r(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 Q1r=S({"src/lib/utils/imageDetection.ts"(){"use strict"}});function fEt(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 eMr=S({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),rD,tMr=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"(){rD=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}}}),rMr=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 iJ(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var nD,aJ,gEt=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"(){rMr(),nD=e=>(nD=Array.isArray,nD(e)),aJ=nD}});function*nMr(e){if(!e)return;if(cJ 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():aJ(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=aJ(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 cJ,yEt,oMr=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){gEt(),cJ=Symbol.for("brand.privateNullableHeaders"),yEt=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[s,i]of nMr(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{[cJ]:!0,values:t,nulls:r}}}});function sMr(e){const t=new Ab(e);return delete t.batches,t}function iMr(e){const t=new Hi(e);return delete t.messages.batches,t}var vEt,wEt,lJ,TEt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){j4(),_yt(),dP(),tMr(),gEt(),oMr(),j4(),vEt="vertex-2023-10-16",wEt=new Set(["/v1/messages","/v1/messages?beta=true"]),lJ=class extends vo{constructor({baseURL:e=rD("ANTHROPIC_VERTEX_BASE_URL"),region:t=rD("CLOUD_ML_REGION")??null,projectId:r=rD("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=sMr(this),this.beta=iMr(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 E9({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=yEt([r,e.headers])}async buildRequest(e){if(iJ(e.body)&&(e.body={...e.body}),iJ(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=vEt)),wEt.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(!iJ(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)}}}}),uJ={};te(uJ,{AnthropicVertex:()=>lJ,BaseAnthropic:()=>vo,default:()=>lJ});var EEt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){TEt(),TEt()}});async function aMr(){return oD||(oD=await Promise.resolve().then(()=>(EEt(),uJ))),oD}function cMr(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 dJ(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 lMr(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 uMr(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 mJ(e){const t=[];let r=0;for(const n of cMr(e)){if(n.type==="regular"){dJ(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:s}=lMr(n,r);o.length!==0&&(r++,dJ(t,"assistant",o),dJ(t,"user",s))}if(uMr(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 pJ(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 wf(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"&&wf(n);if(e.items&&typeof e.items=="object")if(Array.isArray(e.items))for(const n of e.items)n&&typeof n=="object"&&wf(n);else wf(e.items);for(const n of["allOf","anyOf","oneOf"])if(Array.isArray(e[n]))for(const o of e[n])o&&typeof o=="object"&&wf(o)}function SEt(e,t,r){const n=Cmt({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<=xEt?l:{functionResponse:{name:u.name,response:{result:F9(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:U9}]})}return e.length=0,e.push(...i),!0}function _Et(e,t,r){const n=Dwt({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:Pwt(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:jK}]})}return e.length=0,e.push(...i),!0}async function bEt(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 oD,CEt,hJ,Fb,fJ,V0,Tf,kEt,AEt,sD,xEt,gJ,dMr=S({"src/lib/providers/googleVertex/client.ts"(){"use strict";Cn(),yP(),hr(),_c(),Jj(),CP(),iYe(),Lo(),yh(),Th(),O9(),Qt(),Wn(),dt(),Qs(),et(),$wt(),Lct(),BM(),B(),k9(),Amt(),Owt(),iP(),Q1r(),p9(),Vo(),ti(),umt(),Kh(),ia(),xmt(),wmt(),AP(),jwt(),I_(),g0(),z9(),od(),zS(),Ua(),Kt(),rl(),vc(),Am(),gh(),eMr(),I_(),oD=null,CEt=()=>!0,hJ=()=>yi(yur()),Fb=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",fJ=(e,t)=>{const r=t||Fb();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||Kq.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},V0=fJ,Tf=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",kEt=()=>!!(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),AEt=async(e,t,r,n)=>{const o=e||Fb();return{projectId:r?r.projectId?.trim()||"express":hJ(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},sD=e=>e.toLowerCase().includes("claude"),xEt=2048,gJ=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||kEt()||yi(vur()),this.projectId=s?.projectId||(i?"":hJ()),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 Tf()}async getAISDKModel(){throw new Ae({code:Ge.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&&b7(t.input),t.input?.files?.length)try{await C7(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||Tf();return GPe({name:"neurolink.provider.stream",tracer:$e.provider,attributes:{[_e.GEN_AI_SYSTEM]:this.providerName,[_e.GEN_AI_MODEL]:n,[_e.GEN_AI_OPERATION]:"stream",[_e.NL_PROVIDER]:this.providerName}},async o=>{const s=Date.now(),i=t.tools||{};await this.preprocessNativeFileInput(t);const c={...await at({name:"neurolink.message.build",tracer:$e.provider,attributes:{[_e.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;sD(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){Nmt("GoogleVertex");const r=this.resolveExpressApiKey(),n=r?"":this.projectId,o=t||this.location||Fb(),i=(await Promise.resolve().then(()=>(WE(),Sy))).GoogleGenAI;if(!i)throw new Ae({code:Ge.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=pUe(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||Tf(),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 qe;typeof ke=="string"?Ro.existsSync(ke)?qe=Ro.readFileSync(ke):qe=Buffer.from(ke,"base64"):qe=ke;const ne=qe.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:ne}})}}if(await R9(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 qe=s_(ke);let ne,J="image/jpeg";if(typeof qe=="string")if(Ro.existsSync(qe)){ne=Ro.readFileSync(qe);const oe=u_(qe);J=oe.startsWith("image/")?oe:this.detectImageType(ne)}else if(qe.startsWith("data:")){const oe=qe.match(/^data:([^;]+);base64,(.+)$/);if(oe)J=oe[1],ne=Buffer.from(oe[2],"base64");else continue}else if(qe.startsWith("http://")||qe.startsWith("https://"))try{const oe=await fetch(qe);if(!oe.ok){p.warn(`[GoogleVertex] Image fetch failed: ${oe.status} ${oe.statusText}, skipping`,{url:Qr(qe)});continue}const re=await oe.arrayBuffer();ne=Buffer.from(re);const pe=oe.headers.get("content-type");pe&&pe.startsWith("image/")&&(J=pe.split(";")[0])}catch(oe){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${oe instanceof Error?oe.message:String(oe)}`,{url:Qr(qe)});continue}else ne=Buffer.from(qe,"base64"),J=this.detectImageType(ne);else ne=qe,J=this.detectImageType(ne);const fe=ne.toString("base64");i.push({inlineData:{mimeType:J,data:fe}})}}_P(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[qe,ne]of ke.executeMap)l.set(qe,ne);p.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ke.toolsConfig[0].functionDeclarations.length,toolNames:ke.toolsConfig[0].functionDeclarations.map(qe=>qe.name)})}const d=t;let m=!1;if(d.schema&&c){m=!0;const ke=Mo(d.schema,"openApi3"),qe=On(ke);qe.$schema&&delete qe.$schema;const ne=Fi(qe),J=c[0]?.functionDeclarations||[];J.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:ne}),c=[{functionDeclarations:J}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(ne),totalTools:J.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};m9(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}},eJ=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}}}},tJ=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},rJ=6e5,Ywt=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??XK(),i=o?"api_key":r?.authMethod??Jwt(s),a=r?.subscriptionTier??(i==="oauth"?Kwt(s):"api"),c=e||H0();let l=c;!process.env.ANTHROPIC_BASE_URL&&a!=="api"&&!UK(c,a)&&(l=BK(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=ARr(()=>h.accessToken,this.enableBetaFeatures,!1,!0);m=new ff({apiKey:"oauth-authenticated",fetch:kwt(f),timeout:rJ,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??ZK(),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 ff({apiKey:h,defaultHeaders:d,...f&&{baseURL:f},fetch:kwt(Pt()),timeout:rJ,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?Q4["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"]=Q4["anthropic-beta"];return t&&(e["User-Agent"]=gf),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=UK(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 zK(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+pae;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":gf},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:FK}),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=kt(_i(),".neurolink");Ms(d)||L5(d,{recursive:!0});const m=kt(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}),$5(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=QK(i.prompt),c=a.messages;let l=a.system,u=(i.tools??[]).filter(F=>F.type==="function").map(F=>{const q=pd(F);return{name:F.name,...F.description?{description:F.description}:{},input_schema:F.inputSchema??{type:"object",properties:{}},...q?{cache_control:q}:{}}});u&&u.length===0&&(u=void 0);let d=i.toolChoice?eJ(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=Bwt(u,h);u=F.tools,f=F.applied,F.applied&&(l=zwt(l))}const g=i.providerOptions?.anthropic?.thinking;u=B9(u);const y=Nwt({system:l,tools:u,messages:c}),w=Lwt(c,K4-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:cP(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 q=I?.aborted?I.reason:void 0;throw q instanceof Da?q:F}finally{R?.cleanup()}const M=[];let O;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?O=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("")}),O!==void 0){const F=M.filter(q=>q.type==="reasoning");M.length=0,M.push(...F,{type:"text",text:O}),p.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:O.length})}const N=x.usage.cache_read_input_tokens??0,$=x.usage.cache_creation_input_tokens??0;return{content:M,finishReason:{unified:O!==void 0&&tJ(x.stop_reason)==="tool-calls"?"stop":tJ(x.stop_reason),raw:x.stop_reason??"stop"},usage:{inputTokens:{total:x.usage.input_tokens+N+$,noCache:x.usage.input_tokens,cacheRead:N,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:ORr()??{},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:mt,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:mt,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await PRr(()=>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(!OP(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 bV({doGenerate:o,conversation:f,...c?{tools:a}:{},toolsRecord:i,...c&&e.toolChoice?{toolChoice:FP(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=>hy(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:I8(g),toolExecutions:Sh(e,Xu(g)),enhancedWithTools:y.toolsUsed.length>0};return this.finalizeNativeGenerate(w,e,t)}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),LRr(e),FRr(e,this.modelName)}supportsExecutionControl(){return!0}async executeStream(e,t){return NRr(()=>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=ohe([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 Te=await this.buildMessagesForStream(e);if(u=QK(Te),e.schema&&l&&l.length>0){const ve=Bwt(l,Mo(e.schema));l=ve.tools,m=ve.applied,ve.applied&&(u.system=zwt(u.system))}}catch(Te){throw s?.cleanup(),this.handleProviderError(Te)}const h=this.modelName||H0(),f=d&&l&&l.length>0?eJ(FP(e,c,d)):void 0,g=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,y=Wwt.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}=gV();A.then(Te=>{y.setAttribute("gen_ai.usage.input_tokens",Te.promptTokens||0),y.setAttribute("gen_ai.usage.output_tokens",Te.completionTokens||0),Te.cacheReadTokens&&y.setAttribute("gen_ai.usage.cached_input_tokens",Te.cacheReadTokens);const ve=Ba(this.providerName,this.modelName,{input:Te.promptTokens||0,output:Te.completionTokens||0,total:Te.totalTokens||0,...Te.cacheReadTokens?{cacheReadTokens:Te.cacheReadTokens}:{},...Te.cacheCreationTokens?{cacheCreationTokens:Te.cacheCreationTokens}:{}});ve&&ve>0&&y.setAttribute("neurolink.cost",ve)}).catch(()=>{}),k.then(Te=>{y.setAttribute("gen_ai.response.finish_reason",Te||"unknown"),y.end()}).catch(()=>{y.end()});let x;const M=this.client,O=[],U=Date.now(),P={};let N=0,$=0,F=0,q=0,j=null;const H=()=>({promptTokens:N,completionTokens:$,totalTokens:N+F+q+$,...F>0?{cacheReadTokens:F}:{},...q>0?{cacheCreationTokens:q}:{}});let W="",G;const ee=(Te,ve)=>{const Fe=Pe=>{if(typeof Pe=="string")return Pe;try{return JSON.stringify(Pe)??""}catch{return""}};return gr(Fe(Te),"anthropic")+gr(Fe(ve),"anthropic")},le=(async()=>{let Te,ve;const Ne=VK({client:M,maxSteps:w,toolsRecord:c,buildParams:fe=>{if(l){const se=new Set(l.map(Ie=>Ie.name)),ge=Object.fromEntries(Object.entries(c).filter(([Ie])=>!se.has(Ie)));if(Object.keys(ge).length>0){const Ie=y0(ge,"input_schema");Ie&&Ie.length>0&&(l=[...l,...Ie])}}const oe=B9(l),re=Nwt({system:u.system,tools:oe,messages:fe}),pe=Lwt(fe,K4-re),Q=Ql("anthropic",h,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream");return g&&Q.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:pe,max_tokens:cP(h,e.maxTokens),...u.system?{system:u.system}:{},...!g&&Q.temperature!==void 0?{temperature:Q.temperature}:{},...oe&&oe.length>0?{tools:oe}:{},...f?{tool_choice:f}:{},...g?{thinking:g}:{}}},planReclaim:fe=>{const oe=Dwt({conversation:fe,availableInputTokens:nu("anthropic",h,e.maxTokens??void 0),fixedOverheadTokens:ee(u.system,l),provider:"anthropic",observedPromptTokens:Te,previousSentEstimate:ve,onSentEstimate:se=>{ve=se}});if(!oe)return;const re=new Set(oe.drop),pe=new Set(oe.truncate),Q=[];for(let se=0;se<fe.length;se++){if(re.has(se))continue;const ge=fe[se];if(pe.has(se)&&Array.isArray(ge.content)){Q.push({...ge,content:ge.content.map(Ie=>Ie.type==="tool_result"?{...Ie,content:Pwt(typeof Ie.content=="string"?Ie.content:JSON.stringify(Ie.content)??"")}:Ie)});continue}Q.push(ge)}if(re.size>0){let se=Q.findIndex(ge=>Array.isArray(ge.content)&&ge.content.some(Ie=>Ie.type==="tool_use"||Ie.type==="tool_result"));se<0&&(se=Math.min(1,Q.length)),Q.splice(se,0,{role:"user",content:[{type:"text",text:jK}]})}return{conversation:Q}},...r?{requestTimeoutMs:r.requestTimeoutMs,requireTerminalEvent:!0}:{},noteObservedPromptTokens:fe=>{Te=fe},...m?{finalResultToolName:Nb,onTerminalResult:fe=>{G=fe,p.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:fe.length})}}:{}}),xe={...Ne,buildToolResultMessages:(fe,oe,re,pe)=>{for(const ge of re)O.push(ge.name);const Q=re.map(ge=>({type:"tool-call",toolCallId:ge.id,toolName:ge.name,args:ge.args})),se=re.map(ge=>ge.error?{type:"tool-result",toolCallId:ge.id,toolName:ge.name,error:ge.error}:{type:"tool-result",toolCallId:ge.id,toolName:ge.name,result:ge.output});return Rpt(E,se.map(ge=>({toolName:ge.toolName,result:"result"in ge?ge.result:void 0,error:"error"in ge?ge.error:void 0}))),this.handleToolExecutionStorage(Q,se,e,new Date).catch(ge=>{p.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ge instanceof Error?ge.message:String(ge)})}),Ne.buildToolResultMessages(fe,oe,re,pe)}},Ke={};for(const[fe,oe]of Object.entries(c)){const re=oe.execute;re&&(Ke[fe]={execute:async(pe,Q)=>{const se=Q;return re(pe,{toolCallId:se.toolCallId??"",...se.abortSignal?{abortSignal:se.abortSignal}:{},messages:[]})}})}const ut=lt.getActiveSpan(),Tt=r?.beforeStep,Re=Tt?async fe=>{const oe=r?.beforeStepTimeoutMs??B7,re=sa(oe,this.providerName,"stream"),pe=o5(fe.signal,re?.controller.signal);try{return await n5(Promise.resolve(Tt({...fe,signal:pe.signal??fe.signal})),pe.signal??fe.signal)}catch(Q){p.warn("[Anthropic] executionControl.beforeStep failed or timed out; the step cap stands",{error:Q instanceof Error?Q.message:String(Q),stepsCompleted:fe.stepsCompleted});return}finally{pe.dispose(),re?.cleanup()}}:void 0,{stream:ke,resultPromise:qe}=md(xe,u.messages.slice(),{tools:Ke,...a?{abortSignal:a}:{},...ut?{span:ut}:{},...Re?{beforeStep:Re}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}}),ne=(async()=>{for await(const fe of ke)fe.reasoning&&b({content:"",reasoning:fe.reasoning}),fe.content&&(m?W+=fe.content:b({content:fe.content}))})();let J;try{J=await qe}catch(fe){throw await Wh(ne,"Anthropic"),fe}if(await ne,N+=J.usage.inputTokens,$+=J.usage.outputTokens,F+=J.usage.cacheReadTokens??0,q+=J.usage.cacheWriteTokens??0,j=J.rawStopReason??j,J.aborted){const fe=a?.aborted?a.reason:void 0;P.stopReason=fe instanceof Da?"time-limit":"aborted",P.finishReason="other",J.rawStopReason&&(P.rawFinishReason=J.rawStopReason),R(H()),I("other");return}P.finishReason=J.finishReason,J.rawStopReason&&(P.rawFinishReason=J.rawStopReason),J.finishReason==="tool-calls"&&G===void 0&&(P.stopReason="step-cap"),R(H()),I(j??"stop")})().catch(Te=>{throw x=Te,p.error("Anthropic: Stream error",{error:Te instanceof Error?Te.message:String(Te)}),R(H()),I("error"),this.formatProviderError(Te)}).finally(()=>{if(m){const Te=G??W;Te.length>0&&b({content:Te})}s?.cleanup(),_.close()});le.catch(()=>{});const Y=this.providerName;return{stream:async function*(){let Te=0;try{for await(const ve of _.iterable)"content"in ve&&typeof ve.content=="string"&&ve.content.length>0&&Te++,yield ve;if(await le,Te===0&&O.length===0){p.warn(`${Y}: Stream produced no output \u2014 emitting enriched sentinel`);const ve=new Gl({message:"Stream produced no output"}),Fe=await Gh(ve,void 0,x);qh(Fe),yield Fe}}catch(ve){const Fe=await Gh(ve,void 0,x);if(qh(Fe),yield Fe,!Gl.isInstance(ve))throw ve}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],metadata:P,analytics:k.then(async()=>{const Te=await _V.createAnalytics(this.providerName,h,{textStream:(async function*(){})(),usage:A,finishReason:k},Date.now()-U,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),ve=DRr();return ve&&Te&&(this.recordLimitSnapshot(ve),Te.limits=ve),Te})}}async isAvailable(){try{return XK()||ZK(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),Zwt={};te(Zwt,{ANTHROPIC_BETA_HEADERS:()=>Q4,AnthropicProvider:()=>Ywt,ModelAccessError:()=>I$,getModelCapabilities:()=>zK,getRecommendedModelForTier:()=>BK,isModelAvailableForTier:()=>UK});var YRr=S({"src/lib/providers/anthropic/index.ts"(){"use strict";JRr(),Vwt()}}),yf,$s,ZRr,XRr,Xwt,Qwt,eTt,Lb,tTt,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,C1r,k1r,A1r,x1r,I1r,R1r,M1r,P1r,D1r,O1r,N1r,L1r,F1r,rTt=S({"npm-stub:@aws-sdk/client-bedrock-runtime"(){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})}})}},$s=new Proxy({},yf),{BedrockClient:ZRr,ListFoundationModelsCommand:XRr,BedrockRuntimeClient:Xwt,ConverseCommand:Qwt,ConverseStreamCommand:eTt,ImageFormat:Lb,InvokeModelCommand:tTt}=$s,{SageMakerRuntimeClient:QRr,InvokeEndpointCommand:e1r,InvokeEndpointWithResponseStreamCommand:t1r}=$s,{GoogleAuth:r1r,VertexAI:n1r,TextToSpeechClient:o1r}=$s,{Webhook:s1r}=$s,{Hippocampus:i1r,HippocampusConfig:a1r}=$s,{createClient:c1r}=$s,{Queue:l1r,Worker:u1r,Job:d1r,QueueScheduler:m1r,FlowProducer:p1r}=$s,{Cron:h1r}=$s,{parseBuffer:f1r,selectCover:g1r}=$s,{extractRawText:y1r,convertToHtml:v1r}=$s,{Hono:w1r}=$s,{cors:T1r,HTTPException:E1r,logger:S1r,secureHeaders:_1r,streamSSE:b1r,timeout:C1r}=$s,k1r=globalThis.fetch,A1r=globalThis.Request,x1r=globalThis.Response,I1r=globalThis.Headers,R1r=globalThis.FormData,M1r=globalThis.File,P1r=globalThis.Blob,D1r=$s.Agent,O1r=$s.Pool,N1r=$s.Client,L1r=$s.Dispatcher,F1r=$s.MockAgent}});function $1r(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 U1r(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function nTt(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 B1r(e,t){if(e.startsWith("arn:")||U1r(e))return[];const r=[],n=$1r(t);return n&&r.push(`${n}.${e}`),r.push(`${iTt}.${e}`),r}function oTt(e,t){return`${e}::${t}`}function z1r(e,t){return nJ.get(oTt(t,e))}function G1r(e,t,r){nJ.set(oTt(t,e),r),p.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function sTt(e,t,r){const n=z1r(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!nTt(o))throw o;const s=B1r(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 G1r(e,t,i),a}catch(a){if(!nTt(a))throw a}throw o}}var iTt,nJ,q1r=S({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";B(),iTt="global",nJ=new Map}});function eD(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function aTt(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 cTt(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??eD(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function j1r(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??eD()}}if(g.contentBlockDelta?.delta?.toolUse){const y=i(g.contentBlockDelta.contentBlockIndex??0);y.toolUse??={name:"",input:{},toolUseId:eD()};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;aTt(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)aTt(g,s.get(f)??"");const h=n.filter(f=>f.text||f.toolUse||f.image||f.document);return{text:a,toolCalls:cTt(h),usage:{inputTokens:l,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:m},rawStopReason:c,raw:h}}function H1r(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??eD(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:cTt(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 lTt(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 sTt(o.modelId??"",e.region,a=>ze(e.client.send(new Qwt({...o,modelId:a}),{abortSignal:n}),oJ,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return H1r(i)}const s=await sTt(o.modelId??"",e.region,i=>ze(e.client.send(new eTt({...o,modelId:i}),{abortSignal:n}),oJ,new Error("Bedrock streaming API call timed out")));return j1r(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 oJ,V1r=S({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";rTt(),et(),q1r(),oJ=12e4}});function uTt(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 W1r=S({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),tD,dTt=S({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";Ua(),tD=$e.provider}}),mTt={};te(mTt,{Agent:()=>tEt,BedrockClient:()=>hTt,BedrockRuntimeClient:()=>gTt,Blob:()=>eEt,Client:()=>nEt,ConverseCommand:()=>yTt,ConverseStreamCommand:()=>vTt,Cron:()=>LTt,Dispatcher:()=>oEt,File:()=>QTt,FlowProducer:()=>NTt,FormData:()=>XTt,GoogleAuth:()=>bTt,HTTPException:()=>qTt,Headers:()=>ZTt,Hippocampus:()=>xTt,HippocampusConfig:()=>ITt,Hono:()=>zTt,ImageFormat:()=>wTt,InvokeEndpointCommand:()=>STt,InvokeEndpointWithResponseStreamCommand:()=>_Tt,InvokeModelCommand:()=>TTt,Job:()=>DTt,ListFoundationModelsCommand:()=>fTt,MockAgent:()=>aEt,Pool:()=>rEt,Queue:()=>MTt,QueueScheduler:()=>OTt,Request:()=>JTt,Response:()=>YTt,SageMakerRuntimeClient:()=>ETt,TextToSpeechClient:()=>kTt,VertexAI:()=>CTt,Webhook:()=>ATt,Worker:()=>PTt,convertToHtml:()=>BTt,cors:()=>GTt,createClient:()=>RTt,default:()=>pTt,extractRawText:()=>UTt,fetch:()=>KTt,getGlobalDispatcher:()=>iEt,interceptors:()=>cEt,logger:()=>jTt,parseBuffer:()=>FTt,request:()=>lEt,secureHeaders:()=>HTt,selectCover:()=>$Tt,setGlobalDispatcher:()=>sEt,streamSSE:()=>VTt,timeout:()=>WTt});var vf,os,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,rEt,nEt,oEt,sEt,iEt,aEt,cEt,lEt,K1r=S({"npm-stub:@aws-sdk/client-bedrock"(){vf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:vf.get}):new Proxy(function(...r){return new Proxy({},{get:vf.get})},{get:vf.get,apply(r,n,o){return new Proxy({},{get:vf.get})},construct(r,n){return new Proxy({},{get:vf.get})}})}},os=new Proxy({},vf),pTt=os,{BedrockClient:hTt,ListFoundationModelsCommand:fTt,BedrockRuntimeClient:gTt,ConverseCommand:yTt,ConverseStreamCommand:vTt,ImageFormat:wTt,InvokeModelCommand:TTt}=os,{SageMakerRuntimeClient:ETt,InvokeEndpointCommand:STt,InvokeEndpointWithResponseStreamCommand:_Tt}=os,{GoogleAuth:bTt,VertexAI:CTt,TextToSpeechClient:kTt}=os,{Webhook:ATt}=os,{Hippocampus:xTt,HippocampusConfig:ITt}=os,{createClient:RTt}=os,{Queue:MTt,Worker:PTt,Job:DTt,QueueScheduler:OTt,FlowProducer:NTt}=os,{Cron:LTt}=os,{parseBuffer:FTt,selectCover:$Tt}=os,{extractRawText:UTt,convertToHtml:BTt}=os,{Hono:zTt}=os,{cors:GTt,HTTPException:qTt,logger:jTt,secureHeaders:HTt,streamSSE:VTt,timeout:WTt}=os,KTt=globalThis.fetch,JTt=globalThis.Request,YTt=globalThis.Response,ZTt=globalThis.Headers,XTt=globalThis.FormData,QTt=globalThis.File,eEt=globalThis.Blob,tEt=os.Agent,rEt=os.Pool,nEt=os.Client,oEt=os.Dispatcher,sEt=()=>{},iEt=()=>os,aEt=os.MockAgent,cEt={redirect:()=>e=>e,retry:()=>e=>e},lEt=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 sJ(){return await Promise.resolve().then(()=>(K1r(),mTt))}var uEt=S({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}}),dEt,J1r=S({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";rTt(),hr(),OS(),_c(),Lo(),AP(),Am(),vc(),V1r(),dt(),Qs(),et(),B(),gh(),BM(),W1r(),ti(),Kt(),dTt(),uEt(),dEt=class wrr 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=wrr.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 Xwt({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 sJ(),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 h=uTt(n,this.providerName,this.modelName),f=await FM(h,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(f)}else{p.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const m={role:"user",content:[{text:n.prompt||o?.text||""}]};this.conversationHistory.push(m)}p.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let i,a,c,l,u;try{({text:i,usage:a,finishReason:c,rawFinishReason:l,toolExecutions:u}=await this.conversationLoop(n))}catch(m){const h=this.neurolink?.getEventEmitter();throw h&&h.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:m instanceof Error?m.message:String(m)}),m}const d=this.neurolink?.getEventEmitter();return d&&d.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},toolsUsed:u.filter(m=>m.error===void 0).map(m=>m.name),toolCalls:u.map(m=>({toolCallId:m.id,toolName:m.name,args:m.input})),toolExecutions:Sh(n,Xu(u)),enhancedWithTools:u.some(m=>m.error===void 0)}}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=lTt({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}=md(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,toolExecutions:c.toolExecutions}}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 tD.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:Le.OK}),u}catch(i){throw p.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:i}),s.setStatus({code:Le.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?ym.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"),tD.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=uTt(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:Le.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:Le.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:Le.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:Le.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=lTt({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}=md(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,O=R?.cacheWriteTokens??0;return{input:I,output:x,total:I+M+O+x,...M>0&&{cacheReadTokens:M},...O>0&&{cacheCreationTokens:O}}};return g.then(R=>{_(Fy(this.providerName,this.modelName||this.getDefaultModel(),{usage:A(R.result?.usage),toolExecutions:R.result?.toolExecutions??[],toolsUsed:(R.result?.toolExecutions??[]).filter(I=>I.error===void 0).map(I=>I.name)},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 sJ(),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:mt,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:mt,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 tTt({modelId:n,contentType:"application/json",accept:"application/json",body:o}),i=await ze(this.bedrockClient.send(s),6e4,new Error("Bedrock embedding API call timed out")),a=JSON.parse(new TextDecoder().decode(i.body));if(!a.embedding||!Array.isArray(a.embedding))throw new Error("Invalid embedding response from Bedrock");return 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)}}}}}),mEt={};te(mEt,{AmazonBedrockProvider:()=>dEt,bedrockTracer:()=>tD,loadBedrockControl:()=>sJ});var Y1r=S({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";J1r(),dTt(),uEt()}}),pEt={};te(pEt,{AzureOpenAIProvider:()=>hEt});var hEt,Z1r=S({"src/lib/providers/azureOpenai.ts"(){"use strict";dt(),B(),Qs(),Vo(),vc(),Va(),Km(),hEt=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(aur()),d||yi(cur()),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",M$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??_pt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function X1r(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 Q1r=S({"src/lib/utils/imageDetection.ts"(){"use strict"}});function fEt(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 eMr=S({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),rD,tMr=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"(){rD=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}}}),rMr=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 iJ(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var nD,aJ,gEt=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"(){rMr(),nD=e=>(nD=Array.isArray,nD(e)),aJ=nD}});function*nMr(e){if(!e)return;if(cJ 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():aJ(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=aJ(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 cJ,yEt,oMr=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){gEt(),cJ=Symbol.for("brand.privateNullableHeaders"),yEt=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[s,i]of nMr(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{[cJ]:!0,values:t,nulls:r}}}});function sMr(e){const t=new Ab(e);return delete t.batches,t}function iMr(e){const t=new Hi(e);return delete t.messages.batches,t}var vEt,wEt,lJ,TEt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){j4(),_yt(),dP(),tMr(),gEt(),oMr(),j4(),vEt="vertex-2023-10-16",wEt=new Set(["/v1/messages","/v1/messages?beta=true"]),lJ=class extends vo{constructor({baseURL:e=rD("ANTHROPIC_VERTEX_BASE_URL"),region:t=rD("CLOUD_ML_REGION")??null,projectId:r=rD("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=sMr(this),this.beta=iMr(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 E9({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=yEt([r,e.headers])}async buildRequest(e){if(iJ(e.body)&&(e.body={...e.body}),iJ(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=vEt)),wEt.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(!iJ(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)}}}}),uJ={};te(uJ,{AnthropicVertex:()=>lJ,BaseAnthropic:()=>vo,default:()=>lJ});var EEt=S({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){TEt(),TEt()}});async function aMr(){return oD||(oD=await Promise.resolve().then(()=>(EEt(),uJ))),oD}function cMr(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 dJ(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 lMr(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 uMr(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 mJ(e){const t=[];let r=0;for(const n of cMr(e)){if(n.type==="regular"){dJ(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:s}=lMr(n,r);o.length!==0&&(r++,dJ(t,"assistant",o),dJ(t,"user",s))}if(uMr(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 pJ(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 wf(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"&&wf(n);if(e.items&&typeof e.items=="object")if(Array.isArray(e.items))for(const n of e.items)n&&typeof n=="object"&&wf(n);else wf(e.items);for(const n of["allOf","anyOf","oneOf"])if(Array.isArray(e[n]))for(const o of e[n])o&&typeof o=="object"&&wf(o)}function SEt(e,t,r){const n=Cmt({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<=xEt?l:{functionResponse:{name:u.name,response:{result:F9(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:U9}]})}return e.length=0,e.push(...i),!0}function _Et(e,t,r){const n=Dwt({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:Pwt(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:jK}]})}return e.length=0,e.push(...i),!0}async function bEt(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 oD,CEt,hJ,Fb,fJ,V0,Tf,kEt,AEt,sD,xEt,gJ,dMr=S({"src/lib/providers/googleVertex/client.ts"(){"use strict";Cn(),yP(),hr(),_c(),Jj(),CP(),iYe(),Lo(),yh(),Th(),O9(),Qt(),Wn(),dt(),Qs(),et(),$wt(),Lct(),BM(),B(),k9(),Amt(),Owt(),iP(),Q1r(),p9(),Vo(),ti(),umt(),Kh(),ia(),xmt(),wmt(),AP(),jwt(),I_(),g0(),z9(),od(),zS(),Ua(),Kt(),rl(),vc(),Am(),gh(),eMr(),I_(),oD=null,CEt=()=>!0,hJ=()=>yi(yur()),Fb=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",fJ=(e,t)=>{const r=t||Fb();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||Kq.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},V0=fJ,Tf=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",kEt=()=>!!(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),AEt=async(e,t,r,n)=>{const o=e||Fb();return{projectId:r?r.projectId?.trim()||"express":hJ(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},sD=e=>e.toLowerCase().includes("claude"),xEt=2048,gJ=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||kEt()||yi(vur()),this.projectId=s?.projectId||(i?"":hJ()),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 Tf()}async getAISDKModel(){throw new Ae({code:Ge.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&&b7(t.input),t.input?.files?.length)try{await C7(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||Tf();return GPe({name:"neurolink.provider.stream",tracer:$e.provider,attributes:{[_e.GEN_AI_SYSTEM]:this.providerName,[_e.GEN_AI_MODEL]:n,[_e.GEN_AI_OPERATION]:"stream",[_e.NL_PROVIDER]:this.providerName}},async o=>{const s=Date.now(),i=t.tools||{};await this.preprocessNativeFileInput(t);const c={...await at({name:"neurolink.message.build",tracer:$e.provider,attributes:{[_e.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;sD(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){Nmt("GoogleVertex");const r=this.resolveExpressApiKey(),n=r?"":this.projectId,o=t||this.location||Fb(),i=(await Promise.resolve().then(()=>(WE(),Sy))).GoogleGenAI;if(!i)throw new Ae({code:Ge.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=pUe(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||Tf(),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 qe;typeof ke=="string"?Ro.existsSync(ke)?qe=Ro.readFileSync(ke):qe=Buffer.from(ke,"base64"):qe=ke;const ne=qe.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:ne}})}}if(await R9(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 qe=s_(ke);let ne,J="image/jpeg";if(typeof qe=="string")if(Ro.existsSync(qe)){ne=Ro.readFileSync(qe);const oe=u_(qe);J=oe.startsWith("image/")?oe:this.detectImageType(ne)}else if(qe.startsWith("data:")){const oe=qe.match(/^data:([^;]+);base64,(.+)$/);if(oe)J=oe[1],ne=Buffer.from(oe[2],"base64");else continue}else if(qe.startsWith("http://")||qe.startsWith("https://"))try{const oe=await fetch(qe);if(!oe.ok){p.warn(`[GoogleVertex] Image fetch failed: ${oe.status} ${oe.statusText}, skipping`,{url:Qr(qe)});continue}const re=await oe.arrayBuffer();ne=Buffer.from(re);const pe=oe.headers.get("content-type");pe&&pe.startsWith("image/")&&(J=pe.split(";")[0])}catch(oe){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${oe instanceof Error?oe.message:String(oe)}`,{url:Qr(qe)});continue}else ne=Buffer.from(qe,"base64"),J=this.detectImageType(ne);else ne=qe,J=this.detectImageType(ne);const fe=ne.toString("base64");i.push({inlineData:{mimeType:J,data:fe}})}}_P(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[qe,ne]of ke.executeMap)l.set(qe,ne);p.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ke.toolsConfig[0].functionDeclarations.length,toolNames:ke.toolsConfig[0].functionDeclarations.map(qe=>qe.name)})}const d=t;let m=!1;if(d.schema&&c){m=!0;const ke=Mo(d.schema,"openApi3"),qe=On(ke);qe.$schema&&delete qe.$schema;const ne=Fi(qe),J=c[0]?.functionDeclarations||[];J.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:ne}),c=[{functionDeclarations:J}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(ne),totalTools:J.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};m9(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=A9(t.thinkingConfig,r);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"),qe=On(ke);qe.$schema&&delete qe.$schema;const ne=Fi(qe);wf(ne),f.responseSchema=ne,p.debug("[GoogleVertex] Added responseSchema for JSON output (stream)",{schemaKeys:Object.keys(ne)})}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(nd("vertex",r));let O=!1,U=0,P=0,N=0,$=0;const F=[],q=Yc(t.timeout)??kS,j=bS(t.toolTimeoutMs),H=t.turnTimeoutMs??q,W=new AbortController,G=()=>W.abort();t.abortSignal?.addEventListener("abort",G);const ee=SP({turnTimeoutMs:t.turnTimeoutMs,defaultTurnTimeoutMs:q,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:ke=>{p.warn(ke==="timeout"?`[GoogleVertex] Native Gemini turn exceeded its ${H}ms time budget \u2014 aborting`:`[GoogleVertex] Native Gemini turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),W.abort()}}),ye=W.signal;t.abortSignal?.aborted&&W.abort();let le=!1,Y=!1,me=!1,Te=0;try{const ke=kP({providerLabel:"GoogleVertex",maxSteps:_,toolFailureBreaker:{maxRetries:hh,consecutive:!0,classifyResultFailure:pe=>ZM(pe)??void 0},liveTools:t.tools??{},toolGuards:{toolTimeoutMs:j,abortSignal:ye,onProgress:()=>ee.noteProgress()},...u?{declarations:u}:{},...m?{finalResultToolName:"final_result",onTerminalResult:pe=>{try{x=JSON.parse(pe)}catch{}}}:{},enableMalformedRetry:!0,buildMalformedRetryNote:(pe,Q)=>(this.emitTurnEvent({phase:"malformed-retry",step:Q+1,maxSteps:_}),[...pe,{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:(pe,Q)=>bEt(pe,Q,{onProgress:()=>ee.noteProgress(),onUsage:(se,ge)=>M.noteUsage(se,ge),onUsageDelta:(se,ge)=>{se==="input"?U+=ge:se==="output"?P+=ge:se==="cacheRead"?N+=ge:$+=ge}}),planReclaim:pe=>{if(!M.shouldStop())return;const Q=[...pe];return SEt(Q,r,M.projectedNextPromptTokens)?(M.resetAfterReclaim(),{conversation:Q}):(O=!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:pe=>({model:r,contents:pe,config:{...f,...c?{tools:c}:{}}}),sendStep:async(pe,Q)=>{ee.noteProgress();const se=pe;return o.models.generateContentStream({model:se.model,contents:se.contents,config:{...se.config??{},abortSignal:Q}})}}),qe={...ke,buildStepRequest:(pe,Q)=>(Te=Q+1,ke.buildStepRequest(pe,Q)),buildToolResultMessages:(pe,Q,se,ge)=>{const Ie=ke.buildToolResultMessages(pe,Q,se,ge);if(ee.shouldNudgeWrapup()){const V=Ie[Ie.length-1];V&&Array.isArray(V.parts)&&V.parts.push({text:TP(m)})}const C=wP(Q.raw.rawResponseParts);It(this.handleToolExecutionStorage(se.map((V,Ee)=>({toolName:V.name,args:V.args,...Ee===0&&C?{thoughtSignature:C}:{},stepIndex:ge+1})),se.map(V=>({toolName:V.name,output:V.output,stepIndex:ge+1})),t,new Date),fh,"tool storage write timed out").catch(V=>{p.warn("[GoogleVertex] Failed to store native Gemini stream tool executions",{error:V instanceof Error?V.message:String(V)})});try{const V=Ie[Ie.length-1];M.noteAppendedChars(JSON.stringify(V?.parts??[]).length)}catch{}return Ie}},{stream:ne,resultPromise:J}=md(qe,b,{tools:vP(u,t.tools,{toolTimeoutMs:j,abortSignal:ye,onProgress:()=>ee.noteProgress()}),abortSignal:ye,toolTimeoutMs:j}),fe=(async()=>{for await(const pe of ne)pe.content&&F.push(pe.content)})();let oe,re;try{oe=await J}catch(pe){re=pe}if(await Wh(fe,"GoogleVertex"),re!==void 0)if(ye.aborted||Hm(re))le=!0;else throw p.error("[GoogleVertex] Native SDK error",re),this.handleProviderError(re);if(oe){A=oe.text,k=oe.rawStopReason??k;for(const pe of oe.toolCalls)R.push({toolName:pe.name,args:pe.args});for(const pe of oe.toolExecutions)I.push({name:pe.name,input:pe.input,output:pe.output});b.length=0,b.push(...oe.conversation)}if(ye.aborted&&(le=!0),!A&&(Te>=_||le||O)){Y=Te>=_&&!le;const pe=R.filter(Q=>Q.toolName!=="final_result").length;if(F.length>0)p.warn(O?"[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(le)p.warn(`[GoogleVertex] Tool call loop ended mid-turn (${ee.timedOut?"turn time limit":ee.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),A=this.buildLoopExitMessage({turnClock:ee,wasAborted:le,stallTimeoutMs:t.stallTimeoutMs,maxSteps:_,toolCallCount:pe});else{p.warn(O?"[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 Q=await this.synthesizeFinalAnswerWithoutTools(o,r,f,b,m,Yc(t.timeout)??kS,ye);Q.text?(me=!0,A=Q.text,F.push(Q.text),U+=Q.inputTokens,P+=Q.outputTokens,$+=Q.reasoningTokens??0,Q.finishReason&&(k=Q.finishReason)):A=O?bc(pe):Vm(_,pe)}}}finally{ee.dispose(),t.abortSignal?.removeEventListener("abort",G)}const ve=Y&&!me?"tool-calls":I9(k),Fe=EP({timedOut:ee.timedOut,stalled:ee.stalled,wasAborted:le,cappedWithoutAnswer:Y&&!me,contextCappedWithoutAnswer:O&&!me,finishReason:ve});Fe!=="completed"&&this.emitTurnEvent({phase:Fe,step:Te,maxSteps:_,toolCallCount:R.filter(ke=>ke.toolName!=="final_result").length,elapsedMs:ee.elapsedMs()});const Pe=Date.now()-w,Ne=x?[A]:F.length>0?F:[A];async function*xe(){for(const ke of Ne)ke.length>0&&(yield{content:ke})}const Ke=R.filter(ke=>ke.toolName!=="final_result"),ut=I.filter(ke=>ke.name!=="final_result"),Tt=Math.max(0,U-N),Re={stream:xe(),provider:this.providerName,model:r,finishReason:ve,stopReason:Fe,rawFinishReason:k,usage:{input:Tt,output:P+$,total:Tt+N+P+$,...N>0&&{cacheReadTokens:N},...$>0&&{reasoning:$}},toolCalls:Ke.map(ke=>({toolName:ke.toolName,args:ke.args})),toolsUsed:Ke.map(ke=>ke.toolName),toolExecutions:Xu(ut),metadata:{streamId:`native-vertex-${Date.now()}`,startTime:w,responseTime:Pe,totalToolExecutions:Ke.length,stopReason:Fe,rawFinishReason:k,stepsUsed:Te}};return x&&(Re.structuredOutput=x),Re}async executeNativeGemini3Generate(t){const r=t.model||this.modelName||Tf(),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 Re of c.pdfFiles){let ke;typeof Re=="string"?Ro.existsSync(Re)?ke=Ro.readFileSync(Re):ke=Buffer.from(Re,"base64"):ke=Re;const qe=ke.toString("base64");a.push({inlineData:{mimeType:"application/pdf",data:qe}})}}if(await R9(a,c?.nativeAudioFiles,"[GoogleVertex]"),c?.images&&c.images.length>0){p.debug(`[GoogleVertex] Processing ${c.images.length} image(s) for native generate`);for(const Re of c.images){const ke=s_(Re);let qe,ne="image/jpeg";if(typeof ke=="string")if(Ro.existsSync(ke)){qe=Ro.readFileSync(ke);const fe=u_(ke);ne=fe.startsWith("image/")?fe:this.detectImageType(qe)}else if(ke.startsWith("data:")){const fe=ke.match(/^data:([^;]+);base64,(.+)$/);if(fe)ne=fe[1],qe=Buffer.from(fe[2],"base64");else continue}else if(ke.startsWith("http://")||ke.startsWith("https://"))try{const fe=await fetch(ke);if(!fe.ok){p.warn(`[GoogleVertex] Image fetch failed: ${fe.status} ${fe.statusText}, skipping`,{url:Qr(ke)});continue}const oe=await fe.arrayBuffer();qe=Buffer.from(oe);const re=fe.headers.get("content-type");re&&re.startsWith("image/")&&(ne=re.split(";")[0])}catch(fe){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${fe instanceof Error?fe.message:String(fe)}`,{url:Qr(ke)});continue}else qe=Buffer.from(ke,"base64"),ne=this.detectImageType(qe);else qe=ke,ne=this.detectImageType(qe);const J=qe.toString("base64");a.push({inlineData:{mimeType:ne,data:J}})}}_P(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 Re=y0(l,"functionDeclarations");m=Re,u=Re.toolsConfig;for(const[ke,qe]of Re.executeMap)d.set(ke,qe);p.debug("[GoogleVertex] Converted tools for native SDK generate",{toolCount:Re.toolsConfig[0].functionDeclarations.length,toolNames:Re.toolsConfig[0].functionDeclarations.map(ke=>ke.name)})}let h=!1;if(t.schema&&u){h=!0;const Re=Mo(t.schema,"openApi3"),ke=On(Re);ke.$schema&&delete ke.$schema;const qe=Fi(ke),ne=u[0]?.functionDeclarations||[];ne.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:qe}),u=[{functionDeclarations:ne}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (generate)",{schemaKeys:Object.keys(qe),totalTools:ne.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};m9(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
 
@@ -2280,10 +2280,13 @@ ${h}`:h);continue}if(typeof d.content=="string")r.push({role:d.role,content:d.co
2280
2280
  data: ${r}
2281
2281
 
2282
2282
  `}var Kk=class{state="idle";currentBlockType=null;sawToolUseBlock=!1;blockIndex=0;hasOpenedBlock=!1;outputTokens=0;messageStarted=!1;messageId;model;inputTokens;constructor(e,t=0){this.messageId=kXt(),this.model=e,this.inputTokens=t}getState(){return this.state}getCurrentBlockType(){return this.currentBlockType}getBlockIndex(){return this.blockIndex}static pingEvent(){return $c("ping",{type:"ping"})}*ensureMessageStarted(){if(this.messageStarted)return;const e={type:"message_start",message:{id:this.messageId,type:"message",role:"assistant",content:[],model:this.model,stop_reason:null,stop_sequence:null,usage:{input_tokens:this.inputTokens,output_tokens:0}}};yield $c("message_start",e),yield $c("ping",{type:"ping"}),this.messageStarted=!0,this.state="streaming"}*closeCurrentBlock(){this.currentBlockType!==null&&(yield $c("content_block_stop",{type:"content_block_stop",index:this.blockIndex}),this.currentBlockType=null)}*openBlock(e){yield*this.closeCurrentBlock(),this.hasOpenedBlock&&(this.blockIndex+=1),this.hasOpenedBlock=!0;const t={type:"content_block_start",index:this.blockIndex,content_block:e};yield $c("content_block_start",t),this.currentBlockType=e.type}*start(){this.state==="idle"&&(yield*this.ensureMessageStarted())}*pushDelta(e){if(this.state==="done"||this.state==="error")return;yield*this.ensureMessageStarted(),this.currentBlockType!=="text"&&(yield*this.openBlock({type:"text",text:""}));const t={type:"content_block_delta",index:this.blockIndex,delta:{type:"text_delta",text:e}};yield $c("content_block_delta",t)}*pushThinkingDelta(e){if(this.state==="done"||this.state==="error")return;yield*this.ensureMessageStarted(),this.currentBlockType!=="thinking"&&(yield*this.openBlock({type:"thinking",thinking:""}));const t={type:"content_block_delta",index:this.blockIndex,delta:{type:"thinking_delta",thinking:e}};yield $c("content_block_delta",t)}*pushToolUse(e,t,r){if(this.state==="done"||this.state==="error")return;this.sawToolUseBlock=!0,yield*this.ensureMessageStarted(),yield*this.openBlock({type:"tool_use",id:e,name:t,input:""});const n=JSON.stringify(r??{}),o=100;for(let s=0;s<n.length;s+=o){const i=n.slice(s,s+o),a={type:"content_block_delta",index:this.blockIndex,delta:{type:"input_json_delta",partial_json:i}};yield $c("content_block_delta",a)}if(n.length===0){const s={type:"content_block_delta",index:this.blockIndex,delta:{type:"input_json_delta",partial_json:"{}"}};yield $c("content_block_delta",s)}yield*this.closeCurrentBlock()}*finish(e,t,r){if(this.state==="idle"&&(yield*this.ensureMessageStarted()),this.state==="done"||this.state==="error")return;this.outputTokens=e??this.outputTokens;const n=this.sawToolUseBlock&&(!t||t==="stop")?"tool_use":t;yield*this.closeCurrentBlock();const o={type:"message_delta",delta:{stop_reason:AXt(n),stop_sequence:null},usage:{...r,output_tokens:this.outputTokens}};yield $c("message_delta",o),yield $c("message_stop",{type:"message_stop"}),this.state="done"}*emitError(e,t){this.state="error";const r=Aa(e,t);yield $c("error",r)}};Hn();var rF=100*1024,OJr=5e3,$oe=2048,xXt=1024*1024,Jd="...[TRUNCATED]";function nF(e){const t=[];let r=0;for(;r<e.length;){const n=/\r\n\r\n|\n\n|\r\r/.exec(e.slice(r));if(!n||n.index===void 0)break;const o=r+n.index,s=e.slice(r,o);r=o+n[0].length;let i="";const a=[],c=s.split(/\r\n|\n|\r/);for(const u of c)if(u.startsWith("event:"))i=u.slice(6).trim();else if(u.startsWith("data:")){const d=u.slice(5);a.push(d.startsWith(" ")?d.slice(1):d)}const l=a.join(`
2283
- `);(i||l)&&t.push({event:i,data:l})}return{events:t,remainder:e.slice(r)}}function NJr(e){return{messageStopReceived:!1,messageId:"",model:"",inputTokens:0,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0,contentBlocks:[],blockByteCounts:new Map,stopReason:null,stopSequence:null,eventCount:0,startTime:Date.now(),totalBytesReceived:0,events:[],rawTextChunks:e?[]:void 0,rawTextBytes:0,rawTextTruncated:!1,eventLogTruncated:!1}}function Dw(e){return Buffer.byteLength(e,"utf8")}function Uoe(e,t){if(Dw(e)<=t)return e;const r=Dw(Jd);if(t<=0||t<r)return"";let n="",o=0;for(const s of e){const i=Dw(s);if(o+i+r>t)break;n+=s,o+=i}return`${n}${Jd}`}function Boe(e,t){return Uoe(e,t)}function zoe(e,t,r,n){const o=Dw(t);if(r>=n)return{value:e&&e.endsWith(Jd)?e:`${e??""}${Jd}`,nextBytes:r+o};const s=n-r,i=r+o;return o<=s?{value:`${e??""}${t}`,nextBytes:i}:{value:`${e??""}${Uoe(t,s)}`,nextBytes:i}}function IXt(e,t){if(!e.rawTextChunks||e.rawTextTruncated)return;const r=xXt-e.rawTextBytes;if(r<=0){e.rawTextChunks.push(Jd),e.rawTextTruncated=!0;return}const n=Dw(t);if(n<=r){e.rawTextChunks.push(t),e.rawTextBytes+=n;return}e.rawTextChunks.push(Uoe(t,r)),e.rawTextBytes=xXt,e.rawTextTruncated=!0}function LJr(e){return Dw(e.text??e.thinking??e.toolInput??"")}function FJr(e){const t=e.inputTokens+e.outputTokens;return{messageId:e.messageId,messageStopReceived:e.messageStopReceived,firstUsefulOutputAt:e.firstUsefulOutputAt,firstUsefulOutputEvent:e.firstUsefulOutputEvent,observationIncomplete:e.observationIncomplete,model:e.model,usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationInputTokens:e.cacheCreationInputTokens,cacheReadInputTokens:e.cacheReadInputTokens,totalTokens:t},contentBlocks:e.contentBlocks,stopReason:e.stopReason,stopSequence:e.stopSequence,eventCount:e.eventCount,streamDurationMs:Date.now()-e.startTime,totalBytesReceived:e.totalBytesReceived,events:e.events,...e.streamErrorMessage?{streamErrorMessage:e.streamErrorMessage}:{},...e.rawTextChunks?{rawText:e.rawTextChunks.join("")}:{},rawTextTruncated:e.rawTextTruncated}}function $Jr(e,t){const r=t.message;if(!r)return;e.messageId=r.id??"",e.model=r.model??"";const n=r.usage;n&&(e.inputTokens+=n.input_tokens??0,e.outputTokens+=n.output_tokens??0,e.cacheCreationInputTokens+=n.cache_creation_input_tokens??0,e.cacheReadInputTokens+=n.cache_read_input_tokens??0)}function UJr(e,t){const r=t.index??0,n=t.content_block;if(!n)return;const o=n.type,s={index:r,type:o};o==="text"?s.text=n.text??"":o==="thinking"?s.thinking=n.thinking??"":o==="tool_use"&&(s.toolName=n.name??"",s.toolId=n.id??"",s.toolInput=""),e.contentBlocks.push(s),e.blockByteCounts.set(r,LJr(s))}function BJr(e,t){const r=t.index??0,n=t.delta;if(!n)return;const o=e.contentBlocks.find(a=>a.index===r);if(!o)return;const s=e.blockByteCounts.get(r)??0,i=s>=rF;if(n.type==="text_delta"&&n.text!==null){const a=n.text,c=zoe(o.text,a,s,rF);e.blockByteCounts.set(r,c.nextBytes),(!i||!o.text?.endsWith(Jd))&&(o.text=c.value)}else if(n.type==="thinking_delta"&&n.thinking!==null){const a=n.thinking,c=zoe(o.thinking,a,s,rF);e.blockByteCounts.set(r,c.nextBytes),(!i||!o.thinking?.endsWith(Jd))&&(o.thinking=c.value)}else if(n.type==="input_json_delta"&&n.partial_json!==null){const a=n.partial_json,c=zoe(o.toolInput,a,s,rF);e.blockByteCounts.set(r,c.nextBytes),(!i||!o.toolInput?.endsWith(Jd))&&(o.toolInput=c.value)}}function zJr(e,t){const r=t.delta;r&&(e.stopReason=r.stop_reason??e.stopReason,e.stopSequence=r.stop_sequence??e.stopSequence);const n=t.usage;n&&(e.outputTokens+=n.output_tokens??0)}function GJr(e,t){e.eventCount++;const r=Date.now();if(e.events.length<OJr-1?t.event==="content_block_delta"?e.events.push({type:t.event,timestamp:r,data:""}):e.events.push({type:t.event,timestamp:r,data:Boe(t.data,$oe)}):e.eventLogTruncated||(e.events.push({type:"truncated",timestamp:r,data:Jd}),e.eventLogTruncated=!0),!t.data)return;if(t.data.length>1024*1024){e.observationIncomplete=!0;return}let n;try{n=JSON.parse(t.data)}catch{e.observationIncomplete=!0;return}const o=n&&typeof n=="object"&&"type"in n?n.type:void 0,s=t.event||(typeof o=="string"?o:"");if(s==="error"||o==="error"){const i=n&&typeof n=="object"?n:{},c=(i.error&&typeof i.error=="object"?i.error:void 0)?.message??i.message;e.streamErrorMessage=typeof c=="string"&&c.trim()?Boe(c.trim(),$oe):Boe(t.data,$oe)}if(s==="message_stop"&&(e.messageStopReceived=!0),s==="content_block_delta"&&n&&typeof n=="object"&&"delta"in n){const i=n.delta;i&&typeof i=="object"&&("text"in i&&typeof i.text=="string"&&i.text.trim().length>0||"partial_json"in i&&typeof i.partial_json=="string"&&i.partial_json.trim().length>0||"refusal"in i&&typeof i.refusal=="string"&&i.refusal.trim().length>0)&&e.firstUsefulOutputAt===void 0&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent=`content_block_delta.${"text"in i?"text":"refusal"in i?"refusal":"partial_json"}`)}if(e.firstUsefulOutputAt===void 0&&n&&typeof n=="object"){const i=n;s==="message_start"&&Toe(i.message)&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent="message_start.content");const a=i.content_block;if(s==="content_block_start"&&a&&typeof a=="object"){const c=a;(typeof c.text=="string"&&c.text.trim().length>0||typeof c.refusal=="string"&&c.refusal.trim().length>0||(c.type==="tool_use"||c.type==="server_tool_use")&&c.input&&typeof c.input=="object"&&Object.keys(c.input).length>0)&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent="content_block_start")}if(s==="content_block_stop"&&typeof i.index=="number"){const c=e.contentBlocks.find(l=>l.index===i.index);c?.type==="tool_use"&&c.toolName&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent="content_block_stop.tool_use")}}switch(s){case"message_start":$Jr(e,n);break;case"content_block_start":UJr(e,n);break;case"content_block_delta":BJr(e,n);break;case"message_delta":zJr(e,n);break;default:break}}function oF(e={}){const t=e.captureRawText??!1,r=NJr(t);let n="",o=!1,s=!1;const i=new TextDecoder;let a;const c=new Promise(w=>{a=w});function l(){s||(s=!0,n.trim()&&(r.observationIncomplete=!0),a(FJr(r)))}const u=new TransformStream({transform(w,E){E.enqueue(w),r.totalBytesReceived+=w.byteLength;const _=i.decode(w,{stream:!0});if(IXt(r,_),n+=_,o){const k=/\r\n\r\n|\n\n|\r\r/.exec(n);if(!k){n=n.slice(-4);return}n=n.slice(k.index+k[0].length),o=!1}const{events:b,remainder:A}=nF(n);n=A,n.length>1024*1024&&(r.observationIncomplete=!0,o=!0,n=n.slice(-4));for(const k of b)GJr(r,k)},flush(){const w=i.decode();w&&(IXt(r,w),n+=w),l()}}),d=u.writable.getWriter();let m;const h=new WritableStream({start(w){m=w},write(w){return d.write(w)},close(){return d.close()},abort(w){return l(),d.abort(w)}});d.closed.catch(w=>{l();try{m.error(w)}catch{}});const f=u.readable.getReader();return{stream:{readable:new ReadableStream({async pull(w){try{const{done:E,value:_}=await f.read();E?w.close():w.enqueue(_)}catch(E){w.error(E)}},async cancel(w){l();try{m.error(w)}catch{}await Promise.allSettled([f.cancel(w),d.abort(w)])}}),writable:h},telemetry:c}}Qt();var Jk=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0;function sF(e){if(!e||typeof e!="object")return!1;if("type"in e){if(e.type==="function_call")return"arguments"in e&&typeof e.arguments=="string"&&e.arguments.trim().length>0;if(e.type==="custom_tool_call")return"input"in e&&typeof e.input=="string"&&e.input.trim().length>0;if(e.type==="output_text")return"text"in e&&typeof e.text=="string"&&e.text.trim().length>0;if(e.type==="refusal")return"refusal"in e&&typeof e.refusal=="string"&&e.refusal.trim().length>0}return"content"in e&&Array.isArray(e.content)&&e.content.some(sF)}function Goe(e){if(e===null||typeof e!="object")return null;const t=e,r=t.response,n=r&&typeof r=="object"&&r.usage?r.usage:t.usage;if(!n||typeof n!="object")return null;const o=n.input_tokens??n.prompt_tokens,s=n.output_tokens??n.completion_tokens;if(o===void 0&&s===void 0)return null;const i=n.input_tokens_details,a=n.output_tokens_details;return{inputTokens:Jk(o),outputTokens:Jk(s),cacheReadTokens:Jk(i?.cached_tokens),cacheCreationTokens:Jk(i?.cache_write_tokens),reasoningTokens:Jk(a?.reasoning_tokens)}}var RXt=256*1024;function qJr(){const e=process.env.NEUROLINK_PROXY_CODEX_CAPTURE;if(!e||process.env.NEUROLINK_PROXY_LOG_SINK==="otel")return null;let t=0,r=!1;return n=>{if(!(t>=RXt))try{const o=RXt-t,s=n.byteLength>o?n.subarray(0,o):n;HS(e,s,{flag:r?"a":"w"}),r=!0,t+=s.byteLength}catch{}}}function jJr(){const e={completed:!1,terminalBytes:0};let t=0;const r=g=>{for(const y of g)if(y.data.trim()!=="[DONE]")try{const w=JSON.parse(y.data);if(!w||typeof w!="object"){e.observationIncomplete=!0;continue}const E=Goe(w);E&&(u=E);const _=w.type??y.event;(_==="response.output_text.delta"||_==="response.refusal.delta"||_==="response.function_call_arguments.delta")&&typeof w.delta=="string"&&w.delta.trim().length>0&&e.firstUsefulOutputAt===void 0&&(e.firstUsefulOutputAt=Date.now(),e.firstUsefulOutputEvent=String(_));const b=sF(w.item),A=w.response,k=_==="response.completed"&&A&&typeof A=="object"&&"output"in A&&Array.isArray(A.output)&&A.output.some(sF),R=_==="response.output_text.done"&&typeof w.text=="string"&&w.text.trim().length>0||_==="response.refusal.done"&&typeof w.refusal=="string"&&w.refusal.trim().length>0||_==="response.function_call_arguments.done"&&typeof w.arguments=="string"&&w.arguments.trim().length>0||_==="response.custom_tool_call_input.done"&&typeof w.input=="string"&&w.input.trim().length>0||(_==="response.content_part.added"||_==="response.content_part.done")&&sF(w.part),I=_==="response.custom_tool_call_input.delta"&&typeof w.delta=="string"&&w.delta.trim().length>0;if(e.firstUsefulOutputAt===void 0&&(R||k||I||(_==="response.output_item.added"||_==="response.output_item.done")&&b)&&(e.firstUsefulOutputAt=Date.now(),e.firstUsefulOutputEvent=String(_)),_==="response.completed")e.completed=!0,e.terminalBytes=t;else if(_==="error"||_==="response.failed"||_==="response.incomplete"){e.errorType="stream_error";const x=w.response,M=x&&typeof x=="object"?x:w,O=M.error,U=O&&typeof O=="object"?O:M,P=M.incomplete_details,N=P&&typeof P=="object"&&"reason"in P?P.reason:void 0;e.errorCode=typeof U.code=="string"?qr(U.code).slice(0,200):typeof N=="string"?qr(N).slice(0,200):String(_),e.errorMessage=typeof U.message=="string"?qr(U.message).slice(0,200):_==="response.incomplete"?"Codex reported an incomplete response":"Codex reported a stream failure",e.terminalBytes=t}}catch{e.observationIncomplete=!0}};let n=()=>{};const o=new Promise(g=>{n=g});let s=!1;const i=g=>{s||(s=!0,n(g))},a=new TextDecoder,c=qJr();let l="",u=null;const d=1024*1024;let m=!1;const h={transform(g,y){y.enqueue(g),t+=g.byteLength;try{if(c?.(g),l+=a.decode(g,{stream:!0}),m){const _=/\r\n\r\n|\n\n|\r\r/.exec(l);if(!_){l=l.slice(-3);return}l=l.slice(_.index+_[0].length),m=!1}const{events:w,remainder:E}=nF(l);l=E,r(w),l.length>d&&(e.observationIncomplete=!0,l=l.slice(-2),m=!0)}catch{e.observationIncomplete=!0}},flush(){(m||l.trim())&&(e.observationIncomplete=!0),i(u)},cancel(){i(u)}};return{stream:new TransformStream(h),usage:o,evidence:()=>({...e})}}var Yk=class extends Error{status;responseBody;constructor(e,t){super(`Codex fallback request returned HTTP ${e}`),this.name="CodexFallbackResponseError",this.status=e,this.responseBody=t}};function Pl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ow(e){return typeof e=="string"&&e.length>0?e:void 0}function HJr(e){if(typeof e.system=="string")return e.system||void 0;if(Array.isArray(e.system))return e.system.map(r=>typeof r.text=="string"?r.text:"").filter(Boolean).join(`
2283
+ `);(i||l)&&t.push({event:i,data:l})}return{events:t,remainder:e.slice(r)}}function NJr(e){return{messageStopReceived:!1,messageId:"",model:"",inputTokens:0,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0,contentBlocks:[],blockByteCounts:new Map,stopReason:null,stopSequence:null,eventCount:0,startTime:Date.now(),totalBytesReceived:0,events:[],rawTextChunks:e?[]:void 0,rawTextBytes:0,rawTextTruncated:!1,eventLogTruncated:!1}}function Dw(e){return Buffer.byteLength(e,"utf8")}function Uoe(e,t){if(Dw(e)<=t)return e;const r=Dw(Jd);if(t<=0||t<r)return"";let n="",o=0;for(const s of e){const i=Dw(s);if(o+i+r>t)break;n+=s,o+=i}return`${n}${Jd}`}function Boe(e,t){return Uoe(e,t)}function zoe(e,t,r,n){const o=Dw(t);if(r>=n)return{value:e&&e.endsWith(Jd)?e:`${e??""}${Jd}`,nextBytes:r+o};const s=n-r,i=r+o;return o<=s?{value:`${e??""}${t}`,nextBytes:i}:{value:`${e??""}${Uoe(t,s)}`,nextBytes:i}}function IXt(e,t){if(!e.rawTextChunks||e.rawTextTruncated)return;const r=xXt-e.rawTextBytes;if(r<=0){e.rawTextChunks.push(Jd),e.rawTextTruncated=!0;return}const n=Dw(t);if(n<=r){e.rawTextChunks.push(t),e.rawTextBytes+=n;return}e.rawTextChunks.push(Uoe(t,r)),e.rawTextBytes=xXt,e.rawTextTruncated=!0}function LJr(e){return Dw(e.text??e.thinking??e.toolInput??"")}function FJr(e){const t=e.inputTokens+e.outputTokens;return{messageId:e.messageId,messageStopReceived:e.messageStopReceived,firstUsefulOutputAt:e.firstUsefulOutputAt,firstUsefulOutputEvent:e.firstUsefulOutputEvent,observationIncomplete:e.observationIncomplete,model:e.model,usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationInputTokens:e.cacheCreationInputTokens,cacheReadInputTokens:e.cacheReadInputTokens,totalTokens:t},contentBlocks:e.contentBlocks,stopReason:e.stopReason,stopSequence:e.stopSequence,eventCount:e.eventCount,streamDurationMs:Date.now()-e.startTime,totalBytesReceived:e.totalBytesReceived,events:e.events,...e.streamErrorMessage?{streamErrorMessage:e.streamErrorMessage}:{},...e.rawTextChunks?{rawText:e.rawTextChunks.join("")}:{},rawTextTruncated:e.rawTextTruncated}}function $Jr(e,t){const r=t.message;if(!r)return;e.messageId=r.id??"",e.model=r.model??"";const n=r.usage;n&&(e.inputTokens+=n.input_tokens??0,e.outputTokens+=n.output_tokens??0,e.cacheCreationInputTokens+=n.cache_creation_input_tokens??0,e.cacheReadInputTokens+=n.cache_read_input_tokens??0)}function UJr(e,t){const r=t.index??0,n=t.content_block;if(!n)return;const o=n.type,s={index:r,type:o};o==="text"?s.text=n.text??"":o==="thinking"?s.thinking=n.thinking??"":o==="tool_use"&&(s.toolName=n.name??"",s.toolId=n.id??"",s.toolInput=""),e.contentBlocks.push(s),e.blockByteCounts.set(r,LJr(s))}function BJr(e,t){const r=t.index??0,n=t.delta;if(!n)return;const o=e.contentBlocks.find(a=>a.index===r);if(!o)return;const s=e.blockByteCounts.get(r)??0,i=s>=rF;if(n.type==="text_delta"&&n.text!==null){const a=n.text,c=zoe(o.text,a,s,rF);e.blockByteCounts.set(r,c.nextBytes),(!i||!o.text?.endsWith(Jd))&&(o.text=c.value)}else if(n.type==="thinking_delta"&&n.thinking!==null){const a=n.thinking,c=zoe(o.thinking,a,s,rF);e.blockByteCounts.set(r,c.nextBytes),(!i||!o.thinking?.endsWith(Jd))&&(o.thinking=c.value)}else if(n.type==="input_json_delta"&&n.partial_json!==null){const a=n.partial_json,c=zoe(o.toolInput,a,s,rF);e.blockByteCounts.set(r,c.nextBytes),(!i||!o.toolInput?.endsWith(Jd))&&(o.toolInput=c.value)}}function zJr(e,t){const r=t.delta;r&&(e.stopReason=r.stop_reason??e.stopReason,e.stopSequence=r.stop_sequence??e.stopSequence);const n=t.usage;n&&(e.outputTokens+=n.output_tokens??0)}function GJr(e,t){e.eventCount++;const r=Date.now();if(e.events.length<OJr-1?t.event==="content_block_delta"?e.events.push({type:t.event,timestamp:r,data:""}):e.events.push({type:t.event,timestamp:r,data:Boe(t.data,$oe)}):e.eventLogTruncated||(e.events.push({type:"truncated",timestamp:r,data:Jd}),e.eventLogTruncated=!0),!t.data)return;if(t.data.length>1024*1024){e.observationIncomplete=!0;return}let n;try{n=JSON.parse(t.data)}catch{e.observationIncomplete=!0;return}const o=n&&typeof n=="object"&&"type"in n?n.type:void 0,s=t.event||(typeof o=="string"?o:"");if(s==="error"||o==="error"){const i=n&&typeof n=="object"?n:{},c=(i.error&&typeof i.error=="object"?i.error:void 0)?.message??i.message;e.streamErrorMessage=typeof c=="string"&&c.trim()?Boe(c.trim(),$oe):Boe(t.data,$oe)}if(s==="message_stop"&&(e.messageStopReceived=!0),s==="content_block_delta"&&n&&typeof n=="object"&&"delta"in n){const i=n.delta;i&&typeof i=="object"&&("text"in i&&typeof i.text=="string"&&i.text.trim().length>0||"partial_json"in i&&typeof i.partial_json=="string"&&i.partial_json.trim().length>0||"refusal"in i&&typeof i.refusal=="string"&&i.refusal.trim().length>0)&&e.firstUsefulOutputAt===void 0&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent=`content_block_delta.${"text"in i?"text":"refusal"in i?"refusal":"partial_json"}`)}if(e.firstUsefulOutputAt===void 0&&n&&typeof n=="object"){const i=n;s==="message_start"&&Toe(i.message)&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent="message_start.content");const a=i.content_block;if(s==="content_block_start"&&a&&typeof a=="object"){const c=a;(typeof c.text=="string"&&c.text.trim().length>0||typeof c.refusal=="string"&&c.refusal.trim().length>0||(c.type==="tool_use"||c.type==="server_tool_use")&&c.input&&typeof c.input=="object"&&Object.keys(c.input).length>0)&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent="content_block_start")}if(s==="content_block_stop"&&typeof i.index=="number"){const c=e.contentBlocks.find(l=>l.index===i.index);c?.type==="tool_use"&&c.toolName&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent="content_block_stop.tool_use")}}switch(s){case"message_start":$Jr(e,n);break;case"content_block_start":UJr(e,n);break;case"content_block_delta":BJr(e,n);break;case"message_delta":zJr(e,n);break;default:break}}function oF(e={}){const t=e.captureRawText??!1,r=NJr(t);let n="",o=!1,s=!1;const i=new TextDecoder;let a;const c=new Promise(w=>{a=w});function l(){s||(s=!0,n.trim()&&(r.observationIncomplete=!0),a(FJr(r)))}const u=new TransformStream({transform(w,E){E.enqueue(w),r.totalBytesReceived+=w.byteLength;const _=i.decode(w,{stream:!0});if(IXt(r,_),n+=_,o){const k=/\r\n\r\n|\n\n|\r\r/.exec(n);if(!k){n=n.slice(-4);return}n=n.slice(k.index+k[0].length),o=!1}const{events:b,remainder:A}=nF(n);n=A,n.length>1024*1024&&(r.observationIncomplete=!0,o=!0,n=n.slice(-4));for(const k of b)GJr(r,k)},flush(){const w=i.decode();w&&(IXt(r,w),n+=w),l()}}),d=u.writable.getWriter();let m;const h=new WritableStream({start(w){m=w},write(w){return d.write(w)},close(){return d.close()},abort(w){return l(),d.abort(w)}});d.closed.catch(w=>{l();try{m.error(w)}catch{}});const f=u.readable.getReader();return{stream:{readable:new ReadableStream({async pull(w){try{const{done:E,value:_}=await f.read();E?w.close():w.enqueue(_)}catch(E){w.error(E)}},async cancel(w){l();try{m.error(w)}catch{}await Promise.allSettled([f.cancel(w),d.abort(w)])}}),writable:h},telemetry:c}}Qt();var Jk=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0;function sF(e){if(!e||typeof e!="object")return!1;if("type"in e){if(e.type==="function_call")return"arguments"in e&&typeof e.arguments=="string"&&e.arguments.trim().length>0;if(e.type==="custom_tool_call")return"input"in e&&typeof e.input=="string"&&e.input.trim().length>0;if(e.type==="output_text")return"text"in e&&typeof e.text=="string"&&e.text.trim().length>0;if(e.type==="refusal")return"refusal"in e&&typeof e.refusal=="string"&&e.refusal.trim().length>0}return"content"in e&&Array.isArray(e.content)&&e.content.some(sF)}function Goe(e){if(e===null||typeof e!="object")return null;const t=e,r=t.response,n=r&&typeof r=="object"&&r.usage?r.usage:t.usage;if(!n||typeof n!="object")return null;const o=n.input_tokens??n.prompt_tokens,s=n.output_tokens??n.completion_tokens;if(o===void 0&&s===void 0)return null;const i=n.input_tokens_details,a=n.output_tokens_details;return{inputTokens:Jk(o),outputTokens:Jk(s),cacheReadTokens:Jk(i?.cached_tokens),cacheCreationTokens:Jk(i?.cache_write_tokens),reasoningTokens:Jk(a?.reasoning_tokens)}}var RXt=256*1024;function qJr(){const e=process.env.NEUROLINK_PROXY_CODEX_CAPTURE;if(!e||process.env.NEUROLINK_PROXY_LOG_SINK==="otel")return null;let t=0,r=!1;return n=>{if(!(t>=RXt))try{const o=RXt-t,s=n.byteLength>o?n.subarray(0,o):n;HS(e,s,{flag:r?"a":"w"}),r=!0,t+=s.byteLength}catch{}}}function jJr(){const e={completed:!1,terminalBytes:0};let t=0;const r=g=>{for(const y of g)if(y.data.trim()!=="[DONE]")try{const w=JSON.parse(y.data);if(!w||typeof w!="object"){e.observationIncomplete=!0;continue}const E=Goe(w);E&&(u=E);const _=w.type??y.event;(_==="response.output_text.delta"||_==="response.refusal.delta"||_==="response.function_call_arguments.delta")&&typeof w.delta=="string"&&w.delta.trim().length>0&&e.firstUsefulOutputAt===void 0&&(e.firstUsefulOutputAt=Date.now(),e.firstUsefulOutputEvent=String(_));const b=sF(w.item),A=w.response,k=_==="response.completed"&&A&&typeof A=="object"&&"output"in A&&Array.isArray(A.output)&&A.output.some(sF),R=_==="response.output_text.done"&&typeof w.text=="string"&&w.text.trim().length>0||_==="response.refusal.done"&&typeof w.refusal=="string"&&w.refusal.trim().length>0||_==="response.function_call_arguments.done"&&typeof w.arguments=="string"&&w.arguments.trim().length>0||_==="response.custom_tool_call_input.done"&&typeof w.input=="string"&&w.input.trim().length>0||(_==="response.content_part.added"||_==="response.content_part.done")&&sF(w.part),I=_==="response.custom_tool_call_input.delta"&&typeof w.delta=="string"&&w.delta.trim().length>0;if(e.firstUsefulOutputAt===void 0&&(R||k||I||(_==="response.output_item.added"||_==="response.output_item.done")&&b)&&(e.firstUsefulOutputAt=Date.now(),e.firstUsefulOutputEvent=String(_)),_==="response.completed")e.completed=!0,e.terminalBytes=t;else if(_==="error"||_==="response.failed"||_==="response.incomplete"){e.errorType="stream_error";const x=w.response,M=x&&typeof x=="object"?x:w,O=M.error,U=O&&typeof O=="object"?O:M,P=M.incomplete_details,N=P&&typeof P=="object"&&"reason"in P?P.reason:void 0;e.errorCode=typeof U.code=="string"?qr(U.code).slice(0,200):typeof N=="string"?qr(N).slice(0,200):String(_),e.errorMessage=typeof U.message=="string"?qr(U.message).slice(0,200):_==="response.incomplete"?"Codex reported an incomplete response":"Codex reported a stream failure",e.terminalBytes=t}}catch{e.observationIncomplete=!0}};let n=()=>{};const o=new Promise(g=>{n=g});let s=!1;const i=g=>{s||(s=!0,n(g))},a=new TextDecoder,c=qJr();let l="",u=null;const d=1024*1024;let m=!1;const h={transform(g,y){y.enqueue(g),t+=g.byteLength;try{if(c?.(g),l+=a.decode(g,{stream:!0}),m){const _=/\r\n\r\n|\n\n|\r\r/.exec(l);if(!_){l=l.slice(-3);return}l=l.slice(_.index+_[0].length),m=!1}const{events:w,remainder:E}=nF(l);l=E,r(w),l.length>d&&(e.observationIncomplete=!0,l=l.slice(-2),m=!0)}catch{e.observationIncomplete=!0}},flush(){(m||l.trim())&&(e.observationIncomplete=!0),i(u)},cancel(){i(u)}};return{stream:new TransformStream(h),usage:o,evidence:()=>({...e})}}var Yk=class extends Error{status;responseBody;constructor(e,t){super(`Codex fallback request returned HTTP ${e}`),this.name="CodexFallbackResponseError",this.status=e,this.responseBody=t}};function Pl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ow(e){return typeof e=="string"&&e.length>0?e:void 0}function HJr(e){const t=[];if(typeof e.system=="string")e.system&&t.push(e.system);else if(Array.isArray(e.system)){const r=e.system.map(n=>typeof n.text=="string"?n.text:"").filter(Boolean).join(`
2284
2284
 
2285
- `)||void 0}function VJr(e){if(e.source.type==="url"&&e.source.url)return e.source.url;if(e.source.type==="base64"&&e.source.data)return`data:${e.source.media_type??"image/png"};base64,${e.source.data}`}function MXt(e){return typeof e=="string"?e:e.map(t=>{switch(t.type){case"text":return t.text;case"thinking":return t.thinking;case"image":return"[image attachment]";case"tool_use":return`[tool call ${t.name}] ${JSON.stringify(t.input??{})}`;case"tool_result":return MXt(t.content)}}).join(`
2286
- `)}function WJr(e,t){const r=t==="assistant"?"output_text":"input_text";switch(e.type){case"text":return{type:r,text:e.text};case"thinking":return{type:r,text:e.thinking};case"image":{const n=VJr(e);return t==="user"&&n?{type:"input_image",image_url:n}:{type:r,text:"[image attachment]"}}}}function KJr(e,t){if(typeof t=="string")return[{role:e,content:[{type:e==="assistant"?"output_text":"input_text",text:t}]}];const r=[];let n=[];const o=()=>{n.length!==0&&(r.push({role:e,content:n}),n=[])};for(const s of t){if(s.type==="tool_use"){o(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});continue}if(s.type==="tool_result"){o(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:MXt(s.content)});continue}n.push(WJr(s,e))}return o(),r}function JJr(e,t,r){const n=e.messages.flatMap(i=>KJr(i.role,i.content)),o={model:t,input:n,stream:!0,store:!1,...r!==void 0?{reasoning:{effort:r}}:{}},s=HJr(e);if(s&&(o.instructions=s),e.tools&&e.tools.length>0&&(o.tools=e.tools.map(i=>({type:"function",name:i.name,...i.description?{description:i.description}:{},parameters:i.input_schema}))),e.tool_choice)switch(e.tool_choice.type){case"any":o.tool_choice="required";break;case"tool":o.tool_choice={type:"function",name:e.tool_choice.name};break;default:o.tool_choice=e.tool_choice.type;break}return o}function YJr(e){if(Pl(e))return e;if(typeof e!="string")throw new Error("Codex fallback function call is missing JSON arguments");try{const t=JSON.parse(e||"{}");if(!Pl(t))throw new Error("not an object");return t}catch{throw new Error("Codex fallback function call returned invalid JSON arguments")}}function qoe(e){return!Pl(e)||e.type!=="message"||!Array.isArray(e.content)?"":e.content.filter(Pl).filter(t=>t.type==="output_text").map(t=>typeof t.text=="string"?t.text:"").join("")}function PXt(e,t){if(e.type!=="function_call")return;const r=Ow(e.call_id),n=Ow(e.name);if(!r||!n)throw new Error("Codex fallback function call is missing an id or name");t.set(r,{toolCallId:r,toolName:n,args:YJr(e.arguments)})}function DXt(e){const t=e.replace(/\r\n?/g,`
2285
+ `);r&&t.push(r)}for(const r of e.messages){if(r.role!=="system")continue;const n=typeof r.content=="string"?r.content:r.content.map(o=>o.type==="text"?o.text:"").filter(Boolean).join(`
2286
+ `);n&&t.push(n)}return t.length>0?t.join(`
2287
+
2288
+ `):void 0}function VJr(e){if(e.source.type==="url"&&e.source.url)return e.source.url;if(e.source.type==="base64"&&e.source.data)return`data:${e.source.media_type??"image/png"};base64,${e.source.data}`}function MXt(e){return typeof e=="string"?e:e.map(t=>{switch(t.type){case"text":return t.text;case"thinking":return t.thinking;case"image":return"[image attachment]";case"tool_use":return`[tool call ${t.name}] ${JSON.stringify(t.input??{})}`;case"tool_result":return MXt(t.content)}}).join(`
2289
+ `)}function WJr(e,t){const r=t==="assistant"?"output_text":"input_text";switch(e.type){case"text":return{type:r,text:e.text};case"thinking":return{type:r,text:e.thinking};case"image":{const n=VJr(e);return t==="user"&&n?{type:"input_image",image_url:n}:{type:r,text:"[image attachment]"}}}}function KJr(e,t){if(typeof t=="string")return[{role:e,content:[{type:e==="assistant"?"output_text":"input_text",text:t}]}];const r=[];let n=[];const o=()=>{n.length!==0&&(r.push({role:e,content:n}),n=[])};for(const s of t){if(s.type==="tool_use"){o(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});continue}if(s.type==="tool_result"){o(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:MXt(s.content)});continue}if(s.type==="tool_addition")continue;const i=WJr(s,e);i&&n.push(i)}return o(),r}function JJr(e,t,r){const n=e.messages.flatMap(i=>i.role==="system"?[]:KJr(i.role,i.content)),o={model:t,input:n,stream:!0,store:!1,...r!==void 0?{reasoning:{effort:r}}:{}},s=HJr(e);if(s&&(o.instructions=s),e.tools&&e.tools.length>0&&(o.tools=e.tools.map(i=>({type:"function",name:i.name,...i.description?{description:i.description}:{},parameters:i.input_schema}))),e.tool_choice)switch(e.tool_choice.type){case"any":o.tool_choice="required";break;case"tool":o.tool_choice={type:"function",name:e.tool_choice.name};break;default:o.tool_choice=e.tool_choice.type;break}return o}function YJr(e){if(Pl(e))return e;if(typeof e!="string")throw new Error("Codex fallback function call is missing JSON arguments");try{const t=JSON.parse(e||"{}");if(!Pl(t))throw new Error("not an object");return t}catch{throw new Error("Codex fallback function call returned invalid JSON arguments")}}function qoe(e){return!Pl(e)||e.type!=="message"||!Array.isArray(e.content)?"":e.content.filter(Pl).filter(t=>t.type==="output_text").map(t=>typeof t.text=="string"?t.text:"").join("")}function PXt(e,t){if(e.type!=="function_call")return;const r=Ow(e.call_id),n=Ow(e.name);if(!r||!n)throw new Error("Codex fallback function call is missing an id or name");t.set(r,{toolCallId:r,toolName:n,args:YJr(e.arguments)})}function DXt(e){const t=e.replace(/\r\n?/g,`
2287
2290
  `).split(`
2288
2291
 
2289
2292
  `),r=[];for(const n of t){if(!n.trim())continue;let o;const s=[];for(const a of n.split(`