@mcp-use/inspector 0.14.0-canary.8 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{browser-C2Fn0YFm.js → browser-EyInsrZa.js} +48 -48
- package/dist/client/assets/client-JeU2zpxn.js +92 -0
- package/dist/client/assets/{display-A5IEINAP-CARbqwYz.js → display-A5IEINAP-Btv2gL3n.js} +2 -2
- package/dist/client/assets/{embeddings-CS1tQ9WC.js → embeddings-Dya_KnH0.js} +1 -1
- package/dist/client/assets/{index-BHWuEnDp.js → index--IpKhg5F.js} +1 -1
- package/dist/client/assets/{index-w9z_NOXw.js → index-01y2e9ko.js} +1 -1
- package/dist/client/assets/{index-CZ1ZJ4DA.js → index-3gQQW6s7.js} +1 -1
- package/dist/client/assets/{index-CEc6a116.js → index-BZCfajuh.js} +1 -1
- package/dist/client/assets/{index-B66nJ4Ui.js → index-BiUxRAkS.js} +1 -1
- package/dist/client/assets/{index-CWxR53gB.js → index-CwGEcSpK.js} +1 -1
- package/dist/client/assets/{index-03ai9_N2.js → index-D7646HFQ.js} +1 -1
- package/dist/client/assets/index-DoHGzyNN.js +1753 -0
- package/dist/client/assets/index-G80eS8Oh.css +1 -0
- package/dist/client/assets/{index-BGExFjwX.js → index-dRu1bjMq.js} +1 -1
- package/dist/client/assets/{llms-BT3kT7gN.js → llms-CQ_t8ic9.js} +1 -1
- package/dist/client/index.html +3 -3
- package/dist/client/index.js +1096 -0
- package/dist/server/{chunk-NOEIHEAG.js → chunk-4OEEUHLZ.js} +1 -1
- package/dist/server/{chunk-F7YWZTWJ.js → chunk-E4Y73JSU.js} +1 -1
- package/dist/server/{chunk-JCLAFMDT.js → chunk-PUX4EJWH.js} +11 -0
- package/dist/server/cli.js +2 -2
- package/dist/server/index.js +3 -3
- package/dist/server/middleware.js +3 -3
- package/dist/server/server.d.ts +11 -0
- package/dist/server/server.d.ts.map +1 -1
- package/dist/server/server.js +6 -24
- package/dist/server/shared-routes.js +2 -2
- package/dist/server/shared-static.d.ts +5 -1
- package/dist/server/shared-static.d.ts.map +1 -1
- package/dist/server/shared-utils-browser.d.ts +9 -1
- package/dist/server/shared-utils-browser.d.ts.map +1 -1
- package/dist/server/transport-wrapper.d.ts +1 -1
- package/dist/server/transport-wrapper.d.ts.map +1 -1
- package/dist/server/utils.d.ts +14 -0
- package/dist/server/utils.d.ts.map +1 -1
- package/dist/server/utils.js +5 -3
- package/package.json +9 -4
- package/dist/client/assets/client-Bt6xNGvA.js +0 -92
- package/dist/client/assets/index-BYhrMpLe.js +0 -1753
- package/dist/client/assets/index-D_5vBeGJ.css +0 -1
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import{B as me,_ as g,g as Y,c as Ue,J as He,d as Ke,e as We,T as ze,l as m,M as Ge,H as Ye,a as Xe,C as Ze,f as re,h as Qe}from"./index-DoHGzyNN.js";var O,et=(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}`)}},g(O,"CodeModeConnector"),O);function X(){throw new Error("fs.readFileSync is not available in browser environment")}function _e(){throw new Error("fs.writeFileSync is not available in browser environment")}function ve(){return!1}function we(){throw new Error("fs.readFile is not available in browser environment")}function ge(){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 be(){throw new Error("fs.stat is not available in browser environment")}function Ee(){throw new Error("fs.unlink is not available in browser environment")}function Ce(){throw new Error("fs.rmdir is not available in browser environment")}const L={readFileSync:X,writeFileSync:_e,existsSync:ve,readFile:we,writeFile:ge,mkdir:ye,readdir:xe,stat:be,unlink:Ee,rmdir:Ce},tt=Object.freeze(Object.defineProperty({__proto__:null,default:L,existsSync:ve,mkdir:ye,readFile:we,readFileSync:X,readdir:xe,rmdir:Ce,stat:be,unlink:Ee,writeFile:ge,writeFileSync:_e},Symbol.toStringTag,{value:"Module"}));function Z(...s){return s.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/$/,"")}function Se(...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 Me(s){return s.replace(/\/+/g,"/")}function Te(s){return s.startsWith("/")}function Pe(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 Oe="/",Ne=":",ke={join:Z,resolve:Se,dirname:Q,basename:q,extname:ee,normalize:Me,isAbsolute:Te,parse:Pe,sep:Oe,delimiter:Ne},nt=Object.freeze(Object.defineProperty({__proto__:null,basename:q,default:ke,delimiter:Ne,dirname:Q,extname:ee,isAbsolute:Te,join:Z,normalize:Me,parse:Pe,resolve:Se,sep:Oe},Symbol.toStringTag,{value:"Module"})),rt={},ot="browser",st="v18.0.0",it={node:"18.0.0"},ct=()=>"/",at=(s,...e)=>queueMicrotask(()=>s(...e)),lt=!0,j={env:rt,platform:ot,version:st,versions:it,cwd:ct,nextTick:at,browser:lt};var T={exports:{}};function $e(){throw new Error("child_process.spawn is not available in browser environment")}function Ae(){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 Ie(){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 je(){throw new Error("child_process.spawnSync is not available in browser environment")}function qe(){throw new Error("child_process.execFileSync is not available in browser environment")}const ut={spawn:$e,exec:Ae,execFile:Re,fork:Ie,execSync:Le,spawnSync:je,execFileSync:qe},dt=Object.freeze(Object.defineProperty({__proto__:null,default:ut,exec:Ae,execFile:Re,execFileSync:qe,execSync:Le,fork:Ie,spawn:$e,spawnSync:je},Symbol.toStringTag,{value:"Module"})),ht=Y(dt),Fe=Y(nt),Be=Y(tt);var J,oe;function ft(){if(oe)return J;oe=1;var s={};J=r,r.sync=o;var e=Be;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 J}var V,se;function pt(){if(se)return V;se=1,V=e,e.sync=t;var s=Be;function e(o,i,a){s.stat(o,function(l,c){a(l,l?!1:n(c,i))})}function t(o,i){return n(s.statSync(o),i)}function n(o,i){return o.isFile()&&r(o,i)}function r(o,i){var a=o.mode,l=o.uid,c=o.gid,u=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),d=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),h=parseInt("100",8),f=parseInt("010",8),p=parseInt("001",8),y=h|f,_=a&p||a&f&&c===d||a&h&&l===u||a&y&&u===0;return _}return V}var D,ie;function mt(){if(ie)return D;ie=1;var s;globalThis.TESTING_WINDOWS?s=ft():s=pt(),D=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 D}var U,ce;function _t(){if(ce)return U;ce=1;var s={};const e=s.OSTYPE==="cygwin"||s.OSTYPE==="msys",t=Fe,n=e?";":":",r=mt(),o=c=>Object.assign(new Error(`not found: ${c}`),{code:"ENOENT"}),i=(c,u)=>{const d=u.colon||n,h=c.match(/\//)||e&&c.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(u.path||s.PATH||"").split(d)],f=e?u.pathExt||s.PATHEXT||".EXE;.CMD;.BAT;.COM":"",p=e?f.split(d):[""];return e&&c.indexOf(".")!==-1&&p[0]!==""&&p.unshift(""),{pathEnv:h,pathExt:p,pathExtExe:f}},a=(c,u,d)=>{typeof u=="function"&&(d=u,u={}),u||(u={});const{pathEnv:h,pathExt:f,pathExtExe:p}=i(c,u),y=[],_=v=>new Promise((x,w)=>{if(v===h.length)return u.all&&y.length?x(y):w(o(c));const b=h[v],C=/^".*"$/.test(b)?b.slice(1,-1):b,P=t.join(C,c),B=!C&&/^\.[\\\/]/.test(c)?c.slice(0,2)+P:P;x(E(B,v,0))}),E=(v,x,w)=>new Promise((b,C)=>{if(w===f.length)return b(_(x+1));const P=f[w];r(v+P,{pathExt:p},(B,De)=>{if(!B&&De)if(u.all)y.push(v+P);else return b(v+P);return b(E(v,x,w+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 y=0;y<d.length;y++){const _=d[y],E=/^".*"$/.test(_)?_.slice(1,-1):_,v=t.join(E,c),x=!E&&/^\.[\\\/]/.test(c)?c.slice(0,2)+v:v;for(let w=0;w<h.length;w++){const b=x+h[w];try{if(r.sync(b,{pathExt:f}))if(u.all)p.push(b);else return b}catch{}}}if(u.all&&p.length)return p;if(u.nothrow)return null;throw o(c)};return U=a,a.sync=l,U}var I={exports:{}},ae;function vt(){if(ae)return I.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 I.exports=e,I.exports.default=e,I.exports}var H,le;function wt(){if(le)return H;le=1;var s={};const e=Fe,t=_t(),n=vt();function r(i,a){const l=i.options.env||s,c=process.cwd(),u=i.options.cwd!=null,d=u&&process.chdir!==void 0&&!process.chdir.disabled;if(d)try{process.chdir(i.options.cwd)}catch{}let h;try{h=t.sync(i.command,{path:l[n({env:l})],pathExt:a?e.delimiter:void 0})}catch{}finally{d&&process.chdir(c)}return h&&(h=e.resolve(u?i.options.cwd:"",h)),h}function o(i){return r(i)||r(i,!0)}return H=o,H}var K,ue;function gt(){if(ue)return K;ue=1,wt();function s(t){return t}function e(t,n,r){n&&!Array.isArray(n)&&(r=n,n=null),n=n?n.slice(0):[],r=Object.assign({},r);const o={command:t,args:n,options:r,file:void 0,original:{command:t,args:n}};return r.shell?o:o}return K=e,K}var W,de;function yt(){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 xt(){if(he)return T.exports;he=1;const s=ht,e=gt(),t=yt();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 bt=xt();const Et=Ue(bt);class Ct{constructor(){console.warn("PassThrough stream is not available in browser environment")}}class St{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf(`
|
|
2
|
+
`);if(e===-1)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Mt(t)}clear(){this._buffer=void 0}}function Mt(s){return He.parse(JSON.parse(s))}function Tt(s){return JSON.stringify(s)+`
|
|
3
|
+
`}const Pt=["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Ot(){const s={};for(const e of Pt){const t=j.env[e];t!==void 0&&(t.startsWith("()")||(s[e]=t))}return s}class Nt{constructor(e){this._readBuffer=new St,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Ct)}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:{...Ot(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:j.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{t(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{const e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){const e=this._process;this._process=void 0;const t=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([t,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw new Error("Not connected");const n=Tt(e);this._process.stdin.write(n)?t():this._process.stdin.once("drain",t)})}}var kt={},N,te=(N=class{client;_connecting=!1;constructor(e){this.client=e}async ensureServersConnected(){const e=this.client.getServerNames(),t=Object.keys(this.client.getAllActiveSessions()),n=e.filter(r=>!t.includes(r));if(n.length>0&&!this._connecting){this._connecting=!0;try{m.debug(`Connecting to configured servers for code execution: ${n.join(", ")}`),await this.client.createAllSessions()}finally{this._connecting=!1}}else if(n.length>0&&this._connecting){m.debug("Waiting for ongoing server connection...");const r=Date.now();for(;this._connecting&&Date.now()-r<5e3;)await new Promise(o=>setTimeout(o,100))}}getToolNamespaces(){const e=[],t=this.client.getAllActiveSessions();for(const[n,r]of Object.entries(t))if(n!=="code_mode")try{const o=r.connector;let i;try{i=o.tools}catch(a){m.warn(`Tools not available for server ${n}: ${a}`);continue}if(!i||i.length===0)continue;e.push({serverName:n,tools:i,session:r})}catch(o){m.warn(`Failed to load tools for server ${n}: ${o}`)}return e}createSearchToolsFunction(){return async(e="",t="full")=>{const n=[],r=new Set,o=e.toLowerCase(),i=this.client.getAllActiveSessions();for(const[l,c]of Object.entries(i))if(l!=="code_mode")try{const u=c.connector.tools;u&&u.length>0&&r.add(l);for(const d of u)t==="names"?n.push({name:d.name,server:l}):t==="descriptions"?n.push({name:d.name,server:l,description:d.description}):n.push({name:d.name,server:l,description:d.description,input_schema:d.inputSchema})}catch(u){m.warn(`Failed to search tools in server ${l}: ${u}`)}let a=n;return e&&(a=n.filter(l=>{const c=l.name.toLowerCase().includes(o),u=l.description?.toLowerCase().includes(o),d=l.server.toLowerCase().includes(o);return c||u||d})),{meta:{total_tools:n.length,namespaces:Array.from(r).sort(),result_count:a.length},results:a}}}},g(N,"BaseCodeExecutor"),N),k,fe=(k=class extends te{e2bApiKey;codeExecSandbox=null;SandboxClass=null;timeoutMs;constructor(e,t){super(e),this.e2bApiKey=t.apiKey,this.timeoutMs=t.timeoutMs??3e5}async ensureSandboxClass(){if(!this.SandboxClass)try{const e=await Xe(()=>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
|
+
// MCP Bridge Shim
|
|
5
|
+
global.__callMcpTool = async (server, tool, args) => {
|
|
6
|
+
const id = Math.random().toString(36).substring(7);
|
|
7
|
+
console.log(JSON.stringify({
|
|
8
|
+
type: '__MCP_TOOL_CALL__',
|
|
9
|
+
id,
|
|
10
|
+
server,
|
|
11
|
+
tool,
|
|
12
|
+
args
|
|
13
|
+
}));
|
|
14
|
+
|
|
15
|
+
const resultPath = \`/tmp/mcp_result_\${id}.json\`;
|
|
16
|
+
const fs = require('fs');
|
|
17
|
+
|
|
18
|
+
// Poll for result file
|
|
19
|
+
let attempts = 0;
|
|
20
|
+
while (attempts < 300) { // 30 seconds timeout
|
|
21
|
+
if (fs.existsSync(resultPath)) {
|
|
22
|
+
const content = fs.readFileSync(resultPath, 'utf8');
|
|
23
|
+
const result = JSON.parse(content);
|
|
24
|
+
fs.unlinkSync(resultPath); // Clean up
|
|
25
|
+
|
|
26
|
+
if (result.error) {
|
|
27
|
+
throw new Error(result.error);
|
|
28
|
+
}
|
|
29
|
+
return result.data;
|
|
30
|
+
}
|
|
31
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
32
|
+
attempts++;
|
|
33
|
+
}
|
|
34
|
+
throw new Error('Tool execution timed out');
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// Global search_tools helper
|
|
38
|
+
global.search_tools = async (query, detailLevel = 'full') => {
|
|
39
|
+
const allTools = ${JSON.stringify(Object.entries(e).flatMap(([n,r])=>r.map(o=>({name:o.name,description:o.description,server:n,input_schema:o.inputSchema}))))};
|
|
40
|
+
|
|
41
|
+
const filtered = allTools.filter(tool => {
|
|
42
|
+
if (!query) return true;
|
|
43
|
+
const q = query.toLowerCase();
|
|
44
|
+
return tool.name.toLowerCase().includes(q) ||
|
|
45
|
+
(tool.description && tool.description.toLowerCase().includes(q));
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
if (detailLevel === 'names') {
|
|
49
|
+
return filtered.map(t => ({ name: t.name, server: t.server }));
|
|
50
|
+
} else if (detailLevel === 'descriptions') {
|
|
51
|
+
return filtered.map(t => ({ name: t.name, server: t.server, description: t.description }));
|
|
52
|
+
}
|
|
53
|
+
return filtered;
|
|
54
|
+
};
|
|
55
|
+
`;for(const[n,r]of Object.entries(e)){if(!r||r.length===0)continue;const o=n.replace(/[^a-zA-Z0-9_]/g,"_");t+=`
|
|
56
|
+
global['${n}'] = {`;for(const i of r)t+=`
|
|
57
|
+
'${i.name}': async (args) => await global.__callMcpTool('${n}', '${i.name}', args),`;t+=`
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// Also expose as safe name if different
|
|
61
|
+
if ('${o}' !== '${n}') {
|
|
62
|
+
global['${o}'] = global['${n}'];
|
|
63
|
+
}
|
|
64
|
+
`}return t}buildToolCatalog(){const e={},t=this.getToolNamespaces();for(const{serverName:n,tools:r}of t)e[n]=r;return e}async execute(e,t=3e4){const n=Date.now();let r=null,o=null,i=[];try{await this.ensureServersConnected();const a=await this.getOrCreateCodeExecSandbox(),l=this.buildToolCatalog(),u=`
|
|
65
|
+
${this.generateShim(l)}
|
|
66
|
+
|
|
67
|
+
(async () => {
|
|
68
|
+
try {
|
|
69
|
+
const func = async () => {
|
|
70
|
+
${e}
|
|
71
|
+
};
|
|
72
|
+
const result = await func();
|
|
73
|
+
console.log('__MCP_RESULT_START__');
|
|
74
|
+
console.log(JSON.stringify(result));
|
|
75
|
+
console.log('__MCP_RESULT_END__');
|
|
76
|
+
} catch (e) {
|
|
77
|
+
console.error(e);
|
|
78
|
+
process.exit(1);
|
|
79
|
+
}
|
|
80
|
+
})();
|
|
81
|
+
`,d=`exec_${Date.now()}.js`;await a.files.write(d,u);const h=await a.commands.run(`node ${d}`,{timeoutMs:t,onStdout:g(async f=>{try{const p=f.split(`
|
|
82
|
+
`);for(const y of p)if(y.trim().startsWith('{"type":"__MCP_TOOL_CALL__"')){const _=JSON.parse(y);if(_.type==="__MCP_TOOL_CALL__")try{m.debug(`[E2B Bridge] Calling tool ${_.server}.${_.tool}`);const v=this.client.getAllActiveSessions()[_.server];if(!v)throw new Error(`Server ${_.server} not found`);const x=await v.connector.callTool(_.tool,_.args);let w=x;if(x.content&&x.content.length>0){const C=x.content[0];if(C.type==="text")try{w=JSON.parse(C.text)}catch{w=C.text}else w=C}const b=`/tmp/mcp_result_${_.id}.json`;await a.files.write(b,JSON.stringify({data:w}))}catch(E){m.error(`[E2B Bridge] Tool execution failed: ${E.message}`);const v=`/tmp/mcp_result_${_.id}.json`;await a.files.write(v,JSON.stringify({error:E.message||String(E)}))}}}catch{}},"onStdout")});if(i=[h.stdout,h.stderr].filter(Boolean),h.exitCode!==0)o=h.stderr||"Execution failed";else{const f=h.stdout,p="__MCP_RESULT_START__",y="__MCP_RESULT_END__",_=f.indexOf(p),E=f.indexOf(y);if(_!==-1&&E!==-1){const v=f.substring(_+p.length,E).trim();try{r=JSON.parse(v)}catch{r=v}i=i.map(x=>{let w=x.replace(new RegExp(p+"[\\s\\S]*?"+y),"[Result captured]");return w=w.split(`
|
|
83
|
+
`).filter(b=>!b.includes("__MCP_TOOL_CALL__")).join(`
|
|
84
|
+
`),w})}}}catch(a){o=a.message||String(a),o&&(o.includes("timeout")||o.includes("timed out"))&&(o="Script execution timed out")}return{result:r,logs:i,error:o,execution_time:(Date.now()-n)/1e3}}async cleanup(){if(this.codeExecSandbox)try{await this.codeExecSandbox.kill(),this.codeExecSandbox=null,m.debug("E2B code execution sandbox stopped")}catch(e){m.error("Failed to stop E2B code execution sandbox:",e)}}},g(k,"E2BCodeExecutor"),k),S=null,z=!1;function ne(){return["node","vm"].join(":")}g(ne,"getVMModuleName");function F(){if(z)return S!==null;z=!0;try{const s=typeof re<"u"?re:null;if(s)return S=s(ne()),!0}catch{m.debug("node:vm module not available via require")}return!1}g(F,"tryLoadVM");async function Je(){if(S!==null||!z&&F())return!0;try{return S=await import(ne()),!0}catch{return m.debug("node:vm module not available in this environment (e.g., Deno)"),!1}}g(Je,"tryLoadVMAsync");function $t(){return F(),S!==null}g($t,"isVMAvailable");var $,pe=($=class extends te{defaultTimeout;memoryLimitMb;constructor(e,t){super(e),this.defaultTimeout=t?.timeoutMs??3e4,this.memoryLimitMb=t?.memoryLimitMb,F()}async ensureVMLoaded(){if(S!==null)return;if(!await Je())throw new Error("node:vm module is not available in this environment. Please use E2B executor instead or run in a Node.js environment.")}async execute(e,t){const n=t??this.defaultTimeout;await this.ensureVMLoaded(),await this.ensureServersConnected();const r=[],o=Date.now();let i=null,a=null;try{const c=await this._buildContext(r),u=`
|
|
85
|
+
(async () => {
|
|
86
|
+
try {
|
|
87
|
+
${e}
|
|
88
|
+
} catch (e) {
|
|
89
|
+
throw e;
|
|
90
|
+
}
|
|
91
|
+
})()
|
|
92
|
+
`;i=await new S.Script(u,{filename:"agent_code.js"}).runInNewContext(c,{timeout:n,displayErrors:!0})}catch(c){a=c.message||String(c),(c.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"||c.message==="Script execution timed out."||typeof a=="string"&&(a.includes("timed out")||a.includes("timeout")))&&(a="Script execution timed out"),c.stack&&m.debug(`Code execution error stack: ${c.stack}`)}const l=(Date.now()-o)/1e3;return{result:i,logs:r,error:a,execution_time:l}}async _buildContext(e){const t=g((...i)=>{e.push(i.map(a=>typeof a=="object"?JSON.stringify(a,null,2):String(a)).join(" "))},"logHandler"),n={console:{log:t,error:g((...i)=>{t("[ERROR]",...i)},"error"),warn:g((...i)=>{t("[WARN]",...i)},"warn"),info:t,debug:t},Object,Array,String,Number,Boolean,Date,Math,JSON,RegExp,Map,Set,Promise,parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,setTimeout,clearTimeout,search_tools:this.createSearchToolsFunction(),__tool_namespaces:[]},r={},o=this.getToolNamespaces();for(const{serverName:i,tools:a,session:l}of o){const c={};for(const u of a){const d=u.name;c[d]=async h=>{const f=await l.connector.callTool(d,h||{});if(f.content&&f.content.length>0){const p=f.content[0];if(p.type==="text")try{return JSON.parse(p.text)}catch{return p.text}return p}return f}}n[i]=c,r[i]=!0}return n.__tool_namespaces=Object.keys(r),S.createContext(n)}async cleanup(){}},g($,"VMCodeExecutor"),$),A,At=(A=class extends Qe{serverParams;errlog;_transport=null;constructor(e,t=process.stderr){super(),this.serverParams=e,this.errlog=t}async establishConnection(){return this._transport=new Nt(this.serverParams),this._transport.stderr&&typeof this._transport.stderr.pipe=="function"&&this._transport.stderr.pipe(this.errlog),m.debug(`${this.constructor.name} connected successfully`),this._transport}async closeConnection(e){if(this._transport)try{await this._transport.close()}catch(t){m.warn(`Error closing stdio transport: ${t}`)}finally{this._transport=null}}},g(A,"StdioConnectionManager"),A),R,Rt=(R=class extends me{command;args;env;errlog;clientInfo;constructor({command:e="npx",args:t=[],env:n,errlog:r=j.stderr,...o}={}){super(o),this.command=e,this.args=t,this.env=n,this.errlog=r,this.clientInfo=o.clientInfo??{name:"stdio-connector",version:"1.0.0"}}async connect(){if(this.connected){m.debug("Already connected to MCP implementation");return}m.debug(`Connecting to MCP implementation via stdio: ${this.command}`);try{let e;if(this.env){e={};for(const[o,i]of Object.entries(j.env))i!==void 0&&(e[o]=i);Object.assign(e,this.env)}const t={command:this.command,args:this.args,env:e};this.connectionManager=new At(t,this.errlog);const n=await this.connectionManager.start(),r={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};this.client=new Ze(this.clientInfo,r),await this.client.connect(n),this.connected=!0,this.setupNotificationHandler(),this.setupRootsHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),m.debug(`Successfully connected to MCP implementation: ${this.command}`),this.trackConnectorInit({serverCommand:this.command,serverArgs:this.args,publicIdentifier:`${this.command} ${this.args.join(" ")}`})}catch(e){throw m.error(`Failed to connect to MCP implementation: ${e}`),await this.cleanupResources(),e}}get publicIdentifier(){return{type:"stdio","command&args":`${this.command} ${this.args.join(" ")}`}}},g(R,"StdioConnector"),R);function G(s){const e=X();return JSON.parse(e)}g(G,"loadConfigFile");function Ve(s,e){if("command"in s&&"args"in s)return new Rt({command:s.command,args:s.args,env:s.env,...e});if("url"in s){const t=s.transport||"http";return new Ye(s.url,{headers:s.headers,authToken:s.auth_token||s.authToken,preferSse:s.preferSse||t==="sse",disableSseFallback:s.disableSseFallback,clientInfo:s.clientInfo,...e})}throw new Error("Cannot determine connector type from config")}g(Ve,"createConnectorFromConfig");var M,Lt=(M=class extends Ke{static getPackageVersion(){return We()}codeMode=!1;_codeExecutor=null;_customCodeExecutor=null;_codeExecutorConfig="vm";_executorOptions;_samplingCallback;_elicitationCallback;constructor(e,t){e?typeof e=="string"?super(G()):super(e):super();let n=!1,r="vm",o;t?.codeMode&&(typeof t.codeMode=="boolean"?n=t.codeMode:(n=t.codeMode.enabled,r=t.codeMode.executor??"vm",o=t.codeMode.executorOptions)),this.codeMode=n,this._codeExecutorConfig=r,this._executorOptions=o,this._samplingCallback=t?.samplingCallback,this._elicitationCallback=t?.elicitationCallback,this.codeMode&&this._setupCodeModeConnector(),this._trackClientInit()}_trackClientInit(){const e=Object.keys(this.config.mcpServers??{}),t=!!this._samplingCallback,n=!!this._elicitationCallback;ze.getInstance().trackMCPClientInit({codeMode:this.codeMode,sandbox:!1,allCallbacks:t&&n,verify:!1,servers:e,numServers:e.length,isBrowser:!1}).catch(r=>m.debug(`Failed to track MCPClient init: ${r}`))}static fromDict(e,t){return new M(e,t)}static fromConfigFile(e,t){return new M(G(),t)}saveConfig(e){const t=ke.dirname(e);L.existsSync(t)||L.mkdirSync(t,{recursive:!0}),L.writeFileSync(e,JSON.stringify(this.config,null,2),"utf-8")}createConnectorFromConfig(e){return Ve(e,{samplingCallback:this._samplingCallback,elicitationCallback:this._elicitationCallback})}_setupCodeModeConnector(){m.debug("Code mode connector initialized as internal meta server");const e=new et(this),t=new Ge(e);this.sessions.code_mode=t,this.activeSessions.push("code_mode")}_ensureCodeExecutor(){if(!this._codeExecutor){const e=this._codeExecutorConfig;if(e instanceof te)this._codeExecutor=e;else{if(typeof e=="function")throw this._customCodeExecutor=e,new Error("Custom executor function should be handled in executeCode");if(e==="e2b"){const t=this._executorOptions;if(t?.apiKey)this._codeExecutor=new fe(this,t);else{m.warn("E2B executor requires apiKey. Falling back to VM.");try{this._codeExecutor=new pe(this,this._executorOptions)}catch{throw new Error("VM executor is not available in this environment and E2B API key is not provided. Please provide an E2B API key or run in a Node.js environment.")}}}else try{this._codeExecutor=new pe(this,this._executorOptions)}catch{const n=this._executorOptions,r=n?.apiKey||kt.E2B_API_KEY;if(r)m.info("VM executor not available in this environment. Falling back to E2B."),this._codeExecutor=new fe(this,{...n,apiKey:r});else throw new Error("VM executor is not available in this environment. Please provide an E2B API key via executorOptions or E2B_API_KEY environment variable, or run in a Node.js environment.")}}}return this._codeExecutor}async executeCode(e,t){if(!this.codeMode)throw new Error("Code execution mode is not enabled");return this._customCodeExecutor?this._customCodeExecutor(e,t):this._ensureCodeExecutor().execute(e,t)}async searchTools(e="",t="full"){if(!this.codeMode)throw new Error("Code execution mode is not enabled");return this._ensureCodeExecutor().createSearchToolsFunction()(e,t)}getServerNames(){const e=this.codeMode;return super.getServerNames().filter(t=>!e||t!=="code_mode")}async close(){this._codeExecutor&&(await this._codeExecutor.cleanup(),this._codeExecutor=null),await this.closeAllSessions()}},g(M,"MCPClient"),M);export{te as BaseCodeExecutor,fe as E2BCodeExecutor,Lt as MCPClient,Ge as MCPSession,pe as VMCodeExecutor,$t as isVMAvailable};
|
|
@@ -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-D7646HFQ.js","assets/index-DoHGzyNN.js","assets/index-G80eS8Oh.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as a,a as k}from"./index-DoHGzyNN.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-D7646HFQ.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-BiUxRAkS.js";var l={};c(l,{chunkArray:()=>u});const u=(r,s)=>r.reduce((a,n,o)=>{const e=Math.floor(o/s),t=a[e]||[];return a[e]=t.concat([n]),a},[]);var h={};c(h,{Embeddings:()=>i});var i=class{caller;constructor(r){this.caller=new d(r??{})}};export{i as E,l as c,h as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{F as Es,aK as Ra,aL as I,V as $a,U as Pa,y as $e,L as Jn,i as Xe,ad as Ea,ap as Ma,M as Na,I as Ms,J as Ns,B as Se,f as js,aM as ja,E as mn,aN as Kn,aO as Ua,aP as La,aQ as Da,K as Zn,aR as zn,aS as Fa,t as Ba,D as Gt}from"./index-
|
|
1
|
+
import{F as Es,aK as Ra,aL as I,V as $a,U as Pa,y as $e,L as Jn,i as Xe,ad as Ea,ap as Ma,M as Na,I as Ms,J as Ns,B as Se,f as js,aM as ja,E as mn,aN as Kn,aO as Ua,aP as La,aQ as Da,K as Zn,aR as zn,aS as Fa,t as Ba,D as Gt}from"./index-BiUxRAkS.js";import{c as Wa,j as qa,h as Ja,f as Us,S as Hn,J as Vn,R as Xn}from"./index-01y2e9ko.js";import{x as Ka,y as Za,o as K,m as ee,v as Ls,n as J,i as At,s as Q,q as gn,z as za}from"./index-DoHGzyNN.js";import{J as Gn,c as Ha,p as Ds,m as at}from"./llms-CQ_t8ic9.js";import"./embeddings-Dya_KnH0.js";import"./index-CwGEcSpK.js";function Ge(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
2
2
|
|
|
3
3
|
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
4
4
|
`,t}function O(t,e,n,s,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function c(t,e,n,s){if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(t):s?s.value:e.get(t)}let Fs=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return Fs=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^n()&15>>+s/4).toString(16))};function Qt(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const Yt=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class x extends Error{}class q extends x{constructor(e,n,s,r){super(`${q.makeMessage(e,n,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=n;const a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,n,s){const r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,n,s,r){if(!e||!r)return new Rt({message:s,cause:Yt(n)});const a=n?.error;return e===400?new Bs(e,a,s,r):e===401?new Ws(e,a,s,r):e===403?new qs(e,a,s,r):e===404?new Js(e,a,s,r):e===409?new Ks(e,a,s,r):e===422?new Zs(e,a,s,r):e===429?new zs(e,a,s,r):e>=500?new Hs(e,a,s,r):new q(e,a,s,r)}}class Y extends q{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Rt extends q{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class $t extends Rt{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Bs extends q{}class Ws extends q{}class qs extends q{}class Js extends q{}class Ks extends q{}class Zs extends q{}class zs extends q{}class Hs extends q{}class Vs extends x{constructor(){super("Could not parse response content as the length limit was reached")}}class Xs extends x{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Pe extends Error{constructor(e){super(e)}}const Va=/^[a-z][a-z0-9+.-]*:/i,Xa=t=>Va.test(t);let H=t=>(H=Array.isArray,H(t)),Qn=H;function Gs(t){return typeof t!="object"?{}:t??{}}function Ga(t){if(!t)return!0;for(const e in t)return!1;return!0}function Qa(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Wt(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const Ya=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${t} must be an integer`);if(e<0)throw new x(`${t} must be a positive integer`);return e},ei=t=>{try{return JSON.parse(t)}catch{return}},Ke=t=>new Promise(e=>setTimeout(e,t)),Oe="6.10.0",ti=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function ni(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const si=()=>{const t=ni();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Oe,"X-Stainless-OS":es(Deno.build.os),"X-Stainless-Arch":Yn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Oe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Oe,"X-Stainless-OS":es(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Yn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=ri();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Oe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Oe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ri(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const s=n.exec(navigator.userAgent);if(s){const r=s[1]||0,a=s[2]||0,i=s[3]||0;return{browser:e,version:`${r}.${a}.${i}`}}}return null}const Yn=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",es=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let ts;const ai=()=>ts??(ts=si());function ii(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Qs(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Ys(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Qs({start(){},async pull(n){const{done:s,value:r}=await e.next();s?n.close():n.enqueue(r)},async cancel(){await e.return?.()}})}function er(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function oi(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const ui=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),tr="RFC3986",nr=t=>String(t),ns={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:nr},li="RFC1738";let en=(t,e)=>(en=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),en(t,e));const re=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),qt=1024,ci=(t,e,n,s,r)=>{if(t.length===0)return t;let a=t;if(typeof t=="symbol"?a=Symbol.prototype.toString.call(t):typeof t!="string"&&(a=String(t)),n==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=qt){const l=a.length>=qt?a.slice(o,o+qt):a,u=[];for(let m=0;m<l.length;++m){let p=l.charCodeAt(m);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||r===li&&(p===40||p===41)){u[u.length]=l.charAt(m);continue}if(p<128){u[u.length]=re[p];continue}if(p<2048){u[u.length]=re[192|p>>6]+re[128|p&63];continue}if(p<55296||p>=57344){u[u.length]=re[224|p>>12]+re[128|p>>6&63]+re[128|p&63];continue}m+=1,p=65536+((p&1023)<<10|l.charCodeAt(m)&1023),u[u.length]=re[240|p>>18]+re[128|p>>12&63]+re[128|p>>6&63]+re[128|p&63]}i+=u.join("")}return i};function di(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ss(t,e){if(H(t)){const n=[];for(let s=0;s<t.length;s+=1)n.push(e(t[s]));return n}return e(t)}const sr={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},rr=function(t,e){Array.prototype.push.apply(t,H(e)?e:[e])};let rs;const j={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ci,encodeValuesOnly:!1,format:tr,formatter:nr,indices:!1,serializeDate(t){return(rs??(rs=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function pi(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const Jt={};function ar(t,e,n,s,r,a,i,o,l,u,m,p,f,d,b,w,$,h){let g=t,T=h,C=0,Z=!1;for(;(T=T.get(Jt))!==void 0&&!Z;){const P=T.get(t);if(C+=1,typeof P<"u"){if(P===C)throw new RangeError("Cyclic object value");Z=!0}typeof T.get(Jt)>"u"&&(C=0)}if(typeof u=="function"?g=u(e,g):g instanceof Date?g=f?.(g):n==="comma"&&H(g)&&(g=ss(g,function(P){return P instanceof Date?f?.(P):P})),g===null){if(a)return l&&!w?l(e,j.encoder,$,"key",d):e;g=""}if(pi(g)||di(g)){if(l){const P=w?e:l(e,j.encoder,$,"key",d);return[b?.(P)+"="+b?.(l(g,j.encoder,$,"value",d))]}return[b?.(e)+"="+b?.(String(g))]}const U=[];if(typeof g>"u")return U;let R;if(n==="comma"&&H(g))w&&l&&(g=ss(g,l)),R=[{value:g.length>0?g.join(",")||null:void 0}];else if(H(u))R=u;else{const P=Object.keys(g);R=m?P.sort(m):P}const F=o?String(e).replace(/\./g,"%2E"):String(e),L=s&&H(g)&&g.length===1?F+"[]":F;if(r&&H(g)&&g.length===0)return L+"[]";for(let P=0;P<R.length;++P){const M=R[P],Wn=typeof M=="object"&&typeof M.value<"u"?M.value:g[M];if(i&&Wn===null)continue;const Bt=p&&o?M.replace(/\./g,"%2E"):M,Aa=H(g)?typeof n=="function"?n(L,Bt):L:L+(p?"."+Bt:"["+Bt+"]");h.set(t,C);const qn=new WeakMap;qn.set(Jt,h),rr(U,ar(Wn,Aa,n,s,r,a,i,o,n==="comma"&&w&&H(g)?null:l,u,m,p,f,d,b,w,$,qn))}return U}function fi(t=j){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||j.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=tr;if(typeof t.format<"u"){if(!en(ns,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const s=ns[n];let r=j.filter;(typeof t.filter=="function"||H(t.filter))&&(r=t.filter);let a;if(t.arrayFormat&&t.arrayFormat in sr?a=t.arrayFormat:"indices"in t?a=t.indices?"indices":"repeat":a=j.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:j.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:j.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:j.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:j.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?j.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:j.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:j.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:j.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:j.encodeValuesOnly,filter:r,format:n,formatter:s,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:j.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:j.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:j.strictNullHandling}}function hi(t,e={}){let n=t;const s=fi(e);let r,a;typeof s.filter=="function"?(a=s.filter,n=a("",n)):H(s.filter)&&(a=s.filter,r=a);const i=[];if(typeof n!="object"||n===null)return"";const o=sr[s.arrayFormat],l=o==="comma"&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const u=new WeakMap;for(let f=0;f<r.length;++f){const d=r[f];s.skipNulls&&n[d]===null||rr(i,ar(n[d],d,o,l,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,u))}const m=i.join(s.delimiter);let p=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),m.length>0?p+m:""}function mi(t){let e=0;for(const r of t)e+=r.length;const n=new Uint8Array(e);let s=0;for(const r of t)n.set(r,s),s+=r.length;return n}let as;function _n(t){let e;return(as??(e=new globalThis.TextEncoder,as=e.encode.bind(e)))(t)}let is;function os(t){let e;return(is??(e=new globalThis.TextDecoder,is=e.decode.bind(e)))(t)}var V,X;class Pt{constructor(){V.set(this,void 0),X.set(this,void 0),O(this,V,new Uint8Array),O(this,X,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?_n(e):e;O(this,V,mi([c(this,V,"f"),n]));const s=[];let r;for(;(r=gi(c(this,V,"f"),c(this,X,"f")))!=null;){if(r.carriage&&c(this,X,"f")==null){O(this,X,r.index);continue}if(c(this,X,"f")!=null&&(r.index!==c(this,X,"f")+1||r.carriage)){s.push(os(c(this,V,"f").subarray(0,c(this,X,"f")-1))),O(this,V,c(this,V,"f").subarray(c(this,X,"f"))),O(this,X,null);continue}const a=c(this,X,"f")!==null?r.preceding-1:r.preceding,i=os(c(this,V,"f").subarray(0,a));s.push(i),O(this,V,c(this,V,"f").subarray(r.index)),O(this,X,null)}return s}flush(){return c(this,V,"f").length?this.decode(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{N as Ue,O as je,P as J,Q as ae,i as Ae,S as H,y as le,g as U,U as Nt,V as kt,W as xt,X as Pt,Y as Mt,Z as Rt,$ as Ft,a0 as Lt,a1 as Dt,a2 as Bt,h as Ut,a3 as jt,a4 as Vt,a5 as zt,b as Gt,a6 as Zt,a7 as $t,a8 as Ht,a9 as Wt,aa as Jt,r as Xt,ab as Yt,a as $e,ac as Kt,ad as He,ae as qt,af as Qt,ag as ea,ah as Se,ai as ta,aj as aa,ak as sa,q as We,al as re,e as oe,am as Je,an as Xe,x as ce,L as na,C as ye,ao as Ve,w as ra,R as ze,z as X,t as ia,ap as Ie,E as oa,M as Ye,aq as ca,ar as ua,as as la,B as Ke,at as ie,k as G,au as qe,av as ha,aw as Qe,ax as pa,l as ga,m as ma,ay as fa,az as da,aA as ba,aB as ya,aC as _a,aD as Ta,aE as va,aF as Ea,D as Ge,aG as wa,G as Ca,aH as Aa,aI as Sa,aJ as ve,o as et,s as tt,u as Ia}from"./index-B66nJ4Ui.js";import{c as Oa}from"./index-BYhrMpLe.js";function at(e,a,n,r,i){if(a!==e){typeof a.toJSON=="function"&&(a=a.toJSON());for(var c=Ue(a),h=Ue(e),l=!1,b=h.length-1;b>=0;b--){var f=h[b],T=e[f];if(je(a,f)&&!(a[f]===void 0&&T!==void 0&&Array.isArray(a)===!1)){var _=a[f];typeof T=="object"&&T!=null&&typeof _=="object"&&_!=null&&Array.isArray(T)===Array.isArray(_)?at(T,_,n,r+"/"+J(f),i):T!==_&&(i&&n.push({op:"test",path:r+"/"+J(f),value:ae(T)}),n.push({op:"replace",path:r+"/"+J(f),value:ae(_)}))}else Array.isArray(e)===Array.isArray(a)?(i&&n.push({op:"test",path:r+"/"+J(f),value:ae(T)}),n.push({op:"remove",path:r+"/"+J(f)}),l=!0):(i&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:a}))}if(!(!l&&c.length==h.length))for(var b=0;b<c.length;b++){var f=c[b];!je(e,f)&&a[f]!==void 0&&n.push({op:"add",path:r+"/"+J(f),value:ae(a[f])})}}}function Oe(e,a,n=!1){var r=[];return at(e,a,r,"",n),r}function st(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function nt(e){return e!==void 0&&H.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function rt(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Ae(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function it(e){return rt(e)||nt(e)||st(e)}var Na={};U(Na,{convertToOpenAIFunction:()=>ot,convertToOpenAITool:()=>ka,isLangChainTool:()=>it,isRunnableToolLike:()=>nt,isStructuredTool:()=>st,isStructuredToolParams:()=>rt});function ot(e,a){const n=typeof a=="number"?void 0:a;return{name:e.name,description:e.description,parameters:le(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function ka(e,a){const n=typeof a=="number"?void 0:a;let r;return it(e)?r={type:"function",function:ot(e)}:r=e,n?.strict!==void 0&&(r.function.strict=n.strict),r}var xa={};U(xa,{extendInteropZodObject:()=>ea,getInteropZodDefaultGetter:()=>Qt,getInteropZodObjectShape:()=>qt,getSchemaDescription:()=>He,interopParse:()=>Kt,interopParseAsync:()=>$e,interopSafeParse:()=>Yt,interopSafeParseAsync:()=>Xt,interopZodObjectMakeFieldsOptional:()=>Jt,interopZodObjectPartial:()=>Wt,interopZodObjectPassthrough:()=>Ht,interopZodObjectStrict:()=>$t,interopZodTransformInputSchema:()=>Zt,isInteropZodError:()=>Gt,isInteropZodLiteral:()=>zt,isInteropZodObject:()=>Vt,isInteropZodSchema:()=>Ae,isShapelessZodSchema:()=>jt,isSimpleStringZodSchema:()=>Ut,isZodArrayV4:()=>Bt,isZodLiteralV3:()=>Dt,isZodLiteralV4:()=>Lt,isZodNullableV4:()=>Ft,isZodObjectV3:()=>Rt,isZodObjectV4:()=>Mt,isZodOptionalV4:()=>Pt,isZodSchema:()=>xt,isZodSchemaV3:()=>kt,isZodSchemaV4:()=>Nt});var Pa={};U(Pa,{BasePromptValue:()=>he,ChatPromptValue:()=>ut,ImagePromptValue:()=>Ma,StringPromptValue:()=>ct});var he=class extends aa{},ct=class extends he{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new Se(this.value)]}},ut=class extends he{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return ta(this.messages)}toChatMessages(){return this.messages}},Ma=class extends he{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Se({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},y="0123456789abcdef".split(""),Ra=[-2147483648,8388608,32768,128],D=[24,16,8,0],se=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],M=[];function B(e,a){a?(M[0]=M[16]=M[1]=M[2]=M[3]=M[4]=M[5]=M[6]=M[7]=M[8]=M[9]=M[10]=M[11]=M[12]=M[13]=M[14]=M[15]=0,this.blocks=M):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}B.prototype.update=function(e){if(!this.finalized){var a,n=typeof e;if(n!=="string"){if(n==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);a=!0}for(var r,i=0,c,h=e.length,l=this.blocks;i<h;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),a)for(c=this.start;i<h&&c<64;++i)l[c>>>2]|=e[i]<<D[c++&3];else for(c=this.start;i<h&&c<64;++i)r=e.charCodeAt(i),r<128?l[c>>>2]|=r<<D[c++&3]:r<2048?(l[c>>>2]|=(192|r>>>6)<<D[c++&3],l[c>>>2]|=(128|r&63)<<D[c++&3]):r<55296||r>=57344?(l[c>>>2]|=(224|r>>>12)<<D[c++&3],l[c>>>2]|=(128|r>>>6&63)<<D[c++&3],l[c>>>2]|=(128|r&63)<<D[c++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),l[c>>>2]|=(240|r>>>18)<<D[c++&3],l[c>>>2]|=(128|r>>>12&63)<<D[c++&3],l[c>>>2]|=(128|r>>>6&63)<<D[c++&3],l[c>>>2]|=(128|r&63)<<D[c++&3]);this.lastByteIndex=c,this.bytes+=c-this.start,c>=64?(this.block=l[16],this.start=c-64,this.hash(),this.hashed=!0):this.start=c}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};B.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,a=this.lastByteIndex;e[16]=this.block,e[a>>>2]|=Ra[a&3],this.block=e[16],a>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};B.prototype.hash=function(){var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,b=this.blocks,f,T,_,E,g,d,m,v,w,A,C;for(f=16;f<64;++f)g=b[f-15],T=(g>>>7|g<<25)^(g>>>18|g<<14)^g>>>3,g=b[f-2],_=(g>>>17|g<<15)^(g>>>19|g<<13)^g>>>10,b[f]=b[f-16]+T+b[f-7]+_<<0;for(C=a&n,f=0;f<64;f+=4)this.first?(this.is224?(v=300032,g=b[0]-1413257819,l=g-150054599<<0,r=g+24177077<<0):(v=704751109,g=b[0]-210244248,l=g-1521486534<<0,r=g+143694565<<0),this.first=!1):(T=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),_=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),v=e&a,E=v^e&n^C,m=i&c^~i&h,g=l+_+m+se[f]+b[f],d=T+E,l=r+g<<0,r=g+d<<0),T=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),_=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),w=r&e,E=w^r&a^v,m=h&l^~h&i,g=c+_+m+se[f+1]+b[f+1],d=T+E,h=n+g<<0,n=g+d<<0,T=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),_=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),A=n&r,E=A^n&e^w,m=c&h^~c&l,g=i+_+m+se[f+2]+b[f+2],d=T+E,c=a+g<<0,a=g+d<<0,T=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),_=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),C=a&n,E=C^a&r^A,m=c&h^~c&l,g=i+_+m+se[f+3]+b[f+3],d=T+E,i=e+g<<0,e=g+d<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+a<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+c<<0,this.h6=this.h6+h<<0,this.h7=this.h7+l<<0};B.prototype.hex=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,b=y[e>>>28&15]+y[e>>>24&15]+y[e>>>20&15]+y[e>>>16&15]+y[e>>>12&15]+y[e>>>8&15]+y[e>>>4&15]+y[e&15]+y[a>>>28&15]+y[a>>>24&15]+y[a>>>20&15]+y[a>>>16&15]+y[a>>>12&15]+y[a>>>8&15]+y[a>>>4&15]+y[a&15]+y[n>>>28&15]+y[n>>>24&15]+y[n>>>20&15]+y[n>>>16&15]+y[n>>>12&15]+y[n>>>8&15]+y[n>>>4&15]+y[n&15]+y[r>>>28&15]+y[r>>>24&15]+y[r>>>20&15]+y[r>>>16&15]+y[r>>>12&15]+y[r>>>8&15]+y[r>>>4&15]+y[r&15]+y[i>>>28&15]+y[i>>>24&15]+y[i>>>20&15]+y[i>>>16&15]+y[i>>>12&15]+y[i>>>8&15]+y[i>>>4&15]+y[i&15]+y[c>>>28&15]+y[c>>>24&15]+y[c>>>20&15]+y[c>>>16&15]+y[c>>>12&15]+y[c>>>8&15]+y[c>>>4&15]+y[c&15]+y[h>>>28&15]+y[h>>>24&15]+y[h>>>20&15]+y[h>>>16&15]+y[h>>>12&15]+y[h>>>8&15]+y[h>>>4&15]+y[h&15];return this.is224||(b+=y[l>>>28&15]+y[l>>>24&15]+y[l>>>20&15]+y[l>>>16&15]+y[l>>>12&15]+y[l>>>8&15]+y[l>>>4&15]+y[l&15]),b};B.prototype.toString=B.prototype.hex;B.prototype.digest=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,b=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||b.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),b};B.prototype.array=B.prototype.digest;B.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),a=new DataView(e);return a.setUint32(0,this.h0),a.setUint32(4,this.h1),a.setUint32(8,this.h2),a.setUint32(12,this.h3),a.setUint32(16,this.h4),a.setUint32(20,this.h5),a.setUint32(24,this.h6),this.is224||a.setUint32(28,this.h7),e};const lt=(...e)=>new B(!1,!0).update(e.join("")).hex();var Fa={};U(Fa,{sha256:()=>lt});var La={};U(La,{BaseCache:()=>pt,InMemoryCache:()=>gt,defaultHashKeyEncoder:()=>ht,deserializeStoredGeneration:()=>Da,serializeGeneration:()=>Ba});const ht=(...e)=>lt(e.join("_"));function Da(e){return e.message!==void 0?{text:e.text,message:sa(e.message)}:{text:e.text}}function Ba(e){const a={text:e.text};return e.message!==void 0&&(a.message=e.message.toDict()),a}var pt=class{keyEncoder=ht;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const Ua=new Map;var gt=class mt extends pt{cache;constructor(a){super(),this.cache=a??new Map}lookup(a,n){return Promise.resolve(this.cache.get(this.keyEncoder(a,n))??null)}async update(a,n,r){this.cache.set(this.keyEncoder(a,n),r)}static global(){return new mt(Ua)}},q={},Ze;function ja(){if(Ze)return q;Ze=1,q.byteLength=l,q.toByteArray=f,q.fromByteArray=E;for(var e=[],a=[],n=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=r.length;i<c;++i)e[i]=r[i],a[r.charCodeAt(i)]=i;a[45]=62,a[95]=63;function h(g){var d=g.length;if(d%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var m=g.indexOf("=");m===-1&&(m=d);var v=m===d?0:4-m%4;return[m,v]}function l(g){var d=h(g),m=d[0],v=d[1];return(m+v)*3/4-v}function b(g,d,m){return(d+m)*3/4-m}function f(g){var d,m=h(g),v=m[0],w=m[1],A=new n(b(g,v,w)),C=0,P=w>0?v-4:v,O;for(O=0;O<P;O+=4)d=a[g.charCodeAt(O)]<<18|a[g.charCodeAt(O+1)]<<12|a[g.charCodeAt(O+2)]<<6|a[g.charCodeAt(O+3)],A[C++]=d>>16&255,A[C++]=d>>8&255,A[C++]=d&255;return w===2&&(d=a[g.charCodeAt(O)]<<2|a[g.charCodeAt(O+1)]>>4,A[C++]=d&255),w===1&&(d=a[g.charCodeAt(O)]<<10|a[g.charCodeAt(O+1)]<<4|a[g.charCodeAt(O+2)]>>2,A[C++]=d>>8&255,A[C++]=d&255),A}function T(g){return e[g>>18&63]+e[g>>12&63]+e[g>>6&63]+e[g&63]}function _(g,d,m){for(var v,w=[],A=d;A<m;A+=3)v=(g[A]<<16&16711680)+(g[A+1]<<8&65280)+(g[A+2]&255),w.push(T(v));return w.join("")}function E(g){for(var d,m=g.length,v=m%3,w=[],A=16383,C=0,P=m-v;C<P;C+=A)w.push(_(g,C,C+A>P?P:C+A));return v===1?(d=g[m-1],w.push(e[d>>2]+e[d<<4&63]+"==")):v===2&&(d=(g[m-2]<<8)+g[m-1],w.push(e[d>>10]+e[d>>4&63]+e[d<<2&63]+"=")),w.join("")}return q}var Va=ja();const za=Oa(Va);var Ga=Object.defineProperty,Za=(e,a,n)=>a in e?Ga(e,a,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[a]=n,$a=(e,a,n)=>(Za(e,a+"",n),n);function Ha(e,a){let n=Array.from({length:e.length},(r,i)=>({start:i,end:i+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){const c=e.slice(n[i].start,n[i+1].end),h=a.get(c.join(","));h!=null&&(r==null||h<r[0])&&(r=[h,i])}if(r!=null){const i=r[1];n[i]={start:n[i].start,end:n[i+1].end},n.splice(i+1,1)}else break}return n}function Wa(e,a){return e.length===1?[a.get(e.join(","))]:Ha(e,a).map(n=>a.get(e.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function Ja(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var Ee=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,a){this.patStr=e.pat_str;const n=e.bpe_ranks.split(`
|
|
1
|
+
import{N as Ue,O as je,P as J,Q as ae,i as Ae,S as H,y as le,g as U,U as Nt,V as kt,W as xt,X as Pt,Y as Mt,Z as Rt,$ as Ft,a0 as Lt,a1 as Dt,a2 as Bt,h as Ut,a3 as jt,a4 as Vt,a5 as zt,b as Gt,a6 as Zt,a7 as $t,a8 as Ht,a9 as Wt,aa as Jt,r as Xt,ab as Yt,a as $e,ac as Kt,ad as He,ae as qt,af as Qt,ag as ea,ah as Se,ai as ta,aj as aa,ak as sa,q as We,al as re,e as oe,am as Je,an as Xe,x as ce,L as na,C as ye,ao as Ve,w as ra,R as ze,z as X,t as ia,ap as Ie,E as oa,M as Ye,aq as ca,ar as ua,as as la,B as Ke,at as ie,k as G,au as qe,av as ha,aw as Qe,ax as pa,l as ga,m as ma,ay as fa,az as da,aA as ba,aB as ya,aC as _a,aD as Ta,aE as va,aF as Ea,D as Ge,aG as wa,G as Ca,aH as Aa,aI as Sa,aJ as ve,o as et,s as tt,u as Ia}from"./index-BiUxRAkS.js";import{c as Oa}from"./index-DoHGzyNN.js";function at(e,a,n,r,i){if(a!==e){typeof a.toJSON=="function"&&(a=a.toJSON());for(var c=Ue(a),h=Ue(e),l=!1,b=h.length-1;b>=0;b--){var f=h[b],T=e[f];if(je(a,f)&&!(a[f]===void 0&&T!==void 0&&Array.isArray(a)===!1)){var _=a[f];typeof T=="object"&&T!=null&&typeof _=="object"&&_!=null&&Array.isArray(T)===Array.isArray(_)?at(T,_,n,r+"/"+J(f),i):T!==_&&(i&&n.push({op:"test",path:r+"/"+J(f),value:ae(T)}),n.push({op:"replace",path:r+"/"+J(f),value:ae(_)}))}else Array.isArray(e)===Array.isArray(a)?(i&&n.push({op:"test",path:r+"/"+J(f),value:ae(T)}),n.push({op:"remove",path:r+"/"+J(f)}),l=!0):(i&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:a}))}if(!(!l&&c.length==h.length))for(var b=0;b<c.length;b++){var f=c[b];!je(e,f)&&a[f]!==void 0&&n.push({op:"add",path:r+"/"+J(f),value:ae(a[f])})}}}function Oe(e,a,n=!1){var r=[];return at(e,a,r,"",n),r}function st(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function nt(e){return e!==void 0&&H.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function rt(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Ae(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function it(e){return rt(e)||nt(e)||st(e)}var Na={};U(Na,{convertToOpenAIFunction:()=>ot,convertToOpenAITool:()=>ka,isLangChainTool:()=>it,isRunnableToolLike:()=>nt,isStructuredTool:()=>st,isStructuredToolParams:()=>rt});function ot(e,a){const n=typeof a=="number"?void 0:a;return{name:e.name,description:e.description,parameters:le(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function ka(e,a){const n=typeof a=="number"?void 0:a;let r;return it(e)?r={type:"function",function:ot(e)}:r=e,n?.strict!==void 0&&(r.function.strict=n.strict),r}var xa={};U(xa,{extendInteropZodObject:()=>ea,getInteropZodDefaultGetter:()=>Qt,getInteropZodObjectShape:()=>qt,getSchemaDescription:()=>He,interopParse:()=>Kt,interopParseAsync:()=>$e,interopSafeParse:()=>Yt,interopSafeParseAsync:()=>Xt,interopZodObjectMakeFieldsOptional:()=>Jt,interopZodObjectPartial:()=>Wt,interopZodObjectPassthrough:()=>Ht,interopZodObjectStrict:()=>$t,interopZodTransformInputSchema:()=>Zt,isInteropZodError:()=>Gt,isInteropZodLiteral:()=>zt,isInteropZodObject:()=>Vt,isInteropZodSchema:()=>Ae,isShapelessZodSchema:()=>jt,isSimpleStringZodSchema:()=>Ut,isZodArrayV4:()=>Bt,isZodLiteralV3:()=>Dt,isZodLiteralV4:()=>Lt,isZodNullableV4:()=>Ft,isZodObjectV3:()=>Rt,isZodObjectV4:()=>Mt,isZodOptionalV4:()=>Pt,isZodSchema:()=>xt,isZodSchemaV3:()=>kt,isZodSchemaV4:()=>Nt});var Pa={};U(Pa,{BasePromptValue:()=>he,ChatPromptValue:()=>ut,ImagePromptValue:()=>Ma,StringPromptValue:()=>ct});var he=class extends aa{},ct=class extends he{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new Se(this.value)]}},ut=class extends he{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return ta(this.messages)}toChatMessages(){return this.messages}},Ma=class extends he{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Se({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},y="0123456789abcdef".split(""),Ra=[-2147483648,8388608,32768,128],D=[24,16,8,0],se=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],M=[];function B(e,a){a?(M[0]=M[16]=M[1]=M[2]=M[3]=M[4]=M[5]=M[6]=M[7]=M[8]=M[9]=M[10]=M[11]=M[12]=M[13]=M[14]=M[15]=0,this.blocks=M):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}B.prototype.update=function(e){if(!this.finalized){var a,n=typeof e;if(n!=="string"){if(n==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);a=!0}for(var r,i=0,c,h=e.length,l=this.blocks;i<h;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),a)for(c=this.start;i<h&&c<64;++i)l[c>>>2]|=e[i]<<D[c++&3];else for(c=this.start;i<h&&c<64;++i)r=e.charCodeAt(i),r<128?l[c>>>2]|=r<<D[c++&3]:r<2048?(l[c>>>2]|=(192|r>>>6)<<D[c++&3],l[c>>>2]|=(128|r&63)<<D[c++&3]):r<55296||r>=57344?(l[c>>>2]|=(224|r>>>12)<<D[c++&3],l[c>>>2]|=(128|r>>>6&63)<<D[c++&3],l[c>>>2]|=(128|r&63)<<D[c++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),l[c>>>2]|=(240|r>>>18)<<D[c++&3],l[c>>>2]|=(128|r>>>12&63)<<D[c++&3],l[c>>>2]|=(128|r>>>6&63)<<D[c++&3],l[c>>>2]|=(128|r&63)<<D[c++&3]);this.lastByteIndex=c,this.bytes+=c-this.start,c>=64?(this.block=l[16],this.start=c-64,this.hash(),this.hashed=!0):this.start=c}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};B.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,a=this.lastByteIndex;e[16]=this.block,e[a>>>2]|=Ra[a&3],this.block=e[16],a>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};B.prototype.hash=function(){var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,b=this.blocks,f,T,_,E,g,d,m,v,w,A,C;for(f=16;f<64;++f)g=b[f-15],T=(g>>>7|g<<25)^(g>>>18|g<<14)^g>>>3,g=b[f-2],_=(g>>>17|g<<15)^(g>>>19|g<<13)^g>>>10,b[f]=b[f-16]+T+b[f-7]+_<<0;for(C=a&n,f=0;f<64;f+=4)this.first?(this.is224?(v=300032,g=b[0]-1413257819,l=g-150054599<<0,r=g+24177077<<0):(v=704751109,g=b[0]-210244248,l=g-1521486534<<0,r=g+143694565<<0),this.first=!1):(T=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),_=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),v=e&a,E=v^e&n^C,m=i&c^~i&h,g=l+_+m+se[f]+b[f],d=T+E,l=r+g<<0,r=g+d<<0),T=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),_=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),w=r&e,E=w^r&a^v,m=h&l^~h&i,g=c+_+m+se[f+1]+b[f+1],d=T+E,h=n+g<<0,n=g+d<<0,T=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),_=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),A=n&r,E=A^n&e^w,m=c&h^~c&l,g=i+_+m+se[f+2]+b[f+2],d=T+E,c=a+g<<0,a=g+d<<0,T=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),_=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),C=a&n,E=C^a&r^A,m=c&h^~c&l,g=i+_+m+se[f+3]+b[f+3],d=T+E,i=e+g<<0,e=g+d<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+a<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+c<<0,this.h6=this.h6+h<<0,this.h7=this.h7+l<<0};B.prototype.hex=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,b=y[e>>>28&15]+y[e>>>24&15]+y[e>>>20&15]+y[e>>>16&15]+y[e>>>12&15]+y[e>>>8&15]+y[e>>>4&15]+y[e&15]+y[a>>>28&15]+y[a>>>24&15]+y[a>>>20&15]+y[a>>>16&15]+y[a>>>12&15]+y[a>>>8&15]+y[a>>>4&15]+y[a&15]+y[n>>>28&15]+y[n>>>24&15]+y[n>>>20&15]+y[n>>>16&15]+y[n>>>12&15]+y[n>>>8&15]+y[n>>>4&15]+y[n&15]+y[r>>>28&15]+y[r>>>24&15]+y[r>>>20&15]+y[r>>>16&15]+y[r>>>12&15]+y[r>>>8&15]+y[r>>>4&15]+y[r&15]+y[i>>>28&15]+y[i>>>24&15]+y[i>>>20&15]+y[i>>>16&15]+y[i>>>12&15]+y[i>>>8&15]+y[i>>>4&15]+y[i&15]+y[c>>>28&15]+y[c>>>24&15]+y[c>>>20&15]+y[c>>>16&15]+y[c>>>12&15]+y[c>>>8&15]+y[c>>>4&15]+y[c&15]+y[h>>>28&15]+y[h>>>24&15]+y[h>>>20&15]+y[h>>>16&15]+y[h>>>12&15]+y[h>>>8&15]+y[h>>>4&15]+y[h&15];return this.is224||(b+=y[l>>>28&15]+y[l>>>24&15]+y[l>>>20&15]+y[l>>>16&15]+y[l>>>12&15]+y[l>>>8&15]+y[l>>>4&15]+y[l&15]),b};B.prototype.toString=B.prototype.hex;B.prototype.digest=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,b=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||b.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),b};B.prototype.array=B.prototype.digest;B.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),a=new DataView(e);return a.setUint32(0,this.h0),a.setUint32(4,this.h1),a.setUint32(8,this.h2),a.setUint32(12,this.h3),a.setUint32(16,this.h4),a.setUint32(20,this.h5),a.setUint32(24,this.h6),this.is224||a.setUint32(28,this.h7),e};const lt=(...e)=>new B(!1,!0).update(e.join("")).hex();var Fa={};U(Fa,{sha256:()=>lt});var La={};U(La,{BaseCache:()=>pt,InMemoryCache:()=>gt,defaultHashKeyEncoder:()=>ht,deserializeStoredGeneration:()=>Da,serializeGeneration:()=>Ba});const ht=(...e)=>lt(e.join("_"));function Da(e){return e.message!==void 0?{text:e.text,message:sa(e.message)}:{text:e.text}}function Ba(e){const a={text:e.text};return e.message!==void 0&&(a.message=e.message.toDict()),a}var pt=class{keyEncoder=ht;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const Ua=new Map;var gt=class mt extends pt{cache;constructor(a){super(),this.cache=a??new Map}lookup(a,n){return Promise.resolve(this.cache.get(this.keyEncoder(a,n))??null)}async update(a,n,r){this.cache.set(this.keyEncoder(a,n),r)}static global(){return new mt(Ua)}},q={},Ze;function ja(){if(Ze)return q;Ze=1,q.byteLength=l,q.toByteArray=f,q.fromByteArray=E;for(var e=[],a=[],n=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=r.length;i<c;++i)e[i]=r[i],a[r.charCodeAt(i)]=i;a[45]=62,a[95]=63;function h(g){var d=g.length;if(d%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var m=g.indexOf("=");m===-1&&(m=d);var v=m===d?0:4-m%4;return[m,v]}function l(g){var d=h(g),m=d[0],v=d[1];return(m+v)*3/4-v}function b(g,d,m){return(d+m)*3/4-m}function f(g){var d,m=h(g),v=m[0],w=m[1],A=new n(b(g,v,w)),C=0,P=w>0?v-4:v,O;for(O=0;O<P;O+=4)d=a[g.charCodeAt(O)]<<18|a[g.charCodeAt(O+1)]<<12|a[g.charCodeAt(O+2)]<<6|a[g.charCodeAt(O+3)],A[C++]=d>>16&255,A[C++]=d>>8&255,A[C++]=d&255;return w===2&&(d=a[g.charCodeAt(O)]<<2|a[g.charCodeAt(O+1)]>>4,A[C++]=d&255),w===1&&(d=a[g.charCodeAt(O)]<<10|a[g.charCodeAt(O+1)]<<4|a[g.charCodeAt(O+2)]>>2,A[C++]=d>>8&255,A[C++]=d&255),A}function T(g){return e[g>>18&63]+e[g>>12&63]+e[g>>6&63]+e[g&63]}function _(g,d,m){for(var v,w=[],A=d;A<m;A+=3)v=(g[A]<<16&16711680)+(g[A+1]<<8&65280)+(g[A+2]&255),w.push(T(v));return w.join("")}function E(g){for(var d,m=g.length,v=m%3,w=[],A=16383,C=0,P=m-v;C<P;C+=A)w.push(_(g,C,C+A>P?P:C+A));return v===1?(d=g[m-1],w.push(e[d>>2]+e[d<<4&63]+"==")):v===2&&(d=(g[m-2]<<8)+g[m-1],w.push(e[d>>10]+e[d>>4&63]+e[d<<2&63]+"=")),w.join("")}return q}var Va=ja();const za=Oa(Va);var Ga=Object.defineProperty,Za=(e,a,n)=>a in e?Ga(e,a,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[a]=n,$a=(e,a,n)=>(Za(e,a+"",n),n);function Ha(e,a){let n=Array.from({length:e.length},(r,i)=>({start:i,end:i+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){const c=e.slice(n[i].start,n[i+1].end),h=a.get(c.join(","));h!=null&&(r==null||h<r[0])&&(r=[h,i])}if(r!=null){const i=r[1];n[i]={start:n[i].start,end:n[i+1].end},n.splice(i+1,1)}else break}return n}function Wa(e,a){return e.length===1?[a.get(e.join(","))]:Ha(e,a).map(n=>a.get(e.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function Ja(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var Ee=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,a){this.patStr=e.pat_str;const n=e.bpe_ranks.split(`
|
|
2
2
|
`).filter(Boolean).reduce((r,i)=>{const[c,h,...l]=i.split(" "),b=Number.parseInt(h,10);return l.forEach((f,T)=>r[f]=b+T),r},{});for(const[r,i]of Object.entries(n)){const c=za.toByteArray(r);this.rankMap.set(c.join(","),i),this.textMap.set(i,c)}this.specialTokens={...e.special_tokens,...a},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[i,c])=>(r[c]=this.textEncoder.encode(i),r),{})}encode(e,a=[],n="all"){const r=new RegExp(this.patStr,"ug"),i=Ee.specialTokenRegex(Object.keys(this.specialTokens)),c=[],h=new Set(a==="all"?Object.keys(this.specialTokens):a),l=new Set(n==="all"?Object.keys(this.specialTokens).filter(f=>!h.has(f)):n);if(l.size>0){const f=Ee.specialTokenRegex([...l]),T=e.match(f);if(T!=null)throw new Error(`The text contains a special token that is not allowed: ${T[0]}`)}let b=0;for(;;){let f=null,T=b;for(;i.lastIndex=T,f=i.exec(e),!(f==null||h.has(f[0]));)T=f.index+1;const _=f?.index??e.length;for(const g of e.substring(b,_).matchAll(r)){const d=this.textEncoder.encode(g[0]),m=this.rankMap.get(d.join(","));if(m!=null){c.push(m);continue}c.push(...Wa(d,this.rankMap))}if(f==null)break;let E=this.specialTokens[f[0]];c.push(E),b=f.index+f[0].length}return c}decode(e){const a=[];let n=0;for(let c=0;c<e.length;++c){const h=e[c],l=this.textMap.get(h)??this.inverseSpecialTokens[h];l!=null&&(a.push(l),n+=l.length)}const r=new Uint8Array(n);let i=0;for(const c of a)r.set(c,i),i+=c.length;return this.textDecoder.decode(r)}},ft=Ee;$a(ft,"specialTokenRegex",e=>new RegExp(e.map(a=>Ja(a)).join("|"),"g"));function Xa(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var Ya={};U(Ya,{encodingForModel:()=>Ne,getEncoding:()=>dt});const ne={},Ka=new We({});async function dt(e){return e in ne||(ne[e]=Ka.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(a=>a.json()).then(a=>new ft(a)).catch(a=>{throw delete ne[e],a})),await ne[e]}async function Ne(e){return dt(Xa(e))}var qa={};U(qa,{BaseLangChain:()=>yt,BaseLanguageModel:()=>_t,calculateMaxTokens:()=>ts,getEmbeddingContextSize:()=>Qa,getModelContextSize:()=>bt,getModelNameForTiktoken:()=>pe,isOpenAITool:()=>es});const pe=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,Qa=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},bt=e=>{switch(pe(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function es(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}const ts=async({prompt:e,modelName:a})=>{let n;try{n=(await Ne(pe(a))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(e.length/4)}return bt(a)-n},as=()=>!1;var yt=class extends H{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??as(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},_t=class extends yt{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:a,...n}){const{cache:r,...i}=n;super({callbacks:e??a,...i}),typeof r=="object"?this.cache=r:r?this.cache=gt.global():this.cache=void 0,this.caller=new We(n??{})}_encoding;async getNumTokens(e){let a;typeof e=="string"?a=e:a=e.map(r=>typeof r=="string"?r:r.type==="text"&&"text"in r?r.text:"").join("");let n=Math.ceil(a.length/4);if(!this._encoding)try{this._encoding=await Ne("modelName"in this?pe(this.modelName):"gpt2")}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}if(this._encoding)try{n=this._encoding.encode(a).length}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}return n}static _convertInputToPromptValue(e){return typeof e=="string"?new ct(e):Array.isArray(e)?new ut(e.map(re)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...a}){const n={...this._identifyingParams(),...a,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([c,h])=>h!==void 0).map(([c,h])=>`${c}:${JSON.stringify(h)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}},ue=class extends H{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,a){const n=oe(a);return this.func&&await this.func(e,n),this._callWithConfig(r=>Promise.resolve(r),e,n)}async*transform(e,a){const n=oe(a);let r,i=!0;for await(const c of this._transformStreamWithConfig(e,h=>h,n))if(yield c,i)if(r===void 0)r=c;else try{r=ce(r,c)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new Je(new Xe({steps:e}))}};const ss=e=>e();function _e(e){const a=e.constructor;return new a({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var ns={};U(ns,{BaseChatModel:()=>Tt,SimpleChatModel:()=>rs});function Te(e){const a=[];for(const n of e){let r=n;if(Array.isArray(n.content))for(let i=0;i<n.content.length;i++){const c=n.content[i];(ca(c)||ua(c))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,i),la(c),...n.content.slice(i+1)]}))}a.push(r)}return a}var Tt=class Z extends _t{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(a){super(a),this.outputVersion=ss(()=>{const n=a.outputVersion??na("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}_separateRunnableConfigFromCallOptionsCompat(a){const[n,r]=super._separateRunnableConfigFromCallOptions(a);return r.signal=n.signal,[n,r]}async invoke(a,n){const r=Z._convertInputToPromptValue(a);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(a,n,r){throw new Error("Not implemented.")}async*_streamIterator(a,n){if(this._streamResponseChunks===Z.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(a,n);else{const i=Z._convertInputToPromptValue(a).toChatMessages(),[c,h]=this._separateRunnableConfigFromCallOptionsCompat(n),l={...c.metadata,...this.getLsParams(h)},b=await ye.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose}),f={options:h,invocation_params:this?.invocationParams(h),batch_size:1},T=h.outputVersion??this.outputVersion,_=await b?.handleChatModelStart(this.toJSON(),[Te(i)],c.runId,void 0,f,void 0,void 0,c.runName);let E,g;try{for await(const d of this._streamResponseChunks(i,h,_?.[0])){if(d.message.id==null){const m=_?.at(0)?.runId;m!=null&&d.message._updateId(`run-${m}`)}d.message.response_metadata={...d.generationInfo,...d.message.response_metadata},T==="v1"?yield _e(d.message):yield d.message,E?E=E.concat(d):E=d,Ve(d.message)&&d.message.usage_metadata!==void 0&&(g={tokenUsage:{promptTokens:d.message.usage_metadata.input_tokens,completionTokens:d.message.usage_metadata.output_tokens,totalTokens:d.message.usage_metadata.total_tokens}})}}catch(d){throw await Promise.all((_??[]).map(m=>m?.handleLLMError(d))),d}await Promise.all((_??[]).map(d=>d?.handleLLMEnd({generations:[[E]],llmOutput:g})))}}getLsParams(a){const n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:a.stop,ls_provider:n}}async _generateUncached(a,n,r,i){const c=a.map(E=>E.map(re));let h;if(i!==void 0&&i.length===c.length)h=i;else{const E={...r.metadata,...this.getLsParams(n)},g=await ye.configure(r.callbacks,this.callbacks,r.tags,this.tags,E,this.metadata,{verbose:this.verbose}),d={options:n,invocation_params:this?.invocationParams(n),batch_size:1};h=await g?.handleChatModelStart(this.toJSON(),c.map(Te),r.runId,void 0,d,void 0,void 0,r.runName)}const l=n.outputVersion??this.outputVersion,b=[],f=[];if(!!h?.[0].handlers.find(ra)&&!this.disableStreaming&&c.length===1&&this._streamResponseChunks!==Z.prototype._streamResponseChunks)try{const E=await this._streamResponseChunks(c[0],n,h?.[0]);let g,d;for await(const m of E){if(m.message.id==null){const v=h?.at(0)?.runId;v!=null&&m.message._updateId(`run-${v}`)}g===void 0?g=m:g=ce(g,m),Ve(m.message)&&m.message.usage_metadata!==void 0&&(d={tokenUsage:{promptTokens:m.message.usage_metadata.input_tokens,completionTokens:m.message.usage_metadata.output_tokens,totalTokens:m.message.usage_metadata.total_tokens}})}if(g===void 0)throw new Error("Received empty response from chat model call.");b.push([g]),await h?.[0].handleLLMEnd({generations:b,llmOutput:d})}catch(E){throw await h?.[0].handleLLMError(E),E}else{const E=await Promise.allSettled(c.map(async(g,d)=>{const m=await this._generate(g,{...n,promptIndex:d},h?.[d]);if(l==="v1")for(const v of m.generations)v.message=_e(v.message);return m}));await Promise.all(E.map(async(g,d)=>{if(g.status==="fulfilled"){const m=g.value;for(const v of m.generations){if(v.message.id==null){const w=h?.at(0)?.runId;w!=null&&v.message._updateId(`run-${w}`)}v.message.response_metadata={...v.generationInfo,...v.message.response_metadata}}return m.generations.length===1&&(m.generations[0].message.response_metadata={...m.llmOutput,...m.generations[0].message.response_metadata}),b[d]=m.generations,f[d]=m.llmOutput,h?.[d]?.handleLLMEnd({generations:[m.generations],llmOutput:m.llmOutput})}else return await h?.[d]?.handleLLMError(g.reason),Promise.reject(g.reason)}))}const _={generations:b,llmOutput:f.length?this._combineLLMOutput?.(...f):void 0};return Object.defineProperty(_,ze,{value:h?{runIds:h?.map(E=>E.runId)}:void 0,configurable:!0}),_}async _generateCached({messages:a,cache:n,llmStringKey:r,parsedOptions:i,handledOptions:c}){const h=a.map(w=>w.map(re)),l={...c.metadata,...this.getLsParams(i)},b=await ye.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose}),f={options:i,invocation_params:this?.invocationParams(i),batch_size:1},T=await b?.handleChatModelStart(this.toJSON(),h.map(Te),c.runId,void 0,f,void 0,void 0,c.runName),_=[],g=(await Promise.allSettled(h.map(async(w,A)=>{const C=Z._convertInputToPromptValue(w).toString(),P=await n.lookup(C,r);return P==null&&_.push(A),P}))).map((w,A)=>({result:w,runManager:T?.[A]})).filter(({result:w})=>w.status==="fulfilled"&&w.value!=null||w.status==="rejected"),d=i.outputVersion??this.outputVersion,m=[];await Promise.all(g.map(async({result:w,runManager:A},C)=>{if(w.status==="fulfilled"){const P=w.value;return m[C]=P.map(O=>("message"in O&&X(O.message)&&ia(O.message)&&(O.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},d==="v1"&&(O.message=_e(O.message))),O.generationInfo={...O.generationInfo,tokenUsage:{}},O)),P.length&&await A?.handleLLMNewToken(P[0].text),A?.handleLLMEnd({generations:[P]},void 0,void 0,void 0,{cached:!0})}else return await A?.handleLLMError(w.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(w.reason)}));const v={generations:m,missingPromptIndices:_,startedRunManagers:T};return Object.defineProperty(v,ze,{value:T?{runIds:T?.map(w=>w.runId)}:void 0,configurable:!0}),v}async generate(a,n,r){let i;Array.isArray(n)?i={stop:n}:i=n;const c=a.map(d=>d.map(re)),[h,l]=this._separateRunnableConfigFromCallOptionsCompat(i);if(h.callbacks=h.callbacks??r,!this.cache)return this._generateUncached(c,l,h);const{cache:b}=this,f=this._getSerializedCacheKeyParametersForCall(l),{generations:T,missingPromptIndices:_,startedRunManagers:E}=await this._generateCached({messages:c,cache:b,llmStringKey:f,parsedOptions:l,handledOptions:h});let g={};if(_.length>0){const d=await this._generateUncached(_.map(m=>c[m]),l,h,E!==void 0?_.map(m=>E?.[m]):void 0);await Promise.all(d.generations.map(async(m,v)=>{const w=_[v];T[w]=m;const A=Z._convertInputToPromptValue(c[w]).toString();return b.update(A,f,m)})),g=d.llmOutput??{}}return{generations:T,llmOutput:g}}invocationParams(a){return{}}_modelType(){return"base_chat_model"}async generatePrompt(a,n,r){const i=a.map(c=>c.toChatMessages());return this.generate(i,n,r)}withStructuredOutput(a,n){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(n?.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=a,i=n?.name,c=He(r)??"A function available to call.",h=n?.method,l=n?.includeRaw;if(h==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let b=i??"extract",f;Ae(r)?f=[{type:"function",function:{name:b,description:c,parameters:le(r)}}]:("name"in r&&(b=r.name),f=[{type:"function",function:{name:b,description:c,parameters:r}}]);const T=this.bindTools(f),_=Ie.from(m=>{if(!oa.isInstance(m))throw new Error("Input is not an AIMessageChunk.");if(!m.tool_calls||m.tool_calls.length===0)throw new Error("No tool calls found in the response.");const v=m.tool_calls.find(w=>w.name===b);if(!v)throw new Error(`No tool call found with name ${b}.`);return v.args});if(!l)return T.pipe(_).withConfig({runName:"StructuredOutput"});const E=ue.assign({parsed:(m,v)=>_.invoke(m.raw,v)}),g=ue.assign({parsed:()=>null}),d=E.withFallbacks({fallbacks:[g]});return Ye.from([{raw:T},d]).withConfig({runName:"StructuredOutputRunnable"})}},rs=class extends Tt{async _generate(e,a,n){const r=await this._call(e,a,n),i=new Ke(r);if(typeof i.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:i.content,message:i}]}}},is=class extends H{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,a){const{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw new Error(`No runnable associated with key "${n}".`);return i.invoke(r,oe(a))}async batch(e,a,n){const r=e.map(_=>_.key),i=e.map(_=>_.input);if(r.find(_=>this.runnables[_]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const h=r.map(_=>this.runnables[_]),l=this._getOptionsList(a??{},e.length),b=l[0]?.maxConcurrency??n?.maxConcurrency,f=b&&b>0?b:e.length,T=[];for(let _=0;_<i.length;_+=f){const E=i.slice(_,_+f).map((d,m)=>h[m].invoke(d,l[m])),g=await Promise.all(E);T.push(g)}return T.flat()}async stream(e,a){const{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw new Error(`No runnable associated with key "${n}".`);return i.stream(r,a)}},os=class extends H{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");const n=e.slice(0,-1).map(([i,c])=>[ie(i),ie(c)]),r=ie(e[e.length-1]);return new this({branches:n,default:r})}async _invoke(e,a,n){let r;for(let i=0;i<this.branches.length;i+=1){const[c,h]=this.branches[i];if(await c.invoke(e,G(a,{callbacks:n?.getChild(`condition:${i+1}`)}))){r=await h.invoke(e,G(a,{callbacks:n?.getChild(`branch:${i+1}`)}));break}}return r||(r=await this.default.invoke(e,G(a,{callbacks:n?.getChild("branch:default")}))),r}async invoke(e,a={}){return this._callWithConfig(this._invoke,e,a)}async*_streamIterator(e,a){const r=await(await qe(a))?.handleChainStart(this.toJSON(),ha(e,"input"),a?.runId,void 0,void 0,void 0,a?.runName);let i,c=!0,h;try{for(let l=0;l<this.branches.length;l+=1){const[b,f]=this.branches[l];if(await b.invoke(e,G(a,{callbacks:r?.getChild(`condition:${l+1}`)}))){h=await f.stream(e,G(a,{callbacks:r?.getChild(`branch:${l+1}`)}));for await(const _ of h)if(yield _,c)if(i===void 0)i=_;else try{i=ce(i,_)}catch{i=void 0,c=!1}break}}if(h===void 0){h=await this.default.stream(e,G(a,{callbacks:r?.getChild("branch:default")}));for await(const l of h)if(yield l,c)if(i===void 0)i=l;else try{i=ce(i,l)}catch{i=void 0,c=!1}}}catch(l){throw await r?.handleChainError(l),l}await r?.handleChainEnd(i??{})}},cs=class extends Qe{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let a=Ie.from((c,h)=>this._enterHistory(c,h??{})).withConfig({runName:"loadHistory"});const n=e.historyMessagesKey??e.inputMessagesKey;n&&(a=ue.assign({[n]:a}).withConfig({runName:"insertHistory"}));const r=a.pipe(e.runnable.withListeners({onEnd:(c,h)=>this._exitHistory(c,h??{})})).withConfig({runName:"RunnableWithMessageHistory"}),i=e.config??{};super({...e,config:i,bound:r}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let a;if(typeof e=="object"&&!Array.isArray(e)&&!X(e)){let n;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="input",Array.isArray(e[n])&&Array.isArray(e[n][0])?a=e[n][0]:a=e[n]}else a=e;if(typeof a=="string")return[new Se(a)];if(Array.isArray(a))return a;if(X(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
|
|
3
3
|
Got ${JSON.stringify(a,null,2)}`)}_getOutputMessages(e){let a;if(!Array.isArray(e)&&!X(e)&&typeof e!="string"){let n;this.outputMessagesKey!==void 0?n=this.outputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="output",e.generations!==void 0?a=e.generations[0][0].message:a=e[n]}else a=e;if(typeof a=="string")return[new Ke(a)];if(Array.isArray(a))return a;if(X(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(a,null,2)}`)}async _enterHistory(e,a){const r=await(a?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(e)):r}async _exitHistory(e,a){const n=a.configurable?.messageHistory;let r;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?r=e.inputs[0]:r=e.inputs;let i=this._getInputMessages(r);if(this.historyMessagesKey===void 0){const l=await n.getMessages();i=i.slice(l.length)}const c=e.outputs;if(!c)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const h=this._getOutputMessages(c);await n.addMessages([...i,...h])}async _mergeConfig(...e){const a=await super._mergeConfig(...e);if(!a.configurable||!a.configurable.sessionId){const r={[this.inputMessagesKey??"input"]:"foo"},i={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
|
|
4
4
|
eg. chain.invoke(${JSON.stringify(r)}, ${JSON.stringify(i)})`)}const{sessionId:n}=a.configurable;return a.configurable.messageHistory=await this.getMessageHistory(n),a}},us={};U(us,{RouterRunnable:()=>is,Runnable:()=>H,RunnableAssign:()=>Je,RunnableBinding:()=>Qe,RunnableBranch:()=>os,RunnableEach:()=>Ta,RunnableLambda:()=>Ie,RunnableMap:()=>Xe,RunnableParallel:()=>_a,RunnablePassthrough:()=>ue,RunnablePick:()=>ya,RunnableRetry:()=>ba,RunnableSequence:()=>Ye,RunnableToolLike:()=>da,RunnableWithFallbacks:()=>fa,RunnableWithMessageHistory:()=>cs,_coerceToRunnable:()=>ie,ensureConfig:()=>oe,getCallbackManagerForConfig:()=>qe,mergeConfigs:()=>ma,patchConfig:()=>G,pickRunnableConfigKeys:()=>ga,raceWithSignal:()=>pa});var vt=class extends H{parseResultWithPrompt(e,a,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,a){return typeof e=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r?.callbacks),e,{...a,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r?.callbacks),e,{...a,runType:"parser"})}},ge=class extends vt{parseResult(e,a){return this.parse(e[0].text,a)}async parseWithPrompt(e,a,n){return this.parse(e,n)}_type(){throw new Error("_type not implemented")}},$=class extends Error{llmOutput;observation;sendToLLM;constructor(e,a,n,r=!1){if(super(e),this.llmOutput=a,this.observation=n,this.sendToLLM=r,r&&(n===void 0||a===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");va(this,"OUTPUT_PARSING_FAILURE")}},Q=class extends ge{async*_transform(e){for await(const a of e)typeof a=="string"?yield this.parseResult([{text:a}]):yield this.parseResult([{message:a,text:this._baseMessageToString(a)}])}async*transform(e,a){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...a,runType:"parser"})}},ke=class extends Q{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let a,n;for await(const r of e){if(typeof r!="string"&&typeof r.content!="string")throw new Error("Cannot handle non-string output.");let i;if(Ea(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");i=new Ge({message:r,text:r.content})}else if(X(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");i=new Ge({message:wa(r),text:r.content})}else i=new Ca({text:r});n===void 0?n=i:n=n.concat(i);const c=await this.parsePartialResult([n]);c!=null&&!Aa(c,a)&&(this.diff?yield this._diff(a,c):yield c,a=c)}}getFormatInstructions(){return""}},ls={};U(ls,{applyPatch:()=>Sa,compare:()=>Oe});var hs=class extends ke{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(e,a){return this.diff?super._concatOutputChunks(e,a):a}_diff(e,a){if(a)return e?Oe(e,a):[{op:"replace",path:"",value:a}]}async parsePartialResult(e){return ve(e[0].text)}async parse(e){return ve(e,JSON.parse)}getFormatInstructions(){return""}},ps=class extends Q{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}},ee=class extends Q{re;async*_transform(e){let a="";for await(const n of e)if(typeof n=="string"?a+=n:a+=n.content,this.re){const r=[...a.matchAll(this.re)];if(r.length>1){let i=0;for(const c of r.slice(0,-1))yield[c[1]],i+=(c.index??0)+c[0].length;a=a.slice(i)}}else{const r=await this.parse(a);if(r.length>1){for(const i of r.slice(0,-1))yield[i];a=r[r.length-1]}}for(const n of await this.parse(a))yield[n]}},gs=class extends ee{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(a=>a.trim())}catch{throw new $(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},ms=class extends ee{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:a}){super(...arguments),this.length=e,this.separator=a||","}async parse(e){try{const a=e.trim().split(this.separator).map(n=>n.trim());if(this.length!==void 0&&a.length!==this.length)throw new $(`Incorrect number of items. Expected ${this.length}, got ${a.length}.`);return a}catch(a){throw Object.getPrototypeOf(a)===$.prototype?a:new $(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},fs=class extends ee{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{g as wn,O as Ut,h as bn,c as $t,f as xn,S as kn,J as Sn,R as Bt}from"./index-w9z_NOXw.js";import{r as Tn,K as xs,t as Lt,ah as jt,I as Mn,J as On,E as N,B as qt,L as vn,y as ie,i as at,D as In,M as Rn}from"./index-B66nJ4Ui.js";import{o as y,i as Wt,j as An,k as Cn,u as Dt,s as b,m as w,n as E,q as Ze,t as Mt,v as Pn,w as En}from"./index-BYhrMpLe.js";import"./index-CWxR53gB.js";var Ft=class extends wn{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(n){throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const s=await Tn(this.zodSchema,e);if(s.success)return s.data;throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:a}=r;return Array.isArray(a.content)?ks(a.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[s]=e;return await this._validateResult(s.args)}};function ks(t){const e=[];for(const s of t)s.type==="tool_use"&&e.push({name:s.name,args:s.input,id:s.id,type:"tool_call"});return e}function Nn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}const Un=y({cache_control:Cn().optional().nullable(),defer_loading:An().optional(),input_examples:Wt(Dt()).optional(),allowed_callers:Wt(Dt()).optional()}),Ht={tool_search_tool_regex_20251119:"advanced-tool-use-2025-11-20",tool_search_tool_bm25_20251119:"advanced-tool-use-2025-11-20",memory_20250818:"context-management-2025-06-27",web_fetch_20250910:"web-fetch-2025-09-10",code_execution_20250825:"code-execution-2025-08-25",computer_20251124:"computer-use-2025-11-24",computer_20250124:"computer-use-2025-01-24",mcp_toolset:"mcp-client-2025-11-20"};function $n(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Bn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function Ln(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function jn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=xs({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Wn=t=>t();function Dn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Fn(t){function*e(){for(const s of t)Dn(s)&&(s.source==="char"?yield{type:"char_location",file_id:s.url??"",start_char_index:s.startIndex??0,end_char_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="page"?yield{type:"page_location",file_id:s.url??"",start_page_number:s.startIndex??0,end_page_number:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="block"?yield{type:"content_block_location",file_id:s.url??"",start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="url"?yield{type:"web_search_result_location",url:s.url??"",title:s.title??null,encrypted_index:String(s.startIndex??0),cited_text:s.citedText??""}:s.source==="search"&&(yield{type:"search_result_location",title:s.title??null,start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,search_result_index:0,source:s.source??"",cited_text:s.citedText??""}))}return Array.from(e())}function oe(t){return typeof t=="string"?t:Hn(t)}function Hn(t){const e=[];for(let s=0,{length:n}=t;s<n;s++)e.push(String.fromCharCode(t[s]));return btoa(e.join(""))}function it(t){return(t??"").split(";")[0].toLowerCase()}function Se(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function Z(t,e){const s=Se(e,"cache_control");s!==void 0&&(t.cache_control=s);const n=Se(e,"citations");n!==void 0&&(t.citations=n);const r=Se(e,"context");r!==void 0&&(t.context=r);const a=Se(e,"title");return a!==void 0&&(t.title=a),t}function ot(t,e){const s=Se(e,"cache_control");return s!==void 0&&(t.cache_control=s),t}function Jt(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function Jn(t){const e=[],s=t.response_metadata,n="model_provider"in s&&s?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Fn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const a=Wn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:a})}else if(r.type==="reasoning"&&n)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&n)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&n)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const a=r.output.urls.map(i=>({type:"web_search_result",title:"",encrypted_content:"",url:i}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:a})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const a=r.metadata;if(r.fileId){e.push(Z({type:"document",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){const i=it(r.mimeType);if(i==="application/pdf"||i===""){e.push(Z({type:"document",source:{type:"url",url:r.url}},a));continue}}if(r.data){const i=it(r.mimeType);if(i===""||i==="application/pdf")e.push(Z({type:"document",source:{type:"base64",data:oe(r.data),media_type:"application/pdf"}},a));else if(i==="text/plain")e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},a));else if(Jt(i))e.push(Z({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:oe(r.data),media_type:i}}]}},a));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${i}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const a=r.metadata;if(r.fileId){e.push(ot({type:"image",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){e.push(ot({type:"image",source:{type:"url",url:r.url}},a));continue}if(r.data){const i=it(r.mimeType)||"image/png";Jt(i)&&e.push(ot({type:"image",source:{type:"base64",data:oe(r.data),media_type:i}},a));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&n&&e.push(r.value))}return e}function Kt(t){const e=xs({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let s;try{s=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
|
|
1
|
+
import{g as wn,O as Ut,h as bn,c as $t,f as xn,S as kn,J as Sn,R as Bt}from"./index-01y2e9ko.js";import{r as Tn,K as xs,t as Lt,ah as jt,I as Mn,J as On,E as N,B as qt,L as vn,y as ie,i as at,D as In,M as Rn}from"./index-BiUxRAkS.js";import{o as y,i as Wt,j as An,k as Cn,u as Dt,s as b,m as w,n as E,q as Ze,t as Mt,v as Pn,w as En}from"./index-DoHGzyNN.js";import"./index-CwGEcSpK.js";var Ft=class extends wn{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(n){throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const s=await Tn(this.zodSchema,e);if(s.success)return s.data;throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:a}=r;return Array.isArray(a.content)?ks(a.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[s]=e;return await this._validateResult(s.args)}};function ks(t){const e=[];for(const s of t)s.type==="tool_use"&&e.push({name:s.name,args:s.input,id:s.id,type:"tool_call"});return e}function Nn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}const Un=y({cache_control:Cn().optional().nullable(),defer_loading:An().optional(),input_examples:Wt(Dt()).optional(),allowed_callers:Wt(Dt()).optional()}),Ht={tool_search_tool_regex_20251119:"advanced-tool-use-2025-11-20",tool_search_tool_bm25_20251119:"advanced-tool-use-2025-11-20",memory_20250818:"context-management-2025-06-27",web_fetch_20250910:"web-fetch-2025-09-10",code_execution_20250825:"code-execution-2025-08-25",computer_20251124:"computer-use-2025-11-24",computer_20250124:"computer-use-2025-01-24",mcp_toolset:"mcp-client-2025-11-20"};function $n(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Bn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function Ln(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function jn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=xs({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Wn=t=>t();function Dn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Fn(t){function*e(){for(const s of t)Dn(s)&&(s.source==="char"?yield{type:"char_location",file_id:s.url??"",start_char_index:s.startIndex??0,end_char_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="page"?yield{type:"page_location",file_id:s.url??"",start_page_number:s.startIndex??0,end_page_number:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="block"?yield{type:"content_block_location",file_id:s.url??"",start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="url"?yield{type:"web_search_result_location",url:s.url??"",title:s.title??null,encrypted_index:String(s.startIndex??0),cited_text:s.citedText??""}:s.source==="search"&&(yield{type:"search_result_location",title:s.title??null,start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,search_result_index:0,source:s.source??"",cited_text:s.citedText??""}))}return Array.from(e())}function oe(t){return typeof t=="string"?t:Hn(t)}function Hn(t){const e=[];for(let s=0,{length:n}=t;s<n;s++)e.push(String.fromCharCode(t[s]));return btoa(e.join(""))}function it(t){return(t??"").split(";")[0].toLowerCase()}function Se(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function Z(t,e){const s=Se(e,"cache_control");s!==void 0&&(t.cache_control=s);const n=Se(e,"citations");n!==void 0&&(t.citations=n);const r=Se(e,"context");r!==void 0&&(t.context=r);const a=Se(e,"title");return a!==void 0&&(t.title=a),t}function ot(t,e){const s=Se(e,"cache_control");return s!==void 0&&(t.cache_control=s),t}function Jt(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function Jn(t){const e=[],s=t.response_metadata,n="model_provider"in s&&s?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Fn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const a=Wn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:a})}else if(r.type==="reasoning"&&n)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&n)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&n)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const a=r.output.urls.map(i=>({type:"web_search_result",title:"",encrypted_content:"",url:i}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:a})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const a=r.metadata;if(r.fileId){e.push(Z({type:"document",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){const i=it(r.mimeType);if(i==="application/pdf"||i===""){e.push(Z({type:"document",source:{type:"url",url:r.url}},a));continue}}if(r.data){const i=it(r.mimeType);if(i===""||i==="application/pdf")e.push(Z({type:"document",source:{type:"base64",data:oe(r.data),media_type:"application/pdf"}},a));else if(i==="text/plain")e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},a));else if(Jt(i))e.push(Z({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:oe(r.data),media_type:i}}]}},a));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${i}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const a=r.metadata;if(r.fileId){e.push(ot({type:"image",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){e.push(ot({type:"image",source:{type:"url",url:r.url}},a));continue}if(r.data){const i=it(r.mimeType)||"image/png";Jt(i)&&e.push(ot({type:"image",source:{type:"base64",data:oe(r.data),media_type:i}},a));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&n&&e.push(r.value))}return e}function Kt(t){const e=xs({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let s;try{s=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
|
|
2
2
|
|
|
3
3
|
`))}if(s.protocol==="http:"||s.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(s.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
|
|
4
4
|
|