@mcp-use/inspector 0.14.2 → 0.14.3-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/web/assets/{browser-BLnflEDD.js → browser-CJMCg3ZC.js} +3 -3
- package/dist/web/assets/{client-D72CJBab.js → client-CBVDiOq1.js} +1 -1
- package/dist/web/assets/{display-A5IEINAP-DWRfr5cj.js → display-A5IEINAP-DUaOR-3m.js} +2 -2
- package/dist/web/assets/{embeddings-CVWvogFr.js → embeddings-DBkvyXXr.js} +1 -1
- package/dist/web/assets/{index-CbPoLZEh.js → index-1YTmX4QT.js} +1 -1
- package/dist/web/assets/{index-pQiGNlCj.js → index-BpbjNRUs.js} +1 -1
- package/dist/web/assets/{index-BgQZjv_u.js → index-C314DwyM.js} +1 -1
- package/dist/web/assets/{index-DdrkmeYH.js → index-CW3Avs3Z.js} +1 -1
- package/dist/web/assets/{index-BDlTOMS5.js → index-CpzEQlXL.js} +1 -1
- package/dist/web/assets/{index-Bi42MNIH.js → index-CqlJu5dO.js} +106 -106
- package/dist/web/assets/{index-D7_719w8.js → index-CvL4NMn9.js} +1 -1
- package/dist/web/assets/{index-Cv4xpdR-.js → index-hu1QYxMc.js} +1 -1
- package/dist/web/assets/{index-DdkxcTE2.js → index-nULKD42X.js} +1 -1
- package/dist/web/assets/{llms-xXlg9f0z.js → llms-DLjfslEu.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +3 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-
|
|
2
|
-
import{O as co,P as Rl,Q as jl,_ as N,o as we,l as m,s as br,S as ke,Z as Mr,w as Ar,j as Ll,n as Dl,i as Fl,U as Ul,V as Vl,W as Bl,p as ti,e as zl,X as Pr,Y as uo,a as Ut,x as $n}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-CBVDiOq1.js","assets/index-CqlJu5dO.js","assets/index-G80eS8Oh.css","assets/display-A5IEINAP-DUaOR-3m.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{O as co,P as Rl,Q as jl,_ as N,o as we,l as m,s as br,S as ke,Z as Mr,w as Ar,j as Ll,n as Dl,i as Fl,U as Ul,V as Vl,W as Bl,p as ti,e as zl,X as Pr,Y as uo,a as Ut,x as $n}from"./index-CqlJu5dO.js";import{B as fg,a0 as pg,T as mg,H as gg,a1 as yg,a2 as wg,M as vg,T as bg,a3 as _g,a4 as Sg,a5 as Cg,a5 as kg}from"./index-CqlJu5dO.js";import{D as Rn,S as _r,t as Wl,a as ni,T as Hl,b as Gl}from"./index-1YTmX4QT.js";import{h as Cn,s as Kl,k as ql,I as Jl,C as Yl,g as ri,d as Xl,l as Zl,m as Ql,t as ec,n as tc,o as nc,p as rc,q as sc,r as oc,u as ic,v as ac,w as lc,x as cc,y as uc,R as hc,z as dc,e as fc}from"./index-BpbjNRUs.js";import{aT as pc,aU as Ps,aV as mc,aw as Oe,e as nn,aW as gc,aX as hn,a4 as fe,y as Ee,aY as si,i as yc,aZ as Qr,g as J,aj as Xt,ah as pe,B as O,S as Q,p as wc,C as vc,a_ as bc,aE as oi,a$ as _e,al as dn,b0 as an,F as ii,z as je,b1 as Os,u as ho,D as es,E as Vt,ap as Bt,b2 as _c,b3 as Sc,b4 as Cc,b5 as kc,b6 as Tc,b7 as Ec,b8 as xc,b9 as Mc,ba as Ac,bb as Pc,bc as Oc,bd as Nc,be as Ic,bf as $c,bg as Rc,bh as jc,bi as Lc,L as Dc,bj as Fc,bk as Uc,bl as Vc,A as Ve,k as ln,m as Fe,M as tt,at as zt,bm as Bc,H as zc,aF as fo,au as Wc,bn as po,bo as mo,af as Ns,ae as go,ad as ts,ag as Hc,V as Gc,a9 as Is,ac as Xe,bp as tr,o as z,bq as le,br as Kc,bs as Ie,bt as Ct,bu as qc,bv as $s,f as U,aa as Jc,r as Yc,T as Xc,bw as nr,bx as We,by as V,bz as ai,s as ne,ab as Zc,bA as jn,bB as li,bC as Wt,bD as fn,bE as rr,bF as sr,bG as Qc,aP as eu,aN as tu,aM as nu,bH as ru}from"./index-CW3Avs3Z.js";import{E as ci,c as su,e as ou}from"./embeddings-DBkvyXXr.js";import{L as ui,o as iu,l as au}from"./llms-DLjfslEu.js";const lu=t=>{const e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},cu=()=>{const t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${lu(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${Rl(r.values[0])}`:`Invalid option: expected one of ${co(r.values,"|")}`;case"too_big":{const s=r.inclusive?"<=":"<",o=e(r.origin);return o?`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{const s=r.inclusive?">=":">",o=e(r.origin);return o?`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${o.unit}`:`Too small: expected ${r.origin} to be ${s}${r.minimum.toString()}`}case"invalid_format":{const s=r;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${n[s.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${co(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function uu(){return{localeError:cu()}}jl(uu());var Or,Mn,Nr=0,Ir=0;function hu(t,e,n){var r=0,s=e||new Array(16);t=t||{};var o=t.node,i=t.clockseq;if(t._v6||(o||(o=Or),i==null&&(i=Mn)),o==null||i==null){var a=t.random||(t.rng||pc)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Or&&!t._v6&&(o[0]|=1,Or=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Mn===void 0&&!t._v6&&(Mn=i))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Ir+1,u=l-Nr+(c-Ir)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||l>Nr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Nr=l,Ir=c,Mn=i,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=l/4294967296*1e4&268435455;s[r++]=d>>>8&255,s[r++]=d&255,s[r++]=d>>>24&15|16,s[r++]=d>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var f=0;f<6;++f)s[r+f]=o[f];return e||Ps(s)}function du(t){var e=typeof t=="string"?mc(t):t,n=fu(e);return typeof t=="string"?Ps(n):n}function fu(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function yo(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function wo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?yo(Object(n),!0).forEach(function(r){pu(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):yo(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function pu(t,e,n){return(e=mu(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mu(t){var e=gu(t,"string");return typeof e=="symbol"?e:e+""}function gu(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function yu(t={},e,n=0){var r=hu(wo(wo({},t),{},{_v6:!0}),new Uint8Array(16));return r=du(r),Ps(r)}async function*wu(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}N(wu,"streamEventsToAISDK");function vu(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}N(vu,"createReadableStreamFromGenerator");async function*bu(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
|
|
3
3
|
🔧 Using tool: ${e.name}
|
|
4
4
|
`;break;case"on_tool_end":yield`
|
|
5
5
|
✅ Tool completed: ${e.name}
|
|
@@ -374,7 +374,7 @@ You can then use these server-specific tools in subsequent steps.
|
|
|
374
374
|
Here are the tools *currently* available to you (this list includes server management tools and will
|
|
375
375
|
change when you connect to a server):
|
|
376
376
|
{tool_descriptions}
|
|
377
|
-
`;function er(t,e,n,r,s){if(typeof t=="object"&&t!==null){const o=t;return{query:o.prompt,maxSteps:o.maxSteps,manageConnector:o.manageConnector,externalHistory:o.externalHistory,outputSchema:o.schema}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s}}N(er,"normalizeRunOptions");var Ft,ug=(Ft=class{static getPackageVersion(){return zl()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new qm({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new gt,this.telemetry=Pr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Zo({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(typeof e.llm=="string"){if(this.isSimplifiedMode=!0,this.llmString=e.llm,this.llmConfig=e.llmConfig,this.mcpServersConfig=e.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw new Error("Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }");this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],m.info(`🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw new Error("Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.");if(this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.isSimplifiedMode)this.adapter=e.adapter??new gt(this.disallowedTools),this.telemetry=Pr.getInstance(),this.modelProvider="unknown",this.modelName="unknown";else{if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new gt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Xo(this.client,this.adapter)}else this.adapter=e.adapter??new gt(this.disallowedTools);if(this.telemetry=Pr.getInstance(),this.llm){const[r,s]=uo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Zo({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:N(()=>this.getMetadata(),"metadataProvider"),tagsProvider:N(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:N(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:N(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:N(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(m.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(m.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){m.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await Ut(async()=>{const{MCPClient:s}=await import("./client-D72CJBab.js");return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),m.info("✅ MCPClient created successfully")}if(this.llmString){m.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await Ol(this.llmString,this.llmConfig),m.info("✅ LLM created successfully");const[r,s]=uo(this.llm);this.modelProvider=r,this.modelName=s}catch(r){throw new Error(`Failed to create LLM from string '${this.llmString}': ${r?.message||r}`)}}if(this.useServerManager){if(!this.client)throw new Error("'client' must be available when 'useServerManager' is true.");this.serverManager=new Xo(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&m.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),m.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),m.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(m.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),m.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),m.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else{const s=await this.adapter.createToolsFromConnectors(Object.values(this.sessions).map(a=>a.connector)),o=await this.adapter.createResourcesFromConnectors(Object.values(this.sessions).map(a=>a.connector)),i=await this.adapter.createPromptsFromConnectors(Object.values(this.sessions).map(a=>a.connector));this._tools=[...s,...o,...i],m.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{m.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),m.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}m.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),m.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),m.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Xm;this.systemMessage=$l(e,n,Zm,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof _e))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(o=>o.name);m.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Ml({runLimit:this.maxSteps})],s=yl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return m.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new _e(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof _e)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),m.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new gt(this.disallowedTools),this._initialized&&m.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},m.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],m.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){m.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(m.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){m.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else m.warn(`Unsupported metadata value type for key '${o}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){m.warn(`Failed to get config for server '${s}': ${o}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){m.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof O)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof pe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof O||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,o){const{query:i,maxSteps:a,manageConnector:l,externalHistory:c,outputSchema:u}=er(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(i,a,l,c,u);const h=this.stream(i,a,l,c,u);return this._consumeAndReturn(h)}async*stream(e,n,r=!0,s,o){const{query:i,maxSteps:a,manageConnector:l,externalHistory:c,outputSchema:u}=er(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(i,a,l,c,u);let h=!1;const d=Date.now();let f=!1,g=null,p=0;try{if(l&&!this._initialized?(await this.initialize(),h=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),h=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const M=this.serverManager.tools,w=new Set(M.map(T=>T.name)),v=new Set(this._tools.map(T=>T.name));(w.size!==v.size||[...w].some(T=>!v.has(T)))&&(m.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...w].join(", ")}`),this._tools=M,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const S=c??this.conversationHistory,C=[];for(const M of S)(this._isHumanMessageLike(M)||this._isAIMessageLike(M)||this._isToolMessageLike(M))&&C.push(M);const y=i.length>50?`${i.slice(0,50).replace(/\n/g," ")}...`:i.replace(/\n/g," ");m.info(`💬 Received query: '${y}'`),m.info("🏁 Starting agent execution");const _=3;let b=0;const k=[...C,new pe(i)];for(;b<=_;){const M={messages:k};let w=!1;const v=await this._agentExecutor.stream(M,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const T of v){for(const[x,A]of Object.entries(T))if(m.debug(`📦 Node '${x}' output: ${JSON.stringify(A)}`),A&&typeof A=="object"&&"messages"in A){let I=A.messages;Array.isArray(I)||(I=[I]);for(const j of I)k.includes(j)||k.push(j);for(const j of I){if("tool_calls"in j&&Array.isArray(j.tool_calls)&&j.tool_calls.length>0)for(const ee of j.tool_calls){const re=ee.name||"unknown",Se=ee.args||{};this.toolsUsedNames.push(re),p++;let Me=JSON.stringify(Se);Me.length>100&&(Me=`${Me.slice(0,97)}...`),m.info(`🔧 Tool call: ${re} with input: ${Me}`),yield{action:{tool:re,toolInput:Se,log:`Calling tool ${re}`},observation:""}}if(this._isToolMessageLike(j)){const ee=j.content;let re=String(ee);if(re.length>100&&(re=`${re.slice(0,97)}...`),re=re.replace(/\n/g," "),m.info(`📄 Tool result: ${re}`),this.useServerManager&&this.serverManager){const Se=this.serverManager.tools,Me=new Set(Se.map(en=>en.name)),xn=new Set(this._tools.map(en=>en.name));if(Me.size!==xn.size||[...Me].some(en=>!xn.has(en))){m.info(`🔄 Tools changed during execution. New tools: ${[...Me].join(", ")}`),this._tools=Se,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),w=!0,b++,m.info(`🔃 Restarting execution with updated tools (restart ${b}/${_})`);break}}}this._isAIMessageLike(j)&&!this._messageHasToolCalls(j)&&(g=this._normalizeOutput(this._getMessageContent(j)),m.info("✅ Agent finished with output"))}if(w)break}if(w)break}if(!w)break;if(b>_){m.warn(`⚠️ Max restarts (${_}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const M=k.slice(C.length);for(const w of M)this.addToHistory(w)}if(u&&g)try{m.info("🔧 Attempting structured output...");const M=await this._attemptStructuredOutput(g,this.llm,u);return this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(M)}`)),m.info("✅ Structured output successful"),f=!0,M}catch(M){throw m.error(`❌ Structured output failed: ${M}`),new Error(`Failed to generate structured output: ${M instanceof Error?M.message:String(M)}`)}return m.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,g||"No output generated"}catch(S){throw m.error(`❌ Error running query: ${S}`),h&&l&&(m.info("🧹 Cleaning up resources after error"),await this.close()),S}finally{const S=Date.now()-d;let C=0;this.client?C=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(C=this.connectors.length);const y=this.memoryEnabled?this.conversationHistory.length:0,_=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:i,success:f,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:C,serverIdentifiers:this.connectors.map(b=>b.publicIdentifier),totalToolsAvailable:_.length,toolsAvailableNames:_.map(b=>b.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:l??!0,externalHistoryUsed:c!==void 0,stepsTaken:p,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||"",executionTimeMs:S,errorType:f?null:"execution_error",conversationHistoryLength:y}),l&&!this.client&&h&&(m.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(m.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}m.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(m.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(m.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)m.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(m.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new gt)}finally{this._initialized=!1,m.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Ut(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-DWRfr5cj.js");return{prettyStreamEvents:l}},__vite__mapDeps([3,1,2])),a="";for await(const l of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o){const i=er(e,n,r,s,o);let{query:a}=i;const{maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:h}=i;let d=!1;const f=Date.now();let g=!1,p=0,S=0,C="";h&&(a=this._enhanceQueryWithSchema(a,h));try{c&&!this._initialized?(await this.initialize(),d=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),d=!0);const y=this._agentExecutor;if(!y)throw new Error("MCP agent failed to initialize");this.maxSteps=l??this.maxSteps;const _=typeof a=="string"&&a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:typeof a=="string"?a.replace(/\n/g," "):String(a);m.info(`💬 Received query for streamEvents: '${_}'`),this.memoryEnabled&&(m.info(`🔄 Adding user message to history: ${_}`),this.addToHistory(new pe({content:a})));const b=u??this.conversationHistory,k=[];for(const v of b)this._isHumanMessageLike(v)||this._isAIMessageLike(v)||this._isToolMessageLike(v)?k.push(v):m.info(`⚠️ Skipped message of type: ${v.constructor?.name||typeof v}`);const M=[...k,new pe(a)];m.info("callbacks",this.callbacks);const w=y.streamEvents({messages:M},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const v of w)if(p++,!(!v||typeof v!="object")){if(v.event==="on_chat_model_stream"&&v.data?.chunk?.content&&(S+=v.data.chunk.content.length),v.event==="on_chat_model_stream"&&v.data?.chunk){const T=v.data.chunk;if(T.content){C||(C="");const x=this._normalizeOutput(T.content);C+=x,m.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield v,v.event==="on_chain_end"&&v.data?.output&&!C){const T=v.data.output;Array.isArray(T)&&T.length>0&&T[0]?.text?C=T[0].text:typeof T=="string"?C=T:T&&typeof T=="object"&&"output"in T&&(C=T.output)}}if(h&&C){m.info("🔧 Attempting structured output conversion...");try{let v=!1,T=null,x=null;this._attemptStructuredOutput(C,this.llm,h).then(I=>(v=!0,T=I,I)).catch(I=>{throw v=!0,x=I,I});let A=0;for(;!v;)await new Promise(I=>setTimeout(I,2e3)),v||(A++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${A*2}s)`,elapsed:A*2}});if(x)throw x;T&&(yield{event:"on_structured_output",data:{output:T}},this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(T)}`)),m.info("✅ Structured output successful"))}catch(v){m.warn(`⚠️ Structured output failed: ${v}`),yield{event:"on_structured_output_error",data:{error:v instanceof Error?v.message:String(v)}}}}else this.memoryEnabled&&C&&this.addToHistory(new O(C));console.log(`
|
|
377
|
+
`;function er(t,e,n,r,s){if(typeof t=="object"&&t!==null){const o=t;return{query:o.prompt,maxSteps:o.maxSteps,manageConnector:o.manageConnector,externalHistory:o.externalHistory,outputSchema:o.schema}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s}}N(er,"normalizeRunOptions");var Ft,ug=(Ft=class{static getPackageVersion(){return zl()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new qm({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new gt,this.telemetry=Pr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Zo({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(typeof e.llm=="string"){if(this.isSimplifiedMode=!0,this.llmString=e.llm,this.llmConfig=e.llmConfig,this.mcpServersConfig=e.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw new Error("Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }");this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],m.info(`🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw new Error("Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.");if(this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.isSimplifiedMode)this.adapter=e.adapter??new gt(this.disallowedTools),this.telemetry=Pr.getInstance(),this.modelProvider="unknown",this.modelName="unknown";else{if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new gt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Xo(this.client,this.adapter)}else this.adapter=e.adapter??new gt(this.disallowedTools);if(this.telemetry=Pr.getInstance(),this.llm){const[r,s]=uo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Zo({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:N(()=>this.getMetadata(),"metadataProvider"),tagsProvider:N(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:N(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:N(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:N(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(m.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(m.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){m.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await Ut(async()=>{const{MCPClient:s}=await import("./client-CBVDiOq1.js");return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),m.info("✅ MCPClient created successfully")}if(this.llmString){m.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await Ol(this.llmString,this.llmConfig),m.info("✅ LLM created successfully");const[r,s]=uo(this.llm);this.modelProvider=r,this.modelName=s}catch(r){throw new Error(`Failed to create LLM from string '${this.llmString}': ${r?.message||r}`)}}if(this.useServerManager){if(!this.client)throw new Error("'client' must be available when 'useServerManager' is true.");this.serverManager=new Xo(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&m.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),m.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),m.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(m.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),m.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),m.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else{const s=await this.adapter.createToolsFromConnectors(Object.values(this.sessions).map(a=>a.connector)),o=await this.adapter.createResourcesFromConnectors(Object.values(this.sessions).map(a=>a.connector)),i=await this.adapter.createPromptsFromConnectors(Object.values(this.sessions).map(a=>a.connector));this._tools=[...s,...o,...i],m.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{m.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),m.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}m.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),m.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),m.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Xm;this.systemMessage=$l(e,n,Zm,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof _e))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(o=>o.name);m.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Ml({runLimit:this.maxSteps})],s=yl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return m.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new _e(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof _e)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),m.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new gt(this.disallowedTools),this._initialized&&m.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},m.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],m.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){m.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(m.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){m.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else m.warn(`Unsupported metadata value type for key '${o}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){m.warn(`Failed to get config for server '${s}': ${o}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){m.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof O)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof pe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof O||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,o){const{query:i,maxSteps:a,manageConnector:l,externalHistory:c,outputSchema:u}=er(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(i,a,l,c,u);const h=this.stream(i,a,l,c,u);return this._consumeAndReturn(h)}async*stream(e,n,r=!0,s,o){const{query:i,maxSteps:a,manageConnector:l,externalHistory:c,outputSchema:u}=er(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(i,a,l,c,u);let h=!1;const d=Date.now();let f=!1,g=null,p=0;try{if(l&&!this._initialized?(await this.initialize(),h=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),h=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const M=this.serverManager.tools,w=new Set(M.map(T=>T.name)),v=new Set(this._tools.map(T=>T.name));(w.size!==v.size||[...w].some(T=>!v.has(T)))&&(m.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...w].join(", ")}`),this._tools=M,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const S=c??this.conversationHistory,C=[];for(const M of S)(this._isHumanMessageLike(M)||this._isAIMessageLike(M)||this._isToolMessageLike(M))&&C.push(M);const y=i.length>50?`${i.slice(0,50).replace(/\n/g," ")}...`:i.replace(/\n/g," ");m.info(`💬 Received query: '${y}'`),m.info("🏁 Starting agent execution");const _=3;let b=0;const k=[...C,new pe(i)];for(;b<=_;){const M={messages:k};let w=!1;const v=await this._agentExecutor.stream(M,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const T of v){for(const[x,A]of Object.entries(T))if(m.debug(`📦 Node '${x}' output: ${JSON.stringify(A)}`),A&&typeof A=="object"&&"messages"in A){let I=A.messages;Array.isArray(I)||(I=[I]);for(const j of I)k.includes(j)||k.push(j);for(const j of I){if("tool_calls"in j&&Array.isArray(j.tool_calls)&&j.tool_calls.length>0)for(const ee of j.tool_calls){const re=ee.name||"unknown",Se=ee.args||{};this.toolsUsedNames.push(re),p++;let Me=JSON.stringify(Se);Me.length>100&&(Me=`${Me.slice(0,97)}...`),m.info(`🔧 Tool call: ${re} with input: ${Me}`),yield{action:{tool:re,toolInput:Se,log:`Calling tool ${re}`},observation:""}}if(this._isToolMessageLike(j)){const ee=j.content;let re=String(ee);if(re.length>100&&(re=`${re.slice(0,97)}...`),re=re.replace(/\n/g," "),m.info(`📄 Tool result: ${re}`),this.useServerManager&&this.serverManager){const Se=this.serverManager.tools,Me=new Set(Se.map(en=>en.name)),xn=new Set(this._tools.map(en=>en.name));if(Me.size!==xn.size||[...Me].some(en=>!xn.has(en))){m.info(`🔄 Tools changed during execution. New tools: ${[...Me].join(", ")}`),this._tools=Se,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),w=!0,b++,m.info(`🔃 Restarting execution with updated tools (restart ${b}/${_})`);break}}}this._isAIMessageLike(j)&&!this._messageHasToolCalls(j)&&(g=this._normalizeOutput(this._getMessageContent(j)),m.info("✅ Agent finished with output"))}if(w)break}if(w)break}if(!w)break;if(b>_){m.warn(`⚠️ Max restarts (${_}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const M=k.slice(C.length);for(const w of M)this.addToHistory(w)}if(u&&g)try{m.info("🔧 Attempting structured output...");const M=await this._attemptStructuredOutput(g,this.llm,u);return this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(M)}`)),m.info("✅ Structured output successful"),f=!0,M}catch(M){throw m.error(`❌ Structured output failed: ${M}`),new Error(`Failed to generate structured output: ${M instanceof Error?M.message:String(M)}`)}return m.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,g||"No output generated"}catch(S){throw m.error(`❌ Error running query: ${S}`),h&&l&&(m.info("🧹 Cleaning up resources after error"),await this.close()),S}finally{const S=Date.now()-d;let C=0;this.client?C=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(C=this.connectors.length);const y=this.memoryEnabled?this.conversationHistory.length:0,_=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:i,success:f,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:C,serverIdentifiers:this.connectors.map(b=>b.publicIdentifier),totalToolsAvailable:_.length,toolsAvailableNames:_.map(b=>b.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:l??!0,externalHistoryUsed:c!==void 0,stepsTaken:p,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||"",executionTimeMs:S,errorType:f?null:"execution_error",conversationHistoryLength:y}),l&&!this.client&&h&&(m.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(m.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}m.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(m.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(m.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)m.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(m.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new gt)}finally{this._initialized=!1,m.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Ut(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-DUaOR-3m.js");return{prettyStreamEvents:l}},__vite__mapDeps([3,1,2])),a="";for await(const l of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o){const i=er(e,n,r,s,o);let{query:a}=i;const{maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:h}=i;let d=!1;const f=Date.now();let g=!1,p=0,S=0,C="";h&&(a=this._enhanceQueryWithSchema(a,h));try{c&&!this._initialized?(await this.initialize(),d=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),d=!0);const y=this._agentExecutor;if(!y)throw new Error("MCP agent failed to initialize");this.maxSteps=l??this.maxSteps;const _=typeof a=="string"&&a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:typeof a=="string"?a.replace(/\n/g," "):String(a);m.info(`💬 Received query for streamEvents: '${_}'`),this.memoryEnabled&&(m.info(`🔄 Adding user message to history: ${_}`),this.addToHistory(new pe({content:a})));const b=u??this.conversationHistory,k=[];for(const v of b)this._isHumanMessageLike(v)||this._isAIMessageLike(v)||this._isToolMessageLike(v)?k.push(v):m.info(`⚠️ Skipped message of type: ${v.constructor?.name||typeof v}`);const M=[...k,new pe(a)];m.info("callbacks",this.callbacks);const w=y.streamEvents({messages:M},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const v of w)if(p++,!(!v||typeof v!="object")){if(v.event==="on_chat_model_stream"&&v.data?.chunk?.content&&(S+=v.data.chunk.content.length),v.event==="on_chat_model_stream"&&v.data?.chunk){const T=v.data.chunk;if(T.content){C||(C="");const x=this._normalizeOutput(T.content);C+=x,m.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield v,v.event==="on_chain_end"&&v.data?.output&&!C){const T=v.data.output;Array.isArray(T)&&T.length>0&&T[0]?.text?C=T[0].text:typeof T=="string"?C=T:T&&typeof T=="object"&&"output"in T&&(C=T.output)}}if(h&&C){m.info("🔧 Attempting structured output conversion...");try{let v=!1,T=null,x=null;this._attemptStructuredOutput(C,this.llm,h).then(I=>(v=!0,T=I,I)).catch(I=>{throw v=!0,x=I,I});let A=0;for(;!v;)await new Promise(I=>setTimeout(I,2e3)),v||(A++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${A*2}s)`,elapsed:A*2}});if(x)throw x;T&&(yield{event:"on_structured_output",data:{output:T}},this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(T)}`)),m.info("✅ Structured output successful"))}catch(v){m.warn(`⚠️ Structured output failed: ${v}`),yield{event:"on_structured_output_error",data:{error:v instanceof Error?v.message:String(v)}}}}else this.memoryEnabled&&C&&this.addToHistory(new O(C));console.log(`
|
|
378
378
|
|
|
379
379
|
`),m.info(`🎉 StreamEvents complete - ${p} events emitted`),g=!0}catch(y){throw m.error(`❌ Error during streamEvents: ${y}`),d&&c&&(m.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),y}finally{const y=Date.now()-f;let _=0;this.client?_=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(_=this.connectors.length);const b=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:a,success:g,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:_,serverIdentifiers:this.connectors.map(k=>k.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(k=>k.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:l??null,manageConnector:c??!0,externalHistoryUsed:u!==void 0,response:`[STREAMED RESPONSE - ${S} chars]`,executionTimeMs:y,errorType:g?null:"streaming_error",conversationHistoryLength:b}),c&&!this.client&&d&&(m.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){m.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),m.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,o="";if(m.debug(`🔄 Structured output requested, schema: ${JSON.stringify($n(r),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")s=n.withStructuredOutput(r);else if(n)s=n;else throw new Error("LLM is required for structured output");const i=$n(r),{$schema:a,additionalProperties:l,...c}=i;o=JSON.stringify(c,null,2),m.info(`🔄 Schema description: ${o}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),m.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){m.info(`🔄 Structured output attempt ${f}/${h}`);let g=`
|
|
380
380
|
Please format the following information according to the EXACT schema specified below.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{B as me,_ as v,g as Y,c as We,J as ze,d as Ge,e as _e,T as Ye,l as m,M as Xe,H as Ze,a as Qe,C as et,f as re,h as tt}from"./index-Bi42MNIH.js";var O,nt=(O=class extends me{mcpClient;_tools;constructor(e){super(),this.mcpClient=e,this.connected=!0,this._tools=this._createToolsList()}async connect(){this.connected=!0}async disconnect(){this.connected=!1}get publicIdentifier(){return{name:"code_mode",version:"1.0.0"}}_createToolsList(){return[{name:"execute_code",description:"Execute JavaScript/TypeScript code with access to MCP tools. This is the PRIMARY way to interact with MCP servers in code mode. Write code that discovers tools using search_tools(), calls tools as async functions (e.g., await github.get_pull_request(...)), processes data efficiently, and returns results. Use 'await' for async operations and 'return' to return values. Available in code: search_tools(), __tool_namespaces, and server.tool_name() functions.",inputSchema:{type:"object",properties:{code:{type:"string",description:"JavaScript/TypeScript code to execute. Use 'await' for async operations. Use 'return' to return a value. Available: search_tools(), server.tool_name(), __tool_namespaces"},timeout:{type:"number",description:"Execution timeout in milliseconds",default:3e4}},required:["code"]}},{name:"search_tools",description:"Search and discover available MCP tools across all servers. Use this to find out what tools are available before writing code. Returns tool information including names, descriptions, and schemas. Can filter by query and control detail level.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query to filter tools by name or description",default:""},detail_level:{type:"string",description:"Detail level: 'names', 'descriptions', or 'full'",enum:["names","descriptions","full"],default:"full"}}}}]}get tools(){return this._tools}async initialize(){return this.toolsCache=this._tools,{capabilities:{},version:"1.0.0"}}async callTool(e,t){if(e==="execute_code"){const n=t.code,r=t.timeout||3e4,o=await this.mcpClient.executeCode(n,r);return{content:[{type:"text",text:JSON.stringify(o)}]}}else if(e==="search_tools"){const n=t.query||"",r=t.detail_level,o=await this.mcpClient.searchTools(n,r&&r in["names","descriptions","full"]?r:"full");return{content:[{type:"text",text:JSON.stringify(o)}]}}throw new Error(`Unknown tool: ${e}`)}},v(O,"CodeModeConnector"),O);function X(){throw new Error("fs.readFileSync is not available in browser environment")}function we(){throw new Error("fs.writeFileSync is not available in browser environment")}function ve(){return!1}function ge(){throw new Error("fs.readFile is not available in browser environment")}function ye(){throw new Error("fs.writeFile is not available in browser environment")}function be(){throw new Error("fs.mkdir is not available in browser environment")}function xe(){throw new Error("fs.readdir is not available in browser environment")}function Ce(){throw new Error("fs.stat is not available in browser environment")}function Se(){throw new Error("fs.unlink is not available in browser environment")}function Ee(){throw new Error("fs.rmdir is not available in browser environment")}const L={readFileSync:X,writeFileSync:we,existsSync:ve,readFile:ge,writeFile:ye,mkdir:be,readdir:xe,stat:Ce,unlink:Se,rmdir:Ee},rt=Object.freeze(Object.defineProperty({__proto__:null,default:L,existsSync:ve,mkdir:be,readFile:ge,readFileSync:X,readdir:xe,rmdir:Ee,stat:Ce,unlink:Se,writeFile:ye,writeFileSync:we},Symbol.toStringTag,{value:"Module"}));function Z(...s){return s.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/$/,"")}function Me(...s){return Z(...s)}function Q(s){const e=s.split("/");return e.pop(),e.join("/")||"/"}function q(s,e){const t=s.split("/");let n=t[t.length-1]||"";return e&&n.endsWith(e)&&(n=n.slice(0,-e.length)),n}function ee(s){const e=q(s),t=e.lastIndexOf(".");return t>0?e.slice(t):""}function Te(s){return s.replace(/\/+/g,"/")}function Pe(s){return s.startsWith("/")}function Oe(s){const e=s.startsWith("/")?"/":"",t=Q(s),n=q(s),r=ee(s),o=r?n.slice(0,-r.length):n;return{root:e,dir:t,base:n,ext:r,name:o}}const Ne="/",ke=":",$e={join:Z,resolve:Me,dirname:Q,basename:q,extname:ee,normalize:Te,isAbsolute:Pe,parse:Oe,sep:Ne,delimiter:ke},ot=Object.freeze(Object.defineProperty({__proto__:null,basename:q,default:$e,delimiter:ke,dirname:Q,extname:ee,isAbsolute:Pe,join:Z,normalize:Te,parse:Oe,resolve:Me,sep:Ne},Symbol.toStringTag,{value:"Module"})),st={},it="browser",ct="v18.0.0",at={node:"18.0.0"},lt=()=>"/",ut=(s,...e)=>queueMicrotask(()=>s(...e)),dt=!0,j={env:st,platform:it,version:ct,versions:at,cwd:lt,nextTick:ut,browser:dt};var T={exports:{}};function Ae(){throw new Error("child_process.spawn is not available in browser environment")}function Ie(){throw new Error("child_process.exec is not available in browser environment")}function Re(){throw new Error("child_process.execFile is not available in browser environment")}function Le(){throw new Error("child_process.fork is not available in browser environment")}function je(){throw new Error("child_process.execSync is not available in browser environment")}function qe(){throw new Error("child_process.spawnSync is not available in browser environment")}function Fe(){throw new Error("child_process.execFileSync is not available in browser environment")}const ht={spawn:Ae,exec:Ie,execFile:Re,fork:Le,execSync:je,spawnSync:qe,execFileSync:Fe},ft=Object.freeze(Object.defineProperty({__proto__:null,default:ht,exec:Ie,execFile:Re,execFileSync:Fe,execSync:je,fork:Le,spawn:Ae,spawnSync:qe},Symbol.toStringTag,{value:"Module"})),pt=Y(ft),Be=Y(ot),De=Y(rt);var D,oe;function mt(){if(oe)return D;oe=1;var s={};D=r,r.sync=o;var e=De;function t(i,a){var l=a.pathExt!==void 0?a.pathExt:s.PATHEXT;if(!l||(l=l.split(";"),l.indexOf("")!==-1))return!0;for(var c=0;c<l.length;c++){var u=l[c].toLowerCase();if(u&&i.substr(-u.length).toLowerCase()===u)return!0}return!1}function n(i,a,l){return!i.isSymbolicLink()&&!i.isFile()?!1:t(a,l)}function r(i,a,l){e.stat(i,function(c,u){l(c,c?!1:n(u,i,a))})}function o(i,a){return n(e.statSync(i),i,a)}return D}var J,se;function _t(){if(se)return J;se=1,J=e,e.sync=t;var s=De;function e(o,i,a){s.stat(o,function(l,c){a(l,l?!1:n(c,i))})}function t(o,i){return n(s.statSync(o),i)}function n(o,i){return o.isFile()&&r(o,i)}function r(o,i){var a=o.mode,l=o.uid,c=o.gid,u=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),d=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),h=parseInt("100",8),f=parseInt("010",8),p=parseInt("001",8),y=h|f,_=a&p||a&f&&c===d||a&h&&l===u||a&y&&u===0;return _}return J}var U,ie;function wt(){if(ie)return U;ie=1;var s;globalThis.TESTING_WINDOWS?s=mt():s=_t(),U=e,e.sync=t;function e(n,r,o){if(typeof r=="function"&&(o=r,r={}),!o){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(i,a){e(n,r||{},function(l,c){l?a(l):i(c)})})}s(n,r||{},function(i,a){i&&(i.code==="EACCES"||r&&r.ignoreErrors)&&(i=null,a=!1),o(i,a)})}function t(n,r){try{return s.sync(n,r||{})}catch(o){if(r&&r.ignoreErrors||o.code==="EACCES")return!1;throw o}}return U}var V,ce;function vt(){if(ce)return V;ce=1;var s={};const e=s.OSTYPE==="cygwin"||s.OSTYPE==="msys",t=Be,n=e?";":":",r=wt(),o=c=>Object.assign(new Error(`not found: ${c}`),{code:"ENOENT"}),i=(c,u)=>{const d=u.colon||n,h=c.match(/\//)||e&&c.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(u.path||s.PATH||"").split(d)],f=e?u.pathExt||s.PATHEXT||".EXE;.CMD;.BAT;.COM":"",p=e?f.split(d):[""];return e&&c.indexOf(".")!==-1&&p[0]!==""&&p.unshift(""),{pathEnv:h,pathExt:p,pathExtExe:f}},a=(c,u,d)=>{typeof u=="function"&&(d=u,u={}),u||(u={});const{pathEnv:h,pathExt:f,pathExtExe:p}=i(c,u),y=[],_=w=>new Promise((b,g)=>{if(w===h.length)return u.all&&y.length?b(y):g(o(c));const x=h[w],S=/^".*"$/.test(x)?x.slice(1,-1):x,P=t.join(S,c),B=!S&&/^\.[\\\/]/.test(c)?c.slice(0,2)+P:P;b(C(B,w,0))}),C=(w,b,g)=>new Promise((x,S)=>{if(g===f.length)return x(_(b+1));const P=f[g];r(w+P,{pathExt:p},(B,Ke)=>{if(!B&&Ke)if(u.all)y.push(w+P);else return x(w+P);return x(C(w,b,g+1))})});return d?_(0).then(w=>d(null,w),d):_(0)},l=(c,u)=>{u=u||{};const{pathEnv:d,pathExt:h,pathExtExe:f}=i(c,u),p=[];for(let y=0;y<d.length;y++){const _=d[y],C=/^".*"$/.test(_)?_.slice(1,-1):_,w=t.join(C,c),b=!C&&/^\.[\\\/]/.test(c)?c.slice(0,2)+w:w;for(let g=0;g<h.length;g++){const x=b+h[g];try{if(r.sync(x,{pathExt:f}))if(u.all)p.push(x);else return x}catch{}}}if(u.all&&p.length)return p;if(u.nothrow)return null;throw o(c)};return V=a,a.sync=l,V}var R={exports:{}},ae;function gt(){if(ae)return R.exports;ae=1;var s={};const e=(t={})=>{const n=t.env||s;return(t.platform||"browser")!=="win32"?"PATH":Object.keys(n).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};return R.exports=e,R.exports.default=e,R.exports}var H,le;function yt(){if(le)return H;le=1;var s={};const e=Be,t=vt(),n=gt();function r(i,a){const l=i.options.env||s,c=process.cwd(),u=i.options.cwd!=null,d=u&&process.chdir!==void 0&&!process.chdir.disabled;if(d)try{process.chdir(i.options.cwd)}catch{}let h;try{h=t.sync(i.command,{path:l[n({env:l})],pathExt:a?e.delimiter:void 0})}catch{}finally{d&&process.chdir(c)}return h&&(h=e.resolve(u?i.options.cwd:"",h)),h}function o(i){return r(i)||r(i,!0)}return H=o,H}var K,ue;function bt(){if(ue)return K;ue=1,yt();function s(t){return t}function e(t,n,r){n&&!Array.isArray(n)&&(r=n,n=null),n=n?n.slice(0):[],r=Object.assign({},r);const o={command:t,args:n,options:r,file:void 0,original:{command:t,args:n}};return r.shell?o:o}return K=e,K}var W,de;function xt(){if(de)return W;de=1;function s(r,o){return Object.assign(new Error(`${o} ${r.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${o} ${r.command}`,path:r.command,spawnargs:r.args})}function e(r,o){}function t(r,o){return null}function n(r,o){return null}return W={hookChildProcess:e,verifyENOENT:t,verifyENOENTSync:n,notFoundError:s},W}var he;function Ct(){if(he)return T.exports;he=1;const s=pt,e=bt(),t=xt();function n(o,i,a){const l=e(o,i,a),c=s.spawn(l.command,l.args,l.options);return t.hookChildProcess(c,l),c}function r(o,i,a){const l=e(o,i,a),c=s.spawnSync(l.command,l.args,l.options);return c.error=c.error||t.verifyENOENTSync(c.status,l),c}return T.exports=n,T.exports.spawn=n,T.exports.sync=r,T.exports._parse=e,T.exports._enoent=t,T.exports}var St=Ct();const Et=We(St);class Mt{constructor(){console.warn("PassThrough stream is not available in browser environment")}}class Tt{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf(`
|
|
1
|
+
import{B as me,_ as v,g as Y,c as We,J as ze,d as Ge,e as _e,T as Ye,l as m,M as Xe,H as Ze,a as Qe,C as et,f as re,h as tt}from"./index-CqlJu5dO.js";var O,nt=(O=class extends me{mcpClient;_tools;constructor(e){super(),this.mcpClient=e,this.connected=!0,this._tools=this._createToolsList()}async connect(){this.connected=!0}async disconnect(){this.connected=!1}get publicIdentifier(){return{name:"code_mode",version:"1.0.0"}}_createToolsList(){return[{name:"execute_code",description:"Execute JavaScript/TypeScript code with access to MCP tools. This is the PRIMARY way to interact with MCP servers in code mode. Write code that discovers tools using search_tools(), calls tools as async functions (e.g., await github.get_pull_request(...)), processes data efficiently, and returns results. Use 'await' for async operations and 'return' to return values. Available in code: search_tools(), __tool_namespaces, and server.tool_name() functions.",inputSchema:{type:"object",properties:{code:{type:"string",description:"JavaScript/TypeScript code to execute. Use 'await' for async operations. Use 'return' to return a value. Available: search_tools(), server.tool_name(), __tool_namespaces"},timeout:{type:"number",description:"Execution timeout in milliseconds",default:3e4}},required:["code"]}},{name:"search_tools",description:"Search and discover available MCP tools across all servers. Use this to find out what tools are available before writing code. Returns tool information including names, descriptions, and schemas. Can filter by query and control detail level.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query to filter tools by name or description",default:""},detail_level:{type:"string",description:"Detail level: 'names', 'descriptions', or 'full'",enum:["names","descriptions","full"],default:"full"}}}}]}get tools(){return this._tools}async initialize(){return this.toolsCache=this._tools,{capabilities:{},version:"1.0.0"}}async callTool(e,t){if(e==="execute_code"){const n=t.code,r=t.timeout||3e4,o=await this.mcpClient.executeCode(n,r);return{content:[{type:"text",text:JSON.stringify(o)}]}}else if(e==="search_tools"){const n=t.query||"",r=t.detail_level,o=await this.mcpClient.searchTools(n,r&&r in["names","descriptions","full"]?r:"full");return{content:[{type:"text",text:JSON.stringify(o)}]}}throw new Error(`Unknown tool: ${e}`)}},v(O,"CodeModeConnector"),O);function X(){throw new Error("fs.readFileSync is not available in browser environment")}function we(){throw new Error("fs.writeFileSync is not available in browser environment")}function ve(){return!1}function ge(){throw new Error("fs.readFile is not available in browser environment")}function ye(){throw new Error("fs.writeFile is not available in browser environment")}function be(){throw new Error("fs.mkdir is not available in browser environment")}function xe(){throw new Error("fs.readdir is not available in browser environment")}function Ce(){throw new Error("fs.stat is not available in browser environment")}function Se(){throw new Error("fs.unlink is not available in browser environment")}function Ee(){throw new Error("fs.rmdir is not available in browser environment")}const L={readFileSync:X,writeFileSync:we,existsSync:ve,readFile:ge,writeFile:ye,mkdir:be,readdir:xe,stat:Ce,unlink:Se,rmdir:Ee},rt=Object.freeze(Object.defineProperty({__proto__:null,default:L,existsSync:ve,mkdir:be,readFile:ge,readFileSync:X,readdir:xe,rmdir:Ee,stat:Ce,unlink:Se,writeFile:ye,writeFileSync:we},Symbol.toStringTag,{value:"Module"}));function Z(...s){return s.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/$/,"")}function Me(...s){return Z(...s)}function Q(s){const e=s.split("/");return e.pop(),e.join("/")||"/"}function q(s,e){const t=s.split("/");let n=t[t.length-1]||"";return e&&n.endsWith(e)&&(n=n.slice(0,-e.length)),n}function ee(s){const e=q(s),t=e.lastIndexOf(".");return t>0?e.slice(t):""}function Te(s){return s.replace(/\/+/g,"/")}function Pe(s){return s.startsWith("/")}function Oe(s){const e=s.startsWith("/")?"/":"",t=Q(s),n=q(s),r=ee(s),o=r?n.slice(0,-r.length):n;return{root:e,dir:t,base:n,ext:r,name:o}}const Ne="/",ke=":",$e={join:Z,resolve:Me,dirname:Q,basename:q,extname:ee,normalize:Te,isAbsolute:Pe,parse:Oe,sep:Ne,delimiter:ke},ot=Object.freeze(Object.defineProperty({__proto__:null,basename:q,default:$e,delimiter:ke,dirname:Q,extname:ee,isAbsolute:Pe,join:Z,normalize:Te,parse:Oe,resolve:Me,sep:Ne},Symbol.toStringTag,{value:"Module"})),st={},it="browser",ct="v18.0.0",at={node:"18.0.0"},lt=()=>"/",ut=(s,...e)=>queueMicrotask(()=>s(...e)),dt=!0,j={env:st,platform:it,version:ct,versions:at,cwd:lt,nextTick:ut,browser:dt};var T={exports:{}};function Ae(){throw new Error("child_process.spawn is not available in browser environment")}function Ie(){throw new Error("child_process.exec is not available in browser environment")}function Re(){throw new Error("child_process.execFile is not available in browser environment")}function Le(){throw new Error("child_process.fork is not available in browser environment")}function je(){throw new Error("child_process.execSync is not available in browser environment")}function qe(){throw new Error("child_process.spawnSync is not available in browser environment")}function Fe(){throw new Error("child_process.execFileSync is not available in browser environment")}const ht={spawn:Ae,exec:Ie,execFile:Re,fork:Le,execSync:je,spawnSync:qe,execFileSync:Fe},ft=Object.freeze(Object.defineProperty({__proto__:null,default:ht,exec:Ie,execFile:Re,execFileSync:Fe,execSync:je,fork:Le,spawn:Ae,spawnSync:qe},Symbol.toStringTag,{value:"Module"})),pt=Y(ft),Be=Y(ot),De=Y(rt);var D,oe;function mt(){if(oe)return D;oe=1;var s={};D=r,r.sync=o;var e=De;function t(i,a){var l=a.pathExt!==void 0?a.pathExt:s.PATHEXT;if(!l||(l=l.split(";"),l.indexOf("")!==-1))return!0;for(var c=0;c<l.length;c++){var u=l[c].toLowerCase();if(u&&i.substr(-u.length).toLowerCase()===u)return!0}return!1}function n(i,a,l){return!i.isSymbolicLink()&&!i.isFile()?!1:t(a,l)}function r(i,a,l){e.stat(i,function(c,u){l(c,c?!1:n(u,i,a))})}function o(i,a){return n(e.statSync(i),i,a)}return D}var J,se;function _t(){if(se)return J;se=1,J=e,e.sync=t;var s=De;function e(o,i,a){s.stat(o,function(l,c){a(l,l?!1:n(c,i))})}function t(o,i){return n(s.statSync(o),i)}function n(o,i){return o.isFile()&&r(o,i)}function r(o,i){var a=o.mode,l=o.uid,c=o.gid,u=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),d=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),h=parseInt("100",8),f=parseInt("010",8),p=parseInt("001",8),y=h|f,_=a&p||a&f&&c===d||a&h&&l===u||a&y&&u===0;return _}return J}var U,ie;function wt(){if(ie)return U;ie=1;var s;globalThis.TESTING_WINDOWS?s=mt():s=_t(),U=e,e.sync=t;function e(n,r,o){if(typeof r=="function"&&(o=r,r={}),!o){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(i,a){e(n,r||{},function(l,c){l?a(l):i(c)})})}s(n,r||{},function(i,a){i&&(i.code==="EACCES"||r&&r.ignoreErrors)&&(i=null,a=!1),o(i,a)})}function t(n,r){try{return s.sync(n,r||{})}catch(o){if(r&&r.ignoreErrors||o.code==="EACCES")return!1;throw o}}return U}var V,ce;function vt(){if(ce)return V;ce=1;var s={};const e=s.OSTYPE==="cygwin"||s.OSTYPE==="msys",t=Be,n=e?";":":",r=wt(),o=c=>Object.assign(new Error(`not found: ${c}`),{code:"ENOENT"}),i=(c,u)=>{const d=u.colon||n,h=c.match(/\//)||e&&c.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(u.path||s.PATH||"").split(d)],f=e?u.pathExt||s.PATHEXT||".EXE;.CMD;.BAT;.COM":"",p=e?f.split(d):[""];return e&&c.indexOf(".")!==-1&&p[0]!==""&&p.unshift(""),{pathEnv:h,pathExt:p,pathExtExe:f}},a=(c,u,d)=>{typeof u=="function"&&(d=u,u={}),u||(u={});const{pathEnv:h,pathExt:f,pathExtExe:p}=i(c,u),y=[],_=w=>new Promise((b,g)=>{if(w===h.length)return u.all&&y.length?b(y):g(o(c));const x=h[w],S=/^".*"$/.test(x)?x.slice(1,-1):x,P=t.join(S,c),B=!S&&/^\.[\\\/]/.test(c)?c.slice(0,2)+P:P;b(C(B,w,0))}),C=(w,b,g)=>new Promise((x,S)=>{if(g===f.length)return x(_(b+1));const P=f[g];r(w+P,{pathExt:p},(B,Ke)=>{if(!B&&Ke)if(u.all)y.push(w+P);else return x(w+P);return x(C(w,b,g+1))})});return d?_(0).then(w=>d(null,w),d):_(0)},l=(c,u)=>{u=u||{};const{pathEnv:d,pathExt:h,pathExtExe:f}=i(c,u),p=[];for(let y=0;y<d.length;y++){const _=d[y],C=/^".*"$/.test(_)?_.slice(1,-1):_,w=t.join(C,c),b=!C&&/^\.[\\\/]/.test(c)?c.slice(0,2)+w:w;for(let g=0;g<h.length;g++){const x=b+h[g];try{if(r.sync(x,{pathExt:f}))if(u.all)p.push(x);else return x}catch{}}}if(u.all&&p.length)return p;if(u.nothrow)return null;throw o(c)};return V=a,a.sync=l,V}var R={exports:{}},ae;function gt(){if(ae)return R.exports;ae=1;var s={};const e=(t={})=>{const n=t.env||s;return(t.platform||"browser")!=="win32"?"PATH":Object.keys(n).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};return R.exports=e,R.exports.default=e,R.exports}var H,le;function yt(){if(le)return H;le=1;var s={};const e=Be,t=vt(),n=gt();function r(i,a){const l=i.options.env||s,c=process.cwd(),u=i.options.cwd!=null,d=u&&process.chdir!==void 0&&!process.chdir.disabled;if(d)try{process.chdir(i.options.cwd)}catch{}let h;try{h=t.sync(i.command,{path:l[n({env:l})],pathExt:a?e.delimiter:void 0})}catch{}finally{d&&process.chdir(c)}return h&&(h=e.resolve(u?i.options.cwd:"",h)),h}function o(i){return r(i)||r(i,!0)}return H=o,H}var K,ue;function bt(){if(ue)return K;ue=1,yt();function s(t){return t}function e(t,n,r){n&&!Array.isArray(n)&&(r=n,n=null),n=n?n.slice(0):[],r=Object.assign({},r);const o={command:t,args:n,options:r,file:void 0,original:{command:t,args:n}};return r.shell?o:o}return K=e,K}var W,de;function xt(){if(de)return W;de=1;function s(r,o){return Object.assign(new Error(`${o} ${r.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${o} ${r.command}`,path:r.command,spawnargs:r.args})}function e(r,o){}function t(r,o){return null}function n(r,o){return null}return W={hookChildProcess:e,verifyENOENT:t,verifyENOENTSync:n,notFoundError:s},W}var he;function Ct(){if(he)return T.exports;he=1;const s=pt,e=bt(),t=xt();function n(o,i,a){const l=e(o,i,a),c=s.spawn(l.command,l.args,l.options);return t.hookChildProcess(c,l),c}function r(o,i,a){const l=e(o,i,a),c=s.spawnSync(l.command,l.args,l.options);return c.error=c.error||t.verifyENOENTSync(c.status,l),c}return T.exports=n,T.exports.spawn=n,T.exports.sync=r,T.exports._parse=e,T.exports._enoent=t,T.exports}var St=Ct();const Et=We(St);class Mt{constructor(){console.warn("PassThrough stream is not available in browser environment")}}class Tt{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf(`
|
|
2
2
|
`);if(e===-1)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Pt(t)}clear(){this._buffer=void 0}}function Pt(s){return ze.parse(JSON.parse(s))}function Ot(s){return JSON.stringify(s)+`
|
|
3
3
|
`}const Nt=["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function kt(){const s={};for(const e of Nt){const t=j.env[e];t!==void 0&&(t.startsWith("()")||(s[e]=t))}return s}class $t{constructor(e){this._readBuffer=new Tt,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Mt)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._process=Et(this._serverParams.command,this._serverParams.args??[],{env:{...kt(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:j.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{t(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{const e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){const e=this._process;this._process=void 0;const t=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([t,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw new Error("Not connected");const n=Ot(e);this._process.stdin.write(n)?t():this._process.stdin.once("drain",t)})}}var At={},N,te=(N=class{client;_connecting=!1;constructor(e){this.client=e}async ensureServersConnected(){const e=this.client.getServerNames(),t=Object.keys(this.client.getAllActiveSessions()),n=e.filter(r=>!t.includes(r));if(n.length>0&&!this._connecting){this._connecting=!0;try{m.debug(`Connecting to configured servers for code execution: ${n.join(", ")}`),await this.client.createAllSessions()}finally{this._connecting=!1}}else if(n.length>0&&this._connecting){m.debug("Waiting for ongoing server connection...");const r=Date.now();for(;this._connecting&&Date.now()-r<5e3;)await new Promise(o=>setTimeout(o,100))}}getToolNamespaces(){const e=[],t=this.client.getAllActiveSessions();for(const[n,r]of Object.entries(t))if(n!=="code_mode")try{const o=r.connector;let i;try{i=o.tools}catch(a){m.warn(`Tools not available for server ${n}: ${a}`);continue}if(!i||i.length===0)continue;e.push({serverName:n,tools:i,session:r})}catch(o){m.warn(`Failed to load tools for server ${n}: ${o}`)}return e}createSearchToolsFunction(){return async(e="",t="full")=>{const n=[],r=new Set,o=e.toLowerCase(),i=this.client.getAllActiveSessions();for(const[l,c]of Object.entries(i))if(l!=="code_mode")try{const u=c.connector.tools;u&&u.length>0&&r.add(l);for(const d of u)t==="names"?n.push({name:d.name,server:l}):t==="descriptions"?n.push({name:d.name,server:l,description:d.description}):n.push({name:d.name,server:l,description:d.description,input_schema:d.inputSchema})}catch(u){m.warn(`Failed to search tools in server ${l}: ${u}`)}let a=n;return e&&(a=n.filter(l=>{const c=l.name.toLowerCase().includes(o),u=l.description?.toLowerCase().includes(o),d=l.server.toLowerCase().includes(o);return c||u||d})),{meta:{total_tools:n.length,namespaces:Array.from(r).sort(),result_count:a.length},results:a}}}},v(N,"BaseCodeExecutor"),N),k,fe=(k=class extends te{e2bApiKey;codeExecSandbox=null;SandboxClass=null;timeoutMs;constructor(e,t){super(e),this.e2bApiKey=t.apiKey,this.timeoutMs=t.timeoutMs??3e5}async ensureSandboxClass(){if(!this.SandboxClass)try{const e=await Qe(()=>import("@e2b/code-interpreter"),[]);this.SandboxClass=e.Sandbox}catch{throw new Error("@e2b/code-interpreter is not installed. The E2B code executor requires this optional dependency. Install it with: yarn add @e2b/code-interpreter")}}async getOrCreateCodeExecSandbox(){return this.codeExecSandbox?this.codeExecSandbox:(await this.ensureSandboxClass(),m.debug("Starting E2B sandbox for code execution..."),this.codeExecSandbox=await this.SandboxClass.create("base",{apiKey:this.e2bApiKey,timeoutMs:this.timeoutMs}),this.codeExecSandbox)}generateShim(e){let t=`
|
|
4
4
|
// MCP Bridge Shim
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
2
|
-
import{_ as a,a as k}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-hu1QYxMc.js","assets/index-CqlJu5dO.js","assets/index-G80eS8Oh.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as a,a as k}from"./index-CqlJu5dO.js";var y=null,L=null,O=null,J=!1,V=typeof process<"u"&&process.versions?.node;(async()=>{if(V)try{O=(await k(()=>import("./util-QmrWvrtn.js"),[])).stripVTControlCharacters}catch{}try{y=(await k(()=>import("./index-JiKw9JSs.js"),[])).default}catch{}try{L=(await k(()=>import("./index-hu1QYxMc.js").then(e=>e.i),__vite__mapDeps([0,1,2]))).highlight}catch{}V&&(!y||!L)&&(J||(J=!0,console.warn(`
|
|
3
3
|
✨ For enhanced console output with colors and syntax highlighting, install:
|
|
4
4
|
|
|
5
5
|
npm install chalk cli-highlight
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as c,q as d}from"./index-
|
|
1
|
+
import{g as c,q as d}from"./index-CW3Avs3Z.js";var l={};c(l,{chunkArray:()=>u});const u=(r,s)=>r.reduce((a,n,o)=>{const e=Math.floor(o/s),t=a[e]||[];return a[e]=t.concat([n]),a},[]);var h={};c(h,{Embeddings:()=>i});var i=class{caller;constructor(r){this.caller=new d(r??{})}};export{i as E,l as c,h as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{p as y,e as E,m as x,_ as g,i as P,a as $,b as N,T as f,v as O,C as A,c as I,d as L,f as S,g as J,o as F,s as R,h as M,j as B,k as b,A as C,l as _,n as j}from"./index-
|
|
1
|
+
import{p as y,e as E,m as x,_ as g,i as P,a as $,b as N,T as f,v as O,C as A,c as I,d as L,f as S,g as J,o as F,s as R,h as M,j as B,k as b,A as C,l as _,n as j}from"./index-CW3Avs3Z.js";import{B as Z,i as W,a as H,b as K,c as V}from"./index-BpbjNRUs.js";import{p as q}from"./index-CqlJu5dO.js";var z={};J(z,{BaseToolkit:()=>G,DynamicStructuredTool:()=>k,DynamicTool:()=>D,StructuredTool:()=>T,Tool:()=>w,ToolInputParsingException:()=>f,isLangChainTool:()=>V,isRunnableToolLike:()=>K,isStructuredTool:()=>H,isStructuredToolParams:()=>W,tool:()=>Q});var T=class extends Z{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(t){super(t??{}),this.verboseParsingErrors=t?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=t?.responseFormat??this.responseFormat,this.defaultConfig=t?.defaultConfig??this.defaultConfig,this.metadata=t?.metadata??this.metadata,this.extras=t?.extras??this.extras}async invoke(t,e){let a,s=E(x(this.defaultConfig,e));return g(t)?(a=t.args,s={...s,toolCall:t}):a=t,this.call(a,s)}async call(t,e,a){const s=g(t)?t.args:t;let u;if(P(this.schema))try{u=await $(this.schema,s)}catch(c){let o="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(o=`${o}
|
|
2
2
|
Details: ${c.message}`),N(c)&&(o=`${o}
|
|
3
3
|
|
|
4
4
|
${q(c)}`),new f(o,JSON.stringify(t))}else{const c=O(s,this.schema);if(!c.valid){let o="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(o=`${o}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{N as Ue,O as je,P as J,Q as ae,i as Ae,S as H,y as le,g as U,U as Nt,V as kt,W as xt,X as Pt,Y as Mt,Z as Rt,$ as Ft,a0 as Lt,a1 as Dt,a2 as Bt,h as Ut,a3 as jt,a4 as Vt,a5 as zt,b as Gt,a6 as Zt,a7 as $t,a8 as Ht,a9 as Wt,aa as Jt,r as Xt,ab as Yt,a as $e,ac as Kt,ad as He,ae as qt,af as Qt,ag as ea,ah as Se,ai as ta,aj as aa,ak as sa,q as We,al as re,e as oe,am as Je,an as Xe,x as ce,L as na,C as ye,ao as Ve,w as ra,R as ze,z as X,t as ia,ap as Ie,E as oa,M as Ye,aq as ca,ar as ua,as as la,B as Ke,at as ie,k as G,au as qe,av as ha,aw as Qe,ax as pa,l as ga,m as ma,ay as fa,az as da,aA as ba,aB as ya,aC as _a,aD as Ta,aE as va,aF as Ea,D as Ge,aG as wa,G as Ca,aH as Aa,aI as Sa,aJ as ve,o as et,s as tt,u as Ia}from"./index-DdrkmeYH.js";import{c as Oa}from"./index-Bi42MNIH.js";function at(e,a,n,r,i){if(a!==e){typeof a.toJSON=="function"&&(a=a.toJSON());for(var c=Ue(a),h=Ue(e),l=!1,b=h.length-1;b>=0;b--){var f=h[b],T=e[f];if(je(a,f)&&!(a[f]===void 0&&T!==void 0&&Array.isArray(a)===!1)){var _=a[f];typeof T=="object"&&T!=null&&typeof _=="object"&&_!=null&&Array.isArray(T)===Array.isArray(_)?at(T,_,n,r+"/"+J(f),i):T!==_&&(i&&n.push({op:"test",path:r+"/"+J(f),value:ae(T)}),n.push({op:"replace",path:r+"/"+J(f),value:ae(_)}))}else Array.isArray(e)===Array.isArray(a)?(i&&n.push({op:"test",path:r+"/"+J(f),value:ae(T)}),n.push({op:"remove",path:r+"/"+J(f)}),l=!0):(i&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:a}))}if(!(!l&&c.length==h.length))for(var b=0;b<c.length;b++){var f=c[b];!je(e,f)&&a[f]!==void 0&&n.push({op:"add",path:r+"/"+J(f),value:ae(a[f])})}}}function Oe(e,a,n=!1){var r=[];return at(e,a,r,"",n),r}function st(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function nt(e){return e!==void 0&&H.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function rt(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Ae(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function it(e){return rt(e)||nt(e)||st(e)}var Na={};U(Na,{convertToOpenAIFunction:()=>ot,convertToOpenAITool:()=>ka,isLangChainTool:()=>it,isRunnableToolLike:()=>nt,isStructuredTool:()=>st,isStructuredToolParams:()=>rt});function ot(e,a){const n=typeof a=="number"?void 0:a;return{name:e.name,description:e.description,parameters:le(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function ka(e,a){const n=typeof a=="number"?void 0:a;let r;return it(e)?r={type:"function",function:ot(e)}:r=e,n?.strict!==void 0&&(r.function.strict=n.strict),r}var xa={};U(xa,{extendInteropZodObject:()=>ea,getInteropZodDefaultGetter:()=>Qt,getInteropZodObjectShape:()=>qt,getSchemaDescription:()=>He,interopParse:()=>Kt,interopParseAsync:()=>$e,interopSafeParse:()=>Yt,interopSafeParseAsync:()=>Xt,interopZodObjectMakeFieldsOptional:()=>Jt,interopZodObjectPartial:()=>Wt,interopZodObjectPassthrough:()=>Ht,interopZodObjectStrict:()=>$t,interopZodTransformInputSchema:()=>Zt,isInteropZodError:()=>Gt,isInteropZodLiteral:()=>zt,isInteropZodObject:()=>Vt,isInteropZodSchema:()=>Ae,isShapelessZodSchema:()=>jt,isSimpleStringZodSchema:()=>Ut,isZodArrayV4:()=>Bt,isZodLiteralV3:()=>Dt,isZodLiteralV4:()=>Lt,isZodNullableV4:()=>Ft,isZodObjectV3:()=>Rt,isZodObjectV4:()=>Mt,isZodOptionalV4:()=>Pt,isZodSchema:()=>xt,isZodSchemaV3:()=>kt,isZodSchemaV4:()=>Nt});var Pa={};U(Pa,{BasePromptValue:()=>he,ChatPromptValue:()=>ut,ImagePromptValue:()=>Ma,StringPromptValue:()=>ct});var he=class extends aa{},ct=class extends he{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new Se(this.value)]}},ut=class extends he{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return ta(this.messages)}toChatMessages(){return this.messages}},Ma=class extends he{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Se({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},y="0123456789abcdef".split(""),Ra=[-2147483648,8388608,32768,128],D=[24,16,8,0],se=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],M=[];function B(e,a){a?(M[0]=M[16]=M[1]=M[2]=M[3]=M[4]=M[5]=M[6]=M[7]=M[8]=M[9]=M[10]=M[11]=M[12]=M[13]=M[14]=M[15]=0,this.blocks=M):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}B.prototype.update=function(e){if(!this.finalized){var a,n=typeof e;if(n!=="string"){if(n==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);a=!0}for(var r,i=0,c,h=e.length,l=this.blocks;i<h;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),a)for(c=this.start;i<h&&c<64;++i)l[c>>>2]|=e[i]<<D[c++&3];else for(c=this.start;i<h&&c<64;++i)r=e.charCodeAt(i),r<128?l[c>>>2]|=r<<D[c++&3]:r<2048?(l[c>>>2]|=(192|r>>>6)<<D[c++&3],l[c>>>2]|=(128|r&63)<<D[c++&3]):r<55296||r>=57344?(l[c>>>2]|=(224|r>>>12)<<D[c++&3],l[c>>>2]|=(128|r>>>6&63)<<D[c++&3],l[c>>>2]|=(128|r&63)<<D[c++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),l[c>>>2]|=(240|r>>>18)<<D[c++&3],l[c>>>2]|=(128|r>>>12&63)<<D[c++&3],l[c>>>2]|=(128|r>>>6&63)<<D[c++&3],l[c>>>2]|=(128|r&63)<<D[c++&3]);this.lastByteIndex=c,this.bytes+=c-this.start,c>=64?(this.block=l[16],this.start=c-64,this.hash(),this.hashed=!0):this.start=c}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};B.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,a=this.lastByteIndex;e[16]=this.block,e[a>>>2]|=Ra[a&3],this.block=e[16],a>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};B.prototype.hash=function(){var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,b=this.blocks,f,T,_,E,g,d,m,v,w,A,C;for(f=16;f<64;++f)g=b[f-15],T=(g>>>7|g<<25)^(g>>>18|g<<14)^g>>>3,g=b[f-2],_=(g>>>17|g<<15)^(g>>>19|g<<13)^g>>>10,b[f]=b[f-16]+T+b[f-7]+_<<0;for(C=a&n,f=0;f<64;f+=4)this.first?(this.is224?(v=300032,g=b[0]-1413257819,l=g-150054599<<0,r=g+24177077<<0):(v=704751109,g=b[0]-210244248,l=g-1521486534<<0,r=g+143694565<<0),this.first=!1):(T=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),_=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),v=e&a,E=v^e&n^C,m=i&c^~i&h,g=l+_+m+se[f]+b[f],d=T+E,l=r+g<<0,r=g+d<<0),T=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),_=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),w=r&e,E=w^r&a^v,m=h&l^~h&i,g=c+_+m+se[f+1]+b[f+1],d=T+E,h=n+g<<0,n=g+d<<0,T=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),_=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),A=n&r,E=A^n&e^w,m=c&h^~c&l,g=i+_+m+se[f+2]+b[f+2],d=T+E,c=a+g<<0,a=g+d<<0,T=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),_=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),C=a&n,E=C^a&r^A,m=c&h^~c&l,g=i+_+m+se[f+3]+b[f+3],d=T+E,i=e+g<<0,e=g+d<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+a<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+c<<0,this.h6=this.h6+h<<0,this.h7=this.h7+l<<0};B.prototype.hex=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,b=y[e>>>28&15]+y[e>>>24&15]+y[e>>>20&15]+y[e>>>16&15]+y[e>>>12&15]+y[e>>>8&15]+y[e>>>4&15]+y[e&15]+y[a>>>28&15]+y[a>>>24&15]+y[a>>>20&15]+y[a>>>16&15]+y[a>>>12&15]+y[a>>>8&15]+y[a>>>4&15]+y[a&15]+y[n>>>28&15]+y[n>>>24&15]+y[n>>>20&15]+y[n>>>16&15]+y[n>>>12&15]+y[n>>>8&15]+y[n>>>4&15]+y[n&15]+y[r>>>28&15]+y[r>>>24&15]+y[r>>>20&15]+y[r>>>16&15]+y[r>>>12&15]+y[r>>>8&15]+y[r>>>4&15]+y[r&15]+y[i>>>28&15]+y[i>>>24&15]+y[i>>>20&15]+y[i>>>16&15]+y[i>>>12&15]+y[i>>>8&15]+y[i>>>4&15]+y[i&15]+y[c>>>28&15]+y[c>>>24&15]+y[c>>>20&15]+y[c>>>16&15]+y[c>>>12&15]+y[c>>>8&15]+y[c>>>4&15]+y[c&15]+y[h>>>28&15]+y[h>>>24&15]+y[h>>>20&15]+y[h>>>16&15]+y[h>>>12&15]+y[h>>>8&15]+y[h>>>4&15]+y[h&15];return this.is224||(b+=y[l>>>28&15]+y[l>>>24&15]+y[l>>>20&15]+y[l>>>16&15]+y[l>>>12&15]+y[l>>>8&15]+y[l>>>4&15]+y[l&15]),b};B.prototype.toString=B.prototype.hex;B.prototype.digest=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,b=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||b.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),b};B.prototype.array=B.prototype.digest;B.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),a=new DataView(e);return a.setUint32(0,this.h0),a.setUint32(4,this.h1),a.setUint32(8,this.h2),a.setUint32(12,this.h3),a.setUint32(16,this.h4),a.setUint32(20,this.h5),a.setUint32(24,this.h6),this.is224||a.setUint32(28,this.h7),e};const lt=(...e)=>new B(!1,!0).update(e.join("")).hex();var Fa={};U(Fa,{sha256:()=>lt});var La={};U(La,{BaseCache:()=>pt,InMemoryCache:()=>gt,defaultHashKeyEncoder:()=>ht,deserializeStoredGeneration:()=>Da,serializeGeneration:()=>Ba});const ht=(...e)=>lt(e.join("_"));function Da(e){return e.message!==void 0?{text:e.text,message:sa(e.message)}:{text:e.text}}function Ba(e){const a={text:e.text};return e.message!==void 0&&(a.message=e.message.toDict()),a}var pt=class{keyEncoder=ht;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const Ua=new Map;var gt=class mt extends pt{cache;constructor(a){super(),this.cache=a??new Map}lookup(a,n){return Promise.resolve(this.cache.get(this.keyEncoder(a,n))??null)}async update(a,n,r){this.cache.set(this.keyEncoder(a,n),r)}static global(){return new mt(Ua)}},q={},Ze;function ja(){if(Ze)return q;Ze=1,q.byteLength=l,q.toByteArray=f,q.fromByteArray=E;for(var e=[],a=[],n=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=r.length;i<c;++i)e[i]=r[i],a[r.charCodeAt(i)]=i;a[45]=62,a[95]=63;function h(g){var d=g.length;if(d%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var m=g.indexOf("=");m===-1&&(m=d);var v=m===d?0:4-m%4;return[m,v]}function l(g){var d=h(g),m=d[0],v=d[1];return(m+v)*3/4-v}function b(g,d,m){return(d+m)*3/4-m}function f(g){var d,m=h(g),v=m[0],w=m[1],A=new n(b(g,v,w)),C=0,P=w>0?v-4:v,O;for(O=0;O<P;O+=4)d=a[g.charCodeAt(O)]<<18|a[g.charCodeAt(O+1)]<<12|a[g.charCodeAt(O+2)]<<6|a[g.charCodeAt(O+3)],A[C++]=d>>16&255,A[C++]=d>>8&255,A[C++]=d&255;return w===2&&(d=a[g.charCodeAt(O)]<<2|a[g.charCodeAt(O+1)]>>4,A[C++]=d&255),w===1&&(d=a[g.charCodeAt(O)]<<10|a[g.charCodeAt(O+1)]<<4|a[g.charCodeAt(O+2)]>>2,A[C++]=d>>8&255,A[C++]=d&255),A}function T(g){return e[g>>18&63]+e[g>>12&63]+e[g>>6&63]+e[g&63]}function _(g,d,m){for(var v,w=[],A=d;A<m;A+=3)v=(g[A]<<16&16711680)+(g[A+1]<<8&65280)+(g[A+2]&255),w.push(T(v));return w.join("")}function E(g){for(var d,m=g.length,v=m%3,w=[],A=16383,C=0,P=m-v;C<P;C+=A)w.push(_(g,C,C+A>P?P:C+A));return v===1?(d=g[m-1],w.push(e[d>>2]+e[d<<4&63]+"==")):v===2&&(d=(g[m-2]<<8)+g[m-1],w.push(e[d>>10]+e[d>>4&63]+e[d<<2&63]+"=")),w.join("")}return q}var Va=ja();const za=Oa(Va);var Ga=Object.defineProperty,Za=(e,a,n)=>a in e?Ga(e,a,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[a]=n,$a=(e,a,n)=>(Za(e,a+"",n),n);function Ha(e,a){let n=Array.from({length:e.length},(r,i)=>({start:i,end:i+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){const c=e.slice(n[i].start,n[i+1].end),h=a.get(c.join(","));h!=null&&(r==null||h<r[0])&&(r=[h,i])}if(r!=null){const i=r[1];n[i]={start:n[i].start,end:n[i+1].end},n.splice(i+1,1)}else break}return n}function Wa(e,a){return e.length===1?[a.get(e.join(","))]:Ha(e,a).map(n=>a.get(e.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function Ja(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var Ee=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,a){this.patStr=e.pat_str;const n=e.bpe_ranks.split(`
|
|
1
|
+
import{N as Ue,O as je,P as J,Q as ae,i as Ae,S as H,y as le,g as U,U as Nt,V as kt,W as xt,X as Pt,Y as Mt,Z as Rt,$ as Ft,a0 as Lt,a1 as Dt,a2 as Bt,h as Ut,a3 as jt,a4 as Vt,a5 as zt,b as Gt,a6 as Zt,a7 as $t,a8 as Ht,a9 as Wt,aa as Jt,r as Xt,ab as Yt,a as $e,ac as Kt,ad as He,ae as qt,af as Qt,ag as ea,ah as Se,ai as ta,aj as aa,ak as sa,q as We,al as re,e as oe,am as Je,an as Xe,x as ce,L as na,C as ye,ao as Ve,w as ra,R as ze,z as X,t as ia,ap as Ie,E as oa,M as Ye,aq as ca,ar as ua,as as la,B as Ke,at as ie,k as G,au as qe,av as ha,aw as Qe,ax as pa,l as ga,m as ma,ay as fa,az as da,aA as ba,aB as ya,aC as _a,aD as Ta,aE as va,aF as Ea,D as Ge,aG as wa,G as Ca,aH as Aa,aI as Sa,aJ as ve,o as et,s as tt,u as Ia}from"./index-CW3Avs3Z.js";import{c as Oa}from"./index-CqlJu5dO.js";function at(e,a,n,r,i){if(a!==e){typeof a.toJSON=="function"&&(a=a.toJSON());for(var c=Ue(a),h=Ue(e),l=!1,b=h.length-1;b>=0;b--){var f=h[b],T=e[f];if(je(a,f)&&!(a[f]===void 0&&T!==void 0&&Array.isArray(a)===!1)){var _=a[f];typeof T=="object"&&T!=null&&typeof _=="object"&&_!=null&&Array.isArray(T)===Array.isArray(_)?at(T,_,n,r+"/"+J(f),i):T!==_&&(i&&n.push({op:"test",path:r+"/"+J(f),value:ae(T)}),n.push({op:"replace",path:r+"/"+J(f),value:ae(_)}))}else Array.isArray(e)===Array.isArray(a)?(i&&n.push({op:"test",path:r+"/"+J(f),value:ae(T)}),n.push({op:"remove",path:r+"/"+J(f)}),l=!0):(i&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:a}))}if(!(!l&&c.length==h.length))for(var b=0;b<c.length;b++){var f=c[b];!je(e,f)&&a[f]!==void 0&&n.push({op:"add",path:r+"/"+J(f),value:ae(a[f])})}}}function Oe(e,a,n=!1){var r=[];return at(e,a,r,"",n),r}function st(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function nt(e){return e!==void 0&&H.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function rt(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Ae(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function it(e){return rt(e)||nt(e)||st(e)}var Na={};U(Na,{convertToOpenAIFunction:()=>ot,convertToOpenAITool:()=>ka,isLangChainTool:()=>it,isRunnableToolLike:()=>nt,isStructuredTool:()=>st,isStructuredToolParams:()=>rt});function ot(e,a){const n=typeof a=="number"?void 0:a;return{name:e.name,description:e.description,parameters:le(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function ka(e,a){const n=typeof a=="number"?void 0:a;let r;return it(e)?r={type:"function",function:ot(e)}:r=e,n?.strict!==void 0&&(r.function.strict=n.strict),r}var xa={};U(xa,{extendInteropZodObject:()=>ea,getInteropZodDefaultGetter:()=>Qt,getInteropZodObjectShape:()=>qt,getSchemaDescription:()=>He,interopParse:()=>Kt,interopParseAsync:()=>$e,interopSafeParse:()=>Yt,interopSafeParseAsync:()=>Xt,interopZodObjectMakeFieldsOptional:()=>Jt,interopZodObjectPartial:()=>Wt,interopZodObjectPassthrough:()=>Ht,interopZodObjectStrict:()=>$t,interopZodTransformInputSchema:()=>Zt,isInteropZodError:()=>Gt,isInteropZodLiteral:()=>zt,isInteropZodObject:()=>Vt,isInteropZodSchema:()=>Ae,isShapelessZodSchema:()=>jt,isSimpleStringZodSchema:()=>Ut,isZodArrayV4:()=>Bt,isZodLiteralV3:()=>Dt,isZodLiteralV4:()=>Lt,isZodNullableV4:()=>Ft,isZodObjectV3:()=>Rt,isZodObjectV4:()=>Mt,isZodOptionalV4:()=>Pt,isZodSchema:()=>xt,isZodSchemaV3:()=>kt,isZodSchemaV4:()=>Nt});var Pa={};U(Pa,{BasePromptValue:()=>he,ChatPromptValue:()=>ut,ImagePromptValue:()=>Ma,StringPromptValue:()=>ct});var he=class extends aa{},ct=class extends he{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new Se(this.value)]}},ut=class extends he{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return ta(this.messages)}toChatMessages(){return this.messages}},Ma=class extends he{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Se({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},y="0123456789abcdef".split(""),Ra=[-2147483648,8388608,32768,128],D=[24,16,8,0],se=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],M=[];function B(e,a){a?(M[0]=M[16]=M[1]=M[2]=M[3]=M[4]=M[5]=M[6]=M[7]=M[8]=M[9]=M[10]=M[11]=M[12]=M[13]=M[14]=M[15]=0,this.blocks=M):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}B.prototype.update=function(e){if(!this.finalized){var a,n=typeof e;if(n!=="string"){if(n==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);a=!0}for(var r,i=0,c,h=e.length,l=this.blocks;i<h;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),a)for(c=this.start;i<h&&c<64;++i)l[c>>>2]|=e[i]<<D[c++&3];else for(c=this.start;i<h&&c<64;++i)r=e.charCodeAt(i),r<128?l[c>>>2]|=r<<D[c++&3]:r<2048?(l[c>>>2]|=(192|r>>>6)<<D[c++&3],l[c>>>2]|=(128|r&63)<<D[c++&3]):r<55296||r>=57344?(l[c>>>2]|=(224|r>>>12)<<D[c++&3],l[c>>>2]|=(128|r>>>6&63)<<D[c++&3],l[c>>>2]|=(128|r&63)<<D[c++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),l[c>>>2]|=(240|r>>>18)<<D[c++&3],l[c>>>2]|=(128|r>>>12&63)<<D[c++&3],l[c>>>2]|=(128|r>>>6&63)<<D[c++&3],l[c>>>2]|=(128|r&63)<<D[c++&3]);this.lastByteIndex=c,this.bytes+=c-this.start,c>=64?(this.block=l[16],this.start=c-64,this.hash(),this.hashed=!0):this.start=c}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};B.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,a=this.lastByteIndex;e[16]=this.block,e[a>>>2]|=Ra[a&3],this.block=e[16],a>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};B.prototype.hash=function(){var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,b=this.blocks,f,T,_,E,g,d,m,v,w,A,C;for(f=16;f<64;++f)g=b[f-15],T=(g>>>7|g<<25)^(g>>>18|g<<14)^g>>>3,g=b[f-2],_=(g>>>17|g<<15)^(g>>>19|g<<13)^g>>>10,b[f]=b[f-16]+T+b[f-7]+_<<0;for(C=a&n,f=0;f<64;f+=4)this.first?(this.is224?(v=300032,g=b[0]-1413257819,l=g-150054599<<0,r=g+24177077<<0):(v=704751109,g=b[0]-210244248,l=g-1521486534<<0,r=g+143694565<<0),this.first=!1):(T=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),_=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),v=e&a,E=v^e&n^C,m=i&c^~i&h,g=l+_+m+se[f]+b[f],d=T+E,l=r+g<<0,r=g+d<<0),T=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),_=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),w=r&e,E=w^r&a^v,m=h&l^~h&i,g=c+_+m+se[f+1]+b[f+1],d=T+E,h=n+g<<0,n=g+d<<0,T=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),_=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),A=n&r,E=A^n&e^w,m=c&h^~c&l,g=i+_+m+se[f+2]+b[f+2],d=T+E,c=a+g<<0,a=g+d<<0,T=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),_=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),C=a&n,E=C^a&r^A,m=c&h^~c&l,g=i+_+m+se[f+3]+b[f+3],d=T+E,i=e+g<<0,e=g+d<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+a<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+c<<0,this.h6=this.h6+h<<0,this.h7=this.h7+l<<0};B.prototype.hex=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,b=y[e>>>28&15]+y[e>>>24&15]+y[e>>>20&15]+y[e>>>16&15]+y[e>>>12&15]+y[e>>>8&15]+y[e>>>4&15]+y[e&15]+y[a>>>28&15]+y[a>>>24&15]+y[a>>>20&15]+y[a>>>16&15]+y[a>>>12&15]+y[a>>>8&15]+y[a>>>4&15]+y[a&15]+y[n>>>28&15]+y[n>>>24&15]+y[n>>>20&15]+y[n>>>16&15]+y[n>>>12&15]+y[n>>>8&15]+y[n>>>4&15]+y[n&15]+y[r>>>28&15]+y[r>>>24&15]+y[r>>>20&15]+y[r>>>16&15]+y[r>>>12&15]+y[r>>>8&15]+y[r>>>4&15]+y[r&15]+y[i>>>28&15]+y[i>>>24&15]+y[i>>>20&15]+y[i>>>16&15]+y[i>>>12&15]+y[i>>>8&15]+y[i>>>4&15]+y[i&15]+y[c>>>28&15]+y[c>>>24&15]+y[c>>>20&15]+y[c>>>16&15]+y[c>>>12&15]+y[c>>>8&15]+y[c>>>4&15]+y[c&15]+y[h>>>28&15]+y[h>>>24&15]+y[h>>>20&15]+y[h>>>16&15]+y[h>>>12&15]+y[h>>>8&15]+y[h>>>4&15]+y[h&15];return this.is224||(b+=y[l>>>28&15]+y[l>>>24&15]+y[l>>>20&15]+y[l>>>16&15]+y[l>>>12&15]+y[l>>>8&15]+y[l>>>4&15]+y[l&15]),b};B.prototype.toString=B.prototype.hex;B.prototype.digest=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,b=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||b.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),b};B.prototype.array=B.prototype.digest;B.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),a=new DataView(e);return a.setUint32(0,this.h0),a.setUint32(4,this.h1),a.setUint32(8,this.h2),a.setUint32(12,this.h3),a.setUint32(16,this.h4),a.setUint32(20,this.h5),a.setUint32(24,this.h6),this.is224||a.setUint32(28,this.h7),e};const lt=(...e)=>new B(!1,!0).update(e.join("")).hex();var Fa={};U(Fa,{sha256:()=>lt});var La={};U(La,{BaseCache:()=>pt,InMemoryCache:()=>gt,defaultHashKeyEncoder:()=>ht,deserializeStoredGeneration:()=>Da,serializeGeneration:()=>Ba});const ht=(...e)=>lt(e.join("_"));function Da(e){return e.message!==void 0?{text:e.text,message:sa(e.message)}:{text:e.text}}function Ba(e){const a={text:e.text};return e.message!==void 0&&(a.message=e.message.toDict()),a}var pt=class{keyEncoder=ht;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const Ua=new Map;var gt=class mt extends pt{cache;constructor(a){super(),this.cache=a??new Map}lookup(a,n){return Promise.resolve(this.cache.get(this.keyEncoder(a,n))??null)}async update(a,n,r){this.cache.set(this.keyEncoder(a,n),r)}static global(){return new mt(Ua)}},q={},Ze;function ja(){if(Ze)return q;Ze=1,q.byteLength=l,q.toByteArray=f,q.fromByteArray=E;for(var e=[],a=[],n=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=r.length;i<c;++i)e[i]=r[i],a[r.charCodeAt(i)]=i;a[45]=62,a[95]=63;function h(g){var d=g.length;if(d%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var m=g.indexOf("=");m===-1&&(m=d);var v=m===d?0:4-m%4;return[m,v]}function l(g){var d=h(g),m=d[0],v=d[1];return(m+v)*3/4-v}function b(g,d,m){return(d+m)*3/4-m}function f(g){var d,m=h(g),v=m[0],w=m[1],A=new n(b(g,v,w)),C=0,P=w>0?v-4:v,O;for(O=0;O<P;O+=4)d=a[g.charCodeAt(O)]<<18|a[g.charCodeAt(O+1)]<<12|a[g.charCodeAt(O+2)]<<6|a[g.charCodeAt(O+3)],A[C++]=d>>16&255,A[C++]=d>>8&255,A[C++]=d&255;return w===2&&(d=a[g.charCodeAt(O)]<<2|a[g.charCodeAt(O+1)]>>4,A[C++]=d&255),w===1&&(d=a[g.charCodeAt(O)]<<10|a[g.charCodeAt(O+1)]<<4|a[g.charCodeAt(O+2)]>>2,A[C++]=d>>8&255,A[C++]=d&255),A}function T(g){return e[g>>18&63]+e[g>>12&63]+e[g>>6&63]+e[g&63]}function _(g,d,m){for(var v,w=[],A=d;A<m;A+=3)v=(g[A]<<16&16711680)+(g[A+1]<<8&65280)+(g[A+2]&255),w.push(T(v));return w.join("")}function E(g){for(var d,m=g.length,v=m%3,w=[],A=16383,C=0,P=m-v;C<P;C+=A)w.push(_(g,C,C+A>P?P:C+A));return v===1?(d=g[m-1],w.push(e[d>>2]+e[d<<4&63]+"==")):v===2&&(d=(g[m-2]<<8)+g[m-1],w.push(e[d>>10]+e[d>>4&63]+e[d<<2&63]+"=")),w.join("")}return q}var Va=ja();const za=Oa(Va);var Ga=Object.defineProperty,Za=(e,a,n)=>a in e?Ga(e,a,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[a]=n,$a=(e,a,n)=>(Za(e,a+"",n),n);function Ha(e,a){let n=Array.from({length:e.length},(r,i)=>({start:i,end:i+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){const c=e.slice(n[i].start,n[i+1].end),h=a.get(c.join(","));h!=null&&(r==null||h<r[0])&&(r=[h,i])}if(r!=null){const i=r[1];n[i]={start:n[i].start,end:n[i+1].end},n.splice(i+1,1)}else break}return n}function Wa(e,a){return e.length===1?[a.get(e.join(","))]:Ha(e,a).map(n=>a.get(e.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function Ja(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var Ee=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,a){this.patStr=e.pat_str;const n=e.bpe_ranks.split(`
|
|
2
2
|
`).filter(Boolean).reduce((r,i)=>{const[c,h,...l]=i.split(" "),b=Number.parseInt(h,10);return l.forEach((f,T)=>r[f]=b+T),r},{});for(const[r,i]of Object.entries(n)){const c=za.toByteArray(r);this.rankMap.set(c.join(","),i),this.textMap.set(i,c)}this.specialTokens={...e.special_tokens,...a},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[i,c])=>(r[c]=this.textEncoder.encode(i),r),{})}encode(e,a=[],n="all"){const r=new RegExp(this.patStr,"ug"),i=Ee.specialTokenRegex(Object.keys(this.specialTokens)),c=[],h=new Set(a==="all"?Object.keys(this.specialTokens):a),l=new Set(n==="all"?Object.keys(this.specialTokens).filter(f=>!h.has(f)):n);if(l.size>0){const f=Ee.specialTokenRegex([...l]),T=e.match(f);if(T!=null)throw new Error(`The text contains a special token that is not allowed: ${T[0]}`)}let b=0;for(;;){let f=null,T=b;for(;i.lastIndex=T,f=i.exec(e),!(f==null||h.has(f[0]));)T=f.index+1;const _=f?.index??e.length;for(const g of e.substring(b,_).matchAll(r)){const d=this.textEncoder.encode(g[0]),m=this.rankMap.get(d.join(","));if(m!=null){c.push(m);continue}c.push(...Wa(d,this.rankMap))}if(f==null)break;let E=this.specialTokens[f[0]];c.push(E),b=f.index+f[0].length}return c}decode(e){const a=[];let n=0;for(let c=0;c<e.length;++c){const h=e[c],l=this.textMap.get(h)??this.inverseSpecialTokens[h];l!=null&&(a.push(l),n+=l.length)}const r=new Uint8Array(n);let i=0;for(const c of a)r.set(c,i),i+=c.length;return this.textDecoder.decode(r)}},ft=Ee;$a(ft,"specialTokenRegex",e=>new RegExp(e.map(a=>Ja(a)).join("|"),"g"));function Xa(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var Ya={};U(Ya,{encodingForModel:()=>Ne,getEncoding:()=>dt});const ne={},Ka=new We({});async function dt(e){return e in ne||(ne[e]=Ka.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(a=>a.json()).then(a=>new ft(a)).catch(a=>{throw delete ne[e],a})),await ne[e]}async function Ne(e){return dt(Xa(e))}var qa={};U(qa,{BaseLangChain:()=>yt,BaseLanguageModel:()=>_t,calculateMaxTokens:()=>ts,getEmbeddingContextSize:()=>Qa,getModelContextSize:()=>bt,getModelNameForTiktoken:()=>pe,isOpenAITool:()=>es});const pe=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,Qa=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},bt=e=>{switch(pe(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function es(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}const ts=async({prompt:e,modelName:a})=>{let n;try{n=(await Ne(pe(a))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(e.length/4)}return bt(a)-n},as=()=>!1;var yt=class extends H{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??as(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},_t=class extends yt{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:a,...n}){const{cache:r,...i}=n;super({callbacks:e??a,...i}),typeof r=="object"?this.cache=r:r?this.cache=gt.global():this.cache=void 0,this.caller=new We(n??{})}_encoding;async getNumTokens(e){let a;typeof e=="string"?a=e:a=e.map(r=>typeof r=="string"?r:r.type==="text"&&"text"in r?r.text:"").join("");let n=Math.ceil(a.length/4);if(!this._encoding)try{this._encoding=await Ne("modelName"in this?pe(this.modelName):"gpt2")}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}if(this._encoding)try{n=this._encoding.encode(a).length}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}return n}static _convertInputToPromptValue(e){return typeof e=="string"?new ct(e):Array.isArray(e)?new ut(e.map(re)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...a}){const n={...this._identifyingParams(),...a,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([c,h])=>h!==void 0).map(([c,h])=>`${c}:${JSON.stringify(h)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}},ue=class extends H{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,a){const n=oe(a);return this.func&&await this.func(e,n),this._callWithConfig(r=>Promise.resolve(r),e,n)}async*transform(e,a){const n=oe(a);let r,i=!0;for await(const c of this._transformStreamWithConfig(e,h=>h,n))if(yield c,i)if(r===void 0)r=c;else try{r=ce(r,c)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new Je(new Xe({steps:e}))}};const ss=e=>e();function _e(e){const a=e.constructor;return new a({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var ns={};U(ns,{BaseChatModel:()=>Tt,SimpleChatModel:()=>rs});function Te(e){const a=[];for(const n of e){let r=n;if(Array.isArray(n.content))for(let i=0;i<n.content.length;i++){const c=n.content[i];(ca(c)||ua(c))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,i),la(c),...n.content.slice(i+1)]}))}a.push(r)}return a}var Tt=class Z extends _t{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(a){super(a),this.outputVersion=ss(()=>{const n=a.outputVersion??na("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}_separateRunnableConfigFromCallOptionsCompat(a){const[n,r]=super._separateRunnableConfigFromCallOptions(a);return r.signal=n.signal,[n,r]}async invoke(a,n){const r=Z._convertInputToPromptValue(a);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(a,n,r){throw new Error("Not implemented.")}async*_streamIterator(a,n){if(this._streamResponseChunks===Z.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(a,n);else{const i=Z._convertInputToPromptValue(a).toChatMessages(),[c,h]=this._separateRunnableConfigFromCallOptionsCompat(n),l={...c.metadata,...this.getLsParams(h)},b=await ye.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose}),f={options:h,invocation_params:this?.invocationParams(h),batch_size:1},T=h.outputVersion??this.outputVersion,_=await b?.handleChatModelStart(this.toJSON(),[Te(i)],c.runId,void 0,f,void 0,void 0,c.runName);let E,g;try{for await(const d of this._streamResponseChunks(i,h,_?.[0])){if(d.message.id==null){const m=_?.at(0)?.runId;m!=null&&d.message._updateId(`run-${m}`)}d.message.response_metadata={...d.generationInfo,...d.message.response_metadata},T==="v1"?yield _e(d.message):yield d.message,E?E=E.concat(d):E=d,Ve(d.message)&&d.message.usage_metadata!==void 0&&(g={tokenUsage:{promptTokens:d.message.usage_metadata.input_tokens,completionTokens:d.message.usage_metadata.output_tokens,totalTokens:d.message.usage_metadata.total_tokens}})}}catch(d){throw await Promise.all((_??[]).map(m=>m?.handleLLMError(d))),d}await Promise.all((_??[]).map(d=>d?.handleLLMEnd({generations:[[E]],llmOutput:g})))}}getLsParams(a){const n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:a.stop,ls_provider:n}}async _generateUncached(a,n,r,i){const c=a.map(E=>E.map(re));let h;if(i!==void 0&&i.length===c.length)h=i;else{const E={...r.metadata,...this.getLsParams(n)},g=await ye.configure(r.callbacks,this.callbacks,r.tags,this.tags,E,this.metadata,{verbose:this.verbose}),d={options:n,invocation_params:this?.invocationParams(n),batch_size:1};h=await g?.handleChatModelStart(this.toJSON(),c.map(Te),r.runId,void 0,d,void 0,void 0,r.runName)}const l=n.outputVersion??this.outputVersion,b=[],f=[];if(!!h?.[0].handlers.find(ra)&&!this.disableStreaming&&c.length===1&&this._streamResponseChunks!==Z.prototype._streamResponseChunks)try{const E=await this._streamResponseChunks(c[0],n,h?.[0]);let g,d;for await(const m of E){if(m.message.id==null){const v=h?.at(0)?.runId;v!=null&&m.message._updateId(`run-${v}`)}g===void 0?g=m:g=ce(g,m),Ve(m.message)&&m.message.usage_metadata!==void 0&&(d={tokenUsage:{promptTokens:m.message.usage_metadata.input_tokens,completionTokens:m.message.usage_metadata.output_tokens,totalTokens:m.message.usage_metadata.total_tokens}})}if(g===void 0)throw new Error("Received empty response from chat model call.");b.push([g]),await h?.[0].handleLLMEnd({generations:b,llmOutput:d})}catch(E){throw await h?.[0].handleLLMError(E),E}else{const E=await Promise.allSettled(c.map(async(g,d)=>{const m=await this._generate(g,{...n,promptIndex:d},h?.[d]);if(l==="v1")for(const v of m.generations)v.message=_e(v.message);return m}));await Promise.all(E.map(async(g,d)=>{if(g.status==="fulfilled"){const m=g.value;for(const v of m.generations){if(v.message.id==null){const w=h?.at(0)?.runId;w!=null&&v.message._updateId(`run-${w}`)}v.message.response_metadata={...v.generationInfo,...v.message.response_metadata}}return m.generations.length===1&&(m.generations[0].message.response_metadata={...m.llmOutput,...m.generations[0].message.response_metadata}),b[d]=m.generations,f[d]=m.llmOutput,h?.[d]?.handleLLMEnd({generations:[m.generations],llmOutput:m.llmOutput})}else return await h?.[d]?.handleLLMError(g.reason),Promise.reject(g.reason)}))}const _={generations:b,llmOutput:f.length?this._combineLLMOutput?.(...f):void 0};return Object.defineProperty(_,ze,{value:h?{runIds:h?.map(E=>E.runId)}:void 0,configurable:!0}),_}async _generateCached({messages:a,cache:n,llmStringKey:r,parsedOptions:i,handledOptions:c}){const h=a.map(w=>w.map(re)),l={...c.metadata,...this.getLsParams(i)},b=await ye.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose}),f={options:i,invocation_params:this?.invocationParams(i),batch_size:1},T=await b?.handleChatModelStart(this.toJSON(),h.map(Te),c.runId,void 0,f,void 0,void 0,c.runName),_=[],g=(await Promise.allSettled(h.map(async(w,A)=>{const C=Z._convertInputToPromptValue(w).toString(),P=await n.lookup(C,r);return P==null&&_.push(A),P}))).map((w,A)=>({result:w,runManager:T?.[A]})).filter(({result:w})=>w.status==="fulfilled"&&w.value!=null||w.status==="rejected"),d=i.outputVersion??this.outputVersion,m=[];await Promise.all(g.map(async({result:w,runManager:A},C)=>{if(w.status==="fulfilled"){const P=w.value;return m[C]=P.map(O=>("message"in O&&X(O.message)&&ia(O.message)&&(O.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},d==="v1"&&(O.message=_e(O.message))),O.generationInfo={...O.generationInfo,tokenUsage:{}},O)),P.length&&await A?.handleLLMNewToken(P[0].text),A?.handleLLMEnd({generations:[P]},void 0,void 0,void 0,{cached:!0})}else return await A?.handleLLMError(w.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(w.reason)}));const v={generations:m,missingPromptIndices:_,startedRunManagers:T};return Object.defineProperty(v,ze,{value:T?{runIds:T?.map(w=>w.runId)}:void 0,configurable:!0}),v}async generate(a,n,r){let i;Array.isArray(n)?i={stop:n}:i=n;const c=a.map(d=>d.map(re)),[h,l]=this._separateRunnableConfigFromCallOptionsCompat(i);if(h.callbacks=h.callbacks??r,!this.cache)return this._generateUncached(c,l,h);const{cache:b}=this,f=this._getSerializedCacheKeyParametersForCall(l),{generations:T,missingPromptIndices:_,startedRunManagers:E}=await this._generateCached({messages:c,cache:b,llmStringKey:f,parsedOptions:l,handledOptions:h});let g={};if(_.length>0){const d=await this._generateUncached(_.map(m=>c[m]),l,h,E!==void 0?_.map(m=>E?.[m]):void 0);await Promise.all(d.generations.map(async(m,v)=>{const w=_[v];T[w]=m;const A=Z._convertInputToPromptValue(c[w]).toString();return b.update(A,f,m)})),g=d.llmOutput??{}}return{generations:T,llmOutput:g}}invocationParams(a){return{}}_modelType(){return"base_chat_model"}async generatePrompt(a,n,r){const i=a.map(c=>c.toChatMessages());return this.generate(i,n,r)}withStructuredOutput(a,n){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(n?.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=a,i=n?.name,c=He(r)??"A function available to call.",h=n?.method,l=n?.includeRaw;if(h==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let b=i??"extract",f;Ae(r)?f=[{type:"function",function:{name:b,description:c,parameters:le(r)}}]:("name"in r&&(b=r.name),f=[{type:"function",function:{name:b,description:c,parameters:r}}]);const T=this.bindTools(f),_=Ie.from(m=>{if(!oa.isInstance(m))throw new Error("Input is not an AIMessageChunk.");if(!m.tool_calls||m.tool_calls.length===0)throw new Error("No tool calls found in the response.");const v=m.tool_calls.find(w=>w.name===b);if(!v)throw new Error(`No tool call found with name ${b}.`);return v.args});if(!l)return T.pipe(_).withConfig({runName:"StructuredOutput"});const E=ue.assign({parsed:(m,v)=>_.invoke(m.raw,v)}),g=ue.assign({parsed:()=>null}),d=E.withFallbacks({fallbacks:[g]});return Ye.from([{raw:T},d]).withConfig({runName:"StructuredOutputRunnable"})}},rs=class extends Tt{async _generate(e,a,n){const r=await this._call(e,a,n),i=new Ke(r);if(typeof i.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:i.content,message:i}]}}},is=class extends H{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,a){const{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw new Error(`No runnable associated with key "${n}".`);return i.invoke(r,oe(a))}async batch(e,a,n){const r=e.map(_=>_.key),i=e.map(_=>_.input);if(r.find(_=>this.runnables[_]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const h=r.map(_=>this.runnables[_]),l=this._getOptionsList(a??{},e.length),b=l[0]?.maxConcurrency??n?.maxConcurrency,f=b&&b>0?b:e.length,T=[];for(let _=0;_<i.length;_+=f){const E=i.slice(_,_+f).map((d,m)=>h[m].invoke(d,l[m])),g=await Promise.all(E);T.push(g)}return T.flat()}async stream(e,a){const{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw new Error(`No runnable associated with key "${n}".`);return i.stream(r,a)}},os=class extends H{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");const n=e.slice(0,-1).map(([i,c])=>[ie(i),ie(c)]),r=ie(e[e.length-1]);return new this({branches:n,default:r})}async _invoke(e,a,n){let r;for(let i=0;i<this.branches.length;i+=1){const[c,h]=this.branches[i];if(await c.invoke(e,G(a,{callbacks:n?.getChild(`condition:${i+1}`)}))){r=await h.invoke(e,G(a,{callbacks:n?.getChild(`branch:${i+1}`)}));break}}return r||(r=await this.default.invoke(e,G(a,{callbacks:n?.getChild("branch:default")}))),r}async invoke(e,a={}){return this._callWithConfig(this._invoke,e,a)}async*_streamIterator(e,a){const r=await(await qe(a))?.handleChainStart(this.toJSON(),ha(e,"input"),a?.runId,void 0,void 0,void 0,a?.runName);let i,c=!0,h;try{for(let l=0;l<this.branches.length;l+=1){const[b,f]=this.branches[l];if(await b.invoke(e,G(a,{callbacks:r?.getChild(`condition:${l+1}`)}))){h=await f.stream(e,G(a,{callbacks:r?.getChild(`branch:${l+1}`)}));for await(const _ of h)if(yield _,c)if(i===void 0)i=_;else try{i=ce(i,_)}catch{i=void 0,c=!1}break}}if(h===void 0){h=await this.default.stream(e,G(a,{callbacks:r?.getChild("branch:default")}));for await(const l of h)if(yield l,c)if(i===void 0)i=l;else try{i=ce(i,l)}catch{i=void 0,c=!1}}}catch(l){throw await r?.handleChainError(l),l}await r?.handleChainEnd(i??{})}},cs=class extends Qe{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let a=Ie.from((c,h)=>this._enterHistory(c,h??{})).withConfig({runName:"loadHistory"});const n=e.historyMessagesKey??e.inputMessagesKey;n&&(a=ue.assign({[n]:a}).withConfig({runName:"insertHistory"}));const r=a.pipe(e.runnable.withListeners({onEnd:(c,h)=>this._exitHistory(c,h??{})})).withConfig({runName:"RunnableWithMessageHistory"}),i=e.config??{};super({...e,config:i,bound:r}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let a;if(typeof e=="object"&&!Array.isArray(e)&&!X(e)){let n;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="input",Array.isArray(e[n])&&Array.isArray(e[n][0])?a=e[n][0]:a=e[n]}else a=e;if(typeof a=="string")return[new Se(a)];if(Array.isArray(a))return a;if(X(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
|
|
3
3
|
Got ${JSON.stringify(a,null,2)}`)}_getOutputMessages(e){let a;if(!Array.isArray(e)&&!X(e)&&typeof e!="string"){let n;this.outputMessagesKey!==void 0?n=this.outputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="output",e.generations!==void 0?a=e.generations[0][0].message:a=e[n]}else a=e;if(typeof a=="string")return[new Ke(a)];if(Array.isArray(a))return a;if(X(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(a,null,2)}`)}async _enterHistory(e,a){const r=await(a?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(e)):r}async _exitHistory(e,a){const n=a.configurable?.messageHistory;let r;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?r=e.inputs[0]:r=e.inputs;let i=this._getInputMessages(r);if(this.historyMessagesKey===void 0){const l=await n.getMessages();i=i.slice(l.length)}const c=e.outputs;if(!c)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const h=this._getOutputMessages(c);await n.addMessages([...i,...h])}async _mergeConfig(...e){const a=await super._mergeConfig(...e);if(!a.configurable||!a.configurable.sessionId){const r={[this.inputMessagesKey??"input"]:"foo"},i={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
|
|
4
4
|
eg. chain.invoke(${JSON.stringify(r)}, ${JSON.stringify(i)})`)}const{sessionId:n}=a.configurable;return a.configurable.messageHistory=await this.getMessageHistory(n),a}},us={};U(us,{RouterRunnable:()=>is,Runnable:()=>H,RunnableAssign:()=>Je,RunnableBinding:()=>Qe,RunnableBranch:()=>os,RunnableEach:()=>Ta,RunnableLambda:()=>Ie,RunnableMap:()=>Xe,RunnableParallel:()=>_a,RunnablePassthrough:()=>ue,RunnablePick:()=>ya,RunnableRetry:()=>ba,RunnableSequence:()=>Ye,RunnableToolLike:()=>da,RunnableWithFallbacks:()=>fa,RunnableWithMessageHistory:()=>cs,_coerceToRunnable:()=>ie,ensureConfig:()=>oe,getCallbackManagerForConfig:()=>qe,mergeConfigs:()=>ma,patchConfig:()=>G,pickRunnableConfigKeys:()=>ga,raceWithSignal:()=>pa});var vt=class extends H{parseResultWithPrompt(e,a,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,a){return typeof e=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r?.callbacks),e,{...a,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r?.callbacks),e,{...a,runType:"parser"})}},ge=class extends vt{parseResult(e,a){return this.parse(e[0].text,a)}async parseWithPrompt(e,a,n){return this.parse(e,n)}_type(){throw new Error("_type not implemented")}},$=class extends Error{llmOutput;observation;sendToLLM;constructor(e,a,n,r=!1){if(super(e),this.llmOutput=a,this.observation=n,this.sendToLLM=r,r&&(n===void 0||a===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");va(this,"OUTPUT_PARSING_FAILURE")}},Q=class extends ge{async*_transform(e){for await(const a of e)typeof a=="string"?yield this.parseResult([{text:a}]):yield this.parseResult([{message:a,text:this._baseMessageToString(a)}])}async*transform(e,a){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...a,runType:"parser"})}},ke=class extends Q{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let a,n;for await(const r of e){if(typeof r!="string"&&typeof r.content!="string")throw new Error("Cannot handle non-string output.");let i;if(Ea(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");i=new Ge({message:r,text:r.content})}else if(X(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");i=new Ge({message:wa(r),text:r.content})}else i=new Ca({text:r});n===void 0?n=i:n=n.concat(i);const c=await this.parsePartialResult([n]);c!=null&&!Aa(c,a)&&(this.diff?yield this._diff(a,c):yield c,a=c)}}getFormatInstructions(){return""}},ls={};U(ls,{applyPatch:()=>Sa,compare:()=>Oe});var hs=class extends ke{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(e,a){return this.diff?super._concatOutputChunks(e,a):a}_diff(e,a){if(a)return e?Oe(e,a):[{op:"replace",path:"",value:a}]}async parsePartialResult(e){return ve(e[0].text)}async parse(e){return ve(e,JSON.parse)}getFormatInstructions(){return""}},ps=class extends Q{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}},ee=class extends Q{re;async*_transform(e){let a="";for await(const n of e)if(typeof n=="string"?a+=n:a+=n.content,this.re){const r=[...a.matchAll(this.re)];if(r.length>1){let i=0;for(const c of r.slice(0,-1))yield[c[1]],i+=(c.index??0)+c[0].length;a=a.slice(i)}}else{const r=await this.parse(a);if(r.length>1){for(const i of r.slice(0,-1))yield[i];a=r[r.length-1]}}for(const n of await this.parse(a))yield[n]}},gs=class extends ee{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(a=>a.trim())}catch{throw new $(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},ms=class extends ee{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:a}){super(...arguments),this.length=e,this.separator=a||","}async parse(e){try{const a=e.trim().split(this.separator).map(n=>n.trim());if(this.length!==void 0&&a.length!==this.length)throw new $(`Incorrect number of items. Expected ${this.length}, got ${a.length}.`);return a}catch(a){throw Object.getPrototypeOf(a)===$.prototype?a:new $(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},fs=class extends ee{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|