@juspay/neurolink 12.23.2 → 12.23.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,8 +1,9 @@
1
- ## [12.23.2](https://github.com/juspay/neurolink/compare/v12.23.1...v12.23.2) (2026-09-25)
1
+ ## [12.23.3](https://github.com/juspay/neurolink/compare/v12.23.2...v12.23.3) (2026-09-25)
2
2
 
3
3
  ### Bug Fixes
4
4
 
5
- - **(docs-site):** make search-index.json generation reproducible ([86487c2](https://github.com/juspay/neurolink/commit/86487c287265664d415ef177af533ceb5b4c3c26)), closes [#1749](https://github.com/juspay/neurolink/issues/1749)
5
+ - **(analytics):** stop double-billing cached input tokens in the native loop ([c26e6eb](https://github.com/juspay/neurolink/commit/c26e6eb1c4460c9e13455ff5fde0882d56ce3adf))
6
+ - **(streaming):** split cache-inclusive input on the no-tool-call stream path ([8521098](https://github.com/juspay/neurolink/commit/8521098bb790c48ab78aa56ea611edd643967c77))
6
7
 
7
8
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
8
9
 
@@ -1007,7 +1007,7 @@ ${k}`,l++}else Bft(v,w,_)?u=v.slice(v.charCodeAt(w+6)===up?w+7:w+6,S)||void 0:h(
1007
1007
  `,w);let C=-1;if(S!==-1&&_!==-1?C=S<_?S:_:S!==-1?S===v.length-1?C=-1:C=S:_!==-1&&(C=_),C===-1)break;h(v,w,C),w=C+1,v.charCodeAt(w-1)===zft&&v.charCodeAt(w)===fW&&w++}return v.slice(w)}function h(v,w,S){if(w===S){g();return}const _=v.charCodeAt(w);if(Uft(v,w,_)){const M=v.charCodeAt(w+5)===up?w+6:w+5,D=v.slice(M,S);c=l===0?D:`${c}
1008
1008
  ${D}`,l++;return}if(Bft(v,w,_)){u=v.slice(v.charCodeAt(w+6)===up?w+7:w+6,S)||void 0;return}if(_===105&&v.charCodeAt(w+1)===100&&v.charCodeAt(w+2)===58){const M=v.slice(v.charCodeAt(w+3)===up?w+4:w+3,S);a=M.includes("\0")?void 0:M;return}if(_===58){if(o){const M=v.slice(w,S);o(M.slice(v.charCodeAt(w+1)===up?2:1))}return}const C=v.slice(w,S),k=C.indexOf(":");if(k===-1){f(C,"",C);return}const A=C.slice(0,k),I=C.charCodeAt(k+1)===up?2:1,R=C.slice(k+I);f(A,R,C)}function f(v,w,S){switch(v){case"event":u=w||void 0;break;case"data":c=l===0?w:`${c}
1009
1009
  ${w}`,l++;break;case"id":a=w.includes("\0")?void 0:w;break;case"retry":/^\d+$/.test(w)?n(parseInt(w,10)):r(new hW(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:S}));break;default:r(new hW(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:w,line:S}));break}}function g(){l>0&&t({id:a,event:u,data:c}),a=void 0,c="",l=0,u=void 0}function y(v={}){if(v.consume&&s.length>0){const w=s.join("");h(w,0,w.length)}i=!0,a=void 0,c="",l=0,u=void 0,s.length=0}return{feed:d,reset:y}}function Uft(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Bft(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var hW,fW,zft,up,gW=b({"node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/index.js"(){hW=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},fW=10,zft=13,up=32}}),qft={};se(qft,{createAnnotatedTool:()=>jft,filterToolsByAnnotations:()=>Wft,getAnnotationSummary:()=>Kft,getToolSafetyLevel:()=>Vft,inferAnnotations:()=>Md,isSafeToRetry:()=>vW,mergeAnnotations:()=>yW,requiresConfirmation:()=>Hft,validateAnnotations:()=>Gft});function Md(e){const t=e.name,r=e.description.toLowerCase(),n={},o=(l,u)=>new RegExp(`\\b${u}\\b`,"i").test(l)?!0:l.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[_-]/).some(m=>m===u.toLowerCase());return["get","list","read","fetch","query","search","find","show","display","view","retrieve","check","inspect","look"].some(l=>o(r,l)||o(t,l))&&(n.readOnlyHint=!0),["delete","remove","drop","destroy","clear","purge","erase","wipe","truncate","reset"].some(l=>o(r,l)||o(t,l))&&(n.destructiveHint=!0,n.requiresConfirmation=!0),["set","update","put","upsert","replace"].some(l=>o(r,l)||o(t,l))&&!n.destructiveHint&&(n.idempotentHint=!0),["complex","analyze","process","generate","transform","compute","calculate"].some(l=>o(r,l)||o(t,l))?n.complexity="complex":r.length>100?n.complexity="medium":n.complexity="simple",n}function yW(...e){const t={};for(const r of e)if(r){const n=t.tags?[...t.tags]:[];if(Object.assign(t,r),n.length>0||r.tags){const o=r.tags??[];t.tags=[...new Set([...n,...o])]}}return t}function Gft(e){const t=[];if(e.readOnlyHint&&e.destructiveHint&&t.push("Tool cannot be both readOnly and destructive - these are conflicting hints"),e.rateLimitHint!==void 0&&(e.rateLimitHint<0||!Number.isFinite(e.rateLimitHint))&&t.push("rateLimitHint must be a non-negative number"),e.estimatedDuration!==void 0&&(e.estimatedDuration<0||!Number.isFinite(e.estimatedDuration))&&t.push("estimatedDuration must be a non-negative number"),e.costHint!==void 0&&(e.costHint<0||!Number.isFinite(e.costHint))&&t.push("costHint must be a non-negative number"),e.tags){for(const r of e.tags)if(typeof r!="string"||r.length===0){t.push("All tags must be non-empty strings");break}}return t}function jft(e){const t=Md(e),r=yW(t,e.annotations);return{...e,annotations:r}}function Hft(e){return!!(e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)}function vW(e){return!!(e.annotations?.idempotentHint||e.annotations?.readOnlyHint)}function Vft(e){return e.annotations?.destructiveHint?"dangerous":e.annotations?.readOnlyHint?"safe":(e.annotations?.idempotentHint,"moderate")}function Wft(e,t){return e.filter(r=>{const n=r.annotations??{};return t(n)})}function Kft(e){const t=[];return e.title&&t.push(e.title),e.readOnlyHint&&t.push("read-only"),e.destructiveHint&&t.push("DESTRUCTIVE"),e.idempotentHint&&t.push("idempotent"),e.requiresConfirmation&&t.push("requires confirmation"),e.complexity&&t.push(`${e.complexity} complexity`),e.estimatedDuration!==void 0&&t.push(`~${e.estimatedDuration}ms`),e.tags?.length&&t.push(`tags: ${e.tags.join(", ")}`),t.length>0?`[${t.join(" | ")}]`:"[no annotations]"}var T_=b({"src/lib/mcp/toolAnnotations.ts"(){"use strict"}}),TW={};se(TW,{TOOL_COMPATIBILITY:()=>bW,batchConvertToMCP:()=>Xft,batchConvertToNeuroLink:()=>Zft,createToolFromFunction:()=>Qft,mcpProtocolToolToServerTool:()=>Jft,mcpToolToNeuroLink:()=>EW,neuroLinkToolToMCP:()=>wW,sanitizeToolName:()=>SW,serverToolToMCPProtocol:()=>Yft,validateToolName:()=>egt});function wW(e,t={}){const{inferAnnotations:r=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:s}=t,i=s?`${s}_${e.name}`:e.name,a=r?Md({name:e.name,description:e.description}):{},c={...n,...a};e.tags?.length&&(c.tags=[...new Set([...c.tags??[],...e.tags])]);const l=e.parameters??{type:"object",properties:{}},u=o?{...e.metadata}:{};return e.category&&(u.category=e.category),e.isAsync!==void 0&&(u.isAsync=e.isAsync),{name:i,description:e.description,inputSchema:l,annotations:c,execute:e.execute,metadata:u}}function EW(e,t={}){const{removeNamespacePrefix:r}=t;let n=e.name;return r&&e.name.startsWith(`${r}_`)&&(n=e.name.slice(r.length+1)),{name:n,description:e.description,parameters:e.inputSchema,execute:e.execute,category:e.metadata?.category,tags:e.annotations?.tags,metadata:e.metadata}}function Jft(e,t,r={}){const{inferAnnotations:n=!0,defaultAnnotations:o={}}=r,s=e.annotations??{},i=n?Md({name:e.name,description:e.description??""}):{},a={...o,...i,title:s.title??i.title??o.title,readOnlyHint:s.readOnlyHint??i.readOnlyHint??o.readOnlyHint,destructiveHint:s.destructiveHint??i.destructiveHint??o.destructiveHint,idempotentHint:s.idempotentHint??i.idempotentHint??o.idempotentHint,openWorldHint:s.openWorldHint??i.openWorldHint??o.openWorldHint};return{name:e.name,description:e.description??"No description provided",inputSchema:e.inputSchema,annotations:a,execute:t}}function Yft(e){const t={};e.annotations?.title&&(t.title=e.annotations.title),e.annotations?.readOnlyHint!==void 0&&(t.readOnlyHint=e.annotations.readOnlyHint),e.annotations?.destructiveHint!==void 0&&(t.destructiveHint=e.annotations.destructiveHint),e.annotations?.idempotentHint!==void 0&&(t.idempotentHint=e.annotations.idempotentHint),e.annotations?.openWorldHint!==void 0&&(t.openWorldHint=e.annotations.openWorldHint);const r=e.inputSchema??{type:"object",properties:{}};return{name:e.name,description:e.description,inputSchema:{type:"object",properties:r.properties??{},required:"required"in r?r.required:void 0},annotations:Object.keys(t).length>0?t:void 0}}function Xft(e,t={}){return e.map(r=>wW(r,t))}function Zft(e,t={}){return e.map(r=>EW(r,t))}function Qft(e,t,r,n){const o=Md({name:e,description:t});return{name:e,description:t,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(s,i)=>await _t(r(s,i),3e4,`Tool '${e}' execution timed out after 30000ms`),metadata:n?.metadata}}function egt(e){const t=[];return!e||typeof e!="string"?t.push("Tool name is required and must be a string"):(e.length>64&&t.push("Tool name must be 64 characters or less"),/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e)||t.push("Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens")),{valid:t.length===0,errors:t}}function SW(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return/^[a-zA-Z_]/.test(t)||(t=`_${t}`),t.length>64&&(t=t.slice(0,64)),t}var bW,_P=b({"src/lib/mcp/toolConverter.ts"(){"use strict";T_(),Lr(),bW={MCP_2024_11_05:{annotations:!0,inputSchema:!0,outputSchema:!1,streamingResults:!1,batchExecution:!1},NEUROLINK:{annotations:!0,inputSchema:!0,outputSchema:!0,streamingResults:!0,batchExecution:!0,categories:!0,tags:!0}}}});function F1r(e){const t=e?.error?.message;if(typeof t=="string"&&t.trim().length>0)return t;if(Array.isArray(t)){const r=t.map(n=>n.msg?.trim()).filter(n=>n!==void 0&&n.length>0);if(r.length>0)return r.join("; ")}return typeof e?.detail=="string"&&e.detail.trim().length>0?e.detail:void 0}var Ca,_W,CP,CW,bl,w_,kW,AW,tgt,xW,IW,rgt,ngt,RW,MW,ogt,sgt,X0,Rf,igt,agt,cgt,PW,lgt,DW,OW,E_,NW,ugt,dp=b({"src/lib/providers/openaiChatCompletionsClient.ts"(){"use strict";gW(),_P(),id(),di(),is(),Ca=e=>e.replace(/\/+$/,""),_W=/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/,CP=(e,t)=>{if(e.every(o=>_W.test(o)&&!t?.has(o)))return;const r=new Map,n=new Map;for(const o of e){let s=_W.test(o)?o:SW(o);if(n.has(s)||t?.has(s)){let i=2,a;do{const c=`_${i}`;a=`${s.slice(0,64-c.length)}${c}`,i++}while(n.has(a)||t?.has(a));s=a}r.set(o,s),n.set(s,o)}return{toWire:r,fromWire:n}},CW=(e,t,r)=>{let n=0;for(const o of e){if(Array.isArray(o.content)){for(const i of o.content)n+=i.type==="image_url"?o_:Zt(i.text,r);n+=Dc}else{const i=typeof o.content=="string"?o.content:bl(o.content);n+=Zt(i,r)+Dc}const s=o.tool_calls;s&&(n+=Zt(bl(s),r))}return t&&t.length>0&&(n+=Zt(bl(t),r)),n},bl=e=>{try{return JSON.stringify(e??"")}catch{return String(e??"")}},w_=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return"{}"}},kW=e=>{if(e==null)return"";if(typeof e=="string")return e;if(typeof e!="object")return String(e);const t=e;switch(t.type){case"text":return typeof t.value=="string"?t.value:bl(t.value);case"json":return bl(t.value);case"execution-denied":return`Tool execution denied${t.reason?`: ${t.reason}`:""}`;case"error-text":return typeof t.value=="string"?t.value:bl(t.value);case"error-json":return bl(t.value);case"content":return Array.isArray(t.value)?t.value.map(r=>r&&typeof r=="object"&&r.type==="text"?String(r.text??""):"").filter(r=>r.length>0).join(`
1010
- `):"";default:return bl(e)}},AW=(e,t)=>{const r=t&&t.includes("/")?t:"image/png";if(typeof e=="string")return e.startsWith("data:")||/^https?:\/\//i.test(e)?e:`data:${r};base64,${e}`;if(e instanceof URL)return e.toString();if(e instanceof Uint8Array)return`data:${r};base64,${Buffer.from(e).toString("base64")}`},tgt=e=>{if(typeof e=="string")return e;if(!Array.isArray(e))return bl(e);const t=[];for(const r of e){if(typeof r=="string"){t.push({type:"text",text:r});continue}if(!r||typeof r!="object")continue;const n=r;if(n.type==="text")t.push({type:"text",text:r.text??""});else if(n.type==="image"||n.type==="image_url"){const o=r.image??r.data??r.url,s=r.mediaType??r.mimeType,i=AW(o,s);i&&t.push({type:"image_url",image_url:{url:i}})}else if(n.type==="file"){const o=r;if(o.mediaType?.startsWith("image/")){const s=AW(o.data,o.mediaType);s&&t.push({type:"image_url",image_url:{url:s}})}}}return t.length===1&&t[0].type==="text"?t[0].text:t},xW=(e,t)=>{const r=[];for(const n of e)switch(n.role){case"system":r.push({role:"system",content:typeof n.content=="string"?n.content:bl(n.content)});break;case"user":r.push({role:"user",content:tgt(n.content)});break;case"assistant":{const o=Array.isArray(n.content)?n.content:[n.content],s=[],i=[];for(const c of o)if(c&&typeof c=="object"){const l=c;if(l.type==="text")s.push({type:"text",text:c.text??""});else if(l.type==="tool-call"){const u=c,d=u.toolName??"";i.push({id:u.toolCallId??"",type:"function",function:{name:t?.get(d)??d,arguments:w_(u.input)}})}}else typeof c=="string"&&s.push({type:"text",text:c});const a=s.length===0?null:s.length===1&&s[0].type==="text"?s[0].text:s;r.push({role:"assistant",content:a,...i.length>0?{tool_calls:i}:{}});break}case"tool":{if(Array.isArray(n.content))for(const o of n.content){if(!o||typeof o!="object")continue;const s=o;s.type==="tool-result"&&r.push({role:"tool",tool_call_id:s.toolCallId??"",content:kW(s.output)})}else typeof n.content=="string"&&r.push({role:"tool",tool_call_id:n.toolCallId??"",content:n.content});break}}return r},IW=(e,t)=>{const r=Object.entries(e);if(r.length===0)return;const n=[];for(const[o,s]of r){const i=s,a=i.inputSchema??i.parameters,c=a?_Ue(No(a)):{type:"object",properties:{}};n.push({type:"function",function:{name:t?.get(o)??o,...i.description?{description:i.description}:{},parameters:c}})}return n},rgt=(e,t)=>{if(!e||e.length===0)return;const r=[];for(const n of e)n.type==="function"&&r.push({type:"function",function:{name:t?.get(n.name)??n.name,...n.description?{description:n.description}:{},parameters:_Ue(n.inputSchema),...n.strict!==void 0?{strict:n.strict}:{}}});return r.length>0?r:void 0},ngt=(e,t)=>{switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:t?.get(e.toolName)??e.toolName}}}},RW=["properties","patternProperties","$defs","definitions"],MW=["items","prefixItems","anyOf","oneOf","allOf","not","then","else"],ogt=["allOf","not","if","then","else"],sgt=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([r,n])=>[r,t(n)])),X0=e=>{if(Array.isArray(e))return e.map(X0);if(!e||typeof e!="object")return e;const t={...e};for(const r of RW)r in t&&(t[r]=sgt(t[r],X0));for(const r of MW)r in t&&(t[r]=X0(t[r]));return t.additionalProperties&&typeof t.additionalProperties=="object"?t.additionalProperties=X0(t.additionalProperties):t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1),t},Rf=e=>{if(Array.isArray(e))return e.every(Rf);if(!e||typeof e!="object")return!0;const t=e;if(ogt.some(o=>o in t))return!1;if(t.type==="object"){if(t.additionalProperties!==!1)return!1;const o=Object.keys(t.properties??{}),s=Array.isArray(t.required)?t.required:[];if(o.some(i=>!s.includes(i)))return!1}const r=RW.filter(o=>o in t).every(o=>Object.values(t[o]??{}).every(Rf)),n=MW.filter(o=>o in t).every(o=>Rf(t[o]));return r&&n},igt=e=>{if(e.type==="text")return{type:"text"};if(!e.schema)return{type:"json_object"};const t=e.schema,r=X0(t),n=Rf(t)?t:Rf(r)?r:t;return{type:"json_schema",json_schema:{name:e.name??"response",schema:n,...e.description?{description:e.description}:{},strict:Rf(n)}}},agt=(e,t)=>{if(e){if(e==="auto"||e==="none"||e==="required")return e;if(typeof e=="object"&&e!==null){const r=e;if(r.type==="tool"&&r.toolName)return{type:"function",function:{name:t?.get(r.toolName)??r.toolName}}}}},cgt=e=>e.some(t=>{const r=t.content;return typeof r=="string"?/\bjson\b/i.test(r):Array.isArray(r)?r.some(n=>typeof n?.text=="string"&&/\bjson\b/i.test(n.text)):!1}),PW=e=>e.response_format?.type==="json_object"&&!cgt(e.messages)?{...e,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...e.messages]}:e,lgt=e=>/^(o\d|gpt-5)/i.test(e.replace(/^.*\//,"")),DW=e=>{const{modelId:t,messages:r,options:n,tools:o,toolChoice:s,streaming:i,responseFormat:a}=e,c={model:t,messages:r,...i?{stream:!0}:{},...i?{stream_options:{include_usage:!0}}:{}};n.maxTokens!==void 0&&n.maxTokens!==null&&(c.max_tokens=n.maxTokens);const l=ml("openai-compatible",t,{...n.temperature!==void 0&&n.temperature!==null?{temperature:n.temperature}:{},...n.topP!==void 0&&n.topP!==null?{topP:n.topP}:{}},"openaiCompatible.buildBody");return l.temperature!==void 0&&(c.temperature=l.temperature),l.topP!==void 0&&(c.top_p=l.topP),n.presencePenalty!==void 0&&n.presencePenalty!==null&&(c.presence_penalty=n.presencePenalty),n.frequencyPenalty!==void 0&&n.frequencyPenalty!==null&&(c.frequency_penalty=n.frequencyPenalty),n.seed!==void 0&&n.seed!==null&&(c.seed=n.seed),n.stopSequences&&n.stopSequences.length>0&&(c.stop=n.stopSequences),o&&(c.tools=o),s!==void 0&&o&&o.length>0&&(c.tool_choice=s),a&&(c.response_format=a),n.extraBody&&Object.assign(c,n.extraBody),c},OW=async(e,t,r)=>{const n={text:"",reasoning:"",toolCalls:new Map,finishReason:null,usage:void 0},o=new TextDecoder;let s;const a=pW({onEvent:l=>{const u=l.data;if(!u||u==="[DONE]")return;let d;try{d=JSON.parse(u)}catch(g){s=g instanceof Error?g:new Error(String(g));return}d.usage&&(n.usage=d.usage),d.id&&!n.id&&(n.id=d.id),d.model&&!n.model&&(n.model=d.model);const m=d.choices?.[0];if(!m)return;const h=m.delta;h?.content&&(n.text+=h.content,t(h.content));const f=h?.reasoning_content||h?.reasoning;if(f&&(n.reasoning+=f,r?.(f)),h?.tool_calls)for(const g of h.tool_calls){let y=n.toolCalls.get(g.index);y?g.id&&(y.id=g.id):(y={id:g.id??`call_${g.index}_${Date.now()}`,name:g.function?.name??"",argsBuffered:""},n.toolCalls.set(g.index,y)),g.function?.name&&(y.name=g.function.name),g.function?.arguments&&(y.argsBuffered+=g.function.arguments)}m.finish_reason&&(n.finishReason=m.finish_reason)}}),c=e.getReader();try{for(;;){const{done:l,value:u}=await c.read();if(l)break;a.feed(o.decode(u,{stream:!0}))}a.feed(o.decode())}finally{c.releaseLock()}if(s)throw s;return n},E_=async(e,t,r)=>{let n,o;try{n=await r.text(),o=n?JSON.parse(n):void 0}catch{o=void 0}const s=F1r(o)??`OpenAI-compatible request failed with status ${r.status}`,i=new Error(s);return i.statusCode=r.status,i.responseHeaders=Object.fromEntries([...r.headers.entries()].filter(([a])=>{const c=a.toLowerCase();return c==="retry-after"||c.startsWith("x-ratelimit-")})),i.url=e,i.requestBody={model:t.model,stream:t.stream===!0,tool_count:t.tools?.length??0},n!==void 0&&(i.responseBody=n),i},NW=()=>{let e=()=>{};const t=new Promise(o=>{e=o});let r=()=>{};const n=new Promise(o=>{r=o});return{usagePromise:t,finishPromise:n,resolveUsage:e,resolveFinish:r}},ugt=(e,t)=>{if(!e)return t;if(!t)return e;const r=(e.prompt_tokens_details?.cached_tokens??0)+(t.prompt_tokens_details?.cached_tokens??0),n=(e.completion_tokens_details?.reasoning_tokens??0)+(t.completion_tokens_details?.reasoning_tokens??0),o=s=>s.total_tokens||(s.prompt_tokens??0)+(s.completion_tokens??0);return{prompt_tokens:(e.prompt_tokens??0)+(t.prompt_tokens??0),completion_tokens:(e.completion_tokens??0)+(t.completion_tokens??0),total_tokens:o(e)+o(t),...r>0?{prompt_tokens_details:{cached_tokens:r}}:{},...n>0?{completion_tokens_details:{reasoning_tokens:n}}:{}}}}});function kP(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function $1r(e,t){let r=kP(e.content);return e.role==="assistant"&&e.tool_calls&&(r+=kP(e.tool_calls)),Zt(r,t)+Dc}function U1r(e,t){if(e.role!=="tool")return;const r=kP(e.content),n={maxBytes:LW,maxLines:FW};if(!zmt(r,n))return;const{preview:o}=Qa(r,n);return Zt(o,t)+Dc}function B1r(e,t){return e.map(r=>{const n=$1r(r,t);if(r.role==="tool"){const o=U1r(r,t);return{kind:"toolResult",tokens:n,...o!==void 0?{previewTokens:o}:{}}}return r.role==="assistant"&&r.tool_calls?.length?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function z1r(e){const{conversation:t,availableInputTokens:r,fixedOverheadTokens:n,provider:o,observedPromptTokens:s,previousSentEstimate:i,onSentEstimate:a}=e,c=B1r(t,o),l=n+c.reduce((g,y)=>g+y.tokens,0);let u=1;s&&s>0&&i&&i>0&&(u=Math.min(3,Math.max(1,s/i)));const d=TP(c,{availableInputTokens:r,fixedOverheadTokens:n,calibration:u});if(!d.fire){a?.(l);return}const m=new Set(d.truncate),h=new Set(d.drop),f=[];for(let g=0;g<t.length;g++){if(h.has(g))continue;const y=t[g];if(m.has(g)&&y.role==="tool"){const{preview:v}=Qa(kP(y.content),{maxBytes:LW,maxLines:FW});f.push({...y,content:v});continue}f.push(y)}if(h.size>0){let g=f.findIndex(y=>y.role==="tool"||y.role==="assistant"&&y.tool_calls);g<0&&(g=Math.min(1,f.length)),f.splice(g,0,{role:"user",content:dgt})}return p.info("[OpenAICompatLoopGuard] Reclaimed agent-loop context",{provider:o,messagesBefore:t.length,messagesAfter:f.length,toolOutputsTruncated:d.truncate.length,messagesDropped:d.drop.length,projectedTokens:d.projectedTokens,calibration:u}),a?.(d.projectedTokens),f}var LW,FW,dgt,q1r=b({"src/lib/context/openaiCompatLoopGuard.ts"(){"use strict";is(),wf(),wP(),B(),LW=2048,FW=60,dgt="[Earlier tool exchanges were removed to fit the context window.]"}});function G1r(e){let t,r;const n=o=>Zt(UW(o),e.provider)+Dc;return{observeUsage(o){const s=S_(o)?o.inputTokens:void 0,i=S_(s)?s.total:s;r=typeof i=="number"&&Number.isFinite(i)&&i>0?i:void 0},guardConversation(o){const s=o.findIndex(S=>S.role==="user"),i=Math.max(1,s+1),a=o.slice(i),c=a.map(mgt),l=[{kind:"other",tokens:o.slice(0,i).reduce((S,_)=>S+n(_),0)},...a.map((S,_)=>{const C=$W(S.content);return S.role==="assistant"&&C.some(k=>k.type==="tool-call")?{kind:"toolCall",tokens:n(S)}:S.role==="tool"&&C.some(k=>k.type==="tool-result")?{kind:"toolResult",tokens:n(S),previewTokens:n(c[_])}:{kind:"other",tokens:n(S)}})],u=e.getFixedOverheadTokens(),d=r&&t?Math.min(3,Math.max(1,r/t)):1,m=TP(l,{availableInputTokens:e.availableInputTokens,fixedOverheadTokens:u,calibration:d}),h=Math.floor(e.availableInputTokens*JR/(d>0?d:1)),f=u+l.reduce((S,_)=>S+_.tokens,0);if(!m.fire){t=f,f>h?p.warn("[NativeGenerateGuard] Over threshold, nothing reclaimable",{provider:e.provider,availableInputTokens:e.availableInputTokens,reclaimThresholdTokens:h,estimatedPromptTokens:f,overThresholdByTokens:f-h,calibration:d}):p.debug("[NativeGenerateGuard] Under threshold",{provider:e.provider,availableInputTokens:e.availableInputTokens,reclaimThresholdTokens:h,estimatedPromptTokens:f,headroomToThresholdTokens:h-f,calibration:d});return}const g=new Set(m.drop),y=new Set(m.truncate),v=[...o.slice(0,i)];let w=!1;return a.forEach((S,_)=>{const C=_+1;g.has(C)?(w||v.push({role:"user",content:"[Earlier tool exchanges were removed to fit the context window.]"}),w=!0):v.push(y.has(C)?c[_]:S)}),t=u+v.reduce((S,_)=>S+n(_),0),p.info("[NativeGenerateGuard] Reclaimed context",{provider:e.provider,availableInputTokens:e.availableInputTokens,reclaimThresholdTokens:h,estimatedBeforeTokens:f,estimatedAfterTokens:t,truncated:m.truncate.length,dropped:m.drop.length,calibration:d}),v}}}var S_,$W,UW,mgt,j1r=b({"src/lib/context/nativeGenerateGuard.ts"(){"use strict";is(),B(),wP(),Do(),wf(),S_=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$W=e=>Array.isArray(e)?e.filter(S_):[],UW=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}},mgt=e=>({...e,content:$W(e.content).map(t=>{if(t.type!=="tool-result")return t;const r=t.output,n=S_(r)&&["text","json","error-text","error-json"].includes(String(r.type))&&"value"in r,{preview:o,truncated:s}=Qa(UW(n?r.value:r),{maxBytes:2048,maxLines:60});return s?{...t,output:n?{...r,type:String(r.type).startsWith("error")?"error-text":"text",value:o}:o}:t})})}});function BW(e){const t=qW(e);return t?GW.some(({patterns:r})=>r.some(n=>n.test(t))):!1}function H1r(e){const t=qW(e);if(!t)return null;for(const{provider:r,patterns:n}of GW)if(n.some(o=>o.test(t)))return r;return null}function zW(e){const t=qW(e);if(!t||t.length>2e3)return null;const r=t.match(/resulted\s+in\s+(\d[\d,]{0,19})\s*tokens/i),n=t.match(/maximum\s+context\s+length\s+is\s+(\d[\d,]{0,19})/i);if(r&&n)return{actualTokens:parseInt(r[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10)};const o=t.match(/prompt\s+contains\s+at\s+least\s+(\d[\d,]{0,19})\s+input\s+tokens/i);if(o&&n){const a=t.match(/requested\s+(\d[\d,]{0,19})\s+output\s+tokens/i);return{actualTokens:parseInt(o[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10),...a?{requestedOutputTokens:parseInt(a[1].replace(/,/g,""),10)}:{}}}const s=t.match(/(\d[\d,]{0,19})\s*tokens?\s*[>:]\s*(\d[\d,]{0,19})/i);if(s)return{actualTokens:parseInt(s[1].replace(/,/g,""),10),budgetTokens:parseInt(s[2].replace(/,/g,""),10)};const i=t.match(/(\d[\d,]{0,19})\s*(?:>|exceeds)\s*(\d[\d,]{0,19})/i);return i?{actualTokens:parseInt(i[1].replace(/,/g,""),10),budgetTokens:parseInt(i[2].replace(/,/g,""),10)}:null}function qW(e){if(!e)return null;if(typeof e=="string")return e;if(e instanceof Error){const t=e.message,r=e?.cause;return r instanceof Error?`${t} ${r.message}`:t}if(typeof e=="object"){const t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error;if(typeof t.error=="object"&&t.error!==null){const r=t.error;if(typeof r.message=="string")return r.message}}return null}var GW,pgt=b({"src/lib/context/errorDetection.ts"(){"use strict";GW=[{provider:"openai",patterns:[/This model's maximum context length is/i,/tokens\. However, (?:your messages|you requested)/i,/reduce the length of the messages/i,/Please reduce the length/i]},{provider:"azure",patterns:[/content_length_exceeded/i]},{provider:"google",patterns:[/RESOURCE_EXHAUSTED/i,/exceeds the maximum number of tokens/i,/content is too long/i,/request payload size exceeds/i,/input token limit/i]},{provider:"bedrock",patterns:[/ValidationException.*token/i,/Input is too long/i,/exceeds the model's maximum/i]},{provider:"mistral",patterns:[/context length exceeded/i,/maximum number of tokens/i]},{provider:"openrouter",patterns:[/context_length_exceeded/i]},{provider:"anthropic",patterns:[/prompt is too long/i,/input is too long/i,/too many tokens/i,/maximum context length/i]}]}}),ka,hgt=b({"src/lib/context/errors.ts"(){"use strict";ka=class extends Error{estimatedTokens;availableTokens;stagesUsed;breakdown;constructor(e,t){super(e),this.name="ContextBudgetExceededError",this.estimatedTokens=t.estimatedTokens,this.availableTokens=t.availableTokens,this.stagesUsed=t.stagesUsed,this.breakdown=t.breakdown}}}}),fgt,jW,ggt=b({"src/lib/core/streamAnalytics.ts"(){"use strict";pb(),B(),gM(),Dm(),fgt=class{async collectUsage(e){try{const t=await e.usage;return t?fM(t):(p.debug("No usage data available from stream result"),h3e())}catch(t){return ou.isInstance(t)?p.debug("No output generated from stream \u2014 returning empty usage"):p.warn("Failed to collect usage from stream result",{error:t}),h3e()}}async collectMetadata(e){try{const[t,r]=await Promise.all([e.response,e.finishReason]);return{id:t?.id,model:t?.model,timestamp:t?.timestamp instanceof Date?t.timestamp.getTime():t?.timestamp||Date.now(),finishReason:r}}catch(t){return ou.isInstance(t)?p.debug("No output generated from stream \u2014 returning default metadata"):p.warn("Failed to collect metadata from stream result",{error:t}),{timestamp:Date.now(),finishReason:"error"}}}async createAnalytics(e,t,r,n,o){try{const[s,i]=await Promise.all([this.collectUsage(r),this.collectMetadata(r)]),[a,c,l,u]=await Promise.all([Promise.resolve(r.text).catch(()=>""),Promise.resolve(r.finishReason).catch(()=>"error"),Promise.resolve(r.toolResults||[]).catch(()=>[]),Promise.resolve(r.toolCalls||[]).catch(()=>[])]);return p0(e,t,{usage:s,content:a,response:i,finishReason:c,toolResults:l,toolCalls:u},n,{...o,streamingMode:!0,responseId:i.id,finishReason:c})}catch(s){return p.error("Failed to create analytics from stream result",{provider:e,model:t,error:s instanceof Error?s.message:String(s)}),p0(e,t,{usage:{input:0,output:0,total:0}},n,{...o,streamingMode:!0,analyticsError:!0})}}cleanup(){const e=process.memoryUsage().heapUsed,t=500*1024*1024;typeof global<"u"&&global.gc&&e>t&&global.gc()}},jW=new fgt}});function ygt(e,t){if(!(!e||!t||t.length===0))for(const r of t){const n=r.output??r.result,o=!!r.error||n!=null&&typeof n=="object"&&"isError"in n&&n.isError===!0;let s;if(o){if(r.error)s=r.error;else if(n&&typeof n=="object"){const i=n.content;if(Array.isArray(i)){const a=i.filter(c=>c.type==="text"&&c.text).map(c=>c.text);s=a.length>0?a.join(" "):"Tool returned isError: true"}else s="Tool returned isError: true"}}e.emit("tool:end",F0(r.toolName,{responseTime:0,success:!o,timestamp:Date.now(),result:n,error:s}))}}var vgt=b({"src/lib/utils/toolEndEmitter.ts"(){"use strict";b9()}});async function HW(e,t){const r=[];let n="",o="",s="stop",i,a=0,c=0,l=0,u=0,d=0,m=!1,h=!1,f;const g=!!(e.tools&&e.tools.length>0);for(let y=0;y<e.maxSteps;y++){d=y+1;const v=e.guardConversation?.(e.conversation);v&&e.conversation.splice(0,e.conversation.length,...v);const w=()=>e.runStep(()=>e.doGenerate({prompt:e.conversation,...e.tools&&e.tools.length>0?{tools:e.tools}:{},...m?{toolChoice:{type:"none"}}:e.toolChoice!==void 0?{toolChoice:e.toolChoice}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.providerOptions?{providerOptions:e.providerOptions}:{},...e.maxOutputTokens?{maxOutputTokens:e.maxOutputTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{}}));let S;try{S=await w()}catch(M){if(h&&f){p.warn("toolChoice: none re-ask failed; returning the original result",{error:M instanceof Error?M.message:String(M)}),n=f.text,s=f.finishReason,i=f.rawFinishReason;break}throw M}h=!1,e.observeUsage?.(S.usage);const _=Tgt(S.content);n=_.filter(M=>M.type==="text"&&typeof M.text=="string").map(M=>M.text).join(""),o+=_.filter(M=>M.type==="reasoning"&&typeof M.text=="string").map(M=>M.text).join("");const C=S.finishReason;if(typeof C=="string")s=C;else if(typeof C=="object"&&C!==null){const M=C;s=M.unified??s,i=M.raw??i}const k=S.usage;a+=VW(k?.inputTokens),c+=VW(k?.outputTokens);const A=k?.inputTokens;l+=A?.cacheRead??0,u+=A?.cacheWrite??0;const I=_.filter(M=>M.type==="tool-call");if(I.length===0){if(s==="tool-calls"&&n.trim()===""&&g&&!m&&y+1<e.maxSteps){m=!0,h=!0,f={text:n,finishReason:s,rawFinishReason:i},e.conversation.push({role:"assistant",content:_});continue}break}e.conversation.push({role:"assistant",content:_});const R=[];for(const M of I){const D=String(M.toolName??""),U=String(M.toolCallId??""),P=new Date,$=wgt(M.input),N=$.input,F=e.toolsRecord[D];let j,z;const V=$.error??(typeof F?.execute=="function"?Egt(F,N):void 0);if(typeof F?.execute!="function")z=`Tool not found: ${D}`,j={error:z};else if(V)z=`Tool ${D}: ${V}`,j={error:z};else try{j=await _f(D,F.execute,{...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}})(N,{toolCallId:U,messages:[],...e.abortSignal?{abortSignal:e.abortSignal}:{}}),r.push(D)}catch(q){z=q instanceof Error?q.message:String(q),j={error:z}}t.push({toolCallId:U,toolName:D,input:N,...z?{error:z}:{output:j},startTime:P,endTime:new Date}),R.push({type:"tool-result",toolCallId:U,output:j})}e.conversation.push({role:"tool",content:R})}return{text:n,...o?{reasoning:o}:{},finishReason:s,...i?{rawFinishReason:i}:{},inputTokens:a,outputTokens:c,cacheReadTokens:l,cacheWriteTokens:u,toolsUsed:r,steps:d}}var AP,Tgt,VW,wgt,Egt,b_,WW=b({"src/lib/core/nativeGenerateLoop.ts"(){"use strict";B(),dP(),AP=e=>typeof e=="object"&&e!==null&&typeof e.doGenerate=="function",Tgt=e=>Array.isArray(e)?e:[],VW=e=>typeof e=="object"&&e!==null&&typeof e.total=="number"?e.total:0,wgt=e=>{if(typeof e!="string")return{input:e??{}};if(e.trim()==="")return{input:{}};try{return{input:JSON.parse(e)}}catch{return{input:{},error:"arguments were not valid JSON"}}},Egt=(e,t)=>{const r=e?.inputSchema;if(typeof r?.safeParse!="function")return;const n=r.safeParse(t);return n.success?void 0:`input did not match the tool's schema: ${n.error instanceof Error?n.error.message:"schema mismatch"}`},b_=(e,t)=>{const r=`When you give your final answer, respond with only a single JSON object that conforms to the following JSON Schema. No prose before or after it, and no markdown code fence. JSON Schema: ${JSON.stringify(t)}`,n=e.reduce((i,a,c)=>a.role==="system"?c:i,-1);if(n===-1)return[{role:"system",content:r},...e];const o=e[n],s=typeof o.content=="string"?`${o.content}
1010
+ `):"";default:return bl(e)}},AW=(e,t)=>{const r=t&&t.includes("/")?t:"image/png";if(typeof e=="string")return e.startsWith("data:")||/^https?:\/\//i.test(e)?e:`data:${r};base64,${e}`;if(e instanceof URL)return e.toString();if(e instanceof Uint8Array)return`data:${r};base64,${Buffer.from(e).toString("base64")}`},tgt=e=>{if(typeof e=="string")return e;if(!Array.isArray(e))return bl(e);const t=[];for(const r of e){if(typeof r=="string"){t.push({type:"text",text:r});continue}if(!r||typeof r!="object")continue;const n=r;if(n.type==="text")t.push({type:"text",text:r.text??""});else if(n.type==="image"||n.type==="image_url"){const o=r.image??r.data??r.url,s=r.mediaType??r.mimeType,i=AW(o,s);i&&t.push({type:"image_url",image_url:{url:i}})}else if(n.type==="file"){const o=r;if(o.mediaType?.startsWith("image/")){const s=AW(o.data,o.mediaType);s&&t.push({type:"image_url",image_url:{url:s}})}}}return t.length===1&&t[0].type==="text"?t[0].text:t},xW=(e,t)=>{const r=[];for(const n of e)switch(n.role){case"system":r.push({role:"system",content:typeof n.content=="string"?n.content:bl(n.content)});break;case"user":r.push({role:"user",content:tgt(n.content)});break;case"assistant":{const o=Array.isArray(n.content)?n.content:[n.content],s=[],i=[];for(const c of o)if(c&&typeof c=="object"){const l=c;if(l.type==="text")s.push({type:"text",text:c.text??""});else if(l.type==="tool-call"){const u=c,d=u.toolName??"";i.push({id:u.toolCallId??"",type:"function",function:{name:t?.get(d)??d,arguments:w_(u.input)}})}}else typeof c=="string"&&s.push({type:"text",text:c});const a=s.length===0?null:s.length===1&&s[0].type==="text"?s[0].text:s;r.push({role:"assistant",content:a,...i.length>0?{tool_calls:i}:{}});break}case"tool":{if(Array.isArray(n.content))for(const o of n.content){if(!o||typeof o!="object")continue;const s=o;s.type==="tool-result"&&r.push({role:"tool",tool_call_id:s.toolCallId??"",content:kW(s.output)})}else typeof n.content=="string"&&r.push({role:"tool",tool_call_id:n.toolCallId??"",content:n.content});break}}return r},IW=(e,t)=>{const r=Object.entries(e);if(r.length===0)return;const n=[];for(const[o,s]of r){const i=s,a=i.inputSchema??i.parameters,c=a?_Ue(No(a)):{type:"object",properties:{}};n.push({type:"function",function:{name:t?.get(o)??o,...i.description?{description:i.description}:{},parameters:c}})}return n},rgt=(e,t)=>{if(!e||e.length===0)return;const r=[];for(const n of e)n.type==="function"&&r.push({type:"function",function:{name:t?.get(n.name)??n.name,...n.description?{description:n.description}:{},parameters:_Ue(n.inputSchema),...n.strict!==void 0?{strict:n.strict}:{}}});return r.length>0?r:void 0},ngt=(e,t)=>{switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:t?.get(e.toolName)??e.toolName}}}},RW=["properties","patternProperties","$defs","definitions"],MW=["items","prefixItems","anyOf","oneOf","allOf","not","then","else"],ogt=["allOf","not","if","then","else"],sgt=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([r,n])=>[r,t(n)])),X0=e=>{if(Array.isArray(e))return e.map(X0);if(!e||typeof e!="object")return e;const t={...e};for(const r of RW)r in t&&(t[r]=sgt(t[r],X0));for(const r of MW)r in t&&(t[r]=X0(t[r]));return t.additionalProperties&&typeof t.additionalProperties=="object"?t.additionalProperties=X0(t.additionalProperties):t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1),t},Rf=e=>{if(Array.isArray(e))return e.every(Rf);if(!e||typeof e!="object")return!0;const t=e;if(ogt.some(o=>o in t))return!1;if(t.type==="object"){if(t.additionalProperties!==!1)return!1;const o=Object.keys(t.properties??{}),s=Array.isArray(t.required)?t.required:[];if(o.some(i=>!s.includes(i)))return!1}const r=RW.filter(o=>o in t).every(o=>Object.values(t[o]??{}).every(Rf)),n=MW.filter(o=>o in t).every(o=>Rf(t[o]));return r&&n},igt=e=>{if(e.type==="text")return{type:"text"};if(!e.schema)return{type:"json_object"};const t=e.schema,r=X0(t),n=Rf(t)?t:Rf(r)?r:t;return{type:"json_schema",json_schema:{name:e.name??"response",schema:n,...e.description?{description:e.description}:{},strict:Rf(n)}}},agt=(e,t)=>{if(e){if(e==="auto"||e==="none"||e==="required")return e;if(typeof e=="object"&&e!==null){const r=e;if(r.type==="tool"&&r.toolName)return{type:"function",function:{name:t?.get(r.toolName)??r.toolName}}}}},cgt=e=>e.some(t=>{const r=t.content;return typeof r=="string"?/\bjson\b/i.test(r):Array.isArray(r)?r.some(n=>typeof n?.text=="string"&&/\bjson\b/i.test(n.text)):!1}),PW=e=>e.response_format?.type==="json_object"&&!cgt(e.messages)?{...e,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...e.messages]}:e,lgt=e=>/^(o\d|gpt-5)/i.test(e.replace(/^.*\//,"")),DW=e=>{const{modelId:t,messages:r,options:n,tools:o,toolChoice:s,streaming:i,responseFormat:a}=e,c={model:t,messages:r,...i?{stream:!0}:{},...i?{stream_options:{include_usage:!0}}:{}};n.maxTokens!==void 0&&n.maxTokens!==null&&(c.max_tokens=n.maxTokens);const l=ml("openai-compatible",t,{...n.temperature!==void 0&&n.temperature!==null?{temperature:n.temperature}:{},...n.topP!==void 0&&n.topP!==null?{topP:n.topP}:{}},"openaiCompatible.buildBody");return l.temperature!==void 0&&(c.temperature=l.temperature),l.topP!==void 0&&(c.top_p=l.topP),n.presencePenalty!==void 0&&n.presencePenalty!==null&&(c.presence_penalty=n.presencePenalty),n.frequencyPenalty!==void 0&&n.frequencyPenalty!==null&&(c.frequency_penalty=n.frequencyPenalty),n.seed!==void 0&&n.seed!==null&&(c.seed=n.seed),n.stopSequences&&n.stopSequences.length>0&&(c.stop=n.stopSequences),o&&(c.tools=o),s!==void 0&&o&&o.length>0&&(c.tool_choice=s),a&&(c.response_format=a),n.extraBody&&Object.assign(c,n.extraBody),c},OW=async(e,t,r)=>{const n={text:"",reasoning:"",toolCalls:new Map,finishReason:null,usage:void 0},o=new TextDecoder;let s;const a=pW({onEvent:l=>{const u=l.data;if(!u||u==="[DONE]")return;let d;try{d=JSON.parse(u)}catch(g){s=g instanceof Error?g:new Error(String(g));return}d.usage&&(n.usage=d.usage),d.id&&!n.id&&(n.id=d.id),d.model&&!n.model&&(n.model=d.model);const m=d.choices?.[0];if(!m)return;const h=m.delta;h?.content&&(n.text+=h.content,t(h.content));const f=h?.reasoning_content||h?.reasoning;if(f&&(n.reasoning+=f,r?.(f)),h?.tool_calls)for(const g of h.tool_calls){let y=n.toolCalls.get(g.index);y?g.id&&(y.id=g.id):(y={id:g.id??`call_${g.index}_${Date.now()}`,name:g.function?.name??"",argsBuffered:""},n.toolCalls.set(g.index,y)),g.function?.name&&(y.name=g.function.name),g.function?.arguments&&(y.argsBuffered+=g.function.arguments)}m.finish_reason&&(n.finishReason=m.finish_reason)}}),c=e.getReader();try{for(;;){const{done:l,value:u}=await c.read();if(l)break;a.feed(o.decode(u,{stream:!0}))}a.feed(o.decode())}finally{c.releaseLock()}if(s)throw s;return n},E_=async(e,t,r)=>{let n,o;try{n=await r.text(),o=n?JSON.parse(n):void 0}catch{o=void 0}const s=F1r(o)??`OpenAI-compatible request failed with status ${r.status}`,i=new Error(s);return i.statusCode=r.status,i.responseHeaders=Object.fromEntries([...r.headers.entries()].filter(([a])=>{const c=a.toLowerCase();return c==="retry-after"||c.startsWith("x-ratelimit-")})),i.url=e,i.requestBody={model:t.model,stream:t.stream===!0,tool_count:t.tools?.length??0},n!==void 0&&(i.responseBody=n),i},NW=()=>{let e=()=>{};const t=new Promise(o=>{e=o});let r=()=>{};const n=new Promise(o=>{r=o});return{usagePromise:t,finishPromise:n,resolveUsage:e,resolveFinish:r}},ugt=(e,t)=>{if(!e)return t;if(!t)return e;const r=(e.prompt_tokens_details?.cached_tokens??0)+(t.prompt_tokens_details?.cached_tokens??0),n=(e.completion_tokens_details?.reasoning_tokens??0)+(t.completion_tokens_details?.reasoning_tokens??0),o=s=>s.total_tokens||(s.prompt_tokens??0)+(s.completion_tokens??0);return{prompt_tokens:(e.prompt_tokens??0)+(t.prompt_tokens??0),completion_tokens:(e.completion_tokens??0)+(t.completion_tokens??0),total_tokens:o(e)+o(t),...r>0?{prompt_tokens_details:{cached_tokens:r}}:{},...n>0?{completion_tokens_details:{reasoning_tokens:n}}:{}}}}});function kP(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function $1r(e,t){let r=kP(e.content);return e.role==="assistant"&&e.tool_calls&&(r+=kP(e.tool_calls)),Zt(r,t)+Dc}function U1r(e,t){if(e.role!=="tool")return;const r=kP(e.content),n={maxBytes:LW,maxLines:FW};if(!zmt(r,n))return;const{preview:o}=Qa(r,n);return Zt(o,t)+Dc}function B1r(e,t){return e.map(r=>{const n=$1r(r,t);if(r.role==="tool"){const o=U1r(r,t);return{kind:"toolResult",tokens:n,...o!==void 0?{previewTokens:o}:{}}}return r.role==="assistant"&&r.tool_calls?.length?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function z1r(e){const{conversation:t,availableInputTokens:r,fixedOverheadTokens:n,provider:o,observedPromptTokens:s,previousSentEstimate:i,onSentEstimate:a}=e,c=B1r(t,o),l=n+c.reduce((g,y)=>g+y.tokens,0);let u=1;s&&s>0&&i&&i>0&&(u=Math.min(3,Math.max(1,s/i)));const d=TP(c,{availableInputTokens:r,fixedOverheadTokens:n,calibration:u});if(!d.fire){a?.(l);return}const m=new Set(d.truncate),h=new Set(d.drop),f=[];for(let g=0;g<t.length;g++){if(h.has(g))continue;const y=t[g];if(m.has(g)&&y.role==="tool"){const{preview:v}=Qa(kP(y.content),{maxBytes:LW,maxLines:FW});f.push({...y,content:v});continue}f.push(y)}if(h.size>0){let g=f.findIndex(y=>y.role==="tool"||y.role==="assistant"&&y.tool_calls);g<0&&(g=Math.min(1,f.length)),f.splice(g,0,{role:"user",content:dgt})}return p.info("[OpenAICompatLoopGuard] Reclaimed agent-loop context",{provider:o,messagesBefore:t.length,messagesAfter:f.length,toolOutputsTruncated:d.truncate.length,messagesDropped:d.drop.length,projectedTokens:d.projectedTokens,calibration:u}),a?.(d.projectedTokens),f}var LW,FW,dgt,q1r=b({"src/lib/context/openaiCompatLoopGuard.ts"(){"use strict";is(),wf(),wP(),B(),LW=2048,FW=60,dgt="[Earlier tool exchanges were removed to fit the context window.]"}});function G1r(e){let t,r;const n=o=>Zt(UW(o),e.provider)+Dc;return{observeUsage(o){const s=S_(o)?o.inputTokens:void 0,i=S_(s)?s.total:s;r=typeof i=="number"&&Number.isFinite(i)&&i>0?i:void 0},guardConversation(o){const s=o.findIndex(S=>S.role==="user"),i=Math.max(1,s+1),a=o.slice(i),c=a.map(mgt),l=[{kind:"other",tokens:o.slice(0,i).reduce((S,_)=>S+n(_),0)},...a.map((S,_)=>{const C=$W(S.content);return S.role==="assistant"&&C.some(k=>k.type==="tool-call")?{kind:"toolCall",tokens:n(S)}:S.role==="tool"&&C.some(k=>k.type==="tool-result")?{kind:"toolResult",tokens:n(S),previewTokens:n(c[_])}:{kind:"other",tokens:n(S)}})],u=e.getFixedOverheadTokens(),d=r&&t?Math.min(3,Math.max(1,r/t)):1,m=TP(l,{availableInputTokens:e.availableInputTokens,fixedOverheadTokens:u,calibration:d}),h=Math.floor(e.availableInputTokens*JR/(d>0?d:1)),f=u+l.reduce((S,_)=>S+_.tokens,0);if(!m.fire){t=f,f>h?p.warn("[NativeGenerateGuard] Over threshold, nothing reclaimable",{provider:e.provider,availableInputTokens:e.availableInputTokens,reclaimThresholdTokens:h,estimatedPromptTokens:f,overThresholdByTokens:f-h,calibration:d}):p.debug("[NativeGenerateGuard] Under threshold",{provider:e.provider,availableInputTokens:e.availableInputTokens,reclaimThresholdTokens:h,estimatedPromptTokens:f,headroomToThresholdTokens:h-f,calibration:d});return}const g=new Set(m.drop),y=new Set(m.truncate),v=[...o.slice(0,i)];let w=!1;return a.forEach((S,_)=>{const C=_+1;g.has(C)?(w||v.push({role:"user",content:"[Earlier tool exchanges were removed to fit the context window.]"}),w=!0):v.push(y.has(C)?c[_]:S)}),t=u+v.reduce((S,_)=>S+n(_),0),p.info("[NativeGenerateGuard] Reclaimed context",{provider:e.provider,availableInputTokens:e.availableInputTokens,reclaimThresholdTokens:h,estimatedBeforeTokens:f,estimatedAfterTokens:t,truncated:m.truncate.length,dropped:m.drop.length,calibration:d}),v}}}var S_,$W,UW,mgt,j1r=b({"src/lib/context/nativeGenerateGuard.ts"(){"use strict";is(),B(),wP(),Do(),wf(),S_=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$W=e=>Array.isArray(e)?e.filter(S_):[],UW=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}},mgt=e=>({...e,content:$W(e.content).map(t=>{if(t.type!=="tool-result")return t;const r=t.output,n=S_(r)&&["text","json","error-text","error-json"].includes(String(r.type))&&"value"in r,{preview:o,truncated:s}=Qa(UW(n?r.value:r),{maxBytes:2048,maxLines:60});return s?{...t,output:n?{...r,type:String(r.type).startsWith("error")?"error-text":"text",value:o}:o}:t})})}});function BW(e){const t=qW(e);return t?GW.some(({patterns:r})=>r.some(n=>n.test(t))):!1}function H1r(e){const t=qW(e);if(!t)return null;for(const{provider:r,patterns:n}of GW)if(n.some(o=>o.test(t)))return r;return null}function zW(e){const t=qW(e);if(!t||t.length>2e3)return null;const r=t.match(/resulted\s+in\s+(\d[\d,]{0,19})\s*tokens/i),n=t.match(/maximum\s+context\s+length\s+is\s+(\d[\d,]{0,19})/i);if(r&&n)return{actualTokens:parseInt(r[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10)};const o=t.match(/prompt\s+contains\s+at\s+least\s+(\d[\d,]{0,19})\s+input\s+tokens/i);if(o&&n){const a=t.match(/requested\s+(\d[\d,]{0,19})\s+output\s+tokens/i);return{actualTokens:parseInt(o[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10),...a?{requestedOutputTokens:parseInt(a[1].replace(/,/g,""),10)}:{}}}const s=t.match(/(\d[\d,]{0,19})\s*tokens?\s*[>:]\s*(\d[\d,]{0,19})/i);if(s)return{actualTokens:parseInt(s[1].replace(/,/g,""),10),budgetTokens:parseInt(s[2].replace(/,/g,""),10)};const i=t.match(/(\d[\d,]{0,19})\s*(?:>|exceeds)\s*(\d[\d,]{0,19})/i);return i?{actualTokens:parseInt(i[1].replace(/,/g,""),10),budgetTokens:parseInt(i[2].replace(/,/g,""),10)}:null}function qW(e){if(!e)return null;if(typeof e=="string")return e;if(e instanceof Error){const t=e.message,r=e?.cause;return r instanceof Error?`${t} ${r.message}`:t}if(typeof e=="object"){const t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error;if(typeof t.error=="object"&&t.error!==null){const r=t.error;if(typeof r.message=="string")return r.message}}return null}var GW,pgt=b({"src/lib/context/errorDetection.ts"(){"use strict";GW=[{provider:"openai",patterns:[/This model's maximum context length is/i,/tokens\. However, (?:your messages|you requested)/i,/reduce the length of the messages/i,/Please reduce the length/i]},{provider:"azure",patterns:[/content_length_exceeded/i]},{provider:"google",patterns:[/RESOURCE_EXHAUSTED/i,/exceeds the maximum number of tokens/i,/content is too long/i,/request payload size exceeds/i,/input token limit/i]},{provider:"bedrock",patterns:[/ValidationException.*token/i,/Input is too long/i,/exceeds the model's maximum/i]},{provider:"mistral",patterns:[/context length exceeded/i,/maximum number of tokens/i]},{provider:"openrouter",patterns:[/context_length_exceeded/i]},{provider:"anthropic",patterns:[/prompt is too long/i,/input is too long/i,/too many tokens/i,/maximum context length/i]}]}}),ka,hgt=b({"src/lib/context/errors.ts"(){"use strict";ka=class extends Error{estimatedTokens;availableTokens;stagesUsed;breakdown;constructor(e,t){super(e),this.name="ContextBudgetExceededError",this.estimatedTokens=t.estimatedTokens,this.availableTokens=t.availableTokens,this.stagesUsed=t.stagesUsed,this.breakdown=t.breakdown}}}}),fgt,jW,ggt=b({"src/lib/core/streamAnalytics.ts"(){"use strict";pb(),B(),gM(),Dm(),fgt=class{async collectUsage(e){try{const t=await e.usage;return t?fM(t):(p.debug("No usage data available from stream result"),h3e())}catch(t){return ou.isInstance(t)?p.debug("No output generated from stream \u2014 returning empty usage"):p.warn("Failed to collect usage from stream result",{error:t}),h3e()}}async collectMetadata(e){try{const[t,r]=await Promise.all([e.response,e.finishReason]);return{id:t?.id,model:t?.model,timestamp:t?.timestamp instanceof Date?t.timestamp.getTime():t?.timestamp||Date.now(),finishReason:r}}catch(t){return ou.isInstance(t)?p.debug("No output generated from stream \u2014 returning default metadata"):p.warn("Failed to collect metadata from stream result",{error:t}),{timestamp:Date.now(),finishReason:"error"}}}async createAnalytics(e,t,r,n,o){try{const[s,i]=await Promise.all([this.collectUsage(r),this.collectMetadata(r)]),[a,c,l,u]=await Promise.all([Promise.resolve(r.text).catch(()=>""),Promise.resolve(r.finishReason).catch(()=>"error"),Promise.resolve(r.toolResults||[]).catch(()=>[]),Promise.resolve(r.toolCalls||[]).catch(()=>[])]);return p0(e,t,{usage:s,content:a,response:i,finishReason:c,toolResults:l,toolCalls:u},n,{...o,streamingMode:!0,responseId:i.id,finishReason:c})}catch(s){return p.error("Failed to create analytics from stream result",{provider:e,model:t,error:s instanceof Error?s.message:String(s)}),p0(e,t,{usage:{input:0,output:0,total:0}},n,{...o,streamingMode:!0,analyticsError:!0})}}cleanup(){const e=process.memoryUsage().heapUsed,t=500*1024*1024;typeof global<"u"&&global.gc&&e>t&&global.gc()}},jW=new fgt}});function ygt(e,t){if(!(!e||!t||t.length===0))for(const r of t){const n=r.output??r.result,o=!!r.error||n!=null&&typeof n=="object"&&"isError"in n&&n.isError===!0;let s;if(o){if(r.error)s=r.error;else if(n&&typeof n=="object"){const i=n.content;if(Array.isArray(i)){const a=i.filter(c=>c.type==="text"&&c.text).map(c=>c.text);s=a.length>0?a.join(" "):"Tool returned isError: true"}else s="Tool returned isError: true"}}e.emit("tool:end",F0(r.toolName,{responseTime:0,success:!o,timestamp:Date.now(),result:n,error:s}))}}var vgt=b({"src/lib/utils/toolEndEmitter.ts"(){"use strict";b9()}});async function HW(e,t){const r=[];let n="",o="",s="stop",i,a=0,c=0,l=0,u=0,d=0,m=!1,h=!1,f;const g=!!(e.tools&&e.tools.length>0);for(let y=0;y<e.maxSteps;y++){d=y+1;const v=e.guardConversation?.(e.conversation);v&&e.conversation.splice(0,e.conversation.length,...v);const w=()=>e.runStep(()=>e.doGenerate({prompt:e.conversation,...e.tools&&e.tools.length>0?{tools:e.tools}:{},...m?{toolChoice:{type:"none"}}:e.toolChoice!==void 0?{toolChoice:e.toolChoice}:{},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.providerOptions?{providerOptions:e.providerOptions}:{},...e.maxOutputTokens?{maxOutputTokens:e.maxOutputTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{}}));let S;try{S=await w()}catch(M){if(h&&f){p.warn("toolChoice: none re-ask failed; returning the original result",{error:M instanceof Error?M.message:String(M)}),n=f.text,s=f.finishReason,i=f.rawFinishReason;break}throw M}h=!1,e.observeUsage?.(S.usage);const _=Tgt(S.content);n=_.filter(M=>M.type==="text"&&typeof M.text=="string").map(M=>M.text).join(""),o+=_.filter(M=>M.type==="reasoning"&&typeof M.text=="string").map(M=>M.text).join("");const C=S.finishReason;if(typeof C=="string")s=C;else if(typeof C=="object"&&C!==null){const M=C;s=M.unified??s,i=M.raw??i}const k=S.usage;c+=VW(k?.outputTokens);const A=k?.inputTokens;a+=typeof A?.noCache=="number"?A.noCache:VW(k?.inputTokens),l+=A?.cacheRead??0,u+=A?.cacheWrite??0;const I=_.filter(M=>M.type==="tool-call");if(I.length===0){if(s==="tool-calls"&&n.trim()===""&&g&&!m&&y+1<e.maxSteps){m=!0,h=!0,f={text:n,finishReason:s,rawFinishReason:i},e.conversation.push({role:"assistant",content:_});continue}break}e.conversation.push({role:"assistant",content:_});const R=[];for(const M of I){const D=String(M.toolName??""),U=String(M.toolCallId??""),P=new Date,$=wgt(M.input),N=$.input,F=e.toolsRecord[D];let j,z;const V=$.error??(typeof F?.execute=="function"?Egt(F,N):void 0);if(typeof F?.execute!="function")z=`Tool not found: ${D}`,j={error:z};else if(V)z=`Tool ${D}: ${V}`,j={error:z};else try{j=await _f(D,F.execute,{...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}})(N,{toolCallId:U,messages:[],...e.abortSignal?{abortSignal:e.abortSignal}:{}}),r.push(D)}catch(q){z=q instanceof Error?q.message:String(q),j={error:z}}t.push({toolCallId:U,toolName:D,input:N,...z?{error:z}:{output:j},startTime:P,endTime:new Date}),R.push({type:"tool-result",toolCallId:U,output:j})}e.conversation.push({role:"tool",content:R})}return{text:n,...o?{reasoning:o}:{},finishReason:s,...i?{rawFinishReason:i}:{},inputTokens:a,outputTokens:c,cacheReadTokens:l,cacheWriteTokens:u,toolsUsed:r,steps:d}}var AP,Tgt,VW,wgt,Egt,b_,WW=b({"src/lib/core/nativeGenerateLoop.ts"(){"use strict";B(),dP(),AP=e=>typeof e=="object"&&e!==null&&typeof e.doGenerate=="function",Tgt=e=>Array.isArray(e)?e:[],VW=e=>typeof e=="object"&&e!==null&&typeof e.total=="number"?e.total:0,wgt=e=>{if(typeof e!="string")return{input:e??{}};if(e.trim()==="")return{input:{}};try{return{input:JSON.parse(e)}}catch{return{input:{},error:"arguments were not valid JSON"}}},Egt=(e,t)=>{const r=e?.inputSchema;if(typeof r?.safeParse!="function")return;const n=r.safeParse(t);return n.success?void 0:`input did not match the tool's schema: ${n.error instanceof Error?n.error.message:"schema mismatch"}`},b_=(e,t)=>{const r=`When you give your final answer, respond with only a single JSON object that conforms to the following JSON Schema. No prose before or after it, and no markdown code fence. JSON Schema: ${JSON.stringify(t)}`,n=e.reduce((i,a,c)=>a.role==="system"?c:i,-1);if(n===-1)return[{role:"system",content:r},...e];const o=e[n],s=typeof o.content=="string"?`${o.content}
1011
1011
 
1012
1012
  ${r}`:r;return e.map((i,a)=>a===n?{...i,content:s}:i)}}}),Mf,V1r=b({"node_modules/.pnpm/jsonrepair@3.14.0/node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js"(){Mf=class extends Error{constructor(e,t){super(`${e} at position ${t}`),this.position=t}}}});function W1r(e){return/^[0-9A-Fa-f]$/.test(e)}function Pf(e){return e>="0"&&e<="9"}function K1r(e){return e>=" "}function xP(e){return`,:[]/{}()
1013
1013
  +`.includes(e)}function Sgt(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"||e==="$"}function bgt(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"||e==="$"||e>="0"&&e<="9"}function _gt(e){return`,[]/{}
@@ -1017,7 +1017,7 @@ ${r}`:r;return e.map((i,a)=>a===n?{...i,content:s}:i)}}}),Mf,V1r=b({"node_module
1017
1017
  ${r}
1018
1018
  ]`}function w(){let z=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,V=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,q=e[t]==="\\";if(q&&(t++,q=!0),IP(e[t])){const G=Agt(e[t])?Agt:xgt(e[t])?xgt:KW(e[t])?KW:kgt,J=t,re=r.length;let pe='"';for(t++;;){if(t>=e.length){const ne=R(t-1);return!z&&xP(e.charAt(ne))?(t=J,r=r.substring(0,re),w(!0)):(pe=_l(pe,'"'),r+=pe,!0)}if(t===V)return pe=_l(pe,'"'),r+=pe,!0;if(G(e[t])){const ne=t,ie=pe.length;if(pe+='"',t++,r+=pe,i(!1),z||t>=e.length||xP(e[t])||IP(e[t])||Pf(e[t]))return S(),!0;const Ie=R(ne-1),Ce=e.charAt(Ie);if(Ce===",")return t=J,r=r.substring(0,re),w(!1,Ie);if(xP(Ce))return t=J,r=r.substring(0,re),w(!0);r=r.substring(0,re),t=ne+1,pe=`${pe.substring(0,ie)}\\${pe.substring(ie)}`}else if(z&&_gt(e[t])){if(e[t-1]===":"&&ZW.test(e.substring(J+1,t+2)))for(;t<e.length&&QW.test(e[t]);)pe+=e[t],t++;return pe=_l(pe,'"'),r+=pe,S(),!0}else if(e[t]==="\\"){const ne=e.charAt(t+1);if(Bgt[ne]!==void 0)pe+=e.slice(t,t+2),t+=2;else if(ne==="u"){let Ie=2;for(;Ie<6&&W1r(e[t+Ie]);)Ie++;Ie===6?(pe+=e.slice(t,t+6),t+=6):t+Ie>=e.length?t=e.length:j()}else ne===`
1019
1019
  `?(pe+="\\n",t+=2):(pe+=ne,t+=2)}else{const ne=e.charAt(t);ne==='"'&&e[t-1]!=="\\"?(pe+=`\\${ne}`,t++):J1r(ne)?(pe+=Ugt[ne],t++):(K1r(ne)||U(ne),pe+=ne,t++)}q&&h()}}return!1}function S(){let z=!1;for(i();e[t]==="+";){z=!0,t++,i(),r=__(r,'"',!0);const V=r.length;w()?r=Z1r(r,V,1):r=_l(r,'"')}return z}function _(){const z=t;if(e[t]==="-"){if(t++,M())return D(z),!0;if(!Pf(e[t]))return t=z,!1}for(;Pf(e[t]);)t++;if(e[t]==="."){if(t++,M())return D(z),!0;if(!Pf(e[t]))return t=z,!1;for(;Pf(e[t]);)t++}if(e[t]==="e"||e[t]==="E"){if(t++,(e[t]==="-"||e[t]==="+")&&t++,M())return D(z),!0;if(!Pf(e[t]))return t=z,!1;for(;Pf(e[t]);)t++}if(!M())return t=z,!1;if(t>z){const V=e.slice(z,t),q=/^0\d/.test(V);return r+=q?`"${V}"`:V,!0}return!1}function C(){return k("true","true")||k("false","false")||k("null","null")||k("True","true")||k("False","false")||k("None","null")}function k(z,V){return e.slice(t,t+z.length)===z?(r+=V,t+=z.length,!0):!1}function A(z){const V=t;if(Sgt(e[t])){for(;t<e.length&&bgt(e[t]);)t++;let q=t;for(;Df(e,q);)q++;if(e[q]==="(")return t=q+1,s(),e[t]===")"&&(t++,e[t]===";"&&t++),!0}for(;t<e.length&&!_gt(e[t])&&!IP(e[t])&&(!z||e[t]!==":");)t++;if(e[t-1]===":"&&ZW.test(e.substring(V,t+2)))for(;t<e.length&&QW.test(e[t]);)t++;if(t>V){for(;Df(e,t-1)&&t>0;)t--;const q=e.slice(V,t);return r+=q==="undefined"?"null":JSON.stringify(q),e[t]==='"'&&t++,!0}}function I(){if(e[t]==="/"){const z=t;for(t++;t<e.length&&(e[t]!=="/"||e[t-1]==="\\");)t++;return t++,r+=JSON.stringify(e.substring(z,t)),!0}}function R(z){let V=z;for(;V>0&&Df(e,V);)V--;return V}function M(){return t>=e.length||xP(e[t])||Df(e,t)}function D(z){r+=`${e.slice(z,t)}0`}function U(z){throw new Mf(`Invalid character ${JSON.stringify(z)}`,t)}function P(){throw new Mf(`Unexpected character ${JSON.stringify(e[t])}`,t)}function $(){throw new Mf("Unexpected end of json string",e.length)}function N(){throw new Mf("Object key expected",t)}function F(){throw new Mf("Colon expected",t)}function j(){const z=e.slice(t,t+6);throw new Mf(`Invalid unicode character "${z}"`,t)}}function rMr(e,t){return e[t]==="*"&&e[t+1]==="/"}var Ugt,Bgt,nMr=b({"node_modules/.pnpm/jsonrepair@3.14.0/node_modules/jsonrepair/lib/esm/regular/jsonrepair.js"(){V1r(),eMr(),Ugt={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Bgt={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
1020
- `,r:"\r",t:" "}}}),oMr=b({"node_modules/.pnpm/jsonrepair@3.14.0/node_modules/jsonrepair/lib/esm/index.js"(){nMr()}});function zgt(e,t=0){for(let r=t;r<e.length;r++){const n=e[r];if(n!=="{"&&n!=="[")continue;const o=n==="{"?"}":"]";let s=0,i=!1,a=!1;for(let c=r;c<e.length;c++){const l=e[c];if(a){a=!1;continue}if(l==="\\"){a=!0;continue}if(l==='"'){i=!i;continue}if(!i){if(l===n)s++;else if(l===o&&(s--,s===0))return{span:e.substring(r,c+1),end:c+1}}}}return null}var sMr=b({"src/lib/utils/json/extract.ts"(){"use strict"}});function qgt(e){return typeof e.safeParse=="function"}function eK(e,t){return!e||!qgt(e)?!0:e.safeParse(t).success}function iMr(e,t){try{const r=JSON.parse(e);return r===""?{kind:"empty"}:r==null?{kind:"nullish"}:eK(t,r)?{kind:"accepted",value:r}:{kind:"rejected",value:r}}catch{return{kind:"not-json"}}}function Ggt(e){try{return{value:JSON.parse(e),repaired:!1}}catch{}try{const t=tMr(e),r=JSON.parse(t);return t!==e&&p.shouldLog("debug")&&p.debug("[coerceJsonToSchema] jsonrepair altered model output",{originalLength:e.length,repairedLength:t.length}),{value:r,repaired:t!==e}}catch{return}}function aMr(e){let t=e;for(let r=0;r<Vgt&&t.length>1;r++){const n=Math.max(t.lastIndexOf(","),t.lastIndexOf("}"),t.lastIndexOf("]"));if(n<=0)break;t=t.slice(0,n);const o=Ggt(t);if(o!==void 0&&o.value!==null&&typeof o.value=="object")return o.value}}function tK(e,t=0){if(t>Hgt)return{value:e,changed:!1};if(typeof e=="string"){const r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{const o=JSON.parse(r);if(o!==null&&typeof o=="object")return{value:o,changed:!0}}catch{}return{value:e,changed:!1}}if(Array.isArray(e)){let r=!1;const n=e.map(o=>{const s=tK(o,t+1);return s.changed&&(r=!0),s.value});return{value:r?n:e,changed:r}}if(e!==null&&typeof e=="object"){let r=!1;const n={};for(const[o,s]of Object.entries(e)){const i=tK(s,t+1);i.changed&&(r=!0),n[o]=i.value}return{value:r?n:e,changed:r}}return{value:e,changed:!1}}function jgt(e,t){if(typeof e!="string"||e.trim().length===0)return null;const r=[],n=[e.indexOf("{"),e.indexOf("[")].filter(v=>v>=0),o=n.length>0?Math.min(...n):-1;let s=!1,i=0;for(;;){const v=zgt(e,i);if(!v)break;const w=v.end-v.span.length;w===o&&(s=!0),r.push({text:v.span,truncated:!1,rootAligned:w===o}),i=v.end}const a=o>=0&&!s,c=Math.max(e.lastIndexOf("}"),e.lastIndexOf("]"));o>=0&&c>o&&r.push({text:e.slice(o,c+1),truncated:a,rootAligned:!0}),o>=0&&r.push({text:e.slice(o),truncated:!0,rootAligned:!0});const l=e.trim();if(l.length>1&&l.startsWith('"')&&l.endsWith('"'))try{const v=JSON.parse(l);if(typeof v=="string"){let w=0;for(;;){const S=zgt(v,w);if(!S)break;r.push({text:S.span,truncated:!1,rootAligned:!1}),w=S.end}}}catch{}const u=[...r.filter(v=>v.rootAligned),...r.filter(v=>!v.rootAligned)];let d;const m=[],h=!!(t&&qgt(t)),f=new Set;for(const v of u){if(f.has(v.text))continue;f.add(v.text);const w=Ggt(v.text);if(w===void 0||w.value===null||typeof w.value!="object")continue;const S={value:w.value,repaired:w.repaired,truncated:v.truncated,rootAligned:v.rootAligned};if(d===void 0&&(d=S),!h)break;const _=t;if(_.safeParse(w.value).success)m.push(S);else{const C=tK(w.value);C.changed&&C.value!==null&&typeof C.value=="object"&&_.safeParse(C.value).success?m.push({value:C.value,repaired:!0,truncated:v.truncated,rootAligned:v.rootAligned}):Array.isArray(w.value)&&w.value.length===1&&w.value[0]!==null&&typeof w.value[0]=="object"&&!Array.isArray(w.value[0])&&_.safeParse(w.value[0]).success&&m.push({value:w.value[0],repaired:!0,truncated:v.truncated,rootAligned:v.rootAligned})}}const g=m.length>0?m.reduce((v,w)=>JSON.stringify(w.value).length>JSON.stringify(v.value).length?w:v):void 0;let y=g??d;if(a&&g===void 0&&(y===void 0||!y.rootAligned)){const v=aMr(e.slice(o));v!==void 0?(p.debug("[coerceJsonToSchema] salvaged a partial truncated object",{textLength:e.length}),y={value:v,repaired:!0,truncated:!0,rootAligned:!0}):y!==void 0&&(y={...y,truncated:!0})}return y===void 0?null:{content:JSON.stringify(y.value),structuredData:y.value,repaired:y.repaired,truncated:y.truncated}}var Hgt,Vgt,Wgt=b({"src/lib/utils/json/coerce.ts"(){"use strict";oMr(),B(),sMr(),Hgt=6,Vgt=8}});function RP(e,t,r){return!r||!t||Object.keys(t).length===0?"none":e.toolChoice??"auto"}function cMr(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){const t=e;if(t.type==="tool")return t.toolName?{type:"tool",toolName:t.toolName}:void 0;if(t.type)return t.type}}var Kgt=b({"src/lib/utils/toolChoice.ts"(){"use strict"}});async function*lMr(e,t){const r=e.getReader();let n=!1;try{for(;;){const o=await r.read();if(o.done){n=!0;return}const s=o.value;if(s.type==="text-delta")yield{content:s.delta};else if(s.type==="reasoning-delta")yield{content:"",reasoning:s.delta};else if(s.type==="finish")t(s);else if(s.type==="error")throw s.error}}finally{try{n||await r.cancel()}finally{r.releaseLock()}}}var MP,rK,C_,Jgt,Aa,rc=b({"src/lib/providers/openaiChatCompletionsBase.ts"(){"use strict";Yt(),Sl(),q1r(),is(),j1r(),pgt(),hgt(),ec(),Do(),ggt(),Mn(),B(),Ut(),Dm(),c9(),ga(),vgt(),qh(),WW(),jm(),di(),Wgt(),Kgt(),Ic(),nd(),tW(),wb(),dp(),W0(),MP=512,rK=class extends Error{},C_=(e,t)=>{const r=jgt(e,t);return r!==null&&eK(t,r.structuredData)},Jgt=(e,t,r)=>{const n=e[Symbol.asyncIterator]();return new ReadableStream({async pull(o){try{const s=await n.next();s.done?(o.enqueue(await t),o.close()):s.value.reasoning?o.enqueue({type:"reasoning-delta",delta:s.value.reasoning}):o.enqueue({type:"text-delta",delta:s.value.content})}catch(s){o.error(s)}},async cancel(){r(),await n.return?.()}})},Aa=class extends _a{config;resolvedModel;constructor(e,t,r,n){super(t,e,r),this.config=n}getFallbackModelName(){return"gpt-3.5-turbo"}getModelFallbacks(){return this.getFallbackModels()}refreshHandlersForModel(e){this.resolvedModel=e,super.refreshHandlersForModel(e)}getFallbackModels(){return[]}adjustBuildBodyOptions(e,t){return t}adjustResponseFormat(e,t){return e}suppressResponseFormatWithTools(){return!0}useStreamingWireForGenerate(){return!1}adjustRequestBody(e,t){return e}adjustBodyAfter400(e,t){}resolveWireMaxTokens(e,t,r,n){const o=P7(this.providerName,e);let s=t;o!==void 0&&(s===void 0||s>o)&&(s!==void 0&&p.debug(`${this.providerName}: clamping max_tokens ${s} to the advertised ${e} output ceiling ${o}`),s=o);const i=M7(this.providerName,e);if(i!==void 0){const a=CW(r,n,this.providerName),c=i-a-MP;if(c<=0)throw new ka(`Estimated input (${a} tokens) alone exceeds the ${this.providerName}/${e} context window advertised by the serving infrastructure (${i} tokens). Reduce the prompt/conversation size \u2014 no max_tokens value can make this request fit.`,{estimatedTokens:a,availableTokens:Math.max(0,i-MP),stagesUsed:[],breakdown:{}});s!==void 0&&s>c&&(p.warn(`${this.providerName}: max_tokens ${s} cannot fit the ${e} window (${i}) with ~${a} input tokens \u2014 re-fitting to ${c}`),s=c)}return s}correctBodyAfterContextOverflow(e,t){if(!BW(t))return;const r=zW(t)??zW(t.responseBody);if(!r||r.budgetTokens<=0)return;R7(this.providerName,e.model,r.budgetTokens);const n=typeof e.max_tokens=="number"?e.max_tokens:r.requestedOutputTokens;if(n===void 0||r.actualTokens<=0)return;const o=r.budgetTokens-r.actualTokens-MP;if(!(o<=0||o>=n))return p.warn(`${this.providerName}: ${e.model} rejected the request as over-window \u2014 retrying once with max_tokens re-fit from the provider's own numbers`,{window:r.budgetTokens,inputTokens:r.actualTokens,previousMaxTokens:n,refitMaxTokens:o}),{...e,max_tokens:o}}onStreamStart(e){}shouldAutoDiscoverModel(){return!0}getChatCompletionsURL(e){return`${Ca(this.config.baseURL)}/chat/completions`}getAuthHeaders(){return{Authorization:`Bearer ${this.config.apiKey}`}}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}async probeModelsEndpoint(e={}){try{const t=`${Ca(this.config.baseURL)}/models`,n=await Rt()(t,{headers:{...e,"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)});return n.ok?!!(await n.json().catch(()=>null))?.data?.some(s=>typeof s?.id=="string"&&s.id.trim().length>0):!1}catch(t){return p.debug(`[${this.constructor.name}] probeModelsEndpoint failed`,{baseURL:yo(this.config.baseURL),error:t instanceof Error?t.message:String(t)}),!1}}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}async getAISDKModel(){const e=await this.resolveModelName();return this.buildDelegatingModel(e)}async resolveModelName(){if(this.resolvedModel)return this.resolvedModel;const e=this.modelName||this.getDefaultModel();if(e&&e.trim()!=="")return this.resolvedModel=e,this.modelName!==e&&this.refreshHandlersForModel(e),e;if(this.shouldAutoDiscoverModel()){try{const r=await this.getAvailableModels();if(r.length>0)return this.resolvedModel=r[0],this.refreshHandlersForModel(r[0]),p.info(`\u{1F50D} Auto-discovered model: ${r[0]} from ${r.length} available models`),r[0]}catch(r){p.warn("Model auto-discovery failed, using fallback:",r)}return this.getFallbackModelName()}const t=this.getFallbackModelName();return this.resolvedModel=t,this.refreshHandlersForModel(t),t}buildDelegatingModel(e){const t=this.getChatCompletionsURL(e),r=Rt(),n=this.getAuthHeaders.bind(this),o=this.providerName,s=this.adjustBuildBodyOptions.bind(this),i=this.adjustResponseFormat.bind(this),a=this.adjustRequestBody.bind(this),c=this.adjustBodyAfter400.bind(this),l=this.correctBodyAfterContextOverflow.bind(this),u=this.resolveWireMaxTokens.bind(this),d=this.suppressResponseFormatWithTools.bind(this),m=this.useStreamingWireForGenerate.bind(this),h=f=>this.getTimeout(f??{});return{specificationVersion:"v3",provider:o,modelId:e,supportedUrls:{},doGenerate:async f=>{const g=CP((f.tools??[]).filter(V=>V.type==="function").map(V=>V.name)),y=xW(f.prompt,g?.toWire),v=Array.isArray(f.tools)&&f.tools.length>0,w=f.responseFormat&&!(v&&d())?i(igt(f.responseFormat),e):void 0,S=rgt(f.tools,g?.toWire),_=u(e,f.maxOutputTokens,y,S),C=m(),k=PW(a(DW({modelId:e,messages:y,options:s(e,{maxTokens:_,temperature:f.temperature,topP:f.topP,presencePenalty:f.presencePenalty,frequencyPenalty:f.frequencyPenalty,seed:f.seed,stopSequences:f.stopSequences}),tools:S,...f.toolChoice?{toolChoice:ngt(f.toolChoice,g?.toWire)}:{},streaming:C,...w?{responseFormat:w}:{}}),e)),A=f.providerOptions?.neurolink?.timeoutMs,I=fa(typeof A=="number"?A:h(f),o,"generate"),{signal:R,dispose:M}=gB(f.abortSignal,I?.controller.signal);let D,U=C;try{let V=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(k),...R?{signal:R}:{}});if(!V.ok){const q=await E_(t,k,V),G=q;let J=V.status===400?(()=>{const re=l(k,G);return c(re??k,G)??re})():void 0;if(!J&&C&&V.status===400&&/stream/i.test(G.responseBody??"")){const{stream:re,stream_options:pe,...ne}=k;J=ne,U=!1}if(!J)throw q;if(V=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(J),...R?{signal:R}:{}}),!V.ok)throw await E_(t,J,V)}if(U){if(!V.body)throw new Error(`${o}: streaming generate response had no body`);const q=I?V.body.pipeThrough(new TransformStream({transform(J,re){I.reset(),re.enqueue(J)}})):V.body,G=await OW(q,()=>{});D={...G.id?{id:G.id}:{},...G.model?{model:G.model}:{},choices:[{index:0,message:{role:"assistant",content:G.text.length>0?G.text:null,...G.reasoning?{reasoning:G.reasoning}:{},...G.toolCalls.size>0?{tool_calls:[...G.toolCalls.values()].map(J=>({id:J.id,type:"function",function:{name:J.name,arguments:J.argsBuffered}}))}:{}},finish_reason:G.finishReason??"stop"}],...G.usage?{usage:G.usage}:{}}}else D=await V.json()}finally{I?.cleanup(),M()}const P=D.choices?.[0],$=(typeof P?.message?.content=="string"?P.message.content:"")??"",N=[],F=P?.message?.reasoning_content||P?.message?.reasoning;typeof F=="string"&&F.length>0&&N.push({type:"reasoning",text:F}),$.length>0&&N.push({type:"text",text:$});for(const V of P?.message?.tool_calls??[])N.push({type:"tool-call",toolCallId:V.id,toolName:g?.fromWire.get(V.function.name)??V.function.name,input:V.function.arguments??""});const j=P?.finish_reason;return{content:N,finishReason:{unified:j==="length"?"length":j==="tool_calls"||j==="function_call"?"tool-calls":j==="content_filter"?"content-filter":"stop",raw:j??"stop"},usage:{inputTokens:{total:D.usage?.prompt_tokens,noCache:D.usage?.prompt_tokens!==void 0&&D.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.max(0,D.usage.prompt_tokens-D.usage.prompt_tokens_details.cached_tokens):D.usage?.prompt_tokens,cacheRead:D.usage?.prompt_tokens!==void 0&&D.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.min(D.usage.prompt_tokens_details.cached_tokens,D.usage.prompt_tokens):D.usage?.prompt_tokens_details?.cached_tokens,cacheWrite:void 0},outputTokens:{total:D.usage?.completion_tokens,text:D.usage?.completion_tokens!==void 0&&D.usage?.completion_tokens_details?.reasoning_tokens!==void 0?Math.max(0,D.usage.completion_tokens-D.usage.completion_tokens_details.reasoning_tokens):D.usage?.completion_tokens,reasoning:D.usage?.completion_tokens_details?.reasoning_tokens}},warnings:[],request:{body:k},response:{...D.id?{id:D.id}:{},...D.model?{modelId:D.model}:{},headers:{},body:D}}},doStream:()=>{throw new Error(`${o}: 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.`)}}}async generate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if(pd(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=await this.resolveModelName(),n=await this.getAISDKModelWithMiddleware(e);if(!AP(n))throw this.handleProviderError(new Error(`${this.providerName}: model handle exposes no doGenerate()`));const o=n.doGenerate.bind(n),s=!e.disableTools&&this.supportsTools(),i=s?e.tools||await this.getAllTools():{},a=s?Object.entries(i).map(([I,R])=>{const M=R;return{type:"function",name:I,description:M.description??"",inputSchema:M.inputSchema?No(M.inputSchema):{type:"object",properties:{}}}}):void 0,c=!!a&&a.length>0,l=e.schema?No(e.schema):void 0,u=l!==void 0&&c&&this.suppressResponseFormatWithTools(),d=l&&!u?{type:"json",schema:l}:void 0,m=await this.buildMessagesForStream(e),h=[],f=(I,R,M=!0)=>HW({doGenerate:o,...G1r({provider:this.providerName,availableInputTokens:El(this.providerName,r,e.maxTokens??void 0),getFixedOverheadTokens:()=>Zt(UV({...M&&a?{tools:a}:{},responseFormat:R}),this.providerName)}),conversation:I,...M&&a?{tools:a}:{},toolsRecord:i,...M&&c&&e.toolChoice?{toolChoice:RP(e,i,!0)}:{},...typeof e.timeout=="number"?{providerOptions:{neurolink:{timeoutMs:e.timeout}}}:{},...R?{responseFormat:R}:{},maxSteps:e.maxSteps||zs,...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:D=>Vy(D,lt.getActiveSpan()??void 0,`${this.providerName} generate`).catch(U=>{throw this.handleProviderError(U)})},h);let g;try{g=await f(m,d)}catch(I){if(!(d!==void 0&&(YRr(I)||sft(I))))throw I;p.warn(`[${this.providerName}] provider rejected response_format \u2014 retrying with the schema in the system prompt`,{provider:this.providerName,model:r}),g=await f(b_(m,d.schema),void 0)}if(d!==void 0&&e.schema!==void 0&&!C_(g.text,e.schema)){p.warn(`[${this.providerName}] response_format did not yield a schema-valid object \u2014 retrying with the schema in the system prompt`,{provider:this.providerName,model:r});const I=g,R=await f(b_(m,d.schema),void 0);g={...R,inputTokens:I.inputTokens+R.inputTokens,outputTokens:I.outputTokens+R.outputTokens,cacheReadTokens:(I.cacheReadTokens??0)+(R.cacheReadTokens??0),cacheWriteTokens:(I.cacheWriteTokens??0)+(R.cacheWriteTokens??0)}}u&&l&&e.schema&&(g=await this.reformatWithoutTools({toolPhase:g,conversation:m,schemaJson:l,schema:e.schema,runLoop:f,modelId:r,abortSignal:e.abortSignal}));const{text:y,finishReason:v,toolsUsed:w}=g,S=g.inputTokens,_=g.outputTokens,C=g.steps,k=C>=(e.maxSteps||zs)&&v==="tool-calls"?"step-cap":v==="error"?"provider-error":"completed",A={content:y,provider:this.providerName,model:r,finishReason:v,...g.rawFinishReason?{rawFinishReason:g.rawFinishReason}:{},stopReason:k,stepsUsed:C,usage:{input:S,output:_,total:S+_,...g.cacheReadTokens?{cacheReadTokens:g.cacheReadTokens}:{},...g.cacheWriteTokens?{cacheCreationTokens:g.cacheWriteTokens}:{}},responseTime:Date.now()-t,...g.reasoning?{reasoning:g.reasoning}:{},toolsUsed:w,toolCalls:jj(h),toolExecutions:Wh(e,fd(h)),enhancedWithTools:w.length>0};return this.finalizeNativeGenerate(A,e,t)}async reformatWithoutTools(e){const{toolPhase:t,conversation:r,schemaJson:n,schema:o,runLoop:s,modelId:i,abortSignal:a}=e;let c=t;const l=()=>a?.aborted===!0;if(c.text.trim().length>0&&!l()&&!C_(c.text,o)){p.warn(`[${this.providerName}] tools suppressed response_format and the answer is not schema-valid \u2014 re-asking once without tools`,{provider:this.providerName,model:i});const u={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},d=m=>{u.inputTokens+=m.inputTokens,u.outputTokens+=m.outputTokens,u.cacheReadTokens+=m.cacheReadTokens??0,u.cacheWriteTokens+=m.cacheWriteTokens??0};try{const m=[...r,{role:"assistant",content:t.text},{role:"user",content:"Return that same answer as a single JSON value conforming to the required schema. No prose before or after it, and no markdown code fence."}];let h,f=!1;try{h=await s(m,{type:"json",schema:n},!1),d(h)}catch(g){if(l())throw g;p.warn(`[${this.providerName}] the re-ask's response_format was rejected \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:i,error:g instanceof Error?g.message:String(g)}),h=await s(b_(m,n),void 0,!1),d(h),f=!0}if(!f&&!l()&&!C_(h.text,o)&&(p.warn(`[${this.providerName}] the re-ask's response_format carried no schema \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:i}),h=await s(b_(m,n),void 0,!1),d(h)),!C_(h.text,o))throw p.warn(`[${this.providerName}] the tool-free re-ask did not yield a schema-valid object either; keeping the original answer`,{provider:this.providerName,model:i}),new rK;c={...h,toolsUsed:[...new Set([...t.toolsUsed,...h.toolsUsed])],inputTokens:t.inputTokens+u.inputTokens,outputTokens:t.outputTokens+u.outputTokens,cacheReadTokens:(t.cacheReadTokens??0)+u.cacheReadTokens,cacheWriteTokens:(t.cacheWriteTokens??0)+u.cacheWriteTokens,steps:t.steps,...t.finishReason!=="stop"?{finishReason:t.finishReason,rawFinishReason:t.rawFinishReason}:{finishReason:h.finishReason}}}catch(m){if(l()&&!(a?.reason instanceof ja))throw m;m instanceof rK||p.warn(`[${this.providerName}] the tool-free structured-output re-ask failed; keeping the original answer`,{provider:this.providerName,model:i,error:m instanceof Error?m.message:String(m)}),c={...c,inputTokens:c.inputTokens+u.inputTokens,outputTokens:c.outputTokens+u.outputTokens,cacheReadTokens:(c.cacheReadTokens??0)+u.cacheReadTokens,cacheWriteTokens:(c.cacheWriteTokens??0)+u.cacheWriteTokens}}}return c}async executeStream(e,t){this.validateStreamOptions(e);const r=Date.now(),n=this.getTimeout(e),o=fa(n,this.providerName,"stream"),s=new AbortController,i=hge([e.abortSignal,o?.controller.signal,s.signal]).signal;let a,c,l,u,d,m;try{a=await this.resolveModelName();const q=!e.disableTools&&this.supportsTools();c=q?e.tools||await this.getAllTools():{},l=q?CP(Object.keys(c)):void 0,u=q?IW(c,l?.toWire):void 0,d=agt(RP(e,c,q),l?.toWire),m=await this.buildMessagesForStream(e)}catch(q){throw o?.cleanup(),q}const h=this.getChatCompletionsURL(a),f=Rt(),g=e.maxSteps||zs,y=this.neurolink?.getEventEmitter(),v=[],w=[],{usagePromise:S,finishPromise:_,resolveUsage:C,resolveFinish:k}=NW(),A=V0(),I=this.onStreamStart(a),R=u?.map(q=>({type:"function",name:q.function.name,description:q.function.description,inputSchema:q.function.parameters})),M={prompt:m,...R?{tools:R}:{},...e.maxTokens!==void 0?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.topP!==void 0?{topP:e.topP}:{}};let D;const U=this.providerName,P={specificationVersion:"v3",provider:U,modelId:a,supportedUrls:{},doGenerate:async q=>{const G=await this.getAISDKModel();if(typeof G=="string")throw new Error("Native model handle required");return G.doGenerate(q)},doStream:async q=>{q?.tools!==void 0&&q.tools!==R&&p.warn(`${U}: middleware rewrote 'tools' on the streaming path; tool rewrites are not applied to the wire request yet \u2014 the original tool list was sent.`);const G=Array.isArray(q?.prompt)?q.prompt:m,J=xW(G,l?.toWire),re={...e,...typeof q?.maxOutputTokens=="number"?{maxTokens:q.maxOutputTokens}:{},...typeof q?.temperature=="number"?{temperature:q.temperature}:{},...typeof q?.topP=="number"?{topP:q.topP}:{}};D=this.runStreamLoop({maxSteps:g,modelId:a,url:h,fetchImpl:f,abortSignal:i,options:re,conversation:J,openAITools:u,openAIToolChoice:d,toolsRecord:c,toolNameFromWire:l?.fromWire,emitter:y,toolsUsed:v,toolExecutionSummaries:w,pushChunk:A.push,closeChannel:A.close,resolveUsage:C,resolveFinish:k});const pe=D.then(()=>Promise.all([S,_]).then(([ne,ie])=>({type:"finish",finishReason:{unified:ie},usage:{inputTokens:{total:ne.promptTokens,cacheRead:ne.cacheReadTokens},outputTokens:{total:ne.completionTokens}}})));return pe.catch(()=>{}),{stream:Jgt(A.iterable,pe,()=>s.abort())}}};let $;try{const q=await this.applyMiddlewareToModel(P,e);if(typeof q=="string")throw new Error("Native stream model handle required");const{stream:G}=await q.doStream(M);$=lMr(G,J=>{if(!D){const re=J.usage.inputTokens.total??0,pe=J.usage.outputTokens.total??0;C({promptTokens:re,completionTokens:pe,totalTokens:re+pe}),k(J.finishReason.unified)}})}catch(q){throw s.abort(),A.close(),o?.cleanup(),q}let N;const F=q=>{N=q};I?.onUsage&&S.then(I.onUsage).catch(()=>{}),I?.onFinish&&_.then(q=>I.onFinish?.(q,N)).catch(()=>{});const j=this.providerName,V={stream:async function*(){let q=0;try{for await(const G of $)"content"in G&&typeof G.content=="string"&&G.content.length>0&&q++,yield G;if(await D,q===0&&v.length===0){p.warn(`${j}: Stream produced no output \u2014 emitting enriched sentinel`);const G=new ou({message:"Stream produced no output"}),J=await gf(G,void 0,N);yf(J),yield J}}catch(G){if(ou.isInstance(G)){const re=await gf(G,void 0,N);yf(re),yield re;return}const J=await gf(G,void 0,N);throw yf(J),yield J,G}finally{D||(C({promptTokens:0,completionTokens:0,totalTokens:0}),k("stop")),o?.cleanup(),s.signal.aborted||s.abort()}}(),provider:this.providerName,model:a,analytics:jW.createAnalytics(this.providerName,a,{textStream:(async function*(){})(),usage:S,finishReason:_},Date.now()-r,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),toolsUsed:v,metadata:{startTime:r,streamId:`${this.providerName}-${Date.now()}`}};return Object.defineProperty(V,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>fd(w.map(q=>({toolName:q.toolName,input:q.input,output:q.output,duration:q.endTime.getTime()-q.startTime.getTime()})))}),D?.finally(()=>o?.cleanup()).catch(q=>{F(q)}),V}async runStreamLoop(e){const{maxSteps:t,modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:c,openAIToolChoice:l,toolsRecord:u,toolNameFromWire:d,emitter:m,toolsUsed:h,toolExecutionSummaries:f,pushChunk:g,closeChannel:y,resolveUsage:v,resolveFinish:w}=e;let S=null,_;const C=()=>{const k=_?.prompt_tokens??0,A=_?.completion_tokens??0,I=Math.min(_?.prompt_tokens_details?.cached_tokens??0,k),R=Math.min(Math.max(0,_?.completion_tokens_details?.reasoning_tokens??0),A);return{promptTokens:k-I,completionTokens:A,totalTokens:_?.total_tokens||k+A,...I>0?{cacheReadTokens:I}:{},...R>0?{reasoningTokens:R}:{}}};try{let k=d,A,I;for(let R=0;R<t;R++){if(c){const U=new Set(c.map($=>k?.get($.function.name)??$.function.name)),P=Object.fromEntries(Object.entries(u).filter(([$])=>!U.has($)));if(Object.keys(P).length>0){const $=CP(Object.keys(P),new Set(c.map(N=>N.function.name)));if($){k??=new Map;for(const[N,F]of $.fromWire)k.set(N,F)}c.push(...IW(P,$?.toWire)??[]),p.info(`${this.providerName}: ${Object.keys(P).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(P).join(", ")}`)}}const M=z1r({conversation:a,availableInputTokens:El(this.providerName,r,i.maxTokens??void 0),fixedOverheadTokens:CW([],c,this.providerName),provider:this.providerName,observedPromptTokens:A,previousSentEstimate:I,onSentEstimate:U=>{I=U}});M&&(a.length=0,a.push(...M));const D=await this.streamOneStep({modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:c,openAIToolChoice:l,pushChunk:g});if(A=D.usage?.prompt_tokens,S=D.finishReason,D.usage&&(_=ugt(_,D.usage)),D.toolCalls.size===0)break;await this.executeToolBatch({stepResult:D,conversation:a,toolsRecord:u,toolNameFromWire:k,emitter:m,toolsUsed:h,toolExecutionSummaries:f,options:i})}return v(C()),w(S??"stop"),y(),{finishReason:S??"stop",usage:_}}catch(k){throw p.error(`${this.providerName}: Stream error`,{error:k instanceof Error?k.message:String(k)}),v(C()),w("error"),y(),k}}async streamOneStep(e){const t=this.resolveWireMaxTokens(e.modelId,e.options.maxTokens??void 0,e.conversation,e.openAITools),r=t!==e.options.maxTokens?{...e.options,maxTokens:t}:e.options,n=PW(this.adjustRequestBody(DW({modelId:e.modelId,messages:e.conversation,options:this.adjustBuildBodyOptions(e.modelId,r),tools:e.openAITools,...e.openAIToolChoice!==void 0?{toolChoice:e.openAIToolChoice}:{},streaming:!0}),e.modelId)),o=async()=>{const i=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(n),...e.abortSignal?{signal:e.abortSignal}:{}});if(!i.ok)throw await E_(e.url,n,i);return i};let s;try{s=await Vy(o,lt.getActiveSpan()??void 0,`${this.providerName} stream`)}catch(i){const a=i,c=a.statusCode===400?(()=>{const l=this.correctBodyAfterContextOverflow(n,a);return this.adjustBodyAfter400(l??n,a)??l})():void 0;if(!c)throw a;if(s=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(c),...e.abortSignal?{signal:e.abortSignal}:{}}),!s.ok)throw await E_(e.url,c,s)}if(!s.body)throw new Error(`${this.providerName}: stream response had no body`);return OW(s.body,i=>{e.pushChunk({content:i})},i=>{e.pushChunk({content:"",reasoning:i})})}async executeToolBatch(e){const{stepResult:t,conversation:r,toolsRecord:n,toolNameFromWire:o,emitter:s,toolsUsed:i,toolExecutionSummaries:a,options:c}=e,l=[];for(const[,d]of t.toolCalls)l.push({id:d.id,type:"function",function:{name:d.name,arguments:d.argsBuffered}});r.push({role:"assistant",content:t.text.length>0?t.text:null,tool_calls:l});for(const[,d]of t.toolCalls){const m=new Date;let h;try{h=JSON.parse(d.argsBuffered||"{}")}catch{h=d.argsBuffered}let f,g;const y=o?.get(d.name)??d.name,v=n[y]??iH(n,y);if(s?.emit("tool:start",{toolName:y,toolCallId:d.id,input:h}),!v||typeof v.execute!="function")g=`Tool '${y}' is not registered.`,f={error:g};else try{f=await v.execute(h,{})}catch(S){g=S instanceof Error?S.message:String(S),f={error:g}}const w=new Date;i.push(y),a.push({toolCallId:d.id,toolName:y,input:h,output:f,...g?{error:g}:{},startTime:m,endTime:w}),r.push({role:"tool",tool_call_id:d.id,content:kW(f)})}const u=a.slice(-t.toolCalls.size);ygt(s,u.map(d=>({toolName:d.toolName,output:d.output,...d.error?{error:d.error}:{}})));try{await this.handleToolExecutionStorage(u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,output:d.output})),u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,output:d.output})),c,new Date)}catch(d){p.warn(`[${this.constructor.name}] Failed to store tool executions`,{provider:this.providerName,error:d instanceof Error?d.message:String(d)})}}async getAvailableModels(){try{const e=`${Ca(this.config.baseURL)}/models`;p.debug(`Fetching available models from: ${e}`);const t=Rt(),r=new AbortController,n=setTimeout(()=>r.abort(),5e3),o=await t(e,{headers:{...this.getAuthHeaders(),"Content-Type":"application/json"},signal:r.signal});if(clearTimeout(n),!o.ok)return p.warn(`Models endpoint returned ${o.status}: ${o.statusText}`),this.getFallbackModels();const s=await o.json();if(!s.data||!Array.isArray(s.data))return p.warn("Invalid models response format"),this.getFallbackModels();const i=s.data.map(a=>a.id).filter(Boolean);return p.shouldLog("debug")&&p.debug(`Discovered ${i.length} models:`,i),i.length>0?i:this.getFallbackModels()}catch(e){return p.warn(`[${this.constructor.name}] Failed to fetch models from endpoint:`,e),this.getFallbackModels()}}async getFirstAvailableModel(){return(await this.getAvailableModels())[0]||this.getFallbackModelName()}}}}),nK,Ygt,Xgt,Zgt,Qgt,eyt,uMr=b({"src/lib/providers/openAI/client.ts"(){"use strict";Yt(),Mn(),ct(),B(),Ut(),Ya(),ci(),qo(),tc(),If(),ga(),dp(),rc(),nd(),nK="https://api.openai.com/v1",Ygt=(e,t)=>{const r=[e,t].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??nK;try{const n=new URL(r),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",Ca(n.toString())}catch{}return r},Xgt=()=>Ai(Yhr()),Zgt=()=>li("OPENAI_MODEL","gpt-4o"),Qgt=lt.getTracer("neurolink.provider.openai"),eyt=class extends Aa{constructor(e,t,r,n){const o=n?.apiKey?.trim(),s=o&&o.length>0?o:Xgt(),i=Ygt(n?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:i,apiKey:s}),p.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:yo(this.config.baseURL)})}suppressResponseFormatWithTools(){return!1}getProviderName(){return"openai"}getDefaultModel(){return Zgt()}formatProviderError(e){const t=e,r=t?.type&&typeof t.type=="string"?t.type:void 0,n=[{match:o=>o.statusCode===401||r==="invalid_api_key"||/API_KEY_INVALID|Invalid API key|Incorrect API key|invalid_api_key/i.test(o.message),errorClass:kr,message:o=>/Incorrect API key|Invalid API key/i.test(o.message)?o.message:"Invalid OpenAI API key. Please check your OPENAI_API_KEY environment variable."},{match:o=>wge(o.error),errorClass:Xe,message:"OpenAI quota exhausted \u2014 this will not resolve by retrying. Check your plan and billing details at https://platform.openai.com/account/billing"},{match:o=>o.statusCode===429||r==="rate_limit_error"||/rate limit/i.test(o.message),errorClass:vs,message:"OpenAI rate limit exceeded. Please try again later."},{match:o=>/model_not_found/i.test(o.message),errorClass:go,message:o=>`Model not found: ${o.modelName}`},...ya];return ki(e,n,this.providerName,this.modelName)}onStreamStart(e){const t=Qgt.startSpan("neurolink.provider.streamText",{kind:zr.CLIENT,attributes:{"gen_ai.system":"openai","gen_ai.request.model":e}});let r=!1;const n=()=>{r||(r=!0,t.end())};return{onUsage:o=>{t.setAttribute("gen_ai.usage.input_tokens",o.promptTokens+(o.cacheReadTokens??0)+(o.cacheCreationTokens??0)),t.setAttribute("gen_ai.usage.output_tokens",o.completionTokens);const s=Ri(this.providerName,e,{input:o.promptTokens,output:o.completionTokens,total:o.totalTokens,...o.cacheReadTokens?{cacheReadTokens:o.cacheReadTokens}:{},...o.cacheCreationTokens?{cacheCreationTokens:o.cacheCreationTokens}:{}});s&&s>0&&t.setAttribute("neurolink.cost",s)},onFinish:(o,s)=>{t.setAttribute("gen_ai.response.finish_reason",o||"unknown"),o==="error"&&t.setStatus({code:Fe.ERROR,message:s instanceof Error?s.message:String(s??"stream error")}),n()}}}getDefaultEmbeddingModel(){return process.env.OPENAI_EMBEDDING_MODEL||"text-embedding-3-small"}async embed(e,t){if(typeof e!="string"&&e.image)throw new Xe(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||this.getDefaultEmbeddingModel();p.debug("Generating embedding",{provider:this.providerName,model:n,textLength:r.length});try{const[o]=await this.callEmbeddings(n,[r],"embed");return p.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:o.length}),o}catch(o){throw p.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:r.length}),this.handleProviderError(o)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel();p.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=await this.callEmbeddings(r,e,"embedMany");return p.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:n.length,embeddingDimension:n[0]?.length}),n}catch(n){throw p.error("Batch embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,count:e.length}),this.handleProviderError(n)}}async callEmbeddings(e,t,r){const n=`${Ca(this.config.baseURL)}/embeddings`,o=Rt(),s=fa(3e4,this.providerName,"generate");try{const i=await o(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...s?.controller.signal?{signal:s.controller.signal}:{}});if(!i.ok){const l=await i.text().catch(()=>"");let u=`OpenAI ${r} failed with status ${i.status}`,d;if(l)try{const m=JSON.parse(l);m.error?.message&&(u=m.error.message),d=m.error?.type}catch{}throw Object.assign(new Error(u),{status:i.status,type:d})}const c=((await i.json()).data??[]).map(l=>l.embedding).filter(l=>Array.isArray(l));if(c.length===0)throw new Xe(`OpenAI ${r} returned no embeddings`,this.providerName);return c}finally{s?.cleanup()}}async executeImageGeneration(e){const t=Date.now(),r=e.prompt??e.input?.text??"";if(!r.trim())throw new Error("OpenAI image generation requires a prompt (input.text or prompt)");const n=e.model??this.modelName,o=Ca(this.config.baseURL??nK),s=e,i=s.size??this.aspectRatioToOpenAISize(s.aspectRatio,n),a=s.numberOfImages??1;let c;n==="gpt-image-1"||n.startsWith("dall-e-3")?c=1:n.startsWith("dall-e-2")?c=Math.min(Math.max(a,1),10):c=1;const u={model:n,prompt:r,n:c,size:i};n==="gpt-image-1"?s.quality&&(u.quality=s.quality):n.startsWith("dall-e-3")?(u.response_format="b64_json",s.quality&&(u.quality=s.quality),s.style&&(u.style=s.style)):u.response_format="b64_json";const d=12e4,m=new AbortController,h=setTimeout(()=>m.abort(),d);let f;try{f=await Rt()(`${o}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:m.signal})}catch(S){throw S instanceof Error&&S.name==="AbortError"?new Error(`OpenAI image generation timed out after ${d/1e3}s`,{cause:S}):S}finally{clearTimeout(h)}if(!f.ok){const S=await f.text();throw new Error(`OpenAI image generation failed: ${f.status} \u2014 ${S}`)}const y=(await f.json()).data?.[0];if(!y)throw new Error("OpenAI image generation returned no images");let v=y.b64_json;if(!v&&y.url){await xf(y.url);const S=Rt(),_=new AbortController,C=setTimeout(()=>_.abort(),6e4);let k;try{k=await S(y.url,{signal:_.signal})}catch(I){throw I instanceof Error&&I.name==="AbortError"?new Error("OpenAI image URL download timed out after 60s",{cause:I}):I}finally{clearTimeout(C)}if(!k.ok)throw new Error(`OpenAI image generation: failed to fetch hosted URL ${y.url} (${k.status})`);v=(await Rd(k,Af,"OpenAI image fallback")).toString("base64")}if(!v)throw new Error("OpenAI image generation returned neither b64_json nor a URL");const w=Date.now()-t;return p.info(`[OpenAIProvider] Generated image (${v.length} base64 chars) in ${w}ms \u2014 model ${n}`),{content:y.revised_prompt??r,provider:this.providerName,model:n,usage:{input:0,output:0,total:0},imageOutput:{base64:v}}}aspectRatioToOpenAISize(e,t){return t==="gpt-image-1"?e==="16:9"||e==="3:2"?"1536x1024":e==="9:16"||e==="2:3"?"1024x1536":"1024x1024":t.startsWith("dall-e-3")?e==="16:9"||e==="3:2"?"1792x1024":e==="9:16"||e==="2:3"?"1024x1792":"1024x1024":"1024x1024"}}}}),tyt={};se(tyt,{OpenAIProvider:()=>eyt});var dMr=b({"src/lib/providers/openAI/index.ts"(){"use strict";uMr()}});function Ne(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r}function H(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var nc=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/tslib.mjs"(){}}),k_,oK=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs"(){k_=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return k_=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}}});function Z0(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var A_,Q0=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/errors.mjs"(){A_=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)}}}),st,Oi,Lc,ev,sK,ryt,iK,aK,cK,lK,uK,dK,mK,pK,So=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/error.mjs"(){Q0(),st=class extends Error{},Oi=class Ace extends st{constructor(t,r,n,o,s){super(`${Ace.makeMessage(t,r,n)}`),this.status=t,this.headers=o,this.requestID=o?.get("request-id"),this.error=r,this.type=s??null}static makeMessage(t,r,n){const o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,r,n,o){if(!t||!o)return new ev({message:n,cause:A_(r)});const s=r,i=s?.error?.type;return t===400?new iK(t,s,n,o,i):t===401?new aK(t,s,n,o,i):t===403?new cK(t,s,n,o,i):t===404?new lK(t,s,n,o,i):t===409?new uK(t,s,n,o,i):t===422?new dK(t,s,n,o,i):t===429?new mK(t,s,n,o,i):t>=500?new pK(t,s,n,o,i):new Ace(t,s,n,o,i)}},Lc=class extends Oi{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ev=class extends Oi{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},sK=class extends ev{constructor({message:e}={}){super({message:e??"Request timed out."})}},ryt=class extends st{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},iK=class extends Oi{},aK=class extends Oi{},cK=class extends Oi{},lK=class extends Oi{},uK=class extends Oi{},dK=class extends Oi{},mK=class extends Oi{},pK=class extends Oi{}}});function hK(e){return typeof e!="object"?{}:e??{}}function nyt(e){if(!e)return!0;for(const t in e)return!1;return!0}function mMr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var oyt,syt,Qi,fK,iyt,gK,Pd=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs"(){So(),oyt=/^[a-z][a-z0-9+.-]*:/i,syt=e=>oyt.test(e),Qi=e=>(Qi=Array.isArray,Qi(e)),fK=Qi,iyt=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new st(`${e} must be an integer`);if(t<0)throw new st(`${e} must be a positive integer`);return t},gK=e=>{try{return JSON.parse(e)}catch{return}}}}),mp,x_=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"(){mp=(e,t)=>new Promise(r=>{if(t?.aborted)return r();const n=()=>{clearTimeout(o),r()},o=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}}),Dd,PP=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/version.mjs"(){Dd="0.102.0"}});function pMr(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function hMr(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:r}of e){const n=r.exec(navigator.userAgent);if(n){const o=n[1]||0,s=n[2]||0,i=n[3]||0;return{browser:t,version:`${o}.${s}.${i}`}}}return null}var ayt,cyt,yK,vK,lyt,DP,TK=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs"(){PP(),ayt=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",cyt=()=>{const e=pMr();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dd,"X-Stainless-OS":vK(Deno.build.os),"X-Stainless-Arch":yK(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dd,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dd,"X-Stainless-OS":vK(globalThis.process.platform??"unknown"),"X-Stainless-Arch":yK(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=hMr();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dd,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dd,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},yK=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",vK=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),DP=()=>lyt??(lyt=cyt())}});function fMr(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function uyt(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function dyt(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return uyt({start(){},async pull(r){const{done:n,value:o}=await t.next();n?r.close():r.enqueue(o)},async cancel(){await t.return?.()}})}function wK(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){const r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function gMr(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}const t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var I_=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/shims.mjs"(){}}),myt,yMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/request-options.mjs"(){myt=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)})}}),EK,SK,bK,pyt,hyt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs"(){EK="RFC3986",SK=e=>String(e),bK={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:SK},pyt="RFC1738"}});function vMr(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function fyt(e,t){if(Qi(e)){const r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}var OP,Cl,NP,gyt,TMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs"(){hyt(),Pd(),OP=(e,t)=>(OP=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),OP(e,t)),Cl=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),NP=1024,gyt=(e,t,r,n,o)=>{if(e.length===0)return e;let s=e;if(typeof e=="symbol"?s=Symbol.prototype.toString.call(e):typeof e!="string"&&(s=String(e)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=NP){const c=s.length>=NP?s.slice(a,a+NP):s,l=[];for(let u=0;u<c.length;++u){let d=c.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===pyt&&(d===40||d===41)){l[l.length]=c.charAt(u);continue}if(d<128){l[l.length]=Cl[d];continue}if(d<2048){l[l.length]=Cl[192|d>>6]+Cl[128|d&63];continue}if(d<55296||d>=57344){l[l.length]=Cl[224|d>>12]+Cl[128|d>>6&63]+Cl[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=Cl[240|d>>18]+Cl[128|d>>12&63]+Cl[128|d>>6&63]+Cl[128|d&63]}i+=l.join("")}return i}}});function wMr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}function yyt(e,t,r,n,o,s,i,a,c,l,u,d,m,h,f,g,y,v){let w=e,S=v,_=0,C=!1;for(;(S=S.get(LP))!==void 0&&!C;){const M=S.get(e);if(_+=1,typeof M<"u"){if(M===_)throw new RangeError("Cyclic object value");C=!0}typeof S.get(LP)>"u"&&(_=0)}if(typeof l=="function"?w=l(t,w):w instanceof Date?w=m?.(w):r==="comma"&&Qi(w)&&(w=fyt(w,function(M){return M instanceof Date?m?.(M):M})),w===null){if(s)return c&&!g?c(t,cs.encoder,y,"key",h):t;w=""}if(wMr(w)||vMr(w)){if(c){const M=g?t:c(t,cs.encoder,y,"key",h);return[f?.(M)+"="+f?.(c(w,cs.encoder,y,"value",h))]}return[f?.(t)+"="+f?.(String(w))]}const k=[];if(typeof w>"u")return k;let A;if(r==="comma"&&Qi(w))g&&c&&(w=fyt(w,c)),A=[{value:w.length>0?w.join(",")||null:void 0}];else if(Qi(l))A=l;else{const M=Object.keys(w);A=u?M.sort(u):M}const I=a?String(t).replace(/\./g,"%2E"):String(t),R=n&&Qi(w)&&w.length===1?I+"[]":I;if(o&&Qi(w)&&w.length===0)return R+"[]";for(let M=0;M<A.length;++M){const D=A[M],U=typeof D=="object"&&typeof D.value<"u"?D.value:w[D];if(i&&U===null)continue;const P=d&&a?D.replace(/\./g,"%2E"):D,$=Qi(w)?typeof r=="function"?r(R,P):R:R+(d?"."+P:"["+P+"]");v.set(e,_);const N=new WeakMap;N.set(LP,v),CK(k,yyt(U,$,r,n,o,s,i,a,r==="comma"&&g&&Qi(w)?null:c,l,u,d,m,h,f,g,y,N))}return k}function EMr(e=cs){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");const t=e.charset||cs.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=EK;if(typeof e.format<"u"){if(!OP(bK,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const n=bK[r];let o=cs.filter;(typeof e.filter=="function"||Qi(e.filter))&&(o=e.filter);let s;if(e.arrayFormat&&e.arrayFormat in _K?s=e.arrayFormat:"indices"in e?s=e.indices?"indices":"repeat":s=cs.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:cs.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:cs.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:cs.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:cs.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?cs.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:cs.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:cs.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:cs.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:cs.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:cs.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:cs.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:cs.strictNullHandling}}function SMr(e,t={}){let r=e;const n=EMr(t);let o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):Qi(n.filter)&&(s=n.filter,o=s);const i=[];if(typeof r!="object"||r===null)return"";const a=_K[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);const l=new WeakMap;for(let m=0;m<o.length;++m){const h=o[m];n.skipNulls&&r[h]===null||CK(i,yyt(r[h],h,a,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}const u=i.join(n.delimiter);let d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}var _K,CK,vyt,cs,LP,bMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs"(){TMr(),hyt(),Pd(),_K={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},CK=function(e,t){Array.prototype.push.apply(e,Qi(t)?t:[t])},cs={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:gyt,encodeValuesOnly:!1,format:EK,formatter:SK,indices:!1,serializeDate(e){return(vyt??(vyt=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},LP={}}});function _Mr(e){return SMr(e,{arrayFormat:"brackets"})}var Tyt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs"(){bMr()}});function wyt(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new Pn(`Invalid token endpoint base URL "${e}": ${n}`)}if(t.protocol==="https:")return;const r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(t.protocol==="http:"&&(r==="localhost"||r==="127.0.0.1"||r==="::1")))throw new Pn(`Refusing to send credential over non-https token endpoint "${e}"`)}async function Eyt(e,t){const r=await CMr(e);let n;try{n=JSON.parse(r)}catch{throw new Pn(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,Fc(r),t)}if(!n.access_token)throw new Pn(`Token endpoint response missing access_token: ${JSON.stringify(Fc(n))}`,e.status,Fc(n),t);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new Pn(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,Fc(n),t);return n}function Fc(e){if(e==null)return e;if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{return e.length<=$P?e:e.slice(0,$P)+`... <${e.length-$P} more chars>`}return JSON.stringify(Fc(t))}if(typeof e=="object"&&!Array.isArray(e)){const t={};for(const[r,n]of Object.entries(e))Iyt.has(r)&&(t[r]=n);return t}return null}async function Syt(e,t=r=>console.warn(`anthropic-sdk: ${r}`)){if(typeof process>"u"||process.platform==="win32")return;const r=await Promise.resolve().then(()=>(Zn(),gd));let n=e,o;try{n=await r.promises.realpath(e),o=await r.promises.stat(n)}catch{return}const s=o.mode&511;if(s&18)throw new Pn(`Credentials file at ${n} is group/world-writable (mode 0o${s.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${n}\`.`);if(s&36)throw new Pn(`Credentials file at ${n} is group/world-readable (mode 0o${s.toString(8)}); run \`chmod 600 ${n}\` before retrying.`);typeof process.getuid=="function"&&o.uid!==process.getuid()&&t(`credentials file at ${n} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function byt(e,t){const r=await Promise.resolve().then(()=>(Zn(),gd)),o=(await Promise.resolve().then(()=>(Ht(),Wm))).dirname(e);await r.promises.mkdir(o,{recursive:!0,mode:448});const s=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const i=await r.promises.open(s,"w",384);try{await i.writeFile(JSON.stringify(t,null,2)),await i.sync()}finally{await i.close()}await r.promises.rename(s,e)}catch(i){throw await r.promises.unlink(s).catch(()=>{}),i}try{const i=await r.promises.open(o,"r");try{await i.sync()}finally{await i.close()}}catch{}}async function CMr(e){if(!e.body)return"";const t=e.body.getReader(),r=[];let n=0;for(;;){const{done:s,value:i}=await t.read();if(s)break;if(n+i.length>AK){const a=AK-n;a>0&&r.push(i.subarray(0,a)),await t.cancel();break}r.push(i),n+=i.length}let o;if(r.length===1)o=r[0];else{o=new Uint8Array(r.reduce((i,a)=>i+a.length,0));let s=0;for(const i of r)o.set(i,s),s+=i.length}return new TextDecoder("utf-8").decode(o)}var _yt,Cyt,kK,R_,kyt,Ayt,FP,xyt,AK,$P,Iyt,Pn,M_=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs"(){So(),_yt="urn:ietf:params:oauth:grant-type:jwt-bearer",Cyt="refresh_token",kK="/v1/oauth/token",R_="oauth-2025-04-20",kyt="oidc-federation-2026-04-01",Ayt=120,FP=30,xyt=5,AK=1<<20,$P=2e3,Iyt=new Set(["error","error_description","error_uri"]),Pn=class extends st{constructor(e,t=null,r=null,n=null){super(e),this.statusCode=t,this.body=r,this.requestId=n}}}});function Of(){return Math.floor(Date.now()/1e3)}var UP=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/time.mjs"(){}}),Ryt,kMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs"(){M_(),UP(),Ryt=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){const e=this.nextForce;this.nextForce=!1;const t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;const r=t.expiresAt-Of();return r>Ayt?t.token:r>FP?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||Of()-this.lastAdvisoryError<xyt||this.doRefresh().catch(e=>{this.lastAdvisoryError=Of(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(t=>(this.cached=t,this.pendingRefresh=null,t),t=>{throw this.pendingRefresh=null,t}),this.pendingRefresh}}}}),Sr,BP=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs"(){Sr=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}}});function AMr(e){let t=0;for(const o of e)t+=o.length;const r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function xK(e){let t;return(Pyt??(t=new globalThis.TextEncoder,Pyt=t.encode.bind(t)))(e)}function Myt(e){let t;return(Dyt??(t=new globalThis.TextDecoder,Dyt=t.decode.bind(t)))(e)}var Pyt,Dyt,IK=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs"(){}}),xMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs"(){So(),IK()}});function P_(){}function zP(e,t,r){return!t||D_[e]>D_[r]?P_:t[e].bind(t)}function bo(e){const t=e.logger,r=e.logLevel??"off";if(!t)return Oyt;const n=MK.get(t);if(n&&n[0]===r)return n[1];const o={error:zP("error",t,r),warn:zP("warn",t,r),info:zP("info",t,r),debug:zP("debug",t,r)};return MK.set(t,[r,o]),o}var D_,RK,Oyt,MK,Od,pp=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs"(){Pd(),D_={off:0,error:200,warn:300,info:400,debug:500},RK=(e,t,r)=>{if(e){if(mMr(D_,e))return e;bo(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(D_))}`)}},Oyt={error:P_,warn:P_,info:P_,debug:P_},MK=new WeakMap,Od=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="api-key"||t.toLowerCase()==="x-api-key"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e)}}),Nyt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils.mjs"(){Pd(),xMr(),BP(),pp(),oK(),x_(),Tyt()}});function Lyt(e){if(!e)throw new Error("profile name is empty");if(e==="."||e==="..")throw new Error(`profile name "${e}" is not allowed`);if(e.includes("/")||e.includes("\\"))throw new Error(`profile name "${e}" must not contain path separators`);if(!Fyt.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var PK,Fyt,$yt,Uyt,qP,Byt,DK,zyt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/credentials.mjs"(){TK(),Nyt(),PK="1.0",Fyt=/^[A-Za-z0-9_.-]+$/,$yt=async e=>{var t,r;const n=await qP();if(n===null)return null;const o=e??await DK();if(o===null)return null;Lyt(o);const s=await Promise.resolve().then(()=>(Zn(),gd)),a=(await Promise.resolve().then(()=>(Ht(),Wm))).join(n,"configs",`${o}.json`);let c;try{c=await s.promises.readFile(a,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${a}: ${d}`);c=null}if(c===null){const d=Sr("ANTHROPIC_ORGANIZATION_ID"),m=Sr("ANTHROPIC_IDENTITY_TOKEN_FILE"),h=Sr("ANTHROPIC_FEDERATION_RULE_ID");return h&&d?{fromFile:!1,config:{organization_id:d,workspace_id:Sr("ANTHROPIC_WORKSPACE_ID"),base_url:Sr("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:h,service_account_id:Sr("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:m?{source:"file",path:m}:void 0,scope:Sr("ANTHROPIC_SCOPE")}}}:null}let l;try{l=JSON.parse(c)}catch(d){throw new Error(`failed to parse config file ${a}: ${d}`)}if(!l.authentication)throw new Error(`config file ${a} is missing "authentication"`);const u=l.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw new Error(`authentication.type "${u}" is not a known authentication type`);if(l.organization_id??(l.organization_id=Sr("ANTHROPIC_ORGANIZATION_ID")),l.workspace_id??(l.workspace_id=Sr("ANTHROPIC_WORKSPACE_ID")),l.base_url??(l.base_url=Sr("ANTHROPIC_BASE_URL")),(t=l.authentication).scope??(t.scope=Sr("ANTHROPIC_SCOPE")),l.authentication.type==="oidc_federation"){if(!l.authentication.identity_token){const d=Sr("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(l.authentication.identity_token={source:"file",path:d})}l.authentication.federation_rule_id||(l.authentication.federation_rule_id=Sr("ANTHROPIC_FEDERATION_RULE_ID")??""),(r=l.authentication).service_account_id??(r.service_account_id=Sr("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:l,fromFile:!0}},Uyt=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const r=await qP();if(!r)return null;const n=t??await DK();return n?(Lyt(n),(await Promise.resolve().then(()=>(Ht(),Wm))).join(r,"credentials",`${n}.json`)):null},qP=async()=>{if(!Byt())return null;const e=await Promise.resolve().then(()=>(Ht(),Wm)),t=Sr("ANTHROPIC_CONFIG_DIR");if(t)return t;if(DP()["X-Stainless-OS"]==="Windows"){const s=Sr("APPDATA");if(s)return e.join(s,"Anthropic");const i=Sr("USERPROFILE");return i?e.join(i,"AppData","Roaming","Anthropic"):null}const n=Sr("XDG_CONFIG_HOME");if(n)return e.join(n,"anthropic");const o=Sr("HOME");return o?e.join(o,".config","anthropic"):null},Byt=()=>{const e=DP()["X-Stainless-Runtime"];return e==="node"||e==="deno"},DK=async()=>{const e=await qP();if(!e)return null;const t=Sr("ANTHROPIC_PROFILE");if(t)return t;const r=await Promise.resolve().then(()=>(Zn(),gd)),o=(await Promise.resolve().then(()=>(Ht(),Wm))).join(e,"active_config");try{return(await r.promises.readFile(o,"utf-8")).trim()||"default"}catch(s){if(s?.code!=="ENOENT")throw new Error(`failed to read ${o}: ${s}`);return"default"}}}});function qyt(e){if(!e)throw new st("Identity token file path is empty");return async()=>{const t=await Promise.resolve().then(()=>(Zn(),gd));let r;try{r=await t.promises.readFile(e,"utf-8")}catch(o){throw new st(`Failed to read identity token file at ${e}: ${o}`)}const n=r.trim();if(!n)throw new st(`Identity token file at ${e} is empty`);return n}}function IMr(e){if(!e)throw new st("Identity token value is empty");return()=>e}var RMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs"(){So()}});function MMr(e){return async()=>{wyt(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16*1024)throw new Pn(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const r={grant_type:_yt,assertion:t,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(r.service_account_id=e.serviceAccountId),e.workspaceId&&(r.workspace_id=e.workspaceId);const n=`${e.baseURL}${kK}`;let o;try{o=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${R_},${kyt}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${Dd} oidcFederationProvider`},body:JSON.stringify(r)})}catch(c){throw new Pn(`Failed to reach token endpoint ${n}: ${c}`)}const s=o.headers.get("Request-Id");if(!o.ok){const c=await o.text().catch(()=>""),l=Fc(c);let u="";throw o.status===401&&(u=` Ensure your federation rule matches your identity token. ${e.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new Pn(`Token exchange failed with status ${o.status}${s?` (request-id ${s})`:""}: ${l}${u}`,o.status,l,s)}const i=await Eyt(o,s),a=Number(i.expires_in);if(!Number.isFinite(a))throw new Pn(`Token endpoint response missing required fields: ${JSON.stringify(Fc(i))}`,o.status,Fc(i),s);return{token:i.access_token,expiresAt:Of()+a}}}var PMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs"(){M_(),UP(),PP()}});function DMr(e){return async t=>{const r=await Promise.resolve().then(()=>(Zn(),gd));await Syt(e.credentialsPath,e.onSafetyWarning);let n;try{n=await r.promises.readFile(e.credentialsPath,"utf-8")}catch(y){throw new Pn(`Credentials file not found at ${e.credentialsPath}: ${y}`)}let o;try{o=JSON.parse(n)}catch(y){throw new Pn(`Credentials file at ${e.credentialsPath} is not valid JSON: ${y}`)}const s=o.access_token;if(!s)throw new Pn(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const i=o.expires_at;if(!t?.forceRefresh&&(i==null||Of()<i-FP))return{token:s,expiresAt:i??null};const a=o.refresh_token;if(!e.clientId||!a)throw new Pn(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);wyt(e.baseURL);const c={grant_type:Cyt,refresh_token:a,client_id:e.clientId},l=`${e.baseURL}${kK}`;let u;try{u=await e.fetch(l,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":R_,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${Dd} userOAuthProvider`},body:JSON.stringify(c)})}catch(y){throw new Pn(`User OAuth refresh failed to reach token endpoint: ${y}`)}const d=u.headers.get("Request-Id");if(!u.ok){const y=await u.text().catch(()=>"");throw new Pn(`User OAuth refresh failed (HTTP ${u.status}): ${Fc(y)}`,u.status,Fc(y),d)}const m=await Eyt(u,d),h=Number(m.expires_in);if(!Number.isFinite(h))throw new Pn(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(Fc(m))}`,u.status,Fc(m),d);const f=Of()+h,g=m.refresh_token||a;return await byt(e.credentialsPath,{...o,version:PK,type:"oauth_token",access_token:m.access_token,expires_at:f,refresh_token:g}),{token:m.access_token,expiresAt:f}}}var OMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs"(){zyt(),M_(),UP(),PP()}});function Gyt(e,t){const r=e.authentication.credentials_path??null,n=(e.base_url||t.baseURL).replace(/\/+$/,""),o=LMr(e,r,n,t),s={};return e.workspace_id&&e.authentication.type==="user_oauth"&&(s["anthropic-workspace-id"]=e.workspace_id),{provider:o,extraHeaders:s,baseURL:e.base_url||void 0}}async function NMr(e,t){const r=await $yt(t);if(!r)return null;const{config:n,fromFile:o}=r,s=n.authentication.credentials_path||!o?n:{...n,authentication:{...n.authentication,credentials_path:await Uyt(n,t)??void 0}};return Gyt(s,e)}function LMr(e,t,r,n){switch(e.authentication.type){case"oidc_federation":{const o=e.authentication,s=FMr(o);if(!s)throw new Pn("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!o.federation_rule_id)throw new Pn("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!e.organization_id)throw new Pn("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const i=MMr({identityTokenProvider:s,federationRuleId:o.federation_rule_id,organizationId:e.organization_id,serviceAccountId:o.service_account_id,workspaceId:e.workspace_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent});return t?$Mr(i,t,n.onCacheWriteError,n.onSafetyWarning):i}case"user_oauth":{if(!t)throw new Pn("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return DMr({credentialsPath:t,clientId:e.authentication.client_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent,onSafetyWarning:n.onSafetyWarning})}default:{const o=e.authentication.type;throw new Pn(`authentication.type "${o}" is not a known authentication type`)}}}function FMr(e){if(e.identity_token){const n=e.identity_token.source;if(n!=="file")throw new Pn(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new Pn('identity_token.source "file" requires a non-empty path');return qyt(e.identity_token.path)}const t=Sr("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return qyt(t);const r=Sr("ANTHROPIC_IDENTITY_TOKEN");return r?IMr(r):null}function $Mr(e,t,r,n){return async o=>{const s=await Promise.resolve().then(()=>(Zn(),gd));await Syt(t,n);let i;try{const c=await s.promises.readFile(t,"utf-8");i=JSON.parse(c);const l=i?.access_token;if(l&&!o?.forceRefresh){const u=i?.expires_at;if(u==null||Of()<u-FP)return{token:l,expiresAt:u??null}}}catch(c){c?.code!=="ENOENT"&&!(c instanceof SyntaxError)&&r?.(c)}const a=await e(o);try{await byt(t,{...i??{},version:PK,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(c){r?.(c)}return a}}var UMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs"(){BP(),zyt(),M_(),UP(),RMr(),PMr(),OMr()}});function BMr(e,t){for(let o=t??0;o<e.length;o++){if(e[o]===10)return{preceding:o,index:o+1,carriage:!1};if(e[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function zMr(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var oc,sc,tv,jyt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"(){nc(),IK(),tv=class{constructor(){oc.set(this,void 0),sc.set(this,void 0),Ne(this,oc,new Uint8Array,"f"),Ne(this,sc,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?xK(e):e;Ne(this,oc,AMr([H(this,oc,"f"),t]),"f");const r=[];let n;for(;(n=BMr(H(this,oc,"f"),H(this,sc,"f")))!=null;){if(n.carriage&&H(this,sc,"f")==null){Ne(this,sc,n.index,"f");continue}if(H(this,sc,"f")!=null&&(n.index!==H(this,sc,"f")+1||n.carriage)){r.push(Myt(H(this,oc,"f").subarray(0,H(this,sc,"f")-1))),Ne(this,oc,H(this,oc,"f").subarray(H(this,sc,"f")),"f"),Ne(this,sc,null,"f");continue}const o=H(this,sc,"f")!==null?n.preceding-1:n.preceding,s=Myt(H(this,oc,"f").subarray(0,o));r.push(s),Ne(this,oc,H(this,oc,"f").subarray(n.index),"f"),Ne(this,sc,null,"f")}return r}flush(){return H(this,oc,"f").length?this.decode(`
1020
+ `,r:"\r",t:" "}}}),oMr=b({"node_modules/.pnpm/jsonrepair@3.14.0/node_modules/jsonrepair/lib/esm/index.js"(){nMr()}});function zgt(e,t=0){for(let r=t;r<e.length;r++){const n=e[r];if(n!=="{"&&n!=="[")continue;const o=n==="{"?"}":"]";let s=0,i=!1,a=!1;for(let c=r;c<e.length;c++){const l=e[c];if(a){a=!1;continue}if(l==="\\"){a=!0;continue}if(l==='"'){i=!i;continue}if(!i){if(l===n)s++;else if(l===o&&(s--,s===0))return{span:e.substring(r,c+1),end:c+1}}}}return null}var sMr=b({"src/lib/utils/json/extract.ts"(){"use strict"}});function qgt(e){return typeof e.safeParse=="function"}function eK(e,t){return!e||!qgt(e)?!0:e.safeParse(t).success}function iMr(e,t){try{const r=JSON.parse(e);return r===""?{kind:"empty"}:r==null?{kind:"nullish"}:eK(t,r)?{kind:"accepted",value:r}:{kind:"rejected",value:r}}catch{return{kind:"not-json"}}}function Ggt(e){try{return{value:JSON.parse(e),repaired:!1}}catch{}try{const t=tMr(e),r=JSON.parse(t);return t!==e&&p.shouldLog("debug")&&p.debug("[coerceJsonToSchema] jsonrepair altered model output",{originalLength:e.length,repairedLength:t.length}),{value:r,repaired:t!==e}}catch{return}}function aMr(e){let t=e;for(let r=0;r<Vgt&&t.length>1;r++){const n=Math.max(t.lastIndexOf(","),t.lastIndexOf("}"),t.lastIndexOf("]"));if(n<=0)break;t=t.slice(0,n);const o=Ggt(t);if(o!==void 0&&o.value!==null&&typeof o.value=="object")return o.value}}function tK(e,t=0){if(t>Hgt)return{value:e,changed:!1};if(typeof e=="string"){const r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{const o=JSON.parse(r);if(o!==null&&typeof o=="object")return{value:o,changed:!0}}catch{}return{value:e,changed:!1}}if(Array.isArray(e)){let r=!1;const n=e.map(o=>{const s=tK(o,t+1);return s.changed&&(r=!0),s.value});return{value:r?n:e,changed:r}}if(e!==null&&typeof e=="object"){let r=!1;const n={};for(const[o,s]of Object.entries(e)){const i=tK(s,t+1);i.changed&&(r=!0),n[o]=i.value}return{value:r?n:e,changed:r}}return{value:e,changed:!1}}function jgt(e,t){if(typeof e!="string"||e.trim().length===0)return null;const r=[],n=[e.indexOf("{"),e.indexOf("[")].filter(v=>v>=0),o=n.length>0?Math.min(...n):-1;let s=!1,i=0;for(;;){const v=zgt(e,i);if(!v)break;const w=v.end-v.span.length;w===o&&(s=!0),r.push({text:v.span,truncated:!1,rootAligned:w===o}),i=v.end}const a=o>=0&&!s,c=Math.max(e.lastIndexOf("}"),e.lastIndexOf("]"));o>=0&&c>o&&r.push({text:e.slice(o,c+1),truncated:a,rootAligned:!0}),o>=0&&r.push({text:e.slice(o),truncated:!0,rootAligned:!0});const l=e.trim();if(l.length>1&&l.startsWith('"')&&l.endsWith('"'))try{const v=JSON.parse(l);if(typeof v=="string"){let w=0;for(;;){const S=zgt(v,w);if(!S)break;r.push({text:S.span,truncated:!1,rootAligned:!1}),w=S.end}}}catch{}const u=[...r.filter(v=>v.rootAligned),...r.filter(v=>!v.rootAligned)];let d;const m=[],h=!!(t&&qgt(t)),f=new Set;for(const v of u){if(f.has(v.text))continue;f.add(v.text);const w=Ggt(v.text);if(w===void 0||w.value===null||typeof w.value!="object")continue;const S={value:w.value,repaired:w.repaired,truncated:v.truncated,rootAligned:v.rootAligned};if(d===void 0&&(d=S),!h)break;const _=t;if(_.safeParse(w.value).success)m.push(S);else{const C=tK(w.value);C.changed&&C.value!==null&&typeof C.value=="object"&&_.safeParse(C.value).success?m.push({value:C.value,repaired:!0,truncated:v.truncated,rootAligned:v.rootAligned}):Array.isArray(w.value)&&w.value.length===1&&w.value[0]!==null&&typeof w.value[0]=="object"&&!Array.isArray(w.value[0])&&_.safeParse(w.value[0]).success&&m.push({value:w.value[0],repaired:!0,truncated:v.truncated,rootAligned:v.rootAligned})}}const g=m.length>0?m.reduce((v,w)=>JSON.stringify(w.value).length>JSON.stringify(v.value).length?w:v):void 0;let y=g??d;if(a&&g===void 0&&(y===void 0||!y.rootAligned)){const v=aMr(e.slice(o));v!==void 0?(p.debug("[coerceJsonToSchema] salvaged a partial truncated object",{textLength:e.length}),y={value:v,repaired:!0,truncated:!0,rootAligned:!0}):y!==void 0&&(y={...y,truncated:!0})}return y===void 0?null:{content:JSON.stringify(y.value),structuredData:y.value,repaired:y.repaired,truncated:y.truncated}}var Hgt,Vgt,Wgt=b({"src/lib/utils/json/coerce.ts"(){"use strict";oMr(),B(),sMr(),Hgt=6,Vgt=8}});function RP(e,t,r){return!r||!t||Object.keys(t).length===0?"none":e.toolChoice??"auto"}function cMr(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){const t=e;if(t.type==="tool")return t.toolName?{type:"tool",toolName:t.toolName}:void 0;if(t.type)return t.type}}var Kgt=b({"src/lib/utils/toolChoice.ts"(){"use strict"}});async function*lMr(e,t){const r=e.getReader();let n=!1;try{for(;;){const o=await r.read();if(o.done){n=!0;return}const s=o.value;if(s.type==="text-delta")yield{content:s.delta};else if(s.type==="reasoning-delta")yield{content:"",reasoning:s.delta};else if(s.type==="finish")t(s);else if(s.type==="error")throw s.error}}finally{try{n||await r.cancel()}finally{r.releaseLock()}}}var MP,rK,C_,Jgt,Aa,rc=b({"src/lib/providers/openaiChatCompletionsBase.ts"(){"use strict";Yt(),Sl(),q1r(),is(),j1r(),pgt(),hgt(),ec(),Do(),ggt(),Mn(),B(),Ut(),Dm(),c9(),ga(),vgt(),qh(),WW(),jm(),di(),Wgt(),Kgt(),Ic(),nd(),tW(),wb(),dp(),W0(),MP=512,rK=class extends Error{},C_=(e,t)=>{const r=jgt(e,t);return r!==null&&eK(t,r.structuredData)},Jgt=(e,t,r)=>{const n=e[Symbol.asyncIterator]();return new ReadableStream({async pull(o){try{const s=await n.next();s.done?(o.enqueue(await t),o.close()):s.value.reasoning?o.enqueue({type:"reasoning-delta",delta:s.value.reasoning}):o.enqueue({type:"text-delta",delta:s.value.content})}catch(s){o.error(s)}},async cancel(){r(),await n.return?.()}})},Aa=class extends _a{config;resolvedModel;constructor(e,t,r,n){super(t,e,r),this.config=n}getFallbackModelName(){return"gpt-3.5-turbo"}getModelFallbacks(){return this.getFallbackModels()}refreshHandlersForModel(e){this.resolvedModel=e,super.refreshHandlersForModel(e)}getFallbackModels(){return[]}adjustBuildBodyOptions(e,t){return t}adjustResponseFormat(e,t){return e}suppressResponseFormatWithTools(){return!0}useStreamingWireForGenerate(){return!1}adjustRequestBody(e,t){return e}adjustBodyAfter400(e,t){}resolveWireMaxTokens(e,t,r,n){const o=P7(this.providerName,e);let s=t;o!==void 0&&(s===void 0||s>o)&&(s!==void 0&&p.debug(`${this.providerName}: clamping max_tokens ${s} to the advertised ${e} output ceiling ${o}`),s=o);const i=M7(this.providerName,e);if(i!==void 0){const a=CW(r,n,this.providerName),c=i-a-MP;if(c<=0)throw new ka(`Estimated input (${a} tokens) alone exceeds the ${this.providerName}/${e} context window advertised by the serving infrastructure (${i} tokens). Reduce the prompt/conversation size \u2014 no max_tokens value can make this request fit.`,{estimatedTokens:a,availableTokens:Math.max(0,i-MP),stagesUsed:[],breakdown:{}});s!==void 0&&s>c&&(p.warn(`${this.providerName}: max_tokens ${s} cannot fit the ${e} window (${i}) with ~${a} input tokens \u2014 re-fitting to ${c}`),s=c)}return s}correctBodyAfterContextOverflow(e,t){if(!BW(t))return;const r=zW(t)??zW(t.responseBody);if(!r||r.budgetTokens<=0)return;R7(this.providerName,e.model,r.budgetTokens);const n=typeof e.max_tokens=="number"?e.max_tokens:r.requestedOutputTokens;if(n===void 0||r.actualTokens<=0)return;const o=r.budgetTokens-r.actualTokens-MP;if(!(o<=0||o>=n))return p.warn(`${this.providerName}: ${e.model} rejected the request as over-window \u2014 retrying once with max_tokens re-fit from the provider's own numbers`,{window:r.budgetTokens,inputTokens:r.actualTokens,previousMaxTokens:n,refitMaxTokens:o}),{...e,max_tokens:o}}onStreamStart(e){}shouldAutoDiscoverModel(){return!0}getChatCompletionsURL(e){return`${Ca(this.config.baseURL)}/chat/completions`}getAuthHeaders(){return{Authorization:`Bearer ${this.config.apiKey}`}}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}async probeModelsEndpoint(e={}){try{const t=`${Ca(this.config.baseURL)}/models`,n=await Rt()(t,{headers:{...e,"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)});return n.ok?!!(await n.json().catch(()=>null))?.data?.some(s=>typeof s?.id=="string"&&s.id.trim().length>0):!1}catch(t){return p.debug(`[${this.constructor.name}] probeModelsEndpoint failed`,{baseURL:yo(this.config.baseURL),error:t instanceof Error?t.message:String(t)}),!1}}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}async getAISDKModel(){const e=await this.resolveModelName();return this.buildDelegatingModel(e)}async resolveModelName(){if(this.resolvedModel)return this.resolvedModel;const e=this.modelName||this.getDefaultModel();if(e&&e.trim()!=="")return this.resolvedModel=e,this.modelName!==e&&this.refreshHandlersForModel(e),e;if(this.shouldAutoDiscoverModel()){try{const r=await this.getAvailableModels();if(r.length>0)return this.resolvedModel=r[0],this.refreshHandlersForModel(r[0]),p.info(`\u{1F50D} Auto-discovered model: ${r[0]} from ${r.length} available models`),r[0]}catch(r){p.warn("Model auto-discovery failed, using fallback:",r)}return this.getFallbackModelName()}const t=this.getFallbackModelName();return this.resolvedModel=t,this.refreshHandlersForModel(t),t}buildDelegatingModel(e){const t=this.getChatCompletionsURL(e),r=Rt(),n=this.getAuthHeaders.bind(this),o=this.providerName,s=this.adjustBuildBodyOptions.bind(this),i=this.adjustResponseFormat.bind(this),a=this.adjustRequestBody.bind(this),c=this.adjustBodyAfter400.bind(this),l=this.correctBodyAfterContextOverflow.bind(this),u=this.resolveWireMaxTokens.bind(this),d=this.suppressResponseFormatWithTools.bind(this),m=this.useStreamingWireForGenerate.bind(this),h=f=>this.getTimeout(f??{});return{specificationVersion:"v3",provider:o,modelId:e,supportedUrls:{},doGenerate:async f=>{const g=CP((f.tools??[]).filter(V=>V.type==="function").map(V=>V.name)),y=xW(f.prompt,g?.toWire),v=Array.isArray(f.tools)&&f.tools.length>0,w=f.responseFormat&&!(v&&d())?i(igt(f.responseFormat),e):void 0,S=rgt(f.tools,g?.toWire),_=u(e,f.maxOutputTokens,y,S),C=m(),k=PW(a(DW({modelId:e,messages:y,options:s(e,{maxTokens:_,temperature:f.temperature,topP:f.topP,presencePenalty:f.presencePenalty,frequencyPenalty:f.frequencyPenalty,seed:f.seed,stopSequences:f.stopSequences}),tools:S,...f.toolChoice?{toolChoice:ngt(f.toolChoice,g?.toWire)}:{},streaming:C,...w?{responseFormat:w}:{}}),e)),A=f.providerOptions?.neurolink?.timeoutMs,I=fa(typeof A=="number"?A:h(f),o,"generate"),{signal:R,dispose:M}=gB(f.abortSignal,I?.controller.signal);let D,U=C;try{let V=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(k),...R?{signal:R}:{}});if(!V.ok){const q=await E_(t,k,V),G=q;let J=V.status===400?(()=>{const re=l(k,G);return c(re??k,G)??re})():void 0;if(!J&&C&&V.status===400&&/stream/i.test(G.responseBody??"")){const{stream:re,stream_options:pe,...ne}=k;J=ne,U=!1}if(!J)throw q;if(V=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(J),...R?{signal:R}:{}}),!V.ok)throw await E_(t,J,V)}if(U){if(!V.body)throw new Error(`${o}: streaming generate response had no body`);const q=I?V.body.pipeThrough(new TransformStream({transform(J,re){I.reset(),re.enqueue(J)}})):V.body,G=await OW(q,()=>{});D={...G.id?{id:G.id}:{},...G.model?{model:G.model}:{},choices:[{index:0,message:{role:"assistant",content:G.text.length>0?G.text:null,...G.reasoning?{reasoning:G.reasoning}:{},...G.toolCalls.size>0?{tool_calls:[...G.toolCalls.values()].map(J=>({id:J.id,type:"function",function:{name:J.name,arguments:J.argsBuffered}}))}:{}},finish_reason:G.finishReason??"stop"}],...G.usage?{usage:G.usage}:{}}}else D=await V.json()}finally{I?.cleanup(),M()}const P=D.choices?.[0],$=(typeof P?.message?.content=="string"?P.message.content:"")??"",N=[],F=P?.message?.reasoning_content||P?.message?.reasoning;typeof F=="string"&&F.length>0&&N.push({type:"reasoning",text:F}),$.length>0&&N.push({type:"text",text:$});for(const V of P?.message?.tool_calls??[])N.push({type:"tool-call",toolCallId:V.id,toolName:g?.fromWire.get(V.function.name)??V.function.name,input:V.function.arguments??""});const j=P?.finish_reason;return{content:N,finishReason:{unified:j==="length"?"length":j==="tool_calls"||j==="function_call"?"tool-calls":j==="content_filter"?"content-filter":"stop",raw:j??"stop"},usage:{inputTokens:{total:D.usage?.prompt_tokens,noCache:D.usage?.prompt_tokens!==void 0&&D.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.max(0,D.usage.prompt_tokens-D.usage.prompt_tokens_details.cached_tokens):D.usage?.prompt_tokens,cacheRead:D.usage?.prompt_tokens!==void 0&&D.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.min(D.usage.prompt_tokens_details.cached_tokens,D.usage.prompt_tokens):D.usage?.prompt_tokens_details?.cached_tokens,cacheWrite:void 0},outputTokens:{total:D.usage?.completion_tokens,text:D.usage?.completion_tokens!==void 0&&D.usage?.completion_tokens_details?.reasoning_tokens!==void 0?Math.max(0,D.usage.completion_tokens-D.usage.completion_tokens_details.reasoning_tokens):D.usage?.completion_tokens,reasoning:D.usage?.completion_tokens_details?.reasoning_tokens}},warnings:[],request:{body:k},response:{...D.id?{id:D.id}:{},...D.model?{modelId:D.model}:{},headers:{},body:D}}},doStream:()=>{throw new Error(`${o}: 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.`)}}}async generate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if(pd(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=await this.resolveModelName(),n=await this.getAISDKModelWithMiddleware(e);if(!AP(n))throw this.handleProviderError(new Error(`${this.providerName}: model handle exposes no doGenerate()`));const o=n.doGenerate.bind(n),s=!e.disableTools&&this.supportsTools(),i=s?e.tools||await this.getAllTools():{},a=s?Object.entries(i).map(([I,R])=>{const M=R;return{type:"function",name:I,description:M.description??"",inputSchema:M.inputSchema?No(M.inputSchema):{type:"object",properties:{}}}}):void 0,c=!!a&&a.length>0,l=e.schema?No(e.schema):void 0,u=l!==void 0&&c&&this.suppressResponseFormatWithTools(),d=l&&!u?{type:"json",schema:l}:void 0,m=await this.buildMessagesForStream(e),h=[],f=(I,R,M=!0)=>HW({doGenerate:o,...G1r({provider:this.providerName,availableInputTokens:El(this.providerName,r,e.maxTokens??void 0),getFixedOverheadTokens:()=>Zt(UV({...M&&a?{tools:a}:{},responseFormat:R}),this.providerName)}),conversation:I,...M&&a?{tools:a}:{},toolsRecord:i,...M&&c&&e.toolChoice?{toolChoice:RP(e,i,!0)}:{},...typeof e.timeout=="number"?{providerOptions:{neurolink:{timeoutMs:e.timeout}}}:{},...R?{responseFormat:R}:{},maxSteps:e.maxSteps||zs,...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:D=>Vy(D,lt.getActiveSpan()??void 0,`${this.providerName} generate`).catch(U=>{throw this.handleProviderError(U)})},h);let g;try{g=await f(m,d)}catch(I){if(!(d!==void 0&&(YRr(I)||sft(I))))throw I;p.warn(`[${this.providerName}] provider rejected response_format \u2014 retrying with the schema in the system prompt`,{provider:this.providerName,model:r}),g=await f(b_(m,d.schema),void 0)}if(d!==void 0&&e.schema!==void 0&&!C_(g.text,e.schema)){p.warn(`[${this.providerName}] response_format did not yield a schema-valid object \u2014 retrying with the schema in the system prompt`,{provider:this.providerName,model:r});const I=g,R=await f(b_(m,d.schema),void 0);g={...R,inputTokens:I.inputTokens+R.inputTokens,outputTokens:I.outputTokens+R.outputTokens,cacheReadTokens:(I.cacheReadTokens??0)+(R.cacheReadTokens??0),cacheWriteTokens:(I.cacheWriteTokens??0)+(R.cacheWriteTokens??0)}}u&&l&&e.schema&&(g=await this.reformatWithoutTools({toolPhase:g,conversation:m,schemaJson:l,schema:e.schema,runLoop:f,modelId:r,abortSignal:e.abortSignal}));const{text:y,finishReason:v,toolsUsed:w}=g,S=g.inputTokens,_=g.outputTokens,C=g.steps,k=C>=(e.maxSteps||zs)&&v==="tool-calls"?"step-cap":v==="error"?"provider-error":"completed",A={content:y,provider:this.providerName,model:r,finishReason:v,...g.rawFinishReason?{rawFinishReason:g.rawFinishReason}:{},stopReason:k,stepsUsed:C,usage:{input:S,output:_,total:S+_+g.cacheReadTokens+g.cacheWriteTokens,...g.cacheReadTokens?{cacheReadTokens:g.cacheReadTokens}:{},...g.cacheWriteTokens?{cacheCreationTokens:g.cacheWriteTokens}:{}},responseTime:Date.now()-t,...g.reasoning?{reasoning:g.reasoning}:{},toolsUsed:w,toolCalls:jj(h),toolExecutions:Wh(e,fd(h)),enhancedWithTools:w.length>0};return this.finalizeNativeGenerate(A,e,t)}async reformatWithoutTools(e){const{toolPhase:t,conversation:r,schemaJson:n,schema:o,runLoop:s,modelId:i,abortSignal:a}=e;let c=t;const l=()=>a?.aborted===!0;if(c.text.trim().length>0&&!l()&&!C_(c.text,o)){p.warn(`[${this.providerName}] tools suppressed response_format and the answer is not schema-valid \u2014 re-asking once without tools`,{provider:this.providerName,model:i});const u={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},d=m=>{u.inputTokens+=m.inputTokens,u.outputTokens+=m.outputTokens,u.cacheReadTokens+=m.cacheReadTokens??0,u.cacheWriteTokens+=m.cacheWriteTokens??0};try{const m=[...r,{role:"assistant",content:t.text},{role:"user",content:"Return that same answer as a single JSON value conforming to the required schema. No prose before or after it, and no markdown code fence."}];let h,f=!1;try{h=await s(m,{type:"json",schema:n},!1),d(h)}catch(g){if(l())throw g;p.warn(`[${this.providerName}] the re-ask's response_format was rejected \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:i,error:g instanceof Error?g.message:String(g)}),h=await s(b_(m,n),void 0,!1),d(h),f=!0}if(!f&&!l()&&!C_(h.text,o)&&(p.warn(`[${this.providerName}] the re-ask's response_format carried no schema \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:i}),h=await s(b_(m,n),void 0,!1),d(h)),!C_(h.text,o))throw p.warn(`[${this.providerName}] the tool-free re-ask did not yield a schema-valid object either; keeping the original answer`,{provider:this.providerName,model:i}),new rK;c={...h,toolsUsed:[...new Set([...t.toolsUsed,...h.toolsUsed])],inputTokens:t.inputTokens+u.inputTokens,outputTokens:t.outputTokens+u.outputTokens,cacheReadTokens:(t.cacheReadTokens??0)+u.cacheReadTokens,cacheWriteTokens:(t.cacheWriteTokens??0)+u.cacheWriteTokens,steps:t.steps,...t.finishReason!=="stop"?{finishReason:t.finishReason,rawFinishReason:t.rawFinishReason}:{finishReason:h.finishReason}}}catch(m){if(l()&&!(a?.reason instanceof ja))throw m;m instanceof rK||p.warn(`[${this.providerName}] the tool-free structured-output re-ask failed; keeping the original answer`,{provider:this.providerName,model:i,error:m instanceof Error?m.message:String(m)}),c={...c,inputTokens:c.inputTokens+u.inputTokens,outputTokens:c.outputTokens+u.outputTokens,cacheReadTokens:(c.cacheReadTokens??0)+u.cacheReadTokens,cacheWriteTokens:(c.cacheWriteTokens??0)+u.cacheWriteTokens}}}return c}async executeStream(e,t){this.validateStreamOptions(e);const r=Date.now(),n=this.getTimeout(e),o=fa(n,this.providerName,"stream"),s=new AbortController,i=hge([e.abortSignal,o?.controller.signal,s.signal]).signal;let a,c,l,u,d,m;try{a=await this.resolveModelName();const q=!e.disableTools&&this.supportsTools();c=q?e.tools||await this.getAllTools():{},l=q?CP(Object.keys(c)):void 0,u=q?IW(c,l?.toWire):void 0,d=agt(RP(e,c,q),l?.toWire),m=await this.buildMessagesForStream(e)}catch(q){throw o?.cleanup(),q}const h=this.getChatCompletionsURL(a),f=Rt(),g=e.maxSteps||zs,y=this.neurolink?.getEventEmitter(),v=[],w=[],{usagePromise:S,finishPromise:_,resolveUsage:C,resolveFinish:k}=NW(),A=V0(),I=this.onStreamStart(a),R=u?.map(q=>({type:"function",name:q.function.name,description:q.function.description,inputSchema:q.function.parameters})),M={prompt:m,...R?{tools:R}:{},...e.maxTokens!==void 0?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.topP!==void 0?{topP:e.topP}:{}};let D;const U=this.providerName,P={specificationVersion:"v3",provider:U,modelId:a,supportedUrls:{},doGenerate:async q=>{const G=await this.getAISDKModel();if(typeof G=="string")throw new Error("Native model handle required");return G.doGenerate(q)},doStream:async q=>{q?.tools!==void 0&&q.tools!==R&&p.warn(`${U}: middleware rewrote 'tools' on the streaming path; tool rewrites are not applied to the wire request yet \u2014 the original tool list was sent.`);const G=Array.isArray(q?.prompt)?q.prompt:m,J=xW(G,l?.toWire),re={...e,...typeof q?.maxOutputTokens=="number"?{maxTokens:q.maxOutputTokens}:{},...typeof q?.temperature=="number"?{temperature:q.temperature}:{},...typeof q?.topP=="number"?{topP:q.topP}:{}};D=this.runStreamLoop({maxSteps:g,modelId:a,url:h,fetchImpl:f,abortSignal:i,options:re,conversation:J,openAITools:u,openAIToolChoice:d,toolsRecord:c,toolNameFromWire:l?.fromWire,emitter:y,toolsUsed:v,toolExecutionSummaries:w,pushChunk:A.push,closeChannel:A.close,resolveUsage:C,resolveFinish:k});const pe=D.then(()=>Promise.all([S,_]).then(([ne,ie])=>({type:"finish",finishReason:{unified:ie},usage:{inputTokens:{total:ne.promptTokens,cacheRead:ne.cacheReadTokens},outputTokens:{total:ne.completionTokens}}})));return pe.catch(()=>{}),{stream:Jgt(A.iterable,pe,()=>s.abort())}}};let $;try{const q=await this.applyMiddlewareToModel(P,e);if(typeof q=="string")throw new Error("Native stream model handle required");const{stream:G}=await q.doStream(M);$=lMr(G,J=>{if(!D){const re=J.usage.inputTokens.total??0,pe=J.usage.outputTokens.total??0,ne=Math.min(J.usage.inputTokens.cacheRead??0,re);C({promptTokens:re-ne,completionTokens:pe,totalTokens:re+pe,...ne>0?{cacheReadTokens:ne}:{}}),k(J.finishReason.unified)}})}catch(q){throw s.abort(),A.close(),o?.cleanup(),q}let N;const F=q=>{N=q};I?.onUsage&&S.then(I.onUsage).catch(()=>{}),I?.onFinish&&_.then(q=>I.onFinish?.(q,N)).catch(()=>{});const j=this.providerName,V={stream:async function*(){let q=0;try{for await(const G of $)"content"in G&&typeof G.content=="string"&&G.content.length>0&&q++,yield G;if(await D,q===0&&v.length===0){p.warn(`${j}: Stream produced no output \u2014 emitting enriched sentinel`);const G=new ou({message:"Stream produced no output"}),J=await gf(G,void 0,N);yf(J),yield J}}catch(G){if(ou.isInstance(G)){const re=await gf(G,void 0,N);yf(re),yield re;return}const J=await gf(G,void 0,N);throw yf(J),yield J,G}finally{D||(C({promptTokens:0,completionTokens:0,totalTokens:0}),k("stop")),o?.cleanup(),s.signal.aborted||s.abort()}}(),provider:this.providerName,model:a,analytics:jW.createAnalytics(this.providerName,a,{textStream:(async function*(){})(),usage:S,finishReason:_},Date.now()-r,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),toolsUsed:v,metadata:{startTime:r,streamId:`${this.providerName}-${Date.now()}`}};return Object.defineProperty(V,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>fd(w.map(q=>({toolName:q.toolName,input:q.input,output:q.output,duration:q.endTime.getTime()-q.startTime.getTime()})))}),D?.finally(()=>o?.cleanup()).catch(q=>{F(q)}),V}async runStreamLoop(e){const{maxSteps:t,modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:c,openAIToolChoice:l,toolsRecord:u,toolNameFromWire:d,emitter:m,toolsUsed:h,toolExecutionSummaries:f,pushChunk:g,closeChannel:y,resolveUsage:v,resolveFinish:w}=e;let S=null,_;const C=()=>{const k=_?.prompt_tokens??0,A=_?.completion_tokens??0,I=Math.min(_?.prompt_tokens_details?.cached_tokens??0,k),R=Math.min(Math.max(0,_?.completion_tokens_details?.reasoning_tokens??0),A);return{promptTokens:k-I,completionTokens:A,totalTokens:_?.total_tokens||k+A,...I>0?{cacheReadTokens:I}:{},...R>0?{reasoningTokens:R}:{}}};try{let k=d,A,I;for(let R=0;R<t;R++){if(c){const U=new Set(c.map($=>k?.get($.function.name)??$.function.name)),P=Object.fromEntries(Object.entries(u).filter(([$])=>!U.has($)));if(Object.keys(P).length>0){const $=CP(Object.keys(P),new Set(c.map(N=>N.function.name)));if($){k??=new Map;for(const[N,F]of $.fromWire)k.set(N,F)}c.push(...IW(P,$?.toWire)??[]),p.info(`${this.providerName}: ${Object.keys(P).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(P).join(", ")}`)}}const M=z1r({conversation:a,availableInputTokens:El(this.providerName,r,i.maxTokens??void 0),fixedOverheadTokens:CW([],c,this.providerName),provider:this.providerName,observedPromptTokens:A,previousSentEstimate:I,onSentEstimate:U=>{I=U}});M&&(a.length=0,a.push(...M));const D=await this.streamOneStep({modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:c,openAIToolChoice:l,pushChunk:g});if(A=D.usage?.prompt_tokens,S=D.finishReason,D.usage&&(_=ugt(_,D.usage)),D.toolCalls.size===0)break;await this.executeToolBatch({stepResult:D,conversation:a,toolsRecord:u,toolNameFromWire:k,emitter:m,toolsUsed:h,toolExecutionSummaries:f,options:i})}return v(C()),w(S??"stop"),y(),{finishReason:S??"stop",usage:_}}catch(k){throw p.error(`${this.providerName}: Stream error`,{error:k instanceof Error?k.message:String(k)}),v(C()),w("error"),y(),k}}async streamOneStep(e){const t=this.resolveWireMaxTokens(e.modelId,e.options.maxTokens??void 0,e.conversation,e.openAITools),r=t!==e.options.maxTokens?{...e.options,maxTokens:t}:e.options,n=PW(this.adjustRequestBody(DW({modelId:e.modelId,messages:e.conversation,options:this.adjustBuildBodyOptions(e.modelId,r),tools:e.openAITools,...e.openAIToolChoice!==void 0?{toolChoice:e.openAIToolChoice}:{},streaming:!0}),e.modelId)),o=async()=>{const i=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(n),...e.abortSignal?{signal:e.abortSignal}:{}});if(!i.ok)throw await E_(e.url,n,i);return i};let s;try{s=await Vy(o,lt.getActiveSpan()??void 0,`${this.providerName} stream`)}catch(i){const a=i,c=a.statusCode===400?(()=>{const l=this.correctBodyAfterContextOverflow(n,a);return this.adjustBodyAfter400(l??n,a)??l})():void 0;if(!c)throw a;if(s=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(c),...e.abortSignal?{signal:e.abortSignal}:{}}),!s.ok)throw await E_(e.url,c,s)}if(!s.body)throw new Error(`${this.providerName}: stream response had no body`);return OW(s.body,i=>{e.pushChunk({content:i})},i=>{e.pushChunk({content:"",reasoning:i})})}async executeToolBatch(e){const{stepResult:t,conversation:r,toolsRecord:n,toolNameFromWire:o,emitter:s,toolsUsed:i,toolExecutionSummaries:a,options:c}=e,l=[];for(const[,d]of t.toolCalls)l.push({id:d.id,type:"function",function:{name:d.name,arguments:d.argsBuffered}});r.push({role:"assistant",content:t.text.length>0?t.text:null,tool_calls:l});for(const[,d]of t.toolCalls){const m=new Date;let h;try{h=JSON.parse(d.argsBuffered||"{}")}catch{h=d.argsBuffered}let f,g;const y=o?.get(d.name)??d.name,v=n[y]??iH(n,y);if(s?.emit("tool:start",{toolName:y,toolCallId:d.id,input:h}),!v||typeof v.execute!="function")g=`Tool '${y}' is not registered.`,f={error:g};else try{f=await v.execute(h,{})}catch(S){g=S instanceof Error?S.message:String(S),f={error:g}}const w=new Date;i.push(y),a.push({toolCallId:d.id,toolName:y,input:h,output:f,...g?{error:g}:{},startTime:m,endTime:w}),r.push({role:"tool",tool_call_id:d.id,content:kW(f)})}const u=a.slice(-t.toolCalls.size);ygt(s,u.map(d=>({toolName:d.toolName,output:d.output,...d.error?{error:d.error}:{}})));try{await this.handleToolExecutionStorage(u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,output:d.output})),u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,output:d.output})),c,new Date)}catch(d){p.warn(`[${this.constructor.name}] Failed to store tool executions`,{provider:this.providerName,error:d instanceof Error?d.message:String(d)})}}async getAvailableModels(){try{const e=`${Ca(this.config.baseURL)}/models`;p.debug(`Fetching available models from: ${e}`);const t=Rt(),r=new AbortController,n=setTimeout(()=>r.abort(),5e3),o=await t(e,{headers:{...this.getAuthHeaders(),"Content-Type":"application/json"},signal:r.signal});if(clearTimeout(n),!o.ok)return p.warn(`Models endpoint returned ${o.status}: ${o.statusText}`),this.getFallbackModels();const s=await o.json();if(!s.data||!Array.isArray(s.data))return p.warn("Invalid models response format"),this.getFallbackModels();const i=s.data.map(a=>a.id).filter(Boolean);return p.shouldLog("debug")&&p.debug(`Discovered ${i.length} models:`,i),i.length>0?i:this.getFallbackModels()}catch(e){return p.warn(`[${this.constructor.name}] Failed to fetch models from endpoint:`,e),this.getFallbackModels()}}async getFirstAvailableModel(){return(await this.getAvailableModels())[0]||this.getFallbackModelName()}}}}),nK,Ygt,Xgt,Zgt,Qgt,eyt,uMr=b({"src/lib/providers/openAI/client.ts"(){"use strict";Yt(),Mn(),ct(),B(),Ut(),Ya(),ci(),qo(),tc(),If(),ga(),dp(),rc(),nd(),nK="https://api.openai.com/v1",Ygt=(e,t)=>{const r=[e,t].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??nK;try{const n=new URL(r),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",Ca(n.toString())}catch{}return r},Xgt=()=>Ai(Yhr()),Zgt=()=>li("OPENAI_MODEL","gpt-4o"),Qgt=lt.getTracer("neurolink.provider.openai"),eyt=class extends Aa{constructor(e,t,r,n){const o=n?.apiKey?.trim(),s=o&&o.length>0?o:Xgt(),i=Ygt(n?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:i,apiKey:s}),p.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:yo(this.config.baseURL)})}suppressResponseFormatWithTools(){return!1}getProviderName(){return"openai"}getDefaultModel(){return Zgt()}formatProviderError(e){const t=e,r=t?.type&&typeof t.type=="string"?t.type:void 0,n=[{match:o=>o.statusCode===401||r==="invalid_api_key"||/API_KEY_INVALID|Invalid API key|Incorrect API key|invalid_api_key/i.test(o.message),errorClass:kr,message:o=>/Incorrect API key|Invalid API key/i.test(o.message)?o.message:"Invalid OpenAI API key. Please check your OPENAI_API_KEY environment variable."},{match:o=>wge(o.error),errorClass:Xe,message:"OpenAI quota exhausted \u2014 this will not resolve by retrying. Check your plan and billing details at https://platform.openai.com/account/billing"},{match:o=>o.statusCode===429||r==="rate_limit_error"||/rate limit/i.test(o.message),errorClass:vs,message:"OpenAI rate limit exceeded. Please try again later."},{match:o=>/model_not_found/i.test(o.message),errorClass:go,message:o=>`Model not found: ${o.modelName}`},...ya];return ki(e,n,this.providerName,this.modelName)}onStreamStart(e){const t=Qgt.startSpan("neurolink.provider.streamText",{kind:zr.CLIENT,attributes:{"gen_ai.system":"openai","gen_ai.request.model":e}});let r=!1;const n=()=>{r||(r=!0,t.end())};return{onUsage:o=>{t.setAttribute("gen_ai.usage.input_tokens",o.promptTokens+(o.cacheReadTokens??0)+(o.cacheCreationTokens??0)),t.setAttribute("gen_ai.usage.output_tokens",o.completionTokens);const s=Ri(this.providerName,e,{input:o.promptTokens,output:o.completionTokens,total:o.totalTokens,...o.cacheReadTokens?{cacheReadTokens:o.cacheReadTokens}:{},...o.cacheCreationTokens?{cacheCreationTokens:o.cacheCreationTokens}:{}});s&&s>0&&t.setAttribute("neurolink.cost",s)},onFinish:(o,s)=>{t.setAttribute("gen_ai.response.finish_reason",o||"unknown"),o==="error"&&t.setStatus({code:Fe.ERROR,message:s instanceof Error?s.message:String(s??"stream error")}),n()}}}getDefaultEmbeddingModel(){return process.env.OPENAI_EMBEDDING_MODEL||"text-embedding-3-small"}async embed(e,t){if(typeof e!="string"&&e.image)throw new Xe(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||this.getDefaultEmbeddingModel();p.debug("Generating embedding",{provider:this.providerName,model:n,textLength:r.length});try{const[o]=await this.callEmbeddings(n,[r],"embed");return p.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:o.length}),o}catch(o){throw p.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:r.length}),this.handleProviderError(o)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel();p.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=await this.callEmbeddings(r,e,"embedMany");return p.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:n.length,embeddingDimension:n[0]?.length}),n}catch(n){throw p.error("Batch embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,count:e.length}),this.handleProviderError(n)}}async callEmbeddings(e,t,r){const n=`${Ca(this.config.baseURL)}/embeddings`,o=Rt(),s=fa(3e4,this.providerName,"generate");try{const i=await o(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...s?.controller.signal?{signal:s.controller.signal}:{}});if(!i.ok){const l=await i.text().catch(()=>"");let u=`OpenAI ${r} failed with status ${i.status}`,d;if(l)try{const m=JSON.parse(l);m.error?.message&&(u=m.error.message),d=m.error?.type}catch{}throw Object.assign(new Error(u),{status:i.status,type:d})}const c=((await i.json()).data??[]).map(l=>l.embedding).filter(l=>Array.isArray(l));if(c.length===0)throw new Xe(`OpenAI ${r} returned no embeddings`,this.providerName);return c}finally{s?.cleanup()}}async executeImageGeneration(e){const t=Date.now(),r=e.prompt??e.input?.text??"";if(!r.trim())throw new Error("OpenAI image generation requires a prompt (input.text or prompt)");const n=e.model??this.modelName,o=Ca(this.config.baseURL??nK),s=e,i=s.size??this.aspectRatioToOpenAISize(s.aspectRatio,n),a=s.numberOfImages??1;let c;n==="gpt-image-1"||n.startsWith("dall-e-3")?c=1:n.startsWith("dall-e-2")?c=Math.min(Math.max(a,1),10):c=1;const u={model:n,prompt:r,n:c,size:i};n==="gpt-image-1"?s.quality&&(u.quality=s.quality):n.startsWith("dall-e-3")?(u.response_format="b64_json",s.quality&&(u.quality=s.quality),s.style&&(u.style=s.style)):u.response_format="b64_json";const d=12e4,m=new AbortController,h=setTimeout(()=>m.abort(),d);let f;try{f=await Rt()(`${o}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:m.signal})}catch(S){throw S instanceof Error&&S.name==="AbortError"?new Error(`OpenAI image generation timed out after ${d/1e3}s`,{cause:S}):S}finally{clearTimeout(h)}if(!f.ok){const S=await f.text();throw new Error(`OpenAI image generation failed: ${f.status} \u2014 ${S}`)}const y=(await f.json()).data?.[0];if(!y)throw new Error("OpenAI image generation returned no images");let v=y.b64_json;if(!v&&y.url){await xf(y.url);const S=Rt(),_=new AbortController,C=setTimeout(()=>_.abort(),6e4);let k;try{k=await S(y.url,{signal:_.signal})}catch(I){throw I instanceof Error&&I.name==="AbortError"?new Error("OpenAI image URL download timed out after 60s",{cause:I}):I}finally{clearTimeout(C)}if(!k.ok)throw new Error(`OpenAI image generation: failed to fetch hosted URL ${y.url} (${k.status})`);v=(await Rd(k,Af,"OpenAI image fallback")).toString("base64")}if(!v)throw new Error("OpenAI image generation returned neither b64_json nor a URL");const w=Date.now()-t;return p.info(`[OpenAIProvider] Generated image (${v.length} base64 chars) in ${w}ms \u2014 model ${n}`),{content:y.revised_prompt??r,provider:this.providerName,model:n,usage:{input:0,output:0,total:0},imageOutput:{base64:v}}}aspectRatioToOpenAISize(e,t){return t==="gpt-image-1"?e==="16:9"||e==="3:2"?"1536x1024":e==="9:16"||e==="2:3"?"1024x1536":"1024x1024":t.startsWith("dall-e-3")?e==="16:9"||e==="3:2"?"1792x1024":e==="9:16"||e==="2:3"?"1024x1792":"1024x1024":"1024x1024"}}}}),tyt={};se(tyt,{OpenAIProvider:()=>eyt});var dMr=b({"src/lib/providers/openAI/index.ts"(){"use strict";uMr()}});function Ne(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r}function H(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var nc=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/tslib.mjs"(){}}),k_,oK=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs"(){k_=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return k_=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}}});function Z0(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var A_,Q0=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/errors.mjs"(){A_=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)}}}),st,Oi,Lc,ev,sK,ryt,iK,aK,cK,lK,uK,dK,mK,pK,So=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/error.mjs"(){Q0(),st=class extends Error{},Oi=class Ace extends st{constructor(t,r,n,o,s){super(`${Ace.makeMessage(t,r,n)}`),this.status=t,this.headers=o,this.requestID=o?.get("request-id"),this.error=r,this.type=s??null}static makeMessage(t,r,n){const o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,r,n,o){if(!t||!o)return new ev({message:n,cause:A_(r)});const s=r,i=s?.error?.type;return t===400?new iK(t,s,n,o,i):t===401?new aK(t,s,n,o,i):t===403?new cK(t,s,n,o,i):t===404?new lK(t,s,n,o,i):t===409?new uK(t,s,n,o,i):t===422?new dK(t,s,n,o,i):t===429?new mK(t,s,n,o,i):t>=500?new pK(t,s,n,o,i):new Ace(t,s,n,o,i)}},Lc=class extends Oi{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ev=class extends Oi{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},sK=class extends ev{constructor({message:e}={}){super({message:e??"Request timed out."})}},ryt=class extends st{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},iK=class extends Oi{},aK=class extends Oi{},cK=class extends Oi{},lK=class extends Oi{},uK=class extends Oi{},dK=class extends Oi{},mK=class extends Oi{},pK=class extends Oi{}}});function hK(e){return typeof e!="object"?{}:e??{}}function nyt(e){if(!e)return!0;for(const t in e)return!1;return!0}function mMr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var oyt,syt,Qi,fK,iyt,gK,Pd=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs"(){So(),oyt=/^[a-z][a-z0-9+.-]*:/i,syt=e=>oyt.test(e),Qi=e=>(Qi=Array.isArray,Qi(e)),fK=Qi,iyt=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new st(`${e} must be an integer`);if(t<0)throw new st(`${e} must be a positive integer`);return t},gK=e=>{try{return JSON.parse(e)}catch{return}}}}),mp,x_=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"(){mp=(e,t)=>new Promise(r=>{if(t?.aborted)return r();const n=()=>{clearTimeout(o),r()},o=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}}),Dd,PP=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/version.mjs"(){Dd="0.102.0"}});function pMr(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function hMr(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:r}of e){const n=r.exec(navigator.userAgent);if(n){const o=n[1]||0,s=n[2]||0,i=n[3]||0;return{browser:t,version:`${o}.${s}.${i}`}}}return null}var ayt,cyt,yK,vK,lyt,DP,TK=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs"(){PP(),ayt=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",cyt=()=>{const e=pMr();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dd,"X-Stainless-OS":vK(Deno.build.os),"X-Stainless-Arch":yK(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dd,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dd,"X-Stainless-OS":vK(globalThis.process.platform??"unknown"),"X-Stainless-Arch":yK(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=hMr();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dd,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dd,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},yK=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",vK=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),DP=()=>lyt??(lyt=cyt())}});function fMr(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function uyt(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function dyt(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return uyt({start(){},async pull(r){const{done:n,value:o}=await t.next();n?r.close():r.enqueue(o)},async cancel(){await t.return?.()}})}function wK(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){const r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function gMr(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}const t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var I_=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/shims.mjs"(){}}),myt,yMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/request-options.mjs"(){myt=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)})}}),EK,SK,bK,pyt,hyt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs"(){EK="RFC3986",SK=e=>String(e),bK={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:SK},pyt="RFC1738"}});function vMr(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function fyt(e,t){if(Qi(e)){const r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}var OP,Cl,NP,gyt,TMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs"(){hyt(),Pd(),OP=(e,t)=>(OP=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),OP(e,t)),Cl=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),NP=1024,gyt=(e,t,r,n,o)=>{if(e.length===0)return e;let s=e;if(typeof e=="symbol"?s=Symbol.prototype.toString.call(e):typeof e!="string"&&(s=String(e)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=NP){const c=s.length>=NP?s.slice(a,a+NP):s,l=[];for(let u=0;u<c.length;++u){let d=c.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===pyt&&(d===40||d===41)){l[l.length]=c.charAt(u);continue}if(d<128){l[l.length]=Cl[d];continue}if(d<2048){l[l.length]=Cl[192|d>>6]+Cl[128|d&63];continue}if(d<55296||d>=57344){l[l.length]=Cl[224|d>>12]+Cl[128|d>>6&63]+Cl[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=Cl[240|d>>18]+Cl[128|d>>12&63]+Cl[128|d>>6&63]+Cl[128|d&63]}i+=l.join("")}return i}}});function wMr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}function yyt(e,t,r,n,o,s,i,a,c,l,u,d,m,h,f,g,y,v){let w=e,S=v,_=0,C=!1;for(;(S=S.get(LP))!==void 0&&!C;){const M=S.get(e);if(_+=1,typeof M<"u"){if(M===_)throw new RangeError("Cyclic object value");C=!0}typeof S.get(LP)>"u"&&(_=0)}if(typeof l=="function"?w=l(t,w):w instanceof Date?w=m?.(w):r==="comma"&&Qi(w)&&(w=fyt(w,function(M){return M instanceof Date?m?.(M):M})),w===null){if(s)return c&&!g?c(t,cs.encoder,y,"key",h):t;w=""}if(wMr(w)||vMr(w)){if(c){const M=g?t:c(t,cs.encoder,y,"key",h);return[f?.(M)+"="+f?.(c(w,cs.encoder,y,"value",h))]}return[f?.(t)+"="+f?.(String(w))]}const k=[];if(typeof w>"u")return k;let A;if(r==="comma"&&Qi(w))g&&c&&(w=fyt(w,c)),A=[{value:w.length>0?w.join(",")||null:void 0}];else if(Qi(l))A=l;else{const M=Object.keys(w);A=u?M.sort(u):M}const I=a?String(t).replace(/\./g,"%2E"):String(t),R=n&&Qi(w)&&w.length===1?I+"[]":I;if(o&&Qi(w)&&w.length===0)return R+"[]";for(let M=0;M<A.length;++M){const D=A[M],U=typeof D=="object"&&typeof D.value<"u"?D.value:w[D];if(i&&U===null)continue;const P=d&&a?D.replace(/\./g,"%2E"):D,$=Qi(w)?typeof r=="function"?r(R,P):R:R+(d?"."+P:"["+P+"]");v.set(e,_);const N=new WeakMap;N.set(LP,v),CK(k,yyt(U,$,r,n,o,s,i,a,r==="comma"&&g&&Qi(w)?null:c,l,u,d,m,h,f,g,y,N))}return k}function EMr(e=cs){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");const t=e.charset||cs.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=EK;if(typeof e.format<"u"){if(!OP(bK,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const n=bK[r];let o=cs.filter;(typeof e.filter=="function"||Qi(e.filter))&&(o=e.filter);let s;if(e.arrayFormat&&e.arrayFormat in _K?s=e.arrayFormat:"indices"in e?s=e.indices?"indices":"repeat":s=cs.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:cs.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:cs.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:cs.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:cs.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?cs.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:cs.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:cs.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:cs.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:cs.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:cs.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:cs.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:cs.strictNullHandling}}function SMr(e,t={}){let r=e;const n=EMr(t);let o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):Qi(n.filter)&&(s=n.filter,o=s);const i=[];if(typeof r!="object"||r===null)return"";const a=_K[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);const l=new WeakMap;for(let m=0;m<o.length;++m){const h=o[m];n.skipNulls&&r[h]===null||CK(i,yyt(r[h],h,a,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}const u=i.join(n.delimiter);let d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}var _K,CK,vyt,cs,LP,bMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs"(){TMr(),hyt(),Pd(),_K={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},CK=function(e,t){Array.prototype.push.apply(e,Qi(t)?t:[t])},cs={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:gyt,encodeValuesOnly:!1,format:EK,formatter:SK,indices:!1,serializeDate(e){return(vyt??(vyt=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},LP={}}});function _Mr(e){return SMr(e,{arrayFormat:"brackets"})}var Tyt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs"(){bMr()}});function wyt(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new Pn(`Invalid token endpoint base URL "${e}": ${n}`)}if(t.protocol==="https:")return;const r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(t.protocol==="http:"&&(r==="localhost"||r==="127.0.0.1"||r==="::1")))throw new Pn(`Refusing to send credential over non-https token endpoint "${e}"`)}async function Eyt(e,t){const r=await CMr(e);let n;try{n=JSON.parse(r)}catch{throw new Pn(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,Fc(r),t)}if(!n.access_token)throw new Pn(`Token endpoint response missing access_token: ${JSON.stringify(Fc(n))}`,e.status,Fc(n),t);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new Pn(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,Fc(n),t);return n}function Fc(e){if(e==null)return e;if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{return e.length<=$P?e:e.slice(0,$P)+`... <${e.length-$P} more chars>`}return JSON.stringify(Fc(t))}if(typeof e=="object"&&!Array.isArray(e)){const t={};for(const[r,n]of Object.entries(e))Iyt.has(r)&&(t[r]=n);return t}return null}async function Syt(e,t=r=>console.warn(`anthropic-sdk: ${r}`)){if(typeof process>"u"||process.platform==="win32")return;const r=await Promise.resolve().then(()=>(Zn(),gd));let n=e,o;try{n=await r.promises.realpath(e),o=await r.promises.stat(n)}catch{return}const s=o.mode&511;if(s&18)throw new Pn(`Credentials file at ${n} is group/world-writable (mode 0o${s.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${n}\`.`);if(s&36)throw new Pn(`Credentials file at ${n} is group/world-readable (mode 0o${s.toString(8)}); run \`chmod 600 ${n}\` before retrying.`);typeof process.getuid=="function"&&o.uid!==process.getuid()&&t(`credentials file at ${n} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function byt(e,t){const r=await Promise.resolve().then(()=>(Zn(),gd)),o=(await Promise.resolve().then(()=>(Ht(),Wm))).dirname(e);await r.promises.mkdir(o,{recursive:!0,mode:448});const s=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const i=await r.promises.open(s,"w",384);try{await i.writeFile(JSON.stringify(t,null,2)),await i.sync()}finally{await i.close()}await r.promises.rename(s,e)}catch(i){throw await r.promises.unlink(s).catch(()=>{}),i}try{const i=await r.promises.open(o,"r");try{await i.sync()}finally{await i.close()}}catch{}}async function CMr(e){if(!e.body)return"";const t=e.body.getReader(),r=[];let n=0;for(;;){const{done:s,value:i}=await t.read();if(s)break;if(n+i.length>AK){const a=AK-n;a>0&&r.push(i.subarray(0,a)),await t.cancel();break}r.push(i),n+=i.length}let o;if(r.length===1)o=r[0];else{o=new Uint8Array(r.reduce((i,a)=>i+a.length,0));let s=0;for(const i of r)o.set(i,s),s+=i.length}return new TextDecoder("utf-8").decode(o)}var _yt,Cyt,kK,R_,kyt,Ayt,FP,xyt,AK,$P,Iyt,Pn,M_=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs"(){So(),_yt="urn:ietf:params:oauth:grant-type:jwt-bearer",Cyt="refresh_token",kK="/v1/oauth/token",R_="oauth-2025-04-20",kyt="oidc-federation-2026-04-01",Ayt=120,FP=30,xyt=5,AK=1<<20,$P=2e3,Iyt=new Set(["error","error_description","error_uri"]),Pn=class extends st{constructor(e,t=null,r=null,n=null){super(e),this.statusCode=t,this.body=r,this.requestId=n}}}});function Of(){return Math.floor(Date.now()/1e3)}var UP=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/time.mjs"(){}}),Ryt,kMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs"(){M_(),UP(),Ryt=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){const e=this.nextForce;this.nextForce=!1;const t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;const r=t.expiresAt-Of();return r>Ayt?t.token:r>FP?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||Of()-this.lastAdvisoryError<xyt||this.doRefresh().catch(e=>{this.lastAdvisoryError=Of(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(t=>(this.cached=t,this.pendingRefresh=null,t),t=>{throw this.pendingRefresh=null,t}),this.pendingRefresh}}}}),Sr,BP=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs"(){Sr=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}}});function AMr(e){let t=0;for(const o of e)t+=o.length;const r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function xK(e){let t;return(Pyt??(t=new globalThis.TextEncoder,Pyt=t.encode.bind(t)))(e)}function Myt(e){let t;return(Dyt??(t=new globalThis.TextDecoder,Dyt=t.decode.bind(t)))(e)}var Pyt,Dyt,IK=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs"(){}}),xMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs"(){So(),IK()}});function P_(){}function zP(e,t,r){return!t||D_[e]>D_[r]?P_:t[e].bind(t)}function bo(e){const t=e.logger,r=e.logLevel??"off";if(!t)return Oyt;const n=MK.get(t);if(n&&n[0]===r)return n[1];const o={error:zP("error",t,r),warn:zP("warn",t,r),info:zP("info",t,r),debug:zP("debug",t,r)};return MK.set(t,[r,o]),o}var D_,RK,Oyt,MK,Od,pp=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs"(){Pd(),D_={off:0,error:200,warn:300,info:400,debug:500},RK=(e,t,r)=>{if(e){if(mMr(D_,e))return e;bo(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(D_))}`)}},Oyt={error:P_,warn:P_,info:P_,debug:P_},MK=new WeakMap,Od=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="api-key"||t.toLowerCase()==="x-api-key"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e)}}),Nyt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils.mjs"(){Pd(),xMr(),BP(),pp(),oK(),x_(),Tyt()}});function Lyt(e){if(!e)throw new Error("profile name is empty");if(e==="."||e==="..")throw new Error(`profile name "${e}" is not allowed`);if(e.includes("/")||e.includes("\\"))throw new Error(`profile name "${e}" must not contain path separators`);if(!Fyt.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var PK,Fyt,$yt,Uyt,qP,Byt,DK,zyt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/credentials.mjs"(){TK(),Nyt(),PK="1.0",Fyt=/^[A-Za-z0-9_.-]+$/,$yt=async e=>{var t,r;const n=await qP();if(n===null)return null;const o=e??await DK();if(o===null)return null;Lyt(o);const s=await Promise.resolve().then(()=>(Zn(),gd)),a=(await Promise.resolve().then(()=>(Ht(),Wm))).join(n,"configs",`${o}.json`);let c;try{c=await s.promises.readFile(a,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${a}: ${d}`);c=null}if(c===null){const d=Sr("ANTHROPIC_ORGANIZATION_ID"),m=Sr("ANTHROPIC_IDENTITY_TOKEN_FILE"),h=Sr("ANTHROPIC_FEDERATION_RULE_ID");return h&&d?{fromFile:!1,config:{organization_id:d,workspace_id:Sr("ANTHROPIC_WORKSPACE_ID"),base_url:Sr("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:h,service_account_id:Sr("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:m?{source:"file",path:m}:void 0,scope:Sr("ANTHROPIC_SCOPE")}}}:null}let l;try{l=JSON.parse(c)}catch(d){throw new Error(`failed to parse config file ${a}: ${d}`)}if(!l.authentication)throw new Error(`config file ${a} is missing "authentication"`);const u=l.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw new Error(`authentication.type "${u}" is not a known authentication type`);if(l.organization_id??(l.organization_id=Sr("ANTHROPIC_ORGANIZATION_ID")),l.workspace_id??(l.workspace_id=Sr("ANTHROPIC_WORKSPACE_ID")),l.base_url??(l.base_url=Sr("ANTHROPIC_BASE_URL")),(t=l.authentication).scope??(t.scope=Sr("ANTHROPIC_SCOPE")),l.authentication.type==="oidc_federation"){if(!l.authentication.identity_token){const d=Sr("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(l.authentication.identity_token={source:"file",path:d})}l.authentication.federation_rule_id||(l.authentication.federation_rule_id=Sr("ANTHROPIC_FEDERATION_RULE_ID")??""),(r=l.authentication).service_account_id??(r.service_account_id=Sr("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:l,fromFile:!0}},Uyt=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const r=await qP();if(!r)return null;const n=t??await DK();return n?(Lyt(n),(await Promise.resolve().then(()=>(Ht(),Wm))).join(r,"credentials",`${n}.json`)):null},qP=async()=>{if(!Byt())return null;const e=await Promise.resolve().then(()=>(Ht(),Wm)),t=Sr("ANTHROPIC_CONFIG_DIR");if(t)return t;if(DP()["X-Stainless-OS"]==="Windows"){const s=Sr("APPDATA");if(s)return e.join(s,"Anthropic");const i=Sr("USERPROFILE");return i?e.join(i,"AppData","Roaming","Anthropic"):null}const n=Sr("XDG_CONFIG_HOME");if(n)return e.join(n,"anthropic");const o=Sr("HOME");return o?e.join(o,".config","anthropic"):null},Byt=()=>{const e=DP()["X-Stainless-Runtime"];return e==="node"||e==="deno"},DK=async()=>{const e=await qP();if(!e)return null;const t=Sr("ANTHROPIC_PROFILE");if(t)return t;const r=await Promise.resolve().then(()=>(Zn(),gd)),o=(await Promise.resolve().then(()=>(Ht(),Wm))).join(e,"active_config");try{return(await r.promises.readFile(o,"utf-8")).trim()||"default"}catch(s){if(s?.code!=="ENOENT")throw new Error(`failed to read ${o}: ${s}`);return"default"}}}});function qyt(e){if(!e)throw new st("Identity token file path is empty");return async()=>{const t=await Promise.resolve().then(()=>(Zn(),gd));let r;try{r=await t.promises.readFile(e,"utf-8")}catch(o){throw new st(`Failed to read identity token file at ${e}: ${o}`)}const n=r.trim();if(!n)throw new st(`Identity token file at ${e} is empty`);return n}}function IMr(e){if(!e)throw new st("Identity token value is empty");return()=>e}var RMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs"(){So()}});function MMr(e){return async()=>{wyt(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16*1024)throw new Pn(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const r={grant_type:_yt,assertion:t,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(r.service_account_id=e.serviceAccountId),e.workspaceId&&(r.workspace_id=e.workspaceId);const n=`${e.baseURL}${kK}`;let o;try{o=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${R_},${kyt}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${Dd} oidcFederationProvider`},body:JSON.stringify(r)})}catch(c){throw new Pn(`Failed to reach token endpoint ${n}: ${c}`)}const s=o.headers.get("Request-Id");if(!o.ok){const c=await o.text().catch(()=>""),l=Fc(c);let u="";throw o.status===401&&(u=` Ensure your federation rule matches your identity token. ${e.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new Pn(`Token exchange failed with status ${o.status}${s?` (request-id ${s})`:""}: ${l}${u}`,o.status,l,s)}const i=await Eyt(o,s),a=Number(i.expires_in);if(!Number.isFinite(a))throw new Pn(`Token endpoint response missing required fields: ${JSON.stringify(Fc(i))}`,o.status,Fc(i),s);return{token:i.access_token,expiresAt:Of()+a}}}var PMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs"(){M_(),UP(),PP()}});function DMr(e){return async t=>{const r=await Promise.resolve().then(()=>(Zn(),gd));await Syt(e.credentialsPath,e.onSafetyWarning);let n;try{n=await r.promises.readFile(e.credentialsPath,"utf-8")}catch(y){throw new Pn(`Credentials file not found at ${e.credentialsPath}: ${y}`)}let o;try{o=JSON.parse(n)}catch(y){throw new Pn(`Credentials file at ${e.credentialsPath} is not valid JSON: ${y}`)}const s=o.access_token;if(!s)throw new Pn(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const i=o.expires_at;if(!t?.forceRefresh&&(i==null||Of()<i-FP))return{token:s,expiresAt:i??null};const a=o.refresh_token;if(!e.clientId||!a)throw new Pn(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);wyt(e.baseURL);const c={grant_type:Cyt,refresh_token:a,client_id:e.clientId},l=`${e.baseURL}${kK}`;let u;try{u=await e.fetch(l,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":R_,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${Dd} userOAuthProvider`},body:JSON.stringify(c)})}catch(y){throw new Pn(`User OAuth refresh failed to reach token endpoint: ${y}`)}const d=u.headers.get("Request-Id");if(!u.ok){const y=await u.text().catch(()=>"");throw new Pn(`User OAuth refresh failed (HTTP ${u.status}): ${Fc(y)}`,u.status,Fc(y),d)}const m=await Eyt(u,d),h=Number(m.expires_in);if(!Number.isFinite(h))throw new Pn(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(Fc(m))}`,u.status,Fc(m),d);const f=Of()+h,g=m.refresh_token||a;return await byt(e.credentialsPath,{...o,version:PK,type:"oauth_token",access_token:m.access_token,expires_at:f,refresh_token:g}),{token:m.access_token,expiresAt:f}}}var OMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs"(){zyt(),M_(),UP(),PP()}});function Gyt(e,t){const r=e.authentication.credentials_path??null,n=(e.base_url||t.baseURL).replace(/\/+$/,""),o=LMr(e,r,n,t),s={};return e.workspace_id&&e.authentication.type==="user_oauth"&&(s["anthropic-workspace-id"]=e.workspace_id),{provider:o,extraHeaders:s,baseURL:e.base_url||void 0}}async function NMr(e,t){const r=await $yt(t);if(!r)return null;const{config:n,fromFile:o}=r,s=n.authentication.credentials_path||!o?n:{...n,authentication:{...n.authentication,credentials_path:await Uyt(n,t)??void 0}};return Gyt(s,e)}function LMr(e,t,r,n){switch(e.authentication.type){case"oidc_federation":{const o=e.authentication,s=FMr(o);if(!s)throw new Pn("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!o.federation_rule_id)throw new Pn("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!e.organization_id)throw new Pn("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const i=MMr({identityTokenProvider:s,federationRuleId:o.federation_rule_id,organizationId:e.organization_id,serviceAccountId:o.service_account_id,workspaceId:e.workspace_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent});return t?$Mr(i,t,n.onCacheWriteError,n.onSafetyWarning):i}case"user_oauth":{if(!t)throw new Pn("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return DMr({credentialsPath:t,clientId:e.authentication.client_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent,onSafetyWarning:n.onSafetyWarning})}default:{const o=e.authentication.type;throw new Pn(`authentication.type "${o}" is not a known authentication type`)}}}function FMr(e){if(e.identity_token){const n=e.identity_token.source;if(n!=="file")throw new Pn(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new Pn('identity_token.source "file" requires a non-empty path');return qyt(e.identity_token.path)}const t=Sr("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return qyt(t);const r=Sr("ANTHROPIC_IDENTITY_TOKEN");return r?IMr(r):null}function $Mr(e,t,r,n){return async o=>{const s=await Promise.resolve().then(()=>(Zn(),gd));await Syt(t,n);let i;try{const c=await s.promises.readFile(t,"utf-8");i=JSON.parse(c);const l=i?.access_token;if(l&&!o?.forceRefresh){const u=i?.expires_at;if(u==null||Of()<u-FP)return{token:l,expiresAt:u??null}}}catch(c){c?.code!=="ENOENT"&&!(c instanceof SyntaxError)&&r?.(c)}const a=await e(o);try{await byt(t,{...i??{},version:PK,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(c){r?.(c)}return a}}var UMr=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs"(){BP(),zyt(),M_(),UP(),RMr(),PMr(),OMr()}});function BMr(e,t){for(let o=t??0;o<e.length;o++){if(e[o]===10)return{preceding:o,index:o+1,carriage:!1};if(e[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function zMr(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var oc,sc,tv,jyt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"(){nc(),IK(),tv=class{constructor(){oc.set(this,void 0),sc.set(this,void 0),Ne(this,oc,new Uint8Array,"f"),Ne(this,sc,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?xK(e):e;Ne(this,oc,AMr([H(this,oc,"f"),t]),"f");const r=[];let n;for(;(n=BMr(H(this,oc,"f"),H(this,sc,"f")))!=null;){if(n.carriage&&H(this,sc,"f")==null){Ne(this,sc,n.index,"f");continue}if(H(this,sc,"f")!=null&&(n.index!==H(this,sc,"f")+1||n.carriage)){r.push(Myt(H(this,oc,"f").subarray(0,H(this,sc,"f")-1))),Ne(this,oc,H(this,oc,"f").subarray(H(this,sc,"f")),"f"),Ne(this,sc,null,"f");continue}const o=H(this,sc,"f")!==null?n.preceding-1:n.preceding,s=Myt(H(this,oc,"f").subarray(0,o));r.push(s),Ne(this,oc,H(this,oc,"f").subarray(n.index),"f"),Ne(this,sc,null,"f")}return r}flush(){return H(this,oc,"f").length?this.decode(`
1021
1021
  `):[]}},oc=new WeakMap,sc=new WeakMap,tv.NEWLINE_CHARS=new Set([`
1022
1022
  `,"\r"]),tv.NEWLINE_REGEXP=/\r\n|[\n\r]/g}});async function*qMr(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new st("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new st("Attempted to iterate over a response with no body");const r=new Hyt,n=new tv,o=wK(e.body);for await(const s of GMr(o))for(const i of n.decode(s)){const a=r.decode(i);a&&(yield a)}for(const s of n.flush()){const i=r.decode(s);i&&(yield i)}}async function*GMr(e){let t=new Uint8Array;for await(const r of e){if(r==null)continue;const n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?xK(r):r;let o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let s;for(;(s=zMr(t))!==-1;)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}function jMr(e,t){const r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}var O_,Nf,Hyt,OK=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/streaming.mjs"(){nc(),So(),I_(),jyt(),I_(),Q0(),Pd(),IK(),pp(),So(),Nf=class gx{constructor(t,r,n){this.iterator=t,O_.set(this,void 0),this.controller=r,Ne(this,O_,n,"f")}static fromSSEResponse(t,r,n){let o=!1;const s=n?bo(n):console;async function*i(){if(o)throw new st("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(const c of qMr(t,r)){if(c.event==="completion")try{yield JSON.parse(c.data)}catch(l){throw s.error("Could not parse message into JSON:",c.data),s.error("From chunk:",c.raw),l}if(c.event==="message_start"||c.event==="message_delta"||c.event==="message_stop"||c.event==="content_block_start"||c.event==="content_block_delta"||c.event==="content_block_stop"||c.event==="message"||c.event==="user.message"||c.event==="user.interrupt"||c.event==="user.tool_confirmation"||c.event==="user.custom_tool_result"||c.event==="user.tool_result"||c.event==="agent.message"||c.event==="agent.thinking"||c.event==="agent.tool_use"||c.event==="agent.tool_result"||c.event==="agent.mcp_tool_use"||c.event==="agent.mcp_tool_result"||c.event==="agent.custom_tool_use"||c.event==="agent.thread_context_compacted"||c.event==="session.status_running"||c.event==="session.status_idle"||c.event==="session.status_rescheduled"||c.event==="session.status_terminated"||c.event==="session.error"||c.event==="session.deleted"||c.event==="session.updated"||c.event==="span.model_request_start"||c.event==="span.model_request_end"||c.event==="span.outcome_evaluation_start"||c.event==="span.outcome_evaluation_ongoing"||c.event==="span.outcome_evaluation_end"||c.event==="user.define_outcome"||c.event==="agent.thread_message_received"||c.event==="agent.thread_message_sent"||c.event==="agent.session_thread_message_received"||c.event==="agent.session_thread_message_sent"||c.event==="session.thread_created"||c.event==="session.thread_status_created"||c.event==="session.thread_status_running"||c.event==="session.thread_status_idle"||c.event==="session.thread_status_rescheduled"||c.event==="session.thread_status_terminated")try{yield JSON.parse(c.data)}catch(l){throw s.error("Could not parse message into JSON:",c.data),s.error("From chunk:",c.raw),l}if(c.event!=="ping"&&c.event==="error"){const l=gK(c.data)??c.data,u=l?.error?.type;throw new Oi(void 0,l,void 0,t.headers,u)}}a=!0}catch(c){if(Z0(c))return;throw c}finally{a||r.abort()}}return new gx(i,r,n)}static fromReadableStream(t,r,n){let o=!1;async function*s(){const a=new tv,c=wK(t);for await(const l of c)for(const u of a.decode(l))yield u;for(const l of a.flush())yield l}async function*i(){if(o)throw new st("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(const c of s())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(Z0(c))return;throw c}finally{a||r.abort()}}return new gx(i,r,n)}[(O_=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],r=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){const i=n.next();t.push(i),r.push(i)}return s.shift()}});return[new gx(()=>o(t),this.controller,H(this,O_,"f")),new gx(()=>o(r),this.controller,H(this,O_,"f"))]}toReadableStream(){const t=this;let r;return uyt({async start(){r=t[Symbol.asyncIterator]()},async pull(n){try{const{value:o,done:s}=await r.next();if(s)return n.close();const i=xK(JSON.stringify(o)+`
1023
1023
  `);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}},Hyt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join(`
@@ -1075,7 +1075,7 @@ ${r[0].text}`;const n=r.length-1;r[n].text=`${r[n].text}
1075
1075
  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 WDr(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 KDr({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,v=0,w=0,S=0,_=0,C=0,k=0,A=0,I=0,R=0,M=!1;for await(const z of l){if(n.aborted)break;const V=z;if(V.type==="message_start"){const q=V.message?.usage;v+=q?.input_tokens??0;const G=q?.output_tokens??0;w+=G-A,A=G;const J=q?.output_tokens_details?.thinking_tokens??0;I+=J-R,R=J,S+=q?.cache_read_input_tokens??0,_+=q?.cache_creation_input_tokens??0,C+=q?.cache_creation?.ephemeral_5m_input_tokens??0,k+=q?.cache_creation?.ephemeral_1h_input_tokens??0,s?.((q?.input_tokens??0)+(q?.cache_read_input_tokens??0)+(q?.cache_creation_input_tokens??0));continue}if(V.type==="content_block_start"){const q=V.index??0;if(V.content_block?.type==="redacted_thinking"){const G=V.content_block.data;typeof G=="string"&&h.set(q,G)}V.content_block?.type==="tool_use"&&d.set(q,{id:V.content_block.id??"",name:V.content_block.name??"",inputJson:""});continue}if(V.type==="content_block_delta"){const q=V.index??0,G=V.delta;if(G?.type==="text_delta"&&G.text)f+=G.text,u.set(q,(u.get(q)??"")+G.text),r.push({content:G.text});else if(G?.type==="thinking_delta"&&G.thinking){const J=m.get(q)??{text:"",signature:""};J.text+=G.thinking,m.set(q,J),g+=G.thinking,r.push({content:"",reasoning:G.thinking})}else if(G?.type==="signature_delta"&&G.signature){const J=m.get(q)??{text:"",signature:""};J.signature+=G.signature,m.set(q,J)}else if(G?.type==="input_json_delta"&&G.partial_json){const J=d.get(q);J&&(J.inputJson+=G.partial_json)}continue}if(V.type==="message_delta"){y=V.delta?.stop_reason??y;const q=V.usage?.output_tokens??A;w+=q-A,A=q;const G=V.usage?.output_tokens_details?.thinking_tokens??R;I+=G-R,R=G;continue}V.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 D=z=>{if(!z)return{};try{const V=JSON.parse(z);return typeof V=="object"&&V!==null&&!Array.isArray(V)?V:{}}catch{return{}}},U=[],P=new Set([...u.keys(),...d.keys(),...m.keys(),...h.keys()]);for(const z of[...P].sort((V,q)=>V-q)){const V=h.get(z);V&&U.push({type:"redacted_thinking",data:V});const q=m.get(z);q?.text&&q.signature&&U.push({type:"thinking",thinking:q.text,signature:q.signature});const G=u.get(z);G&&U.push({type:"text",text:G});const J=d.get(z);J&&U.push({type:"tool_use",id:J.id,name:J.name,input:D(J.inputJson)})}const $=[...d.values()].map(z=>({id:z.id,name:z.name,args:D(z.inputJson)})),N=i?[...d.values()].find(z=>z.name===i):void 0,F=N?[]:$,j=N?VDr(N.inputJson):f;return N&&a?.(j),{text:j,...g?{reasoning:g}:{},toolCalls:F,usage:{inputTokens:v,outputTokens:w,cacheReadTokens:S,cacheWriteTokens:_,...C?{cacheWrite5mTokens:C}:{},...k?{cacheWrite1hTokens:k}:{},...I?{reasoningTokens:I}:{}},rawStopReason:y,raw:U}}function pY(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=iH(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?fa(e.requestTimeoutMs,"anthropic","stream"):null,i=gB(n,s?.controller.signal);try{return await KDr({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}`:mY(i.output),...i.error?{is_error:!0}:{}}))};return[...t,o,s]},mapFinishReason:WDr}}var DSt=b({"src/lib/providers/anthropic/loopAdapter.ts"(){"use strict";wb(),xSt(),PSt(),ga(),tt()}});function hY(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 HD(e,t){if(e instanceof ArrayBuffer)return HD(new Uint8Array(e),t);if(e instanceof Uint8Array)return{type:"image",source:{type:"base64",media_type:VD(t)??hY(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=VD(n[1])??gY(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:VD(t)??gY(r)??"image/png",data:r}}}function JDr(e){const t=e?.data;if(t==null)return;const r=typeof e.mediaType=="string"?e.mediaType.toLowerCase().split(";")[0].trim():"";if(fY.has(r)||r==="image/jpg")return HD(t,r);if(r==="application/pdf")return yY(t);const n=t instanceof ArrayBuffer?new Uint8Array(t):t instanceof Uint8Array?t:void 0;if(n&&hY(n))return HD(n)}var fY,VD,OSt,gY,yY,YDr=b({"src/lib/providers/anthropicImageBlocks.ts"(){"use strict";fY=new Set(["image/jpeg","image/png","image/gif","image/webp"]),VD=e=>{if(!e)return;const t=e.toLowerCase().split(";")[0].trim();return t==="image/jpg"?"image/jpeg":fY.has(t)?t:void 0},OSt=32,gY=e=>{try{return hY(Buffer.from(e.slice(0,OSt),"base64"))}catch{return}},yY=e=>{if(e instanceof ArrayBuffer)return yY(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}}}}}}),WD,NSt=b({"src/lib/providers/anthropic/constants.ts"(){"use strict";WD={"anthropic-beta":["claude-code-20250219","fine-grained-tool-streaming-2025-05-14"].join(",")}}}),vY,bv,LSt,TY,FSt,$St,wY,EY,SY,bY,USt,XDr=b({"src/lib/providers/anthropic/client.ts"(){"use strict";hTt(),Yt(),on(),Di(),hr(),fC(),m$(),ec(),Do(),ggt(),mSt(),xDr(),Mn(),$Dr(),ct(),ci(),B(),W9(),CSt(),Sl(),is(),Ut(),dY(),Ya(),xSt(),DSt(),_d(),vP(),WW(),nd(),qh(),jm(),Ic(),qo(),ga(),bf(),Kgt(),vgt(),Dm(),c9(),di(),N9(),YDr(),id(),dp(),W0(),iW(),NSt(),hft(),PSt(),mSt(),vY=()=>Ai(Jhr()),bv=()=>li("ANTHROPIC_MODEL","claude-sonnet-4-6"),LSt=lt.getTracer("neurolink.provider.anthropic"),TY=()=>{try{const t=At(Pi(),".neurolink","anthropic-credentials.json");if(Ss(t)){const r=lu(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}},FSt=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"},$St=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},wY=e=>{const t=[],r=[],n=i=>Array.isArray(i)?i:[i],o=(i,a)=>{const c=Id(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(`
1076
1076
  `),c=Id(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=Id(l);a.push({type:"text",text:l.text,...u?{cache_control:u}:{}})}else if(l?.type==="image"||l?.type==="image_url"){const u=HD(l.image??l.data??l.url);if(u){const d=Id(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)?JDr(l):void 0;if(d){const m=Id(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=Id(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:mY(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(`
1077
1077
 
1078
- `);return{...s!==void 0?{system:s}:{},messages:r}},EY=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}}}},SY=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},bY=6e5,USt=class extends _a{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??TY(),i=o?"api_key":r?.authMethod??$St(s),a=r?.subscriptionTier??(i==="oauth"?FSt(s):"api"),c=e||bv();let l=c;!process.env.ANTHROPIC_BASE_URL&&a!=="api"&&!oY(c,a)&&(l=sY(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=ADr(()=>h.accessToken,this.enableBetaFeatures,!1,!0);m=new Gf({apiKey:"oauth-authenticated",fetch:ySt(f),timeout:bY,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??vY(),f=(()=>{const g=process.env.ANTHROPIC_BASE_URL;if(!g)return;const y=g.replace(/\/+$/,""),v=y.replace(/\/v\d+$/,"");return v!==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:yo(g),rewrittenTo:yo(v)}),v})();m=new Gf({apiKey:h,defaultHeaders:d,...f&&{baseURL:f},fetch:ySt(Rt()),timeout:bY,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?WD["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=[...hC,"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"]=WD["anthropic-beta"];return t&&(e["User-Agent"]=jf),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=oY(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 iY(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+wle;if(!t&&!r){p.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new kr("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(pC,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":jf},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:rY}),signal:i.signal});if(clearTimeout(a),!c.ok){const d=await c.text();throw new kr(`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=At(Pi(),".neurolink");Ss(d)||mz(d,{recursive:!0});const m=At(d,"anthropic-credentials.json"),h=`${m}.tmp`,g={...Ss(m)?JSON.parse(lu(m,"utf-8")):{},type:"oauth",oauth:u,updatedAt:Date.now()};ZR(h,JSON.stringify(g,null,2),{mode:384}),hz(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 kr?s:new kr(`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 bv()}getAISDKModel(){const e=this.client,t=this.providerName,r=this.modelName||bv(),n=i=>this.getTimeout(i??{}),o=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:r,supportedUrls:{},doGenerate:async i=>{await o();const a=wY(i.prompt),c=a.messages;let l=a.system,u=(i.tools??[]).filter(j=>j.type==="function").map(j=>{const z=Id(j);return{name:j.name,...j.description?{description:j.description}:{},input_schema:j.inputSchema??{type:"object",properties:{}},...z?{cache_control:z}:{}}});u&&u.length===0&&(u=void 0);const d=cMr(i.toolChoice);let m=d?EY(d):void 0,h;if(i.responseFormat?.type==="json"){h=i.responseFormat.name??"json";const j=i.responseFormat.schema??{type:"object"};u=[{name:h,description:i.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:j}],m={type:"tool",name:h}}const f=i.providerOptions?.anthropic?.finalResultSchema;let g=!1;if(!h&&f){const j=ISt(u,f);u=j.tools,g=j.applied,j.applied&&(l=RSt(l))}const y=i.providerOptions?.anthropic?.thinking;u=sW(u);const v=uY({system:l,tools:u,messages:c}),w=kSt(c,GD-v),S=ml("anthropic",r,{...i.temperature!==void 0&&i.temperature!==null?{temperature:i.temperature}:{},...i.topP!==void 0&&i.topP!==null?{topP:i.topP}:{}},"anthropic.doGenerate");y&&(S.temperature!==void 0||S.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:oP(r,i.maxOutputTokens),...l?{system:l}:{},...!y&&S.temperature!==void 0?{temperature:S.temperature}:{},...!y&&S.topP!==void 0?{top_p:S.topP}:{},...i.stopSequences&&i.stopSequences.length>0?{stop_sequences:i.stopSequences}:{},...u?{tools:u}:{},...m?{tool_choice:m}:{},...y?{thinking:y}:{}},C=i.providerOptions?.neurolink,k=typeof C?.timeoutMs=="number"&&Number.isFinite(C.timeoutMs)&&C.timeoutMs>0?C.timeoutMs:void 0,A=k!==void 0?k:_.max_tokens>8192?Math.max(n(i),3e5):n(i),I=fa(A,t,"generate"),R=FR(i.abortSignal,I?.controller.signal);let M;try{M=await e.messages.create(_,{signal:R})}catch(j){const z=R?.aborted?R.reason:void 0;throw z instanceof ja?z:j}finally{I?.cleanup()}const D=[];let U;const P=[];let $=!1;for(const j of M.content)j.type==="thinking"?D.push({type:"reasoning",text:j.thinking,providerOptions:{anthropic:{signature:j.signature}}}):j.type==="redacted_thinking"?D.push({type:"reasoning",text:"",providerOptions:{anthropic:{redactedData:j.data}}}):j.type==="text"?h?P.push(j.text):D.push({type:"text",text:j.text}):j.type==="tool_use"&&(h&&j.name===h?($=!0,D.push({type:"text",text:w_(j.input)})):g&&j.name===vC?U=w_(j.input):D.push({type:"tool-call",toolCallId:j.id,toolName:j.name,input:w_(j.input)}));if(h&&!$&&P.length>0&&D.push({type:"text",text:P.join("")}),U!==void 0){const j=D.filter(z=>z.type==="reasoning");D.length=0,D.push(...j,{type:"text",text:U}),p.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:U.length})}const N=M.usage.cache_read_input_tokens??0,F=M.usage.cache_creation_input_tokens??0;return{content:D,finishReason:{unified:U!==void 0&&SY(M.stop_reason)==="tool-calls"?"stop":SY(M.stop_reason),raw:M.stop_reason??"stop"},usage:{inputTokens:{total:M.usage.input_tokens+N+F,noCache:M.usage.input_tokens,cacheRead:N,cacheWrite:F},outputTokens:{total:M.usage.output_tokens,text:M.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:_},response:{id:M.id,modelId:M.model,headers:ODr()??{},body:M}}},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 ki(e,[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(r.message),errorClass:kr,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:r=>r.statusCode===429||/rate limit|too_many_requests|429/i.test(r.message),errorClass:vs,message:"Anthropic rate limit exceeded. Please try again later."},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(r.message),errorClass:ko,message:r=>`Connection error: ${r.message}`},{match:r=>/500|502|503|504|server error/i.test(r.message),errorClass:Xe,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:Xe,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await PDr(()=>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(pd(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||bv(),n=await this.getAISDKModelWithMiddleware(e);if(!AP(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(([w,S])=>{const _=S;return{type:"function",name:w,description:_.description??"",inputSchema:_.inputSchema?No(_.inputSchema):{type:"object",properties:{}}}}),c=a.length>0,l=e.schema?No(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 HW({doGenerate:o,conversation:f,...c?{tools:a}:{},toolsRecord:i,...c&&e.toolChoice?{toolChoice:RP(e,i,!0)}:{},...u?{responseFormat:u}:{},...h?{providerOptions:h}:{},maxSteps:e.maxSteps||zs,...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:w=>Vy(w,lt.getActiveSpan()??void 0,"anthropic generate").catch(S=>{throw this.handleProviderError(S)})},g),v={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:jj(g),toolExecutions:Wh(e,fd(g)),enhancedWithTools:y.toolsUsed.length>0};return this.finalizeNativeGenerate(v,e,t)}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),LDr(e),FDr(e,this.modelName)}supportsExecutionControl(){return!0}async executeStream(e,t){return NDr(()=>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=fa(o,this.providerName,"stream"),i=new AbortController,a=hge([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?K0(c,"input_schema"):void 0;const Ie=await this.buildMessagesForStream(e);if(u=wY(Ie),e.schema&&l&&l.length>0){const Ce=ISt(l,No(e.schema));l=Ce.tools,m=Ce.applied,Ce.applied&&(u.system=RSt(u.system))}}catch(Ie){throw s?.cleanup(),this.handleProviderError(Ie)}const h=this.modelName||bv(),f=d&&l&&l.length>0?EY(RP(e,c,d)):void 0,g=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,y=LSt.startSpan("neurolink.provider.streamText",{kind:zr.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":h}}),v=e.maxSteps||zs,w=this.neurolink?.getEventEmitter(),S=V0(),{push:_}=S,{usagePromise:C,finishPromise:k,resolveUsage:A,resolveFinish:I}=NW();C.then(Ie=>{y.setAttribute("gen_ai.usage.input_tokens",Ie.promptTokens||0),y.setAttribute("gen_ai.usage.output_tokens",Ie.completionTokens||0),Ie.cacheReadTokens&&y.setAttribute("gen_ai.usage.cached_input_tokens",Ie.cacheReadTokens);const Ce=Ri(this.providerName,this.modelName,{input:Ie.promptTokens||0,output:Ie.completionTokens||0,total:Ie.totalTokens||0,...Ie.cacheReadTokens?{cacheReadTokens:Ie.cacheReadTokens}:{},...Ie.cacheCreationTokens?{cacheCreationTokens:Ie.cacheCreationTokens}:{}});Ce&&Ce>0&&y.setAttribute("neurolink.cost",Ce)}).catch(()=>{}),k.then(Ie=>{y.setAttribute("gen_ai.response.finish_reason",Ie||"unknown"),y.end()}).catch(()=>{y.end()});let R;const M=this.client,D=[],U=Date.now(),P={};let $=0,N=0,F=0,j=0,z=null;const V=()=>({promptTokens:$,completionTokens:N,totalTokens:$+F+j+N,...F>0?{cacheReadTokens:F}:{},...j>0?{cacheCreationTokens:j}:{}});let q="",G;const J=(Ie,Ce)=>{const Ve=xe=>{if(typeof xe=="string")return xe;try{return JSON.stringify(xe)??""}catch{return""}};return Zt(Ve(Ie),"anthropic")+Zt(Ve(Ce),"anthropic")},pe=(async()=>{let Ie,Ce;const De=pY({client:M,maxSteps:v,toolsRecord:c,buildParams:he=>{if(l){const ce=new Set(l.map(Re=>Re.name)),ve=Object.fromEntries(Object.entries(c).filter(([Re])=>!ce.has(Re)));if(Object.keys(ve).length>0){const Re=K0(ve,"input_schema");Re&&Re.length>0&&(l=[...l,...Re])}}const oe=sW(l),Z=uY({system:u.system,tools:oe,messages:he}),ae=kSt(he,GD-Z),Q=ml("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:ae,max_tokens:oP(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:he=>{const oe=_St({conversation:he,availableInputTokens:El("anthropic",h,e.maxTokens??void 0),fixedOverheadTokens:J(u.system,l),provider:"anthropic",observedPromptTokens:Ie,previousSentEstimate:Ce,onSentEstimate:ce=>{Ce=ce}});if(!oe)return;const Z=new Set(oe.drop),ae=new Set(oe.truncate),Q=[];for(let ce=0;ce<he.length;ce++){if(Z.has(ce))continue;const ve=he[ce];if(ae.has(ce)&&Array.isArray(ve.content)){Q.push({...ve,content:ve.content.map(Re=>Re.type==="tool_result"?{...Re,content:bSt(typeof Re.content=="string"?Re.content:JSON.stringify(Re.content)??"")}:Re)});continue}Q.push(ve)}if(Z.size>0){let ce=Q.findIndex(ve=>Array.isArray(ve.content)&&ve.content.some(Re=>Re.type==="tool_use"||Re.type==="tool_result"));ce<0&&(ce=Math.min(1,Q.length)),Q.splice(ce,0,{role:"user",content:[{type:"text",text:lY}]})}return{conversation:Q}},...r?{requestTimeoutMs:r.requestTimeoutMs,requireTerminalEvent:!0}:{},noteObservedPromptTokens:he=>{Ie=he},...m?{finalResultToolName:vC,onTerminalResult:he=>{G=he,p.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:he.length})}}:{}}),Le={...De,buildToolResultMessages:(he,oe,Z,ae)=>{for(const ve of Z)D.push(ve.name);const Q=Z.map(ve=>({type:"tool-call",toolCallId:ve.id,toolName:ve.name,args:ve.args})),ce=Z.map(ve=>ve.error?{type:"tool-result",toolCallId:ve.id,toolName:ve.name,error:ve.error}:{type:"tool-result",toolCallId:ve.id,toolName:ve.name,result:ve.output});return ygt(w,ce.map(ve=>({toolName:ve.toolName,result:"result"in ve?ve.result:void 0,error:"error"in ve?ve.error:void 0}))),this.handleToolExecutionStorage(Q,ce,e,new Date).catch(ve=>{p.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ve instanceof Error?ve.message:String(ve)})}),De.buildToolResultMessages(he,oe,Z,ae)}},Pe={};for(const[he,oe]of Object.entries(c)){const Z=oe.execute;Z&&(Pe[he]={execute:async(ae,Q)=>{const ce=Q;return Z(ae,{toolCallId:ce.toolCallId??"",...ce.abortSignal?{abortSignal:ce.abortSignal}:{},messages:[]})}})}const mt=lt.getActiveSpan(),Tt=r?.beforeStep,$e=Tt?async he=>{const oe=r?.beforeStepTimeoutMs??a9,Z=fa(oe,this.providerName,"stream"),ae=gB(he.signal,Z?.controller.signal);try{return await td(Promise.resolve(Tt({...he,signal:ae.signal??he.signal})),ae.signal??he.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:he.stepsCompleted});return}finally{ae.dispose(),Z?.cleanup()}}:void 0,{stream:ye,resultPromise:we}=xd(Le,u.messages.slice(),{tools:Pe,...a?{abortSignal:a}:{},...mt?{span:mt}:{},...$e?{beforeStep:$e}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}}),X=(async()=>{for await(const he of ye)he.reasoning&&_({content:"",reasoning:he.reasoning}),he.content&&(m?q+=he.content:_({content:he.content}))})();let W;try{W=await we}catch(he){throw await Sf(X,"Anthropic"),he}if(await X,$+=W.usage.inputTokens,N+=W.usage.outputTokens,F+=W.usage.cacheReadTokens??0,j+=W.usage.cacheWriteTokens??0,z=W.rawStopReason??z,W.aborted){const he=a?.aborted?a.reason:void 0;P.stopReason=he instanceof ja?"time-limit":"aborted",P.finishReason="other",W.rawStopReason&&(P.rawFinishReason=W.rawStopReason),A(V()),I("other");return}P.finishReason=W.finishReason,W.rawStopReason&&(P.rawFinishReason=W.rawStopReason),W.finishReason==="tool-calls"&&G===void 0&&(P.stopReason="step-cap"),A(V()),I(z??"stop")})().catch(Ie=>{throw R=Ie,p.error("Anthropic: Stream error",{error:Ie instanceof Error?Ie.message:String(Ie)}),A(V()),I("error"),this.formatProviderError(Ie)}).finally(()=>{if(m){const Ie=G??q;Ie.length>0&&_({content:Ie})}s?.cleanup(),S.close()});pe.catch(()=>{});const ne=this.providerName;return{stream:async function*(){let Ie=0;try{for await(const Ce of S.iterable)"content"in Ce&&typeof Ce.content=="string"&&Ce.content.length>0&&Ie++,yield Ce;if(await pe,Ie===0&&D.length===0){p.warn(`${ne}: Stream produced no output \u2014 emitting enriched sentinel`);const Ce=new ou({message:"Stream produced no output"}),Ve=await gf(Ce,void 0,R);yf(Ve),yield Ve}}catch(Ce){const Ve=await gf(Ce,void 0,R);if(yf(Ve),yield Ve,!ou.isInstance(Ce))throw Ce}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],metadata:P,analytics:k.then(async()=>{const Ie=await jW.createAnalytics(this.providerName,h,{textStream:(async function*(){})(),usage:C,finishReason:k},Date.now()-U,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),Ce=DDr();return Ce&&Ie&&(this.recordLimitSnapshot(Ce),Ie.limits=Ce),Ie})}}async isAvailable(){try{return TY()||vY(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),BSt={};se(BSt,{ANTHROPIC_BETA_HEADERS:()=>WD,AnthropicProvider:()=>USt,ModelAccessError:()=>q$,getModelCapabilities:()=>iY,getRecommendedModelForTier:()=>sY,isModelAvailableForTier:()=>oY});var ZDr=b({"src/lib/providers/anthropic/index.ts"(){"use strict";XDr(),NSt()}}),Hf,Ws,QDr,eOr,zSt,qSt,GSt,TC,jSt,tOr,rOr,nOr,oOr,sOr,iOr,aOr,cOr,lOr,uOr,dOr,mOr,pOr,hOr,fOr,gOr,yOr,vOr,TOr,wOr,EOr,SOr,bOr,_Or,COr,kOr,AOr,xOr,IOr,ROr,MOr,POr,DOr,OOr,NOr,LOr,FOr,$Or,UOr,HSt=b({"npm-stub:@aws-sdk/client-bedrock-runtime"(){Hf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Hf.get}):new Proxy(function(...r){return new Proxy({},{get:Hf.get})},{get:Hf.get,apply(r,n,o){return new Proxy({},{get:Hf.get})},construct(r,n){return new Proxy({},{get:Hf.get})}})}},Ws=new Proxy({},Hf),{BedrockClient:QDr,ListFoundationModelsCommand:eOr,BedrockRuntimeClient:zSt,ConverseCommand:qSt,ConverseStreamCommand:GSt,ImageFormat:TC,InvokeModelCommand:jSt}=Ws,{SageMakerRuntimeClient:tOr,InvokeEndpointCommand:rOr,InvokeEndpointWithResponseStreamCommand:nOr}=Ws,{GoogleAuth:oOr,VertexAI:sOr,TextToSpeechClient:iOr}=Ws,{Webhook:aOr}=Ws,{Hippocampus:cOr,HippocampusConfig:lOr}=Ws,{createClient:uOr}=Ws,{Queue:dOr,Worker:mOr,Job:pOr,QueueScheduler:hOr,FlowProducer:fOr}=Ws,{Cron:gOr}=Ws,{parseBuffer:yOr,selectCover:vOr}=Ws,{extractRawText:TOr,convertToHtml:wOr}=Ws,{Hono:EOr}=Ws,{cors:SOr,HTTPException:bOr,logger:_Or,secureHeaders:COr,streamSSE:kOr,timeout:AOr}=Ws,xOr=globalThis.fetch,IOr=globalThis.Request,ROr=globalThis.Response,MOr=globalThis.Headers,POr=globalThis.FormData,DOr=globalThis.File,OOr=globalThis.Blob,NOr=Ws.Agent,LOr=Ws.Pool,FOr=Ws.Client,$Or=Ws.Dispatcher,UOr=Ws.MockAgent}});function BOr(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 zOr(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function VSt(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 qOr(e,t){if(e.startsWith("arn:")||zOr(e))return[];const r=[],n=BOr(t);return n&&r.push(`${n}.${e}`),r.push(`${JSt}.${e}`),r}function WSt(e,t){return`${e}::${t}`}function GOr(e,t){return _Y.get(WSt(t,e))}function jOr(e,t,r){_Y.set(WSt(t,e),r),p.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function KSt(e,t,r){const n=GOr(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!VSt(o))throw o;const s=qOr(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 jOr(e,t,i),a}catch(a){if(!VSt(a))throw a}throw o}}var JSt,_Y,HOr=b({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";B(),JSt="global",_Y=new Map}});function KD(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function YSt(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 XSt(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??KD(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function VOr(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,v=g.contentBlockDelta.delta.text;i(y),a+=v,s.set(y,(s.get(y)??"")+v),t.push({content:v})}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??KD()}}if(g.contentBlockDelta?.delta?.toolUse){const y=i(g.contentBlockDelta.contentBlockIndex??0);y.toolUse??={name:"",input:{},toolUseId:KD()};const v=g.contentBlockDelta.delta.toolUse.input;typeof v=="string"?y._inputBuffer=(y._inputBuffer??"")+v:typeof v=="object"&&v!==null&&!Array.isArray(v)&&(y.toolUse.input={...y.toolUse.input??{},...v})}if(g.contentBlockStop){const y=g.contentBlockStop.contentBlockIndex??0;YSt(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)YSt(g,s.get(f)??"");const h=n.filter(f=>f.text||f.toolUse||f.image||f.document);return{text:a,toolCalls:XSt(h),usage:{inputTokens:l,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:m},rawStopReason:c,raw:h}}function WOr(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??KD(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:XSt(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 ZSt(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 KSt(o.modelId??"",e.region,a=>qe(e.client.send(new qSt({...o,modelId:a}),{abortSignal:n}),CY,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return WOr(i)}const s=await KSt(o.modelId??"",e.region,i=>qe(e.client.send(new GSt({...o,modelId:i}),{abortSignal:n}),CY,new Error("Bedrock streaming API call timed out")));return VOr(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 CY,KOr=b({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";HSt(),tt(),HOr(),CY=12e4}});function QSt(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,imageOptions:e.imageOptions,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 JOr=b({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),JD,ebt=b({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";Ja(),JD=Ue.provider}}),tbt={};se(tbt,{Agent:()=>jbt,BedrockClient:()=>nbt,BedrockRuntimeClient:()=>sbt,Blob:()=>Gbt,Client:()=>Vbt,ConverseCommand:()=>ibt,ConverseStreamCommand:()=>abt,Cron:()=>Cbt,Dispatcher:()=>Wbt,File:()=>qbt,FlowProducer:()=>_bt,FormData:()=>zbt,GoogleAuth:()=>pbt,HTTPException:()=>Pbt,Headers:()=>Bbt,Hippocampus:()=>ybt,HippocampusConfig:()=>vbt,Hono:()=>Rbt,ImageFormat:()=>cbt,InvokeEndpointCommand:()=>dbt,InvokeEndpointWithResponseStreamCommand:()=>mbt,InvokeModelCommand:()=>lbt,Job:()=>Sbt,ListFoundationModelsCommand:()=>obt,MockAgent:()=>Ybt,Pool:()=>Hbt,Queue:()=>wbt,QueueScheduler:()=>bbt,Request:()=>$bt,Response:()=>Ubt,SageMakerRuntimeClient:()=>ubt,TextToSpeechClient:()=>fbt,VertexAI:()=>hbt,Webhook:()=>gbt,Worker:()=>Ebt,convertToHtml:()=>Ibt,cors:()=>Mbt,createClient:()=>Tbt,default:()=>rbt,extractRawText:()=>xbt,fetch:()=>Fbt,getGlobalDispatcher:()=>Jbt,interceptors:()=>Xbt,logger:()=>Dbt,parseBuffer:()=>kbt,request:()=>Zbt,secureHeaders:()=>Obt,selectCover:()=>Abt,setGlobalDispatcher:()=>Kbt,streamSSE:()=>Nbt,timeout:()=>Lbt});var Vf,ls,rbt,nbt,obt,sbt,ibt,abt,cbt,lbt,ubt,dbt,mbt,pbt,hbt,fbt,gbt,ybt,vbt,Tbt,wbt,Ebt,Sbt,bbt,_bt,Cbt,kbt,Abt,xbt,Ibt,Rbt,Mbt,Pbt,Dbt,Obt,Nbt,Lbt,Fbt,$bt,Ubt,Bbt,zbt,qbt,Gbt,jbt,Hbt,Vbt,Wbt,Kbt,Jbt,Ybt,Xbt,Zbt,YOr=b({"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})}})}},ls=new Proxy({},Vf),rbt=ls,{BedrockClient:nbt,ListFoundationModelsCommand:obt,BedrockRuntimeClient:sbt,ConverseCommand:ibt,ConverseStreamCommand:abt,ImageFormat:cbt,InvokeModelCommand:lbt}=ls,{SageMakerRuntimeClient:ubt,InvokeEndpointCommand:dbt,InvokeEndpointWithResponseStreamCommand:mbt}=ls,{GoogleAuth:pbt,VertexAI:hbt,TextToSpeechClient:fbt}=ls,{Webhook:gbt}=ls,{Hippocampus:ybt,HippocampusConfig:vbt}=ls,{createClient:Tbt}=ls,{Queue:wbt,Worker:Ebt,Job:Sbt,QueueScheduler:bbt,FlowProducer:_bt}=ls,{Cron:Cbt}=ls,{parseBuffer:kbt,selectCover:Abt}=ls,{extractRawText:xbt,convertToHtml:Ibt}=ls,{Hono:Rbt}=ls,{cors:Mbt,HTTPException:Pbt,logger:Dbt,secureHeaders:Obt,streamSSE:Nbt,timeout:Lbt}=ls,Fbt=globalThis.fetch,$bt=globalThis.Request,Ubt=globalThis.Response,Bbt=globalThis.Headers,zbt=globalThis.FormData,qbt=globalThis.File,Gbt=globalThis.Blob,jbt=ls.Agent,Hbt=ls.Pool,Vbt=ls.Client,Wbt=ls.Dispatcher,Kbt=()=>{},Jbt=()=>ls,Ybt=ls.MockAgent,Xbt={redirect:()=>e=>e,retry:()=>e=>e},Zbt=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 kY(){return await Promise.resolve().then(()=>(YOr(),tbt))}var Qbt=b({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}});function XOr(e){const t=(e??"").split(";").at(0)?.trim().toLowerCase();return AY[t??""]}var AY,e_t,ZOr=b({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";HSt(),hr(),pb(),ec(),Do(),vP(),jm(),Ic(),KOr(),ct(),ci(),tt(),sf(),B(),id(),N4(),JOr(),di(),Yt(),ebt(),Qbt(),AY={"image/png":"png","image/jpeg":"jpeg","image/jpg":"jpeg","image/gif":"gif","image/webp":"webp"},e_t=class oar extends _a{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=oar.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 zSt({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 kY(),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 f=QSt(n,this.providerName,this.modelName),g=await P4(f,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(g)}else{p.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const h={role:"user",content:[{text:n.prompt||o?.text||""}]};this.conversationHistory.push(h)}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(h){const f=this.neurolink?.getEventEmitter();throw f&&(f.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:h instanceof Error?h.message:String(h)}),h&&typeof h=="object"&&(h._generationEndEmitted=!0)),h}const d=this.neurolink?.getEventEmitter();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});const m={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(h=>h.error===void 0).map(h=>h.name),toolCalls:u.map(h=>({toolCallId:h.id,toolName:h.name,args:h.input})),toolExecutions:Wh(n,fd(u)),enhancedWithTools:u.some(h=>h.error===void 0)};return m._generationEndEmitted=!0,m}async conversationLoop(t){const r=t.maxSteps||zs,n=await this.resolveTurnTools(t.tools,t.disableTools),o=this.formatToolsForBedrock(n),s=ml(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converse"),i=ZSt({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}=xd(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 JD.startActiveSpan("bedrock.tool.execute",{kind:zr.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:Fe.OK}),u}catch(i){throw p.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:i}),s.setStatus({code:Fe.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=No(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"?TC.JPEG:i==="png"?TC.PNG:i==="gif"?TC.GIF:TC.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?Nm.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"),JD.startActiveSpan("bedrock.stream",{kind:zr.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=QSt(t,this.providerName,this.modelName),i=await P4(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:Fe.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:Fe.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:Fe.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:Fe.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||zs,s=await this.resolveTurnTools(t.tools,t.disableTools),i=this.formatToolsForBedrock(s),a=ml(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converseStream"),c=ZSt({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,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,...a.temperature!==void 0&&{temperature:a.temperature}},...i?{toolConfig:i}:{}})});let l=!1,u;const d=new Promise(A=>{u=()=>{l=!0,A()}}),m={...c,executeStep:async(A,I,R)=>{const M=await c.executeStep(A,I,R);return u(),M}};r.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});const{stream:h,resultPromise:f}=xd(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:t.abortSignal,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}}),g=f.then(A=>({result:A,error:void 0}),A=>({result:void 0,error:A}));if(await Promise.race([d,g]),!l){const A=await g;if(A.error)throw A.error}const y=this.neurolink?.getEventEmitter(),v=this,w={startTime:n,streamId:`bedrock-${Date.now()}`};let S;const _=new Promise(A=>{S=A}),C=A=>{const I=A?.inputTokens??0,R=A?.outputTokens??0,M=A?.cacheReadTokens??0,D=A?.cacheWriteTokens??0;return{input:I,output:R,total:I+M+D+R,...M>0&&{cacheReadTokens:M},...D>0&&{cacheCreationTokens:D}}};return g.then(A=>{S(p0(this.providerName,this.modelName||this.getDefaultModel(),{usage:C(A.result?.usage),toolExecutions:A.result?.toolExecutions??[],toolsUsed:(A.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 A=!1;try{yield*h}catch(I){throw A=!0,I}finally{const I=await g;I.error&&(A=!0);const R=C(I.result?.usage);if(I.result&&(v.conversationHistory=I.result.conversation,w.finishReason=I.result.finishReason,w.rawFinishReason=I.result.rawStopReason,r.setAttribute("gen_ai.response.stop_reason",I.result.rawStopReason??"unknown")),y){const M=t._streamDedupContext;M&&(M.providerEmitted=!0),y.emit("generation:end",{provider:v.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:R,model:v.modelName||v.getDefaultModel(),provider:v.providerName,finishReason:A?"error":I.result?.rawStopReason},success:!A})}}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:_,metadata:w}}async checkBedrockHealth(){const t=new AbortController,r=setTimeout(()=>t.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await kY(),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(ar(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 ki(t,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:kr,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:vs,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:Xe,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:Xe,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(t,r){const n=typeof t=="string"?{text:t}:t,o=r||this.getDefaultEmbeddingModel(),s=o.includes("nova")&&o.includes("multimodal"),i=o.includes("image")||o.includes("multimodal")||o==="amazon.titan-embed-image-v1"||s;p.debug("Generating embedding",{provider:this.providerName,model:o,hasText:typeof n.text=="string",hasImage:n.image!==void 0,isMultiModalModel:i});try{let a;if(n.image&&!i)throw new Xe(`${this.providerName} model ${o} does not support image embeddings`,this.providerName);if(s){if(n.image&&n.text)throw new Xe(`${this.providerName} model ${o} does not support combined image+text embeddings; provide exactly one of image or text`,this.providerName);const m={embeddingPurpose:"GENERIC_RETRIEVAL"};if(n.image){const h=Buffer.isBuffer(n.image)?n.image:Buffer.from(n.image,"base64"),f=XOr(n.mimeType);if(f===void 0)throw new Xe(`${this.providerName} model ${o} does not support image format '${n.mimeType??"unknown"}'; supported formats are ${Object.keys(AY).join(", ")}`,this.providerName);m.image={detailLevel:"STANDARD_IMAGE",format:f,source:{bytes:wo.safeBase64Convert(h,"bedrock nova embed image")}}}n.text&&(m.text={value:n.text,truncationMode:"NONE"}),a=JSON.stringify({taskType:"SINGLE_EMBEDDING",singleEmbeddingParams:m})}else if(n.image){const m=Buffer.isBuffer(n.image)?n.image:Buffer.from(n.image,"base64");a=JSON.stringify({inputText:n.text??"",inputImage:wo.safeBase64Convert(m,"bedrock titan embed image")})}else a=JSON.stringify({inputText:n.text??""});const c=new jSt({modelId:o,contentType:"application/json",accept:"application/json",body:a}),l=await qe(this.bedrockClient.send(c),6e4,new Error("Bedrock embedding API call timed out")),u=JSON.parse(new TextDecoder().decode(l.body)),d=s?u.embeddings?.at(0)?.embedding:u.embedding;if(!Array.isArray(d))throw new Error("Invalid embedding response from Bedrock");return p.debug("Embedding generated successfully",{provider:this.providerName,model:o,embeddingDimension:d.length}),d}catch(a){throw p.error("Embedding generation failed",{error:a instanceof Error?a.message:String(a),model:o}),this.handleProviderError(a)}}async embedMany(t,r){const n=r||this.getDefaultEmbeddingModel();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)}}}}}),t_t={};se(t_t,{AmazonBedrockProvider:()=>e_t,bedrockTracer:()=>JD,loadBedrockControl:()=>kY});var QOr=b({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";ZOr(),ebt(),Qbt()}}),r_t={};se(r_t,{AzureOpenAIProvider:()=>n_t});var n_t,eNr=b({"src/lib/providers/azureOpenai.ts"(){"use strict";ct(),B(),ci(),qo(),Ic(),rc(),dp(),n_t=class extends Aa{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||Ai(Zhr()),d||Ai(Qhr()),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",AUe({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:kr,message:"Invalid Azure OpenAI API key or endpoint."},...ya];return ki(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??lgt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function xY(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"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&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97?"image/gif":null}function wC(e){return xY(e)??"image/png"}var YD=b({"src/lib/utils/imageDetection.ts"(){"use strict"}});function o_t(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 tNr=b({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),XD,rNr=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs"(){XD=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}}}),nNr=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs"(){So()}});function IY(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var ZD,RY,s_t=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs"(){nNr(),ZD=e=>(ZD=Array.isArray,ZD(e)),RY=ZD}});function*oNr(e){if(!e)return;if(MY 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():RY(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=RY(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 MY,i_t,sNr=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){s_t(),MY=Symbol.for("brand.privateNullableHeaders"),i_t=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[s,i]of oNr(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{[MY]:!0,values:t,nulls:r}}}});function iNr(e){const t=new lC(e);return delete t.batches,t}function aNr(e){const t=new ta(e);return delete t.messages.batches,t}var a_t,c_t,PY,l_t=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){UD(),uTt(),p_(),rNr(),s_t(),sNr(),UD(),a_t="vertex-2023-10-16",c_t=new Set(["/v1/messages","/v1/messages?beta=true"]),PY=class extends xo{constructor({baseURL:e=XD("ANTHROPIC_VERTEX_BASE_URL"),region:t=XD("CLOUD_ML_REGION")??null,projectId:r=XD("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=iNr(this),this.beta=aNr(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 iP({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=i_t([r,e.headers])}async buildRequest(e){if(IY(e.body)&&(e.body={...e.body}),IY(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=a_t)),c_t.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(!IY(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)}}}}),DY={};se(DY,{AnthropicVertex:()=>PY,BaseAnthropic:()=>xo,default:()=>PY});var u_t=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){l_t(),l_t()}});async function cNr(){return QD||(QD=await Promise.resolve().then(()=>(u_t(),DY))),QD}function lNr(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 OY(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 uNr(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 dNr(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 NY(e){const t=[];let r=0;for(const n of lNr(e)){if(n.type==="regular"){OY(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:s}=uNr(n,r);o.length!==0&&(r++,OY(t,"assistant",o),OY(t,"user",s))}if(dNr(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 LY(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 d_t(e,t,r){const n=uft({contents:e,availableInputTokens:El("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<=y_t?l:{functionResponse:{name:u.name,response:{result:rW(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:oW}]})}return e.length=0,e.push(...i),!0}function m_t(e,t,r){const n=_St({conversation:e,availableInputTokens:El("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:bSt(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:lY}]})}return e.length=0,e.push(...i),!0}async function p_t(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 v of g.parts)n.push(v),typeof v.text=="string"&&v.text.length>0&&t.push({content:v.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 v=Math.min(y.cachedContentTokenCount??0,y.promptTokenCount);r.onUsageDelta?.("cacheRead",v-c),c=v}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 QD,h_t,FY,EC,$Y,_v,Kf,f_t,g_t,eO,y_t,UY,mNr=b({"src/lib/providers/googleVertex/client.ts"(){"use strict";on(),dP(),hr(),ec(),u7(),gP(),z7(),Do(),qh(),Hh(),tW(),Ut(),Mn(),ct(),ci(),tt(),dY(),bdt(),N4(),B(),W9(),mft(),CSt(),rP(),YD(),N9(),qo(),di(),Jht(),bf(),ga(),pft(),oft(),vP(),DSt(),l_(),W0(),iW(),Sl(),wb(),Ja(),Yt(),Ya(),Ic(),jm(),id(),tNr(),l_(),QD=null,h_t=()=>!0,FY=()=>Ai(cfr()),EC=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",$Y=(e,t)=>{const r=t||EC();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||rz.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},_v=$Y,Kf=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",f_t=()=>!!(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),g_t=async(e,t,r,n)=>{const o=e||EC();return{projectId:r?r.projectId?.trim()||"express":FY(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},eO=e=>e.toLowerCase().includes("claude"),y_t=2048,UY=class Xr extends _a{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||f_t()||Ai(lfr()),this.projectId=s?.projectId||(i?"":FY()),this.location=o||s?.location||EC(),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 Kf()}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&&jV(t.input),t.input?.files?.length)try{await HV(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 s_(t.input)}async executeStream(t,r){const n=t.model||this.modelName||Kf();return yNe({name:"neurolink.provider.stream",tracer:Ue.provider,attributes:{[be.GEN_AI_SYSTEM]:this.providerName,[be.GEN_AI_MODEL]:n,[be.GEN_AI_OPERATION]:"stream",[be.NL_PROVIDER]:this.providerName}},async o=>{const s=Date.now(),i=t.tools||{};await this.preprocessNativeFileInput(t);const c={...await ut({name:"neurolink.message.build",tracer:Ue.provider,attributes:{[be.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;eO(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){Eft("GoogleVertex");const r=this.resolveExpressApiKey(),n=r?"":this.projectId,o=t||this.location||EC(),i=(await Promise.resolve().then(()=>(OS(),e0))).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=No(s),a=Wn(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=pBe(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=No(t),n=Wn(r);n.$schema&&delete n.$schema;const o=Wi(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||Kf(),n=_v(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 ye of a.pdfFiles){let we;typeof ye=="string"?Oo.existsSync(ye)?we=Oo.readFileSync(ye):we=Buffer.from(ye,"base64"):we=ye;const X=we.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:X}})}}if(await X9(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){p.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(const ye of a.images){const we=Bb(ye);let X,W="image/jpeg";if(typeof we=="string")if(Oo.existsSync(we)){X=Oo.readFileSync(we);const oe=Hb(we);W=oe.startsWith("image/")?oe:this.detectImageType(X)}else if(we.startsWith("data:")){const oe=we.match(/^data:([^;]+);base64,(.+)$/);if(oe)W=oe[1],X=Buffer.from(oe[2],"base64");else continue}else if(we.startsWith("http://")||we.startsWith("https://"))try{const oe=await fetch(we);if(!oe.ok){p.warn(`[GoogleVertex] Image fetch failed: ${oe.status} ${oe.statusText}, skipping`,{url:mr(we)});continue}const Z=await oe.arrayBuffer();X=Buffer.from(Z);const ae=oe.headers.get("content-type");ae&&ae.startsWith("image/")&&(W=ae.split(";")[0])}catch(oe){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${oe instanceof Error?oe.message:String(oe)}`,{url:mr(we)});continue}else X=Buffer.from(we,"base64"),W=this.detectImageType(X);else X=we,W=this.detectImageType(X);const he=X.toString("base64");i.push({inlineData:{mimeType:W,data:he}})}}hP(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 ye=K0(t.tools,"functionDeclarations");u=ye,c=ye.toolsConfig;for(const[we,X]of ye.executeMap)l.set(we,X);p.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ye.toolsConfig[0].functionDeclarations.length,toolNames:ye.toolsConfig[0].functionDeclarations.map(we=>we.name)})}const d=t;let m=!1;if(d.schema&&c){m=!0;const ye=No(d.schema,"openApi3"),we=Wn(ye);we.$schema&&delete we.$schema;const X=Wi(we),W=c[0]?.functionDeclarations||[];W.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:X}),c=[{functionDeclarations:W}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(X),totalTools:W.length})}const h=ml(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};O9(r)&&(f.maxOutputTokens&&f.maxOutputTokens>ba&&(p.warn(`[GoogleVertex] Capping maxOutputTokens from ${f.maxOutputTokens} to ${ba} for ${r}`),f.maxOutputTokens=ba),f.maxOutputTokens||(f.maxOutputTokens=ba)),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+`
1078
+ `);return{...s!==void 0?{system:s}:{},messages:r}},EY=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}}}},SY=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},bY=6e5,USt=class extends _a{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??TY(),i=o?"api_key":r?.authMethod??$St(s),a=r?.subscriptionTier??(i==="oauth"?FSt(s):"api"),c=e||bv();let l=c;!process.env.ANTHROPIC_BASE_URL&&a!=="api"&&!oY(c,a)&&(l=sY(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=ADr(()=>h.accessToken,this.enableBetaFeatures,!1,!0);m=new Gf({apiKey:"oauth-authenticated",fetch:ySt(f),timeout:bY,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??vY(),f=(()=>{const g=process.env.ANTHROPIC_BASE_URL;if(!g)return;const y=g.replace(/\/+$/,""),v=y.replace(/\/v\d+$/,"");return v!==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:yo(g),rewrittenTo:yo(v)}),v})();m=new Gf({apiKey:h,defaultHeaders:d,...f&&{baseURL:f},fetch:ySt(Rt()),timeout:bY,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?WD["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=[...hC,"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"]=WD["anthropic-beta"];return t&&(e["User-Agent"]=jf),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=oY(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 iY(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+wle;if(!t&&!r){p.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new kr("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(pC,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":jf},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:rY}),signal:i.signal});if(clearTimeout(a),!c.ok){const d=await c.text();throw new kr(`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=At(Pi(),".neurolink");Ss(d)||mz(d,{recursive:!0});const m=At(d,"anthropic-credentials.json"),h=`${m}.tmp`,g={...Ss(m)?JSON.parse(lu(m,"utf-8")):{},type:"oauth",oauth:u,updatedAt:Date.now()};ZR(h,JSON.stringify(g,null,2),{mode:384}),hz(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 kr?s:new kr(`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 bv()}getAISDKModel(){const e=this.client,t=this.providerName,r=this.modelName||bv(),n=i=>this.getTimeout(i??{}),o=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:r,supportedUrls:{},doGenerate:async i=>{await o();const a=wY(i.prompt),c=a.messages;let l=a.system,u=(i.tools??[]).filter(j=>j.type==="function").map(j=>{const z=Id(j);return{name:j.name,...j.description?{description:j.description}:{},input_schema:j.inputSchema??{type:"object",properties:{}},...z?{cache_control:z}:{}}});u&&u.length===0&&(u=void 0);const d=cMr(i.toolChoice);let m=d?EY(d):void 0,h;if(i.responseFormat?.type==="json"){h=i.responseFormat.name??"json";const j=i.responseFormat.schema??{type:"object"};u=[{name:h,description:i.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:j}],m={type:"tool",name:h}}const f=i.providerOptions?.anthropic?.finalResultSchema;let g=!1;if(!h&&f){const j=ISt(u,f);u=j.tools,g=j.applied,j.applied&&(l=RSt(l))}const y=i.providerOptions?.anthropic?.thinking;u=sW(u);const v=uY({system:l,tools:u,messages:c}),w=kSt(c,GD-v),S=ml("anthropic",r,{...i.temperature!==void 0&&i.temperature!==null?{temperature:i.temperature}:{},...i.topP!==void 0&&i.topP!==null?{topP:i.topP}:{}},"anthropic.doGenerate");y&&(S.temperature!==void 0||S.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:oP(r,i.maxOutputTokens),...l?{system:l}:{},...!y&&S.temperature!==void 0?{temperature:S.temperature}:{},...!y&&S.topP!==void 0?{top_p:S.topP}:{},...i.stopSequences&&i.stopSequences.length>0?{stop_sequences:i.stopSequences}:{},...u?{tools:u}:{},...m?{tool_choice:m}:{},...y?{thinking:y}:{}},C=i.providerOptions?.neurolink,k=typeof C?.timeoutMs=="number"&&Number.isFinite(C.timeoutMs)&&C.timeoutMs>0?C.timeoutMs:void 0,A=k!==void 0?k:_.max_tokens>8192?Math.max(n(i),3e5):n(i),I=fa(A,t,"generate"),R=FR(i.abortSignal,I?.controller.signal);let M;try{M=await e.messages.create(_,{signal:R})}catch(j){const z=R?.aborted?R.reason:void 0;throw z instanceof ja?z:j}finally{I?.cleanup()}const D=[];let U;const P=[];let $=!1;for(const j of M.content)j.type==="thinking"?D.push({type:"reasoning",text:j.thinking,providerOptions:{anthropic:{signature:j.signature}}}):j.type==="redacted_thinking"?D.push({type:"reasoning",text:"",providerOptions:{anthropic:{redactedData:j.data}}}):j.type==="text"?h?P.push(j.text):D.push({type:"text",text:j.text}):j.type==="tool_use"&&(h&&j.name===h?($=!0,D.push({type:"text",text:w_(j.input)})):g&&j.name===vC?U=w_(j.input):D.push({type:"tool-call",toolCallId:j.id,toolName:j.name,input:w_(j.input)}));if(h&&!$&&P.length>0&&D.push({type:"text",text:P.join("")}),U!==void 0){const j=D.filter(z=>z.type==="reasoning");D.length=0,D.push(...j,{type:"text",text:U}),p.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:U.length})}const N=M.usage.cache_read_input_tokens??0,F=M.usage.cache_creation_input_tokens??0;return{content:D,finishReason:{unified:U!==void 0&&SY(M.stop_reason)==="tool-calls"?"stop":SY(M.stop_reason),raw:M.stop_reason??"stop"},usage:{inputTokens:{total:M.usage.input_tokens+N+F,noCache:M.usage.input_tokens,cacheRead:N,cacheWrite:F},outputTokens:{total:M.usage.output_tokens,text:M.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:_},response:{id:M.id,modelId:M.model,headers:ODr()??{},body:M}}},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 ki(e,[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(r.message),errorClass:kr,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:r=>r.statusCode===429||/rate limit|too_many_requests|429/i.test(r.message),errorClass:vs,message:"Anthropic rate limit exceeded. Please try again later."},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(r.message),errorClass:ko,message:r=>`Connection error: ${r.message}`},{match:r=>/500|502|503|504|server error/i.test(r.message),errorClass:Xe,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:Xe,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await PDr(()=>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(pd(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||bv(),n=await this.getAISDKModelWithMiddleware(e);if(!AP(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(([w,S])=>{const _=S;return{type:"function",name:w,description:_.description??"",inputSchema:_.inputSchema?No(_.inputSchema):{type:"object",properties:{}}}}),c=a.length>0,l=e.schema?No(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 HW({doGenerate:o,conversation:f,...c?{tools:a}:{},toolsRecord:i,...c&&e.toolChoice?{toolChoice:RP(e,i,!0)}:{},...u?{responseFormat:u}:{},...h?{providerOptions:h}:{},maxSteps:e.maxSteps||zs,...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:w=>Vy(w,lt.getActiveSpan()??void 0,"anthropic generate").catch(S=>{throw this.handleProviderError(S)})},g),v={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+y.cacheWriteTokens,...y.cacheReadTokens?{cacheReadTokens:y.cacheReadTokens}:{},...y.cacheWriteTokens?{cacheCreationTokens:y.cacheWriteTokens}:{}},responseTime:Date.now()-t,toolsUsed:y.toolsUsed,toolCalls:jj(g),toolExecutions:Wh(e,fd(g)),enhancedWithTools:y.toolsUsed.length>0};return this.finalizeNativeGenerate(v,e,t)}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),LDr(e),FDr(e,this.modelName)}supportsExecutionControl(){return!0}async executeStream(e,t){return NDr(()=>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=fa(o,this.providerName,"stream"),i=new AbortController,a=hge([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?K0(c,"input_schema"):void 0;const Ie=await this.buildMessagesForStream(e);if(u=wY(Ie),e.schema&&l&&l.length>0){const Ce=ISt(l,No(e.schema));l=Ce.tools,m=Ce.applied,Ce.applied&&(u.system=RSt(u.system))}}catch(Ie){throw s?.cleanup(),this.handleProviderError(Ie)}const h=this.modelName||bv(),f=d&&l&&l.length>0?EY(RP(e,c,d)):void 0,g=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,y=LSt.startSpan("neurolink.provider.streamText",{kind:zr.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":h}}),v=e.maxSteps||zs,w=this.neurolink?.getEventEmitter(),S=V0(),{push:_}=S,{usagePromise:C,finishPromise:k,resolveUsage:A,resolveFinish:I}=NW();C.then(Ie=>{y.setAttribute("gen_ai.usage.input_tokens",Ie.promptTokens||0),y.setAttribute("gen_ai.usage.output_tokens",Ie.completionTokens||0),Ie.cacheReadTokens&&y.setAttribute("gen_ai.usage.cached_input_tokens",Ie.cacheReadTokens);const Ce=Ri(this.providerName,this.modelName,{input:Ie.promptTokens||0,output:Ie.completionTokens||0,total:Ie.totalTokens||0,...Ie.cacheReadTokens?{cacheReadTokens:Ie.cacheReadTokens}:{},...Ie.cacheCreationTokens?{cacheCreationTokens:Ie.cacheCreationTokens}:{}});Ce&&Ce>0&&y.setAttribute("neurolink.cost",Ce)}).catch(()=>{}),k.then(Ie=>{y.setAttribute("gen_ai.response.finish_reason",Ie||"unknown"),y.end()}).catch(()=>{y.end()});let R;const M=this.client,D=[],U=Date.now(),P={};let $=0,N=0,F=0,j=0,z=null;const V=()=>({promptTokens:$,completionTokens:N,totalTokens:$+F+j+N,...F>0?{cacheReadTokens:F}:{},...j>0?{cacheCreationTokens:j}:{}});let q="",G;const J=(Ie,Ce)=>{const Ve=xe=>{if(typeof xe=="string")return xe;try{return JSON.stringify(xe)??""}catch{return""}};return Zt(Ve(Ie),"anthropic")+Zt(Ve(Ce),"anthropic")},pe=(async()=>{let Ie,Ce;const De=pY({client:M,maxSteps:v,toolsRecord:c,buildParams:he=>{if(l){const ce=new Set(l.map(Re=>Re.name)),ve=Object.fromEntries(Object.entries(c).filter(([Re])=>!ce.has(Re)));if(Object.keys(ve).length>0){const Re=K0(ve,"input_schema");Re&&Re.length>0&&(l=[...l,...Re])}}const oe=sW(l),Z=uY({system:u.system,tools:oe,messages:he}),ae=kSt(he,GD-Z),Q=ml("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:ae,max_tokens:oP(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:he=>{const oe=_St({conversation:he,availableInputTokens:El("anthropic",h,e.maxTokens??void 0),fixedOverheadTokens:J(u.system,l),provider:"anthropic",observedPromptTokens:Ie,previousSentEstimate:Ce,onSentEstimate:ce=>{Ce=ce}});if(!oe)return;const Z=new Set(oe.drop),ae=new Set(oe.truncate),Q=[];for(let ce=0;ce<he.length;ce++){if(Z.has(ce))continue;const ve=he[ce];if(ae.has(ce)&&Array.isArray(ve.content)){Q.push({...ve,content:ve.content.map(Re=>Re.type==="tool_result"?{...Re,content:bSt(typeof Re.content=="string"?Re.content:JSON.stringify(Re.content)??"")}:Re)});continue}Q.push(ve)}if(Z.size>0){let ce=Q.findIndex(ve=>Array.isArray(ve.content)&&ve.content.some(Re=>Re.type==="tool_use"||Re.type==="tool_result"));ce<0&&(ce=Math.min(1,Q.length)),Q.splice(ce,0,{role:"user",content:[{type:"text",text:lY}]})}return{conversation:Q}},...r?{requestTimeoutMs:r.requestTimeoutMs,requireTerminalEvent:!0}:{},noteObservedPromptTokens:he=>{Ie=he},...m?{finalResultToolName:vC,onTerminalResult:he=>{G=he,p.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:he.length})}}:{}}),Le={...De,buildToolResultMessages:(he,oe,Z,ae)=>{for(const ve of Z)D.push(ve.name);const Q=Z.map(ve=>({type:"tool-call",toolCallId:ve.id,toolName:ve.name,args:ve.args})),ce=Z.map(ve=>ve.error?{type:"tool-result",toolCallId:ve.id,toolName:ve.name,error:ve.error}:{type:"tool-result",toolCallId:ve.id,toolName:ve.name,result:ve.output});return ygt(w,ce.map(ve=>({toolName:ve.toolName,result:"result"in ve?ve.result:void 0,error:"error"in ve?ve.error:void 0}))),this.handleToolExecutionStorage(Q,ce,e,new Date).catch(ve=>{p.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ve instanceof Error?ve.message:String(ve)})}),De.buildToolResultMessages(he,oe,Z,ae)}},Pe={};for(const[he,oe]of Object.entries(c)){const Z=oe.execute;Z&&(Pe[he]={execute:async(ae,Q)=>{const ce=Q;return Z(ae,{toolCallId:ce.toolCallId??"",...ce.abortSignal?{abortSignal:ce.abortSignal}:{},messages:[]})}})}const mt=lt.getActiveSpan(),Tt=r?.beforeStep,$e=Tt?async he=>{const oe=r?.beforeStepTimeoutMs??a9,Z=fa(oe,this.providerName,"stream"),ae=gB(he.signal,Z?.controller.signal);try{return await td(Promise.resolve(Tt({...he,signal:ae.signal??he.signal})),ae.signal??he.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:he.stepsCompleted});return}finally{ae.dispose(),Z?.cleanup()}}:void 0,{stream:ye,resultPromise:we}=xd(Le,u.messages.slice(),{tools:Pe,...a?{abortSignal:a}:{},...mt?{span:mt}:{},...$e?{beforeStep:$e}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}}),X=(async()=>{for await(const he of ye)he.reasoning&&_({content:"",reasoning:he.reasoning}),he.content&&(m?q+=he.content:_({content:he.content}))})();let W;try{W=await we}catch(he){throw await Sf(X,"Anthropic"),he}if(await X,$+=W.usage.inputTokens,N+=W.usage.outputTokens,F+=W.usage.cacheReadTokens??0,j+=W.usage.cacheWriteTokens??0,z=W.rawStopReason??z,W.aborted){const he=a?.aborted?a.reason:void 0;P.stopReason=he instanceof ja?"time-limit":"aborted",P.finishReason="other",W.rawStopReason&&(P.rawFinishReason=W.rawStopReason),A(V()),I("other");return}P.finishReason=W.finishReason,W.rawStopReason&&(P.rawFinishReason=W.rawStopReason),W.finishReason==="tool-calls"&&G===void 0&&(P.stopReason="step-cap"),A(V()),I(z??"stop")})().catch(Ie=>{throw R=Ie,p.error("Anthropic: Stream error",{error:Ie instanceof Error?Ie.message:String(Ie)}),A(V()),I("error"),this.formatProviderError(Ie)}).finally(()=>{if(m){const Ie=G??q;Ie.length>0&&_({content:Ie})}s?.cleanup(),S.close()});pe.catch(()=>{});const ne=this.providerName;return{stream:async function*(){let Ie=0;try{for await(const Ce of S.iterable)"content"in Ce&&typeof Ce.content=="string"&&Ce.content.length>0&&Ie++,yield Ce;if(await pe,Ie===0&&D.length===0){p.warn(`${ne}: Stream produced no output \u2014 emitting enriched sentinel`);const Ce=new ou({message:"Stream produced no output"}),Ve=await gf(Ce,void 0,R);yf(Ve),yield Ve}}catch(Ce){const Ve=await gf(Ce,void 0,R);if(yf(Ve),yield Ve,!ou.isInstance(Ce))throw Ce}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],metadata:P,analytics:k.then(async()=>{const Ie=await jW.createAnalytics(this.providerName,h,{textStream:(async function*(){})(),usage:C,finishReason:k},Date.now()-U,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),Ce=DDr();return Ce&&Ie&&(this.recordLimitSnapshot(Ce),Ie.limits=Ce),Ie})}}async isAvailable(){try{return TY()||vY(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),BSt={};se(BSt,{ANTHROPIC_BETA_HEADERS:()=>WD,AnthropicProvider:()=>USt,ModelAccessError:()=>q$,getModelCapabilities:()=>iY,getRecommendedModelForTier:()=>sY,isModelAvailableForTier:()=>oY});var ZDr=b({"src/lib/providers/anthropic/index.ts"(){"use strict";XDr(),NSt()}}),Hf,Ws,QDr,eOr,zSt,qSt,GSt,TC,jSt,tOr,rOr,nOr,oOr,sOr,iOr,aOr,cOr,lOr,uOr,dOr,mOr,pOr,hOr,fOr,gOr,yOr,vOr,TOr,wOr,EOr,SOr,bOr,_Or,COr,kOr,AOr,xOr,IOr,ROr,MOr,POr,DOr,OOr,NOr,LOr,FOr,$Or,UOr,HSt=b({"npm-stub:@aws-sdk/client-bedrock-runtime"(){Hf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Hf.get}):new Proxy(function(...r){return new Proxy({},{get:Hf.get})},{get:Hf.get,apply(r,n,o){return new Proxy({},{get:Hf.get})},construct(r,n){return new Proxy({},{get:Hf.get})}})}},Ws=new Proxy({},Hf),{BedrockClient:QDr,ListFoundationModelsCommand:eOr,BedrockRuntimeClient:zSt,ConverseCommand:qSt,ConverseStreamCommand:GSt,ImageFormat:TC,InvokeModelCommand:jSt}=Ws,{SageMakerRuntimeClient:tOr,InvokeEndpointCommand:rOr,InvokeEndpointWithResponseStreamCommand:nOr}=Ws,{GoogleAuth:oOr,VertexAI:sOr,TextToSpeechClient:iOr}=Ws,{Webhook:aOr}=Ws,{Hippocampus:cOr,HippocampusConfig:lOr}=Ws,{createClient:uOr}=Ws,{Queue:dOr,Worker:mOr,Job:pOr,QueueScheduler:hOr,FlowProducer:fOr}=Ws,{Cron:gOr}=Ws,{parseBuffer:yOr,selectCover:vOr}=Ws,{extractRawText:TOr,convertToHtml:wOr}=Ws,{Hono:EOr}=Ws,{cors:SOr,HTTPException:bOr,logger:_Or,secureHeaders:COr,streamSSE:kOr,timeout:AOr}=Ws,xOr=globalThis.fetch,IOr=globalThis.Request,ROr=globalThis.Response,MOr=globalThis.Headers,POr=globalThis.FormData,DOr=globalThis.File,OOr=globalThis.Blob,NOr=Ws.Agent,LOr=Ws.Pool,FOr=Ws.Client,$Or=Ws.Dispatcher,UOr=Ws.MockAgent}});function BOr(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 zOr(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function VSt(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 qOr(e,t){if(e.startsWith("arn:")||zOr(e))return[];const r=[],n=BOr(t);return n&&r.push(`${n}.${e}`),r.push(`${JSt}.${e}`),r}function WSt(e,t){return`${e}::${t}`}function GOr(e,t){return _Y.get(WSt(t,e))}function jOr(e,t,r){_Y.set(WSt(t,e),r),p.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function KSt(e,t,r){const n=GOr(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!VSt(o))throw o;const s=qOr(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 jOr(e,t,i),a}catch(a){if(!VSt(a))throw a}throw o}}var JSt,_Y,HOr=b({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";B(),JSt="global",_Y=new Map}});function KD(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function YSt(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 XSt(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??KD(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function VOr(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,v=g.contentBlockDelta.delta.text;i(y),a+=v,s.set(y,(s.get(y)??"")+v),t.push({content:v})}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??KD()}}if(g.contentBlockDelta?.delta?.toolUse){const y=i(g.contentBlockDelta.contentBlockIndex??0);y.toolUse??={name:"",input:{},toolUseId:KD()};const v=g.contentBlockDelta.delta.toolUse.input;typeof v=="string"?y._inputBuffer=(y._inputBuffer??"")+v:typeof v=="object"&&v!==null&&!Array.isArray(v)&&(y.toolUse.input={...y.toolUse.input??{},...v})}if(g.contentBlockStop){const y=g.contentBlockStop.contentBlockIndex??0;YSt(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)YSt(g,s.get(f)??"");const h=n.filter(f=>f.text||f.toolUse||f.image||f.document);return{text:a,toolCalls:XSt(h),usage:{inputTokens:l,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:m},rawStopReason:c,raw:h}}function WOr(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??KD(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:XSt(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 ZSt(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 KSt(o.modelId??"",e.region,a=>qe(e.client.send(new qSt({...o,modelId:a}),{abortSignal:n}),CY,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return WOr(i)}const s=await KSt(o.modelId??"",e.region,i=>qe(e.client.send(new GSt({...o,modelId:i}),{abortSignal:n}),CY,new Error("Bedrock streaming API call timed out")));return VOr(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 CY,KOr=b({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";HSt(),tt(),HOr(),CY=12e4}});function QSt(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,imageOptions:e.imageOptions,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 JOr=b({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),JD,ebt=b({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";Ja(),JD=Ue.provider}}),tbt={};se(tbt,{Agent:()=>jbt,BedrockClient:()=>nbt,BedrockRuntimeClient:()=>sbt,Blob:()=>Gbt,Client:()=>Vbt,ConverseCommand:()=>ibt,ConverseStreamCommand:()=>abt,Cron:()=>Cbt,Dispatcher:()=>Wbt,File:()=>qbt,FlowProducer:()=>_bt,FormData:()=>zbt,GoogleAuth:()=>pbt,HTTPException:()=>Pbt,Headers:()=>Bbt,Hippocampus:()=>ybt,HippocampusConfig:()=>vbt,Hono:()=>Rbt,ImageFormat:()=>cbt,InvokeEndpointCommand:()=>dbt,InvokeEndpointWithResponseStreamCommand:()=>mbt,InvokeModelCommand:()=>lbt,Job:()=>Sbt,ListFoundationModelsCommand:()=>obt,MockAgent:()=>Ybt,Pool:()=>Hbt,Queue:()=>wbt,QueueScheduler:()=>bbt,Request:()=>$bt,Response:()=>Ubt,SageMakerRuntimeClient:()=>ubt,TextToSpeechClient:()=>fbt,VertexAI:()=>hbt,Webhook:()=>gbt,Worker:()=>Ebt,convertToHtml:()=>Ibt,cors:()=>Mbt,createClient:()=>Tbt,default:()=>rbt,extractRawText:()=>xbt,fetch:()=>Fbt,getGlobalDispatcher:()=>Jbt,interceptors:()=>Xbt,logger:()=>Dbt,parseBuffer:()=>kbt,request:()=>Zbt,secureHeaders:()=>Obt,selectCover:()=>Abt,setGlobalDispatcher:()=>Kbt,streamSSE:()=>Nbt,timeout:()=>Lbt});var Vf,ls,rbt,nbt,obt,sbt,ibt,abt,cbt,lbt,ubt,dbt,mbt,pbt,hbt,fbt,gbt,ybt,vbt,Tbt,wbt,Ebt,Sbt,bbt,_bt,Cbt,kbt,Abt,xbt,Ibt,Rbt,Mbt,Pbt,Dbt,Obt,Nbt,Lbt,Fbt,$bt,Ubt,Bbt,zbt,qbt,Gbt,jbt,Hbt,Vbt,Wbt,Kbt,Jbt,Ybt,Xbt,Zbt,YOr=b({"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})}})}},ls=new Proxy({},Vf),rbt=ls,{BedrockClient:nbt,ListFoundationModelsCommand:obt,BedrockRuntimeClient:sbt,ConverseCommand:ibt,ConverseStreamCommand:abt,ImageFormat:cbt,InvokeModelCommand:lbt}=ls,{SageMakerRuntimeClient:ubt,InvokeEndpointCommand:dbt,InvokeEndpointWithResponseStreamCommand:mbt}=ls,{GoogleAuth:pbt,VertexAI:hbt,TextToSpeechClient:fbt}=ls,{Webhook:gbt}=ls,{Hippocampus:ybt,HippocampusConfig:vbt}=ls,{createClient:Tbt}=ls,{Queue:wbt,Worker:Ebt,Job:Sbt,QueueScheduler:bbt,FlowProducer:_bt}=ls,{Cron:Cbt}=ls,{parseBuffer:kbt,selectCover:Abt}=ls,{extractRawText:xbt,convertToHtml:Ibt}=ls,{Hono:Rbt}=ls,{cors:Mbt,HTTPException:Pbt,logger:Dbt,secureHeaders:Obt,streamSSE:Nbt,timeout:Lbt}=ls,Fbt=globalThis.fetch,$bt=globalThis.Request,Ubt=globalThis.Response,Bbt=globalThis.Headers,zbt=globalThis.FormData,qbt=globalThis.File,Gbt=globalThis.Blob,jbt=ls.Agent,Hbt=ls.Pool,Vbt=ls.Client,Wbt=ls.Dispatcher,Kbt=()=>{},Jbt=()=>ls,Ybt=ls.MockAgent,Xbt={redirect:()=>e=>e,retry:()=>e=>e},Zbt=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 kY(){return await Promise.resolve().then(()=>(YOr(),tbt))}var Qbt=b({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}});function XOr(e){const t=(e??"").split(";").at(0)?.trim().toLowerCase();return AY[t??""]}var AY,e_t,ZOr=b({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";HSt(),hr(),pb(),ec(),Do(),vP(),jm(),Ic(),KOr(),ct(),ci(),tt(),sf(),B(),id(),N4(),JOr(),di(),Yt(),ebt(),Qbt(),AY={"image/png":"png","image/jpeg":"jpeg","image/jpg":"jpeg","image/gif":"gif","image/webp":"webp"},e_t=class oar extends _a{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=oar.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 zSt({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 kY(),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 f=QSt(n,this.providerName,this.modelName),g=await P4(f,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(g)}else{p.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const h={role:"user",content:[{text:n.prompt||o?.text||""}]};this.conversationHistory.push(h)}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(h){const f=this.neurolink?.getEventEmitter();throw f&&(f.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:h instanceof Error?h.message:String(h)}),h&&typeof h=="object"&&(h._generationEndEmitted=!0)),h}const d=this.neurolink?.getEventEmitter();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});const m={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(h=>h.error===void 0).map(h=>h.name),toolCalls:u.map(h=>({toolCallId:h.id,toolName:h.name,args:h.input})),toolExecutions:Wh(n,fd(u)),enhancedWithTools:u.some(h=>h.error===void 0)};return m._generationEndEmitted=!0,m}async conversationLoop(t){const r=t.maxSteps||zs,n=await this.resolveTurnTools(t.tools,t.disableTools),o=this.formatToolsForBedrock(n),s=ml(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converse"),i=ZSt({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}=xd(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 JD.startActiveSpan("bedrock.tool.execute",{kind:zr.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:Fe.OK}),u}catch(i){throw p.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:i}),s.setStatus({code:Fe.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=No(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"?TC.JPEG:i==="png"?TC.PNG:i==="gif"?TC.GIF:TC.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?Nm.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"),JD.startActiveSpan("bedrock.stream",{kind:zr.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=QSt(t,this.providerName,this.modelName),i=await P4(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:Fe.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:Fe.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:Fe.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:Fe.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||zs,s=await this.resolveTurnTools(t.tools,t.disableTools),i=this.formatToolsForBedrock(s),a=ml(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converseStream"),c=ZSt({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,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,...a.temperature!==void 0&&{temperature:a.temperature}},...i?{toolConfig:i}:{}})});let l=!1,u;const d=new Promise(A=>{u=()=>{l=!0,A()}}),m={...c,executeStep:async(A,I,R)=>{const M=await c.executeStep(A,I,R);return u(),M}};r.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});const{stream:h,resultPromise:f}=xd(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:t.abortSignal,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}}),g=f.then(A=>({result:A,error:void 0}),A=>({result:void 0,error:A}));if(await Promise.race([d,g]),!l){const A=await g;if(A.error)throw A.error}const y=this.neurolink?.getEventEmitter(),v=this,w={startTime:n,streamId:`bedrock-${Date.now()}`};let S;const _=new Promise(A=>{S=A}),C=A=>{const I=A?.inputTokens??0,R=A?.outputTokens??0,M=A?.cacheReadTokens??0,D=A?.cacheWriteTokens??0;return{input:I,output:R,total:I+M+D+R,...M>0&&{cacheReadTokens:M},...D>0&&{cacheCreationTokens:D}}};return g.then(A=>{S(p0(this.providerName,this.modelName||this.getDefaultModel(),{usage:C(A.result?.usage),toolExecutions:A.result?.toolExecutions??[],toolsUsed:(A.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 A=!1;try{yield*h}catch(I){throw A=!0,I}finally{const I=await g;I.error&&(A=!0);const R=C(I.result?.usage);if(I.result&&(v.conversationHistory=I.result.conversation,w.finishReason=I.result.finishReason,w.rawFinishReason=I.result.rawStopReason,r.setAttribute("gen_ai.response.stop_reason",I.result.rawStopReason??"unknown")),y){const M=t._streamDedupContext;M&&(M.providerEmitted=!0),y.emit("generation:end",{provider:v.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:R,model:v.modelName||v.getDefaultModel(),provider:v.providerName,finishReason:A?"error":I.result?.rawStopReason},success:!A})}}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:_,metadata:w}}async checkBedrockHealth(){const t=new AbortController,r=setTimeout(()=>t.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await kY(),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(ar(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 ki(t,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:kr,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:vs,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:Xe,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:Xe,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(t,r){const n=typeof t=="string"?{text:t}:t,o=r||this.getDefaultEmbeddingModel(),s=o.includes("nova")&&o.includes("multimodal"),i=o.includes("image")||o.includes("multimodal")||o==="amazon.titan-embed-image-v1"||s;p.debug("Generating embedding",{provider:this.providerName,model:o,hasText:typeof n.text=="string",hasImage:n.image!==void 0,isMultiModalModel:i});try{let a;if(n.image&&!i)throw new Xe(`${this.providerName} model ${o} does not support image embeddings`,this.providerName);if(s){if(n.image&&n.text)throw new Xe(`${this.providerName} model ${o} does not support combined image+text embeddings; provide exactly one of image or text`,this.providerName);const m={embeddingPurpose:"GENERIC_RETRIEVAL"};if(n.image){const h=Buffer.isBuffer(n.image)?n.image:Buffer.from(n.image,"base64"),f=XOr(n.mimeType);if(f===void 0)throw new Xe(`${this.providerName} model ${o} does not support image format '${n.mimeType??"unknown"}'; supported formats are ${Object.keys(AY).join(", ")}`,this.providerName);m.image={detailLevel:"STANDARD_IMAGE",format:f,source:{bytes:wo.safeBase64Convert(h,"bedrock nova embed image")}}}n.text&&(m.text={value:n.text,truncationMode:"NONE"}),a=JSON.stringify({taskType:"SINGLE_EMBEDDING",singleEmbeddingParams:m})}else if(n.image){const m=Buffer.isBuffer(n.image)?n.image:Buffer.from(n.image,"base64");a=JSON.stringify({inputText:n.text??"",inputImage:wo.safeBase64Convert(m,"bedrock titan embed image")})}else a=JSON.stringify({inputText:n.text??""});const c=new jSt({modelId:o,contentType:"application/json",accept:"application/json",body:a}),l=await qe(this.bedrockClient.send(c),6e4,new Error("Bedrock embedding API call timed out")),u=JSON.parse(new TextDecoder().decode(l.body)),d=s?u.embeddings?.at(0)?.embedding:u.embedding;if(!Array.isArray(d))throw new Error("Invalid embedding response from Bedrock");return p.debug("Embedding generated successfully",{provider:this.providerName,model:o,embeddingDimension:d.length}),d}catch(a){throw p.error("Embedding generation failed",{error:a instanceof Error?a.message:String(a),model:o}),this.handleProviderError(a)}}async embedMany(t,r){const n=r||this.getDefaultEmbeddingModel();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)}}}}}),t_t={};se(t_t,{AmazonBedrockProvider:()=>e_t,bedrockTracer:()=>JD,loadBedrockControl:()=>kY});var QOr=b({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";ZOr(),ebt(),Qbt()}}),r_t={};se(r_t,{AzureOpenAIProvider:()=>n_t});var n_t,eNr=b({"src/lib/providers/azureOpenai.ts"(){"use strict";ct(),B(),ci(),qo(),Ic(),rc(),dp(),n_t=class extends Aa{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||Ai(Zhr()),d||Ai(Qhr()),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",AUe({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:kr,message:"Invalid Azure OpenAI API key or endpoint."},...ya];return ki(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??lgt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function xY(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"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&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97?"image/gif":null}function wC(e){return xY(e)??"image/png"}var YD=b({"src/lib/utils/imageDetection.ts"(){"use strict"}});function o_t(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 tNr=b({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),XD,rNr=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs"(){XD=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}}}),nNr=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs"(){So()}});function IY(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var ZD,RY,s_t=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs"(){nNr(),ZD=e=>(ZD=Array.isArray,ZD(e)),RY=ZD}});function*oNr(e){if(!e)return;if(MY 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():RY(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=RY(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 MY,i_t,sNr=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){s_t(),MY=Symbol.for("brand.privateNullableHeaders"),i_t=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[s,i]of oNr(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{[MY]:!0,values:t,nulls:r}}}});function iNr(e){const t=new lC(e);return delete t.batches,t}function aNr(e){const t=new ta(e);return delete t.messages.batches,t}var a_t,c_t,PY,l_t=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){UD(),uTt(),p_(),rNr(),s_t(),sNr(),UD(),a_t="vertex-2023-10-16",c_t=new Set(["/v1/messages","/v1/messages?beta=true"]),PY=class extends xo{constructor({baseURL:e=XD("ANTHROPIC_VERTEX_BASE_URL"),region:t=XD("CLOUD_ML_REGION")??null,projectId:r=XD("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=iNr(this),this.beta=aNr(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 iP({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=i_t([r,e.headers])}async buildRequest(e){if(IY(e.body)&&(e.body={...e.body}),IY(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=a_t)),c_t.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(!IY(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)}}}}),DY={};se(DY,{AnthropicVertex:()=>PY,BaseAnthropic:()=>xo,default:()=>PY});var u_t=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){l_t(),l_t()}});async function cNr(){return QD||(QD=await Promise.resolve().then(()=>(u_t(),DY))),QD}function lNr(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 OY(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 uNr(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 dNr(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 NY(e){const t=[];let r=0;for(const n of lNr(e)){if(n.type==="regular"){OY(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:s}=uNr(n,r);o.length!==0&&(r++,OY(t,"assistant",o),OY(t,"user",s))}if(dNr(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 LY(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 d_t(e,t,r){const n=uft({contents:e,availableInputTokens:El("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<=y_t?l:{functionResponse:{name:u.name,response:{result:rW(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:oW}]})}return e.length=0,e.push(...i),!0}function m_t(e,t,r){const n=_St({conversation:e,availableInputTokens:El("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:bSt(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:lY}]})}return e.length=0,e.push(...i),!0}async function p_t(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 v of g.parts)n.push(v),typeof v.text=="string"&&v.text.length>0&&t.push({content:v.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 v=Math.min(y.cachedContentTokenCount??0,y.promptTokenCount);r.onUsageDelta?.("cacheRead",v-c),c=v}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 QD,h_t,FY,EC,$Y,_v,Kf,f_t,g_t,eO,y_t,UY,mNr=b({"src/lib/providers/googleVertex/client.ts"(){"use strict";on(),dP(),hr(),ec(),u7(),gP(),z7(),Do(),qh(),Hh(),tW(),Ut(),Mn(),ct(),ci(),tt(),dY(),bdt(),N4(),B(),W9(),mft(),CSt(),rP(),YD(),N9(),qo(),di(),Jht(),bf(),ga(),pft(),oft(),vP(),DSt(),l_(),W0(),iW(),Sl(),wb(),Ja(),Yt(),Ya(),Ic(),jm(),id(),tNr(),l_(),QD=null,h_t=()=>!0,FY=()=>Ai(cfr()),EC=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",$Y=(e,t)=>{const r=t||EC();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||rz.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},_v=$Y,Kf=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",f_t=()=>!!(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),g_t=async(e,t,r,n)=>{const o=e||EC();return{projectId:r?r.projectId?.trim()||"express":FY(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},eO=e=>e.toLowerCase().includes("claude"),y_t=2048,UY=class Xr extends _a{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||f_t()||Ai(lfr()),this.projectId=s?.projectId||(i?"":FY()),this.location=o||s?.location||EC(),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 Kf()}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&&jV(t.input),t.input?.files?.length)try{await HV(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 s_(t.input)}async executeStream(t,r){const n=t.model||this.modelName||Kf();return yNe({name:"neurolink.provider.stream",tracer:Ue.provider,attributes:{[be.GEN_AI_SYSTEM]:this.providerName,[be.GEN_AI_MODEL]:n,[be.GEN_AI_OPERATION]:"stream",[be.NL_PROVIDER]:this.providerName}},async o=>{const s=Date.now(),i=t.tools||{};await this.preprocessNativeFileInput(t);const c={...await ut({name:"neurolink.message.build",tracer:Ue.provider,attributes:{[be.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;eO(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){Eft("GoogleVertex");const r=this.resolveExpressApiKey(),n=r?"":this.projectId,o=t||this.location||EC(),i=(await Promise.resolve().then(()=>(OS(),e0))).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=No(s),a=Wn(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=pBe(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=No(t),n=Wn(r);n.$schema&&delete n.$schema;const o=Wi(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||Kf(),n=_v(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 ye of a.pdfFiles){let we;typeof ye=="string"?Oo.existsSync(ye)?we=Oo.readFileSync(ye):we=Buffer.from(ye,"base64"):we=ye;const X=we.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:X}})}}if(await X9(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){p.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(const ye of a.images){const we=Bb(ye);let X,W="image/jpeg";if(typeof we=="string")if(Oo.existsSync(we)){X=Oo.readFileSync(we);const oe=Hb(we);W=oe.startsWith("image/")?oe:this.detectImageType(X)}else if(we.startsWith("data:")){const oe=we.match(/^data:([^;]+);base64,(.+)$/);if(oe)W=oe[1],X=Buffer.from(oe[2],"base64");else continue}else if(we.startsWith("http://")||we.startsWith("https://"))try{const oe=await fetch(we);if(!oe.ok){p.warn(`[GoogleVertex] Image fetch failed: ${oe.status} ${oe.statusText}, skipping`,{url:mr(we)});continue}const Z=await oe.arrayBuffer();X=Buffer.from(Z);const ae=oe.headers.get("content-type");ae&&ae.startsWith("image/")&&(W=ae.split(";")[0])}catch(oe){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${oe instanceof Error?oe.message:String(oe)}`,{url:mr(we)});continue}else X=Buffer.from(we,"base64"),W=this.detectImageType(X);else X=we,W=this.detectImageType(X);const he=X.toString("base64");i.push({inlineData:{mimeType:W,data:he}})}}hP(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 ye=K0(t.tools,"functionDeclarations");u=ye,c=ye.toolsConfig;for(const[we,X]of ye.executeMap)l.set(we,X);p.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ye.toolsConfig[0].functionDeclarations.length,toolNames:ye.toolsConfig[0].functionDeclarations.map(we=>we.name)})}const d=t;let m=!1;if(d.schema&&c){m=!0;const ye=No(d.schema,"openApi3"),we=Wn(ye);we.$schema&&delete we.$schema;const X=Wi(we),W=c[0]?.functionDeclarations||[];W.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:X}),c=[{functionDeclarations:W}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(X),totalTools:W.length})}const h=ml(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};O9(r)&&(f.maxOutputTokens&&f.maxOutputTokens>ba&&(p.warn(`[GoogleVertex] Capping maxOutputTokens from ${f.maxOutputTokens} to ${ba} for ${r}`),f.maxOutputTokens=ba),f.maxOutputTokens||(f.maxOutputTokens=ba)),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+`
1079
1079
 
1080
1080
  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=K9(t.thinkingConfig,r);if(y&&(f.thinkingConfig=y),(d.output?.format==="json"||d.schema)&&!m&&!c&&(f.responseMimeType="application/json",d.schema)){const ye=No(d.schema,"openApi3"),we=Wn(ye);we.$schema&&delete we.$schema;const X=Wi(we);Wf(X),f.responseSchema=X,p.debug("[GoogleVertex] Added responseSchema for JSON output (stream)",{schemaKeys:Object.keys(X)})}const v=Date.now(),w=t.maxSteps||zs,S=Number.isFinite(w)&&w>0?Math.min(Math.floor(w),100):Math.min(zs,100),_=[...s];let C="",k;const A=[],I=[];let R;const M=j0(wd("vertex",r));let D=!1,U=0,P=0,$=0,N=0;const F=[],j=ll(t.timeout)??uS,z=Th(t.toolTimeoutMs),V=t.turnTimeoutMs??j,q=new AbortController,G=()=>q.abort();t.abortSignal?.addEventListener("abort",G);const J=G0({turnTimeoutMs:t.turnTimeoutMs,defaultTurnTimeoutMs:j,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:ye=>{p.warn(ye==="timeout"?`[GoogleVertex] Native Gemini turn exceeded its ${V}ms time budget \u2014 aborting`:`[GoogleVertex] Native Gemini turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),q.abort()}}),re=q.signal;t.abortSignal?.aborted&&q.abort();let pe=!1,ne=!1,ie=!1,Ie=0;try{const ye=yP({providerLabel:"GoogleVertex",maxSteps:S,toolFailureBreaker:{maxRetries:wh,consecutive:!0,classifyResultFailure:ae=>V4(ae)??void 0},liveTools:t.tools??{},toolGuards:{toolTimeoutMs:z,abortSignal:re,onProgress:()=>J.noteProgress()},...u?{declarations:u}:{},...m?{finalResultToolName:"final_result",onTerminalResult:ae=>{try{R=JSON.parse(ae)}catch{}}}:{},enableMalformedRetry:!0,buildMalformedRetryNote:(ae,Q)=>(this.emitTurnEvent({phase:"malformed-retry",step:Q+1,maxSteps:S}),[...ae,{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:(ae,Q)=>p_t(ae,Q,{onProgress:()=>J.noteProgress(),onUsage:(ce,ve)=>M.noteUsage(ce,ve),onUsageDelta:(ce,ve)=>{ce==="input"?U+=ve:ce==="output"?P+=ve:ce==="cacheRead"?$+=ve:N+=ve}}),planReclaim:ae=>{if(!M.shouldStop())return;const Q=[...ae];return d_t(Q,r,M.projectedNextPromptTokens)?(M.resetAfterReclaim(),{conversation:Q}):(D=!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:ae=>({model:r,contents:ae,config:{...f,...c?{tools:c}:{}}}),sendStep:async(ae,Q)=>{J.noteProgress();const ce=ae;return o.models.generateContentStream({model:ce.model,contents:ce.contents,config:{...ce.config??{},abortSignal:Q}})}}),we={...ye,buildStepRequest:(ae,Q)=>(Ie=Q+1,ye.buildStepRequest(ae,Q)),buildToolResultMessages:(ae,Q,ce,ve)=>{const Re=ye.buildToolResultMessages(ae,Q,ce,ve);if(J.shouldNudgeWrapup()){const K=Re[Re.length-1];K&&Array.isArray(K.parts)&&K.parts.push({text:z0(m)})}const x=pP(Q.raw.rawResponseParts);_t(this.handleToolExecutionStorage(ce.map((K,Ee)=>({toolName:K.name,args:K.args,...Ee===0&&x?{thoughtSignature:x}:{},stepIndex:ve+1})),ce.map(K=>({toolName:K.name,output:K.output,stepIndex:ve+1})),t,new Date),Eh,"tool storage write timed out").catch(K=>{p.warn("[GoogleVertex] Failed to store native Gemini stream tool executions",{error:K instanceof Error?K.message:String(K)})});try{const K=Re[Re.length-1];M.noteAppendedChars(JSON.stringify(K?.parts??[]).length)}catch{}return Re}},{stream:X,resultPromise:W}=xd(we,_,{tools:mP(u,t.tools,{toolTimeoutMs:z,abortSignal:re,onProgress:()=>J.noteProgress()}),abortSignal:re,toolTimeoutMs:z}),he=(async()=>{for await(const ae of X)ae.content&&F.push(ae.content)})();let oe,Z;try{oe=await W}catch(ae){Z=ae}if(await Sf(he,"GoogleVertex"),Z!==void 0)if(re.aborted||cp(Z))pe=!0;else throw p.error("[GoogleVertex] Native SDK error",Z),this.handleProviderError(Z);if(oe){C=oe.text,k=oe.rawStopReason??k;for(const ae of oe.toolCalls)A.push({toolName:ae.name,args:ae.args});for(const ae of oe.toolExecutions)I.push({name:ae.name,input:ae.input,output:ae.output});_.length=0,_.push(...oe.conversation)}if(re.aborted&&(pe=!0),!C&&(Ie>=S||pe||D)){ne=Ie>=S&&!pe;const ae=A.filter(Q=>Q.toolName!=="final_result").length;if(F.length>0)p.warn(D?"[GoogleVertex] Tool call loop stopped by the context guard; returning text already gathered from prior steps.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${S}); returning text already gathered from prior steps.`);else if(pe)p.warn(`[GoogleVertex] Tool call loop ended mid-turn (${J.timedOut?"turn time limit":J.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),C=this.buildLoopExitMessage({turnClock:J,wasAborted:pe,stallTimeoutMs:t.stallTimeoutMs,maxSteps:S,toolCallCount:ae});else{p.warn(D?"[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 (${S}) with no text; synthesizing a final answer with tools disabled.`);const Q=await this.synthesizeFinalAnswerWithoutTools(o,r,f,_,m,ll(t.timeout)??uS,re);Q.text?(ie=!0,C=Q.text,F.push(Q.text),U+=Q.inputTokens,P+=Q.outputTokens,N+=Q.reasoningTokens??0,Q.finishReason&&(k=Q.finishReason)):C=D?Nc(ae):lp(S,ae)}}}finally{J.dispose(),t.abortSignal?.removeEventListener("abort",G)}const Ce=ne&&!ie?"tool-calls":y_(k),Ve=q0({timedOut:J.timedOut,stalled:J.stalled,wasAborted:pe,cappedWithoutAnswer:ne&&!ie,contextCappedWithoutAnswer:D&&!ie,finishReason:Ce});Ve!=="completed"&&this.emitTurnEvent({phase:Ve,step:Ie,maxSteps:S,toolCallCount:A.filter(ye=>ye.toolName!=="final_result").length,elapsedMs:J.elapsedMs()});const xe=Date.now()-v,De=R?[C]:F.length>0?F:[C];async function*Le(){for(const ye of De)ye.length>0&&(yield{content:ye})}const Pe=A.filter(ye=>ye.toolName!=="final_result"),mt=I.filter(ye=>ye.name!=="final_result"),Tt=Math.max(0,U-$),$e={stream:Le(),provider:this.providerName,model:r,finishReason:Ce,stopReason:Ve,rawFinishReason:k,usage:{input:Tt,output:P+N,total:Tt+$+P+N,...$>0&&{cacheReadTokens:$},...N>0&&{reasoning:N}},toolCalls:Pe.map(ye=>({toolName:ye.toolName,args:ye.args})),toolsUsed:Pe.map(ye=>ye.toolName),toolExecutions:fd(mt),metadata:{streamId:`native-vertex-${Date.now()}`,startTime:v,responseTime:xe,totalToolExecutions:Pe.length,stopReason:Ve,rawFinishReason:k,stepsUsed:Ie}};return R&&($e.structuredOutput=R),$e}async executeNativeGemini3Generate(t){const r=t.model||this.modelName||Kf(),n=_v(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 $e of c.pdfFiles){let ye;typeof $e=="string"?Oo.existsSync($e)?ye=Oo.readFileSync($e):ye=Buffer.from($e,"base64"):ye=$e;const we=ye.toString("base64");a.push({inlineData:{mimeType:"application/pdf",data:we}})}}if(await X9(a,c?.nativeAudioFiles,"[GoogleVertex]"),c?.images&&c.images.length>0){p.debug(`[GoogleVertex] Processing ${c.images.length} image(s) for native generate`);for(const $e of c.images){const ye=Bb($e);let we,X="image/jpeg";if(typeof ye=="string")if(Oo.existsSync(ye)){we=Oo.readFileSync(ye);const he=Hb(ye);X=he.startsWith("image/")?he:this.detectImageType(we)}else if(ye.startsWith("data:")){const he=ye.match(/^data:([^;]+);base64,(.+)$/);if(he)X=he[1],we=Buffer.from(he[2],"base64");else continue}else if(ye.startsWith("http://")||ye.startsWith("https://"))try{const he=await fetch(ye);if(!he.ok){p.warn(`[GoogleVertex] Image fetch failed: ${he.status} ${he.statusText}, skipping`,{url:mr(ye)});continue}const oe=await he.arrayBuffer();we=Buffer.from(oe);const Z=he.headers.get("content-type");Z&&Z.startsWith("image/")&&(X=Z.split(";")[0])}catch(he){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${he instanceof Error?he.message:String(he)}`,{url:mr(ye)});continue}else we=Buffer.from(ye,"base64"),X=this.detectImageType(we);else we=ye,X=this.detectImageType(we);const W=we.toString("base64");a.push({inlineData:{mimeType:X,data:W}})}}hP(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 $e=K0(l,"functionDeclarations");m=$e,u=$e.toolsConfig;for(const[ye,we]of $e.executeMap)d.set(ye,we);p.debug("[GoogleVertex] Converted tools for native SDK generate",{toolCount:$e.toolsConfig[0].functionDeclarations.length,toolNames:$e.toolsConfig[0].functionDeclarations.map(ye=>ye.name)})}let h=!1;if(t.schema&&u){h=!0;const $e=No(t.schema,"openApi3"),ye=Wn($e);ye.$schema&&delete ye.$schema;const we=Wi(ye),X=u[0]?.functionDeclarations||[];X.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:we}),u=[{functionDeclarations:X}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (generate)",{schemaKeys:Object.keys(we),totalTools:X.length})}const f=ml(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};O9(r)&&(g.maxOutputTokens&&g.maxOutputTokens>ba&&(p.warn(`[GoogleVertex] Capping maxOutputTokens from ${g.maxOutputTokens} to ${ba} for ${r}`),g.maxOutputTokens=ba),g.maxOutputTokens||(g.maxOutputTokens=ba)),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+`
1081
1081
 
@@ -215,9 +215,19 @@ export async function runNativeGenerateLoop(args, toolExecutionSummaries) {
215
215
  rawFinishReason = shaped.raw ?? rawFinishReason;
216
216
  }
217
217
  const usage = res.usage;
218
- inputTokens += readTotal(usage?.inputTokens);
219
218
  outputTokens += readTotal(usage?.outputTokens);
220
219
  const inShaped = usage?.inputTokens;
220
+ // `total` on the shaped input-tokens object is cache-INCLUSIVE (noCache +
221
+ // cacheRead + cacheWrite). Accumulating it into `inputTokens` — while ALSO
222
+ // accumulating cacheRead/cacheWrite below — double-billed every cached
223
+ // token: once folded into `input`, once again as the flat cache fields
224
+ // `calculateCost` prices separately. `noCache` is the disjoint figure
225
+ // `calculateCost` expects; fall back to the inclusive total only when a
226
+ // provider hasn't populated `noCache` (i.e. it never reports cache usage).
227
+ inputTokens +=
228
+ typeof inShaped?.noCache === "number"
229
+ ? inShaped.noCache
230
+ : readTotal(usage?.inputTokens);
221
231
  cacheReadTokens += inShaped?.cacheRead ?? 0;
222
232
  cacheWriteTokens += inShaped?.cacheWrite ?? 0;
223
233
  const calls = parts.filter((p) => p.type === "tool-call");
@@ -1564,7 +1564,13 @@ export class AnthropicProvider extends BaseProvider {
1564
1564
  usage: {
1565
1565
  input: loop.inputTokens,
1566
1566
  output: loop.outputTokens,
1567
- total: loop.inputTokens + loop.outputTokens,
1567
+ // `inputTokens` is now the disjoint (uncached) figure, so cache
1568
+ // tokens must be added back in to keep `total` billing-complete —
1569
+ // they are additive on top of input under Anthropic's convention.
1570
+ total: loop.inputTokens +
1571
+ loop.outputTokens +
1572
+ loop.cacheReadTokens +
1573
+ loop.cacheWriteTokens,
1568
1574
  ...(loop.cacheReadTokens
1569
1575
  ? { cacheReadTokens: loop.cacheReadTokens }
1570
1576
  : {}),
@@ -1055,7 +1055,14 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
1055
1055
  usage: {
1056
1056
  input: inputTokens,
1057
1057
  output: outputTokens,
1058
- total: inputTokens + outputTokens,
1058
+ // `inputTokens` is the disjoint (uncached) figure — doGenerate
1059
+ // already subtracts the overlapping prompt_tokens_details.cached_tokens
1060
+ // subset before handing it to the loop — so cache tokens must be
1061
+ // added back in here to keep `total` billing-complete.
1062
+ total: inputTokens +
1063
+ outputTokens +
1064
+ loop.cacheReadTokens +
1065
+ loop.cacheWriteTokens,
1059
1066
  // doGenerate reads prompt_tokens_details.cached_tokens, and the loop
1060
1067
  // carries the counters out; discarding them here billed cached input
1061
1068
  // at the full rate in calculateCost and made cache effectiveness
@@ -1492,10 +1499,18 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
1492
1499
  if (!loopPromise) {
1493
1500
  const input = part.usage.inputTokens.total ?? 0;
1494
1501
  const output = part.usage.outputTokens.total ?? 0;
1502
+ // `total` is cache-INCLUSIVE (OpenAI-style prompt_tokens), so the
1503
+ // cached portion has to be split out here the same way
1504
+ // doGenerate/toDeferredUsage do — otherwise this branch bills the
1505
+ // cached tokens at the full input rate instead of the cheaper
1506
+ // cacheRead rate. Clamped like the other call sites in this file
1507
+ // in case a gateway reports cacheRead > total.
1508
+ const cacheRead = Math.min(part.usage.inputTokens.cacheRead ?? 0, input);
1495
1509
  resolveUsage({
1496
- promptTokens: input,
1510
+ promptTokens: input - cacheRead,
1497
1511
  completionTokens: output,
1498
1512
  totalTokens: input + output,
1513
+ ...(cacheRead > 0 ? { cacheReadTokens: cacheRead } : {}),
1499
1514
  });
1500
1515
  resolveFinish(part.finishReason.unified);
1501
1516
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "12.23.2",
3
+ "version": "12.23.3",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002/call) for routing, tool selection and context budgeting. MCP-native (4 transports), voice TTS/STT/realtime, RAG, agents, memory, compaction, 9 observability exporters. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · TypeSafe Jev and more.",
6
6
  "author": {
@@ -99,6 +99,7 @@
99
99
  "test:openai-compat-streaming-retry": "pnpm exec tsx test/continuous-test-suite-openai-compat-streaming-retry.ts",
100
100
  "test:anthropic-streaming-retry": "pnpm exec tsx test/continuous-test-suite-anthropic-streaming-retry.ts",
101
101
  "test:anthropic-silent-truncation": "pnpm exec tsx test/continuous-test-suite-anthropic-silent-truncation.ts",
102
+ "test:cache-cost-accounting": "pnpm exec tsx test/continuous-test-suite-cache-cost-accounting.ts",
102
103
  "test:adjust-body-after-400": "pnpm exec tsx test/continuous-test-suite-adjust-body-after-400.ts",
103
104
  "test:zod3-schema-native-path": "pnpm exec tsx test/continuous-test-suite-zod3-schema-native-path.ts",
104
105
  "test:error-classification-e2e": "pnpm exec tsx test/continuous-test-suite-error-classification-e2e.ts",