@mcp-use/inspector 0.14.3 → 0.14.4
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/README.md +5 -5
- package/dist/web/assets/{browser-CrZmtltD.js → browser-jWg_baZz.js} +3 -3
- package/dist/web/assets/{client-CsMGnuwC.js → client-DIeD1xny.js} +1 -1
- package/dist/web/assets/{display-A5IEINAP-D8OCMEUd.js → display-A5IEINAP-B68MmzMm.js} +2 -2
- package/dist/web/assets/{embeddings-By0Dfnxp.js → embeddings-Doip16mQ.js} +1 -1
- package/dist/web/assets/{index-DYa4NhVm.js → index-BVVKUeFG.js} +1 -1
- package/dist/web/assets/{index-o8LZS9ZF.js → index-Bs_zxOrk.js} +1 -1
- package/dist/web/assets/{index-D7mhOTIc.js → index-Bx2mJviJ.js} +1 -1
- package/dist/web/assets/{index-BvMdqfyu.js → index-C6J4X9FC.js} +1 -1
- package/dist/web/assets/{index-BxMZcKR4.js → index-CR746V6H.js} +1 -1
- package/dist/web/assets/{index-Cze4GuPX.js → index-CU5SBmNa.js} +1 -1
- package/dist/web/assets/{index-DwWeVml5.js → index-DNAI7hZM.js} +1 -1
- package/dist/web/assets/{index-CaVm3fHm.js → index-VvYXvWPp.js} +1 -1
- package/dist/web/assets/{index-DjkfvIWz.js → index-yO7Y3pL6.js} +76 -76
- package/dist/web/assets/{llms-DCC0HMlB.js → llms-Cqeyha1C.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
|
|
37
37
|
### 📖 Documentation
|
|
38
38
|
|
|
39
|
-
For detailed usage instructions and guides, visit [
|
|
39
|
+
For detailed usage instructions and guides, visit [mcp-use.com/docs/inspector](https://mcp-use.com/docs/inspector)
|
|
40
40
|
|
|
41
41
|
---
|
|
42
42
|
|
|
@@ -319,7 +319,7 @@ Deploy instantly to Railway with automatic HTTPS and custom domains:
|
|
|
319
319
|
|
|
320
320
|
[](https://railway.app/template)
|
|
321
321
|
|
|
322
|
-
For more deployment options and support, visit the [self-hosting documentation](https://
|
|
322
|
+
For more deployment options and support, visit the [self-hosting documentation](https://mcp-use.com/docs/inspector/self-hosting).
|
|
323
323
|
|
|
324
324
|
---
|
|
325
325
|
|
|
@@ -392,9 +392,9 @@ See our [contributing guide](https://github.com/mcp-use/mcp-use/blob/main/CONTRI
|
|
|
392
392
|
|
|
393
393
|
## 📚 Learn More
|
|
394
394
|
|
|
395
|
-
- [Inspector Documentation](https://
|
|
396
|
-
- [Self-Hosting Guide](https://
|
|
397
|
-
- [mcp-use Documentation](https://
|
|
395
|
+
- [Inspector Documentation](https://mcp-use.com/docs/inspector) - Complete usage guide and tutorials
|
|
396
|
+
- [Self-Hosting Guide](https://mcp-use.com/docs/inspector/self-hosting) - Deploy your own instance
|
|
397
|
+
- [mcp-use Documentation](https://mcp-use.com/docs) - Full framework documentation
|
|
398
398
|
- [Model Context Protocol](https://modelcontextprotocol.io) - Official MCP specification
|
|
399
399
|
- [GitHub Repository](https://github.com/mcp-use/mcp-use) - Source code and examples
|
|
400
400
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-
|
|
2
|
-
import{bV as vo,bW as lc,bX as cc,_ as $,bw as ve,bq as y,bB as kr,bY as ke,bZ as Nr,bH as $r,by as uc,bD as hc,bx as dc,b_ as fc,b$ as pc,c0 as mc,p as Ds,bo as gc,c1 as Rr,c2 as bo,a as Ht,bI as Vn}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-DIeD1xny.js","assets/index-yO7Y3pL6.js","assets/index-DlhqMiEp.css","assets/display-A5IEINAP-B68MmzMm.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{bV as vo,bW as lc,bX as cc,_ as $,bw as ve,bq as y,bB as kr,bY as ke,bZ as Nr,bH as $r,by as uc,bD as hc,bx as dc,b_ as fc,b$ as pc,c0 as mc,p as Ds,bo as gc,c1 as Rr,c2 as bo,a as Ht,bI as Vn}from"./index-yO7Y3pL6.js";import{bj as cy,c3 as uy,bp as hy,bs as dy,c4 as fy,c5 as py,br as my,bp as gy,c6 as yy,c7 as wy,c8 as vy,c8 as by}from"./index-yO7Y3pL6.js";import{D as Bn,S as Er,t as yc,a as hi,T as wc,b as vc}from"./index-VvYXvWPp.js";import{h as xn,s as di,g as fi,d as bc,k as _c,l as Sc,I as Cc,C as Tc,m as kc,t as Ec,n as xc,o as Mc,p as Ac,q as Pc,r as Ic,u as Oc,v as Nc,w as $c,x as Rc,y as jc,R as Lc,z as _o,e as Dc}from"./index-Bs_zxOrk.js";import{aT as Fc,aU as Fs,aV as Uc,aw as $e,e as sn,aW as Vc,aX as fn,a4 as ge,y as xe,aY as pi,i as mi,B as I,f as j,aZ as as,g as q,aj as en,ah as ee,S as re,p as Bc,C as zc,a_ as Wc,u as So,aE as gi,a$ as te,al as pn,b0 as cn,F as yi,z as De,b1 as Us,D as ls,E as Gt,ap as lr,b2 as Hc,b3 as Gc,b4 as Kc,b5 as Jc,b6 as qc,b7 as Yc,b8 as Xc,b9 as Zc,ba as Qc,bb as eu,bc as tu,bd as nu,be as ru,bf as su,bg as ou,bh as iu,bi as au,bj as lu,bk as cu,L as uu,bl as hu,bm as du,bn as fu,A as ze,k as un,m as Ve,M as st,at as Kt,bo as pu,H as mu,aF as Co,au as gu,bp as To,bq as ko,af as Vs,ae as cs,ad as us,ag as yu,V as wu,a9 as Bs,ac as et,br as cr,o as B,bs as Se,bt as vu,bu as Ae,bv as Re,bw as bu,U as jr,s as Q,bx as zs,aa as _u,r as Su,ax as Cu,T as Tu,by as Mn,bz as wi,bA as Jt,bB as mn,bC as Ge,bD as ft,bE as V,ab as ku,bF as zn,ai as Eu,bG as vi,bH as An,bI as xu,aP as Mu,aN as Au,aM as Pu,bJ as Iu}from"./index-Bx2mJviJ.js";import{E as bi,c as Ou,e as Nu}from"./embeddings-Doip16mQ.js";import{L as _i,o as $u,l as Ru}from"./llms-Cqeyha1C.js";const ju=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},Lu=()=>{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 ${ju(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${lc(r.values[0])}`:`Invalid option: expected one of ${vo(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":""}: ${vo(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 Du(){return{localeError:Lu()}}cc(Du());var Lr,$n,Dr=0,Fr=0;function Fu(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=Lr),i==null&&(i=$n)),o==null||i==null){var a=t.random||(t.rng||Fc)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Lr&&!t._v6&&(o[0]|=1,Lr=o)),i==null&&(i=(a[6]<<8|a[7])&16383,$n===void 0&&!t._v6&&($n=i))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Fr+1,u=l-Dr+(c-Fr)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||l>Dr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Dr=l,Fr=c,$n=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||Fs(s)}function Uu(t){var e=typeof t=="string"?Uc(t):t,n=Vu(e);return typeof t=="string"?Fs(n):n}function Vu(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 Eo(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 xo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Eo(Object(n),!0).forEach(function(r){Bu(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Eo(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Bu(t,e,n){return(e=zu(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function zu(t){var e=Wu(t,"string");return typeof e=="symbol"?e:e+""}function Wu(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 Hu(t={},e,n=0){var r=Fu(xo(xo({},t),{},{_v6:!0}),new Uint8Array(16));return r=Uu(r),Fs(r)}async function*Gu(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)}}$(Gu,"streamEventsToAISDK");function Ku(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}$(Ku,"createReadableStreamFromGenerator");async function*Ju(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}
|
|
@@ -387,7 +387,7 @@ You can then use these server-specific tools in subsequent steps.
|
|
|
387
387
|
Here are the tools *currently* available to you (this list includes server management tools and will
|
|
388
388
|
change when you connect to a server):
|
|
389
389
|
{tool_descriptions}
|
|
390
|
-
`;function ar(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}}$(ar,"normalizeRunOptions");var Wt,iy=(Wt=class{static getPackageVersion(){return gc()}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 Wg({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 St,this.telemetry=Rr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new li({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=[],y.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 St(this.disallowedTools),this.telemetry=Rr.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 St(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new ai(this.client,this.adapter)}else this.adapter=e.adapter??new St(this.disallowedTools);if(this.telemetry=Rr.getInstance(),this.llm){const[r,s]=bo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new li({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:$(()=>this.getMetadata(),"metadataProvider"),tagsProvider:$(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:$(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:$(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:$(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(y.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(y.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){y.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await Ht(async()=>{const{MCPClient:s}=await import("./client-CsMGnuwC.js");return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),y.info("✅ MCPClient created successfully")}if(this.llmString){y.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await sc(this.llmString,this.llmConfig),y.info("✅ LLM created successfully");const[r,s]=bo(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 ai(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.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),y.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(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.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]),y.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],y.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{y.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),y.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}y.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),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Kg;this.systemMessage=ac(e,n,Jg,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof te))])}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);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Ql({runLimit:this.maxSteps})],s=Nl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.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 te(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof te)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new St(this.disallowedTools),this._initialized&&y.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},y.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])],y.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){y.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?(y.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){y.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else y.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){y.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){y.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 I)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 ee)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 j)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 I||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}=ar(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}=ar(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,p=null,m=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 k=this.serverManager.tools,_=new Set(k.map(x=>x.name)),v=new Set(this._tools.map(x=>x.name));(_.size!==v.size||[..._].some(x=>!v.has(x)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[..._].join(", ")}`),this._tools=k,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const S=c??this.conversationHistory,C=[];for(const k of S)(this._isHumanMessageLike(k)||this._isAIMessageLike(k)||this._isToolMessageLike(k))&&C.push(k);const E=i.length>50?`${i.slice(0,50).replace(/\n/g," ")}...`:i.replace(/\n/g," ");y.info(`💬 Received query: '${E}'`),y.info("🏁 Starting agent execution");const b=3;let w=0;const g=[...C,new ee(i)];for(;w<=b;){const k={messages:g};let _=!1;const v=await this._agentExecutor.stream(k,{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 x of v){for(const[T,M]of Object.entries(x))if(y.debug(`📦 Node '${T}' output: ${JSON.stringify(M)}`),M&&typeof M=="object"&&"messages"in M){let P=M.messages;Array.isArray(P)||(P=[P]);for(const N of P)g.includes(N)||g.push(N);for(const N of P){if("tool_calls"in N&&Array.isArray(N.tool_calls)&&N.tool_calls.length>0)for(const oe of N.tool_calls){const ae=oe.name||"unknown",Ce=oe.args||{};this.toolsUsedNames.push(ae),m++;let Pe=JSON.stringify(Ce);Pe.length>100&&(Pe=`${Pe.slice(0,97)}...`),y.info(`🔧 Tool call: ${ae} with input: ${Pe}`),yield{action:{tool:ae,toolInput:Ce,log:`Calling tool ${ae}`},observation:""}}if(this._isToolMessageLike(N)){const oe=N.content;let ae=String(oe);if(ae.length>100&&(ae=`${ae.slice(0,97)}...`),ae=ae.replace(/\n/g," "),y.info(`📄 Tool result: ${ae}`),this.useServerManager&&this.serverManager){const Ce=this.serverManager.tools,Pe=new Set(Ce.map(nn=>nn.name)),Nn=new Set(this._tools.map(nn=>nn.name));if(Pe.size!==Nn.size||[...Pe].some(nn=>!Nn.has(nn))){y.info(`🔄 Tools changed during execution. New tools: ${[...Pe].join(", ")}`),this._tools=Ce,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),_=!0,w++,y.info(`🔃 Restarting execution with updated tools (restart ${w}/${b})`);break}}}this._isAIMessageLike(N)&&!this._messageHasToolCalls(N)&&(p=this._normalizeOutput(this._getMessageContent(N)),y.info("✅ Agent finished with output"))}if(_)break}if(_)break}if(!_)break;if(w>b){y.warn(`⚠️ Max restarts (${b}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const k=g.slice(C.length);for(const _ of k)this.addToHistory(_)}if(u&&p)try{y.info("🔧 Attempting structured output...");const k=await this._attemptStructuredOutput(p,this.llm,u);return this.memoryEnabled&&this.addToHistory(new I(`Structured result: ${JSON.stringify(k)}`)),y.info("✅ Structured output successful"),f=!0,k}catch(k){throw y.error(`❌ Structured output failed: ${k}`),new Error(`Failed to generate structured output: ${k instanceof Error?k.message:String(k)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,p||"No output generated"}catch(S){throw y.error(`❌ Error running query: ${S}`),h&&l&&(y.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 E=this.memoryEnabled?this.conversationHistory.length:0,b=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:i,success:f,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:C,serverIdentifiers:this.connectors.map(w=>w.publicIdentifier),totalToolsAvailable:b.length,toolsAvailableNames:b.map(w=>w.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:l??!0,externalHistoryUsed:c!==void 0,stepsTaken:m,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:p||"",executionTimeMs:S,errorType:f?null:"execution_error",conversationHistoryLength:E}),l&&!this.client&&h&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(y.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(y.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new St)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Ht(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-D8OCMEUd.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=ar(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 p=!1,m=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 E=this._agentExecutor;if(!E)throw new Error("MCP agent failed to initialize");this.maxSteps=l??this.maxSteps;const b=typeof a=="string"&&a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:typeof a=="string"?a.replace(/\n/g," "):String(a);y.info(`💬 Received query for streamEvents: '${b}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${b}`),this.addToHistory(new ee({content:a})));const w=u??this.conversationHistory,g=[];for(const v of w)this._isHumanMessageLike(v)||this._isAIMessageLike(v)||this._isToolMessageLike(v)?g.push(v):y.info(`⚠️ Skipped message of type: ${v.constructor?.name||typeof v}`);const k=[...g,new ee(a)];y.info("callbacks",this.callbacks);const _=E.streamEvents({messages:k},{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 _)if(m++,!(!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 x=v.data.chunk;if(x.content){C||(C="");const T=this._normalizeOutput(x.content);C+=T,y.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield v,v.event==="on_chain_end"&&v.data?.output&&!C){const x=v.data.output;Array.isArray(x)&&x.length>0&&x[0]?.text?C=x[0].text:typeof x=="string"?C=x:x&&typeof x=="object"&&"output"in x&&(C=x.output)}}if(h&&C){y.info("🔧 Attempting structured output conversion...");try{let v=!1,x=null,T=null;this._attemptStructuredOutput(C,this.llm,h).then(P=>(v=!0,x=P,P)).catch(P=>{throw v=!0,T=P,P});let M=0;for(;!v;)await new Promise(P=>setTimeout(P,2e3)),v||(M++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${M*2}s)`,elapsed:M*2}});if(T)throw T;x&&(yield{event:"on_structured_output",data:{output:x}},this.memoryEnabled&&this.addToHistory(new I(`Structured result: ${JSON.stringify(x)}`)),y.info("✅ Structured output successful"))}catch(v){y.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 I(C));console.log(`
|
|
390
|
+
`;function ar(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}}$(ar,"normalizeRunOptions");var Wt,iy=(Wt=class{static getPackageVersion(){return gc()}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 Wg({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 St,this.telemetry=Rr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new li({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=[],y.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 St(this.disallowedTools),this.telemetry=Rr.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 St(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new ai(this.client,this.adapter)}else this.adapter=e.adapter??new St(this.disallowedTools);if(this.telemetry=Rr.getInstance(),this.llm){const[r,s]=bo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new li({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:$(()=>this.getMetadata(),"metadataProvider"),tagsProvider:$(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:$(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:$(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:$(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(y.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(y.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){y.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await Ht(async()=>{const{MCPClient:s}=await import("./client-DIeD1xny.js");return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),y.info("✅ MCPClient created successfully")}if(this.llmString){y.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await sc(this.llmString,this.llmConfig),y.info("✅ LLM created successfully");const[r,s]=bo(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 ai(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.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),y.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(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.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]),y.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],y.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{y.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),y.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}y.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),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Kg;this.systemMessage=ac(e,n,Jg,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof te))])}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);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Ql({runLimit:this.maxSteps})],s=Nl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.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 te(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof te)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new St(this.disallowedTools),this._initialized&&y.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},y.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])],y.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){y.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?(y.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){y.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else y.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){y.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){y.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 I)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 ee)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 j)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 I||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}=ar(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}=ar(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,p=null,m=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 k=this.serverManager.tools,_=new Set(k.map(x=>x.name)),v=new Set(this._tools.map(x=>x.name));(_.size!==v.size||[..._].some(x=>!v.has(x)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[..._].join(", ")}`),this._tools=k,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const S=c??this.conversationHistory,C=[];for(const k of S)(this._isHumanMessageLike(k)||this._isAIMessageLike(k)||this._isToolMessageLike(k))&&C.push(k);const E=i.length>50?`${i.slice(0,50).replace(/\n/g," ")}...`:i.replace(/\n/g," ");y.info(`💬 Received query: '${E}'`),y.info("🏁 Starting agent execution");const b=3;let w=0;const g=[...C,new ee(i)];for(;w<=b;){const k={messages:g};let _=!1;const v=await this._agentExecutor.stream(k,{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 x of v){for(const[T,M]of Object.entries(x))if(y.debug(`📦 Node '${T}' output: ${JSON.stringify(M)}`),M&&typeof M=="object"&&"messages"in M){let P=M.messages;Array.isArray(P)||(P=[P]);for(const N of P)g.includes(N)||g.push(N);for(const N of P){if("tool_calls"in N&&Array.isArray(N.tool_calls)&&N.tool_calls.length>0)for(const oe of N.tool_calls){const ae=oe.name||"unknown",Ce=oe.args||{};this.toolsUsedNames.push(ae),m++;let Pe=JSON.stringify(Ce);Pe.length>100&&(Pe=`${Pe.slice(0,97)}...`),y.info(`🔧 Tool call: ${ae} with input: ${Pe}`),yield{action:{tool:ae,toolInput:Ce,log:`Calling tool ${ae}`},observation:""}}if(this._isToolMessageLike(N)){const oe=N.content;let ae=String(oe);if(ae.length>100&&(ae=`${ae.slice(0,97)}...`),ae=ae.replace(/\n/g," "),y.info(`📄 Tool result: ${ae}`),this.useServerManager&&this.serverManager){const Ce=this.serverManager.tools,Pe=new Set(Ce.map(nn=>nn.name)),Nn=new Set(this._tools.map(nn=>nn.name));if(Pe.size!==Nn.size||[...Pe].some(nn=>!Nn.has(nn))){y.info(`🔄 Tools changed during execution. New tools: ${[...Pe].join(", ")}`),this._tools=Ce,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),_=!0,w++,y.info(`🔃 Restarting execution with updated tools (restart ${w}/${b})`);break}}}this._isAIMessageLike(N)&&!this._messageHasToolCalls(N)&&(p=this._normalizeOutput(this._getMessageContent(N)),y.info("✅ Agent finished with output"))}if(_)break}if(_)break}if(!_)break;if(w>b){y.warn(`⚠️ Max restarts (${b}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const k=g.slice(C.length);for(const _ of k)this.addToHistory(_)}if(u&&p)try{y.info("🔧 Attempting structured output...");const k=await this._attemptStructuredOutput(p,this.llm,u);return this.memoryEnabled&&this.addToHistory(new I(`Structured result: ${JSON.stringify(k)}`)),y.info("✅ Structured output successful"),f=!0,k}catch(k){throw y.error(`❌ Structured output failed: ${k}`),new Error(`Failed to generate structured output: ${k instanceof Error?k.message:String(k)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,p||"No output generated"}catch(S){throw y.error(`❌ Error running query: ${S}`),h&&l&&(y.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 E=this.memoryEnabled?this.conversationHistory.length:0,b=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:i,success:f,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:C,serverIdentifiers:this.connectors.map(w=>w.publicIdentifier),totalToolsAvailable:b.length,toolsAvailableNames:b.map(w=>w.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:l??!0,externalHistoryUsed:c!==void 0,stepsTaken:m,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:p||"",executionTimeMs:S,errorType:f?null:"execution_error",conversationHistoryLength:E}),l&&!this.client&&h&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(y.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(y.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new St)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Ht(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-B68MmzMm.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=ar(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 p=!1,m=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 E=this._agentExecutor;if(!E)throw new Error("MCP agent failed to initialize");this.maxSteps=l??this.maxSteps;const b=typeof a=="string"&&a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:typeof a=="string"?a.replace(/\n/g," "):String(a);y.info(`💬 Received query for streamEvents: '${b}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${b}`),this.addToHistory(new ee({content:a})));const w=u??this.conversationHistory,g=[];for(const v of w)this._isHumanMessageLike(v)||this._isAIMessageLike(v)||this._isToolMessageLike(v)?g.push(v):y.info(`⚠️ Skipped message of type: ${v.constructor?.name||typeof v}`);const k=[...g,new ee(a)];y.info("callbacks",this.callbacks);const _=E.streamEvents({messages:k},{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 _)if(m++,!(!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 x=v.data.chunk;if(x.content){C||(C="");const T=this._normalizeOutput(x.content);C+=T,y.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield v,v.event==="on_chain_end"&&v.data?.output&&!C){const x=v.data.output;Array.isArray(x)&&x.length>0&&x[0]?.text?C=x[0].text:typeof x=="string"?C=x:x&&typeof x=="object"&&"output"in x&&(C=x.output)}}if(h&&C){y.info("🔧 Attempting structured output conversion...");try{let v=!1,x=null,T=null;this._attemptStructuredOutput(C,this.llm,h).then(P=>(v=!0,x=P,P)).catch(P=>{throw v=!0,T=P,P});let M=0;for(;!v;)await new Promise(P=>setTimeout(P,2e3)),v||(M++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${M*2}s)`,elapsed:M*2}});if(T)throw T;x&&(yield{event:"on_structured_output",data:{output:x}},this.memoryEnabled&&this.addToHistory(new I(`Structured result: ${JSON.stringify(x)}`)),y.info("✅ Structured output successful"))}catch(v){y.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 I(C));console.log(`
|
|
391
391
|
|
|
392
392
|
`),y.info(`🎉 StreamEvents complete - ${m} events emitted`),p=!0}catch(E){throw y.error(`❌ Error during streamEvents: ${E}`),d&&c&&(y.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),E}finally{const E=Date.now()-f;let b=0;this.client?b=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(b=this.connectors.length);const w=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:a,success:p,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:b,serverIdentifiers:this.connectors.map(g=>g.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(g=>g.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:E,errorType:p?null:"streaming_error",conversationHistoryLength:w}),c&&!this.client&&d&&(y.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){y.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),y.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,o="";if(y.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Vn(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=Vn(r),{$schema:a,additionalProperties:l,...c}=i;o=JSON.stringify(c,null,2),y.info(`🔄 Schema description: ${o}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),y.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){y.info(`🔄 Structured output attempt ${f}/${h}`);let p=`
|
|
393
393
|
Please format the following information according to the EXACT schema specified below.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{bj as me,_ as w,bk as Y,bl as We,bm as ze,bn as Ge,bo as _e,bp as Ye,bq as m,br as Xe,bs as Ze,a as Qe,bt as et,bu as re,bv as tt}from"./index-DjkfvIWz.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}`)}},w(O,"CodeModeConnector"),O);function X(){throw new Error("fs.readFileSync is not available in browser environment")}function ve(){throw new Error("fs.writeFileSync is not available in browser environment")}function we(){return!1}function ge(){throw new Error("fs.readFile is not available in browser environment")}function be(){throw new Error("fs.writeFile is not available in browser environment")}function ye(){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 j={readFileSync:X,writeFileSync:ve,existsSync:we,readFile:ge,writeFile:be,mkdir:ye,readdir:xe,stat:Ce,unlink:Se,rmdir:Ee},rt=Object.freeze(Object.defineProperty({__proto__:null,default:j,existsSync:we,mkdir:ye,readFile:ge,readFileSync:X,readdir:xe,rmdir:Ee,stat:Ce,unlink:Se,writeFile:be,writeFileSync:ve},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 ke="/",Ne=":",$e={join:Z,resolve:Me,dirname:Q,basename:q,extname:ee,normalize:Te,isAbsolute:Pe,parse:Oe,sep:ke,delimiter:Ne},ot=Object.freeze(Object.defineProperty({__proto__:null,basename:q,default:$e,delimiter:Ne,dirname:Q,extname:ee,isAbsolute:Pe,join:Z,normalize:Te,parse:Oe,resolve:Me,sep:ke},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,L={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 je(){throw new Error("child_process.fork is not available in browser environment")}function Le(){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:je,execSync:Le,spawnSync:qe,execFileSync:Fe},ft=Object.freeze(Object.defineProperty({__proto__:null,default:ht,exec:Ie,execFile:Re,execFileSync:Fe,execSync:Le,fork:je,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),b=h|f,_=a&p||a&f&&c===d||a&h&&l===u||a&b&&u===0;return _}return J}var U,ie;function vt(){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 wt(){if(ce)return V;ce=1;var s={};const e=s.OSTYPE==="cygwin"||s.OSTYPE==="msys",t=Be,n=e?";":":",r=vt(),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),b=[],_=v=>new Promise((y,g)=>{if(v===h.length)return u.all&&b.length?y(b):g(o(c));const x=h[v],S=/^".*"$/.test(x)?x.slice(1,-1):x,P=t.join(S,c),B=!S&&/^\.[\\\/]/.test(c)?c.slice(0,2)+P:P;y(C(B,v,0))}),C=(v,y,g)=>new Promise((x,S)=>{if(g===f.length)return x(_(y+1));const P=f[g];r(v+P,{pathExt:p},(B,He)=>{if(!B&&He)if(u.all)b.push(v+P);else return x(v+P);return x(C(v,y,g+1))})});return d?_(0).then(v=>d(null,v),d):_(0)},l=(c,u)=>{u=u||{};const{pathEnv:d,pathExt:h,pathExtExe:f}=i(c,u),p=[];for(let b=0;b<d.length;b++){const _=d[b],C=/^".*"$/.test(_)?_.slice(1,-1):_,v=t.join(C,c),y=!C&&/^\.[\\\/]/.test(c)?c.slice(0,2)+v:v;for(let g=0;g<h.length;g++){const x=y+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 K,le;function bt(){if(le)return K;le=1;var s={};const e=Be,t=wt(),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 K=o,K}var H,ue;function yt(){if(ue)return H;ue=1,bt();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 H=e,H}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=yt(),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{bj as me,_ as w,bk as Y,bl as We,bm as ze,bn as Ge,bo as _e,bp as Ye,bq as m,br as Xe,bs as Ze,a as Qe,bt as et,bu as re,bv as tt}from"./index-yO7Y3pL6.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}`)}},w(O,"CodeModeConnector"),O);function X(){throw new Error("fs.readFileSync is not available in browser environment")}function ve(){throw new Error("fs.writeFileSync is not available in browser environment")}function we(){return!1}function ge(){throw new Error("fs.readFile is not available in browser environment")}function be(){throw new Error("fs.writeFile is not available in browser environment")}function ye(){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 j={readFileSync:X,writeFileSync:ve,existsSync:we,readFile:ge,writeFile:be,mkdir:ye,readdir:xe,stat:Ce,unlink:Se,rmdir:Ee},rt=Object.freeze(Object.defineProperty({__proto__:null,default:j,existsSync:we,mkdir:ye,readFile:ge,readFileSync:X,readdir:xe,rmdir:Ee,stat:Ce,unlink:Se,writeFile:be,writeFileSync:ve},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 ke="/",Ne=":",$e={join:Z,resolve:Me,dirname:Q,basename:q,extname:ee,normalize:Te,isAbsolute:Pe,parse:Oe,sep:ke,delimiter:Ne},ot=Object.freeze(Object.defineProperty({__proto__:null,basename:q,default:$e,delimiter:Ne,dirname:Q,extname:ee,isAbsolute:Pe,join:Z,normalize:Te,parse:Oe,resolve:Me,sep:ke},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,L={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 je(){throw new Error("child_process.fork is not available in browser environment")}function Le(){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:je,execSync:Le,spawnSync:qe,execFileSync:Fe},ft=Object.freeze(Object.defineProperty({__proto__:null,default:ht,exec:Ie,execFile:Re,execFileSync:Fe,execSync:Le,fork:je,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),b=h|f,_=a&p||a&f&&c===d||a&h&&l===u||a&b&&u===0;return _}return J}var U,ie;function vt(){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 wt(){if(ce)return V;ce=1;var s={};const e=s.OSTYPE==="cygwin"||s.OSTYPE==="msys",t=Be,n=e?";":":",r=vt(),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),b=[],_=v=>new Promise((y,g)=>{if(v===h.length)return u.all&&b.length?y(b):g(o(c));const x=h[v],S=/^".*"$/.test(x)?x.slice(1,-1):x,P=t.join(S,c),B=!S&&/^\.[\\\/]/.test(c)?c.slice(0,2)+P:P;y(C(B,v,0))}),C=(v,y,g)=>new Promise((x,S)=>{if(g===f.length)return x(_(y+1));const P=f[g];r(v+P,{pathExt:p},(B,He)=>{if(!B&&He)if(u.all)b.push(v+P);else return x(v+P);return x(C(v,y,g+1))})});return d?_(0).then(v=>d(null,v),d):_(0)},l=(c,u)=>{u=u||{};const{pathEnv:d,pathExt:h,pathExtExe:f}=i(c,u),p=[];for(let b=0;b<d.length;b++){const _=d[b],C=/^".*"$/.test(_)?_.slice(1,-1):_,v=t.join(C,c),y=!C&&/^\.[\\\/]/.test(c)?c.slice(0,2)+v:v;for(let g=0;g<h.length;g++){const x=y+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 K,le;function bt(){if(le)return K;le=1;var s={};const e=Be,t=wt(),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 K=o,K}var H,ue;function yt(){if(ue)return H;ue=1,bt();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 H=e,H}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=yt(),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 kt=["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Nt(){const s={};for(const e of kt){const t=L.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:{...Nt(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:L.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={},k,te=(k=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}}}},w(k,"BaseCodeExecutor"),k),N,fe=(N=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-CU5SBmNa.js","assets/index-yO7Y3pL6.js","assets/index-DlhqMiEp.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as a,a as k}from"./index-yO7Y3pL6.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-CU5SBmNa.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-Bx2mJviJ.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,2 +1,2 @@
|
|
|
1
|
-
import{c as at,f as rt,g as mt,O as Ct,h as Ot,J as yt,R as G}from"./index-o8LZS9ZF.js";import{i as ut,y as It,z as vt,B as _t,D as Et,E as Tt,F as wt,H as St,t as lt,I as Rt,J as At,K as x,r as xt,L as kt,M as Nt}from"./index-D7mhOTIc.js";import"./embeddings-By0Dfnxp.js";import"./index-DjkfvIWz.js";function I(t){if(typeof t=="object"&&t!==null){const e={...t};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(const n in e)n in e&&(Array.isArray(e[n])?e[n]=e[n].map(I):typeof e[n]=="object"&&e[n]!==null&&(e[n]=I(e[n])));return e}return t}function N(t){const e=I(ut(t)?It(t):t),{$schema:n,...s}=e;return s}function bt(t){const e=I(t),{$schema:n,...s}=e;return s}const h=[];for(let t=0;t<256;++t)h.push((t+256).toString(16).slice(1));function Mt(t,e=0){return(h[t[e+0]]+h[t[e+1]]+h[t[e+2]]+h[t[e+3]]+"-"+h[t[e+4]]+h[t[e+5]]+"-"+h[t[e+6]]+h[t[e+7]]+"-"+h[t[e+8]]+h[t[e+9]]+"-"+h[t[e+10]]+h[t[e+11]]+h[t[e+12]]+h[t[e+13]]+h[t[e+14]]+h[t[e+15]]).toLowerCase()}let k;const Dt=new Uint8Array(16);function Gt(){if(!k){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");k=crypto.getRandomValues.bind(crypto)}return k(Dt)}const Ut=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),U={randomUUID:Ut};function ct(t,e,n){if(U.randomUUID&&!t)return U.randomUUID();t=t||{};const s=t.random??t.rng?.()??Gt();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,Mt(s)}const b="__gemini_function_call_thought_signatures__",Lt="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",Pt=t=>t();function jt(t){return wt.isInstance(t)?t.role:t.type}function Ft(t){switch(t){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${t}`)}}function Kt(t){if("mimeType"in t&&"data"in t)return{inlineData:{mimeType:t.mimeType,data:t.data}};if("mimeType"in t&&"fileUri"in t)return{fileData:{mimeType:t.mimeType,fileUri:t.fileUri}};throw new Error("Invalid media content")}function Ht(t,e){return e.map(n=>lt(n)?n.tool_calls??[]:[]).flat().find(n=>n.id===t.tool_call_id)?.name}function $t(t){return{providerName:"Google Gemini",fromStandardTextBlock(n){return{text:n.text}},fromStandardImageBlock(n){if(!t)throw new Error("This model does not support images");if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)},fromStandardAudioBlock(n){if(!t)throw new Error("This model does not support audio");if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)},fromStandardFileBlock(n){if(!t)throw new Error("This model does not support files");if(n.source_type==="text")return{text:n.text};if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)}}}function L(t,e){if(Rt(t))return At(t,$t(e));if(t.type==="text")return{text:t.text};if(t.type==="executableCode")return{executableCode:t.executableCode};if(t.type==="codeExecutionResult")return{codeExecutionResult:t.codeExecutionResult};if(t.type==="image_url"){if(!e)throw new Error("This model does not support images");let n;if(typeof t.image_url=="string")n=t.image_url;else if(typeof t.image_url=="object"&&"url"in t.image_url)n=t.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[s,i]=n.split(",");if(!s.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[o,a]=s.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:i,mimeType:o}}}else{if(t.type==="media")return Kt(t);if(t.type==="tool_use")return{functionCall:{name:t.name,args:t.input}};if(t.type?.includes("/")&&t.type.split("/").length===2&&"data"in t&&typeof t.data=="string")return{inlineData:{mimeType:t.type,data:t.data}};if("functionCall"in t)return;throw"type"in t?new Error(`Unknown content type ${t.type}`):new Error(`Unknown content ${JSON.stringify(t)}`)}}function Yt(t,e,n,s){if(St(t)){const u=t.name??Ht(t,n);if(u===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${t.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const c=Array.isArray(t.content)?t.content.map(p=>L(p,e)).filter(p=>p!==void 0):t.content;return t.status==="error"?[{functionResponse:{name:u,response:{error:{details:c}}}}]:[{functionResponse:{name:u,response:{result:c}}}]}let i=[];const o=[];typeof t.content=="string"&&t.content&&o.push({text:t.content}),Array.isArray(t.content)&&o.push(...t.content.map(u=>L(u,e)).filter(u=>u!==void 0));const a=t.additional_kwargs?.[b];return lt(t)&&t.tool_calls?.length&&(i=t.tool_calls.map(u=>{const c=Pt(()=>{if(u.id){const p=a?.[u.id];if(p)return p}return s?.includes("gemini-3")?Lt:""});return{functionCall:{name:u.name,args:u.args},...c?{thoughtSignature:c}:{}}})),[...o,...i]}function P(t,e,n=!1,s){return t.reduce((i,o,a)=>{if(!vt(o))throw new Error("Unsupported message input");const u=jt(o);if(u==="system"&&a!==0)throw new Error("System message should be the first one");const c=Ft(u),p=i.content[i.content.length];if(!i.mergeWithPreviousContent&&p&&p.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Yt(o,e,t.slice(0,a),s);if(i.mergeWithPreviousContent){const d=i.content[i.content.length-1];if(!d)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return d.parts.push(...r),{mergeWithPreviousContent:!1,content:i.content}}let l=c;(l==="function"||l==="system"&&!n)&&(l="user");const f={role:l,parts:r};return{mergeWithPreviousContent:u==="system"&&!n,content:[...i.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function Bt(t,e){if(!t.candidates||t.candidates.length===0||!t.candidates[0])return{generations:[],llmOutput:{filters:t.promptFeedback}};const[n]=t.candidates,{content:s,...i}=n,o=s.parts?.reduce((r,l)=>("functionCall"in l&&l.functionCall&&r.push({...l,id:"id"in l.functionCall&&typeof l.functionCall.id=="string"?l.functionCall.id:ct()}),r),[]);let a;Array.isArray(s?.parts)&&s.parts.length===1&&s.parts[0].text?a=s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];const u=o?.reduce((r,l)=>("thoughtSignature"in l&&typeof l.thoughtSignature=="string"&&(r[l.id]=l.thoughtSignature),r),{});let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(l=>"text"in l)?.text??c),{generations:[{text:c,message:new _t({content:a??"",tool_calls:o?.map(r=>({type:"tool_call",id:r.id,name:r.functionCall.name,args:r.functionCall.args})),additional_kwargs:{...i,[b]:u},usage_metadata:e?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:e?.usageMetadata?.input_tokens,completionTokens:e?.usageMetadata?.output_tokens,totalTokens:e?.usageMetadata?.total_tokens}}}}function qt(t,e){if(!t.candidates||t.candidates.length===0)return null;const[n]=t.candidates,{content:s,...i}=n,o=s.parts?.reduce((r,l)=>("functionCall"in l&&l.functionCall&&r.push({...l,id:"id"in l.functionCall&&typeof l.functionCall.id=="string"?l.functionCall.id:ct()}),r),[]);let a;Array.isArray(s?.parts)&&s.parts.every(r=>"text"in r)?a=s.parts.map(r=>r.text).join(""):Array.isArray(s?.parts)?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let u="";a&&typeof a=="string"?u=a:Array.isArray(a)&&(u=a.find(l=>"text"in l)?.text??"");const c=[];o&&c.push(...o.map(r=>({type:"tool_call_chunk",id:r.id,name:r.functionCall.name,args:JSON.stringify(r.functionCall.args)})));const p=o?.reduce((r,l)=>("thoughtSignature"in l&&typeof l.thoughtSignature=="string"&&(r[l.id]=l.thoughtSignature),r),{});return new Et({text:u,message:new Tt({content:a||"",name:s?s.role:void 0,tool_call_chunks:c,additional_kwargs:{[b]:p},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:i})}function Wt(t){return t.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?t:[{functionDeclarations:t.map(e=>{if(at(e)){const n=N(e.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:e.name,description:e.description}:{name:e.name,description:e.description,parameters:n}}return rt(e)?{name:e.function.name,description:e.function.description??"A function available to call.",parameters:bt(e.function.parameters)}:e})}]}function j(t,e){const n={input_tokens:t?.promptTokenCount??0,output_tokens:t?.candidatesTokenCount??0,total_tokens:t?.totalTokenCount??0};if(t?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=t.cachedContentTokenCount),e==="gemini-3-pro-preview"){const s=Math.max(0,t?.promptTokenCount??-2e5),i=Math.max(0,t?.cachedContentTokenCount??-2e5);s&&(n.input_token_details={...n.input_token_details,over_200k:s}),i&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:i})}return n}var F=class extends mt{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;const e=await xt(this.zodSchema,t);if(e.success)return e.data;throw new Ct(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(t){const e=t.flatMap(i=>{const{message:o}=i;return!("tool_calls"in o)||!Array.isArray(o.tool_calls)?[]:o.tool_calls});if(e[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}},K;(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(K||(K={}));var H;(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})(H||(H={}));var $;(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})($||($={}));const Y=["user","model","function","system"];var B;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(B||(B={}));var q;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(q||(q={}));var W;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(W||(W={}));var V;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(V||(V={}));var T;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.OTHER="OTHER"})(T||(T={}));var J;(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(J||(J={}));var E;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(E||(E={}));var z;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(z||(z={}));class m extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class _ extends m{constructor(e,n){super(e),this.response=n}}class dt extends m{constructor(e,n,s,i){super(e),this.status=n,this.statusText=s,this.errorDetails=i}}class y extends m{}class ft extends m{}const Vt="https://generativelanguage.googleapis.com",Jt="v1beta",zt="0.24.1",Zt="genai-js";var v;(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(v||(v={}));class Qt{constructor(e,n,s,i,o){this.model=e,this.task=n,this.apiKey=s,this.stream=i,this.requestOptions=o}toString(){var e,n;const s=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||Jt;let o=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||Vt}/${s}/${this.model}:${this.task}`;return this.stream&&(o+="?alt=sse"),o}}function Xt(t){const e=[];return t?.apiClient&&e.push(t.apiClient),e.push(`${Zt}/${zt}`),e.join(" ")}async function te(t){var e;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",Xt(t.requestOptions)),n.append("x-goog-api-key",t.apiKey);let s=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(s){if(!(s instanceof Headers))try{s=new Headers(s)}catch(i){throw new y(`unable to convert customHeaders value ${JSON.stringify(s)} to Headers: ${i.message}`)}for(const[i,o]of s.entries()){if(i==="x-goog-api-key")throw new y(`Cannot set reserved header name ${i}`);if(i==="x-goog-api-client")throw new y(`Header name ${i} can only be set using the apiClient field`);n.append(i,o)}}return n}async function ee(t,e,n,s,i,o){const a=new Qt(t,e,n,s,o);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},oe(o)),{method:"POST",headers:await te(a),body:i})}}async function R(t,e,n,s,i,o={},a=fetch){const{url:u,fetchOptions:c}=await ee(t,e,n,s,i,o);return ne(u,c,a)}async function ne(t,e,n=fetch){let s;try{s=await n(t,e)}catch(i){se(i,t)}return s.ok||await ie(s,t),s}function se(t,e){let n=t;throw n.name==="AbortError"?(n=new ft(`Request aborted when fetching ${e.toString()}: ${t.message}`),n.stack=t.stack):t instanceof dt||t instanceof y||(n=new m(`Error fetching from ${e.toString()}: ${t.message}`),n.stack=t.stack),n}async function ie(t,e){let n="",s;try{const i=await t.json();n=i.error.message,i.error.details&&(n+=` ${JSON.stringify(i.error.details)}`,s=i.error.details)}catch{}throw new dt(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${n}`,t.status,t.statusText,s)}function oe(t){const e={};if(t?.signal!==void 0||t?.timeout>=0){const n=new AbortController;t?.timeout>=0&&setTimeout(()=>n.abort(),t.timeout),t?.signal&&t.signal.addEventListener("abort",()=>{n.abort()}),e.signal=n.signal}return e}function M(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return ae(t)}else if(t.promptFeedback)throw new _(`Text not available. ${O(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),Z(t)[0]}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return Z(t)}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t}function ae(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.text&&o.push(a.text),a.executableCode&&o.push("\n```"+a.executableCode.language+`
|
|
1
|
+
import{c as at,f as rt,g as mt,O as Ct,h as Ot,J as yt,R as G}from"./index-Bs_zxOrk.js";import{i as ut,y as It,z as vt,B as _t,D as Et,E as Tt,F as wt,H as St,t as lt,I as Rt,J as At,K as x,r as xt,L as kt,M as Nt}from"./index-Bx2mJviJ.js";import"./embeddings-Doip16mQ.js";import"./index-yO7Y3pL6.js";function I(t){if(typeof t=="object"&&t!==null){const e={...t};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(const n in e)n in e&&(Array.isArray(e[n])?e[n]=e[n].map(I):typeof e[n]=="object"&&e[n]!==null&&(e[n]=I(e[n])));return e}return t}function N(t){const e=I(ut(t)?It(t):t),{$schema:n,...s}=e;return s}function bt(t){const e=I(t),{$schema:n,...s}=e;return s}const h=[];for(let t=0;t<256;++t)h.push((t+256).toString(16).slice(1));function Mt(t,e=0){return(h[t[e+0]]+h[t[e+1]]+h[t[e+2]]+h[t[e+3]]+"-"+h[t[e+4]]+h[t[e+5]]+"-"+h[t[e+6]]+h[t[e+7]]+"-"+h[t[e+8]]+h[t[e+9]]+"-"+h[t[e+10]]+h[t[e+11]]+h[t[e+12]]+h[t[e+13]]+h[t[e+14]]+h[t[e+15]]).toLowerCase()}let k;const Dt=new Uint8Array(16);function Gt(){if(!k){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");k=crypto.getRandomValues.bind(crypto)}return k(Dt)}const Ut=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),U={randomUUID:Ut};function ct(t,e,n){if(U.randomUUID&&!t)return U.randomUUID();t=t||{};const s=t.random??t.rng?.()??Gt();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,Mt(s)}const b="__gemini_function_call_thought_signatures__",Lt="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",Pt=t=>t();function jt(t){return wt.isInstance(t)?t.role:t.type}function Ft(t){switch(t){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${t}`)}}function Kt(t){if("mimeType"in t&&"data"in t)return{inlineData:{mimeType:t.mimeType,data:t.data}};if("mimeType"in t&&"fileUri"in t)return{fileData:{mimeType:t.mimeType,fileUri:t.fileUri}};throw new Error("Invalid media content")}function Ht(t,e){return e.map(n=>lt(n)?n.tool_calls??[]:[]).flat().find(n=>n.id===t.tool_call_id)?.name}function $t(t){return{providerName:"Google Gemini",fromStandardTextBlock(n){return{text:n.text}},fromStandardImageBlock(n){if(!t)throw new Error("This model does not support images");if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)},fromStandardAudioBlock(n){if(!t)throw new Error("This model does not support audio");if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)},fromStandardFileBlock(n){if(!t)throw new Error("This model does not support files");if(n.source_type==="text")return{text:n.text};if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)}}}function L(t,e){if(Rt(t))return At(t,$t(e));if(t.type==="text")return{text:t.text};if(t.type==="executableCode")return{executableCode:t.executableCode};if(t.type==="codeExecutionResult")return{codeExecutionResult:t.codeExecutionResult};if(t.type==="image_url"){if(!e)throw new Error("This model does not support images");let n;if(typeof t.image_url=="string")n=t.image_url;else if(typeof t.image_url=="object"&&"url"in t.image_url)n=t.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[s,i]=n.split(",");if(!s.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[o,a]=s.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:i,mimeType:o}}}else{if(t.type==="media")return Kt(t);if(t.type==="tool_use")return{functionCall:{name:t.name,args:t.input}};if(t.type?.includes("/")&&t.type.split("/").length===2&&"data"in t&&typeof t.data=="string")return{inlineData:{mimeType:t.type,data:t.data}};if("functionCall"in t)return;throw"type"in t?new Error(`Unknown content type ${t.type}`):new Error(`Unknown content ${JSON.stringify(t)}`)}}function Yt(t,e,n,s){if(St(t)){const u=t.name??Ht(t,n);if(u===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${t.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const c=Array.isArray(t.content)?t.content.map(p=>L(p,e)).filter(p=>p!==void 0):t.content;return t.status==="error"?[{functionResponse:{name:u,response:{error:{details:c}}}}]:[{functionResponse:{name:u,response:{result:c}}}]}let i=[];const o=[];typeof t.content=="string"&&t.content&&o.push({text:t.content}),Array.isArray(t.content)&&o.push(...t.content.map(u=>L(u,e)).filter(u=>u!==void 0));const a=t.additional_kwargs?.[b];return lt(t)&&t.tool_calls?.length&&(i=t.tool_calls.map(u=>{const c=Pt(()=>{if(u.id){const p=a?.[u.id];if(p)return p}return s?.includes("gemini-3")?Lt:""});return{functionCall:{name:u.name,args:u.args},...c?{thoughtSignature:c}:{}}})),[...o,...i]}function P(t,e,n=!1,s){return t.reduce((i,o,a)=>{if(!vt(o))throw new Error("Unsupported message input");const u=jt(o);if(u==="system"&&a!==0)throw new Error("System message should be the first one");const c=Ft(u),p=i.content[i.content.length];if(!i.mergeWithPreviousContent&&p&&p.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Yt(o,e,t.slice(0,a),s);if(i.mergeWithPreviousContent){const d=i.content[i.content.length-1];if(!d)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return d.parts.push(...r),{mergeWithPreviousContent:!1,content:i.content}}let l=c;(l==="function"||l==="system"&&!n)&&(l="user");const f={role:l,parts:r};return{mergeWithPreviousContent:u==="system"&&!n,content:[...i.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function Bt(t,e){if(!t.candidates||t.candidates.length===0||!t.candidates[0])return{generations:[],llmOutput:{filters:t.promptFeedback}};const[n]=t.candidates,{content:s,...i}=n,o=s.parts?.reduce((r,l)=>("functionCall"in l&&l.functionCall&&r.push({...l,id:"id"in l.functionCall&&typeof l.functionCall.id=="string"?l.functionCall.id:ct()}),r),[]);let a;Array.isArray(s?.parts)&&s.parts.length===1&&s.parts[0].text?a=s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];const u=o?.reduce((r,l)=>("thoughtSignature"in l&&typeof l.thoughtSignature=="string"&&(r[l.id]=l.thoughtSignature),r),{});let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(l=>"text"in l)?.text??c),{generations:[{text:c,message:new _t({content:a??"",tool_calls:o?.map(r=>({type:"tool_call",id:r.id,name:r.functionCall.name,args:r.functionCall.args})),additional_kwargs:{...i,[b]:u},usage_metadata:e?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:e?.usageMetadata?.input_tokens,completionTokens:e?.usageMetadata?.output_tokens,totalTokens:e?.usageMetadata?.total_tokens}}}}function qt(t,e){if(!t.candidates||t.candidates.length===0)return null;const[n]=t.candidates,{content:s,...i}=n,o=s.parts?.reduce((r,l)=>("functionCall"in l&&l.functionCall&&r.push({...l,id:"id"in l.functionCall&&typeof l.functionCall.id=="string"?l.functionCall.id:ct()}),r),[]);let a;Array.isArray(s?.parts)&&s.parts.every(r=>"text"in r)?a=s.parts.map(r=>r.text).join(""):Array.isArray(s?.parts)?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let u="";a&&typeof a=="string"?u=a:Array.isArray(a)&&(u=a.find(l=>"text"in l)?.text??"");const c=[];o&&c.push(...o.map(r=>({type:"tool_call_chunk",id:r.id,name:r.functionCall.name,args:JSON.stringify(r.functionCall.args)})));const p=o?.reduce((r,l)=>("thoughtSignature"in l&&typeof l.thoughtSignature=="string"&&(r[l.id]=l.thoughtSignature),r),{});return new Et({text:u,message:new Tt({content:a||"",name:s?s.role:void 0,tool_call_chunks:c,additional_kwargs:{[b]:p},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:i})}function Wt(t){return t.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?t:[{functionDeclarations:t.map(e=>{if(at(e)){const n=N(e.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:e.name,description:e.description}:{name:e.name,description:e.description,parameters:n}}return rt(e)?{name:e.function.name,description:e.function.description??"A function available to call.",parameters:bt(e.function.parameters)}:e})}]}function j(t,e){const n={input_tokens:t?.promptTokenCount??0,output_tokens:t?.candidatesTokenCount??0,total_tokens:t?.totalTokenCount??0};if(t?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=t.cachedContentTokenCount),e==="gemini-3-pro-preview"){const s=Math.max(0,t?.promptTokenCount??-2e5),i=Math.max(0,t?.cachedContentTokenCount??-2e5);s&&(n.input_token_details={...n.input_token_details,over_200k:s}),i&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:i})}return n}var F=class extends mt{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;const e=await xt(this.zodSchema,t);if(e.success)return e.data;throw new Ct(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(t){const e=t.flatMap(i=>{const{message:o}=i;return!("tool_calls"in o)||!Array.isArray(o.tool_calls)?[]:o.tool_calls});if(e[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}},K;(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(K||(K={}));var H;(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})(H||(H={}));var $;(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})($||($={}));const Y=["user","model","function","system"];var B;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(B||(B={}));var q;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(q||(q={}));var W;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(W||(W={}));var V;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(V||(V={}));var T;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.OTHER="OTHER"})(T||(T={}));var J;(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(J||(J={}));var E;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(E||(E={}));var z;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(z||(z={}));class m extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class _ extends m{constructor(e,n){super(e),this.response=n}}class dt extends m{constructor(e,n,s,i){super(e),this.status=n,this.statusText=s,this.errorDetails=i}}class y extends m{}class ft extends m{}const Vt="https://generativelanguage.googleapis.com",Jt="v1beta",zt="0.24.1",Zt="genai-js";var v;(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(v||(v={}));class Qt{constructor(e,n,s,i,o){this.model=e,this.task=n,this.apiKey=s,this.stream=i,this.requestOptions=o}toString(){var e,n;const s=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||Jt;let o=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||Vt}/${s}/${this.model}:${this.task}`;return this.stream&&(o+="?alt=sse"),o}}function Xt(t){const e=[];return t?.apiClient&&e.push(t.apiClient),e.push(`${Zt}/${zt}`),e.join(" ")}async function te(t){var e;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",Xt(t.requestOptions)),n.append("x-goog-api-key",t.apiKey);let s=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(s){if(!(s instanceof Headers))try{s=new Headers(s)}catch(i){throw new y(`unable to convert customHeaders value ${JSON.stringify(s)} to Headers: ${i.message}`)}for(const[i,o]of s.entries()){if(i==="x-goog-api-key")throw new y(`Cannot set reserved header name ${i}`);if(i==="x-goog-api-client")throw new y(`Header name ${i} can only be set using the apiClient field`);n.append(i,o)}}return n}async function ee(t,e,n,s,i,o){const a=new Qt(t,e,n,s,o);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},oe(o)),{method:"POST",headers:await te(a),body:i})}}async function R(t,e,n,s,i,o={},a=fetch){const{url:u,fetchOptions:c}=await ee(t,e,n,s,i,o);return ne(u,c,a)}async function ne(t,e,n=fetch){let s;try{s=await n(t,e)}catch(i){se(i,t)}return s.ok||await ie(s,t),s}function se(t,e){let n=t;throw n.name==="AbortError"?(n=new ft(`Request aborted when fetching ${e.toString()}: ${t.message}`),n.stack=t.stack):t instanceof dt||t instanceof y||(n=new m(`Error fetching from ${e.toString()}: ${t.message}`),n.stack=t.stack),n}async function ie(t,e){let n="",s;try{const i=await t.json();n=i.error.message,i.error.details&&(n+=` ${JSON.stringify(i.error.details)}`,s=i.error.details)}catch{}throw new dt(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${n}`,t.status,t.statusText,s)}function oe(t){const e={};if(t?.signal!==void 0||t?.timeout>=0){const n=new AbortController;t?.timeout>=0&&setTimeout(()=>n.abort(),t.timeout),t?.signal&&t.signal.addEventListener("abort",()=>{n.abort()}),e.signal=n.signal}return e}function M(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return ae(t)}else if(t.promptFeedback)throw new _(`Text not available. ${O(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),Z(t)[0]}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return Z(t)}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t}function ae(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.text&&o.push(a.text),a.executableCode&&o.push("\n```"+a.executableCode.language+`
|
|
2
2
|
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&o.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return o.length>0?o.join(""):""}function Z(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.functionCall&&o.push(a.functionCall);if(o.length>0)return o}const re=[T.RECITATION,T.SAFETY,T.LANGUAGE];function A(t){return!!t.finishReason&&re.includes(t.finishReason)}function O(t){var e,n,s;let i="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)i+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(i+=` due to ${t.promptFeedback.blockReason}`),!((n=t.promptFeedback)===null||n===void 0)&&n.blockReasonMessage&&(i+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((s=t.candidates)===null||s===void 0)&&s[0]){const o=t.candidates[0];A(o)&&(i+=`Candidate was blocked due to ${o.finishReason}`,o.finishMessage&&(i+=`: ${o.finishMessage}`))}return i}function w(t){return this instanceof w?(this.v=t,this):new w(t)}function ue(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=n.apply(t,e||[]),i,o=[];return i={},a("next"),a("throw"),a("return"),i[Symbol.asyncIterator]=function(){return this},i;function a(f){s[f]&&(i[f]=function(d){return new Promise(function(g,C){o.push([f,d,g,C])>1||u(f,d)})})}function u(f,d){try{c(s[f](d))}catch(g){l(o[0][3],g)}}function c(f){f.value instanceof w?Promise.resolve(f.value.v).then(p,r):l(o[0][2],f)}function p(f){u("next",f)}function r(f){u("throw",f)}function l(f,d){f(d),o.shift(),o.length&&u(o[0][0],o[0][1])}}const Q=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function le(t){const e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),n=fe(e),[s,i]=n.tee();return{stream:de(s),response:ce(i)}}async function ce(t){const e=[],n=t.getReader();for(;;){const{done:s,value:i}=await n.read();if(s)return M(pe(e));e.push(i)}}function de(t){return ue(this,arguments,function*(){const n=t.getReader();for(;;){const{value:s,done:i}=yield w(n.read());if(i)break;yield yield w(M(s))}})}function fe(t){const e=t.getReader();return new ReadableStream({start(s){let i="";return o();function o(){return e.read().then(({value:a,done:u})=>{if(u){if(i.trim()){s.error(new m("Failed to parse stream"));return}s.close();return}i+=a;let c=i.match(Q),p;for(;c;){try{p=JSON.parse(c[1])}catch{s.error(new m(`Error parsing JSON response: "${c[1]}"`));return}s.enqueue(p),i=i.substring(c[0].length),c=i.match(Q)}return o()}).catch(a=>{let u=a;throw u.stack=a.stack,u.name==="AbortError"?u=new ft("Request aborted when reading from the stream"):u=new m("Error reading from the stream"),u})}}})}function pe(t){const e=t[t.length-1],n={promptFeedback:e?.promptFeedback};for(const s of t){if(s.candidates){let i=0;for(const o of s.candidates)if(n.candidates||(n.candidates=[]),n.candidates[i]||(n.candidates[i]={index:i}),n.candidates[i].citationMetadata=o.citationMetadata,n.candidates[i].groundingMetadata=o.groundingMetadata,n.candidates[i].finishReason=o.finishReason,n.candidates[i].finishMessage=o.finishMessage,n.candidates[i].safetyRatings=o.safetyRatings,o.content&&o.content.parts){n.candidates[i].content||(n.candidates[i].content={role:o.content.role||"user",parts:[]});const a={};for(const u of o.content.parts)u.text&&(a.text=u.text),u.functionCall&&(a.functionCall=u.functionCall),u.executableCode&&(a.executableCode=u.executableCode),u.codeExecutionResult&&(a.codeExecutionResult=u.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),n.candidates[i].content.parts.push(a)}i++}s.usageMetadata&&(n.usageMetadata=s.usageMetadata)}return n}async function pt(t,e,n,s){const i=await R(e,v.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),s);return le(i)}async function gt(t,e,n,s){const o=await(await R(e,v.GENERATE_CONTENT,t,!1,JSON.stringify(n),s)).json();return{response:M(o)}}function ht(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function S(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(const n of t)typeof n=="string"?e.push({text:n}):e.push(n);return ge(e)}function ge(t){const e={role:"user",parts:[]},n={role:"function",parts:[]};let s=!1,i=!1;for(const o of t)"functionResponse"in o?(n.parts.push(o),i=!0):(e.parts.push(o),s=!0);if(s&&i)throw new m("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!s&&!i)throw new m("No content is provided for sending chat message.");return s?e:n}function he(t,e){var n;let s={model:e?.model,generationConfig:e?.generationConfig,safetySettings:e?.safetySettings,tools:e?.tools,toolConfig:e?.toolConfig,systemInstruction:e?.systemInstruction,cachedContent:(n=e?.cachedContent)===null||n===void 0?void 0:n.name,contents:[]};const i=t.generateContentRequest!=null;if(t.contents){if(i)throw new y("CountTokensRequest must have one of contents or generateContentRequest, not both.");s.contents=t.contents}else if(i)s=Object.assign(Object.assign({},s),t.generateContentRequest);else{const o=S(t);s.contents=[o]}return{generateContentRequest:s}}function X(t){let e;return t.contents?e=t:e={contents:[S(t)]},t.systemInstruction&&(e.systemInstruction=ht(t.systemInstruction)),e}function me(t){return typeof t=="string"||Array.isArray(t)?{content:S(t)}:t}const tt=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],Ce={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function Oe(t){let e=!1;for(const n of t){const{role:s,parts:i}=n;if(!e&&s!=="user")throw new m(`First content should be with role 'user', got ${s}`);if(!Y.includes(s))throw new m(`Each item should include role field. Got ${s} but valid roles are: ${JSON.stringify(Y)}`);if(!Array.isArray(i))throw new m("Content should have 'parts' property with an array of Parts");if(i.length===0)throw new m("Each Content should have at least one part");const o={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const u of i)for(const c of tt)c in u&&(o[c]+=1);const a=Ce[s];for(const u of tt)if(!a.includes(u)&&o[u]>0)throw new m(`Content with role '${s}' can't contain '${u}' part`);e=!0}}function et(t){var e;if(t.candidates===void 0||t.candidates.length===0)return!1;const n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;if(n===void 0||n.parts===void 0||n.parts.length===0)return!1;for(const s of n.parts)if(s===void 0||Object.keys(s).length===0||s.text!==void 0&&s.text==="")return!1;return!0}const nt="SILENT_ERROR";class ye{constructor(e,n,s,i={}){this.model=n,this.params=s,this._requestOptions=i,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,s?.history&&(Oe(s.history),this._history=s.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,n={}){var s,i,o,a,u,c;await this._sendPromise;const p=S(e),r={safetySettings:(s=this.params)===null||s===void 0?void 0:s.safetySettings,generationConfig:(i=this.params)===null||i===void 0?void 0:i.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(u=this.params)===null||u===void 0?void 0:u.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,p]},l=Object.assign(Object.assign({},this._requestOptions),n);let f;return this._sendPromise=this._sendPromise.then(()=>gt(this._apiKey,this.model,r,l)).then(d=>{var g;if(et(d.response)){this._history.push(p);const C=Object.assign({parts:[],role:"model"},(g=d.response.candidates)===null||g===void 0?void 0:g[0].content);this._history.push(C)}else{const C=O(d.response);C&&console.warn(`sendMessage() was unsuccessful. ${C}. Inspect response object for details.`)}f=d}).catch(d=>{throw this._sendPromise=Promise.resolve(),d}),await this._sendPromise,f}async sendMessageStream(e,n={}){var s,i,o,a,u,c;await this._sendPromise;const p=S(e),r={safetySettings:(s=this.params)===null||s===void 0?void 0:s.safetySettings,generationConfig:(i=this.params)===null||i===void 0?void 0:i.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(u=this.params)===null||u===void 0?void 0:u.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,p]},l=Object.assign(Object.assign({},this._requestOptions),n),f=pt(this._apiKey,this.model,r,l);return this._sendPromise=this._sendPromise.then(()=>f).catch(d=>{throw new Error(nt)}).then(d=>d.response).then(d=>{if(et(d)){this._history.push(p);const g=Object.assign({},d.candidates[0].content);g.role||(g.role="model"),this._history.push(g)}else{const g=O(d);g&&console.warn(`sendMessageStream() was unsuccessful. ${g}. Inspect response object for details.`)}}).catch(d=>{d.message!==nt&&console.error(d)}),f}}async function Ie(t,e,n,s){return(await R(e,v.COUNT_TOKENS,t,!1,JSON.stringify(n),s)).json()}async function ve(t,e,n,s){return(await R(e,v.EMBED_CONTENT,t,!1,JSON.stringify(n),s)).json()}async function _e(t,e,n,s){const i=n.requests.map(a=>Object.assign(Object.assign({},a),{model:e}));return(await R(e,v.BATCH_EMBED_CONTENTS,t,!1,JSON.stringify({requests:i}),s)).json()}class st{constructor(e,n,s={}){this.apiKey=e,this._requestOptions=s,n.model.includes("/")?this.model=n.model:this.model=`models/${n.model}`,this.generationConfig=n.generationConfig||{},this.safetySettings=n.safetySettings||[],this.tools=n.tools,this.toolConfig=n.toolConfig,this.systemInstruction=ht(n.systemInstruction),this.cachedContent=n.cachedContent}async generateContent(e,n={}){var s;const i=X(e),o=Object.assign(Object.assign({},this._requestOptions),n);return gt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(s=this.cachedContent)===null||s===void 0?void 0:s.name},i),o)}async generateContentStream(e,n={}){var s;const i=X(e),o=Object.assign(Object.assign({},this._requestOptions),n);return pt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(s=this.cachedContent)===null||s===void 0?void 0:s.name},i),o)}startChat(e){var n;return new ye(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},e),this._requestOptions)}async countTokens(e,n={}){const s=he(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),i=Object.assign(Object.assign({},this._requestOptions),n);return Ie(this.apiKey,this.model,s,i)}async embedContent(e,n={}){const s=me(e),i=Object.assign(Object.assign({},this._requestOptions),n);return ve(this.apiKey,this.model,s,i)}async batchEmbedContents(e,n={}){const s=Object.assign(Object.assign({},this._requestOptions),n);return _e(this.apiKey,this.model,e,s)}}class it{constructor(e){this.apiKey=e}getGenerativeModel(e,n){if(!e.model)throw new m("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new st(this.apiKey,e,n)}getGenerativeModelFromCachedContent(e,n,s){if(!e.name)throw new y("Cached content must contain a `name` field.");if(!e.model)throw new y("Cached content must contain a `model` field.");const i=["model","systemInstruction"];for(const a of i)if(n?.[a]&&e[a]&&n?.[a]!==e[a]){if(a==="model"){const u=n.model.startsWith("models/")?n.model.replace("models/",""):n.model,c=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(u===c)continue}throw new y(`Different value for "${a}" specified in modelParams (${n[a]}) and cachedContent (${e[a]})`)}const o=Object.assign(Object.assign({},n),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new st(this.apiKey,o,s)}}function ot(t,e){const n=Ee(t),s=we(n,e);return{tools:n,toolConfig:s}}function Ee(t){let e=[];const n=[];return t.forEach(i=>{if(at(i)){const[o]=Wt([i]);o.functionDeclarations&&e.push(...o.functionDeclarations)}else if(rt(i)){const{functionDeclarations:o}=Te(i);if(o)e.push(...o);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else n.push(i)}),n.find(i=>"functionDeclarations"in i)?n.map(i=>{if(e?.length>0&&"functionDeclarations"in i){const o={functionDeclarations:[...i.functionDeclarations||[],...e]};return e=[],o}return i}):[...n,...e.length>0?[{functionDeclarations:e}]:[]]}function Te(t){return{functionDeclarations:[{name:t.function.name,description:t.function.description,parameters:I(t.function.parameters)}]}}function we(t,e){if(!t.length||!e)return;const{toolChoice:n,allowedFunctionNames:s}=e,i={any:E.ANY,auto:E.AUTO,none:E.NONE};if(n&&["any","auto","none"].includes(n))return{functionCallingConfig:{mode:i[n]??"MODE_UNSPECIFIED",allowedFunctionNames:s}};if(typeof n=="string"||s)return{functionCallingConfig:{mode:E.ANY,allowedFunctionNames:[...s??[],...n&&typeof n=="string"?[n]:[]]}}}const Se={"gemini-embedding-001":{maxInputTokens:2048,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-image":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-preview-05-20":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-flash-lite-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-flash-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-05-06":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.0-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash-preview-native-audio":{maxInputTokens:131072,imageInputs:!1,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.0-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-06-05":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-lite-preview-06-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-image-preview":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-04-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-pro-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-pro":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-flash":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-1.5-flash-8b":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-lite-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-pro":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1}};var Re=Se,be=class extends Ot{static lc_name(){return"ChatGoogleGenerativeAI"}lc_serializable=!0;get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}lc_namespace=["langchain","chat_models","google_genai"];get lc_aliases(){return{apiKey:"google_api_key"}}model;temperature;maxOutputTokens;topP;topK;stopSequences=[];safetySettings;apiKey;streaming=!1;json;streamUsage=!0;convertSystemMessageToHumanContent;thinkingConfig;client;get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")||this.model.startsWith("gemini-3")}constructor(t){if(super(t),this.model=t.model.replace(/^models\//,""),this.maxOutputTokens=t.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=t.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=t.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=t.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=t.stopSequences??this.stopSequences,this.apiKey=t.apiKey??kt("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=t.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(n=>n.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=t.streaming??this.streaming,this.json=t.json,this.thinkingConfig=t.thinkingConfig??this.thinkingConfig,this.client=new it(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{}}},{apiVersion:t.apiVersion,baseUrl:t.baseUrl,customHeaders:t.customHeaders}),this.streamUsage=t.streamUsage??this.streamUsage}useCachedContent(t,e,n){this.apiKey&&(this.client=new it(this.apiKey).getGenerativeModelFromCachedContent(t,e,n))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent=="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model==="gemini-1.0-pro-001"||this.model.startsWith("gemini-pro-vision")||this.model.startsWith("gemini-1.0-pro-vision")?!1:this.model!=="gemini-pro"}getLsParams(t){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:t.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(t,e){return this.withConfig({tools:ot(t)?.tools,...e})}invocationParams(t){const e=t?.tools?.length?ot(t.tools,{toolChoice:t.tool_choice,allowedFunctionNames:t.allowedFunctionNames}):void 0;return t?.responseSchema?(this.client.generationConfig.responseSchema=t.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...e?.tools?{tools:e.tools}:{},...e?.toolConfig?{toolConfig:e.toolConfig}:{}}}async _generate(t,e,n){const s=P(t,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[p]=s;this.client.systemInstruction=p,i=s.slice(1)}const o=this.invocationParams(e);if(this.streaming){const p={},r=this._streamResponseChunks(t,e,n),l={};for await(const d of r){const g=d.generationInfo?.completion??0;l[g]===void 0?l[g]=d:l[g]=l[g].concat(d)}return{generations:Object.entries(l).sort(([d],[g])=>parseInt(d,10)-parseInt(g,10)).map(([d,g])=>g),llmOutput:{estimatedTokenUsage:p}}}const a=await this.completionWithRetry({...o,contents:i});let u;"usageMetadata"in a.response&&(u=j(a.response.usageMetadata,this.model));const c=Bt(a.response,{usageMetadata:u});return c.generations?.length>0&&await n?.handleLLMNewToken(c.generations[0]?.text??""),c}async*_streamResponseChunks(t,e,n){const s=P(t,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[f]=s;this.client.systemInstruction=f,i=s.slice(1)}const a={...this.invocationParams(e),contents:i},u=await this.caller.callWithOptions({signal:e?.signal},async()=>{const{stream:f}=await this.client.generateContentStream(a);return f});let c,p=0,r=0,l=0;for await(const f of u){if("usageMetadata"in f&&f.usageMetadata!==void 0&&this.streamUsage!==!1&&e.streamUsage!==!1){c=j(f.usageMetadata,this.model);const g=f.usageMetadata.promptTokenCount??0;c.input_tokens=Math.max(0,g-p),p=g;const C=f.usageMetadata.candidatesTokenCount??0;c.output_tokens=Math.max(0,C-r),r=C;const D=f.usageMetadata.totalTokenCount??0;c.total_tokens=Math.max(0,D-l),l=D}const d=qt(f,{usageMetadata:c});d&&(yield d,await n?.handleLLMNewToken(d.text??""))}}async completionWithRetry(t,e){return this.caller.callWithOptions({signal:e?.signal},async()=>{try{return await this.client.generateContent(t)}catch(n){throw n.message?.includes("400 Bad Request")&&(n.status=400),n}})}get profile(){return Re[this.model]??{}}withStructuredOutput(t,e){const n=t,s=e?.name,i=e?.method,o=e?.includeRaw;if(i==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,u;if(i==="functionCalling"){let l=s??"extract",f;if(ut(n)){const d=N(n);f=[{functionDeclarations:[{name:l,description:d.description??"A function available to call.",parameters:d}]}],u=new F({returnSingle:!0,keyName:l,zodSchema:n})}else{let d;typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(d=n,d.parameters=I(n.parameters),l=n.name):d={name:l,description:n.description??"",parameters:I(n)},f=[{functionDeclarations:[d]}],u=new F({returnSingle:!0,keyName:l})}a=this.bindTools(f).withConfig({allowedFunctionNames:[l]})}else{const l=N(n);a=this.withConfig({responseSchema:l}),u=new yt}if(!o)return a.pipe(u).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const c=G.assign({parsed:(l,f)=>u.invoke(l.raw,f)}),p=G.assign({parsed:()=>null}),r=c.withFallbacks({fallbacks:[p]});return Nt.from([{raw:a},r]).withConfig({runName:"StructuredOutputRunnable"})}};export{be as ChatGoogleGenerativeAI};
|