@mcp-use/inspector 0.5.0 → 0.5.1

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.
@@ -1,2 +1,2 @@
1
- import{i as ne,t as fe,a as he,b as pe,C as ge,c as me,d as Ce,e as ye,f as oe,g as se,h as ie,j as _e,k as Ee,p as A,B as ve,l as we,O as Te,m as Ie,n as Oe,J as Re,R as D,o as Se}from"./index-BQq1v1lw.js";import{v as ae}from"./index-C8x1o6em.js";import"./embeddings-BhJwfRpR.js";import"./chunk-VL2OQCWN-BSY6s1ZW.js";import"./index-DRz5BQNA.js";function _(e){if(typeof e=="object"&&e!==null){const n={...e};"additionalProperties"in n&&delete n.additionalProperties,"$schema"in n&&delete n.$schema,"strict"in n&&delete n.strict;for(const t in n)t in n&&(Array.isArray(n[t])?n[t]=n[t].map(_):typeof n[t]=="object"&&n[t]!==null&&(n[t]=_(n[t])));return n}return e}function N(e){const n=_(ne(e)?fe(e):e),{$schema:t,...o}=n;return o}function Ae(e){const n=_(e),{$schema:t,...o}=n;return o}function Ne(e){const n=e._getType();return Ce.isInstance(e)?e.role:n==="tool"?n:e.name??n}function be(e){switch(e){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${e}`)}}function Me(e){if("mimeType"in e&&"data"in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if("mimeType"in e&&"fileUri"in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw new Error("Invalid media content")}function xe(e,n){return n.map(t=>oe(t)?t.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function De(e){return{providerName:"Google Gemini",fromStandardTextBlock(t){return{text:t.text}},fromStandardImageBlock(t){if(!e)throw new Error("This model does not support images");if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw new Error("This model does not support audio");if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw new Error("This model does not support files");if(t.source_type==="text")return{text:t.text};if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)}}}function G(e,n){if(_e(e))return Ee(e,De(n));if(e.type==="text")return{text:e.text};if(e.type==="executableCode")return{executableCode:e.executableCode};if(e.type==="codeExecutionResult")return{codeExecutionResult:e.codeExecutionResult};if(e.type==="image_url"){if(!n)throw new Error("This model does not support images");let t;if(typeof e.image_url=="string")t=e.image_url;else if(typeof e.image_url=="object"&&"url"in e.image_url)t=e.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[o,s]=t.split(",");if(!o.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[i,a]=o.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:s,mimeType:i}}}else{if(e.type==="media")return Me(e);if(e.type==="tool_use")return{functionCall:{name:e.name,args:e.input}};if(e.type?.includes("/")&&e.type.split("/").length===2&&"data"in e&&typeof e.data=="string")return{inlineData:{mimeType:e.type,data:e.data}};if("functionCall"in e)return;throw"type"in e?new Error(`Unknown content type ${e.type}`):new Error(`Unknown content ${JSON.stringify(e)}`)}}function Ge(e,n,t){if(ye(e)){const i=e.name??xe(e,t);if(i===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const a=Array.isArray(e.content)?e.content.map(c=>G(c,n)).filter(c=>c!==void 0):e.content;return e.status==="error"?[{functionResponse:{name:i,response:{error:{details:a}}}}]:[{functionResponse:{name:i,response:{result:a}}}]}let o=[];const s=[];return typeof e.content=="string"&&e.content&&s.push({text:e.content}),Array.isArray(e.content)&&s.push(...e.content.map(i=>G(i,n)).filter(i=>i!==void 0)),oe(e)&&e.tool_calls?.length&&(o=e.tool_calls.map(i=>({functionCall:{name:i.name,args:i.args}}))),[...s,...o]}function k(e,n,t=!1){return e.reduce((o,s,i)=>{if(!he(s))throw new Error("Unsupported message input");const a=Ne(s);if(a==="system"&&i!==0)throw new Error("System message should be the first one");const c=be(a),u=o.content[o.content.length];if(!o.mergeWithPreviousContent&&u&&u.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Ge(s,n,e.slice(0,i));if(o.mergeWithPreviousContent){const d=o.content[o.content.length-1];if(!d)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return d.parts.push(...r),{mergeWithPreviousContent:!1,content:o.content}}let p=c;(p==="function"||p==="system"&&!t)&&(p="user");const f={role:p,parts:r};return{mergeWithPreviousContent:a==="system"&&!t,content:[...o.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function ke(e,n){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.length===1&&s.parts[0].text?a=s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(p=>"text"in p)?.text??c),{generations:[{text:c,message:new pe({content:a??"",tool_calls:t?.map(r=>({...r,type:"tool_call",id:"id"in r&&typeof r.id=="string"?r.id:ae()})),additional_kwargs:{...i},usage_metadata:n?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:n?.usageMetadata?.input_tokens,completionTokens:n?.usageMetadata?.output_tokens,totalTokens:n?.usageMetadata?.total_tokens}}}}function Ue(e,n){if(!e.candidates||e.candidates.length===0)return null;const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.every(r=>"text"in r)?a=s.parts.map(r=>r.text).join(""):Array.isArray(s?.parts)?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";a&&typeof a=="string"?c=a:Array.isArray(a)&&(c=a.find(p=>"text"in p)?.text??"");const u=[];return t&&u.push(...t.map(r=>({...r,args:JSON.stringify(r.args),index:n.index,type:"tool_call_chunk",id:"id"in r&&typeof r.id=="string"?r.id:ae()}))),new ge({text:c,message:new me({content:a||"",name:s?s.role:void 0,tool_call_chunks:u,additional_kwargs:{},response_metadata:{model_provider:"google-genai"},usage_metadata:n.usageMetadata}),generationInfo:i})}function Le(e){return e.every(n=>"functionDeclarations"in n&&Array.isArray(n.functionDeclarations))?e:[{functionDeclarations:e.map(n=>{if(se(n)){const t=N(n.schema);return t.type==="object"&&"properties"in t&&Object.keys(t.properties).length===0?{name:n.name,description:n.description}:{name:n.name,description:n.description,parameters:t}}return ie(n)?{name:n.function.name,description:n.function.description??"A function available to call.",parameters:Ae(n.function.parameters)}:n})}]}var U=class extends ve{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;const n=await we(this.zodSchema,e);if(n.success)return n.data;throw new Te(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const n=e.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(n[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[t]=n;return await this._validateResult(t.args)}},L;(function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"})(L||(L={}));var P;(function(e){e.LANGUAGE_UNSPECIFIED="language_unspecified",e.PYTHON="python"})(P||(P={}));var j;(function(e){e.OUTCOME_UNSPECIFIED="outcome_unspecified",e.OUTCOME_OK="outcome_ok",e.OUTCOME_FAILED="outcome_failed",e.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(j||(j={}));const F=["user","model","function","system"];var K;(function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(K||(K={}));var $;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"})($||($={}));var H;(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(H||(H={}));var B;(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER"})(B||(B={}));var T;(function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.OTHER="OTHER"})(T||(T={}));var Y;(function(e){e.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",e.RETRIEVAL_QUERY="RETRIEVAL_QUERY",e.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",e.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",e.CLASSIFICATION="CLASSIFICATION",e.CLUSTERING="CLUSTERING"})(Y||(Y={}));var w;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"})(w||(w={}));var q;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(q||(q={}));class g extends Error{constructor(n){super(`[GoogleGenerativeAI Error]: ${n}`)}}class v extends g{constructor(n,t){super(n),this.response=t}}class re extends g{constructor(n,t,o,s){super(n),this.status=t,this.statusText=o,this.errorDetails=s}}class y extends g{}class ce extends g{}const Pe="https://generativelanguage.googleapis.com",je="v1beta",Fe="0.24.1",Ke="genai-js";var E;(function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.EMBED_CONTENT="embedContent",e.BATCH_EMBED_CONTENTS="batchEmbedContents"})(E||(E={}));class $e{constructor(n,t,o,s,i){this.model=n,this.task=t,this.apiKey=o,this.stream=s,this.requestOptions=i}toString(){var n,t;const o=((n=this.requestOptions)===null||n===void 0?void 0:n.apiVersion)||je;let i=`${((t=this.requestOptions)===null||t===void 0?void 0:t.baseUrl)||Pe}/${o}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}}function He(e){const n=[];return e?.apiClient&&n.push(e.apiClient),n.push(`${Ke}/${Fe}`),n.join(" ")}async function Be(e){var n;const t=new Headers;t.append("Content-Type","application/json"),t.append("x-goog-api-client",He(e.requestOptions)),t.append("x-goog-api-key",e.apiKey);let o=(n=e.requestOptions)===null||n===void 0?void 0:n.customHeaders;if(o){if(!(o instanceof Headers))try{o=new Headers(o)}catch(s){throw new y(`unable to convert customHeaders value ${JSON.stringify(o)} to Headers: ${s.message}`)}for(const[s,i]of o.entries()){if(s==="x-goog-api-key")throw new y(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new y(`Header name ${s} can only be set using the apiClient field`);t.append(s,i)}}return t}async function Ye(e,n,t,o,s,i){const a=new $e(e,n,t,o,i);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},Je(i)),{method:"POST",headers:await Be(a),body:s})}}async function R(e,n,t,o,s,i={},a=fetch){const{url:c,fetchOptions:u}=await Ye(e,n,t,o,s,i);return qe(c,u,a)}async function qe(e,n,t=fetch){let o;try{o=await t(e,n)}catch(s){We(s,e)}return o.ok||await Ve(o,e),o}function We(e,n){let t=e;throw t.name==="AbortError"?(t=new ce(`Request aborted when fetching ${n.toString()}: ${e.message}`),t.stack=e.stack):e instanceof re||e instanceof y||(t=new g(`Error fetching from ${n.toString()}: ${e.message}`),t.stack=e.stack),t}async function Ve(e,n){let t="",o;try{const s=await e.json();t=s.error.message,s.error.details&&(t+=` ${JSON.stringify(s.error.details)}`,o=s.error.details)}catch{}throw new re(`Error fetching from ${n.toString()}: [${e.status} ${e.statusText}] ${t}`,e.status,e.statusText,o)}function Je(e){const n={};if(e?.signal!==void 0||e?.timeout>=0){const t=new AbortController;e?.timeout>=0&&setTimeout(()=>t.abort(),e.timeout),e?.signal&&e.signal.addEventListener("abort",()=>{t.abort()}),n.signal=t.signal}return n}function b(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return ze(e)}else if(e.promptFeedback)throw new v(`Text not available. ${C(e)}`,e);return""},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),W(e)[0]}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return W(e)}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e}function ze(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.text&&i.push(a.text),a.executableCode&&i.push("\n```"+a.executableCode.language+`
1
+ import{i as ne,t as fe,a as he,b as pe,C as ge,c as me,d as Ce,e as ye,f as oe,g as se,h as ie,j as _e,k as Ee,p as A,B as ve,l as we,O as Te,m as Ie,n as Oe,J as Re,R as D,o as Se}from"./index-CeVhU8eb.js";import{v as ae}from"./index-CNwZaJQ9.js";import"./embeddings-P__c62U6.js";import"./chunk-VL2OQCWN-DBinT58-.js";import"./index-DRz5BQNA.js";function _(e){if(typeof e=="object"&&e!==null){const n={...e};"additionalProperties"in n&&delete n.additionalProperties,"$schema"in n&&delete n.$schema,"strict"in n&&delete n.strict;for(const t in n)t in n&&(Array.isArray(n[t])?n[t]=n[t].map(_):typeof n[t]=="object"&&n[t]!==null&&(n[t]=_(n[t])));return n}return e}function N(e){const n=_(ne(e)?fe(e):e),{$schema:t,...o}=n;return o}function Ae(e){const n=_(e),{$schema:t,...o}=n;return o}function Ne(e){const n=e._getType();return Ce.isInstance(e)?e.role:n==="tool"?n:e.name??n}function be(e){switch(e){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${e}`)}}function Me(e){if("mimeType"in e&&"data"in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if("mimeType"in e&&"fileUri"in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw new Error("Invalid media content")}function xe(e,n){return n.map(t=>oe(t)?t.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function De(e){return{providerName:"Google Gemini",fromStandardTextBlock(t){return{text:t.text}},fromStandardImageBlock(t){if(!e)throw new Error("This model does not support images");if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw new Error("This model does not support audio");if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw new Error("This model does not support files");if(t.source_type==="text")return{text:t.text};if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)}}}function G(e,n){if(_e(e))return Ee(e,De(n));if(e.type==="text")return{text:e.text};if(e.type==="executableCode")return{executableCode:e.executableCode};if(e.type==="codeExecutionResult")return{codeExecutionResult:e.codeExecutionResult};if(e.type==="image_url"){if(!n)throw new Error("This model does not support images");let t;if(typeof e.image_url=="string")t=e.image_url;else if(typeof e.image_url=="object"&&"url"in e.image_url)t=e.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[o,s]=t.split(",");if(!o.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[i,a]=o.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:s,mimeType:i}}}else{if(e.type==="media")return Me(e);if(e.type==="tool_use")return{functionCall:{name:e.name,args:e.input}};if(e.type?.includes("/")&&e.type.split("/").length===2&&"data"in e&&typeof e.data=="string")return{inlineData:{mimeType:e.type,data:e.data}};if("functionCall"in e)return;throw"type"in e?new Error(`Unknown content type ${e.type}`):new Error(`Unknown content ${JSON.stringify(e)}`)}}function Ge(e,n,t){if(ye(e)){const i=e.name??xe(e,t);if(i===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const a=Array.isArray(e.content)?e.content.map(c=>G(c,n)).filter(c=>c!==void 0):e.content;return e.status==="error"?[{functionResponse:{name:i,response:{error:{details:a}}}}]:[{functionResponse:{name:i,response:{result:a}}}]}let o=[];const s=[];return typeof e.content=="string"&&e.content&&s.push({text:e.content}),Array.isArray(e.content)&&s.push(...e.content.map(i=>G(i,n)).filter(i=>i!==void 0)),oe(e)&&e.tool_calls?.length&&(o=e.tool_calls.map(i=>({functionCall:{name:i.name,args:i.args}}))),[...s,...o]}function k(e,n,t=!1){return e.reduce((o,s,i)=>{if(!he(s))throw new Error("Unsupported message input");const a=Ne(s);if(a==="system"&&i!==0)throw new Error("System message should be the first one");const c=be(a),u=o.content[o.content.length];if(!o.mergeWithPreviousContent&&u&&u.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Ge(s,n,e.slice(0,i));if(o.mergeWithPreviousContent){const d=o.content[o.content.length-1];if(!d)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return d.parts.push(...r),{mergeWithPreviousContent:!1,content:o.content}}let p=c;(p==="function"||p==="system"&&!t)&&(p="user");const f={role:p,parts:r};return{mergeWithPreviousContent:a==="system"&&!t,content:[...o.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function ke(e,n){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.length===1&&s.parts[0].text?a=s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(p=>"text"in p)?.text??c),{generations:[{text:c,message:new pe({content:a??"",tool_calls:t?.map(r=>({...r,type:"tool_call",id:"id"in r&&typeof r.id=="string"?r.id:ae()})),additional_kwargs:{...i},usage_metadata:n?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:n?.usageMetadata?.input_tokens,completionTokens:n?.usageMetadata?.output_tokens,totalTokens:n?.usageMetadata?.total_tokens}}}}function Ue(e,n){if(!e.candidates||e.candidates.length===0)return null;const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.every(r=>"text"in r)?a=s.parts.map(r=>r.text).join(""):Array.isArray(s?.parts)?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";a&&typeof a=="string"?c=a:Array.isArray(a)&&(c=a.find(p=>"text"in p)?.text??"");const u=[];return t&&u.push(...t.map(r=>({...r,args:JSON.stringify(r.args),index:n.index,type:"tool_call_chunk",id:"id"in r&&typeof r.id=="string"?r.id:ae()}))),new ge({text:c,message:new me({content:a||"",name:s?s.role:void 0,tool_call_chunks:u,additional_kwargs:{},response_metadata:{model_provider:"google-genai"},usage_metadata:n.usageMetadata}),generationInfo:i})}function Le(e){return e.every(n=>"functionDeclarations"in n&&Array.isArray(n.functionDeclarations))?e:[{functionDeclarations:e.map(n=>{if(se(n)){const t=N(n.schema);return t.type==="object"&&"properties"in t&&Object.keys(t.properties).length===0?{name:n.name,description:n.description}:{name:n.name,description:n.description,parameters:t}}return ie(n)?{name:n.function.name,description:n.function.description??"A function available to call.",parameters:Ae(n.function.parameters)}:n})}]}var U=class extends ve{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;const n=await we(this.zodSchema,e);if(n.success)return n.data;throw new Te(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const n=e.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(n[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[t]=n;return await this._validateResult(t.args)}},L;(function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"})(L||(L={}));var P;(function(e){e.LANGUAGE_UNSPECIFIED="language_unspecified",e.PYTHON="python"})(P||(P={}));var j;(function(e){e.OUTCOME_UNSPECIFIED="outcome_unspecified",e.OUTCOME_OK="outcome_ok",e.OUTCOME_FAILED="outcome_failed",e.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(j||(j={}));const F=["user","model","function","system"];var K;(function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(K||(K={}));var $;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"})($||($={}));var H;(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(H||(H={}));var B;(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER"})(B||(B={}));var T;(function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.OTHER="OTHER"})(T||(T={}));var Y;(function(e){e.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",e.RETRIEVAL_QUERY="RETRIEVAL_QUERY",e.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",e.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",e.CLASSIFICATION="CLASSIFICATION",e.CLUSTERING="CLUSTERING"})(Y||(Y={}));var w;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"})(w||(w={}));var q;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(q||(q={}));class g extends Error{constructor(n){super(`[GoogleGenerativeAI Error]: ${n}`)}}class v extends g{constructor(n,t){super(n),this.response=t}}class re extends g{constructor(n,t,o,s){super(n),this.status=t,this.statusText=o,this.errorDetails=s}}class y extends g{}class ce extends g{}const Pe="https://generativelanguage.googleapis.com",je="v1beta",Fe="0.24.1",Ke="genai-js";var E;(function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.EMBED_CONTENT="embedContent",e.BATCH_EMBED_CONTENTS="batchEmbedContents"})(E||(E={}));class $e{constructor(n,t,o,s,i){this.model=n,this.task=t,this.apiKey=o,this.stream=s,this.requestOptions=i}toString(){var n,t;const o=((n=this.requestOptions)===null||n===void 0?void 0:n.apiVersion)||je;let i=`${((t=this.requestOptions)===null||t===void 0?void 0:t.baseUrl)||Pe}/${o}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}}function He(e){const n=[];return e?.apiClient&&n.push(e.apiClient),n.push(`${Ke}/${Fe}`),n.join(" ")}async function Be(e){var n;const t=new Headers;t.append("Content-Type","application/json"),t.append("x-goog-api-client",He(e.requestOptions)),t.append("x-goog-api-key",e.apiKey);let o=(n=e.requestOptions)===null||n===void 0?void 0:n.customHeaders;if(o){if(!(o instanceof Headers))try{o=new Headers(o)}catch(s){throw new y(`unable to convert customHeaders value ${JSON.stringify(o)} to Headers: ${s.message}`)}for(const[s,i]of o.entries()){if(s==="x-goog-api-key")throw new y(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new y(`Header name ${s} can only be set using the apiClient field`);t.append(s,i)}}return t}async function Ye(e,n,t,o,s,i){const a=new $e(e,n,t,o,i);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},Je(i)),{method:"POST",headers:await Be(a),body:s})}}async function R(e,n,t,o,s,i={},a=fetch){const{url:c,fetchOptions:u}=await Ye(e,n,t,o,s,i);return qe(c,u,a)}async function qe(e,n,t=fetch){let o;try{o=await t(e,n)}catch(s){We(s,e)}return o.ok||await Ve(o,e),o}function We(e,n){let t=e;throw t.name==="AbortError"?(t=new ce(`Request aborted when fetching ${n.toString()}: ${e.message}`),t.stack=e.stack):e instanceof re||e instanceof y||(t=new g(`Error fetching from ${n.toString()}: ${e.message}`),t.stack=e.stack),t}async function Ve(e,n){let t="",o;try{const s=await e.json();t=s.error.message,s.error.details&&(t+=` ${JSON.stringify(s.error.details)}`,o=s.error.details)}catch{}throw new re(`Error fetching from ${n.toString()}: [${e.status} ${e.statusText}] ${t}`,e.status,e.statusText,o)}function Je(e){const n={};if(e?.signal!==void 0||e?.timeout>=0){const t=new AbortController;e?.timeout>=0&&setTimeout(()=>t.abort(),e.timeout),e?.signal&&e.signal.addEventListener("abort",()=>{t.abort()}),n.signal=t.signal}return n}function b(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return ze(e)}else if(e.promptFeedback)throw new v(`Text not available. ${C(e)}`,e);return""},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),W(e)[0]}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return W(e)}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e}function ze(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.text&&i.push(a.text),a.executableCode&&i.push("\n```"+a.executableCode.language+`
2
2
  `+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function W(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}const Xe=[T.RECITATION,T.SAFETY,T.LANGUAGE];function S(e){return!!e.finishReason&&Xe.includes(e.finishReason)}function C(e){var n,t,o;let s="";if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)s+="Response was blocked",!((n=e.promptFeedback)===null||n===void 0)&&n.blockReason&&(s+=` due to ${e.promptFeedback.blockReason}`),!((t=e.promptFeedback)===null||t===void 0)&&t.blockReasonMessage&&(s+=`: ${e.promptFeedback.blockReasonMessage}`);else if(!((o=e.candidates)===null||o===void 0)&&o[0]){const i=e.candidates[0];S(i)&&(s+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(s+=`: ${i.finishMessage}`))}return s}function I(e){return this instanceof I?(this.v=e,this):new I(e)}function Qe(e,n,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=t.apply(e,n||[]),s,i=[];return s={},a("next"),a("throw"),a("return"),s[Symbol.asyncIterator]=function(){return this},s;function a(d){o[d]&&(s[d]=function(l){return new Promise(function(h,m){i.push([d,l,h,m])>1||c(d,l)})})}function c(d,l){try{u(o[d](l))}catch(h){f(i[0][3],h)}}function u(d){d.value instanceof I?Promise.resolve(d.value.v).then(r,p):f(i[0][2],d)}function r(d){c("next",d)}function p(d){c("throw",d)}function f(d,l){d(l),i.shift(),i.length&&c(i[0][0],i[0][1])}}const V=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function Ze(e){const n=e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),t=nt(n),[o,s]=t.tee();return{stream:tt(o),response:et(s)}}async function et(e){const n=[],t=e.getReader();for(;;){const{done:o,value:s}=await t.read();if(o)return b(ot(n));n.push(s)}}function tt(e){return Qe(this,arguments,function*(){const t=e.getReader();for(;;){const{value:o,done:s}=yield I(t.read());if(s)break;yield yield I(b(o))}})}function nt(e){const n=e.getReader();return new ReadableStream({start(o){let s="";return i();function i(){return n.read().then(({value:a,done:c})=>{if(c){if(s.trim()){o.error(new g("Failed to parse stream"));return}o.close();return}s+=a;let u=s.match(V),r;for(;u;){try{r=JSON.parse(u[1])}catch{o.error(new g(`Error parsing JSON response: "${u[1]}"`));return}o.enqueue(r),s=s.substring(u[0].length),u=s.match(V)}return i()}).catch(a=>{let c=a;throw c.stack=a.stack,c.name==="AbortError"?c=new ce("Request aborted when reading from the stream"):c=new g("Error reading from the stream"),c})}}})}function ot(e){const n=e[e.length-1],t={promptFeedback:n?.promptFeedback};for(const o of e){if(o.candidates){let s=0;for(const i of o.candidates)if(t.candidates||(t.candidates=[]),t.candidates[s]||(t.candidates[s]={index:s}),t.candidates[s].citationMetadata=i.citationMetadata,t.candidates[s].groundingMetadata=i.groundingMetadata,t.candidates[s].finishReason=i.finishReason,t.candidates[s].finishMessage=i.finishMessage,t.candidates[s].safetyRatings=i.safetyRatings,i.content&&i.content.parts){t.candidates[s].content||(t.candidates[s].content={role:i.content.role||"user",parts:[]});const a={};for(const c of i.content.parts)c.text&&(a.text=c.text),c.functionCall&&(a.functionCall=c.functionCall),c.executableCode&&(a.executableCode=c.executableCode),c.codeExecutionResult&&(a.codeExecutionResult=c.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),t.candidates[s].content.parts.push(a)}s++}o.usageMetadata&&(t.usageMetadata=o.usageMetadata)}return t}async function le(e,n,t,o){const s=await R(n,E.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(t),o);return Ze(s)}async function ue(e,n,t,o){const i=await(await R(n,E.GENERATE_CONTENT,e,!1,JSON.stringify(t),o)).json();return{response:b(i)}}function de(e){if(e!=null){if(typeof e=="string")return{role:"system",parts:[{text:e}]};if(e.text)return{role:"system",parts:[e]};if(e.parts)return e.role?e:{role:"system",parts:e.parts}}}function O(e){let n=[];if(typeof e=="string")n=[{text:e}];else for(const t of e)typeof t=="string"?n.push({text:t}):n.push(t);return st(n)}function st(e){const n={role:"user",parts:[]},t={role:"function",parts:[]};let o=!1,s=!1;for(const i of e)"functionResponse"in i?(t.parts.push(i),s=!0):(n.parts.push(i),o=!0);if(o&&s)throw new g("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!o&&!s)throw new g("No content is provided for sending chat message.");return o?n:t}function it(e,n){var t;let o={model:n?.model,generationConfig:n?.generationConfig,safetySettings:n?.safetySettings,tools:n?.tools,toolConfig:n?.toolConfig,systemInstruction:n?.systemInstruction,cachedContent:(t=n?.cachedContent)===null||t===void 0?void 0:t.name,contents:[]};const s=e.generateContentRequest!=null;if(e.contents){if(s)throw new y("CountTokensRequest must have one of contents or generateContentRequest, not both.");o.contents=e.contents}else if(s)o=Object.assign(Object.assign({},o),e.generateContentRequest);else{const i=O(e);o.contents=[i]}return{generateContentRequest:o}}function J(e){let n;return e.contents?n=e:n={contents:[O(e)]},e.systemInstruction&&(n.systemInstruction=de(e.systemInstruction)),n}function at(e){return typeof e=="string"||Array.isArray(e)?{content:O(e)}:e}const z=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],rt={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function ct(e){let n=!1;for(const t of e){const{role:o,parts:s}=t;if(!n&&o!=="user")throw new g(`First content should be with role 'user', got ${o}`);if(!F.includes(o))throw new g(`Each item should include role field. Got ${o} but valid roles are: ${JSON.stringify(F)}`);if(!Array.isArray(s))throw new g("Content should have 'parts' property with an array of Parts");if(s.length===0)throw new g("Each Content should have at least one part");const i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const c of s)for(const u of z)u in c&&(i[u]+=1);const a=rt[o];for(const c of z)if(!a.includes(c)&&i[c]>0)throw new g(`Content with role '${o}' can't contain '${c}' part`);n=!0}}function X(e){var n;if(e.candidates===void 0||e.candidates.length===0)return!1;const t=(n=e.candidates[0])===null||n===void 0?void 0:n.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(const o of t.parts)if(o===void 0||Object.keys(o).length===0||o.text!==void 0&&o.text==="")return!1;return!0}const Q="SILENT_ERROR";class lt{constructor(n,t,o,s={}){this.model=t,this.params=o,this._requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=n,o?.history&&(ct(o.history),this._history=o.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(n,t={}){var o,s,i,a,c,u;await this._sendPromise;const r=O(n),p={safetySettings:(o=this.params)===null||o===void 0?void 0:o.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(u=this.params)===null||u===void 0?void 0:u.cachedContent,contents:[...this._history,r]},f=Object.assign(Object.assign({},this._requestOptions),t);let d;return this._sendPromise=this._sendPromise.then(()=>ue(this._apiKey,this.model,p,f)).then(l=>{var h;if(X(l.response)){this._history.push(r);const m=Object.assign({parts:[],role:"model"},(h=l.response.candidates)===null||h===void 0?void 0:h[0].content);this._history.push(m)}else{const m=C(l.response);m&&console.warn(`sendMessage() was unsuccessful. ${m}. Inspect response object for details.`)}d=l}).catch(l=>{throw this._sendPromise=Promise.resolve(),l}),await this._sendPromise,d}async sendMessageStream(n,t={}){var o,s,i,a,c,u;await this._sendPromise;const r=O(n),p={safetySettings:(o=this.params)===null||o===void 0?void 0:o.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(u=this.params)===null||u===void 0?void 0:u.cachedContent,contents:[...this._history,r]},f=Object.assign(Object.assign({},this._requestOptions),t),d=le(this._apiKey,this.model,p,f);return this._sendPromise=this._sendPromise.then(()=>d).catch(l=>{throw new Error(Q)}).then(l=>l.response).then(l=>{if(X(l)){this._history.push(r);const h=Object.assign({},l.candidates[0].content);h.role||(h.role="model"),this._history.push(h)}else{const h=C(l);h&&console.warn(`sendMessageStream() was unsuccessful. ${h}. Inspect response object for details.`)}}).catch(l=>{l.message!==Q&&console.error(l)}),d}}async function ut(e,n,t,o){return(await R(n,E.COUNT_TOKENS,e,!1,JSON.stringify(t),o)).json()}async function dt(e,n,t,o){return(await R(n,E.EMBED_CONTENT,e,!1,JSON.stringify(t),o)).json()}async function ft(e,n,t,o){const s=t.requests.map(a=>Object.assign(Object.assign({},a),{model:n}));return(await R(n,E.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:s}),o)).json()}class Z{constructor(n,t,o={}){this.apiKey=n,this._requestOptions=o,t.model.includes("/")?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=de(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(n,t={}){var o;const s=J(n),i=Object.assign(Object.assign({},this._requestOptions),t);return ue(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(o=this.cachedContent)===null||o===void 0?void 0:o.name},s),i)}async generateContentStream(n,t={}){var o;const s=J(n),i=Object.assign(Object.assign({},this._requestOptions),t);return le(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(o=this.cachedContent)===null||o===void 0?void 0:o.name},s),i)}startChat(n){var t;return new lt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(t=this.cachedContent)===null||t===void 0?void 0:t.name},n),this._requestOptions)}async countTokens(n,t={}){const o=it(n,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),s=Object.assign(Object.assign({},this._requestOptions),t);return ut(this.apiKey,this.model,o,s)}async embedContent(n,t={}){const o=at(n),s=Object.assign(Object.assign({},this._requestOptions),t);return dt(this.apiKey,this.model,o,s)}async batchEmbedContents(n,t={}){const o=Object.assign(Object.assign({},this._requestOptions),t);return ft(this.apiKey,this.model,n,o)}}class ee{constructor(n){this.apiKey=n}getGenerativeModel(n,t){if(!n.model)throw new g("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new Z(this.apiKey,n,t)}getGenerativeModelFromCachedContent(n,t,o){if(!n.name)throw new y("Cached content must contain a `name` field.");if(!n.model)throw new y("Cached content must contain a `model` field.");const s=["model","systemInstruction"];for(const a of s)if(t?.[a]&&n[a]&&t?.[a]!==n[a]){if(a==="model"){const c=t.model.startsWith("models/")?t.model.replace("models/",""):t.model,u=n.model.startsWith("models/")?n.model.replace("models/",""):n.model;if(c===u)continue}throw new y(`Different value for "${a}" specified in modelParams (${t[a]}) and cachedContent (${n[a]})`)}const i=Object.assign(Object.assign({},t),{model:n.model,tools:n.tools,toolConfig:n.toolConfig,systemInstruction:n.systemInstruction,cachedContent:n});return new Z(this.apiKey,i,o)}}function te(e,n){const t=ht(e),o=gt(t,n);return{tools:t,toolConfig:o}}function ht(e){let n=[];const t=[];return e.forEach(s=>{if(se(s)){const[i]=Le([s]);i.functionDeclarations&&n.push(...i.functionDeclarations)}else if(ie(s)){const{functionDeclarations:i}=pt(s);if(i)n.push(...i);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else t.push(s)}),t.find(s=>"functionDeclarations"in s)?t.map(s=>{if(n?.length>0&&"functionDeclarations"in s){const i={functionDeclarations:[...s.functionDeclarations||[],...n]};return n=[],i}return s}):[...t,...n.length>0?[{functionDeclarations:n}]:[]]}function pt(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:_(e.function.parameters)}]}}function gt(e,n){if(!e.length||!n)return;const{toolChoice:t,allowedFunctionNames:o}=n,s={any:w.ANY,auto:w.AUTO,none:w.NONE};if(t&&["any","auto","none"].includes(t))return{functionCallingConfig:{mode:s[t]??"MODE_UNSPECIFIED",allowedFunctionNames:o}};if(typeof t=="string"||o)return{functionCallingConfig:{mode:w.ANY,allowedFunctionNames:[...o??[],...t&&typeof t=="string"?[t]:[]]}}}var vt=class extends Ie{static lc_name(){return"ChatGoogleGenerativeAI"}lc_serializable=!0;get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}lc_namespace=["langchain","chat_models","google_genai"];get lc_aliases(){return{apiKey:"google_api_key"}}model;temperature;maxOutputTokens;topP;topK;stopSequences=[];safetySettings;apiKey;streaming=!1;json;streamUsage=!0;convertSystemMessageToHumanContent;client;get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")}constructor(e){if(super(e),this.model=e.model.replace(/^models\//,""),this.maxOutputTokens=e.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=e.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=e.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=e.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=e.stopSequences??this.stopSequences,this.apiKey=e.apiKey??Oe("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=e.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(t=>t.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=e.streaming??this.streaming,this.json=e.json,this.client=new ee(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{}}},{apiVersion:e.apiVersion,baseUrl:e.baseUrl}),this.streamUsage=e.streamUsage??this.streamUsage}useCachedContent(e,n,t){this.apiKey&&(this.client=new ee(this.apiKey).getGenerativeModelFromCachedContent(e,n,t))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent=="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model==="gemini-1.0-pro-001"||this.model.startsWith("gemini-pro-vision")||this.model.startsWith("gemini-1.0-pro-vision")?!1:this.model!=="gemini-pro"}getLsParams(e){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(e,n){return this.withConfig({tools:te(e)?.tools,...n})}invocationParams(e){const n=e?.tools?.length?te(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return e?.responseSchema?(this.client.generationConfig.responseSchema=e.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...n?.tools?{tools:n.tools}:{},...n?.toolConfig?{toolConfig:n.toolConfig}:{}}}async _generate(e,n,t){const o=k(e,this._isMultimodalModel,this.useSystemInstruction);let s=o;if(o[0].role==="system"){const[r]=o;this.client.systemInstruction=r,s=o.slice(1)}const i=this.invocationParams(n);if(this.streaming){const r={},p=this._streamResponseChunks(e,n,t),f={};for await(const l of p){const h=l.generationInfo?.completion??0;f[h]===void 0?f[h]=l:f[h]=f[h].concat(l)}return{generations:Object.entries(f).sort(([l],[h])=>parseInt(l,10)-parseInt(h,10)).map(([l,h])=>h),llmOutput:{estimatedTokenUsage:r}}}const a=await this.completionWithRetry({...i,contents:s});let c;if("usageMetadata"in a.response){const r=a.response.usageMetadata;c={input_tokens:r.promptTokenCount??0,output_tokens:r.candidatesTokenCount??0,total_tokens:r.totalTokenCount??0}}const u=ke(a.response,{usageMetadata:c});return u.generations?.length>0&&await t?.handleLLMNewToken(u.generations[0]?.text??""),u}async*_streamResponseChunks(e,n,t){const o=k(e,this._isMultimodalModel,this.useSystemInstruction);let s=o;if(o[0].role==="system"){const[l]=o;this.client.systemInstruction=l,s=o.slice(1)}const a={...this.invocationParams(n),contents:s},c=await this.caller.callWithOptions({signal:n?.signal},async()=>{const{stream:l}=await this.client.generateContentStream(a);return l});let u,r=0,p=0,f=0,d=0;for await(const l of c){if("usageMetadata"in l&&l.usageMetadata!==void 0&&this.streamUsage!==!1&&n.streamUsage!==!1){u={input_tokens:l.usageMetadata.promptTokenCount??0,output_tokens:l.usageMetadata.candidatesTokenCount??0,total_tokens:l.usageMetadata.totalTokenCount??0};const m=l.usageMetadata.promptTokenCount??0;u.input_tokens=Math.max(0,m-r),r=m;const M=l.usageMetadata.candidatesTokenCount??0;u.output_tokens=Math.max(0,M-p),p=M;const x=l.usageMetadata.totalTokenCount??0;u.total_tokens=Math.max(0,x-f),f=x}const h=Ue(l,{usageMetadata:u,index:d});d+=1,h&&(yield h,await t?.handleLLMNewToken(h.text??""))}}async completionWithRetry(e,n){return this.caller.callWithOptions({signal:n?.signal},async()=>{try{return await this.client.generateContent(e)}catch(t){throw t.message?.includes("400 Bad Request")&&(t.status=400),t}})}withStructuredOutput(e,n){const t=e,o=n?.name,s=n?.method,i=n?.includeRaw;if(s==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,c;if(s==="functionCalling"){let f=o??"extract",d;if(ne(t)){const l=N(t);d=[{functionDeclarations:[{name:f,description:l.description??"A function available to call.",parameters:l}]}],c=new U({returnSingle:!0,keyName:f,zodSchema:t})}else{let l;typeof t.name=="string"&&typeof t.parameters=="object"&&t.parameters!=null?(l=t,l.parameters=_(t.parameters),f=t.name):l={name:f,description:t.description??"",parameters:_(t)},d=[{functionDeclarations:[l]}],c=new U({returnSingle:!0,keyName:f})}a=this.bindTools(d).withConfig({allowedFunctionNames:[f]})}else{const f=N(t);a=this.withConfig({responseSchema:f}),c=new Re}if(!i)return a.pipe(c).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const u=D.assign({parsed:(f,d)=>c.invoke(f.raw,d)}),r=D.assign({parsed:()=>null}),p=u.withFallbacks({fallbacks:[r]});return Se.from([{raw:a},p]).withConfig({runName:"StructuredOutputRunnable"})}};export{vt as ChatGoogleGenerativeAI};
@@ -1,4 +1,4 @@
1
- import{s as Oi,v as se,P as Pe,p as Ht,a as Ga,b as Nr,g as he,c as kr,d as Ke,_ as Ci,$ as xi,e as Ni,f as ki,h as Rr,i as ca,j as Ri,k as Pi,t as Va,l as Pr,V as Mi,m as Li,n as Ut,o as $i,T as ji}from"./chunk-VL2OQCWN-BSY6s1ZW.js";import{Z as P,a as Za,o as la,s as ua}from"./index-C8x1o6em.js";var Di=Object.defineProperty,F=(e,t)=>{for(var n in t)Di(e,n,{get:t[n],enumerable:!0})};function Ue(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function da(e){return Ue(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function ha(e){return Ue(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function Fi(e){return Ue(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function Mr(e){return Ue(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function Lr(e){if(Ue(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Ui(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),a=t[1].trim();if(n===""||a==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const r={};for(const s of e.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);r[o]=c}return{type:n,subtype:a,parameters:r}}function $n({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let a;if(n){a=n[1].toLowerCase();const r=t?Uint8Array.from(atob(n[2]),s=>s.charCodeAt(0)):n[2];return{mime_type:a,data:r}}}function Bi(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function $r(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function zi(e,t){return t?.[e]||Oi(e)}function Hi(e,t,n){const a={};for(const r in e)Object.hasOwn(e,r)&&(a[t(r,n)]=e[r]);return a}var Gi={};F(Gi,{Serializable:()=>lt,get_lc_unique_name:()=>pa});function qa(e){return Array.isArray(e)?[...e]:{...e}}function Vi(e,t){const n=qa(e);for(const[a,r]of Object.entries(t)){const[s,...i]=a.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=qa(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[r]})}return n}function pa(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var lt=class jr{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,pa(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([a])=>this.lc_serializable_keys?.includes(a))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof jr||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},a=Object.keys(this.lc_kwargs).reduce((r,s)=>(r[s]=s in this?this[s]:this.lc_kwargs[s],r),{});for(let r=Object.getPrototypeOf(this);r;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r,"lc_aliases",this)),Object.assign(n,Reflect.get(r,"lc_secrets",this)),Object.assign(a,Reflect.get(r,"lc_attributes",this));return Object.keys(n).forEach(r=>{let s=this,i=a;const[o,...c]=r.split(".").reverse();for(const l of c.reverse()){if(!(l in s)||s[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof s[l]=="object"&&s[l]!=null?i[l]={}:Array.isArray(s[l])&&(i[l]=[])),s=s[l],i=i[l]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Hi(Object.keys(n).length?Vi(a,n):a,zi,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function C(e,t){return k(e)&&e.type===t}function k(e){return typeof e=="object"&&e!==null}function Ie(e){return Array.isArray(e)}function S(e){return typeof e=="string"}function we(e){return typeof e=="number"}function fa(e){return e instanceof Uint8Array}function Ja(e){try{return JSON.parse(e)}catch{return}}const vt=e=>e();function Zi(e){if(e.type==="char_location"&&S(e.document_title)&&we(e.start_char_index)&&we(e.end_char_index)&&S(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="page_location"&&S(e.document_title)&&we(e.start_page_number)&&we(e.end_page_number)&&S(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="content_block_location"&&S(e.document_title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="web_search_result_location"&&S(e.url)&&S(e.title)&&S(e.encrypted_index)&&S(e.cited_text)){const{url:t,title:n,encrypted_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"url",url:t,title:n,startIndex:Number(a),endIndex:Number(a),citedText:r}}if(e.type==="search_result_location"&&S(e.source)&&S(e.title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{source:t,title:n,start_block_index:a,end_block_index:r,cited_text:s,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:a,endIndex:r,citedText:s}}}function Dr(e){if(C(e,"document")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&S(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(C(e,"image")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function qi(e){function*t(){for(const n of e){const a=Dr(n);a?yield a:yield n}}return Array.from(t())}function Wa(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(C(a,"text")&&S(a.text)){const{text:r,citations:s,...i}=a;if(Ie(s)&&s.length){const o=s.reduce((c,l)=>{const d=Zi(l);return d?[...c,d]:c},[]);yield{...i,type:"text",text:r,annotations:o};continue}else{yield{...i,type:"text",text:r};continue}}else if(C(a,"thinking")&&S(a.thinking)){const{thinking:r,signature:s,...i}=a;yield{...i,type:"reasoning",reasoning:r,signature:s};continue}else if(C(a,"redacted_thinking")){yield{type:"non_standard",value:a};continue}else if(C(a,"tool_use")&&S(a.name)&&S(a.id)){yield{type:"tool_call",id:a.id,name:a.name,args:a.input};continue}else if(C(a,"input_json_delta")){if(Wi(e)&&e.tool_call_chunks?.length){const r=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args,index:r.index};continue}}else if(C(a,"server_tool_use")&&S(a.name)&&S(a.id)){const{name:r,id:s}=a;if(r==="web_search"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.query))return a.input.query;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(a.name==="code_execution"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.code))return a.input.code;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(C(a,"web_search_tool_result")&&S(a.tool_use_id)&&Ie(a.content)){const{content:r,tool_use_id:s}=a,i=r.reduce((o,c)=>C(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(C(a,"code_execution_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"mcp_tool_use")){yield{id:a.id,type:"server_tool_call",name:"mcp_tool_use",args:a.input};continue}else if(C(a,"mcp_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:a.input};continue}else if(C(a,"search_result")){yield{id:a.id,type:"non_standard",value:a};continue}else if(C(a,"tool_result")){yield{id:a.id,type:"non_standard",value:a};continue}else{const r=Dr(a);if(r){yield r;continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const Ji={translateContent:Wa,translateContentChunk:Wa};function Wi(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function Ki(e){return da(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ha(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:Mr(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Yi(e){return e.map(Ki)}function Qi(e){return!!(C(e,"image_url")&&k(e.image_url)||C(e,"input_audio")&&k(e.input_audio)||C(e,"file")&&k(e.file))}function Xi(e){if(C(e,"image_url")&&k(e.image_url)&&S(e.image_url.url)){const t=$n({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(C(e,"input_audio")&&k(e.input_audio)&&S(e.input_audio.data)&&S(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(C(e,"file")&&k(e.file)&&S(e.file.data)){const t=$n({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(S(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function eo(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function to(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function ma(e){const t=[];for(const n of e)Qi(n)?t.push(Xi(n)):t.push(n);return t}function no(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:a,end_index:r}=e;return{type:"citation",url:t,title:n,startIndex:a,endIndex:r}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:a}=e;return{type:"citation",title:n,startIndex:a,endIndex:a,fileId:t}}return e}function Fr(e){function*t(){k(e.additional_kwargs?.reasoning)&&Ie(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((r,s)=>k(s)&&S(s.text)?`${r}${s.text}`:r,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n)if(C(a,"text")){const{text:r,annotations:s,...i}=a;Array.isArray(s)?yield{...i,type:"text",text:String(r),annotations:s.map(no)}:yield{...i,type:"text",text:String(r)}}for(const a of e.tool_calls??[])yield{type:"tool_call",id:a.id,name:a.name,args:a.args};if(k(e.additional_kwargs)&&Ie(e.additional_kwargs.tool_outputs))for(const a of e.additional_kwargs.tool_outputs){if(C(a,"web_search_call")){yield{id:a.id,type:"server_tool_call",name:"web_search",args:{query:a.query}};continue}else if(C(a,"file_search_call")){yield{id:a.id,type:"server_tool_call",name:"file_search",args:{query:a.query}};continue}else if(C(a,"computer_call")){yield{type:"non_standard",value:a};continue}else if(C(a,"code_interpreter_call")){if(S(a.code)&&(yield{id:a.id,type:"server_tool_call",name:"code_interpreter",args:{code:a.code}}),Ie(a.outputs)){const r=vt(()=>{if(a.status!=="in_progress"){if(a.status==="completed")return 0;if(a.status==="incomplete")return 127;if(a.status!=="interpreting"&&a.status==="failed")return 1}});for(const s of a.outputs)if(C(s,"logs")){yield{type:"server_tool_call_result",toolCallId:a.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:r??0,stderr:[0,void 0].includes(r)?void 0:String(s.logs),stdout:[0,void 0].includes(r)?String(s.logs):void 0}};continue}}continue}else if(C(a,"mcp_call")){yield{id:a.id,type:"server_tool_call",name:"mcp_call",args:a.input};continue}else if(C(a,"mcp_list_tools")){yield{id:a.id,type:"server_tool_call",name:"mcp_list_tools",args:a.input};continue}else if(C(a,"mcp_approval_request")){yield{type:"non_standard",value:a};continue}else if(C(a,"image_generation_call")){yield{type:"non_standard",value:a};continue}k(a)&&(yield{type:"non_standard",value:a})}}return Array.from(t())}function ao(e){function*t(){yield*Fr(e);for(const n of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(t())}const ro={translateContent:e=>typeof e.content=="string"?eo(e):Fr(e),translateContentChunk:e=>typeof e.content=="string"?to(e):ao(e)};function so(e,t="pretty"){return t==="pretty"?io(e):JSON.stringify(e)}function io(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-n.length)/2),r="=".repeat(a),s=n.length%2===0?r:`${r}=`;if(t.push(`${r}${n}${s}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
1
+ import{s as Oi,v as se,P as Pe,p as Ht,a as Ga,b as Nr,g as he,c as kr,d as Ke,_ as Ci,$ as xi,e as Ni,f as ki,h as Rr,i as ca,j as Ri,k as Pi,t as Va,l as Pr,V as Mi,m as Li,n as Ut,o as $i,T as ji}from"./chunk-VL2OQCWN-DBinT58-.js";import{Z as P,a as Za,o as la,s as ua}from"./index-CNwZaJQ9.js";var Di=Object.defineProperty,F=(e,t)=>{for(var n in t)Di(e,n,{get:t[n],enumerable:!0})};function Ue(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function da(e){return Ue(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function ha(e){return Ue(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function Fi(e){return Ue(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function Mr(e){return Ue(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function Lr(e){if(Ue(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Ui(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),a=t[1].trim();if(n===""||a==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const r={};for(const s of e.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);r[o]=c}return{type:n,subtype:a,parameters:r}}function $n({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let a;if(n){a=n[1].toLowerCase();const r=t?Uint8Array.from(atob(n[2]),s=>s.charCodeAt(0)):n[2];return{mime_type:a,data:r}}}function Bi(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function $r(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function zi(e,t){return t?.[e]||Oi(e)}function Hi(e,t,n){const a={};for(const r in e)Object.hasOwn(e,r)&&(a[t(r,n)]=e[r]);return a}var Gi={};F(Gi,{Serializable:()=>lt,get_lc_unique_name:()=>pa});function qa(e){return Array.isArray(e)?[...e]:{...e}}function Vi(e,t){const n=qa(e);for(const[a,r]of Object.entries(t)){const[s,...i]=a.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=qa(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[r]})}return n}function pa(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var lt=class jr{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,pa(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([a])=>this.lc_serializable_keys?.includes(a))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof jr||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},a=Object.keys(this.lc_kwargs).reduce((r,s)=>(r[s]=s in this?this[s]:this.lc_kwargs[s],r),{});for(let r=Object.getPrototypeOf(this);r;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r,"lc_aliases",this)),Object.assign(n,Reflect.get(r,"lc_secrets",this)),Object.assign(a,Reflect.get(r,"lc_attributes",this));return Object.keys(n).forEach(r=>{let s=this,i=a;const[o,...c]=r.split(".").reverse();for(const l of c.reverse()){if(!(l in s)||s[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof s[l]=="object"&&s[l]!=null?i[l]={}:Array.isArray(s[l])&&(i[l]=[])),s=s[l],i=i[l]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Hi(Object.keys(n).length?Vi(a,n):a,zi,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function C(e,t){return k(e)&&e.type===t}function k(e){return typeof e=="object"&&e!==null}function Ie(e){return Array.isArray(e)}function S(e){return typeof e=="string"}function we(e){return typeof e=="number"}function fa(e){return e instanceof Uint8Array}function Ja(e){try{return JSON.parse(e)}catch{return}}const vt=e=>e();function Zi(e){if(e.type==="char_location"&&S(e.document_title)&&we(e.start_char_index)&&we(e.end_char_index)&&S(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="page_location"&&S(e.document_title)&&we(e.start_page_number)&&we(e.end_page_number)&&S(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="content_block_location"&&S(e.document_title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="web_search_result_location"&&S(e.url)&&S(e.title)&&S(e.encrypted_index)&&S(e.cited_text)){const{url:t,title:n,encrypted_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"url",url:t,title:n,startIndex:Number(a),endIndex:Number(a),citedText:r}}if(e.type==="search_result_location"&&S(e.source)&&S(e.title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{source:t,title:n,start_block_index:a,end_block_index:r,cited_text:s,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:a,endIndex:r,citedText:s}}}function Dr(e){if(C(e,"document")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&S(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(C(e,"image")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function qi(e){function*t(){for(const n of e){const a=Dr(n);a?yield a:yield n}}return Array.from(t())}function Wa(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(C(a,"text")&&S(a.text)){const{text:r,citations:s,...i}=a;if(Ie(s)&&s.length){const o=s.reduce((c,l)=>{const d=Zi(l);return d?[...c,d]:c},[]);yield{...i,type:"text",text:r,annotations:o};continue}else{yield{...i,type:"text",text:r};continue}}else if(C(a,"thinking")&&S(a.thinking)){const{thinking:r,signature:s,...i}=a;yield{...i,type:"reasoning",reasoning:r,signature:s};continue}else if(C(a,"redacted_thinking")){yield{type:"non_standard",value:a};continue}else if(C(a,"tool_use")&&S(a.name)&&S(a.id)){yield{type:"tool_call",id:a.id,name:a.name,args:a.input};continue}else if(C(a,"input_json_delta")){if(Wi(e)&&e.tool_call_chunks?.length){const r=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args,index:r.index};continue}}else if(C(a,"server_tool_use")&&S(a.name)&&S(a.id)){const{name:r,id:s}=a;if(r==="web_search"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.query))return a.input.query;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(a.name==="code_execution"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.code))return a.input.code;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(C(a,"web_search_tool_result")&&S(a.tool_use_id)&&Ie(a.content)){const{content:r,tool_use_id:s}=a,i=r.reduce((o,c)=>C(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(C(a,"code_execution_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"mcp_tool_use")){yield{id:a.id,type:"server_tool_call",name:"mcp_tool_use",args:a.input};continue}else if(C(a,"mcp_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:a.input};continue}else if(C(a,"search_result")){yield{id:a.id,type:"non_standard",value:a};continue}else if(C(a,"tool_result")){yield{id:a.id,type:"non_standard",value:a};continue}else{const r=Dr(a);if(r){yield r;continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const Ji={translateContent:Wa,translateContentChunk:Wa};function Wi(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function Ki(e){return da(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ha(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:Mr(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Yi(e){return e.map(Ki)}function Qi(e){return!!(C(e,"image_url")&&k(e.image_url)||C(e,"input_audio")&&k(e.input_audio)||C(e,"file")&&k(e.file))}function Xi(e){if(C(e,"image_url")&&k(e.image_url)&&S(e.image_url.url)){const t=$n({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(C(e,"input_audio")&&k(e.input_audio)&&S(e.input_audio.data)&&S(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(C(e,"file")&&k(e.file)&&S(e.file.data)){const t=$n({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(S(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function eo(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function to(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function ma(e){const t=[];for(const n of e)Qi(n)?t.push(Xi(n)):t.push(n);return t}function no(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:a,end_index:r}=e;return{type:"citation",url:t,title:n,startIndex:a,endIndex:r}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:a}=e;return{type:"citation",title:n,startIndex:a,endIndex:a,fileId:t}}return e}function Fr(e){function*t(){k(e.additional_kwargs?.reasoning)&&Ie(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((r,s)=>k(s)&&S(s.text)?`${r}${s.text}`:r,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n)if(C(a,"text")){const{text:r,annotations:s,...i}=a;Array.isArray(s)?yield{...i,type:"text",text:String(r),annotations:s.map(no)}:yield{...i,type:"text",text:String(r)}}for(const a of e.tool_calls??[])yield{type:"tool_call",id:a.id,name:a.name,args:a.args};if(k(e.additional_kwargs)&&Ie(e.additional_kwargs.tool_outputs))for(const a of e.additional_kwargs.tool_outputs){if(C(a,"web_search_call")){yield{id:a.id,type:"server_tool_call",name:"web_search",args:{query:a.query}};continue}else if(C(a,"file_search_call")){yield{id:a.id,type:"server_tool_call",name:"file_search",args:{query:a.query}};continue}else if(C(a,"computer_call")){yield{type:"non_standard",value:a};continue}else if(C(a,"code_interpreter_call")){if(S(a.code)&&(yield{id:a.id,type:"server_tool_call",name:"code_interpreter",args:{code:a.code}}),Ie(a.outputs)){const r=vt(()=>{if(a.status!=="in_progress"){if(a.status==="completed")return 0;if(a.status==="incomplete")return 127;if(a.status!=="interpreting"&&a.status==="failed")return 1}});for(const s of a.outputs)if(C(s,"logs")){yield{type:"server_tool_call_result",toolCallId:a.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:r??0,stderr:[0,void 0].includes(r)?void 0:String(s.logs),stdout:[0,void 0].includes(r)?String(s.logs):void 0}};continue}}continue}else if(C(a,"mcp_call")){yield{id:a.id,type:"server_tool_call",name:"mcp_call",args:a.input};continue}else if(C(a,"mcp_list_tools")){yield{id:a.id,type:"server_tool_call",name:"mcp_list_tools",args:a.input};continue}else if(C(a,"mcp_approval_request")){yield{type:"non_standard",value:a};continue}else if(C(a,"image_generation_call")){yield{type:"non_standard",value:a};continue}k(a)&&(yield{type:"non_standard",value:a})}}return Array.from(t())}function ao(e){function*t(){yield*Fr(e);for(const n of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(t())}const ro={translateContent:e=>typeof e.content=="string"?eo(e):Fr(e),translateContentChunk:e=>typeof e.content=="string"?to(e):ao(e)};function so(e,t="pretty"){return t==="pretty"?io(e):JSON.stringify(e)}function io(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-n.length)/2),r="=".repeat(a),s=n.length%2===0?r:`${r}=`;if(t.push(`${r}${n}${s}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
2
2
  `)}const yn=Symbol.for("langchain.message");function Xe(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.some(n=>Ue(n))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?Ot(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(n=>Ue(n))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function Ur(e,t){return e==="error"||t==="error"?"error":"success"}function oo(e,t){function n(a,r){if(typeof a!="object"||a===null||a===void 0)return a;if(r>=t)return Array.isArray(a)?"[Array]":"[Object]";if(Array.isArray(a))return a.map(i=>n(i,r+1));const s={};for(const i of Object.keys(a))s[i]=n(a[i],r+1);return s}return JSON.stringify(n(e,0),null,2)}var Le=class extends lt{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[yn]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){const t=typeof e=="string"||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):t.content!==void 0?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){const e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Yi,ma,qi].reduce((a,r)=>r(a),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&yn in e&&e[yn]===!0&&$r(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=oo(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return so(this,e)}};function co(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}function ee(e={},t={}){const n={...e};for(const[a,r]of Object.entries(t))if(n[a]==null)n[a]=r;else{if(r==null)continue;if(typeof n[a]!=typeof r||Array.isArray(n[a])!==Array.isArray(r))throw new Error(`field[${a}] already exists in the message chunk, but with a different type.`);if(typeof n[a]=="string"){if(a==="type")continue;["id","name","output_version","model_provider"].includes(a)?n[a]=r:n[a]+=r}else if(typeof n[a]=="object"&&!Array.isArray(n[a]))n[a]=ee(n[a],r);else if(Array.isArray(n[a]))n[a]=Ot(n[a],r);else{if(n[a]===r)continue;console.warn(`field[${a}] already exists in this message chunk and value has unsupported type.`)}}return n}function Ot(e,t){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)return e||t;{const n=[...e];for(const a of t)if(typeof a=="object"&&a!==null&&"index"in a&&typeof a.index=="number"){const r=n.findIndex(s=>{const i=typeof s=="object",o="index"in s&&s.index===a.index,c="id"in s&&"id"in a&&s?.id===a?.id,l=!("id"in s)||!s?.id||!("id"in a)||!a?.id;return i&&o&&(c||l)});r!==-1&&typeof n[r]=="object"&&n[r]!==null?n[r]=ee(n[r],a):n.push(a)}else{if(typeof a=="object"&&a!==null&&"text"in a&&a.text==="")continue;n.push(a)}return n}}}function Br(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(!e||!t)return e||t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.
3
3
  Left ${typeof e}
4
4
  Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return Ot(e,t);if(typeof e=="object"&&typeof t=="object")return ee(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.
@@ -1,4 +1,4 @@
1
- import{B as $n,O as bt,l as jn,p as nn,f as xt,H as St,j as Bn,k as Ln,c as A,b as kt,m as Un,n as qn,h as Wn,g as Fn,t as be,i as Mt,C as Dn,R as Tt,o as Hn}from"./index-BQq1v1lw.js";import"./chunk-VL2OQCWN-BSY6s1ZW.js";import"./index-C8x1o6em.js";import"./index-DRz5BQNA.js";var Rt=class extends $n{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(s){throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const n=await jn(this.zodSchema,e);if(n.success)return n.data;throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:i}=r;return Array.isArray(i.content)?sn(i.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}};function sn(t){const e=[];for(const n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}function Kn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}function Jn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Xn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function zn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function Vn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const Qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=nn({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Gn=t=>t();function Yn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Zn(t){function*e(){for(const n of t)Yn(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function G(t){return typeof t=="string"?t:es(t)}function es(t){const e=[];for(let n=0,{length:s}=t;n<s;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function Ve(t){return(t??"").split(";")[0].toLowerCase()}function he(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function H(t,e){const n=he(e,"cache_control");n!==void 0&&(t.cache_control=n);const s=he(e,"citations");s!==void 0&&(t.citations=s);const r=he(e,"context");r!==void 0&&(t.context=r);const i=he(e,"title");return i!==void 0&&(t.title=i),t}function Qe(t,e){const n=he(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function At(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function ts(t){const e=[],n=t.response_metadata,s="model_provider"in n&&n?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Zn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const i=Gn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:i})}else if(r.type==="reasoning"&&s)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&s)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&s)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const i=r.output.urls.map(a=>({type:"web_search_result",title:"",encrypted_content:"",url:a}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:i})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const i=r.metadata;if(r.fileId){e.push(H({type:"document",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){const a=Ve(r.mimeType);if(a==="application/pdf"||a===""){e.push(H({type:"document",source:{type:"url",url:r.url}},i));continue}}if(r.data){const a=Ve(r.mimeType);if(a===""||a==="application/pdf")e.push(H({type:"document",source:{type:"base64",data:G(r.data),media_type:"application/pdf"}},i));else if(a==="text/plain")e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},i));else if(At(a))e.push(H({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:G(r.data),media_type:a}}]}},i));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${a}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const i=r.metadata;if(r.fileId){e.push(Qe({type:"image",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){e.push(Qe({type:"image",source:{type:"url",url:r.url}},i));continue}if(r.data){const a=Ve(r.mimeType)||"image/png";At(a)&&e.push(Qe({type:"image",source:{type:"base64",data:G(r.data),media_type:a}},i));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&s&&e.push(r.value))}return e}function vt(t){const e=nn({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
1
+ import{B as $n,O as bt,l as jn,p as nn,f as xt,H as St,j as Bn,k as Ln,c as A,b as kt,m as Un,n as qn,h as Wn,g as Fn,t as be,i as Mt,C as Dn,R as Tt,o as Hn}from"./index-CeVhU8eb.js";import"./chunk-VL2OQCWN-DBinT58-.js";import"./index-CNwZaJQ9.js";import"./index-DRz5BQNA.js";var Rt=class extends $n{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(s){throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const n=await jn(this.zodSchema,e);if(n.success)return n.data;throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:i}=r;return Array.isArray(i.content)?sn(i.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}};function sn(t){const e=[];for(const n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}function Kn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}function Jn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Xn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function zn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function Vn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const Qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=nn({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Gn=t=>t();function Yn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Zn(t){function*e(){for(const n of t)Yn(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function G(t){return typeof t=="string"?t:es(t)}function es(t){const e=[];for(let n=0,{length:s}=t;n<s;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function Ve(t){return(t??"").split(";")[0].toLowerCase()}function he(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function H(t,e){const n=he(e,"cache_control");n!==void 0&&(t.cache_control=n);const s=he(e,"citations");s!==void 0&&(t.citations=s);const r=he(e,"context");r!==void 0&&(t.context=r);const i=he(e,"title");return i!==void 0&&(t.title=i),t}function Qe(t,e){const n=he(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function At(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function ts(t){const e=[],n=t.response_metadata,s="model_provider"in n&&n?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Zn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const i=Gn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:i})}else if(r.type==="reasoning"&&s)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&s)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&s)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const i=r.output.urls.map(a=>({type:"web_search_result",title:"",encrypted_content:"",url:a}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:i})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const i=r.metadata;if(r.fileId){e.push(H({type:"document",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){const a=Ve(r.mimeType);if(a==="application/pdf"||a===""){e.push(H({type:"document",source:{type:"url",url:r.url}},i));continue}}if(r.data){const a=Ve(r.mimeType);if(a===""||a==="application/pdf")e.push(H({type:"document",source:{type:"base64",data:G(r.data),media_type:"application/pdf"}},i));else if(a==="text/plain")e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},i));else if(At(a))e.push(H({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:G(r.data),media_type:a}}]}},i));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${a}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const i=r.metadata;if(r.fileId){e.push(Qe({type:"image",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){e.push(Qe({type:"image",source:{type:"url",url:r.url}},i));continue}if(r.data){const a=Ve(r.mimeType)||"image/png";At(a)&&e.push(Qe({type:"image",source:{type:"base64",data:G(r.data),media_type:a}},i));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&s&&e.push(r.value))}return e}function vt(t){const e=nn({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
2
2
 
3
3
  `))}if(n.protocol==="http:"||n.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
4
4
 
@@ -1,4 +1,4 @@
1
- import{Langfuse as T}from"./index-baibQX1A.js";import{B as I,a as v,A as g,b as y,H as M,C as S,S as w,F as D,T as b}from"./langfuse-C4HKZ3NL-CPjc-isq.js";import"./index-C8x1o6em.js";import"./chunk-VL2OQCWN-BSY6s1ZW.js";import"./index-DRz5BQNA.js";import"./__vite-browser-external-DFygW7-s.js";import"./path-C9FudP8b.js";const u="langsmith:hidden";class k extends I{constructor(t){super(),this.name="CallbackHandler",this.rootProvided=!1,this.updateRoot=!1,this.debugEnabled=!1,this.completionStartTimes={},t&&"root"in t?(this.langfuse=t.root.client,this.rootObservationId=t.root.observationId??void 0,this.traceId=t.root.traceId,this.rootProvided=!0,this.updateRoot=t.updateRoot??!1,this.metadata=t.metadata):(this.langfuse=new T({...t,persistence:"memory",sdkIntegration:t?.sdkIntegration??"LANGCHAIN"}),this.sessionId=t?.sessionId,this.userId=t?.userId,this.metadata=t?.metadata,this.tags=t?.tags),this.version=t?.version,this.promptToParentRunMap=new Map,this.traceUpdates=new Map}async flushAsync(){return this.langfuse.flushAsync()}async shutdownAsync(){return this.langfuse.shutdownAsync()}debug(t=!0){this.langfuse.debug(t),this.debugEnabled=t}_log(t){this.debugEnabled&&console.log(t)}async handleNewToken(t,e){return e&&!(e in this.completionStartTimes)&&(this._log(`LLM first streaming token: ${e}`),this.completionStartTimes[e]=new Date),Promise.resolve()}async handleLLMNewToken(t,e,s,i,n,a){return s&&!(s in this.completionStartTimes)&&(this._log(`LLM first streaming token: ${s}`),this.completionStartTimes[s]=new Date),Promise.resolve()}getTraceId(){return this.traceId}getTraceUrl(){return this.traceId?`${this.langfuse.baseUrl}/trace/${this.traceId}`:void 0}getLangchainRunId(){return this.topLevelObservationId}async handleRetrieverError(t,e,s){try{this._log(`Retriever error: ${t} with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString(),endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString())}catch(i){this._log(i)}}async handleChainStart(t,e,s,i,n,a,o,h){try{this._log(`Chain start with Id: ${s}`);const d=h??t.id.at(-1)?.toString()??"Langchain Run";this.registerLangfusePrompt(i,a);let r=e;typeof e=="object"&&"input"in e&&Array.isArray(e.input)&&e.input.every(l=>l instanceof v)?r=e.input.map(l=>this.extractChatMessageContent(l)):typeof e=="object"&&"content"in e&&typeof e.content=="string"&&(r=e.content),this.generateTrace(d,s,i,n,a,r),this.langfuse.span({id:s,traceId:this.traceId,parentObservationId:i??this.rootObservationId,name:d,metadata:this.joinTagsAndMetaData(n,a),input:r,version:this.version,level:n&&n.includes(u)?"DEBUG":void 0}),i||this.traceUpdates.set(s,{tags:n,userId:a&&"langfuseUserId"in a&&typeof a.langfuseUserId=="string"?a.langfuseUserId:void 0,sessionId:a&&"langfuseSessionId"in a&&typeof a.langfuseSessionId=="string"?a.langfuseSessionId:void 0})}catch(d){this._log(d)}}registerLangfusePrompt(t,e){e&&"langfusePrompt"in e&&t&&this.promptToParentRunMap.set(t,e.langfusePrompt)}deregisterLangfusePrompt(t){this.promptToParentRunMap.delete(t)}async handleAgentAction(t,e,s){try{this._log(`Agent action with ID: ${e}`),this.langfuse.span({id:e,parentObservationId:s,traceId:this.traceId,endTime:new Date,input:t,version:this.version})}catch(i){this._log(i)}}async handleAgentEnd(t,e,s){try{this._log(`Agent finish with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,endTime:new Date,output:t,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleChainError(t,e,s){try{this._log(`Chain error: ${t} with ID: ${e}`);const i=this.parseAzureRefusalError(t);this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString()+i,endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString()+i)}catch(i){this._log(i)}}generateTrace(t,e,s,i,n,a){this.traceId&&!s&&!this.rootProvided&&(this.traceId=void 0,this.topLevelObservationId=void 0);const o={name:t,metadata:this.joinTagsAndMetaData(i,n,this.metadata),userId:this.userId,version:this.version,sessionId:this.sessionId,input:a,tags:this.tags};this.traceId||(this.langfuse.trace({id:e,...o}),this.traceId=e),this.rootProvided&&this.updateRoot&&(this.rootObservationId?this.langfuse._updateSpan({id:this.rootObservationId,traceId:this.traceId,...o}):this.langfuse.trace({id:this.traceId,...o})),this.topLevelObservationId=s?this.topLevelObservationId:e}async handleGenerationStart(t,e,s,i,n,a,o,h){this._log(`Generation start with ID: ${s}`);const d=h??t.id.at(-1)?.toString()??"Langchain Generation";this.generateTrace(d,s,i,a,o,e);const r={},l=n?.invocation_params;for(const[f,c]of Object.entries({temperature:l?.temperature,max_tokens:l?.max_tokens,top_p:l?.top_p,frequency_penalty:l?.frequency_penalty,presence_penalty:l?.presence_penalty,request_timeout:l?.request_timeout}))c!=null&&(r[f]=c);let _;if(n){const f=n.invocation_params.model,c=o&&"ls_model_name"in o?o.ls_model_name:void 0;_=f??c}const m=this.promptToParentRunMap.get(i??"root");m&&i&&this.deregisterLangfusePrompt(i),this.langfuse.generation({id:s,traceId:this.traceId,name:h??t.id.at(-1)?.toString(),metadata:this.joinTagsAndMetaData(a,o),parentObservationId:i??this.rootObservationId,input:e,model:_,modelParameters:r,version:this.version,prompt:m,level:a&&a.includes(u)?"DEBUG":void 0})}async handleChatModelStart(t,e,s,i,n,a,o,h){try{this._log(`Chat model start with ID: ${s}`);const d=e.flatMap(r=>r.map(l=>this.extractChatMessageContent(l)));this.handleGenerationStart(t,d,s,i,n,a,o,h)}catch(d){this._log(d)}}async handleChainEnd(t,e,s){try{this._log(`Chain end with ID: ${e}`);let i=t;typeof t=="object"&&"output"in t&&typeof t.output=="string"&&(i=t.output),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:i,endTime:new Date,version:this.version}),this.updateTrace(e,s,i),this.deregisterLangfusePrompt(e)}catch(i){this._log(i)}}async handleLLMStart(t,e,s,i,n,a,o,h){try{this._log(`LLM start with ID: ${s}`),this.handleGenerationStart(t,e,s,i,n,a,o,h)}catch(d){this._log(d)}}async handleToolStart(t,e,s,i,n,a,o){try{this._log(`Tool start with ID: ${s}`),this.langfuse.span({id:s,parentObservationId:i,traceId:this.traceId,name:o??t.id.at(-1)?.toString(),input:e,metadata:this.joinTagsAndMetaData(n,a),version:this.version,level:n&&n.includes(u)?"DEBUG":void 0})}catch(h){this._log(h)}}async handleRetrieverStart(t,e,s,i,n,a,o){try{this._log(`Retriever start with ID: ${s}`),this.langfuse.span({id:s,parentObservationId:i,traceId:this.traceId,name:o??t.id.at(-1)?.toString(),input:e,metadata:this.joinTagsAndMetaData(n,a),version:this.version,level:n&&n.includes(u)?"DEBUG":void 0})}catch(h){this._log(h)}}async handleRetrieverEnd(t,e,s){try{this._log(`Retriever end with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:t,endTime:new Date,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleToolEnd(t,e,s){try{this._log(`Tool end with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:t,endTime:new Date,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleToolError(t,e,s){try{this._log(`Tool error ${t} with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString(),endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString())}catch(i){this._log(i)}}async handleLLMEnd(t,e,s){try{this._log(`LLM end with ID: ${e}`);const i=t.generations[t.generations.length-1][t.generations[t.generations.length-1].length-1],n=this.extractUsageMetadata(i)??t.llmOutput?.tokenUsage,a=this.extractModelNameFromMetadata(i),o={input:n?.input_tokens??("promptTokens"in n?n?.promptTokens:void 0),output:n?.output_tokens??("completionTokens"in n?n?.completionTokens:void 0),total:n?.total_tokens??("totalTokens"in n?n?.totalTokens:void 0)};if(n&&"input_token_details"in n)for(const[d,r]of Object.entries(n.input_token_details??{}))o[`input_${d}`]=r,"input"in o&&typeof r=="number"&&(o.input=Math.max(0,o.input-r));if(n&&"output_token_details"in n)for(const[d,r]of Object.entries(n.output_token_details??{}))o[`output_${d}`]=r,"output"in o&&typeof r=="number"&&(o.output=Math.max(0,o.output-r));const h="message"in i&&i.message instanceof v?this.extractChatMessageContent(i.message):i.text;this.langfuse._updateGeneration({id:e,model:a,traceId:this.traceId,output:h,endTime:new Date,completionStartTime:e in this.completionStartTimes?this.completionStartTimes[e]:void 0,usage:o,usageDetails:o,version:this.version}),e in this.completionStartTimes&&delete this.completionStartTimes[e],this.updateTrace(e,s,h)}catch(i){this._log(i)}}extractUsageMetadata(t){try{return"message"in t&&(t.message instanceof g||t.message instanceof y)?t.message.usage_metadata:void 0}catch(e){this._log(`Error extracting usage metadata: ${e}`);return}}extractModelNameFromMetadata(t){try{return"message"in t&&(t.message instanceof g||t.message instanceof y)?t.message.response_metadata.model_name:void 0}catch{}}extractChatMessageContent(t){let e;return t instanceof M?e={content:t.content,role:"user"}:t instanceof S?e={content:t.content,role:t.role}:t instanceof g?e={content:t.content,role:"assistant"}:t instanceof w?e={content:t.content,role:"system"}:t instanceof D?e={content:t.content,additional_kwargs:t.additional_kwargs,role:t.name}:t instanceof b?e={content:t.content,additional_kwargs:t.additional_kwargs,role:t.name}:t.name?e={role:t.name,content:t.content}:e={content:t.content},t.additional_kwargs.function_call||t.additional_kwargs.tool_calls?{...e,additional_kwargs:t.additional_kwargs}:e}async handleLLMError(t,e,s){try{this._log(`LLM error ${t} with ID: ${e}`);const i=this.parseAzureRefusalError(t);this.langfuse._updateGeneration({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString()+i,endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString()+i)}catch(i){this._log(i)}}parseAzureRefusalError(t){let e="";if(typeof t=="object"&&"error"in t)try{e=`
1
+ import{Langfuse as T}from"./index-98gc3IlW.js";import{B as I,a as v,A as g,b as y,H as M,C as S,S as w,F as D,T as b}from"./langfuse-C4HKZ3NL-BR3E7iCI.js";import"./index-CNwZaJQ9.js";import"./chunk-VL2OQCWN-DBinT58-.js";import"./index-DRz5BQNA.js";import"./__vite-browser-external-DFygW7-s.js";import"./path-C9FudP8b.js";const u="langsmith:hidden";class k extends I{constructor(t){super(),this.name="CallbackHandler",this.rootProvided=!1,this.updateRoot=!1,this.debugEnabled=!1,this.completionStartTimes={},t&&"root"in t?(this.langfuse=t.root.client,this.rootObservationId=t.root.observationId??void 0,this.traceId=t.root.traceId,this.rootProvided=!0,this.updateRoot=t.updateRoot??!1,this.metadata=t.metadata):(this.langfuse=new T({...t,persistence:"memory",sdkIntegration:t?.sdkIntegration??"LANGCHAIN"}),this.sessionId=t?.sessionId,this.userId=t?.userId,this.metadata=t?.metadata,this.tags=t?.tags),this.version=t?.version,this.promptToParentRunMap=new Map,this.traceUpdates=new Map}async flushAsync(){return this.langfuse.flushAsync()}async shutdownAsync(){return this.langfuse.shutdownAsync()}debug(t=!0){this.langfuse.debug(t),this.debugEnabled=t}_log(t){this.debugEnabled&&console.log(t)}async handleNewToken(t,e){return e&&!(e in this.completionStartTimes)&&(this._log(`LLM first streaming token: ${e}`),this.completionStartTimes[e]=new Date),Promise.resolve()}async handleLLMNewToken(t,e,s,i,n,a){return s&&!(s in this.completionStartTimes)&&(this._log(`LLM first streaming token: ${s}`),this.completionStartTimes[s]=new Date),Promise.resolve()}getTraceId(){return this.traceId}getTraceUrl(){return this.traceId?`${this.langfuse.baseUrl}/trace/${this.traceId}`:void 0}getLangchainRunId(){return this.topLevelObservationId}async handleRetrieverError(t,e,s){try{this._log(`Retriever error: ${t} with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString(),endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString())}catch(i){this._log(i)}}async handleChainStart(t,e,s,i,n,a,o,h){try{this._log(`Chain start with Id: ${s}`);const d=h??t.id.at(-1)?.toString()??"Langchain Run";this.registerLangfusePrompt(i,a);let r=e;typeof e=="object"&&"input"in e&&Array.isArray(e.input)&&e.input.every(l=>l instanceof v)?r=e.input.map(l=>this.extractChatMessageContent(l)):typeof e=="object"&&"content"in e&&typeof e.content=="string"&&(r=e.content),this.generateTrace(d,s,i,n,a,r),this.langfuse.span({id:s,traceId:this.traceId,parentObservationId:i??this.rootObservationId,name:d,metadata:this.joinTagsAndMetaData(n,a),input:r,version:this.version,level:n&&n.includes(u)?"DEBUG":void 0}),i||this.traceUpdates.set(s,{tags:n,userId:a&&"langfuseUserId"in a&&typeof a.langfuseUserId=="string"?a.langfuseUserId:void 0,sessionId:a&&"langfuseSessionId"in a&&typeof a.langfuseSessionId=="string"?a.langfuseSessionId:void 0})}catch(d){this._log(d)}}registerLangfusePrompt(t,e){e&&"langfusePrompt"in e&&t&&this.promptToParentRunMap.set(t,e.langfusePrompt)}deregisterLangfusePrompt(t){this.promptToParentRunMap.delete(t)}async handleAgentAction(t,e,s){try{this._log(`Agent action with ID: ${e}`),this.langfuse.span({id:e,parentObservationId:s,traceId:this.traceId,endTime:new Date,input:t,version:this.version})}catch(i){this._log(i)}}async handleAgentEnd(t,e,s){try{this._log(`Agent finish with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,endTime:new Date,output:t,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleChainError(t,e,s){try{this._log(`Chain error: ${t} with ID: ${e}`);const i=this.parseAzureRefusalError(t);this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString()+i,endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString()+i)}catch(i){this._log(i)}}generateTrace(t,e,s,i,n,a){this.traceId&&!s&&!this.rootProvided&&(this.traceId=void 0,this.topLevelObservationId=void 0);const o={name:t,metadata:this.joinTagsAndMetaData(i,n,this.metadata),userId:this.userId,version:this.version,sessionId:this.sessionId,input:a,tags:this.tags};this.traceId||(this.langfuse.trace({id:e,...o}),this.traceId=e),this.rootProvided&&this.updateRoot&&(this.rootObservationId?this.langfuse._updateSpan({id:this.rootObservationId,traceId:this.traceId,...o}):this.langfuse.trace({id:this.traceId,...o})),this.topLevelObservationId=s?this.topLevelObservationId:e}async handleGenerationStart(t,e,s,i,n,a,o,h){this._log(`Generation start with ID: ${s}`);const d=h??t.id.at(-1)?.toString()??"Langchain Generation";this.generateTrace(d,s,i,a,o,e);const r={},l=n?.invocation_params;for(const[f,c]of Object.entries({temperature:l?.temperature,max_tokens:l?.max_tokens,top_p:l?.top_p,frequency_penalty:l?.frequency_penalty,presence_penalty:l?.presence_penalty,request_timeout:l?.request_timeout}))c!=null&&(r[f]=c);let _;if(n){const f=n.invocation_params.model,c=o&&"ls_model_name"in o?o.ls_model_name:void 0;_=f??c}const m=this.promptToParentRunMap.get(i??"root");m&&i&&this.deregisterLangfusePrompt(i),this.langfuse.generation({id:s,traceId:this.traceId,name:h??t.id.at(-1)?.toString(),metadata:this.joinTagsAndMetaData(a,o),parentObservationId:i??this.rootObservationId,input:e,model:_,modelParameters:r,version:this.version,prompt:m,level:a&&a.includes(u)?"DEBUG":void 0})}async handleChatModelStart(t,e,s,i,n,a,o,h){try{this._log(`Chat model start with ID: ${s}`);const d=e.flatMap(r=>r.map(l=>this.extractChatMessageContent(l)));this.handleGenerationStart(t,d,s,i,n,a,o,h)}catch(d){this._log(d)}}async handleChainEnd(t,e,s){try{this._log(`Chain end with ID: ${e}`);let i=t;typeof t=="object"&&"output"in t&&typeof t.output=="string"&&(i=t.output),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:i,endTime:new Date,version:this.version}),this.updateTrace(e,s,i),this.deregisterLangfusePrompt(e)}catch(i){this._log(i)}}async handleLLMStart(t,e,s,i,n,a,o,h){try{this._log(`LLM start with ID: ${s}`),this.handleGenerationStart(t,e,s,i,n,a,o,h)}catch(d){this._log(d)}}async handleToolStart(t,e,s,i,n,a,o){try{this._log(`Tool start with ID: ${s}`),this.langfuse.span({id:s,parentObservationId:i,traceId:this.traceId,name:o??t.id.at(-1)?.toString(),input:e,metadata:this.joinTagsAndMetaData(n,a),version:this.version,level:n&&n.includes(u)?"DEBUG":void 0})}catch(h){this._log(h)}}async handleRetrieverStart(t,e,s,i,n,a,o){try{this._log(`Retriever start with ID: ${s}`),this.langfuse.span({id:s,parentObservationId:i,traceId:this.traceId,name:o??t.id.at(-1)?.toString(),input:e,metadata:this.joinTagsAndMetaData(n,a),version:this.version,level:n&&n.includes(u)?"DEBUG":void 0})}catch(h){this._log(h)}}async handleRetrieverEnd(t,e,s){try{this._log(`Retriever end with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:t,endTime:new Date,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleToolEnd(t,e,s){try{this._log(`Tool end with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:t,endTime:new Date,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleToolError(t,e,s){try{this._log(`Tool error ${t} with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString(),endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString())}catch(i){this._log(i)}}async handleLLMEnd(t,e,s){try{this._log(`LLM end with ID: ${e}`);const i=t.generations[t.generations.length-1][t.generations[t.generations.length-1].length-1],n=this.extractUsageMetadata(i)??t.llmOutput?.tokenUsage,a=this.extractModelNameFromMetadata(i),o={input:n?.input_tokens??("promptTokens"in n?n?.promptTokens:void 0),output:n?.output_tokens??("completionTokens"in n?n?.completionTokens:void 0),total:n?.total_tokens??("totalTokens"in n?n?.totalTokens:void 0)};if(n&&"input_token_details"in n)for(const[d,r]of Object.entries(n.input_token_details??{}))o[`input_${d}`]=r,"input"in o&&typeof r=="number"&&(o.input=Math.max(0,o.input-r));if(n&&"output_token_details"in n)for(const[d,r]of Object.entries(n.output_token_details??{}))o[`output_${d}`]=r,"output"in o&&typeof r=="number"&&(o.output=Math.max(0,o.output-r));const h="message"in i&&i.message instanceof v?this.extractChatMessageContent(i.message):i.text;this.langfuse._updateGeneration({id:e,model:a,traceId:this.traceId,output:h,endTime:new Date,completionStartTime:e in this.completionStartTimes?this.completionStartTimes[e]:void 0,usage:o,usageDetails:o,version:this.version}),e in this.completionStartTimes&&delete this.completionStartTimes[e],this.updateTrace(e,s,h)}catch(i){this._log(i)}}extractUsageMetadata(t){try{return"message"in t&&(t.message instanceof g||t.message instanceof y)?t.message.usage_metadata:void 0}catch(e){this._log(`Error extracting usage metadata: ${e}`);return}}extractModelNameFromMetadata(t){try{return"message"in t&&(t.message instanceof g||t.message instanceof y)?t.message.response_metadata.model_name:void 0}catch{}}extractChatMessageContent(t){let e;return t instanceof M?e={content:t.content,role:"user"}:t instanceof S?e={content:t.content,role:t.role}:t instanceof g?e={content:t.content,role:"assistant"}:t instanceof w?e={content:t.content,role:"system"}:t instanceof D?e={content:t.content,additional_kwargs:t.additional_kwargs,role:t.name}:t instanceof b?e={content:t.content,additional_kwargs:t.additional_kwargs,role:t.name}:t.name?e={role:t.name,content:t.content}:e={content:t.content},t.additional_kwargs.function_call||t.additional_kwargs.tool_calls?{...e,additional_kwargs:t.additional_kwargs}:e}async handleLLMError(t,e,s){try{this._log(`LLM error ${t} with ID: ${e}`);const i=this.parseAzureRefusalError(t);this.langfuse._updateGeneration({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString()+i,endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString()+i)}catch(i){this._log(i)}}parseAzureRefusalError(t){let e="";if(typeof t=="object"&&"error"in t)try{e=`
2
2
 
3
3
  Error details:
4
4
  `+JSON.stringify(t.error,null,2)}catch{}return e}updateTrace(t,e,s){const i=this.traceUpdates.get(t);this.traceUpdates.delete(t),!e&&this.traceId&&this.traceId===t&&this.langfuse.trace({id:this.traceId,output:s,...i}),!e&&this.traceId&&this.rootProvided&&this.updateRoot&&(this.rootObservationId?this.langfuse._updateSpan({id:this.rootObservationId,traceId:this.traceId,output:s}):this.langfuse.trace({id:this.traceId,output:s,...i}))}joinTagsAndMetaData(t,e,s){const i={};return t&&t.length>0&&(i.tags=t),e&&Object.assign(i,e),s&&Object.assign(i,s),this.stripLangfuseKeysFromMetadata(i)}stripLangfuseKeysFromMetadata(t){if(!t)return;const e=["langfusePrompt","langfuseUserId","langfuseSessionId"];return Object.fromEntries(Object.entries(t).filter(([s,i])=>!e.includes(s)))}}const P=async p=>{const{runName:t,item:e,langfuseClient:s,options:i}=p,n={dataset_item_id:e.id,dataset_id:e.datasetId,dataset_run_name:t},a=s.trace();return await e.link(a,t,{description:i?.runDescription,metadata:i?.runMetadata}),{handler:new k({root:a,updateRoot:!0,metadata:n}),trace:a}};export{k as CallbackHandler,T as Langfuse,P as createDatasetItemHandler,k as default};
@@ -1,4 +1,4 @@
1
- import{d as js,g as Ds,q as Wa,r as qa,s as Ja,l as Ka,O as Fs,u as za,f as Bs,v as Za,_ as gn,m as Ha,n as zn,i as Oe,h as Us,S as Zn,J as Hn,t as Ze,w as Va,x as Xa,R as Vn,o as Ga,j as Ws,k as qs,b as xe,T as ht,y as Qa,c as _n,z as Xn,F as Ya,D as ei,E as ti,p as Gn,G as Qn,I as ni,C as Xt,K as si,L as nt,M as ri,N as ai,P as ii,Q as Yn,U as oi,V as li,W as ci,X as Gt,Y as ui,Z as di,$ as hi,a0 as Bt,a1 as fi,a2 as yn,a3 as pi,a4 as mi,a5 as gi,a6 as es,a7 as ts,a8 as ns,a9 as _i,aa as yi}from"./index-BQq1v1lw.js";import{Z as A,o as wi,s as bi}from"./index-C8x1o6em.js";import{t as Js,i as vi,q as ki,r as xi}from"./chunk-VL2OQCWN-BSY6s1ZW.js";import"./embeddings-BhJwfRpR.js";import"./index-DRz5BQNA.js";const ke=t=>t();function We(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Si(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function qe(t){const e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!js.isInstance(t))throw new Error("Invalid generic chat message");return Si(t);default:throw new Error(`Unknown message type: ${e}`)}}function Ai(t){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:s,azureOpenAIBasePath:r,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=t;if((s||i)&&r&&e)return`${r}/${e}`;if((s||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(s||i){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return a}function Ci(t,e){let n;return Ds(t)?n=Wa(t):n=t,e?.strict!==void 0&&(n.function.strict=e.strict),n}function Oi(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Ti(t){const e=["namespace functions {",""];for(const n of t)n.description&&e.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(e.push(`type ${n.name} = (_: {`),e.push(Ks(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
1
+ import{d as js,g as Ds,q as Wa,r as qa,s as Ja,l as Ka,O as Fs,u as za,f as Bs,v as Za,_ as gn,m as Ha,n as zn,i as Oe,h as Us,S as Zn,J as Hn,t as Ze,w as Va,x as Xa,R as Vn,o as Ga,j as Ws,k as qs,b as xe,T as ht,y as Qa,c as _n,z as Xn,F as Ya,D as ei,E as ti,p as Gn,G as Qn,I as ni,C as Xt,K as si,L as nt,M as ri,N as ai,P as ii,Q as Yn,U as oi,V as li,W as ci,X as Gt,Y as ui,Z as di,$ as hi,a0 as Bt,a1 as fi,a2 as yn,a3 as pi,a4 as mi,a5 as gi,a6 as es,a7 as ts,a8 as ns,a9 as _i,aa as yi}from"./index-CeVhU8eb.js";import{Z as A,o as wi,s as bi}from"./index-CNwZaJQ9.js";import{t as Js,i as vi,q as ki,r as xi}from"./chunk-VL2OQCWN-DBinT58-.js";import"./embeddings-P__c62U6.js";import"./index-DRz5BQNA.js";const ke=t=>t();function We(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Si(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function qe(t){const e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!js.isInstance(t))throw new Error("Invalid generic chat message");return Si(t);default:throw new Error(`Unknown message type: ${e}`)}}function Ai(t){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:s,azureOpenAIBasePath:r,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=t;if((s||i)&&r&&e)return`${r}/${e}`;if((s||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(s||i){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return a}function Ci(t,e){let n;return Ds(t)?n=Wa(t):n=t,e?.strict!==void 0&&(n.function.strict=e.strict),n}function Oi(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Ti(t){const e=["namespace functions {",""];for(const n of t)n.description&&e.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(e.push(`type ${n.name} = (_: {`),e.push(Ks(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
2
2
  `)}function Ks(t,e){const n=[];for(const[s,r]of Object.entries(t.properties??{}))r.description&&e<2&&n.push(`// ${r.description}`),t.required?.includes(s)?n.push(`${s}: ${ft(r,e)},`):n.push(`${s}?: ${ft(r,e)},`);return n.map(s=>" ".repeat(e)+s).join(`
3
3
  `)}function ft(t,e){if(Oi(t))return t.anyOf.map(n=>ft(n,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(n=>`"${n}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",Ks(t,e+2),"}"].join(`
4
4
  `);case"array":return t.items?`${ft(t.items,e)}[]`:"any[]";default:return""}}function zs(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function wn(t){return"type"in t&&t.type!=="function"}function Ii(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function pt(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function Zs(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Pi(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function Ri(t){return t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function $i(t){const e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function Ei(t){const e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}function Qt(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const Yt=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class k extends Error{}class q extends k{constructor(e,n,s,r){super(`${q.makeMessage(e,n,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=n;const a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,n,s){const r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,n,s,r){if(!e||!r)return new Ot({message:s,cause:Yt(n)});const a=n?.error;return e===400?new Hs(e,a,s,r):e===401?new Vs(e,a,s,r):e===403?new Xs(e,a,s,r):e===404?new Gs(e,a,s,r):e===409?new Qs(e,a,s,r):e===422?new Ys(e,a,s,r):e===429?new er(e,a,s,r):e>=500?new tr(e,a,s,r):new q(e,a,s,r)}}class X extends q{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Ot extends q{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class Tt extends Ot{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Hs extends q{}class Vs extends q{}class Xs extends q{}class Gs extends q{}class Qs extends q{}class Ys extends q{}class er extends q{}class tr extends q{}class nr extends k{constructor(){super("Could not parse response content as the length limit was reached")}}class sr extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Te extends Error{constructor(e){super(e)}}function mt(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Mi(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function bn(t){return t?.$brand==="auto-parseable-response-format"}function Je(t){return t?.$brand==="auto-parseable-tool"}function Ni(t,e){return!e||!rr(e)?{...t,choices:t.choices.map(n=>(ar(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:vn(t,e)}function vn(t,e){const n=t.choices.map(s=>{if(s.finish_reason==="length")throw new nr;if(s.finish_reason==="content_filter")throw new sr;return ar(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>ji(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?Li(e,s.message.content):null}}});return{...t,choices:n}}function Li(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function ji(t,e){const n=t.tools?.find(s=>mt(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Je(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function Di(t,e){if(!t||!("tools"in t)||!t.tools)return!1;const n=t.tools?.find(s=>mt(s)&&s.function?.name===e.function.name);return mt(n)&&(Je(n)||n?.function.strict||!1)}function rr(t){return bn(t.response_format)?!0:t.tools?.some(e=>Je(e)||e.type==="function"&&e.function.strict===!0)??!1}function ar(t){for(const e of t||[])if(e.type!=="function")throw new k(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Fi(t){for(const e of t??[]){if(e.type!=="function")throw new k(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new k(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const Bi=Symbol("Let zodToJsonSchema decide on which parser to use"),ss={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Ui=t=>typeof t=="string"?{...ss,basePath:["#"],definitions:{},name:t}:{...ss,basePath:["#"],definitions:{},...t},en=t=>"_def"in t?t._def:t;function Wi(t){if(!t)return!0;for(const e in t)return!1;return!0}const qi=t=>{const e=Ui(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([s,r])=>[en(r),{def:en(r),path:[...e.basePath,e.definitionPath,s],jsonSchema:void 0}]))}};function ir(t,e,n,s){s?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function P(t,e,n,s,r){t[e]=n,ir(t,e,s,r)}function Ji(){return{}}function Ki(t,e){const n={type:"array"};return t.type?._def?.typeName!==A.ZodAny&&(n.items=T(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&P(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&P(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(P(n,"minItems",t.exactLength.value,t.exactLength.message,e),P(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function zi(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const s of t.checks)switch(s.kind){case"min":e.target==="jsonSchema7"?s.inclusive?P(n,"minimum",s.value,s.message,e):P(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),P(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?P(n,"maximum",s.value,s.message,e):P(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),P(n,"maximum",s.value,s.message,e));break;case"multipleOf":P(n,"multipleOf",s.value,s.message,e);break}return n}function Zi(){return{type:"boolean"}}function Hi(t,e){return T(t.type._def,e)}const Vi=(t,e)=>T(t.innerType._def,e);function or(t,e,n){const s=n??e.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((r,a)=>or(t,e,r))};switch(s){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Xi(t,e)}}const Xi=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const s of t.checks)switch(s.kind){case"min":P(n,"minimum",s.value,s.message,e);break;case"max":P(n,"maximum",s.value,s.message,e);break}return n};function Gi(t,e){return{...T(t.innerType._def,e),default:t.defaultValue()}}function Qi(t,e,n){return e.effectStrategy==="input"?T(t.schema._def,e,n):{}}function Yi(t){return{type:"string",enum:[...t.values]}}const eo=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function to(t,e){const n=[T(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),T(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let s=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const r=[];return n.forEach(a=>{if(eo(a))r.push(...a.allOf),a.unevaluatedProperties===void 0&&(s=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else s=void 0;r.push(i)}}),r.length?{allOf:r,...s}:void 0}function no(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let Ut;const le={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ut===void 0&&(Ut=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ut),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function lr(t,e){const n={type:"string"};function s(r){return e.patternStrategy==="escape"?so(r):r}if(t.checks)for(const r of t.checks)switch(r.kind){case"min":P(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":P(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":G(n,"email",r.message,e);break;case"format:idn-email":G(n,"idn-email",r.message,e);break;case"pattern:zod":Q(n,le.email,r.message,e);break}break;case"url":G(n,"uri",r.message,e);break;case"uuid":G(n,"uuid",r.message,e);break;case"regex":Q(n,r.regex,r.message,e);break;case"cuid":Q(n,le.cuid,r.message,e);break;case"cuid2":Q(n,le.cuid2,r.message,e);break;case"startsWith":Q(n,RegExp(`^${s(r.value)}`),r.message,e);break;case"endsWith":Q(n,RegExp(`${s(r.value)}$`),r.message,e);break;case"datetime":G(n,"date-time",r.message,e);break;case"date":G(n,"date",r.message,e);break;case"time":G(n,"time",r.message,e);break;case"duration":G(n,"duration",r.message,e);break;case"length":P(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),P(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Q(n,RegExp(s(r.value)),r.message,e);break}case"ip":{r.version!=="v6"&&G(n,"ipv4",r.message,e),r.version!=="v4"&&G(n,"ipv6",r.message,e);break}case"emoji":Q(n,le.emoji,r.message,e);break;case"ulid":{Q(n,le.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{G(n,"binary",r.message,e);break}case"contentEncoding:base64":{P(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Q(n,le.base64,r.message,e);break}}break}case"nanoid":Q(n,le.nanoid,r.message,e)}return n}const so=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),G=(t,e,n,s)=>{t.format||t.anyOf?.some(r=>r.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&s.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&s.errorMessages&&{errorMessage:{format:n}}})):P(t,"format",e,n,s)},Q=(t,e,n,s)=>{t.pattern||t.allOf?.some(r=>r.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&s.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:rs(e,s),...n&&s.errorMessages&&{errorMessage:{pattern:n}}})):P(t,"pattern",rs(e,s),n,s)},rs=(t,e)=>{const n=typeof t=="function"?t():t;if(!e.applyRegexFlags||!n.flags)return n.source;const s={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=s.i?n.source.toLowerCase():n.source;let a="",i=!1,o=!1,c=!1;for(let l=0;l<r.length;l++){if(i){a+=r[l],i=!1;continue}if(s.i){if(o){if(r[l].match(/[a-z]/)){c?(a+=r[l],a+=`${r[l-2]}-${r[l]}`.toUpperCase(),c=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(a+=r[l],c=!0):a+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){a+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(s.m){if(r[l]==="^"){a+=`(^|(?<=[\r
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-v8aqAKR2.js","assets/index-baibQX1A.js","assets/index-C8x1o6em.js","assets/index-Bx3FWJNp.css","assets/chunk-VL2OQCWN-BSY6s1ZW.js","assets/index-DRz5BQNA.js","assets/__vite-browser-external-DFygW7-s.js","assets/path-C9FudP8b.js"])))=>i.map(i=>d[i]);
2
- var yy=Object.defineProperty;var _y=(e,t,n)=>t in e?yy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var du=(e,t,n)=>_y(e,typeof t!="symbol"?t+"":t,n);import{_ as G,c as Wi,u as gt,a as Tt,d as bs,n as le,s as pe,e as Jt,o as Y,f as wy,Z as M,h as nt,i as hu,l as vr,j as vy,k as Fa,p as sh,m as Ur,r as Ss,q as Ua,t as E,v as by,w as Ba,B as Sy,x as Ty,H as Ey,L as Cy,y as Ay,M as ky,W as Oy,z as xy}from"./index-C8x1o6em.js";import{u as Iy,w as Hc,x as Py,y as ze,z as Ny,A as My,B as Ry,C as $y,D as Ly,E as jy,F as Dy,G as Fy,H as Uy,I as By,d as kn,J as zy,g as $e,K as Hy,L as ah,M as Vy,N as Gy,O as za,h as Vc,Q as Wy,R as Jy,S as Ky,U as Zy,W as qy,X as Yy,Y as Xy,Z as Qy,a0 as e_,a1 as t_,a2 as n_,a3 as pu,a4 as r_,a5 as s_,a6 as a_,a7 as i_,s as o_,v as ke,P as nn,p as Ha,a as Ts,b as ih,c as oh,i as Gc,j as c_,f as l_,_ as u_,$ as d_,e as h_,k as p_,t as fu,l as ch,V as Wc,m as f_,n as br,o as m_,T as g_,q as Jc,r as y_,a8 as __}from"./chunk-VL2OQCWN-BSY6s1ZW.js";import{o as Fo}from"./__vite-browser-external-DFygW7-s.js";import{j as Va,d as mu,i as w_}from"./path-C9FudP8b.js";var Ji,ia,Ki=0,Zi=0;function v_(e,t,n){var r=0,s=t||new Array(16);e=e||{};var a=e.node,i=e.clockseq;if(e._v6||(a||(a=Ji),i==null&&(i=ia)),a==null||i==null){var o=e.random||(e.rng||Iy)();a==null&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],!Ji&&!e._v6&&(a[0]|=1,Ji=a)),i==null&&(i=(o[6]<<8|o[7])&16383,ia===void 0&&!e._v6&&(ia=i))}var c=e.msecs!==void 0?e.msecs:Date.now(),l=e.nsecs!==void 0?e.nsecs:Zi+1,u=c-Ki+(l-Zi)/1e4;if(u<0&&e.clockseq===void 0&&(i=i+1&16383),(u<0||c>Ki)&&e.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ki=c,Zi=l,ia=i,c+=122192928e5;var d=((c&268435455)*1e4+l)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=d&255;var h=c/4294967296*1e4&268435455;s[r++]=h>>>8&255,s[r++]=h&255,s[r++]=h>>>24&15|16,s[r++]=h>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var p=0;p<6;++p)s[r+p]=a[p];return t||Hc(s)}function b_(e){var t=typeof e=="string"?Py(e):e,n=S_(t);return typeof e=="string"?Hc(n):n}function S_(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function gu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function yu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?gu(Object(n),!0).forEach(function(r){T_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gu(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function T_(e,t,n){return(t=E_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function E_(e){var t=C_(e,"string");return typeof t=="symbol"?t:t+""}function C_(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function A_(e={},t,n=0){var r=v_(yu(yu({},e),{},{_v6:!0}),new Uint8Array(16));return r=b_(r),Hc(r)}const k_=(e,t)=>{Ny.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Ry(e,n)},flatten:{value:n=>My(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},yi=ze("ZodError",k_,{Parent:Error}),O_=$y(yi),x_=jy(yi),I_=Ly(yi),P_=Dy(yi),ut=ze("ZodType",(e,t)=>(By.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>kn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>O_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>I_(e,n,r),e.parseAsync=async(n,r)=>x_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>P_(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(nw(n,r)),e.superRefine=n=>e.check(rw(n)),e.overwrite=n=>e.check(zy(n)),e.optional=()=>_u(e),e.nullable=()=>wu(e),e.nullish=()=>_u(wu(e)),e.nonoptional=n=>K_(e,n),e.array=()=>R_(e),e.or=n=>L_([e,n]),e.and=n=>D_(e,n),e.transform=n=>vu(e,U_(n)),e.default=n=>V_(e,n),e.prefault=n=>W_(e,n),e.catch=n=>q_(e,n),e.pipe=n=>vu(e,n),e.readonly=()=>Q_(e),e.describe=n=>{const r=e.clone();return $e.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return $e.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return $e.get(e);const r=e.clone();return $e.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),N_=ze("ZodAny",(e,t)=>{Uy.init(e,t),ut.init(e,t)});function oa(){return Fy(N_)}const M_=ze("ZodArray",(e,t)=>{n_.init(e,t),ut.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(pu(n,r)),e.nonempty=n=>e.check(pu(1,n)),e.max=(n,r)=>e.check(r_(n,r)),e.length=(n,r)=>e.check(s_(n,r)),e.unwrap=()=>e.element});function R_(e,t){return Vy(M_,e,t)}const $_=ze("ZodUnion",(e,t)=>{Ky.init(e,t),ut.init(e,t),e.options=t.options});function L_(e,t){return new $_({type:"union",options:e,...ah(t)})}const j_=ze("ZodIntersection",(e,t)=>{Zy.init(e,t),ut.init(e,t)});function D_(e,t){return new j_({type:"intersection",left:e,right:t})}const F_=ze("ZodTransform",(e,t)=>{Yy.init(e,t),ut.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(za(a,n.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),n.issues.push(za(i))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function U_(e){return new F_({type:"transform",transform:e})}const B_=ze("ZodOptional",(e,t)=>{Vc.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _u(e){return new B_({type:"optional",innerType:e})}const z_=ze("ZodNullable",(e,t)=>{Wy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function wu(e){return new z_({type:"nullable",innerType:e})}const H_=ze("ZodDefault",(e,t)=>{Xy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function V_(e,t){return new H_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const G_=ze("ZodPrefault",(e,t)=>{Qy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function W_(e,t){return new G_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const J_=ze("ZodNonOptional",(e,t)=>{Jy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function K_(e,t){return new J_({type:"nonoptional",innerType:e,...ah(t)})}const Z_=ze("ZodCatch",(e,t)=>{e_.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function q_(e,t){return new Z_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Y_=ze("ZodPipe",(e,t)=>{qy.init(e,t),ut.init(e,t),e.in=t.in,e.out=t.out});function vu(e,t){return new Y_({type:"pipe",in:e,out:t})}const X_=ze("ZodReadonly",(e,t)=>{t_.init(e,t),ut.init(e,t)});function Q_(e){return new X_({type:"readonly",innerType:e})}const ew=ze("ZodCustom",(e,t)=>{a_.init(e,t),ut.init(e,t)});function tw(e){const t=new Gy({check:"custom"});return t._zod.check=e,t}function nw(e,t={}){return Hy(ew,e,t)}function rw(e){const t=tw(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(za(r,n.value,t._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),n.issues.push(za(s))}},e(n.value,n)));return t}async function*lh(e){for await(const t of e)if(t.event==="on_chat_model_stream"&&t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}G(lh,"streamEventsToAISDK");function uh(e){return new ReadableStream({async start(t){try{for await(const n of e)t.enqueue(n);t.close()}catch(n){t.error(n)}}})}G(uh,"createReadableStreamFromGenerator");async function*dh(e){for await(const t of e)switch(t.event){case"on_chat_model_stream":if(t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-U0zNfugP.js","assets/index-98gc3IlW.js","assets/index-CNwZaJQ9.js","assets/index-Bx3FWJNp.css","assets/chunk-VL2OQCWN-DBinT58-.js","assets/index-DRz5BQNA.js","assets/__vite-browser-external-DFygW7-s.js","assets/path-C9FudP8b.js"])))=>i.map(i=>d[i]);
2
+ var yy=Object.defineProperty;var _y=(e,t,n)=>t in e?yy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var du=(e,t,n)=>_y(e,typeof t!="symbol"?t+"":t,n);import{_ as G,c as Wi,u as gt,a as Tt,d as bs,n as le,s as pe,e as Jt,o as Y,f as wy,Z as M,h as nt,i as hu,l as vr,j as vy,k as Fa,p as sh,m as Ur,r as Ss,q as Ua,t as E,v as by,w as Ba,B as Sy,x as Ty,H as Ey,L as Cy,y as Ay,M as ky,W as Oy,z as xy}from"./index-CNwZaJQ9.js";import{u as Iy,w as Hc,x as Py,y as ze,z as Ny,A as My,B as Ry,C as $y,D as Ly,E as jy,F as Dy,G as Fy,H as Uy,I as By,d as kn,J as zy,g as $e,K as Hy,L as ah,M as Vy,N as Gy,O as za,h as Vc,Q as Wy,R as Jy,S as Ky,U as Zy,W as qy,X as Yy,Y as Xy,Z as Qy,a0 as e_,a1 as t_,a2 as n_,a3 as pu,a4 as r_,a5 as s_,a6 as a_,a7 as i_,s as o_,v as ke,P as nn,p as Ha,a as Ts,b as ih,c as oh,i as Gc,j as c_,f as l_,_ as u_,$ as d_,e as h_,k as p_,t as fu,l as ch,V as Wc,m as f_,n as br,o as m_,T as g_,q as Jc,r as y_,a8 as __}from"./chunk-VL2OQCWN-DBinT58-.js";import{o as Fo}from"./__vite-browser-external-DFygW7-s.js";import{j as Va,d as mu,i as w_}from"./path-C9FudP8b.js";var Ji,ia,Ki=0,Zi=0;function v_(e,t,n){var r=0,s=t||new Array(16);e=e||{};var a=e.node,i=e.clockseq;if(e._v6||(a||(a=Ji),i==null&&(i=ia)),a==null||i==null){var o=e.random||(e.rng||Iy)();a==null&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],!Ji&&!e._v6&&(a[0]|=1,Ji=a)),i==null&&(i=(o[6]<<8|o[7])&16383,ia===void 0&&!e._v6&&(ia=i))}var c=e.msecs!==void 0?e.msecs:Date.now(),l=e.nsecs!==void 0?e.nsecs:Zi+1,u=c-Ki+(l-Zi)/1e4;if(u<0&&e.clockseq===void 0&&(i=i+1&16383),(u<0||c>Ki)&&e.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ki=c,Zi=l,ia=i,c+=122192928e5;var d=((c&268435455)*1e4+l)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=d&255;var h=c/4294967296*1e4&268435455;s[r++]=h>>>8&255,s[r++]=h&255,s[r++]=h>>>24&15|16,s[r++]=h>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var p=0;p<6;++p)s[r+p]=a[p];return t||Hc(s)}function b_(e){var t=typeof e=="string"?Py(e):e,n=S_(t);return typeof e=="string"?Hc(n):n}function S_(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function gu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function yu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?gu(Object(n),!0).forEach(function(r){T_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gu(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function T_(e,t,n){return(t=E_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function E_(e){var t=C_(e,"string");return typeof t=="symbol"?t:t+""}function C_(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function A_(e={},t,n=0){var r=v_(yu(yu({},e),{},{_v6:!0}),new Uint8Array(16));return r=b_(r),Hc(r)}const k_=(e,t)=>{Ny.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Ry(e,n)},flatten:{value:n=>My(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},yi=ze("ZodError",k_,{Parent:Error}),O_=$y(yi),x_=jy(yi),I_=Ly(yi),P_=Dy(yi),ut=ze("ZodType",(e,t)=>(By.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>kn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>O_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>I_(e,n,r),e.parseAsync=async(n,r)=>x_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>P_(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(nw(n,r)),e.superRefine=n=>e.check(rw(n)),e.overwrite=n=>e.check(zy(n)),e.optional=()=>_u(e),e.nullable=()=>wu(e),e.nullish=()=>_u(wu(e)),e.nonoptional=n=>K_(e,n),e.array=()=>R_(e),e.or=n=>L_([e,n]),e.and=n=>D_(e,n),e.transform=n=>vu(e,U_(n)),e.default=n=>V_(e,n),e.prefault=n=>W_(e,n),e.catch=n=>q_(e,n),e.pipe=n=>vu(e,n),e.readonly=()=>Q_(e),e.describe=n=>{const r=e.clone();return $e.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return $e.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return $e.get(e);const r=e.clone();return $e.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),N_=ze("ZodAny",(e,t)=>{Uy.init(e,t),ut.init(e,t)});function oa(){return Fy(N_)}const M_=ze("ZodArray",(e,t)=>{n_.init(e,t),ut.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(pu(n,r)),e.nonempty=n=>e.check(pu(1,n)),e.max=(n,r)=>e.check(r_(n,r)),e.length=(n,r)=>e.check(s_(n,r)),e.unwrap=()=>e.element});function R_(e,t){return Vy(M_,e,t)}const $_=ze("ZodUnion",(e,t)=>{Ky.init(e,t),ut.init(e,t),e.options=t.options});function L_(e,t){return new $_({type:"union",options:e,...ah(t)})}const j_=ze("ZodIntersection",(e,t)=>{Zy.init(e,t),ut.init(e,t)});function D_(e,t){return new j_({type:"intersection",left:e,right:t})}const F_=ze("ZodTransform",(e,t)=>{Yy.init(e,t),ut.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(za(a,n.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),n.issues.push(za(i))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function U_(e){return new F_({type:"transform",transform:e})}const B_=ze("ZodOptional",(e,t)=>{Vc.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _u(e){return new B_({type:"optional",innerType:e})}const z_=ze("ZodNullable",(e,t)=>{Wy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function wu(e){return new z_({type:"nullable",innerType:e})}const H_=ze("ZodDefault",(e,t)=>{Xy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function V_(e,t){return new H_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const G_=ze("ZodPrefault",(e,t)=>{Qy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function W_(e,t){return new G_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const J_=ze("ZodNonOptional",(e,t)=>{Jy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function K_(e,t){return new J_({type:"nonoptional",innerType:e,...ah(t)})}const Z_=ze("ZodCatch",(e,t)=>{e_.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function q_(e,t){return new Z_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Y_=ze("ZodPipe",(e,t)=>{qy.init(e,t),ut.init(e,t),e.in=t.in,e.out=t.out});function vu(e,t){return new Y_({type:"pipe",in:e,out:t})}const X_=ze("ZodReadonly",(e,t)=>{t_.init(e,t),ut.init(e,t)});function Q_(e){return new X_({type:"readonly",innerType:e})}const ew=ze("ZodCustom",(e,t)=>{a_.init(e,t),ut.init(e,t)});function tw(e){const t=new Gy({check:"custom"});return t._zod.check=e,t}function nw(e,t={}){return Hy(ew,e,t)}function rw(e){const t=tw(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(za(r,n.value,t._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),n.issues.push(za(s))}},e(n.value,n)));return t}async function*lh(e){for await(const t of e)if(t.event==="on_chat_model_stream"&&t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}G(lh,"streamEventsToAISDK");function uh(e){return new ReadableStream({async start(t){try{for await(const n of e)t.enqueue(n);t.close()}catch(n){t.error(n)}}})}G(uh,"createReadableStreamFromGenerator");async function*dh(e){for await(const t of e)switch(t.event){case"on_chat_model_stream":if(t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
3
3
  🔧 Using tool: ${t.name}
4
4
  `;break;case"on_tool_end":yield`
5
5
  ✅ Tool completed: ${t.name}
@@ -559,4 +559,4 @@ ${f}`);const b=await s.stream(f);let S=null,w=0;for await(const T of b){if(w++,E
559
559
 
560
560
  Make sure you gather ALL the required information during your task execution.
561
561
  If any required information is missing, continue working to find it.
562
- `}catch(r){return E.warn(`Could not extract schema details: ${r}`),t}}},G(Fr,"MCPAgent"),Fr),Re={},zP=Re.MCP_USE_LANGFUSE?.toLowerCase()==="false",Gs={handler:null,client:null,initPromise:null};async function au(e,t,n,r){try{const s=await Ba(()=>import("./index-v8aqAKR2.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).catch(()=>null);if(!s){E.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:a}=s,u=class u extends a{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(h,p,f,g,b){super(h),this.agentId=p,this.metadata=f,this.metadataProvider=g,this.tagsProvider=b,this.verbose=h?.verbose??!1}async handleChainStart(h,p,f,g,b,S,w,v){E.debug("Langfuse: Chain start intercepted");const T=this.getCustomTags(),k=this.getMetadata(),O=[...b||[],...T],C={...S||{},...k};return this.verbose&&(E.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(O)}`),E.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(C)}`)),super.handleChainStart(h,p,f,g,O,C,w,v)}getCustomTags(){const h=[],p=this.getEnvironmentTag();if(p&&h.push(`env:${p}`),this.agentId&&h.push(`agent_id:${this.agentId}`),this.tagsProvider){const f=this.tagsProvider();f&&f.length>0&&h.push(...f)}return h}getMetadata(){const h={},p=this.getEnvironmentTag();if(p&&(h.env=p),this.agentId&&(h.agent_id=this.agentId),this.metadata&&Object.assign(h,this.metadata),this.metadataProvider){const f=this.metadataProvider();f&&Object.assign(h,f)}return h}getEnvironmentTag(){const h=Re.MCP_USE_AGENT_ENV;if(!h)return"unknown";const p=h.toLowerCase();return p==="local"||p==="development"?"local":p==="production"||p==="prod"?"production":p==="staging"||p==="stage"?"staging":p==="hosted"||p==="cloud"?"hosted":p.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...h){return E.debug("Langfuse: LLM start intercepted"),this.verbose&&E.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return E.debug("Langfuse: Tool start intercepted"),this.verbose&&E.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return E.debug("Langfuse: Retriever start intercepted"),this.verbose&&E.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return E.debug("Langfuse: Agent action intercepted"),this.verbose&&E.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return E.debug("Langfuse: Agent end intercepted"),this.verbose&&E.debug(`Langfuse: Agent end args: ${JSON.stringify(h)}`),super.handleAgentEnd(...h)}};G(u,"LoggingCallbackHandler");let i=u;const o=t||(n?n():{}),c=r?r():[],l={publicKey:Re.LANGFUSE_PUBLIC_KEY,secretKey:Re.LANGFUSE_SECRET_KEY,baseUrl:Re.LANGFUSE_HOST||Re.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Re.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Re.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Re.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Re.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Re.LANGFUSE_ENABLED!=="false",traceName:o.trace_name||Re.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:o.session_id||void 0,userId:o.user_id||void 0,tags:c.length>0?c:void 0,metadata:o||void 0};E.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Gs.handler=new i(l,e,t,n,r),E.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await Ba(()=>import("./index-baibQX1A.js"),__vite__mapDeps([1,2,3,4,5,6,7])).catch(()=>null);if(d){const{Langfuse:h}=d;Gs.client=new h({publicKey:Re.LANGFUSE_PUBLIC_KEY,secretKey:Re.LANGFUSE_SECRET_KEY,baseUrl:Re.LANGFUSE_HOST||"https://cloud.langfuse.com"}),E.debug("Langfuse client initialized")}}catch(d){E.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){E.debug(`Langfuse initialization error: ${s}`)}}G(au,"initializeLangfuse");zP?E.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Re.LANGFUSE_PUBLIC_KEY||!Re.LANGFUSE_SECRET_KEY?E.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Gs.initPromise=au();var HP=G(()=>Gs.handler,"langfuseHandler"),VP=G(()=>Gs.initPromise,"langfuseInitPromise");const nN=Object.freeze(Object.defineProperty({__proto__:null,BaseAdapter:iy,BaseConnector:Sy,BrowserOAuthClientProvider:Ty,HttpConnector:Ey,LangChainAdapter:Dn,Logger:Cy,MCPAgent:BP,MCPClient:Ay,MCPSession:ky,ObservabilityManager:Uc,RemoteAgent:dy,WebSocketConnector:Oy,createReadableStreamFromGenerator:uh,logger:E,onMcpAuthorization:xy,streamEventsToAISDK:lh,streamEventsToAISDKWithTools:dh},Symbol.toStringTag,{value:"Module"})),rh=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:au,langfuseHandler:HP,langfuseInitPromise:VP},Symbol.toStringTag,{value:"Module"}));export{D as A,es as B,Xn as C,vi as F,he as H,Se as S,X as T,rt as a,yt as b,nN as c,lt as m};
562
+ `}catch(r){return E.warn(`Could not extract schema details: ${r}`),t}}},G(Fr,"MCPAgent"),Fr),Re={},zP=Re.MCP_USE_LANGFUSE?.toLowerCase()==="false",Gs={handler:null,client:null,initPromise:null};async function au(e,t,n,r){try{const s=await Ba(()=>import("./index-U0zNfugP.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).catch(()=>null);if(!s){E.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:a}=s,u=class u extends a{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(h,p,f,g,b){super(h),this.agentId=p,this.metadata=f,this.metadataProvider=g,this.tagsProvider=b,this.verbose=h?.verbose??!1}async handleChainStart(h,p,f,g,b,S,w,v){E.debug("Langfuse: Chain start intercepted");const T=this.getCustomTags(),k=this.getMetadata(),O=[...b||[],...T],C={...S||{},...k};return this.verbose&&(E.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(O)}`),E.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(C)}`)),super.handleChainStart(h,p,f,g,O,C,w,v)}getCustomTags(){const h=[],p=this.getEnvironmentTag();if(p&&h.push(`env:${p}`),this.agentId&&h.push(`agent_id:${this.agentId}`),this.tagsProvider){const f=this.tagsProvider();f&&f.length>0&&h.push(...f)}return h}getMetadata(){const h={},p=this.getEnvironmentTag();if(p&&(h.env=p),this.agentId&&(h.agent_id=this.agentId),this.metadata&&Object.assign(h,this.metadata),this.metadataProvider){const f=this.metadataProvider();f&&Object.assign(h,f)}return h}getEnvironmentTag(){const h=Re.MCP_USE_AGENT_ENV;if(!h)return"unknown";const p=h.toLowerCase();return p==="local"||p==="development"?"local":p==="production"||p==="prod"?"production":p==="staging"||p==="stage"?"staging":p==="hosted"||p==="cloud"?"hosted":p.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...h){return E.debug("Langfuse: LLM start intercepted"),this.verbose&&E.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return E.debug("Langfuse: Tool start intercepted"),this.verbose&&E.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return E.debug("Langfuse: Retriever start intercepted"),this.verbose&&E.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return E.debug("Langfuse: Agent action intercepted"),this.verbose&&E.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return E.debug("Langfuse: Agent end intercepted"),this.verbose&&E.debug(`Langfuse: Agent end args: ${JSON.stringify(h)}`),super.handleAgentEnd(...h)}};G(u,"LoggingCallbackHandler");let i=u;const o=t||(n?n():{}),c=r?r():[],l={publicKey:Re.LANGFUSE_PUBLIC_KEY,secretKey:Re.LANGFUSE_SECRET_KEY,baseUrl:Re.LANGFUSE_HOST||Re.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Re.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Re.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Re.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Re.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Re.LANGFUSE_ENABLED!=="false",traceName:o.trace_name||Re.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:o.session_id||void 0,userId:o.user_id||void 0,tags:c.length>0?c:void 0,metadata:o||void 0};E.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Gs.handler=new i(l,e,t,n,r),E.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await Ba(()=>import("./index-98gc3IlW.js"),__vite__mapDeps([1,2,3,4,5,6,7])).catch(()=>null);if(d){const{Langfuse:h}=d;Gs.client=new h({publicKey:Re.LANGFUSE_PUBLIC_KEY,secretKey:Re.LANGFUSE_SECRET_KEY,baseUrl:Re.LANGFUSE_HOST||"https://cloud.langfuse.com"}),E.debug("Langfuse client initialized")}}catch(d){E.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){E.debug(`Langfuse initialization error: ${s}`)}}G(au,"initializeLangfuse");zP?E.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Re.LANGFUSE_PUBLIC_KEY||!Re.LANGFUSE_SECRET_KEY?E.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Gs.initPromise=au();var HP=G(()=>Gs.handler,"langfuseHandler"),VP=G(()=>Gs.initPromise,"langfuseInitPromise");const nN=Object.freeze(Object.defineProperty({__proto__:null,BaseAdapter:iy,BaseConnector:Sy,BrowserOAuthClientProvider:Ty,HttpConnector:Ey,LangChainAdapter:Dn,Logger:Cy,MCPAgent:BP,MCPClient:Ay,MCPSession:ky,ObservabilityManager:Uc,RemoteAgent:dy,WebSocketConnector:Oy,createReadableStreamFromGenerator:uh,logger:E,onMcpAuthorization:xy,streamEventsToAISDK:lh,streamEventsToAISDKWithTools:dh},Symbol.toStringTag,{value:"Module"})),rh=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:au,langfuseHandler:HP,langfuseInitPromise:VP},Symbol.toStringTag,{value:"Module"}));export{D as A,es as B,Xn as C,vi as F,he as H,Se as S,X as T,rt as a,yt as b,nN as c,lt as m};
@@ -1,4 +1,4 @@
1
- import{b as St,g as Vo}from"./index-C8x1o6em.js";import{o as Ko}from"./__vite-browser-external-DFygW7-s.js";import{r as Jo}from"./index-DRz5BQNA.js";import{p as Zo}from"./path-C9FudP8b.js";function Qo(r,i){for(var v=0;v<i.length;v++){const E=i[v];if(typeof E!="string"&&!Array.isArray(E)){for(const d in E)if(d!=="default"&&!(d in r)){const l=Object.getOwnPropertyDescriptor(E,d);l&&Object.defineProperty(r,d,l.get?l:{enumerable:!0,get:()=>E[d]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}var Pt={},ze={},Tt,rn;function ye(){if(rn)return Tt;rn=1;function r(m){"@babel/helpers - typeof";return r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},r(m)}function i(m,s,c){return Object.defineProperty(m,"prototype",{writable:!1}),m}function v(m,s){if(!(m instanceof s))throw new TypeError("Cannot call a class as a function")}function E(m,s,c){return s=p(s),d(m,_()?Reflect.construct(s,c||[],p(m).constructor):s.apply(m,c))}function d(m,s){if(s&&(r(s)=="object"||typeof s=="function"))return s;if(s!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return l(m)}function l(m){if(m===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return m}function h(m,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");m.prototype=Object.create(s&&s.prototype,{constructor:{value:m,writable:!0,configurable:!0}}),Object.defineProperty(m,"prototype",{writable:!1}),s&&x(m,s)}function t(m){var s=typeof Map=="function"?new Map:void 0;return t=function(a){if(a===null||!y(a))return a;if(typeof a!="function")throw new TypeError("Super expression must either be null or a function");if(s!==void 0){if(s.has(a))return s.get(a);s.set(a,o)}function o(){return u(a,arguments,p(this).constructor)}return o.prototype=Object.create(a.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),x(o,a)},t(m)}function u(m,s,c){if(_())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,s);var o=new(m.bind.apply(m,a));return c&&x(o,c.prototype),o}function _(){try{var m=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_=function(){return!!m})()}function y(m){try{return Function.toString.call(m).indexOf("[native code]")!==-1}catch{return typeof m=="function"}}function x(m,s){return x=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(c,a){return c.__proto__=a,c},x(m,s)}function p(m){return p=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(s){return s.__proto__||Object.getPrototypeOf(s)},p(m)}var w=(function(m){function s(c){var a;return v(this,s),a=E(this,s,[`Format functions must be synchronous taking a two arguments: (info, opts)
1
+ import{b as St,g as Vo}from"./index-CNwZaJQ9.js";import{o as Ko}from"./__vite-browser-external-DFygW7-s.js";import{r as Jo}from"./index-DRz5BQNA.js";import{p as Zo}from"./path-C9FudP8b.js";function Qo(r,i){for(var v=0;v<i.length;v++){const E=i[v];if(typeof E!="string"&&!Array.isArray(E)){for(const d in E)if(d!=="default"&&!(d in r)){const l=Object.getOwnPropertyDescriptor(E,d);l&&Object.defineProperty(r,d,l.get?l:{enumerable:!0,get:()=>E[d]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}var Pt={},ze={},Tt,rn;function ye(){if(rn)return Tt;rn=1;function r(m){"@babel/helpers - typeof";return r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},r(m)}function i(m,s,c){return Object.defineProperty(m,"prototype",{writable:!1}),m}function v(m,s){if(!(m instanceof s))throw new TypeError("Cannot call a class as a function")}function E(m,s,c){return s=p(s),d(m,_()?Reflect.construct(s,c||[],p(m).constructor):s.apply(m,c))}function d(m,s){if(s&&(r(s)=="object"||typeof s=="function"))return s;if(s!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return l(m)}function l(m){if(m===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return m}function h(m,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");m.prototype=Object.create(s&&s.prototype,{constructor:{value:m,writable:!0,configurable:!0}}),Object.defineProperty(m,"prototype",{writable:!1}),s&&x(m,s)}function t(m){var s=typeof Map=="function"?new Map:void 0;return t=function(a){if(a===null||!y(a))return a;if(typeof a!="function")throw new TypeError("Super expression must either be null or a function");if(s!==void 0){if(s.has(a))return s.get(a);s.set(a,o)}function o(){return u(a,arguments,p(this).constructor)}return o.prototype=Object.create(a.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),x(o,a)},t(m)}function u(m,s,c){if(_())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,s);var o=new(m.bind.apply(m,a));return c&&x(o,c.prototype),o}function _(){try{var m=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_=function(){return!!m})()}function y(m){try{return Function.toString.call(m).indexOf("[native code]")!==-1}catch{return typeof m=="function"}}function x(m,s){return x=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(c,a){return c.__proto__=a,c},x(m,s)}function p(m){return p=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(s){return s.__proto__||Object.getPrototypeOf(s)},p(m)}var w=(function(m){function s(c){var a;return v(this,s),a=E(this,s,[`Format functions must be synchronous taking a two arguments: (info, opts)
2
2
  Found: `.concat(c.toString().split(`
3
3
  `)[0],`
4
4
  `)]),Error.captureStackTrace(a,s),a}return h(s,m),i(s)})(t(Error));return Tt=function(m){if(m.length>2)throw new w(m);function s(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.options=a}s.prototype.transform=m;function c(a){return new s(a)}return c.Format=s,c},Tt}var Be={exports:{}},jt={exports:{}},Lt={exports:{}};function po(){return()=>{}}function yo(r){return JSON.stringify(r)}function mo(){}function go(){}const Xo={debuglog:po,inspect:yo,inherits:mo,format:go},ea=Object.freeze(Object.defineProperty({__proto__:null,debuglog:po,default:Xo,format:go,inherits:mo,inspect:yo},Symbol.toStringTag,{value:"Module"})),_e=St(ea);var Mt={exports:{}},nn;function ta(){return nn||(nn=1,(function(r){var i={};r.exports=i;var v={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],brightRed:[91,39],brightGreen:[92,39],brightYellow:[93,39],brightBlue:[94,39],brightMagenta:[95,39],brightCyan:[96,39],brightWhite:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgGray:[100,49],bgGrey:[100,49],bgBrightRed:[101,49],bgBrightGreen:[102,49],bgBrightYellow:[103,49],bgBrightBlue:[104,49],bgBrightMagenta:[105,49],bgBrightCyan:[106,49],bgBrightWhite:[107,49],blackBG:[40,49],redBG:[41,49],greenBG:[42,49],yellowBG:[43,49],blueBG:[44,49],magentaBG:[45,49],cyanBG:[46,49],whiteBG:[47,49]};Object.keys(v).forEach(function(E){var d=v[E],l=i[E]=[];l.open="\x1B["+d[0]+"m",l.close="\x1B["+d[1]+"m"})})(Mt)),Mt.exports}const be=St(Ko);var At,on;function ra(){return on||(on=1,At=function(r,i){i=i||process.argv||[];var v=i.indexOf("--"),E=/^-{1,2}/.test(r)?"":"--",d=i.indexOf(E+r);return d!==-1&&(v===-1?!0:d<v)}),At}var Ct,an;function na(){if(an)return Ct;an=1;var r={},i=ra(),v=r,E=void 0;i("no-color")||i("no-colors")||i("color=false")?E=!1:(i("color")||i("colors")||i("color=true")||i("color=always"))&&(E=!0),"FORCE_COLOR"in v&&(E=v.FORCE_COLOR.length===0||parseInt(v.FORCE_COLOR,10)!==0);function d(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function l(t){if(E===!1)return 0;if(i("color=16m")||i("color=full")||i("color=truecolor"))return 3;if(i("color=256"))return 2;if(t&&!t.isTTY&&E!==!0)return 0;var u=E?1:0;if("CI"in v)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(function(y){return y in v})||v.CI_NAME==="codeship"?1:u;if("TEAMCITY_VERSION"in v)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(v.TEAMCITY_VERSION)?1:0;if("TERM_PROGRAM"in v){var _=parseInt((v.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(v.TERM_PROGRAM){case"iTerm.app":return _>=3?3:2;case"Hyper":return 3;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(v.TERM)?2:/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(v.TERM)||"COLORTERM"in v?1:(v.TERM==="dumb",u)}function h(t){var u=l(t);return d(u)}return Ct={supportsColor:h,stdout:h(process.stdout),stderr:h(process.stderr)},Ct}var It={exports:{}},un;function ia(){return un||(un=1,(function(r){r.exports=function(v,E){var d="";v=v||"Run the trap, drop the bass",v=v.split("");var l={a:["@","Ą","Ⱥ","Ʌ","Δ","Λ","Д"],b:["ß","Ɓ","Ƀ","ɮ","β","฿"],c:["©","Ȼ","Ͼ"],d:["Ð","Ɗ","Ԁ","ԁ","Ԃ","ԃ"],e:["Ë","ĕ","Ǝ","ɘ","Σ","ξ","Ҽ","੬"],f:["Ӻ"],g:["ɢ"],h:["Ħ","ƕ","Ң","Һ","Ӈ","Ԋ"],i:["༏"],j:["Ĵ"],k:["ĸ","Ҡ","Ӄ","Ԟ"],l:["Ĺ"],m:["ʍ","Ӎ","ӎ","Ԡ","ԡ","൩"],n:["Ñ","ŋ","Ɲ","Ͷ","Π","Ҋ"],o:["Ø","õ","ø","Ǿ","ʘ","Ѻ","ם","۝","๏"],p:["Ƿ","Ҏ"],q:["্"],r:["®","Ʀ","Ȑ","Ɍ","ʀ","Я"],s:["§","Ϟ","ϟ","Ϩ"],t:["Ł","Ŧ","ͳ"],u:["Ʊ","Ս"],v:["ט"],w:["Ш","Ѡ","Ѽ","൰"],x:["Ҳ","Ӿ","Ӽ","ӽ"],y:["¥","Ұ","Ӌ"],z:["Ƶ","ɀ"]};return v.forEach(function(h){h=h.toLowerCase();var t=l[h]||[" "],u=Math.floor(Math.random()*t.length);typeof l[h]<"u"?d+=l[h][u]:d+=h}),d}})(It)),It.exports}var qt={exports:{}},sn;function oa(){return sn||(sn=1,(function(r){r.exports=function(v,E){v=v||" he is here ";var d={up:["̍","̎","̄","̅","̿","̑","̆","̐","͒","͗","͑","̇","̈","̊","͂","̓","̈","͊","͋","͌","̃","̂","̌","͐","̀","́","̋","̏","̒","̓","̔","̽","̉","ͣ","ͤ","ͥ","ͦ","ͧ","ͨ","ͩ","ͪ","ͫ","ͬ","ͭ","ͮ","ͯ","̾","͛","͆","̚"],down:["̖","̗","̘","̙","̜","̝","̞","̟","̠","̤","̥","̦","̩","̪","̫","̬","̭","̮","̯","̰","̱","̲","̳","̹","̺","̻","̼","ͅ","͇","͈","͉","͍","͎","͓","͔","͕","͖","͙","͚","̣"],mid:["̕","̛","̀","́","͘","̡","̢","̧","̨","̴","̵","̶","͜","͝","͞","͟","͠","͢","̸","̷","͡"," ҉"]},l=[].concat(d.up,d.down,d.mid);function h(_){var y=Math.floor(Math.random()*_);return y}function t(_){var y=!1;return l.filter(function(x){y=x===_}),y}function u(_,y){var x="",p,w;y=y||{},y.up=typeof y.up<"u"?y.up:!0,y.mid=typeof y.mid<"u"?y.mid:!0,y.down=typeof y.down<"u"?y.down:!0,y.size=typeof y.size<"u"?y.size:"maxi",_=_.split("");for(w in _)if(!t(w)){switch(x=x+_[w],p={up:0,down:0,mid:0},y.size){case"mini":p.up=h(8),p.mid=h(2),p.down=h(8);break;case"maxi":p.up=h(16)+3,p.mid=h(4)+1,p.down=h(64)+3;break;default:p.up=h(8)+1,p.mid=h(6)/2,p.down=h(8)+1;break}var m=["up","mid","down"];for(var s in m)for(var c=m[s],a=0;a<=p[c];a++)y[c]&&(x=x+d[c][h(d[c].length)])}return x}return u(v,E)}})(qt)),qt.exports}var Bt={exports:{}},fn;function aa(){return fn||(fn=1,(function(r){r.exports=function(i){return function(v,E,d){if(v===" ")return v;switch(E%3){case 0:return i.red(v);case 1:return i.white(v);case 2:return i.blue(v)}}}})(Bt)),Bt.exports}var Nt={exports:{}},ln;function ua(){return ln||(ln=1,(function(r){r.exports=function(i){return function(v,E,d){return E%2===0?v:i.inverse(v)}}})(Nt)),Nt.exports}var Ft={exports:{}},cn;function sa(){return cn||(cn=1,(function(r){r.exports=function(i){var v=["red","yellow","green","blue","magenta"];return function(E,d,l){return E===" "?E:i[v[d++%v.length]](E)}}})(Ft)),Ft.exports}var Dt={exports:{}},hn;function fa(){return hn||(hn=1,(function(r){r.exports=function(i){var v=["underline","inverse","grey","yellow","red","green","blue","white","cyan","magenta","brightYellow","brightRed","brightGreen","brightBlue","brightWhite","brightCyan","brightMagenta"];return function(E,d,l){return E===" "?E:i[v[Math.round(Math.random()*(v.length-2))]](E)}}})(Dt)),Dt.exports}var pn;function la(){return pn||(pn=1,(function(r){var i={};r.exports=i,i.themes={};var v=_e,E=i.styles=ta(),d=Object.defineProperties,l=new RegExp(/[\r\n]+/g);i.supportsColor=na().supportsColor,typeof i.enabled>"u"&&(i.enabled=i.supportsColor()!==!1),i.enable=function(){i.enabled=!0},i.disable=function(){i.enabled=!1},i.stripColors=i.strip=function(s){return(""+s).replace(/\x1B\[\d+m/g,"")},i.stylize=function(c,a){if(!i.enabled)return c+"";var o=E[a];return!o&&a in i?i[a](c):o.open+c+o.close};var h=/[|\\{}()[\]^$+*?.]/g,t=function(s){if(typeof s!="string")throw new TypeError("Expected a string");return s.replace(h,"\\$&")};function u(s){var c=function a(){return x.apply(a,arguments)};return c._styles=s,c.__proto__=y,c}var _=(function(){var s={};return E.grey=E.gray,Object.keys(E).forEach(function(c){E[c].closeRe=new RegExp(t(E[c].close),"g"),s[c]={get:function(){return u(this._styles.concat(c))}}}),s})(),y=d(function(){},_);function x(){var s=Array.prototype.slice.call(arguments),c=s.map(function(S){return S!=null&&S.constructor===String?S:v.inspect(S)}).join(" ");if(!i.enabled||!c)return c;for(var a=c.indexOf(`
@@ -27,9 +27,9 @@
27
27
  rel="stylesheet"
28
28
  />
29
29
  <title>Inspector | mcp-use</title>
30
- <script type="module" crossorigin src="/inspector/assets/index-C8x1o6em.js"></script>
30
+ <script type="module" crossorigin src="/inspector/assets/index-CNwZaJQ9.js"></script>
31
31
  <link rel="stylesheet" crossorigin href="/inspector/assets/index-Bx3FWJNp.css">
32
- <script>window.__INSPECTOR_VERSION__ = "0.5.0";</script>
32
+ <script>window.__INSPECTOR_VERSION__ = "0.5.1";</script>
33
33
  </head>
34
34
  <body>
35
35
  <script>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mcp-use/inspector",
3
3
  "type": "module",
4
- "version": "0.5.0",
4
+ "version": "0.5.1",
5
5
  "description": "MCP Inspector - A tool for inspecting and debugging MCP servers",
6
6
  "author": "",
7
7
  "license": "MIT",
@@ -73,7 +73,7 @@
73
73
  "sonner": "^2.0.7",
74
74
  "tailwind-merge": "^3.3.1",
75
75
  "vite-express": "^0.21.1",
76
- "mcp-use": "1.3.0"
76
+ "mcp-use": "1.3.1"
77
77
  },
78
78
  "publishConfig": {
79
79
  "access": "public"