@mcp-use/inspector 0.4.11-canary.0 → 0.4.11

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.
Files changed (43) hide show
  1. package/dist/cli.js +87 -40
  2. package/dist/client/assets/{chunk-VL2OQCWN-BE4txAap.js → chunk-VL2OQCWN-Ce71Oujn.js} +1 -1
  3. package/dist/client/assets/{embeddings-D0mnwVrX.js → embeddings-x1-vu32M.js} +1 -1
  4. package/dist/client/assets/{index-Ba21hizt.css → index-BrUPorMz.css} +1 -1
  5. package/dist/client/assets/{index-B0MYHYe6.js → index-ByN-8efJ.js} +1 -1
  6. package/dist/client/assets/{index-mBO7pd_t.js → index-C1F6bSOH.js} +1 -1
  7. package/dist/client/assets/{index-BEMSyME5.js → index-CLrmeqJ5.js} +1 -1
  8. package/dist/client/assets/{index-CQ9XIRcv.js → index-CynUsoYY.js} +1 -1
  9. package/dist/client/assets/{index-BgupETL3.js → index-D56cgcLQ.js} +1 -1
  10. package/dist/client/assets/{index-DrYUC3_O.js → index-SVv-Z-Et.js} +4 -4
  11. package/dist/client/assets/{index-wkxN17B9.js → index-Z5HYU3am.js} +1 -1
  12. package/dist/client/assets/{langfuse-MO3AMDBE-DYoZ4Kwk.js → langfuse-LCJ6VJEP-B8zS6koH.js} +3 -3
  13. package/dist/client/index.html +33 -13
  14. package/dist/server/{chunk-AFTM3F6I.js → chunk-222XA5JA.js} +7 -3
  15. package/dist/server/{chunk-RK4WSNY7.js → chunk-76XNP4ZB.js} +41 -17
  16. package/dist/server/{chunk-XJDEAO7Y.js → chunk-JCLAFMDT.js} +3 -1
  17. package/dist/server/{chunk-VMVT3HVZ.js → chunk-TIYOH5C4.js} +53 -21
  18. package/dist/server/{chunk-5JZ2RXUR.js → chunk-YGCKPAWJ.js} +9 -5
  19. package/dist/server/{chunk-JTBAUVJ3.js → chunk-ZFMPIRVB.js} +36 -21
  20. package/dist/server/cli.js +11 -7
  21. package/dist/server/index.d.ts +2 -2
  22. package/dist/server/index.d.ts.map +1 -1
  23. package/dist/server/index.js +6 -6
  24. package/dist/server/middleware.d.ts +2 -2
  25. package/dist/server/middleware.d.ts.map +1 -1
  26. package/dist/server/middleware.js +6 -6
  27. package/dist/server/server.d.ts.map +1 -1
  28. package/dist/server/server.js +20 -10
  29. package/dist/server/shared-routes.d.ts +1 -1
  30. package/dist/server/shared-routes.d.ts.map +1 -1
  31. package/dist/server/shared-routes.js +3 -3
  32. package/dist/server/shared-static.d.ts +1 -1
  33. package/dist/server/shared-static.d.ts.map +1 -1
  34. package/dist/server/shared-static.js +2 -2
  35. package/dist/server/shared-utils-browser.d.ts +3 -3
  36. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  37. package/dist/server/shared-utils-browser.js +1 -1
  38. package/dist/server/shared-utils.d.ts +3 -3
  39. package/dist/server/shared-utils.d.ts.map +1 -1
  40. package/dist/server/shared-utils.js +1 -1
  41. package/dist/server/utils.d.ts.map +1 -1
  42. package/dist/server/utils.js +1 -1
  43. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- import{Langfuse as T}from"./index-mBO7pd_t.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-MO3AMDBE-DYoZ4Kwk.js";import"./index-DrYUC3_O.js";import"./chunk-VL2OQCWN-BE4txAap.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-C1F6bSOH.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-LCJ6VJEP-B8zS6koH.js";import"./index-SVv-Z-Et.js";import"./chunk-VL2OQCWN-Ce71Oujn.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 A=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,A as createDatasetItemHandler,k as default};
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-wkxN17B9.js","assets/index-mBO7pd_t.js","assets/index-DrYUC3_O.js","assets/index-Ba21hizt.css","assets/chunk-VL2OQCWN-BE4txAap.js"])))=>i.map(i=>d[i]);
2
- var hy=Object.defineProperty;var py=(e,t,n)=>t in e?hy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var su=(e,t,n)=>py(e,typeof t!="symbol"?t+"":t,n);import{b as ji,u as en,a as ht,c as Rc,n as St,s as Oe,d as Pn,o as te,e as fy,Z as R,f as Ht,h as au,l as Io,i as my,j as Yd,p as Xd,k as Fr,m as $c,q as Qd,_ as G,t as T,w as $a,x as iu,v as gy,y as La,z as yy,A as Po,B as _y,C as wy,H as vy,L as by,D as Sy,M as Ty,W as Ey,E as Cy}from"./index-DrYUC3_O.js";import{u as Ay,w as Lc,x as ky,y as Be,z as Oy,A as xy,B as Iy,C as Py,D as Ny,E as My,F as Ry,G as $y,H as Ly,I as jy,d as An,J as Dy,g as Re,K as Uy,L as eh,M as Fy,N as By,O as ja,h as jc,Q as zy,R as Hy,S as Vy,U as Gy,W as Wy,X as Jy,Y as Ky,Z as Zy,a0 as qy,a1 as Yy,a2 as Xy,a3 as ou,a4 as Qy,a5 as e_,a6 as t_,a7 as n_,s as r_,v as Ce,P as tn,p as Da,a as ws,b as th,c as nh,i as Dc,j as s_,f as a_,_ as i_,$ as o_,e as c_,k as l_,t as cu,l as rh,V as Uc,m as u_,n as br,o as d_,T as h_,q as p_,r as f_,a8 as m_}from"./chunk-VL2OQCWN-BE4txAap.js";var Di,ra,Ui=0,Fi=0;function g_(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=Di),i==null&&(i=ra)),a==null||i==null){var o=e.random||(e.rng||Ay)();a==null&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],!Di&&!e._v6&&(a[0]|=1,Di=a)),i==null&&(i=(o[6]<<8|o[7])&16383,ra===void 0&&!e._v6&&(ra=i))}var c=e.msecs!==void 0?e.msecs:Date.now(),l=e.nsecs!==void 0?e.nsecs:Fi+1,u=c-Ui+(l-Fi)/1e4;if(u<0&&e.clockseq===void 0&&(i=i+1&16383),(u<0||c>Ui)&&e.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ui=c,Fi=l,ra=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||Lc(s)}function y_(e){var t=typeof e=="string"?ky(e):e,n=__(t);return typeof e=="string"?Lc(n):n}function __(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 lu(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 uu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?lu(Object(n),!0).forEach(function(r){w_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lu(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function w_(e,t,n){return(t=v_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function v_(e){var t=b_(e,"string");return typeof t=="symbol"?t:t+""}function b_(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 S_(e={},t,n=0){var r=g_(uu(uu({},e),{},{_v6:!0}),new Uint8Array(16));return r=y_(r),Lc(r)}const T_=(e,t)=>{Oy.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Iy(e,n)},flatten:{value:n=>xy(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},li=Be("ZodError",T_,{Parent:Error}),E_=Py(li),C_=My(li),A_=Ny(li),k_=Ry(li),ct=Be("ZodType",(e,t)=>(jy.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)=>An(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>E_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>A_(e,n,r),e.parseAsync=async(n,r)=>C_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>k_(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(X_(n,r)),e.superRefine=n=>e.check(Q_(n)),e.overwrite=n=>e.check(Dy(n)),e.optional=()=>du(e),e.nullable=()=>hu(e),e.nullish=()=>du(hu(e)),e.nonoptional=n=>V_(e,n),e.array=()=>I_(e),e.or=n=>N_([e,n]),e.and=n=>R_(e,n),e.transform=n=>pu(e,L_(n)),e.default=n=>F_(e,n),e.prefault=n=>z_(e,n),e.catch=n=>W_(e,n),e.pipe=n=>pu(e,n),e.readonly=()=>Z_(e),e.describe=n=>{const r=e.clone();return Re.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return Re.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Re.get(e);const r=e.clone();return Re.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),O_=Be("ZodAny",(e,t)=>{Ly.init(e,t),ct.init(e,t)});function sa(){return $y(O_)}const x_=Be("ZodArray",(e,t)=>{Xy.init(e,t),ct.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(ou(n,r)),e.nonempty=n=>e.check(ou(1,n)),e.max=(n,r)=>e.check(Qy(n,r)),e.length=(n,r)=>e.check(e_(n,r)),e.unwrap=()=>e.element});function I_(e,t){return Fy(x_,e,t)}const P_=Be("ZodUnion",(e,t)=>{Vy.init(e,t),ct.init(e,t),e.options=t.options});function N_(e,t){return new P_({type:"union",options:e,...eh(t)})}const M_=Be("ZodIntersection",(e,t)=>{Gy.init(e,t),ct.init(e,t)});function R_(e,t){return new M_({type:"intersection",left:e,right:t})}const $_=Be("ZodTransform",(e,t)=>{Jy.init(e,t),ct.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(ja(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(ja(i))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function L_(e){return new $_({type:"transform",transform:e})}const j_=Be("ZodOptional",(e,t)=>{jc.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function du(e){return new j_({type:"optional",innerType:e})}const D_=Be("ZodNullable",(e,t)=>{zy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function hu(e){return new D_({type:"nullable",innerType:e})}const U_=Be("ZodDefault",(e,t)=>{Ky.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F_(e,t){return new U_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const B_=Be("ZodPrefault",(e,t)=>{Zy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function z_(e,t){return new B_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const H_=Be("ZodNonOptional",(e,t)=>{Hy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function V_(e,t){return new H_({type:"nonoptional",innerType:e,...eh(t)})}const G_=Be("ZodCatch",(e,t)=>{qy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function W_(e,t){return new G_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const J_=Be("ZodPipe",(e,t)=>{Wy.init(e,t),ct.init(e,t),e.in=t.in,e.out=t.out});function pu(e,t){return new J_({type:"pipe",in:e,out:t})}const K_=Be("ZodReadonly",(e,t)=>{Yy.init(e,t),ct.init(e,t)});function Z_(e){return new K_({type:"readonly",innerType:e})}const q_=Be("ZodCustom",(e,t)=>{t_.init(e,t),ct.init(e,t)});function Y_(e){const t=new By({check:"custom"});return t._zod.check=e,t}function X_(e,t={}){return Uy(q_,e,t)}function Q_(e){const t=Y_(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ja(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(ja(s))}},e(n.value,n)));return t}class ew{static convert(t){return this.parseSchema(t)}static matchesCondition(t,n){if(!n.properties)return!0;if(typeof t!="object"||t===null||Array.isArray(t))return!1;const r=t;for(const[s,a]of Object.entries(n.properties)){if(!(s in r)){if("const"in a)return!1;continue}const i=r[s];if("const"in a&&i!==a.const||"minimum"in a&&typeof i=="number"&&i<a.minimum||"maximum"in a&&typeof i=="number"&&i>a.maximum)return!1}return!0}static validateConditionalSchema(t,n,r){this.validateRequiredProperties(t,n,r),this.validatePropertyPatterns(t,n,r),this.validateNestedConditions(t,n,r)}static validateRequiredProperties(t,n,r){if(n.required){if(typeof t!="object"||t===null){for(const s of n.required)r.addIssue({code:ji.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in t||r.addIssue({code:ji.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(t,n,r){if(!n.properties||typeof t!="object"||t===null||Array.isArray(t))return;const s=t;for(const[a,i]of Object.entries(n.properties)){if(!(a in s))continue;const o=s[a];i.pattern&&typeof o=="string"&&(new RegExp(i.pattern).test(o)||r.addIssue({code:ji.custom,message:`String '${o}' does not match pattern '${i.pattern}'`,path:[a]}))}}static validateNestedConditions(t,n,r){if(!n.if||!n.then)return;this.matchesCondition(t,n.if)?this.validateConditionalSchema(t,n.then,r):n.else&&this.validateConditionalSchema(t,n.else,r)}static parseSchema(t){return Array.isArray(t.type)?this.handleTypeArray(t):t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.if&&t.then?this.parseObject(t):t.properties&&(!t.type||t.type==="object")?this.parseObject(t):this.handleSingleType(t)}static handleTypeArray(t){if(!Array.isArray(t.type))throw new Error("Expected schema.type to be an array");return t.type.includes("null")?this.handleNullableType(t):this.createUnionFromTypes(t.type,t)}static handleNullableType(t){if(!Array.isArray(t.type))throw new Error("Expected schema.type to be an array");const n={...t};return n.type=t.type.filter(s=>s!=="null"),n.type.length===1?this.handleSingleType({...t,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(t,n){const r=t.map(s=>{const a={...n,type:s};return this.parseSchema(a)});return en(r)}static handleSingleType(t){if(t.type===void 0)return t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.properties?this.parseObject(t):ht();switch(t.type){case"string":return this.parseString(t);case"number":case"integer":return this.parseNumberSchema(t);case"boolean":return Rc();case"array":return this.parseArray(t);case"object":return this.parseObject(t);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(t){let n=St(),r=n;return r=this.applyNumberBounds(n,t),r=this.applyNumberMultipleOf(n,t),r=this.applyNumberEnum(n,t),r=this.applyIntegerConstraint(n,t),r}static applyNumberBounds(t,n){let r=t;return n.minimum!==void 0&&(r=n.exclusiveMinimum?r.gt(n.minimum):r.gte(n.minimum)),n.maximum!==void 0&&(r=n.exclusiveMaximum?r.lt(n.maximum):r.lte(n.maximum)),r}static applyNumberMultipleOf(t,n){return n.multipleOf===void 0?t:t.refine(r=>r%n.multipleOf===0,{message:`Number must be a multiple of ${n.multipleOf}`})}static applyNumberEnum(t,n){if(!n.enum)return t;const r=n.enum.filter(s=>typeof s=="number");return r.length===0?t:t.refine(s=>r.includes(s),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(t,n){return n.type!=="integer"?t:t.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(t){let n=Oe(),r=n;return t.format?this.applyStringFormat(n,t):(r=this.applyStringPattern(n,t),r=this.applyStringLength(n,t),r=this.applyStringEnum(n,t),r)}static applyStringFormat(t,n){if(!n.format)return t;switch(n.format){case"email":return t.email();case"date-time":return t.datetime();case"uri":return t.url();case"uuid":return t.uuid();case"date":return t.date();default:return t}}static applyStringPattern(t,n){if(!n.pattern)return t;const r=new RegExp(n.pattern);return t.regex(r,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(t,n){let r=t;return n.minLength!==void 0&&(t=t.min(n.minLength)),n.maxLength!==void 0&&(t=t.max(n.maxLength)),r}static applyStringEnum(t,n){return n.enum?t.refine(r=>n.enum?.includes(r),{message:`Value must be one of: ${n.enum?.join(", ")}`}):t}static parseArray(t){if(Array.isArray(t.items)){const a=t.items.map(i=>this.parseSchema(i));return en(a)}const n=t.items?this.parseSchema(t.items):ht();let r=Pn(n),s=r;return s=this.applyArrayConstraints(r,t),s}static applyArrayConstraints(t,n){return n.minItems!==void 0&&(t=t.min(n.minItems)),n.maxItems!==void 0&&(t=t.max(n.maxItems)),n.uniqueItems?t.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):t}static parseObject(t){if(t.if&&t.then)return this.parseConditional(t);const n={};return this.processObjectProperties(t,n),this.processAdditionalProperties(t,te(n))}static processObjectProperties(t,n){const r=new Set(t.required||[]);if(t.properties)for(const[s,a]of Object.entries(t.properties)){const i=this.parseSchema(a);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(t,n){if(t.additionalProperties===!0)return n.passthrough();if(t.additionalProperties&&typeof t.additionalProperties=="object"){const r=this.parseSchema(t.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(t){const n=this.createBaseObjectSchema(t),r=t.if,s=t.then,a=t.else;return n.superRefine((i,o)=>{const c=this.applyDefaultValues(i,t);this.matchesCondition(c,r)?this.validateConditionalSchema(c,s,o):a&&this.validateConditionalSchema(c,a,o)})}static createBaseObjectSchema(t){const n={},r=new Set(t.required||[]);for(const[a,i]of Object.entries(t.properties||{})){const o=this.parseSchema(i);n[a]=r.has(a)?o:o.optional()}const s=te(n);return this.processAdditionalProperties(t,s)}static applyDefaultValues(t,n){if(typeof t!="object"||t===null||Array.isArray(t))return t;const s={...t};if(!n.properties)return s;for(const[a,i]of Object.entries(n.properties))!(a in s)&&"default"in i&&(s[a]=i.default);return s}static parseCombinator(t){if(t.oneOf)return this.parseOneOf(t.oneOf);if(t.anyOf)return this.parseAnyOf(t.anyOf);if(t.allOf)return this.parseAllOf(t.allOf);throw new Error("Unsupported schema type")}static parseOneOf(t){return this.createUnionFromSchemas(t)}static parseAnyOf(t){return this.createUnionFromSchemas(t)}static createUnionFromSchemas(t){if(t.length===0)return ht();if(t.length===1)return this.parseSchema(t[0]);const n=[];for(const r of t)r.type==="null"?n.push(fy()):n.push(this.parseSchema(r));return n.length>=2?en(n):n.length===1?n[0]:ht()}static parseAllOf(t){if(t.length===0)return ht();if(t.length===1)return this.parseSchema(t[0]);const n=t.reduce((r,s)=>this.mergeSchemas(r,s));return this.parseSchema(n)}static mergeSchemas(t,n){const r={...t,...n};if(t.properties&&n.properties){const s={...t.properties,...n.properties};r.properties=s}if(t.required&&n.required){const s=[...new Set([...t.required,...n.required])];r.required=s}return r}}var tw=Object.defineProperty,F=(e,t)=>{for(var n in t)tw(e,n,{get:t[n],enumerable:!0})};function nw(e,t){return t?.[e]||r_(e)}function rw(e,t){return t?.[e]||n_(e)}function sh(e,t,n){const r={};for(const s in e)Object.hasOwn(e,s)&&(r[t(s,n)]=e[s]);return r}var ah={};F(ah,{Serializable:()=>Tt,get_lc_unique_name:()=>ui});function fu(e){return Array.isArray(e)?[...e]:{...e}}function sw(e,t){const n=fu(e);for(const[r,s]of Object.entries(t)){const[a,...i]=r.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=fu(o[c]),o=o[c]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return n}function ui(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 Tt=class ih{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ui(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(([r])=>this.lc_serializable_keys?.includes(r))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof ih||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},r=Object.keys(this.lc_kwargs).reduce((s,a)=>(s[a]=a in this?this[a]:this.lc_kwargs[a],s),{});for(let s=Object.getPrototypeOf(this);s;s=Object.getPrototypeOf(s))Object.assign(t,Reflect.get(s,"lc_aliases",this)),Object.assign(n,Reflect.get(s,"lc_secrets",this)),Object.assign(r,Reflect.get(s,"lc_attributes",this));return Object.keys(n).forEach(s=>{let a=this,i=r;const[o,...c]=s.split(".").reverse();for(const l of c.reverse()){if(!(l in a)||a[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof a[l]=="object"&&a[l]!=null?i[l]={}:Array.isArray(a[l])&&(i[l]=[])),a=a[l],i=i[l]}o in a&&a[o]!==void 0&&(i[o]=i[o]||a[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:sh(Object.keys(n).length?sw(r,n):r,nw,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function kn(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 Fc(e){return kn(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function Bc(e){return kn(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function aw(e){return kn(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function oh(e){return kn(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function ch(e){if(kn(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 iw(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(),r=t[1].trim();if(n===""||r==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const s={};for(const a of e.split(";").slice(1)){const i=a.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}".`);s[o]=c}return{type:n,subtype:r,parameters:s}}function No({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(n){r=n[1].toLowerCase();const s=t?Uint8Array.from(atob(n[2]),a=>a.charCodeAt(0)):n[2];return{mime_type:r,data:s}}}function ow(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 U(e,t){return H(e)&&e.type===t}function H(e){return typeof e=="object"&&e!==null}function Vt(e){return Array.isArray(e)}function $(e){return typeof e=="string"}function Pt(e){return typeof e=="number"}function zc(e){return e instanceof Uint8Array}function mu(e){try{return JSON.parse(e)}catch{return}}const vs=e=>e();function cw(e){if(e.type==="char_location"&&$(e.document_title)&&Pt(e.start_char_index)&&Pt(e.end_char_index)&&$(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="page_location"&&$(e.document_title)&&Pt(e.start_page_number)&&Pt(e.end_page_number)&&$(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="content_block_location"&&$(e.document_title)&&Pt(e.start_block_index)&&Pt(e.end_block_index)&&$(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="web_search_result_location"&&$(e.url)&&$(e.title)&&$(e.encrypted_index)&&$(e.cited_text)){const{url:t,title:n,encrypted_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"url",url:t,title:n,startIndex:Number(r),endIndex:Number(r),citedText:s}}if(e.type==="search_result_location"&&$(e.source)&&$(e.title)&&Pt(e.start_block_index)&&Pt(e.end_block_index)&&$(e.cited_text)){const{source:t,title:n,start_block_index:r,end_block_index:s,cited_text:a,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:r,endIndex:s,citedText:a}}}function lh(e){if(U(e,"document")&&H(e.source)&&"type"in e.source){if(e.source.type==="base64"&&$(e.source.media_type)&&$(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&$(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&$(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&$(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(U(e,"image")&&H(e.source)&&"type"in e.source){if(e.source.type==="base64"&&$(e.source.media_type)&&$(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&$(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&$(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function lw(e){function*t(){for(const n of e){const r=lh(n);r?yield r:yield n}}return Array.from(t())}function gu(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n){if(U(r,"text")&&$(r.text)){const{text:s,citations:a,...i}=r;if(Vt(a)&&a.length){const o=a.reduce((c,l)=>{const u=cw(l);return u?[...c,u]:c},[]);yield{...i,type:"text",text:s,annotations:o};continue}else{yield{...i,type:"text",text:s};continue}}else if(U(r,"thinking")&&$(r.thinking)){const{thinking:s,signature:a,...i}=r;yield{...i,type:"reasoning",reasoning:s,signature:a};continue}else if(U(r,"redacted_thinking")){yield{type:"non_standard",value:r};continue}else if(U(r,"tool_use")&&$(r.name)&&$(r.id)){yield{type:"tool_call",id:r.id,name:r.name,args:r.input};continue}else if(U(r,"input_json_delta")){if(dw(e)&&e.tool_call_chunks?.length){const s=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:s.id,name:s.name,args:s.args,index:s.index};continue}}else if(U(r,"server_tool_use")&&$(r.name)&&$(r.id)){const{name:s,id:a}=r;if(s==="web_search"){const i=vs(()=>{if(typeof r.input=="string")return r.input;if(H(r.input)&&$(r.input.query))return r.input.query;if($(r.partial_json)){const o=mu(r.partial_json);if(o?.query)return o.query}return""});yield{id:a,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(r.name==="code_execution"){const i=vs(()=>{if(typeof r.input=="string")return r.input;if(H(r.input)&&$(r.input.code))return r.input.code;if($(r.partial_json)){const o=mu(r.partial_json);if(o?.code)return o.code}return""});yield{id:a,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(U(r,"web_search_tool_result")&&$(r.tool_use_id)&&Vt(r.content)){const{content:s,tool_use_id:a}=r,i=s.reduce((o,c)=>U(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:a,status:"success",output:{urls:i}};continue}else if(U(r,"code_execution_tool_result")&&$(r.tool_use_id)&&H(r.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(U(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}else if(U(r,"mcp_tool_result")&&$(r.tool_use_id)&&H(r.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(U(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}else if(U(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}else if(U(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}else{const s=lh(r);if(s){yield s;continue}}yield{type:"non_standard",value:r}}}return Array.from(t())}const uw={translateContent:gu,translateContentChunk:gu};function dw(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function hw(e){return Fc(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:Bc(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:oh(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function pw(e){return e.map(hw)}function fw(e){return!!(U(e,"image_url")&&H(e.image_url)||U(e,"input_audio")&&H(e.input_audio)||U(e,"file")&&H(e.file))}function mw(e){if(U(e,"image_url")&&H(e.image_url)&&$(e.image_url.url)){const t=No({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(U(e,"input_audio")&&H(e.input_audio)&&$(e.input_audio.data)&&$(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(U(e,"file")&&H(e.file)&&$(e.file.data)){const t=No({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if($(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function gw(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...Hc(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 yw(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...Hc(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 Hc(e){const t=[];for(const n of e)fw(n)?t.push(mw(n)):t.push(n);return t}function _w(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:r,end_index:s}=e;return{type:"citation",url:t,title:n,startIndex:r,endIndex:s}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:r}=e;return{type:"citation",title:n,startIndex:r,endIndex:r,fileId:t}}return e}function uh(e){function*t(){H(e.additional_kwargs?.reasoning)&&Vt(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((s,a)=>H(a)&&$(a.text)?`${s}${a.text}`:s,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n)if(U(r,"text")){const{text:s,annotations:a,...i}=r;Array.isArray(a)?yield{...i,type:"text",text:String(s),annotations:a.map(_w)}:yield{...i,type:"text",text:String(s)}}for(const r of e.tool_calls??[])yield{type:"tool_call",id:r.id,name:r.name,args:r.args};if(H(e.additional_kwargs)&&Vt(e.additional_kwargs.tool_outputs))for(const r of e.additional_kwargs.tool_outputs){if(U(r,"web_search_call")){yield{id:r.id,type:"server_tool_call",name:"web_search",args:{query:r.query}};continue}else if(U(r,"file_search_call")){yield{id:r.id,type:"server_tool_call",name:"file_search",args:{query:r.query}};continue}else if(U(r,"computer_call")){yield{type:"non_standard",value:r};continue}else if(U(r,"code_interpreter_call")){if($(r.code)&&(yield{id:r.id,type:"server_tool_call",name:"code_interpreter",args:{code:r.code}}),Vt(r.outputs)){const s=vs(()=>{if(r.status!=="in_progress"){if(r.status==="completed")return 0;if(r.status==="incomplete")return 127;if(r.status!=="interpreting"&&r.status==="failed")return 1}});for(const a of r.outputs)if(U(a,"logs")){yield{type:"server_tool_call_result",toolCallId:r.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:s??0,stderr:[0,void 0].includes(s)?void 0:String(a.logs),stdout:[0,void 0].includes(s)?String(a.logs):void 0}};continue}}continue}else if(U(r,"mcp_call")){yield{id:r.id,type:"server_tool_call",name:"mcp_call",args:r.input};continue}else if(U(r,"mcp_list_tools")){yield{id:r.id,type:"server_tool_call",name:"mcp_list_tools",args:r.input};continue}else if(U(r,"mcp_approval_request")){yield{type:"non_standard",value:r};continue}else if(U(r,"image_generation_call")){yield{type:"non_standard",value:r};continue}H(r)&&(yield{type:"non_standard",value:r})}}return Array.from(t())}function ww(e){function*t(){yield*uh(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 vw={translateContent:e=>typeof e.content=="string"?gw(e):uh(e),translateContentChunk:e=>typeof e.content=="string"?yw(e):ww(e)};function dh(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function bw(e,t="pretty"){return t==="pretty"?Sw(e):JSON.stringify(e)}function Sw(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),s="=".repeat(r),a=n.length%2===0?s:`${s}=`;if(t.push(`${s}${n}${a}`),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
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Z5HYU3am.js","assets/index-C1F6bSOH.js","assets/index-SVv-Z-Et.js","assets/index-BrUPorMz.css","assets/chunk-VL2OQCWN-Ce71Oujn.js"])))=>i.map(i=>d[i]);
2
+ var hy=Object.defineProperty;var py=(e,t,n)=>t in e?hy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var su=(e,t,n)=>py(e,typeof t!="symbol"?t+"":t,n);import{b as ji,u as en,a as ht,c as Rc,n as St,s as Oe,d as Pn,o as te,e as fy,Z as R,f as Ht,h as au,l as Io,i as my,j as Yd,p as Xd,k as Fr,m as $c,q as Qd,_ as G,t as T,w as $a,x as iu,v as gy,y as La,z as yy,A as Po,B as _y,C as wy,H as vy,L as by,D as Sy,M as Ty,W as Ey,E as Cy}from"./index-SVv-Z-Et.js";import{u as Ay,w as Lc,x as ky,y as Be,z as Oy,A as xy,B as Iy,C as Py,D as Ny,E as My,F as Ry,G as $y,H as Ly,I as jy,d as An,J as Dy,g as Re,K as Uy,L as eh,M as Fy,N as By,O as ja,h as jc,Q as zy,R as Hy,S as Vy,U as Gy,W as Wy,X as Jy,Y as Ky,Z as Zy,a0 as qy,a1 as Yy,a2 as Xy,a3 as ou,a4 as Qy,a5 as e_,a6 as t_,a7 as n_,s as r_,v as Ce,P as tn,p as Da,a as ws,b as th,c as nh,i as Dc,j as s_,f as a_,_ as i_,$ as o_,e as c_,k as l_,t as cu,l as rh,V as Uc,m as u_,n as br,o as d_,T as h_,q as p_,r as f_,a8 as m_}from"./chunk-VL2OQCWN-Ce71Oujn.js";var Di,ra,Ui=0,Fi=0;function g_(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=Di),i==null&&(i=ra)),a==null||i==null){var o=e.random||(e.rng||Ay)();a==null&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],!Di&&!e._v6&&(a[0]|=1,Di=a)),i==null&&(i=(o[6]<<8|o[7])&16383,ra===void 0&&!e._v6&&(ra=i))}var c=e.msecs!==void 0?e.msecs:Date.now(),l=e.nsecs!==void 0?e.nsecs:Fi+1,u=c-Ui+(l-Fi)/1e4;if(u<0&&e.clockseq===void 0&&(i=i+1&16383),(u<0||c>Ui)&&e.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ui=c,Fi=l,ra=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||Lc(s)}function y_(e){var t=typeof e=="string"?ky(e):e,n=__(t);return typeof e=="string"?Lc(n):n}function __(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 lu(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 uu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?lu(Object(n),!0).forEach(function(r){w_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lu(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function w_(e,t,n){return(t=v_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function v_(e){var t=b_(e,"string");return typeof t=="symbol"?t:t+""}function b_(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 S_(e={},t,n=0){var r=g_(uu(uu({},e),{},{_v6:!0}),new Uint8Array(16));return r=y_(r),Lc(r)}const T_=(e,t)=>{Oy.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Iy(e,n)},flatten:{value:n=>xy(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},li=Be("ZodError",T_,{Parent:Error}),E_=Py(li),C_=My(li),A_=Ny(li),k_=Ry(li),ct=Be("ZodType",(e,t)=>(jy.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)=>An(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>E_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>A_(e,n,r),e.parseAsync=async(n,r)=>C_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>k_(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(X_(n,r)),e.superRefine=n=>e.check(Q_(n)),e.overwrite=n=>e.check(Dy(n)),e.optional=()=>du(e),e.nullable=()=>hu(e),e.nullish=()=>du(hu(e)),e.nonoptional=n=>V_(e,n),e.array=()=>I_(e),e.or=n=>N_([e,n]),e.and=n=>R_(e,n),e.transform=n=>pu(e,L_(n)),e.default=n=>F_(e,n),e.prefault=n=>z_(e,n),e.catch=n=>W_(e,n),e.pipe=n=>pu(e,n),e.readonly=()=>Z_(e),e.describe=n=>{const r=e.clone();return Re.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return Re.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Re.get(e);const r=e.clone();return Re.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),O_=Be("ZodAny",(e,t)=>{Ly.init(e,t),ct.init(e,t)});function sa(){return $y(O_)}const x_=Be("ZodArray",(e,t)=>{Xy.init(e,t),ct.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(ou(n,r)),e.nonempty=n=>e.check(ou(1,n)),e.max=(n,r)=>e.check(Qy(n,r)),e.length=(n,r)=>e.check(e_(n,r)),e.unwrap=()=>e.element});function I_(e,t){return Fy(x_,e,t)}const P_=Be("ZodUnion",(e,t)=>{Vy.init(e,t),ct.init(e,t),e.options=t.options});function N_(e,t){return new P_({type:"union",options:e,...eh(t)})}const M_=Be("ZodIntersection",(e,t)=>{Gy.init(e,t),ct.init(e,t)});function R_(e,t){return new M_({type:"intersection",left:e,right:t})}const $_=Be("ZodTransform",(e,t)=>{Jy.init(e,t),ct.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(ja(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(ja(i))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function L_(e){return new $_({type:"transform",transform:e})}const j_=Be("ZodOptional",(e,t)=>{jc.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function du(e){return new j_({type:"optional",innerType:e})}const D_=Be("ZodNullable",(e,t)=>{zy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function hu(e){return new D_({type:"nullable",innerType:e})}const U_=Be("ZodDefault",(e,t)=>{Ky.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F_(e,t){return new U_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const B_=Be("ZodPrefault",(e,t)=>{Zy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function z_(e,t){return new B_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const H_=Be("ZodNonOptional",(e,t)=>{Hy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function V_(e,t){return new H_({type:"nonoptional",innerType:e,...eh(t)})}const G_=Be("ZodCatch",(e,t)=>{qy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function W_(e,t){return new G_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const J_=Be("ZodPipe",(e,t)=>{Wy.init(e,t),ct.init(e,t),e.in=t.in,e.out=t.out});function pu(e,t){return new J_({type:"pipe",in:e,out:t})}const K_=Be("ZodReadonly",(e,t)=>{Yy.init(e,t),ct.init(e,t)});function Z_(e){return new K_({type:"readonly",innerType:e})}const q_=Be("ZodCustom",(e,t)=>{t_.init(e,t),ct.init(e,t)});function Y_(e){const t=new By({check:"custom"});return t._zod.check=e,t}function X_(e,t={}){return Uy(q_,e,t)}function Q_(e){const t=Y_(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ja(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(ja(s))}},e(n.value,n)));return t}class ew{static convert(t){return this.parseSchema(t)}static matchesCondition(t,n){if(!n.properties)return!0;if(typeof t!="object"||t===null||Array.isArray(t))return!1;const r=t;for(const[s,a]of Object.entries(n.properties)){if(!(s in r)){if("const"in a)return!1;continue}const i=r[s];if("const"in a&&i!==a.const||"minimum"in a&&typeof i=="number"&&i<a.minimum||"maximum"in a&&typeof i=="number"&&i>a.maximum)return!1}return!0}static validateConditionalSchema(t,n,r){this.validateRequiredProperties(t,n,r),this.validatePropertyPatterns(t,n,r),this.validateNestedConditions(t,n,r)}static validateRequiredProperties(t,n,r){if(n.required){if(typeof t!="object"||t===null){for(const s of n.required)r.addIssue({code:ji.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in t||r.addIssue({code:ji.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(t,n,r){if(!n.properties||typeof t!="object"||t===null||Array.isArray(t))return;const s=t;for(const[a,i]of Object.entries(n.properties)){if(!(a in s))continue;const o=s[a];i.pattern&&typeof o=="string"&&(new RegExp(i.pattern).test(o)||r.addIssue({code:ji.custom,message:`String '${o}' does not match pattern '${i.pattern}'`,path:[a]}))}}static validateNestedConditions(t,n,r){if(!n.if||!n.then)return;this.matchesCondition(t,n.if)?this.validateConditionalSchema(t,n.then,r):n.else&&this.validateConditionalSchema(t,n.else,r)}static parseSchema(t){return Array.isArray(t.type)?this.handleTypeArray(t):t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.if&&t.then?this.parseObject(t):t.properties&&(!t.type||t.type==="object")?this.parseObject(t):this.handleSingleType(t)}static handleTypeArray(t){if(!Array.isArray(t.type))throw new Error("Expected schema.type to be an array");return t.type.includes("null")?this.handleNullableType(t):this.createUnionFromTypes(t.type,t)}static handleNullableType(t){if(!Array.isArray(t.type))throw new Error("Expected schema.type to be an array");const n={...t};return n.type=t.type.filter(s=>s!=="null"),n.type.length===1?this.handleSingleType({...t,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(t,n){const r=t.map(s=>{const a={...n,type:s};return this.parseSchema(a)});return en(r)}static handleSingleType(t){if(t.type===void 0)return t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.properties?this.parseObject(t):ht();switch(t.type){case"string":return this.parseString(t);case"number":case"integer":return this.parseNumberSchema(t);case"boolean":return Rc();case"array":return this.parseArray(t);case"object":return this.parseObject(t);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(t){let n=St(),r=n;return r=this.applyNumberBounds(n,t),r=this.applyNumberMultipleOf(n,t),r=this.applyNumberEnum(n,t),r=this.applyIntegerConstraint(n,t),r}static applyNumberBounds(t,n){let r=t;return n.minimum!==void 0&&(r=n.exclusiveMinimum?r.gt(n.minimum):r.gte(n.minimum)),n.maximum!==void 0&&(r=n.exclusiveMaximum?r.lt(n.maximum):r.lte(n.maximum)),r}static applyNumberMultipleOf(t,n){return n.multipleOf===void 0?t:t.refine(r=>r%n.multipleOf===0,{message:`Number must be a multiple of ${n.multipleOf}`})}static applyNumberEnum(t,n){if(!n.enum)return t;const r=n.enum.filter(s=>typeof s=="number");return r.length===0?t:t.refine(s=>r.includes(s),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(t,n){return n.type!=="integer"?t:t.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(t){let n=Oe(),r=n;return t.format?this.applyStringFormat(n,t):(r=this.applyStringPattern(n,t),r=this.applyStringLength(n,t),r=this.applyStringEnum(n,t),r)}static applyStringFormat(t,n){if(!n.format)return t;switch(n.format){case"email":return t.email();case"date-time":return t.datetime();case"uri":return t.url();case"uuid":return t.uuid();case"date":return t.date();default:return t}}static applyStringPattern(t,n){if(!n.pattern)return t;const r=new RegExp(n.pattern);return t.regex(r,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(t,n){let r=t;return n.minLength!==void 0&&(t=t.min(n.minLength)),n.maxLength!==void 0&&(t=t.max(n.maxLength)),r}static applyStringEnum(t,n){return n.enum?t.refine(r=>n.enum?.includes(r),{message:`Value must be one of: ${n.enum?.join(", ")}`}):t}static parseArray(t){if(Array.isArray(t.items)){const a=t.items.map(i=>this.parseSchema(i));return en(a)}const n=t.items?this.parseSchema(t.items):ht();let r=Pn(n),s=r;return s=this.applyArrayConstraints(r,t),s}static applyArrayConstraints(t,n){return n.minItems!==void 0&&(t=t.min(n.minItems)),n.maxItems!==void 0&&(t=t.max(n.maxItems)),n.uniqueItems?t.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):t}static parseObject(t){if(t.if&&t.then)return this.parseConditional(t);const n={};return this.processObjectProperties(t,n),this.processAdditionalProperties(t,te(n))}static processObjectProperties(t,n){const r=new Set(t.required||[]);if(t.properties)for(const[s,a]of Object.entries(t.properties)){const i=this.parseSchema(a);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(t,n){if(t.additionalProperties===!0)return n.passthrough();if(t.additionalProperties&&typeof t.additionalProperties=="object"){const r=this.parseSchema(t.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(t){const n=this.createBaseObjectSchema(t),r=t.if,s=t.then,a=t.else;return n.superRefine((i,o)=>{const c=this.applyDefaultValues(i,t);this.matchesCondition(c,r)?this.validateConditionalSchema(c,s,o):a&&this.validateConditionalSchema(c,a,o)})}static createBaseObjectSchema(t){const n={},r=new Set(t.required||[]);for(const[a,i]of Object.entries(t.properties||{})){const o=this.parseSchema(i);n[a]=r.has(a)?o:o.optional()}const s=te(n);return this.processAdditionalProperties(t,s)}static applyDefaultValues(t,n){if(typeof t!="object"||t===null||Array.isArray(t))return t;const s={...t};if(!n.properties)return s;for(const[a,i]of Object.entries(n.properties))!(a in s)&&"default"in i&&(s[a]=i.default);return s}static parseCombinator(t){if(t.oneOf)return this.parseOneOf(t.oneOf);if(t.anyOf)return this.parseAnyOf(t.anyOf);if(t.allOf)return this.parseAllOf(t.allOf);throw new Error("Unsupported schema type")}static parseOneOf(t){return this.createUnionFromSchemas(t)}static parseAnyOf(t){return this.createUnionFromSchemas(t)}static createUnionFromSchemas(t){if(t.length===0)return ht();if(t.length===1)return this.parseSchema(t[0]);const n=[];for(const r of t)r.type==="null"?n.push(fy()):n.push(this.parseSchema(r));return n.length>=2?en(n):n.length===1?n[0]:ht()}static parseAllOf(t){if(t.length===0)return ht();if(t.length===1)return this.parseSchema(t[0]);const n=t.reduce((r,s)=>this.mergeSchemas(r,s));return this.parseSchema(n)}static mergeSchemas(t,n){const r={...t,...n};if(t.properties&&n.properties){const s={...t.properties,...n.properties};r.properties=s}if(t.required&&n.required){const s=[...new Set([...t.required,...n.required])];r.required=s}return r}}var tw=Object.defineProperty,F=(e,t)=>{for(var n in t)tw(e,n,{get:t[n],enumerable:!0})};function nw(e,t){return t?.[e]||r_(e)}function rw(e,t){return t?.[e]||n_(e)}function sh(e,t,n){const r={};for(const s in e)Object.hasOwn(e,s)&&(r[t(s,n)]=e[s]);return r}var ah={};F(ah,{Serializable:()=>Tt,get_lc_unique_name:()=>ui});function fu(e){return Array.isArray(e)?[...e]:{...e}}function sw(e,t){const n=fu(e);for(const[r,s]of Object.entries(t)){const[a,...i]=r.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=fu(o[c]),o=o[c]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return n}function ui(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 Tt=class ih{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ui(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(([r])=>this.lc_serializable_keys?.includes(r))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof ih||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},r=Object.keys(this.lc_kwargs).reduce((s,a)=>(s[a]=a in this?this[a]:this.lc_kwargs[a],s),{});for(let s=Object.getPrototypeOf(this);s;s=Object.getPrototypeOf(s))Object.assign(t,Reflect.get(s,"lc_aliases",this)),Object.assign(n,Reflect.get(s,"lc_secrets",this)),Object.assign(r,Reflect.get(s,"lc_attributes",this));return Object.keys(n).forEach(s=>{let a=this,i=r;const[o,...c]=s.split(".").reverse();for(const l of c.reverse()){if(!(l in a)||a[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof a[l]=="object"&&a[l]!=null?i[l]={}:Array.isArray(a[l])&&(i[l]=[])),a=a[l],i=i[l]}o in a&&a[o]!==void 0&&(i[o]=i[o]||a[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:sh(Object.keys(n).length?sw(r,n):r,nw,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function kn(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 Fc(e){return kn(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function Bc(e){return kn(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function aw(e){return kn(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function oh(e){return kn(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function ch(e){if(kn(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 iw(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(),r=t[1].trim();if(n===""||r==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const s={};for(const a of e.split(";").slice(1)){const i=a.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}".`);s[o]=c}return{type:n,subtype:r,parameters:s}}function No({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(n){r=n[1].toLowerCase();const s=t?Uint8Array.from(atob(n[2]),a=>a.charCodeAt(0)):n[2];return{mime_type:r,data:s}}}function ow(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 U(e,t){return H(e)&&e.type===t}function H(e){return typeof e=="object"&&e!==null}function Vt(e){return Array.isArray(e)}function $(e){return typeof e=="string"}function Pt(e){return typeof e=="number"}function zc(e){return e instanceof Uint8Array}function mu(e){try{return JSON.parse(e)}catch{return}}const vs=e=>e();function cw(e){if(e.type==="char_location"&&$(e.document_title)&&Pt(e.start_char_index)&&Pt(e.end_char_index)&&$(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="page_location"&&$(e.document_title)&&Pt(e.start_page_number)&&Pt(e.end_page_number)&&$(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="content_block_location"&&$(e.document_title)&&Pt(e.start_block_index)&&Pt(e.end_block_index)&&$(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="web_search_result_location"&&$(e.url)&&$(e.title)&&$(e.encrypted_index)&&$(e.cited_text)){const{url:t,title:n,encrypted_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"url",url:t,title:n,startIndex:Number(r),endIndex:Number(r),citedText:s}}if(e.type==="search_result_location"&&$(e.source)&&$(e.title)&&Pt(e.start_block_index)&&Pt(e.end_block_index)&&$(e.cited_text)){const{source:t,title:n,start_block_index:r,end_block_index:s,cited_text:a,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:r,endIndex:s,citedText:a}}}function lh(e){if(U(e,"document")&&H(e.source)&&"type"in e.source){if(e.source.type==="base64"&&$(e.source.media_type)&&$(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&$(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&$(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&$(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(U(e,"image")&&H(e.source)&&"type"in e.source){if(e.source.type==="base64"&&$(e.source.media_type)&&$(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&$(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&$(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function lw(e){function*t(){for(const n of e){const r=lh(n);r?yield r:yield n}}return Array.from(t())}function gu(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n){if(U(r,"text")&&$(r.text)){const{text:s,citations:a,...i}=r;if(Vt(a)&&a.length){const o=a.reduce((c,l)=>{const u=cw(l);return u?[...c,u]:c},[]);yield{...i,type:"text",text:s,annotations:o};continue}else{yield{...i,type:"text",text:s};continue}}else if(U(r,"thinking")&&$(r.thinking)){const{thinking:s,signature:a,...i}=r;yield{...i,type:"reasoning",reasoning:s,signature:a};continue}else if(U(r,"redacted_thinking")){yield{type:"non_standard",value:r};continue}else if(U(r,"tool_use")&&$(r.name)&&$(r.id)){yield{type:"tool_call",id:r.id,name:r.name,args:r.input};continue}else if(U(r,"input_json_delta")){if(dw(e)&&e.tool_call_chunks?.length){const s=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:s.id,name:s.name,args:s.args,index:s.index};continue}}else if(U(r,"server_tool_use")&&$(r.name)&&$(r.id)){const{name:s,id:a}=r;if(s==="web_search"){const i=vs(()=>{if(typeof r.input=="string")return r.input;if(H(r.input)&&$(r.input.query))return r.input.query;if($(r.partial_json)){const o=mu(r.partial_json);if(o?.query)return o.query}return""});yield{id:a,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(r.name==="code_execution"){const i=vs(()=>{if(typeof r.input=="string")return r.input;if(H(r.input)&&$(r.input.code))return r.input.code;if($(r.partial_json)){const o=mu(r.partial_json);if(o?.code)return o.code}return""});yield{id:a,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(U(r,"web_search_tool_result")&&$(r.tool_use_id)&&Vt(r.content)){const{content:s,tool_use_id:a}=r,i=s.reduce((o,c)=>U(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:a,status:"success",output:{urls:i}};continue}else if(U(r,"code_execution_tool_result")&&$(r.tool_use_id)&&H(r.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(U(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}else if(U(r,"mcp_tool_result")&&$(r.tool_use_id)&&H(r.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(U(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}else if(U(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}else if(U(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}else{const s=lh(r);if(s){yield s;continue}}yield{type:"non_standard",value:r}}}return Array.from(t())}const uw={translateContent:gu,translateContentChunk:gu};function dw(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function hw(e){return Fc(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:Bc(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:oh(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function pw(e){return e.map(hw)}function fw(e){return!!(U(e,"image_url")&&H(e.image_url)||U(e,"input_audio")&&H(e.input_audio)||U(e,"file")&&H(e.file))}function mw(e){if(U(e,"image_url")&&H(e.image_url)&&$(e.image_url.url)){const t=No({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(U(e,"input_audio")&&H(e.input_audio)&&$(e.input_audio.data)&&$(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(U(e,"file")&&H(e.file)&&$(e.file.data)){const t=No({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if($(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function gw(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...Hc(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 yw(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...Hc(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 Hc(e){const t=[];for(const n of e)fw(n)?t.push(mw(n)):t.push(n);return t}function _w(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:r,end_index:s}=e;return{type:"citation",url:t,title:n,startIndex:r,endIndex:s}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:r}=e;return{type:"citation",title:n,startIndex:r,endIndex:r,fileId:t}}return e}function uh(e){function*t(){H(e.additional_kwargs?.reasoning)&&Vt(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((s,a)=>H(a)&&$(a.text)?`${s}${a.text}`:s,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n)if(U(r,"text")){const{text:s,annotations:a,...i}=r;Array.isArray(a)?yield{...i,type:"text",text:String(s),annotations:a.map(_w)}:yield{...i,type:"text",text:String(s)}}for(const r of e.tool_calls??[])yield{type:"tool_call",id:r.id,name:r.name,args:r.args};if(H(e.additional_kwargs)&&Vt(e.additional_kwargs.tool_outputs))for(const r of e.additional_kwargs.tool_outputs){if(U(r,"web_search_call")){yield{id:r.id,type:"server_tool_call",name:"web_search",args:{query:r.query}};continue}else if(U(r,"file_search_call")){yield{id:r.id,type:"server_tool_call",name:"file_search",args:{query:r.query}};continue}else if(U(r,"computer_call")){yield{type:"non_standard",value:r};continue}else if(U(r,"code_interpreter_call")){if($(r.code)&&(yield{id:r.id,type:"server_tool_call",name:"code_interpreter",args:{code:r.code}}),Vt(r.outputs)){const s=vs(()=>{if(r.status!=="in_progress"){if(r.status==="completed")return 0;if(r.status==="incomplete")return 127;if(r.status!=="interpreting"&&r.status==="failed")return 1}});for(const a of r.outputs)if(U(a,"logs")){yield{type:"server_tool_call_result",toolCallId:r.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:s??0,stderr:[0,void 0].includes(s)?void 0:String(a.logs),stdout:[0,void 0].includes(s)?String(a.logs):void 0}};continue}}continue}else if(U(r,"mcp_call")){yield{id:r.id,type:"server_tool_call",name:"mcp_call",args:r.input};continue}else if(U(r,"mcp_list_tools")){yield{id:r.id,type:"server_tool_call",name:"mcp_list_tools",args:r.input};continue}else if(U(r,"mcp_approval_request")){yield{type:"non_standard",value:r};continue}else if(U(r,"image_generation_call")){yield{type:"non_standard",value:r};continue}H(r)&&(yield{type:"non_standard",value:r})}}return Array.from(t())}function ww(e){function*t(){yield*uh(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 vw={translateContent:e=>typeof e.content=="string"?gw(e):uh(e),translateContentChunk:e=>typeof e.content=="string"?yw(e):ww(e)};function dh(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function bw(e,t="pretty"){return t==="pretty"?Sw(e):JSON.stringify(e)}function Sw(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),s="=".repeat(r),a=n.length%2===0?s:`${s}=`;if(t.push(`${s}${n}${a}`),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(`
3
3
  `)}const Bi=Symbol.for("langchain.message");function Xn(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.some(n=>kn(n))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?zs(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(n=>kn(n))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function hh(e,t){return e==="error"||t==="error"?"error":"success"}function Tw(e,t){function n(r,s){if(typeof r!="object"||r===null||r===void 0)return r;if(s>=t)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(i=>n(i,s+1));const a={};for(const i of Object.keys(r))a[i]=n(r[i],s+1);return a}return JSON.stringify(n(e,0),null,2)}var Ke=class extends Tt{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Bi]=!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[pw,Hc,lw].reduce((r,s)=>s(r),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&&Bi in e&&e[Bi]===!0&&dh(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=Tw(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return bw(this,e)}};function Ew(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}function Ue(e={},t={}){const n={...e};for(const[r,s]of Object.entries(t))if(n[r]==null)n[r]=s;else{if(s==null)continue;if(typeof n[r]!=typeof s||Array.isArray(n[r])!==Array.isArray(s))throw new Error(`field[${r}] already exists in the message chunk, but with a different type.`);if(typeof n[r]=="string"){if(r==="type")continue;["id","name","output_version","model_provider"].includes(r)?n[r]=s:n[r]+=s}else if(typeof n[r]=="object"&&!Array.isArray(n[r]))n[r]=Ue(n[r],s);else if(Array.isArray(n[r]))n[r]=zs(n[r],s);else{if(n[r]===s)continue;console.warn(`field[${r}] already exists in this message chunk and value has unsupported type.`)}}return n}function zs(e,t){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)return e||t;{const n=[...e];for(const r of t)if(typeof r=="object"&&r!==null&&"index"in r&&typeof r.index=="number"){const s=n.findIndex(a=>{const i=typeof a=="object",o="index"in a&&a.index===r.index,c="id"in a&&"id"in r&&a?.id===r?.id,l=!("id"in a)||!a?.id||!("id"in r)||!r?.id;return i&&o&&(c||l)});s!==-1&&typeof n[s]=="object"&&n[s]!==null?n[s]=Ue(n[s],r):n.push(r)}else{if(typeof r=="object"&&r!==null&&"text"in r&&r.text==="")continue;n.push(r)}return n}}}function ph(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.
4
4
  Left ${typeof e}
5
5
  Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return zs(e,t);if(typeof e=="object"&&typeof t=="object")return Ue(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.
@@ -567,4 +567,4 @@ ${f}`);const S=await s.stream(f);let b=null,v=0;for await(const E of S){if(v++,T
567
567
  🔧 Using tool: ${t.name}
568
568
  `;break;case"on_tool_end":yield`
569
569
  ✅ Tool completed: ${t.name}
570
- `;break}}G(ly,"streamEventsToAISDKWithTools");var Me={},kP=Me.MCP_USE_LANGFUSE?.toLowerCase()==="false",Bs={handler:null,client:null,initPromise:null};async function Xl(e,t,n,r){try{const s=await La(()=>import("./index-wkxN17B9.js"),__vite__mapDeps([0,1,2,3,4])).catch(()=>null);if(!s){T.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,y,S){super(h),this.agentId=p,this.metadata=f,this.metadataProvider=y,this.tagsProvider=S,this.verbose=h?.verbose??!1}async handleChainStart(h,p,f,y,S,b,v,w){T.debug("Langfuse: Chain start intercepted");const E=this.getCustomTags(),A=this.getMetadata(),I=[...S||[],...E],k={...b||{},...A};return this.verbose&&(T.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(I)}`),T.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(k)}`)),super.handleChainStart(h,p,f,y,I,k,v,w)}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=Me.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 T.debug("Langfuse: LLM start intercepted"),this.verbose&&T.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return T.debug("Langfuse: Tool start intercepted"),this.verbose&&T.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return T.debug("Langfuse: Retriever start intercepted"),this.verbose&&T.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return T.debug("Langfuse: Agent action intercepted"),this.verbose&&T.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return T.debug("Langfuse: Agent end intercepted"),this.verbose&&T.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:Me.LANGFUSE_PUBLIC_KEY,secretKey:Me.LANGFUSE_SECRET_KEY,baseUrl:Me.LANGFUSE_HOST||Me.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Me.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Me.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Me.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Me.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Me.LANGFUSE_ENABLED!=="false",traceName:o.trace_name||Me.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};T.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Bs.handler=new i(l,e,t,n,r),T.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await La(()=>import("./index-mBO7pd_t.js"),__vite__mapDeps([1,2,3,4])).catch(()=>null);if(d){const{Langfuse:h}=d;Bs.client=new h({publicKey:Me.LANGFUSE_PUBLIC_KEY,secretKey:Me.LANGFUSE_SECRET_KEY,baseUrl:Me.LANGFUSE_HOST||"https://cloud.langfuse.com"}),T.debug("Langfuse client initialized")}}catch(d){T.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){T.debug(`Langfuse initialization error: ${s}`)}}G(Xl,"initializeLangfuse");kP?T.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Me.LANGFUSE_PUBLIC_KEY||!Me.LANGFUSE_SECRET_KEY?T.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Bs.initPromise=Xl();var OP=G(()=>Bs.handler,"langfuseHandler"),xP=G(()=>Bs.initPromise,"langfuseInitPromise");const UP=Object.freeze(Object.defineProperty({__proto__:null,AIMessage:j,BaseAdapter:Xg,BaseConnector:_y,BaseMessage:Ke,BrowserOAuthClientProvider:wy,HttpConnector:vy,HumanMessage:ue,LangChainAdapter:Dn,Logger:by,MCPAgent:AP,MCPClient:Sy,MCPSession:Ty,ObservabilityManager:Pc,RemoteAgent:ry,SystemMessage:fe,ToolMessage:X,WebSocketConnector:Ey,createReadableStreamFromGenerator:cy,logger:T,onMcpAuthorization:Cy,streamEventsToAISDK:oy,streamEventsToAISDKWithTools:ly},Symbol.toStringTag,{value:"Module"})),qd=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:Xl,langfuseHandler:OP,langfuseInitPromise:xP},Symbol.toStringTag,{value:"Module"}));export{j as A,es as B,Qn as C,hi as F,ue as H,fe as S,X as T,Ke as a,mt as b,UP as c,ot as m};
570
+ `;break}}G(ly,"streamEventsToAISDKWithTools");var Me={},kP=Me.MCP_USE_LANGFUSE?.toLowerCase()==="false",Bs={handler:null,client:null,initPromise:null};async function Xl(e,t,n,r){try{const s=await La(()=>import("./index-Z5HYU3am.js"),__vite__mapDeps([0,1,2,3,4])).catch(()=>null);if(!s){T.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,y,S){super(h),this.agentId=p,this.metadata=f,this.metadataProvider=y,this.tagsProvider=S,this.verbose=h?.verbose??!1}async handleChainStart(h,p,f,y,S,b,v,w){T.debug("Langfuse: Chain start intercepted");const E=this.getCustomTags(),A=this.getMetadata(),I=[...S||[],...E],k={...b||{},...A};return this.verbose&&(T.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(I)}`),T.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(k)}`)),super.handleChainStart(h,p,f,y,I,k,v,w)}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=Me.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 T.debug("Langfuse: LLM start intercepted"),this.verbose&&T.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return T.debug("Langfuse: Tool start intercepted"),this.verbose&&T.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return T.debug("Langfuse: Retriever start intercepted"),this.verbose&&T.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return T.debug("Langfuse: Agent action intercepted"),this.verbose&&T.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return T.debug("Langfuse: Agent end intercepted"),this.verbose&&T.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:Me.LANGFUSE_PUBLIC_KEY,secretKey:Me.LANGFUSE_SECRET_KEY,baseUrl:Me.LANGFUSE_HOST||Me.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Me.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Me.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Me.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Me.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Me.LANGFUSE_ENABLED!=="false",traceName:o.trace_name||Me.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};T.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Bs.handler=new i(l,e,t,n,r),T.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await La(()=>import("./index-C1F6bSOH.js"),__vite__mapDeps([1,2,3,4])).catch(()=>null);if(d){const{Langfuse:h}=d;Bs.client=new h({publicKey:Me.LANGFUSE_PUBLIC_KEY,secretKey:Me.LANGFUSE_SECRET_KEY,baseUrl:Me.LANGFUSE_HOST||"https://cloud.langfuse.com"}),T.debug("Langfuse client initialized")}}catch(d){T.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){T.debug(`Langfuse initialization error: ${s}`)}}G(Xl,"initializeLangfuse");kP?T.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Me.LANGFUSE_PUBLIC_KEY||!Me.LANGFUSE_SECRET_KEY?T.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Bs.initPromise=Xl();var OP=G(()=>Bs.handler,"langfuseHandler"),xP=G(()=>Bs.initPromise,"langfuseInitPromise");const UP=Object.freeze(Object.defineProperty({__proto__:null,AIMessage:j,BaseAdapter:Xg,BaseConnector:_y,BaseMessage:Ke,BrowserOAuthClientProvider:wy,HttpConnector:vy,HumanMessage:ue,LangChainAdapter:Dn,Logger:by,MCPAgent:AP,MCPClient:Sy,MCPSession:Ty,ObservabilityManager:Pc,RemoteAgent:ry,SystemMessage:fe,ToolMessage:X,WebSocketConnector:Ey,createReadableStreamFromGenerator:cy,logger:T,onMcpAuthorization:Cy,streamEventsToAISDK:oy,streamEventsToAISDKWithTools:ly},Symbol.toStringTag,{value:"Module"})),qd=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:Xl,langfuseHandler:OP,langfuseInitPromise:xP},Symbol.toStringTag,{value:"Module"}));export{j as A,es as B,Qn as C,hi as F,ue as H,fe as S,X as T,Ke as a,mt as b,UP as c,ot as m};
@@ -2,31 +2,51 @@
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="UTF-8" />
5
- <link rel="icon" type="image/svg+xml" href="https://inspector-cdn.mcp-use.com/favicon-black.svg" />
6
- <link rel="icon" type="image/svg+xml" href="https://inspector-cdn.mcp-use.com/favicon-white.svg" media="(prefers-color-scheme: dark)" />
7
- <link rel="icon" type="image/svg+xml" href="https://inspector-cdn.mcp-use.com/favicon-black.svg" media="(prefers-color-scheme: light)" />
5
+ <link
6
+ rel="icon"
7
+ type="image/svg+xml"
8
+ href="https://inspector-cdn.mcp-use.com/favicon-black.svg"
9
+ />
10
+ <link
11
+ rel="icon"
12
+ type="image/svg+xml"
13
+ href="https://inspector-cdn.mcp-use.com/favicon-white.svg"
14
+ media="(prefers-color-scheme: dark)"
15
+ />
16
+ <link
17
+ rel="icon"
18
+ type="image/svg+xml"
19
+ href="https://inspector-cdn.mcp-use.com/favicon-black.svg"
20
+ media="(prefers-color-scheme: light)"
21
+ />
8
22
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
9
23
  <link rel="preconnect" href="https://fonts.googleapis.com" />
10
24
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
11
- <link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@400;500;700&display=swap" rel="stylesheet" />
25
+ <link
26
+ href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@400;500;700&display=swap"
27
+ rel="stylesheet"
28
+ />
12
29
  <title>Inspector | mcp-use</title>
13
- <script type="module" crossorigin src="/inspector/assets/index-DrYUC3_O.js"></script>
14
- <link rel="stylesheet" crossorigin href="/inspector/assets/index-Ba21hizt.css">
15
- <script>window.__INSPECTOR_VERSION__ = "0.4.11-canary.0";</script>
30
+ <script type="module" crossorigin src="/inspector/assets/index-SVv-Z-Et.js"></script>
31
+ <link rel="stylesheet" crossorigin href="/inspector/assets/index-BrUPorMz.css">
32
+ <script>window.__INSPECTOR_VERSION__ = "0.4.11";</script>
16
33
  </head>
17
34
  <body>
18
35
  <script>
19
36
  // Ensure process is defined globally before any modules load
20
37
  // This prevents "process is not defined" errors in browser environments
21
- if (typeof window !== 'undefined' && typeof window.process === 'undefined') {
38
+ if (
39
+ typeof window !== "undefined" &&
40
+ typeof window.process === "undefined"
41
+ ) {
22
42
  window.process = {
23
43
  env: {},
24
- platform: 'browser',
44
+ platform: "browser",
25
45
  browser: true,
26
- version: 'v18.0.0',
27
- versions: { node: '18.0.0' },
28
- cwd: () => '/',
29
- nextTick: (fn, ...args) => queueMicrotask(() => fn(...args))
46
+ version: "v18.0.0",
47
+ versions: { node: "18.0.0" },
48
+ cwd: () => "/",
49
+ nextTick: (fn, ...args) => queueMicrotask(() => fn(...args)),
30
50
  };
31
51
  }
32
52
  </script>
@@ -2,7 +2,7 @@ import {
2
2
  checkClientFiles,
3
3
  getClientDistPath,
4
4
  getContentType
5
- } from "./chunk-VMVT3HVZ.js";
5
+ } from "./chunk-TIYOH5C4.js";
6
6
 
7
7
  // src/server/shared-static.ts
8
8
  import { existsSync, readFileSync } from "fs";
@@ -11,7 +11,9 @@ function registerStaticRoutes(app, clientDistPath) {
11
11
  const distPath = clientDistPath || getClientDistPath();
12
12
  if (!checkClientFiles(distPath)) {
13
13
  console.warn(`\u26A0\uFE0F MCP Inspector client files not found at ${distPath}`);
14
- console.warn(` Run 'yarn build' in the inspector package to build the UI`);
14
+ console.warn(
15
+ ` Run 'yarn build' in the inspector package to build the UI`
16
+ );
15
17
  app.get("*", (c) => {
16
18
  return c.html(`
17
19
  <!DOCTYPE html>
@@ -66,7 +68,9 @@ function registerStaticRoutesWithDevProxy(app, clientDistPath) {
66
68
  const distPath = clientDistPath || getClientDistPath();
67
69
  const isDev = process.env.NODE_ENV === "development" || process.env.VITE_DEV === "true";
68
70
  if (isDev) {
69
- console.warn("\u{1F527} Development mode: Proxying client requests to Vite dev server");
71
+ console.warn(
72
+ "\u{1F527} Development mode: Proxying client requests to Vite dev server"
73
+ );
70
74
  app.get("*", async (c) => {
71
75
  const path = c.req.path;
72
76
  if (path.startsWith("/api/") || path.startsWith("/inspector/api/") || path === "/inspector/config.json") {
@@ -11,7 +11,9 @@ function toBase64(str) {
11
11
  async function* handleChatRequestStream(requestBody) {
12
12
  const { mcpServerUrl, llmConfig, authConfig, messages } = requestBody;
13
13
  if (!mcpServerUrl || !llmConfig || !messages) {
14
- throw new Error("Missing required fields: mcpServerUrl, llmConfig, messages");
14
+ throw new Error(
15
+ "Missing required fields: mcpServerUrl, llmConfig, messages"
16
+ );
15
17
  }
16
18
  const { MCPAgent, MCPClient } = await import("mcp-use");
17
19
  let llm;
@@ -123,7 +125,9 @@ async function* handleChatRequestStream(requestBody) {
123
125
  async function handleChatRequest(requestBody) {
124
126
  const { mcpServerUrl, llmConfig, authConfig, messages } = requestBody;
125
127
  if (!mcpServerUrl || !llmConfig || !messages) {
126
- throw new Error("Missing required fields: mcpServerUrl, llmConfig, messages");
128
+ throw new Error(
129
+ "Missing required fields: mcpServerUrl, llmConfig, messages"
130
+ );
127
131
  }
128
132
  const { MCPAgent, MCPClient } = await import("mcp-use");
129
133
  let llm;
@@ -163,7 +167,10 @@ async function handleChatRequest(requestBody) {
163
167
  const tokenType = authConfig.oauthTokens.token_type ? authConfig.oauthTokens.token_type.charAt(0).toUpperCase() + authConfig.oauthTokens.token_type.slice(1) : "Bearer";
164
168
  serverConfig.headers.Authorization = `${tokenType} ${authConfig.oauthTokens.access_token}`;
165
169
  console.log("Using OAuth access token for MCP server authentication");
166
- console.log("Authorization header:", `${tokenType} ${authConfig.oauthTokens.access_token.substring(0, 20)}...`);
170
+ console.log(
171
+ "Authorization header:",
172
+ `${tokenType} ${authConfig.oauthTokens.access_token.substring(0, 20)}...`
173
+ );
167
174
  } else {
168
175
  console.warn("OAuth selected but no access token provided");
169
176
  }
@@ -218,21 +225,35 @@ setInterval(
218
225
  5 * 60 * 1e3
219
226
  ).unref();
220
227
  function storeWidgetData(data) {
221
- const { serverId, uri, toolInput, toolOutput, resourceData, toolId, widgetCSP } = data;
228
+ const {
229
+ serverId,
230
+ uri,
231
+ toolInput,
232
+ toolOutput,
233
+ resourceData,
234
+ toolId,
235
+ widgetCSP
236
+ } = data;
222
237
  console.log("[Widget Store] Received request for toolId:", toolId);
223
- console.log("[Widget Store] Fields:", { serverId, uri, hasResourceData: !!resourceData, hasToolInput: !!toolInput, hasToolOutput: !!toolOutput, hasWidgetCSP: !!widgetCSP });
238
+ console.log("[Widget Store] Fields:", {
239
+ serverId,
240
+ uri,
241
+ hasResourceData: !!resourceData,
242
+ hasToolInput: !!toolInput,
243
+ hasToolOutput: !!toolOutput,
244
+ hasWidgetCSP: !!widgetCSP
245
+ });
224
246
  if (!serverId || !uri || !toolId || !resourceData) {
225
247
  const missingFields = [];
226
- if (!serverId)
227
- missingFields.push("serverId");
228
- if (!uri)
229
- missingFields.push("uri");
230
- if (!toolId)
231
- missingFields.push("toolId");
232
- if (!resourceData)
233
- missingFields.push("resourceData");
248
+ if (!serverId) missingFields.push("serverId");
249
+ if (!uri) missingFields.push("uri");
250
+ if (!toolId) missingFields.push("toolId");
251
+ if (!resourceData) missingFields.push("resourceData");
234
252
  console.error("[Widget Store] Missing required fields:", missingFields);
235
- return { success: false, error: `Missing required fields: ${missingFields.join(", ")}` };
253
+ return {
254
+ success: false,
255
+ error: `Missing required fields: ${missingFields.join(", ")}`
256
+ };
236
257
  }
237
258
  widgetDataStore.set(toolId, {
238
259
  serverId,
@@ -286,7 +307,10 @@ function generateWidgetContainerHtml(basePath, toolId) {
286
307
  }
287
308
  function generateWidgetContentHtml(widgetData) {
288
309
  const { serverId, uri, toolInput, toolOutput, resourceData, toolId } = widgetData;
289
- console.log("[Widget Content] Using pre-fetched resource for:", { serverId, uri });
310
+ console.log("[Widget Content] Using pre-fetched resource for:", {
311
+ serverId,
312
+ uri
313
+ });
290
314
  let htmlContent = "";
291
315
  const contentsArray = Array.isArray(resourceData?.contents) ? resourceData.contents : [];
292
316
  const firstContent = contentsArray[0];
@@ -516,8 +540,8 @@ function getWidgetSecurityHeaders(widgetCSP) {
516
540
  "X-Frame-Options": "SAMEORIGIN",
517
541
  "X-Content-Type-Options": "nosniff",
518
542
  "Cache-Control": "no-cache, no-store, must-revalidate",
519
- "Pragma": "no-cache",
520
- "Expires": "0"
543
+ Pragma: "no-cache",
544
+ Expires: "0"
521
545
  };
522
546
  }
523
547
 
@@ -23,7 +23,9 @@ async function findAvailablePort(startPort = 8080, maxAttempts = 100) {
23
23
  continue;
24
24
  }
25
25
  }
26
- throw new Error(`No available port found after trying ${maxAttempts} ports starting from ${startPort}`);
26
+ throw new Error(
27
+ `No available port found after trying ${maxAttempts} ports starting from ${startPort}`
28
+ );
27
29
  }
28
30
  async function isPortAvailable(port) {
29
31
  const net = await import("net");
@@ -6,7 +6,9 @@ import { fileURLToPath } from "url";
6
6
  async function* handleChatRequestStream(requestBody) {
7
7
  const { mcpServerUrl, llmConfig, authConfig, messages } = requestBody;
8
8
  if (!mcpServerUrl || !llmConfig || !messages) {
9
- throw new Error("Missing required fields: mcpServerUrl, llmConfig, messages");
9
+ throw new Error(
10
+ "Missing required fields: mcpServerUrl, llmConfig, messages"
11
+ );
10
12
  }
11
13
  const { MCPAgent, MCPClient } = await import("mcp-use");
12
14
  let llm;
@@ -37,7 +39,9 @@ async function* handleChatRequestStream(requestBody) {
37
39
  if (authConfig && authConfig.type !== "none") {
38
40
  serverConfig.headers = {};
39
41
  if (authConfig.type === "basic" && authConfig.username && authConfig.password) {
40
- const auth = Buffer.from(`${authConfig.username}:${authConfig.password}`).toString("base64");
42
+ const auth = Buffer.from(
43
+ `${authConfig.username}:${authConfig.password}`
44
+ ).toString("base64");
41
45
  serverConfig.headers.Authorization = `Basic ${auth}`;
42
46
  } else if (authConfig.type === "bearer" && authConfig.token) {
43
47
  serverConfig.headers.Authorization = `Bearer ${authConfig.token}`;
@@ -51,7 +55,9 @@ async function* handleChatRequestStream(requestBody) {
51
55
  try {
52
56
  const url = new URL(mcpServerUrl);
53
57
  if (url.username && url.password && (!authConfig || authConfig.type === "none")) {
54
- const auth = Buffer.from(`${url.username}:${url.password}`).toString("base64");
58
+ const auth = Buffer.from(`${url.username}:${url.password}`).toString(
59
+ "base64"
60
+ );
55
61
  serverConfig.headers = serverConfig.headers || {};
56
62
  serverConfig.headers.Authorization = `Basic ${auth}`;
57
63
  serverConfig.url = `${url.protocol}//${url.host}${url.pathname}${url.search}`;
@@ -118,7 +124,9 @@ async function* handleChatRequestStream(requestBody) {
118
124
  async function handleChatRequest(requestBody) {
119
125
  const { mcpServerUrl, llmConfig, authConfig, messages } = requestBody;
120
126
  if (!mcpServerUrl || !llmConfig || !messages) {
121
- throw new Error("Missing required fields: mcpServerUrl, llmConfig, messages");
127
+ throw new Error(
128
+ "Missing required fields: mcpServerUrl, llmConfig, messages"
129
+ );
122
130
  }
123
131
  const { MCPAgent, MCPClient } = await import("mcp-use");
124
132
  let llm;
@@ -149,7 +157,9 @@ async function handleChatRequest(requestBody) {
149
157
  if (authConfig && authConfig.type !== "none") {
150
158
  serverConfig.headers = {};
151
159
  if (authConfig.type === "basic" && authConfig.username && authConfig.password) {
152
- const auth = Buffer.from(`${authConfig.username}:${authConfig.password}`).toString("base64");
160
+ const auth = Buffer.from(
161
+ `${authConfig.username}:${authConfig.password}`
162
+ ).toString("base64");
153
163
  serverConfig.headers.Authorization = `Basic ${auth}`;
154
164
  } else if (authConfig.type === "bearer" && authConfig.token) {
155
165
  serverConfig.headers.Authorization = `Bearer ${authConfig.token}`;
@@ -158,7 +168,10 @@ async function handleChatRequest(requestBody) {
158
168
  const tokenType = authConfig.oauthTokens.token_type ? authConfig.oauthTokens.token_type.charAt(0).toUpperCase() + authConfig.oauthTokens.token_type.slice(1) : "Bearer";
159
169
  serverConfig.headers.Authorization = `${tokenType} ${authConfig.oauthTokens.access_token}`;
160
170
  console.log("Using OAuth access token for MCP server authentication");
161
- console.log("Authorization header:", `${tokenType} ${authConfig.oauthTokens.access_token.substring(0, 20)}...`);
171
+ console.log(
172
+ "Authorization header:",
173
+ `${tokenType} ${authConfig.oauthTokens.access_token.substring(0, 20)}...`
174
+ );
162
175
  } else {
163
176
  console.warn("OAuth selected but no access token provided");
164
177
  }
@@ -167,7 +180,9 @@ async function handleChatRequest(requestBody) {
167
180
  try {
168
181
  const url = new URL(mcpServerUrl);
169
182
  if (url.username && url.password && (!authConfig || authConfig.type === "none")) {
170
- const auth = Buffer.from(`${url.username}:${url.password}`).toString("base64");
183
+ const auth = Buffer.from(`${url.username}:${url.password}`).toString(
184
+ "base64"
185
+ );
171
186
  serverConfig.headers = serverConfig.headers || {};
172
187
  serverConfig.headers.Authorization = `Basic ${auth}`;
173
188
  serverConfig.url = `${url.protocol}//${url.host}${url.pathname}${url.search}`;
@@ -245,21 +260,35 @@ setInterval(
245
260
  5 * 60 * 1e3
246
261
  ).unref();
247
262
  function storeWidgetData(data) {
248
- const { serverId, uri, toolInput, toolOutput, resourceData, toolId, widgetCSP } = data;
263
+ const {
264
+ serverId,
265
+ uri,
266
+ toolInput,
267
+ toolOutput,
268
+ resourceData,
269
+ toolId,
270
+ widgetCSP
271
+ } = data;
249
272
  console.log("[Widget Store] Received request for toolId:", toolId);
250
- console.log("[Widget Store] Fields:", { serverId, uri, hasResourceData: !!resourceData, hasToolInput: !!toolInput, hasToolOutput: !!toolOutput, hasWidgetCSP: !!widgetCSP });
273
+ console.log("[Widget Store] Fields:", {
274
+ serverId,
275
+ uri,
276
+ hasResourceData: !!resourceData,
277
+ hasToolInput: !!toolInput,
278
+ hasToolOutput: !!toolOutput,
279
+ hasWidgetCSP: !!widgetCSP
280
+ });
251
281
  if (!serverId || !uri || !toolId || !resourceData) {
252
282
  const missingFields = [];
253
- if (!serverId)
254
- missingFields.push("serverId");
255
- if (!uri)
256
- missingFields.push("uri");
257
- if (!toolId)
258
- missingFields.push("toolId");
259
- if (!resourceData)
260
- missingFields.push("resourceData");
283
+ if (!serverId) missingFields.push("serverId");
284
+ if (!uri) missingFields.push("uri");
285
+ if (!toolId) missingFields.push("toolId");
286
+ if (!resourceData) missingFields.push("resourceData");
261
287
  console.error("[Widget Store] Missing required fields:", missingFields);
262
- return { success: false, error: `Missing required fields: ${missingFields.join(", ")}` };
288
+ return {
289
+ success: false,
290
+ error: `Missing required fields: ${missingFields.join(", ")}`
291
+ };
263
292
  }
264
293
  widgetDataStore.set(toolId, {
265
294
  serverId,
@@ -313,7 +342,10 @@ function generateWidgetContainerHtml(basePath, toolId) {
313
342
  }
314
343
  function generateWidgetContentHtml(widgetData) {
315
344
  const { serverId, uri, toolInput, toolOutput, resourceData, toolId } = widgetData;
316
- console.log("[Widget Content] Using pre-fetched resource for:", { serverId, uri });
345
+ console.log("[Widget Content] Using pre-fetched resource for:", {
346
+ serverId,
347
+ uri
348
+ });
317
349
  let htmlContent = "";
318
350
  const contentsArray = Array.isArray(resourceData?.contents) ? resourceData.contents : [];
319
351
  const firstContent = contentsArray[0];
@@ -542,8 +574,8 @@ function getWidgetSecurityHeaders(widgetCSP) {
542
574
  "X-Frame-Options": "SAMEORIGIN",
543
575
  "X-Content-Type-Options": "nosniff",
544
576
  "Cache-Control": "no-cache, no-store, must-revalidate",
545
- "Pragma": "no-cache",
546
- "Expires": "0"
577
+ Pragma: "no-cache",
578
+ Expires: "0"
547
579
  };
548
580
  }
549
581