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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DGitogYY.js","assets/index-Ah_aViv6.js","assets/index-B7oaWPow.js","assets/index-BrUPorMz.css","assets/chunk-VL2OQCWN-DDPfe4wt.js"])))=>i.map(i=>d[i]);
2
- var hy=Object.defineProperty;var py=(e,t,n)=>t in e?hy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var su=(e,t,n)=>py(e,typeof t!="symbol"?t+"":t,n);import{_ as G,b as ji,u as en,a as ht,c as Rc,n as St,s as Oe,d as Pn,o as te,e as fy,Z as R,f as Ht,h as au,l as Io,i as my,j as Yd,p as Xd,k as Fr,m as $c,q as Qd,t as T,w as $a,x as iu,v as gy,y as La,z as yy,A as Po,B as _y,C as wy,H as vy,L as by,D as Sy,M as Ty,W as Ey,E as Cy}from"./index-B7oaWPow.js";import{u as Ay,w as Lc,x as ky,y as Be,z as Oy,A as xy,B as Iy,C as Py,D as Ny,E as My,F as Ry,G as $y,H as Ly,I as jy,d as An,J as Dy,g as Re,K as Uy,L as eh,M as Fy,N as By,O as ja,h as jc,Q as zy,R as Hy,S as Vy,U as Gy,W as Wy,X as Jy,Y as Ky,Z as Zy,a0 as qy,a1 as Yy,a2 as Xy,a3 as ou,a4 as Qy,a5 as e_,a6 as t_,a7 as n_,s as r_,v as Ce,P as tn,p as Da,a as ws,b as th,c as nh,i as Dc,j as s_,f as a_,_ as i_,$ as o_,e as c_,k as l_,t as cu,l as rh,V as Uc,m as u_,n as br,o as d_,T as h_,q as p_,r as f_,a8 as m_}from"./chunk-VL2OQCWN-DDPfe4wt.js";var Di,ra,Ui=0,Fi=0;function g_(e,t,n){var r=0,s=t||new Array(16);e=e||{};var a=e.node,i=e.clockseq;if(e._v6||(a||(a=Di),i==null&&(i=ra)),a==null||i==null){var o=e.random||(e.rng||Ay)();a==null&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],!Di&&!e._v6&&(a[0]|=1,Di=a)),i==null&&(i=(o[6]<<8|o[7])&16383,ra===void 0&&!e._v6&&(ra=i))}var c=e.msecs!==void 0?e.msecs:Date.now(),l=e.nsecs!==void 0?e.nsecs:Fi+1,u=c-Ui+(l-Fi)/1e4;if(u<0&&e.clockseq===void 0&&(i=i+1&16383),(u<0||c>Ui)&&e.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ui=c,Fi=l,ra=i,c+=122192928e5;var d=((c&268435455)*1e4+l)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=d&255;var h=c/4294967296*1e4&268435455;s[r++]=h>>>8&255,s[r++]=h&255,s[r++]=h>>>24&15|16,s[r++]=h>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var p=0;p<6;++p)s[r+p]=a[p];return t||Lc(s)}function y_(e){var t=typeof e=="string"?ky(e):e,n=__(t);return typeof e=="string"?Lc(n):n}function __(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function lu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function uu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?lu(Object(n),!0).forEach(function(r){w_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lu(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function w_(e,t,n){return(t=v_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function v_(e){var t=b_(e,"string");return typeof t=="symbol"?t:t+""}function b_(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function S_(e={},t,n=0){var r=g_(uu(uu({},e),{},{_v6:!0}),new Uint8Array(16));return r=y_(r),Lc(r)}const T_=(e,t)=>{Oy.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Iy(e,n)},flatten:{value:n=>xy(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},li=Be("ZodError",T_,{Parent:Error}),E_=Py(li),C_=My(li),A_=Ny(li),k_=Ry(li),ct=Be("ZodType",(e,t)=>(jy.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>An(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>E_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>A_(e,n,r),e.parseAsync=async(n,r)=>C_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>k_(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(X_(n,r)),e.superRefine=n=>e.check(Q_(n)),e.overwrite=n=>e.check(Dy(n)),e.optional=()=>du(e),e.nullable=()=>hu(e),e.nullish=()=>du(hu(e)),e.nonoptional=n=>V_(e,n),e.array=()=>I_(e),e.or=n=>N_([e,n]),e.and=n=>R_(e,n),e.transform=n=>pu(e,L_(n)),e.default=n=>F_(e,n),e.prefault=n=>z_(e,n),e.catch=n=>W_(e,n),e.pipe=n=>pu(e,n),e.readonly=()=>Z_(e),e.describe=n=>{const r=e.clone();return Re.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return Re.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Re.get(e);const r=e.clone();return Re.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),O_=Be("ZodAny",(e,t)=>{Ly.init(e,t),ct.init(e,t)});function sa(){return $y(O_)}const x_=Be("ZodArray",(e,t)=>{Xy.init(e,t),ct.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(ou(n,r)),e.nonempty=n=>e.check(ou(1,n)),e.max=(n,r)=>e.check(Qy(n,r)),e.length=(n,r)=>e.check(e_(n,r)),e.unwrap=()=>e.element});function I_(e,t){return Fy(x_,e,t)}const P_=Be("ZodUnion",(e,t)=>{Vy.init(e,t),ct.init(e,t),e.options=t.options});function N_(e,t){return new P_({type:"union",options:e,...eh(t)})}const M_=Be("ZodIntersection",(e,t)=>{Gy.init(e,t),ct.init(e,t)});function R_(e,t){return new M_({type:"intersection",left:e,right:t})}const $_=Be("ZodTransform",(e,t)=>{Jy.init(e,t),ct.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(ja(a,n.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),n.issues.push(ja(i))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function L_(e){return new $_({type:"transform",transform:e})}const j_=Be("ZodOptional",(e,t)=>{jc.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function du(e){return new j_({type:"optional",innerType:e})}const D_=Be("ZodNullable",(e,t)=>{zy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function hu(e){return new D_({type:"nullable",innerType:e})}const U_=Be("ZodDefault",(e,t)=>{Ky.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F_(e,t){return new U_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const B_=Be("ZodPrefault",(e,t)=>{Zy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function z_(e,t){return new B_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const H_=Be("ZodNonOptional",(e,t)=>{Hy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function V_(e,t){return new H_({type:"nonoptional",innerType:e,...eh(t)})}const G_=Be("ZodCatch",(e,t)=>{qy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function W_(e,t){return new G_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const J_=Be("ZodPipe",(e,t)=>{Wy.init(e,t),ct.init(e,t),e.in=t.in,e.out=t.out});function pu(e,t){return new J_({type:"pipe",in:e,out:t})}const K_=Be("ZodReadonly",(e,t)=>{Yy.init(e,t),ct.init(e,t)});function Z_(e){return new K_({type:"readonly",innerType:e})}const q_=Be("ZodCustom",(e,t)=>{t_.init(e,t),ct.init(e,t)});function Y_(e){const t=new By({check:"custom"});return t._zod.check=e,t}function X_(e,t={}){return Uy(q_,e,t)}function Q_(e){const t=Y_(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ja(r,n.value,t._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),n.issues.push(ja(s))}},e(n.value,n)));return t}async function*sh(e){for await(const t of e)if(t.event==="on_chat_model_stream"&&t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}G(sh,"streamEventsToAISDK");function ah(e){return new ReadableStream({async start(t){try{for await(const n of e)t.enqueue(n);t.close()}catch(n){t.error(n)}}})}G(ah,"createReadableStreamFromGenerator");async function*ih(e){for await(const t of e)switch(t.event){case"on_chat_model_stream":if(t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CvPVR03j.js","assets/index-x_xzGcAx.js","assets/index-LZZ02vm2.js","assets/index-BrUPorMz.css","assets/chunk-VL2OQCWN-B6188h-8.js","assets/index-DRz5BQNA.js","assets/__vite-browser-external-DFygW7-s.js","assets/path-C9FudP8b.js"])))=>i.map(i=>d[i]);
2
+ var hy=Object.defineProperty;var py=(e,t,n)=>t in e?hy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var su=(e,t,n)=>py(e,typeof t!="symbol"?t+"":t,n);import{_ as G,c as ji,u as en,a as ht,d as Rc,n as St,s as Oe,e as Pn,o as te,f as fy,Z as R,h as Ht,i as au,l as Io,j as my,k as Yd,p as Xd,m as Fr,r as $c,q as Qd,t as T,v as gy,w as $a,B as yy,x as _y,H as wy,L as vy,y as by,M as Sy,W as Ty,z as Ey}from"./index-LZZ02vm2.js";import{u as Cy,w as Lc,x as Ay,y as Be,z as ky,A as Oy,B as xy,C as Iy,D as Py,E as Ny,F as My,G as Ry,H as $y,I as Ly,d as An,J as jy,g as Re,K as Dy,L as eh,M as Uy,N as Fy,O as La,h as jc,Q as By,R as zy,S as Hy,U as Vy,W as Gy,X as Wy,Y as Jy,Z as Ky,a0 as Zy,a1 as qy,a2 as Yy,a3 as iu,a4 as Xy,a5 as Qy,a6 as e_,a7 as t_,s as n_,v as Ce,P as tn,p as ja,a as ws,b as th,c as nh,i as Dc,j as r_,f as s_,_ as a_,$ as i_,e as o_,k as c_,t as ou,l as rh,V as Uc,m as l_,n as br,o as u_,T as d_,q as h_,r as p_,a8 as f_}from"./chunk-VL2OQCWN-B6188h-8.js";import{o as Po}from"./__vite-browser-external-DFygW7-s.js";import{j as Da,d as cu,i as m_}from"./path-C9FudP8b.js";var Di,ra,Ui=0,Fi=0;function g_(e,t,n){var r=0,s=t||new Array(16);e=e||{};var a=e.node,i=e.clockseq;if(e._v6||(a||(a=Di),i==null&&(i=ra)),a==null||i==null){var o=e.random||(e.rng||Cy)();a==null&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],!Di&&!e._v6&&(a[0]|=1,Di=a)),i==null&&(i=(o[6]<<8|o[7])&16383,ra===void 0&&!e._v6&&(ra=i))}var c=e.msecs!==void 0?e.msecs:Date.now(),l=e.nsecs!==void 0?e.nsecs:Fi+1,u=c-Ui+(l-Fi)/1e4;if(u<0&&e.clockseq===void 0&&(i=i+1&16383),(u<0||c>Ui)&&e.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ui=c,Fi=l,ra=i,c+=122192928e5;var d=((c&268435455)*1e4+l)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=d&255;var h=c/4294967296*1e4&268435455;s[r++]=h>>>8&255,s[r++]=h&255,s[r++]=h>>>24&15|16,s[r++]=h>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var p=0;p<6;++p)s[r+p]=a[p];return t||Lc(s)}function y_(e){var t=typeof e=="string"?Ay(e):e,n=__(t);return typeof e=="string"?Lc(n):n}function __(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function lu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function uu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?lu(Object(n),!0).forEach(function(r){w_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lu(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function w_(e,t,n){return(t=v_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function v_(e){var t=b_(e,"string");return typeof t=="symbol"?t:t+""}function b_(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function S_(e={},t,n=0){var r=g_(uu(uu({},e),{},{_v6:!0}),new Uint8Array(16));return r=y_(r),Lc(r)}const T_=(e,t)=>{ky.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>xy(e,n)},flatten:{value:n=>Oy(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},li=Be("ZodError",T_,{Parent:Error}),E_=Iy(li),C_=Ny(li),A_=Py(li),k_=My(li),ct=Be("ZodType",(e,t)=>(Ly.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>An(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>E_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>A_(e,n,r),e.parseAsync=async(n,r)=>C_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>k_(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(X_(n,r)),e.superRefine=n=>e.check(Q_(n)),e.overwrite=n=>e.check(jy(n)),e.optional=()=>du(e),e.nullable=()=>hu(e),e.nullish=()=>du(hu(e)),e.nonoptional=n=>V_(e,n),e.array=()=>I_(e),e.or=n=>N_([e,n]),e.and=n=>R_(e,n),e.transform=n=>pu(e,L_(n)),e.default=n=>F_(e,n),e.prefault=n=>z_(e,n),e.catch=n=>W_(e,n),e.pipe=n=>pu(e,n),e.readonly=()=>Z_(e),e.describe=n=>{const r=e.clone();return Re.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return Re.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Re.get(e);const r=e.clone();return Re.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),O_=Be("ZodAny",(e,t)=>{$y.init(e,t),ct.init(e,t)});function sa(){return Ry(O_)}const x_=Be("ZodArray",(e,t)=>{Yy.init(e,t),ct.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(iu(n,r)),e.nonempty=n=>e.check(iu(1,n)),e.max=(n,r)=>e.check(Xy(n,r)),e.length=(n,r)=>e.check(Qy(n,r)),e.unwrap=()=>e.element});function I_(e,t){return Uy(x_,e,t)}const P_=Be("ZodUnion",(e,t)=>{Hy.init(e,t),ct.init(e,t),e.options=t.options});function N_(e,t){return new P_({type:"union",options:e,...eh(t)})}const M_=Be("ZodIntersection",(e,t)=>{Vy.init(e,t),ct.init(e,t)});function R_(e,t){return new M_({type:"intersection",left:e,right:t})}const $_=Be("ZodTransform",(e,t)=>{Wy.init(e,t),ct.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(La(a,n.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),n.issues.push(La(i))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function L_(e){return new $_({type:"transform",transform:e})}const j_=Be("ZodOptional",(e,t)=>{jc.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function du(e){return new j_({type:"optional",innerType:e})}const D_=Be("ZodNullable",(e,t)=>{By.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function hu(e){return new D_({type:"nullable",innerType:e})}const U_=Be("ZodDefault",(e,t)=>{Jy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F_(e,t){return new U_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const B_=Be("ZodPrefault",(e,t)=>{Ky.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function z_(e,t){return new B_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const H_=Be("ZodNonOptional",(e,t)=>{zy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function V_(e,t){return new H_({type:"nonoptional",innerType:e,...eh(t)})}const G_=Be("ZodCatch",(e,t)=>{Zy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function W_(e,t){return new G_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const J_=Be("ZodPipe",(e,t)=>{Gy.init(e,t),ct.init(e,t),e.in=t.in,e.out=t.out});function pu(e,t){return new J_({type:"pipe",in:e,out:t})}const K_=Be("ZodReadonly",(e,t)=>{qy.init(e,t),ct.init(e,t)});function Z_(e){return new K_({type:"readonly",innerType:e})}const q_=Be("ZodCustom",(e,t)=>{e_.init(e,t),ct.init(e,t)});function Y_(e){const t=new Fy({check:"custom"});return t._zod.check=e,t}function X_(e,t={}){return Dy(q_,e,t)}function Q_(e){const t=Y_(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(La(r,n.value,t._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),n.issues.push(La(s))}},e(n.value,n)));return t}async function*sh(e){for await(const t of e)if(t.event==="on_chat_model_stream"&&t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}G(sh,"streamEventsToAISDK");function ah(e){return new ReadableStream({async start(t){try{for await(const n of e)t.enqueue(n);t.close()}catch(n){t.error(n)}}})}G(ah,"createReadableStreamFromGenerator");async function*ih(e){for await(const t of e)switch(t.event){case"on_chat_model_stream":if(t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
3
3
  🔧 Using tool: ${t.name}
4
4
  `;break;case"on_tool_end":yield`
5
5
  ✅ Tool completed: ${t.name}
6
- `;break}}G(ih,"streamEventsToAISDKWithTools");class ew{static convert(t){return this.parseSchema(t)}static matchesCondition(t,n){if(!n.properties)return!0;if(typeof t!="object"||t===null||Array.isArray(t))return!1;const r=t;for(const[s,a]of Object.entries(n.properties)){if(!(s in r)){if("const"in a)return!1;continue}const i=r[s];if("const"in a&&i!==a.const||"minimum"in a&&typeof i=="number"&&i<a.minimum||"maximum"in a&&typeof i=="number"&&i>a.maximum)return!1}return!0}static validateConditionalSchema(t,n,r){this.validateRequiredProperties(t,n,r),this.validatePropertyPatterns(t,n,r),this.validateNestedConditions(t,n,r)}static validateRequiredProperties(t,n,r){if(n.required){if(typeof t!="object"||t===null){for(const s of n.required)r.addIssue({code:ji.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in t||r.addIssue({code:ji.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(t,n,r){if(!n.properties||typeof t!="object"||t===null||Array.isArray(t))return;const s=t;for(const[a,i]of Object.entries(n.properties)){if(!(a in s))continue;const o=s[a];i.pattern&&typeof o=="string"&&(new RegExp(i.pattern).test(o)||r.addIssue({code:ji.custom,message:`String '${o}' does not match pattern '${i.pattern}'`,path:[a]}))}}static validateNestedConditions(t,n,r){if(!n.if||!n.then)return;this.matchesCondition(t,n.if)?this.validateConditionalSchema(t,n.then,r):n.else&&this.validateConditionalSchema(t,n.else,r)}static parseSchema(t){return Array.isArray(t.type)?this.handleTypeArray(t):t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.if&&t.then?this.parseObject(t):t.properties&&(!t.type||t.type==="object")?this.parseObject(t):this.handleSingleType(t)}static handleTypeArray(t){if(!Array.isArray(t.type))throw new Error("Expected schema.type to be an array");return t.type.includes("null")?this.handleNullableType(t):this.createUnionFromTypes(t.type,t)}static handleNullableType(t){if(!Array.isArray(t.type))throw new Error("Expected schema.type to be an array");const n={...t};return n.type=t.type.filter(s=>s!=="null"),n.type.length===1?this.handleSingleType({...t,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(t,n){const r=t.map(s=>{const a={...n,type:s};return this.parseSchema(a)});return en(r)}static handleSingleType(t){if(t.type===void 0)return t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.properties?this.parseObject(t):ht();switch(t.type){case"string":return this.parseString(t);case"number":case"integer":return this.parseNumberSchema(t);case"boolean":return Rc();case"array":return this.parseArray(t);case"object":return this.parseObject(t);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(t){let n=St(),r=n;return r=this.applyNumberBounds(n,t),r=this.applyNumberMultipleOf(n,t),r=this.applyNumberEnum(n,t),r=this.applyIntegerConstraint(n,t),r}static applyNumberBounds(t,n){let r=t;return n.minimum!==void 0&&(r=n.exclusiveMinimum?r.gt(n.minimum):r.gte(n.minimum)),n.maximum!==void 0&&(r=n.exclusiveMaximum?r.lt(n.maximum):r.lte(n.maximum)),r}static applyNumberMultipleOf(t,n){return n.multipleOf===void 0?t:t.refine(r=>r%n.multipleOf===0,{message:`Number must be a multiple of ${n.multipleOf}`})}static applyNumberEnum(t,n){if(!n.enum)return t;const r=n.enum.filter(s=>typeof s=="number");return r.length===0?t:t.refine(s=>r.includes(s),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(t,n){return n.type!=="integer"?t:t.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(t){let n=Oe(),r=n;return t.format?this.applyStringFormat(n,t):(r=this.applyStringPattern(n,t),r=this.applyStringLength(n,t),r=this.applyStringEnum(n,t),r)}static applyStringFormat(t,n){if(!n.format)return t;switch(n.format){case"email":return t.email();case"date-time":return t.datetime();case"uri":return t.url();case"uuid":return t.uuid();case"date":return t.date();default:return t}}static applyStringPattern(t,n){if(!n.pattern)return t;const r=new RegExp(n.pattern);return t.regex(r,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(t,n){let r=t;return n.minLength!==void 0&&(t=t.min(n.minLength)),n.maxLength!==void 0&&(t=t.max(n.maxLength)),r}static applyStringEnum(t,n){return n.enum?t.refine(r=>n.enum?.includes(r),{message:`Value must be one of: ${n.enum?.join(", ")}`}):t}static parseArray(t){if(Array.isArray(t.items)){const a=t.items.map(i=>this.parseSchema(i));return en(a)}const n=t.items?this.parseSchema(t.items):ht();let r=Pn(n),s=r;return s=this.applyArrayConstraints(r,t),s}static applyArrayConstraints(t,n){return n.minItems!==void 0&&(t=t.min(n.minItems)),n.maxItems!==void 0&&(t=t.max(n.maxItems)),n.uniqueItems?t.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):t}static parseObject(t){if(t.if&&t.then)return this.parseConditional(t);const n={};return this.processObjectProperties(t,n),this.processAdditionalProperties(t,te(n))}static processObjectProperties(t,n){const r=new Set(t.required||[]);if(t.properties)for(const[s,a]of Object.entries(t.properties)){const i=this.parseSchema(a);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(t,n){if(t.additionalProperties===!0)return n.passthrough();if(t.additionalProperties&&typeof t.additionalProperties=="object"){const r=this.parseSchema(t.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(t){const n=this.createBaseObjectSchema(t),r=t.if,s=t.then,a=t.else;return n.superRefine((i,o)=>{const c=this.applyDefaultValues(i,t);this.matchesCondition(c,r)?this.validateConditionalSchema(c,s,o):a&&this.validateConditionalSchema(c,a,o)})}static createBaseObjectSchema(t){const n={},r=new Set(t.required||[]);for(const[a,i]of Object.entries(t.properties||{})){const o=this.parseSchema(i);n[a]=r.has(a)?o:o.optional()}const s=te(n);return this.processAdditionalProperties(t,s)}static applyDefaultValues(t,n){if(typeof t!="object"||t===null||Array.isArray(t))return t;const s={...t};if(!n.properties)return s;for(const[a,i]of Object.entries(n.properties))!(a in s)&&"default"in i&&(s[a]=i.default);return s}static parseCombinator(t){if(t.oneOf)return this.parseOneOf(t.oneOf);if(t.anyOf)return this.parseAnyOf(t.anyOf);if(t.allOf)return this.parseAllOf(t.allOf);throw new Error("Unsupported schema type")}static parseOneOf(t){return this.createUnionFromSchemas(t)}static parseAnyOf(t){return this.createUnionFromSchemas(t)}static createUnionFromSchemas(t){if(t.length===0)return ht();if(t.length===1)return this.parseSchema(t[0]);const n=[];for(const r of t)r.type==="null"?n.push(fy()):n.push(this.parseSchema(r));return n.length>=2?en(n):n.length===1?n[0]:ht()}static parseAllOf(t){if(t.length===0)return ht();if(t.length===1)return this.parseSchema(t[0]);const n=t.reduce((r,s)=>this.mergeSchemas(r,s));return this.parseSchema(n)}static mergeSchemas(t,n){const r={...t,...n};if(t.properties&&n.properties){const s={...t.properties,...n.properties};r.properties=s}if(t.required&&n.required){const s=[...new Set([...t.required,...n.required])];r.required=s}return r}}var tw=Object.defineProperty,F=(e,t)=>{for(var n in t)tw(e,n,{get:t[n],enumerable:!0})};function nw(e,t){return t?.[e]||r_(e)}function rw(e,t){return t?.[e]||n_(e)}function oh(e,t,n){const r={};for(const s in e)Object.hasOwn(e,s)&&(r[t(s,n)]=e[s]);return r}var ch={};F(ch,{Serializable:()=>Tt,get_lc_unique_name:()=>ui});function fu(e){return Array.isArray(e)?[...e]:{...e}}function sw(e,t){const n=fu(e);for(const[r,s]of Object.entries(t)){const[a,...i]=r.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=fu(o[c]),o=o[c]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return n}function ui(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var Tt=class lh{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ui(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([r])=>this.lc_serializable_keys?.includes(r))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof lh||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},r=Object.keys(this.lc_kwargs).reduce((s,a)=>(s[a]=a in this?this[a]:this.lc_kwargs[a],s),{});for(let s=Object.getPrototypeOf(this);s;s=Object.getPrototypeOf(s))Object.assign(t,Reflect.get(s,"lc_aliases",this)),Object.assign(n,Reflect.get(s,"lc_secrets",this)),Object.assign(r,Reflect.get(s,"lc_attributes",this));return Object.keys(n).forEach(s=>{let a=this,i=r;const[o,...c]=s.split(".").reverse();for(const l of c.reverse()){if(!(l in a)||a[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof a[l]=="object"&&a[l]!=null?i[l]={}:Array.isArray(a[l])&&(i[l]=[])),a=a[l],i=i[l]}o in a&&a[o]!==void 0&&(i[o]=i[o]||a[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:oh(Object.keys(n).length?sw(r,n):r,nw,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function kn(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function Fc(e){return kn(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function Bc(e){return kn(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function aw(e){return kn(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function uh(e){return kn(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function dh(e){if(kn(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function iw(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),r=t[1].trim();if(n===""||r==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const s={};for(const a of e.split(";").slice(1)){const i=a.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);s[o]=c}return{type:n,subtype:r,parameters:s}}function No({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(n){r=n[1].toLowerCase();const s=t?Uint8Array.from(atob(n[2]),a=>a.charCodeAt(0)):n[2];return{mime_type:r,data:s}}}function ow(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function U(e,t){return H(e)&&e.type===t}function H(e){return typeof e=="object"&&e!==null}function Vt(e){return Array.isArray(e)}function $(e){return typeof e=="string"}function Pt(e){return typeof e=="number"}function zc(e){return e instanceof Uint8Array}function mu(e){try{return JSON.parse(e)}catch{return}}const vs=e=>e();function cw(e){if(e.type==="char_location"&&$(e.document_title)&&Pt(e.start_char_index)&&Pt(e.end_char_index)&&$(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="page_location"&&$(e.document_title)&&Pt(e.start_page_number)&&Pt(e.end_page_number)&&$(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="content_block_location"&&$(e.document_title)&&Pt(e.start_block_index)&&Pt(e.end_block_index)&&$(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="web_search_result_location"&&$(e.url)&&$(e.title)&&$(e.encrypted_index)&&$(e.cited_text)){const{url:t,title:n,encrypted_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"url",url:t,title:n,startIndex:Number(r),endIndex:Number(r),citedText:s}}if(e.type==="search_result_location"&&$(e.source)&&$(e.title)&&Pt(e.start_block_index)&&Pt(e.end_block_index)&&$(e.cited_text)){const{source:t,title:n,start_block_index:r,end_block_index:s,cited_text:a,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:r,endIndex:s,citedText:a}}}function hh(e){if(U(e,"document")&&H(e.source)&&"type"in e.source){if(e.source.type==="base64"&&$(e.source.media_type)&&$(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&$(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&$(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&$(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(U(e,"image")&&H(e.source)&&"type"in e.source){if(e.source.type==="base64"&&$(e.source.media_type)&&$(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&$(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&$(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function lw(e){function*t(){for(const n of e){const r=hh(n);r?yield r:yield n}}return Array.from(t())}function gu(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n){if(U(r,"text")&&$(r.text)){const{text:s,citations:a,...i}=r;if(Vt(a)&&a.length){const o=a.reduce((c,l)=>{const u=cw(l);return u?[...c,u]:c},[]);yield{...i,type:"text",text:s,annotations:o};continue}else{yield{...i,type:"text",text:s};continue}}else if(U(r,"thinking")&&$(r.thinking)){const{thinking:s,signature:a,...i}=r;yield{...i,type:"reasoning",reasoning:s,signature:a};continue}else if(U(r,"redacted_thinking")){yield{type:"non_standard",value:r};continue}else if(U(r,"tool_use")&&$(r.name)&&$(r.id)){yield{type:"tool_call",id:r.id,name:r.name,args:r.input};continue}else if(U(r,"input_json_delta")){if(dw(e)&&e.tool_call_chunks?.length){const s=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:s.id,name:s.name,args:s.args,index:s.index};continue}}else if(U(r,"server_tool_use")&&$(r.name)&&$(r.id)){const{name:s,id:a}=r;if(s==="web_search"){const i=vs(()=>{if(typeof r.input=="string")return r.input;if(H(r.input)&&$(r.input.query))return r.input.query;if($(r.partial_json)){const o=mu(r.partial_json);if(o?.query)return o.query}return""});yield{id:a,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(r.name==="code_execution"){const i=vs(()=>{if(typeof r.input=="string")return r.input;if(H(r.input)&&$(r.input.code))return r.input.code;if($(r.partial_json)){const o=mu(r.partial_json);if(o?.code)return o.code}return""});yield{id:a,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(U(r,"web_search_tool_result")&&$(r.tool_use_id)&&Vt(r.content)){const{content:s,tool_use_id:a}=r,i=s.reduce((o,c)=>U(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:a,status:"success",output:{urls:i}};continue}else if(U(r,"code_execution_tool_result")&&$(r.tool_use_id)&&H(r.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(U(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}else if(U(r,"mcp_tool_result")&&$(r.tool_use_id)&&H(r.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(U(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}else if(U(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}else if(U(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}else{const s=hh(r);if(s){yield s;continue}}yield{type:"non_standard",value:r}}}return Array.from(t())}const uw={translateContent:gu,translateContentChunk:gu};function dw(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function hw(e){return Fc(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:Bc(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:uh(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function pw(e){return e.map(hw)}function fw(e){return!!(U(e,"image_url")&&H(e.image_url)||U(e,"input_audio")&&H(e.input_audio)||U(e,"file")&&H(e.file))}function mw(e){if(U(e,"image_url")&&H(e.image_url)&&$(e.image_url.url)){const t=No({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(U(e,"input_audio")&&H(e.input_audio)&&$(e.input_audio.data)&&$(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(U(e,"file")&&H(e.file)&&$(e.file.data)){const t=No({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if($(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function gw(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...Hc(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function yw(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...Hc(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function Hc(e){const t=[];for(const n of e)fw(n)?t.push(mw(n)):t.push(n);return t}function _w(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:r,end_index:s}=e;return{type:"citation",url:t,title:n,startIndex:r,endIndex:s}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:r}=e;return{type:"citation",title:n,startIndex:r,endIndex:r,fileId:t}}return e}function ph(e){function*t(){H(e.additional_kwargs?.reasoning)&&Vt(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((s,a)=>H(a)&&$(a.text)?`${s}${a.text}`:s,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n)if(U(r,"text")){const{text:s,annotations:a,...i}=r;Array.isArray(a)?yield{...i,type:"text",text:String(s),annotations:a.map(_w)}:yield{...i,type:"text",text:String(s)}}for(const r of e.tool_calls??[])yield{type:"tool_call",id:r.id,name:r.name,args:r.args};if(H(e.additional_kwargs)&&Vt(e.additional_kwargs.tool_outputs))for(const r of e.additional_kwargs.tool_outputs){if(U(r,"web_search_call")){yield{id:r.id,type:"server_tool_call",name:"web_search",args:{query:r.query}};continue}else if(U(r,"file_search_call")){yield{id:r.id,type:"server_tool_call",name:"file_search",args:{query:r.query}};continue}else if(U(r,"computer_call")){yield{type:"non_standard",value:r};continue}else if(U(r,"code_interpreter_call")){if($(r.code)&&(yield{id:r.id,type:"server_tool_call",name:"code_interpreter",args:{code:r.code}}),Vt(r.outputs)){const s=vs(()=>{if(r.status!=="in_progress"){if(r.status==="completed")return 0;if(r.status==="incomplete")return 127;if(r.status!=="interpreting"&&r.status==="failed")return 1}});for(const a of r.outputs)if(U(a,"logs")){yield{type:"server_tool_call_result",toolCallId:r.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:s??0,stderr:[0,void 0].includes(s)?void 0:String(a.logs),stdout:[0,void 0].includes(s)?String(a.logs):void 0}};continue}}continue}else if(U(r,"mcp_call")){yield{id:r.id,type:"server_tool_call",name:"mcp_call",args:r.input};continue}else if(U(r,"mcp_list_tools")){yield{id:r.id,type:"server_tool_call",name:"mcp_list_tools",args:r.input};continue}else if(U(r,"mcp_approval_request")){yield{type:"non_standard",value:r};continue}else if(U(r,"image_generation_call")){yield{type:"non_standard",value:r};continue}H(r)&&(yield{type:"non_standard",value:r})}}return Array.from(t())}function ww(e){function*t(){yield*ph(e);for(const n of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(t())}const vw={translateContent:e=>typeof e.content=="string"?gw(e):ph(e),translateContentChunk:e=>typeof e.content=="string"?yw(e):ww(e)};function fh(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function bw(e,t="pretty"){return t==="pretty"?Sw(e):JSON.stringify(e)}function Sw(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),s="=".repeat(r),a=n.length%2===0?s:`${s}=`;if(t.push(`${s}${n}${a}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
6
+ `;break}}G(ih,"streamEventsToAISDKWithTools");class ew{static convert(t){return this.parseSchema(t)}static matchesCondition(t,n){if(!n.properties)return!0;if(typeof t!="object"||t===null||Array.isArray(t))return!1;const r=t;for(const[s,a]of Object.entries(n.properties)){if(!(s in r)){if("const"in a)return!1;continue}const i=r[s];if("const"in a&&i!==a.const||"minimum"in a&&typeof i=="number"&&i<a.minimum||"maximum"in a&&typeof i=="number"&&i>a.maximum)return!1}return!0}static validateConditionalSchema(t,n,r){this.validateRequiredProperties(t,n,r),this.validatePropertyPatterns(t,n,r),this.validateNestedConditions(t,n,r)}static validateRequiredProperties(t,n,r){if(n.required){if(typeof t!="object"||t===null){for(const s of n.required)r.addIssue({code:ji.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in t||r.addIssue({code:ji.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(t,n,r){if(!n.properties||typeof t!="object"||t===null||Array.isArray(t))return;const s=t;for(const[a,i]of Object.entries(n.properties)){if(!(a in s))continue;const o=s[a];i.pattern&&typeof o=="string"&&(new RegExp(i.pattern).test(o)||r.addIssue({code:ji.custom,message:`String '${o}' does not match pattern '${i.pattern}'`,path:[a]}))}}static validateNestedConditions(t,n,r){if(!n.if||!n.then)return;this.matchesCondition(t,n.if)?this.validateConditionalSchema(t,n.then,r):n.else&&this.validateConditionalSchema(t,n.else,r)}static parseSchema(t){return Array.isArray(t.type)?this.handleTypeArray(t):t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.if&&t.then?this.parseObject(t):t.properties&&(!t.type||t.type==="object")?this.parseObject(t):this.handleSingleType(t)}static handleTypeArray(t){if(!Array.isArray(t.type))throw new Error("Expected schema.type to be an array");return t.type.includes("null")?this.handleNullableType(t):this.createUnionFromTypes(t.type,t)}static handleNullableType(t){if(!Array.isArray(t.type))throw new Error("Expected schema.type to be an array");const n={...t};return n.type=t.type.filter(s=>s!=="null"),n.type.length===1?this.handleSingleType({...t,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(t,n){const r=t.map(s=>{const a={...n,type:s};return this.parseSchema(a)});return en(r)}static handleSingleType(t){if(t.type===void 0)return t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.properties?this.parseObject(t):ht();switch(t.type){case"string":return this.parseString(t);case"number":case"integer":return this.parseNumberSchema(t);case"boolean":return Rc();case"array":return this.parseArray(t);case"object":return this.parseObject(t);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(t){let n=St(),r=n;return r=this.applyNumberBounds(n,t),r=this.applyNumberMultipleOf(n,t),r=this.applyNumberEnum(n,t),r=this.applyIntegerConstraint(n,t),r}static applyNumberBounds(t,n){let r=t;return n.minimum!==void 0&&(r=n.exclusiveMinimum?r.gt(n.minimum):r.gte(n.minimum)),n.maximum!==void 0&&(r=n.exclusiveMaximum?r.lt(n.maximum):r.lte(n.maximum)),r}static applyNumberMultipleOf(t,n){return n.multipleOf===void 0?t:t.refine(r=>r%n.multipleOf===0,{message:`Number must be a multiple of ${n.multipleOf}`})}static applyNumberEnum(t,n){if(!n.enum)return t;const r=n.enum.filter(s=>typeof s=="number");return r.length===0?t:t.refine(s=>r.includes(s),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(t,n){return n.type!=="integer"?t:t.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(t){let n=Oe(),r=n;return t.format?this.applyStringFormat(n,t):(r=this.applyStringPattern(n,t),r=this.applyStringLength(n,t),r=this.applyStringEnum(n,t),r)}static applyStringFormat(t,n){if(!n.format)return t;switch(n.format){case"email":return t.email();case"date-time":return t.datetime();case"uri":return t.url();case"uuid":return t.uuid();case"date":return t.date();default:return t}}static applyStringPattern(t,n){if(!n.pattern)return t;const r=new RegExp(n.pattern);return t.regex(r,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(t,n){let r=t;return n.minLength!==void 0&&(t=t.min(n.minLength)),n.maxLength!==void 0&&(t=t.max(n.maxLength)),r}static applyStringEnum(t,n){return n.enum?t.refine(r=>n.enum?.includes(r),{message:`Value must be one of: ${n.enum?.join(", ")}`}):t}static parseArray(t){if(Array.isArray(t.items)){const a=t.items.map(i=>this.parseSchema(i));return en(a)}const n=t.items?this.parseSchema(t.items):ht();let r=Pn(n),s=r;return s=this.applyArrayConstraints(r,t),s}static applyArrayConstraints(t,n){return n.minItems!==void 0&&(t=t.min(n.minItems)),n.maxItems!==void 0&&(t=t.max(n.maxItems)),n.uniqueItems?t.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):t}static parseObject(t){if(t.if&&t.then)return this.parseConditional(t);const n={};return this.processObjectProperties(t,n),this.processAdditionalProperties(t,te(n))}static processObjectProperties(t,n){const r=new Set(t.required||[]);if(t.properties)for(const[s,a]of Object.entries(t.properties)){const i=this.parseSchema(a);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(t,n){if(t.additionalProperties===!0)return n.passthrough();if(t.additionalProperties&&typeof t.additionalProperties=="object"){const r=this.parseSchema(t.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(t){const n=this.createBaseObjectSchema(t),r=t.if,s=t.then,a=t.else;return n.superRefine((i,o)=>{const c=this.applyDefaultValues(i,t);this.matchesCondition(c,r)?this.validateConditionalSchema(c,s,o):a&&this.validateConditionalSchema(c,a,o)})}static createBaseObjectSchema(t){const n={},r=new Set(t.required||[]);for(const[a,i]of Object.entries(t.properties||{})){const o=this.parseSchema(i);n[a]=r.has(a)?o:o.optional()}const s=te(n);return this.processAdditionalProperties(t,s)}static applyDefaultValues(t,n){if(typeof t!="object"||t===null||Array.isArray(t))return t;const s={...t};if(!n.properties)return s;for(const[a,i]of Object.entries(n.properties))!(a in s)&&"default"in i&&(s[a]=i.default);return s}static parseCombinator(t){if(t.oneOf)return this.parseOneOf(t.oneOf);if(t.anyOf)return this.parseAnyOf(t.anyOf);if(t.allOf)return this.parseAllOf(t.allOf);throw new Error("Unsupported schema type")}static parseOneOf(t){return this.createUnionFromSchemas(t)}static parseAnyOf(t){return this.createUnionFromSchemas(t)}static createUnionFromSchemas(t){if(t.length===0)return ht();if(t.length===1)return this.parseSchema(t[0]);const n=[];for(const r of t)r.type==="null"?n.push(fy()):n.push(this.parseSchema(r));return n.length>=2?en(n):n.length===1?n[0]:ht()}static parseAllOf(t){if(t.length===0)return ht();if(t.length===1)return this.parseSchema(t[0]);const n=t.reduce((r,s)=>this.mergeSchemas(r,s));return this.parseSchema(n)}static mergeSchemas(t,n){const r={...t,...n};if(t.properties&&n.properties){const s={...t.properties,...n.properties};r.properties=s}if(t.required&&n.required){const s=[...new Set([...t.required,...n.required])];r.required=s}return r}}var tw=Object.defineProperty,F=(e,t)=>{for(var n in t)tw(e,n,{get:t[n],enumerable:!0})};function nw(e,t){return t?.[e]||n_(e)}function rw(e,t){return t?.[e]||t_(e)}function oh(e,t,n){const r={};for(const s in e)Object.hasOwn(e,s)&&(r[t(s,n)]=e[s]);return r}var ch={};F(ch,{Serializable:()=>Tt,get_lc_unique_name:()=>ui});function fu(e){return Array.isArray(e)?[...e]:{...e}}function sw(e,t){const n=fu(e);for(const[r,s]of Object.entries(t)){const[a,...i]=r.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=fu(o[c]),o=o[c]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return n}function ui(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var Tt=class lh{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ui(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([r])=>this.lc_serializable_keys?.includes(r))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof lh||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},r=Object.keys(this.lc_kwargs).reduce((s,a)=>(s[a]=a in this?this[a]:this.lc_kwargs[a],s),{});for(let s=Object.getPrototypeOf(this);s;s=Object.getPrototypeOf(s))Object.assign(t,Reflect.get(s,"lc_aliases",this)),Object.assign(n,Reflect.get(s,"lc_secrets",this)),Object.assign(r,Reflect.get(s,"lc_attributes",this));return Object.keys(n).forEach(s=>{let a=this,i=r;const[o,...c]=s.split(".").reverse();for(const l of c.reverse()){if(!(l in a)||a[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof a[l]=="object"&&a[l]!=null?i[l]={}:Array.isArray(a[l])&&(i[l]=[])),a=a[l],i=i[l]}o in a&&a[o]!==void 0&&(i[o]=i[o]||a[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:oh(Object.keys(n).length?sw(r,n):r,nw,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function kn(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function Fc(e){return kn(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function Bc(e){return kn(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function aw(e){return kn(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function uh(e){return kn(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function dh(e){if(kn(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function iw(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),r=t[1].trim();if(n===""||r==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const s={};for(const a of e.split(";").slice(1)){const i=a.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);s[o]=c}return{type:n,subtype:r,parameters:s}}function No({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(n){r=n[1].toLowerCase();const s=t?Uint8Array.from(atob(n[2]),a=>a.charCodeAt(0)):n[2];return{mime_type:r,data:s}}}function ow(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function U(e,t){return H(e)&&e.type===t}function H(e){return typeof e=="object"&&e!==null}function Vt(e){return Array.isArray(e)}function $(e){return typeof e=="string"}function Pt(e){return typeof e=="number"}function zc(e){return e instanceof Uint8Array}function mu(e){try{return JSON.parse(e)}catch{return}}const vs=e=>e();function cw(e){if(e.type==="char_location"&&$(e.document_title)&&Pt(e.start_char_index)&&Pt(e.end_char_index)&&$(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="page_location"&&$(e.document_title)&&Pt(e.start_page_number)&&Pt(e.end_page_number)&&$(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="content_block_location"&&$(e.document_title)&&Pt(e.start_block_index)&&Pt(e.end_block_index)&&$(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="web_search_result_location"&&$(e.url)&&$(e.title)&&$(e.encrypted_index)&&$(e.cited_text)){const{url:t,title:n,encrypted_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"url",url:t,title:n,startIndex:Number(r),endIndex:Number(r),citedText:s}}if(e.type==="search_result_location"&&$(e.source)&&$(e.title)&&Pt(e.start_block_index)&&Pt(e.end_block_index)&&$(e.cited_text)){const{source:t,title:n,start_block_index:r,end_block_index:s,cited_text:a,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:r,endIndex:s,citedText:a}}}function hh(e){if(U(e,"document")&&H(e.source)&&"type"in e.source){if(e.source.type==="base64"&&$(e.source.media_type)&&$(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&$(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&$(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&$(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(U(e,"image")&&H(e.source)&&"type"in e.source){if(e.source.type==="base64"&&$(e.source.media_type)&&$(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&$(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&$(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function lw(e){function*t(){for(const n of e){const r=hh(n);r?yield r:yield n}}return Array.from(t())}function gu(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n){if(U(r,"text")&&$(r.text)){const{text:s,citations:a,...i}=r;if(Vt(a)&&a.length){const o=a.reduce((c,l)=>{const u=cw(l);return u?[...c,u]:c},[]);yield{...i,type:"text",text:s,annotations:o};continue}else{yield{...i,type:"text",text:s};continue}}else if(U(r,"thinking")&&$(r.thinking)){const{thinking:s,signature:a,...i}=r;yield{...i,type:"reasoning",reasoning:s,signature:a};continue}else if(U(r,"redacted_thinking")){yield{type:"non_standard",value:r};continue}else if(U(r,"tool_use")&&$(r.name)&&$(r.id)){yield{type:"tool_call",id:r.id,name:r.name,args:r.input};continue}else if(U(r,"input_json_delta")){if(dw(e)&&e.tool_call_chunks?.length){const s=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:s.id,name:s.name,args:s.args,index:s.index};continue}}else if(U(r,"server_tool_use")&&$(r.name)&&$(r.id)){const{name:s,id:a}=r;if(s==="web_search"){const i=vs(()=>{if(typeof r.input=="string")return r.input;if(H(r.input)&&$(r.input.query))return r.input.query;if($(r.partial_json)){const o=mu(r.partial_json);if(o?.query)return o.query}return""});yield{id:a,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(r.name==="code_execution"){const i=vs(()=>{if(typeof r.input=="string")return r.input;if(H(r.input)&&$(r.input.code))return r.input.code;if($(r.partial_json)){const o=mu(r.partial_json);if(o?.code)return o.code}return""});yield{id:a,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(U(r,"web_search_tool_result")&&$(r.tool_use_id)&&Vt(r.content)){const{content:s,tool_use_id:a}=r,i=s.reduce((o,c)=>U(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:a,status:"success",output:{urls:i}};continue}else if(U(r,"code_execution_tool_result")&&$(r.tool_use_id)&&H(r.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(U(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}else if(U(r,"mcp_tool_result")&&$(r.tool_use_id)&&H(r.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(U(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}else if(U(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}else if(U(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}else{const s=hh(r);if(s){yield s;continue}}yield{type:"non_standard",value:r}}}return Array.from(t())}const uw={translateContent:gu,translateContentChunk:gu};function dw(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function hw(e){return Fc(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:Bc(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:uh(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function pw(e){return e.map(hw)}function fw(e){return!!(U(e,"image_url")&&H(e.image_url)||U(e,"input_audio")&&H(e.input_audio)||U(e,"file")&&H(e.file))}function mw(e){if(U(e,"image_url")&&H(e.image_url)&&$(e.image_url.url)){const t=No({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(U(e,"input_audio")&&H(e.input_audio)&&$(e.input_audio.data)&&$(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(U(e,"file")&&H(e.file)&&$(e.file.data)){const t=No({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if($(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function gw(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...Hc(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function yw(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...Hc(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function Hc(e){const t=[];for(const n of e)fw(n)?t.push(mw(n)):t.push(n);return t}function _w(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:r,end_index:s}=e;return{type:"citation",url:t,title:n,startIndex:r,endIndex:s}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:r}=e;return{type:"citation",title:n,startIndex:r,endIndex:r,fileId:t}}return e}function ph(e){function*t(){H(e.additional_kwargs?.reasoning)&&Vt(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((s,a)=>H(a)&&$(a.text)?`${s}${a.text}`:s,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n)if(U(r,"text")){const{text:s,annotations:a,...i}=r;Array.isArray(a)?yield{...i,type:"text",text:String(s),annotations:a.map(_w)}:yield{...i,type:"text",text:String(s)}}for(const r of e.tool_calls??[])yield{type:"tool_call",id:r.id,name:r.name,args:r.args};if(H(e.additional_kwargs)&&Vt(e.additional_kwargs.tool_outputs))for(const r of e.additional_kwargs.tool_outputs){if(U(r,"web_search_call")){yield{id:r.id,type:"server_tool_call",name:"web_search",args:{query:r.query}};continue}else if(U(r,"file_search_call")){yield{id:r.id,type:"server_tool_call",name:"file_search",args:{query:r.query}};continue}else if(U(r,"computer_call")){yield{type:"non_standard",value:r};continue}else if(U(r,"code_interpreter_call")){if($(r.code)&&(yield{id:r.id,type:"server_tool_call",name:"code_interpreter",args:{code:r.code}}),Vt(r.outputs)){const s=vs(()=>{if(r.status!=="in_progress"){if(r.status==="completed")return 0;if(r.status==="incomplete")return 127;if(r.status!=="interpreting"&&r.status==="failed")return 1}});for(const a of r.outputs)if(U(a,"logs")){yield{type:"server_tool_call_result",toolCallId:r.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:s??0,stderr:[0,void 0].includes(s)?void 0:String(a.logs),stdout:[0,void 0].includes(s)?String(a.logs):void 0}};continue}}continue}else if(U(r,"mcp_call")){yield{id:r.id,type:"server_tool_call",name:"mcp_call",args:r.input};continue}else if(U(r,"mcp_list_tools")){yield{id:r.id,type:"server_tool_call",name:"mcp_list_tools",args:r.input};continue}else if(U(r,"mcp_approval_request")){yield{type:"non_standard",value:r};continue}else if(U(r,"image_generation_call")){yield{type:"non_standard",value:r};continue}H(r)&&(yield{type:"non_standard",value:r})}}return Array.from(t())}function ww(e){function*t(){yield*ph(e);for(const n of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(t())}const vw={translateContent:e=>typeof e.content=="string"?gw(e):ph(e),translateContentChunk:e=>typeof e.content=="string"?yw(e):ww(e)};function fh(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function bw(e,t="pretty"){return t==="pretty"?Sw(e):JSON.stringify(e)}function Sw(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),s="=".repeat(r),a=n.length%2===0?s:`${s}=`;if(t.push(`${s}${n}${a}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
7
7
  `)}const Bi=Symbol.for("langchain.message");function Xn(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.some(n=>kn(n))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?zs(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(n=>kn(n))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function mh(e,t){return e==="error"||t==="error"?"error":"success"}function Tw(e,t){function n(r,s){if(typeof r!="object"||r===null||r===void 0)return r;if(s>=t)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(i=>n(i,s+1));const a={};for(const i of Object.keys(r))a[i]=n(r[i],s+1);return a}return JSON.stringify(n(e,0),null,2)}var Ke=class extends Tt{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Bi]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){const t=typeof e=="string"||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):t.content!==void 0?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){const e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[pw,Hc,lw].reduce((r,s)=>s(r),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&Bi in e&&e[Bi]===!0&&fh(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=Tw(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return bw(this,e)}};function Ew(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}function Ue(e={},t={}){const n={...e};for(const[r,s]of Object.entries(t))if(n[r]==null)n[r]=s;else{if(s==null)continue;if(typeof n[r]!=typeof s||Array.isArray(n[r])!==Array.isArray(s))throw new Error(`field[${r}] already exists in the message chunk, but with a different type.`);if(typeof n[r]=="string"){if(r==="type")continue;["id","name","output_version","model_provider"].includes(r)?n[r]=s:n[r]+=s}else if(typeof n[r]=="object"&&!Array.isArray(n[r]))n[r]=Ue(n[r],s);else if(Array.isArray(n[r]))n[r]=zs(n[r],s);else{if(n[r]===s)continue;console.warn(`field[${r}] already exists in this message chunk and value has unsupported type.`)}}return n}function zs(e,t){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)return e||t;{const n=[...e];for(const r of t)if(typeof r=="object"&&r!==null&&"index"in r&&typeof r.index=="number"){const s=n.findIndex(a=>{const i=typeof a=="object",o="index"in a&&a.index===r.index,c="id"in a&&"id"in r&&a?.id===r?.id,l=!("id"in a)||!a?.id||!("id"in r)||!r?.id;return i&&o&&(c||l)});s!==-1&&typeof n[s]=="object"&&n[s]!==null?n[s]=Ue(n[s],r):n.push(r)}else{if(typeof r=="object"&&r!==null&&"text"in r&&r.text==="")continue;n.push(r)}return n}}}function gh(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(!e||!t)return e||t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.
8
8
  Left ${typeof e}
9
9
  Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return zs(e,t);if(typeof e=="object"&&typeof t=="object")return Ue(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.
@@ -19,7 +19,7 @@ Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/
19
19
  `,e}var vn=class extends Ke{type="remove";id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}};const zw=e=>e();function Hw(e){return ps(e)?e:typeof e.id=="string"&&e.type==="function"&&typeof e.function=="object"&&e.function!==null&&"arguments"in e.function&&typeof e.function.arguments=="string"&&"name"in e.function&&typeof e.function.name=="string"?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function Vw(e){return typeof e=="object"&&e!=null&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs=="object"}function zi(e){let t,n;if(Vw(e)){const r=e.id.at(-1);r==="HumanMessage"||r==="HumanMessageChunk"?t="user":r==="AIMessage"||r==="AIMessageChunk"?t="assistant":r==="SystemMessage"||r==="SystemMessageChunk"?t="system":r==="FunctionMessage"||r==="FunctionMessageChunk"?t="function":r==="ToolMessage"||r==="ToolMessageChunk"?t="tool":t="unknown",n=e.kwargs}else{const{type:r,...s}=e;t=r,n=s}if(t==="human"||t==="user")return new ue(n);if(t==="ai"||t==="assistant"){const{tool_calls:r,...s}=n;if(!Array.isArray(r))return new j(n);const a=r.map(Hw);return new j({...s,tool_calls:a})}else{if(t==="system")return new fe(n);if(t==="developer")return new fe({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if(t==="tool"&&"tool_call_id"in n)return new X({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});if(t==="remove"&&"id"in n&&typeof n.id=="string")return new vn({...n,id:n.id});throw fi(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
20
20
 
21
21
  Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Gt(e){if(typeof e=="string")return new ue(e);if(Ie(e))return e;if(Array.isArray(e)){const[t,n]=e;return zi({type:t,content:n})}else if(yh(e)){const{role:t,...n}=e;return zi({...n,type:t})}else return zi(e)}function Zc(e,t="Human",n="AI"){const r=[];for(const s of e){let a;if(s._getType()==="human")a=t;else if(s._getType()==="ai")a=n;else if(s._getType()==="system")a="System";else if(s._getType()==="tool")a="Tool";else if(s._getType()==="generic")a=s.role;else throw new Error(`Got unsupported message type: ${s._getType()}`);const i=s.name?`${s.name}, `:"",o=typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2);r.push(`${a}: ${i}${o}`)}return r.join(`
22
- `)}function Gw(e){if(e.data!==void 0)return e;{const t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function qc(e){const t=Gw(e);switch(t.type){case"human":return new ue(t.data);case"ai":return new j(t.data);case"system":return new fe(t.data);case"function":if(t.data.name===void 0)throw new Error("Name must be defined for function messages");return new hi(t.data);case"tool":if(t.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new X(t.data);case"generic":if(t.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Qn(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function Ww(e){return e.map(qc)}function Jw(e){return e.map(t=>t.toDict())}function Ua(e){const t=e._getType();if(t==="human")return new Vs({...e});if(t==="ai"){let n={...e};return"tool_calls"in n&&(n={...n,tool_call_chunks:n.tool_calls?.map(r=>({...r,type:"tool_call_chunk",index:void 0,args:JSON.stringify(r.args)}))}),new mt({...n})}else{if(t==="system")return new Kn({...e});if(t==="function")return new pi({...e});if(Qn.isInstance(e))return new di({...e});throw new Error("Unknown message type.")}}var Kw={},Ch={};F(Ch,{getEnv:()=>Ih,getEnvironmentVariable:()=>nn,getRuntimeEnvironment:()=>Ph,isBrowser:()=>Ah,isDeno:()=>mi,isJsDom:()=>Oh,isNode:()=>xh,isWebWorker:()=>kh});const Ah=()=>typeof window<"u"&&typeof window.document<"u",kh=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Oh=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),mi=()=>typeof Deno<"u",xh=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!mi(),Ih=()=>{let e;return Ah()?e="browser":xh()?e="node":kh()?e="webworker":Oh()?e="jsdom":mi()?e="deno":e="other",e};let Hi;function Ph(){return Hi===void 0&&(Hi={library:"langchain-js",runtime:Ih()}),Hi}function nn(e){try{return typeof process<"u"?Kw?.[e]:mi()?Deno?.env.get(e):void 0}catch{return}}var Nh={};F(Nh,{BaseCallbackHandler:()=>es,callbackHandlerPrefersStreaming:()=>Yc,isBaseCallbackHandler:()=>Mh});var Zw=class{};function Yc(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var es=class extends Zw{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ui(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=nn("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Tt.prototype.toJSON.call(this)}toJSONNotImplemented(){return Tt.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends es{name=Ce();constructor(){super(),Object.assign(this,e)}}return new t}};const Mh=e=>{const t=e;return t!==void 0&&typeof t.copy=="function"&&typeof t.name=="string"&&typeof t.awaitHandlers=="boolean"},qw="gen_ai.operation.name",Yw="gen_ai.system",vu="gen_ai.request.model",Xw="gen_ai.response.model",bu="gen_ai.usage.input_tokens",Su="gen_ai.usage.output_tokens",Tu="gen_ai.usage.total_tokens",Qw="gen_ai.request.max_tokens",ev="gen_ai.request.temperature",tv="gen_ai.request.top_p",nv="gen_ai.request.frequency_penalty",rv="gen_ai.request.presence_penalty",sv="gen_ai.response.finish_reasons",av="gen_ai.prompt",iv="gen_ai.completion",ov="gen_ai.request.extra_query",cv="gen_ai.request.extra_body",lv="gen_ai.serialized.name",uv="gen_ai.serialized.signature",dv="gen_ai.serialized.doc",hv="gen_ai.response.id",pv="gen_ai.response.service_tier",fv="gen_ai.response.system_fingerprint",mv="gen_ai.usage.input_token_details",gv="gen_ai.usage.output_token_details",yv="langsmith.trace.session_id",_v="langsmith.trace.session_name",wv="langsmith.span.kind",vv="langsmith.trace.name",bv="langsmith.metadata",Eu="langsmith.span.tags",Sv="langsmith.request.streaming",Tv="langsmith.request.headers",Ev=(...e)=>fetch(...e),Rh=Symbol.for("ls:fetch_implementation"),Cv=()=>{const e=globalThis[Rh];return e?typeof e=="function"&&"Headers"in e&&"Request"in e&&"Response"in e:!1},Av=e=>async(...t)=>{if(e||Qe("DEBUG")==="true"){const[r,s]=t;console.log(`→ ${s?.method||"GET"} ${r}`)}const n=await(globalThis[Rh]??Ev)(...t);return(e||Qe("DEBUG")==="true")&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},$h=()=>Qe("PROJECT")??Jt("LANGCHAIN_SESSION")??"default",Lh="0.3.75";var $o={};let Dt;const kv=()=>typeof window<"u"&&typeof window.document<"u",Ov=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",xv=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),jh=()=>typeof Deno<"u",Iv=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!jh(),Dh=()=>Dt||(typeof Bun<"u"?Dt="bun":kv()?Dt="browser":Iv()?Dt="node":Ov()?Dt="webworker":xv()?Dt="jsdom":jh()?Dt="deno":Dt="other",Dt);let Vi;function Uh(){if(Vi===void 0){const e=Dh(),t=Nv();Vi={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:Lh,...t}}return Vi}function Fh(){const e=Pv(),t={},n=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[r,s]of Object.entries(e))typeof s=="string"&&!n.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?t.revision_id=s:t[r]=s);return t}function Pv(){const e={};try{if(typeof process<"u"&&$o)for(const[t,n]of Object.entries($o))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&n!=null&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&typeof n=="string"?e[t]=n.slice(0,2)+"*".repeat(n.length-4)+n.slice(-2):e[t]=n)}catch{}return e}function Jt(e){try{return typeof process<"u"?$o?.[e]:void 0}catch{return}}function Qe(e){return Jt(`LANGSMITH_${e}`)||Jt(`LANGCHAIN_${e}`)}let Gi;function Nv(){if(Gi!==void 0)return Gi;const e=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],t={};for(const n of e){const r=Jt(n);r!==void 0&&(t[n]=r)}return Gi=t,t}function Bh(){return Jt("OTEL_ENABLED")==="true"||Qe("OTEL_ENABLED")==="true"}class Mv{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(t,...n){!this.hasWarned&&Bh()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let r;if(n.length===1&&typeof n[0]=="function"?r=n[0]:n.length===2&&typeof n[1]=="function"?r=n[1]:n.length===3&&typeof n[2]=="function"&&(r=n[2]),typeof r=="function")return r()}}class Rv{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Mv})}getTracer(t,n){return this.mockTracer}getActiveSpan(){}setSpan(t,n){return t}getSpan(t){}setSpanContext(t,n){return t}getTracerProvider(){}setGlobalTracerProvider(t){return!1}}class $v{active(){return{}}with(t,n){return n()}}const Wi=Symbol.for("ls:otel_trace"),Ji=Symbol.for("ls:otel_context"),Cu=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Lv=new Rv,jv=new $v;class Dv{getTraceInstance(){return globalThis[Wi]??Lv}getContextInstance(){return globalThis[Ji]??jv}initializeGlobalInstances(t){globalThis[Wi]===void 0&&(globalThis[Wi]=t.trace),globalThis[Ji]===void 0&&(globalThis[Ji]=t.context)}setDefaultOTLPTracerComponents(t){globalThis[Cu]=t}getDefaultOTLPTracerComponents(){return globalThis[Cu]??void 0}}const Xc=new Dv;function zh(){return Xc.getTraceInstance()}function Uv(){return Xc.getContextInstance()}function Fv(){return Xc.getDefaultOTLPTracerComponents()}const Bv={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function zv(e){return Bv[e]||e}class Hv{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(t,n){for(const r of t)try{if(!r.run)continue;if(r.operation==="post"){const s=this.createSpanForRun(r,r.run,n.get(r.id));s&&!r.run.end_time&&this.spans.set(r.id,s)}else this.updateSpanForRun(r,r.run)}catch(s){console.error(`Error processing operation ${r.id}:`,s)}}createSpanForRun(t,n,r){const s=r&&zh().getSpan(r);if(s)try{return this.finishSpanSetup(s,n,t)}catch(a){console.error(`Failed to create span for run ${t.id}:`,a);return}}finishSpanSetup(t,n,r){return this.setSpanAttributes(t,n,r),n.error?(t.setStatus({code:2}),t.recordException(new Error(n.error))):t.setStatus({code:1}),n.end_time&&t.end(new Date(n.end_time)),t}updateSpanForRun(t,n){try{const r=this.spans.get(t.id);if(!r){console.debug(`No span found for run ${t.id} during update`);return}this.setSpanAttributes(r,n,t),n.error?(r.setStatus({code:2}),r.recordException(new Error(n.error))):r.setStatus({code:1});const s=n.end_time;s&&(r.end(new Date(s)),this.spans.delete(t.id))}catch(r){console.error(`Failed to update span for run ${t.id}:`,r)}}extractModelName(t){if(t.extra?.metadata){const n=t.extra.metadata;if(n.ls_model_name)return n.ls_model_name;if(n.invocation_params){const r=n.invocation_params;if(r.model)return r.model;if(r.model_name)return r.model_name}}}setSpanAttributes(t,n,r){if("run_type"in n&&n.run_type){t.setAttribute(wv,n.run_type);const o=zv(n.run_type||"chain");t.setAttribute(qw,o)}"name"in n&&n.name&&t.setAttribute(vv,n.name),"session_id"in n&&n.session_id&&t.setAttribute(yv,n.session_id),"session_name"in n&&n.session_name&&t.setAttribute(_v,n.session_name),this.setGenAiSystem(t,n);const s=this.extractModelName(n);s&&t.setAttribute(vu,s),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&t.setAttribute(bu,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&t.setAttribute(Su,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&t.setAttribute(Tu,n.total_tokens),this.setInvocationParameters(t,n);const a=n.extra?.metadata||{};for(const[o,c]of Object.entries(a))c!=null&&t.setAttribute(`${bv}.${o}`,String(c));const i=n.tags;if(i&&Array.isArray(i)?t.setAttribute(Eu,i.join(", ")):i&&t.setAttribute(Eu,String(i)),"serialized"in n&&typeof n.serialized=="object"){const o=n.serialized;o.name&&t.setAttribute(lv,String(o.name)),o.signature&&t.setAttribute(uv,String(o.signature)),o.doc&&t.setAttribute(dv,String(o.doc))}this.setIOAttributes(t,r)}setGenAiSystem(t,n){let r="langchain";const s=this.extractModelName(n);if(s){const a=s.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?r="anthropic":a.includes("bedrock")?r="aws.bedrock":a.includes("azure")&&a.includes("openai")?r="az.ai.openai":a.includes("azure")&&a.includes("inference")?r="az.ai.inference":a.includes("cohere")?r="cohere":a.includes("deepseek")?r="deepseek":a.includes("gemini")?r="gemini":a.includes("groq")?r="groq":a.includes("watson")||a.includes("ibm")?r="ibm.watsonx.ai":a.includes("mistral")?r="mistral_ai":a.includes("gpt")||a.includes("openai")?r="openai":a.includes("perplexity")||a.includes("sonar")?r="perplexity":a.includes("vertex")?r="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(r="xai")}t.setAttribute(Yw,r)}setInvocationParameters(t,n){if(!n.extra?.metadata?.invocation_params)return;const r=n.extra.metadata.invocation_params;r.max_tokens!==void 0&&t.setAttribute(Qw,r.max_tokens),r.temperature!==void 0&&t.setAttribute(ev,r.temperature),r.top_p!==void 0&&t.setAttribute(tv,r.top_p),r.frequency_penalty!==void 0&&t.setAttribute(nv,r.frequency_penalty),r.presence_penalty!==void 0&&t.setAttribute(rv,r.presence_penalty)}setIOAttributes(t,n){if(n.run.inputs)try{const r=n.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&t.setAttribute(vu,r.model),r.stream!==void 0&&t.setAttribute(Sv,r.stream),r.extra_headers&&t.setAttribute(Tv,JSON.stringify(r.extra_headers)),r.extra_query&&t.setAttribute(ov,JSON.stringify(r.extra_query)),r.extra_body&&t.setAttribute(cv,JSON.stringify(r.extra_body))),t.setAttribute(av,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${n.id}`,r)}if(n.run.outputs)try{const r=n.run.outputs,s=this.getUnifiedRunTokens(r);if(s&&(t.setAttribute(bu,s[0]),t.setAttribute(Su,s[1]),t.setAttribute(Tu,s[0]+s[1])),r&&typeof r=="object"){if(r.model&&t.setAttribute(Xw,String(r.model)),r.id&&t.setAttribute(hv,r.id),r.choices&&Array.isArray(r.choices)){const a=r.choices.map(i=>i.finish_reason).filter(i=>i).map(String);a.length>0&&t.setAttribute(sv,a.join(", "))}if(r.service_tier&&t.setAttribute(pv,r.service_tier),r.system_fingerprint&&t.setAttribute(fv,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const a=r.usage_metadata;a.input_token_details&&t.setAttribute(mv,JSON.stringify(a.input_token_details)),a.output_token_details&&t.setAttribute(gv,JSON.stringify(a.output_token_details))}}t.setAttribute(iv,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${n.id}`,r)}}getUnifiedRunTokens(t){if(!t)return null;let n=this.extractUnifiedRunTokens(t.usage_metadata);if(n)return n;const r=Object.keys(t);for(const i of r){const o=t[i];if(!(!o||typeof o!="object")&&(n=this.extractUnifiedRunTokens(o.usage_metadata),n||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(n=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),n)))return n}const s=t.generations||[];if(!Array.isArray(s))return null;const a=Array.isArray(s[0])?s.flat():s;for(const i of a)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(n=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),n))return n;return null}extractUnifiedRunTokens(t){return!t||typeof t!="object"||typeof t.input_tokens!="number"||typeof t.output_tokens!="number"?null:[t.input_tokens,t.output_tokens]}}const Vv=[429,500,502,503,504];let Au=class{constructor(t){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,"default"in tn?this.queue=new tn.default({concurrency:this.maxConcurrency}):this.queue=new tn({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...n){const r=this.onFailedResponseHook;return this.queue.add(()=>Da(()=>t(...n).catch(s=>{throw s instanceof Error?s:new Error(s)}),{async onFailedAttempt(s){if(s.message.startsWith("Cancel")||s.message.startsWith("TimeoutError")||s.name==="TimeoutError"||s.message.startsWith("AbortError")||s?.code==="ECONNABORTED")throw s;const a=s?.response;if(r&&await r(a))return;const i=a?.status??s?.status;if(i&&!Vv.includes(+i))throw s},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,n,...r){return t.signal?Promise.race([this.call(n,...r),new Promise((s,a)=>{t.signal?.addEventListener("abort",()=>{a(new Error("AbortError"))})})]):this.call(n,...r)}};function ku(e){return typeof e?._getType=="function"}function Ou(e){const t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}const Gv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function V(e,t){if(!Gv.test(e)){const n=t!==void 0?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`;throw new Error(n)}return e}const xu={};function Lo(e){xu[e]||(console.warn(e),xu[e]=!0)}function dn(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);const[t,n]=e.split(":"),r=n||"latest";if(t.includes("/")){const[s,a]=t.split("/",2);if(!s||!a)throw new Error(`Invalid identifier format: ${e}`);return[s,a,r]}else{if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,r]}}class Wv extends Error{constructor(t){super(t),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function D(e,t,n){let r;if(e.ok){n&&(r=await e.text());return}if(e.status===403)try{(await e.json())?.error==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${e.status} ${e.statusText}`);throw o.status=e?.status,o}if(r===void 0)try{r=await e.text()}catch{r=""}const s=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${r}`;if(e.status===409)throw new Wv(s);const a=new Error(s);throw a.status=e.status,a}const Hh="ERR_CONFLICTING_ENDPOINTS";class Jv extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:Hh}),this.name="ConflictingEndpointsError"}}function Kv(e){return typeof e=="object"&&e!==null&&e.code===Hh}var Iu="[...]",Zv={result:"[Circular]"},Fa=[],fr=[];const qv=new TextEncoder;function Yv(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function aa(e){return qv.encode(e)}function Vh(e){if(e&&typeof e=="object"&&e!==null){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if(typeof e=="bigint")return e.toString();return e}function Xv(e){return function(t,n){return Vh(n)}}function lt(e,t,n,r,s){try{const a=JSON.stringify(e,Xv(n),r);return aa(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`
22
+ `)}function Gw(e){if(e.data!==void 0)return e;{const t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function qc(e){const t=Gw(e);switch(t.type){case"human":return new ue(t.data);case"ai":return new j(t.data);case"system":return new fe(t.data);case"function":if(t.data.name===void 0)throw new Error("Name must be defined for function messages");return new hi(t.data);case"tool":if(t.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new X(t.data);case"generic":if(t.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Qn(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function Ww(e){return e.map(qc)}function Jw(e){return e.map(t=>t.toDict())}function Ua(e){const t=e._getType();if(t==="human")return new Vs({...e});if(t==="ai"){let n={...e};return"tool_calls"in n&&(n={...n,tool_call_chunks:n.tool_calls?.map(r=>({...r,type:"tool_call_chunk",index:void 0,args:JSON.stringify(r.args)}))}),new mt({...n})}else{if(t==="system")return new Kn({...e});if(t==="function")return new pi({...e});if(Qn.isInstance(e))return new di({...e});throw new Error("Unknown message type.")}}var Kw={},Ch={};F(Ch,{getEnv:()=>Ih,getEnvironmentVariable:()=>nn,getRuntimeEnvironment:()=>Ph,isBrowser:()=>Ah,isDeno:()=>mi,isJsDom:()=>Oh,isNode:()=>xh,isWebWorker:()=>kh});const Ah=()=>typeof window<"u"&&typeof window.document<"u",kh=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Oh=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),mi=()=>typeof Deno<"u",xh=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!mi(),Ih=()=>{let e;return Ah()?e="browser":xh()?e="node":kh()?e="webworker":Oh()?e="jsdom":mi()?e="deno":e="other",e};let Hi;function Ph(){return Hi===void 0&&(Hi={library:"langchain-js",runtime:Ih()}),Hi}function nn(e){try{return typeof process<"u"?Kw?.[e]:mi()?Deno?.env.get(e):void 0}catch{return}}var Nh={};F(Nh,{BaseCallbackHandler:()=>es,callbackHandlerPrefersStreaming:()=>Yc,isBaseCallbackHandler:()=>Mh});var Zw=class{};function Yc(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var es=class extends Zw{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ui(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=nn("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Tt.prototype.toJSON.call(this)}toJSONNotImplemented(){return Tt.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends es{name=Ce();constructor(){super(),Object.assign(this,e)}}return new t}};const Mh=e=>{const t=e;return t!==void 0&&typeof t.copy=="function"&&typeof t.name=="string"&&typeof t.awaitHandlers=="boolean"},qw="gen_ai.operation.name",Yw="gen_ai.system",vu="gen_ai.request.model",Xw="gen_ai.response.model",bu="gen_ai.usage.input_tokens",Su="gen_ai.usage.output_tokens",Tu="gen_ai.usage.total_tokens",Qw="gen_ai.request.max_tokens",ev="gen_ai.request.temperature",tv="gen_ai.request.top_p",nv="gen_ai.request.frequency_penalty",rv="gen_ai.request.presence_penalty",sv="gen_ai.response.finish_reasons",av="gen_ai.prompt",iv="gen_ai.completion",ov="gen_ai.request.extra_query",cv="gen_ai.request.extra_body",lv="gen_ai.serialized.name",uv="gen_ai.serialized.signature",dv="gen_ai.serialized.doc",hv="gen_ai.response.id",pv="gen_ai.response.service_tier",fv="gen_ai.response.system_fingerprint",mv="gen_ai.usage.input_token_details",gv="gen_ai.usage.output_token_details",yv="langsmith.trace.session_id",_v="langsmith.trace.session_name",wv="langsmith.span.kind",vv="langsmith.trace.name",bv="langsmith.metadata",Eu="langsmith.span.tags",Sv="langsmith.request.streaming",Tv="langsmith.request.headers",Ev=(...e)=>fetch(...e),Rh=Symbol.for("ls:fetch_implementation"),Cv=()=>{const e=globalThis[Rh];return e?typeof e=="function"&&"Headers"in e&&"Request"in e&&"Response"in e:!1},Av=e=>async(...t)=>{if(e||Qe("DEBUG")==="true"){const[r,s]=t;console.log(`→ ${s?.method||"GET"} ${r}`)}const n=await(globalThis[Rh]??Ev)(...t);return(e||Qe("DEBUG")==="true")&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},$h=()=>Qe("PROJECT")??Jt("LANGCHAIN_SESSION")??"default",Lh="0.3.75";var $o={};let Dt;const kv=()=>typeof window<"u"&&typeof window.document<"u",Ov=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",xv=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),jh=()=>typeof Deno<"u",Iv=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!jh(),Dh=()=>Dt||(typeof Bun<"u"?Dt="bun":kv()?Dt="browser":Iv()?Dt="node":Ov()?Dt="webworker":xv()?Dt="jsdom":jh()?Dt="deno":Dt="other",Dt);let Vi;function Uh(){if(Vi===void 0){const e=Dh(),t=Nv();Vi={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:Lh,...t}}return Vi}function Fh(){const e=Pv(),t={},n=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[r,s]of Object.entries(e))typeof s=="string"&&!n.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?t.revision_id=s:t[r]=s);return t}function Pv(){const e={};try{if(typeof process<"u"&&$o)for(const[t,n]of Object.entries($o))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&n!=null&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&typeof n=="string"?e[t]=n.slice(0,2)+"*".repeat(n.length-4)+n.slice(-2):e[t]=n)}catch{}return e}function Jt(e){try{return typeof process<"u"?$o?.[e]:void 0}catch{return}}function Qe(e){return Jt(`LANGSMITH_${e}`)||Jt(`LANGCHAIN_${e}`)}let Gi;function Nv(){if(Gi!==void 0)return Gi;const e=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],t={};for(const n of e){const r=Jt(n);r!==void 0&&(t[n]=r)}return Gi=t,t}function Bh(){return Jt("OTEL_ENABLED")==="true"||Qe("OTEL_ENABLED")==="true"}class Mv{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(t,...n){!this.hasWarned&&Bh()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let r;if(n.length===1&&typeof n[0]=="function"?r=n[0]:n.length===2&&typeof n[1]=="function"?r=n[1]:n.length===3&&typeof n[2]=="function"&&(r=n[2]),typeof r=="function")return r()}}class Rv{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Mv})}getTracer(t,n){return this.mockTracer}getActiveSpan(){}setSpan(t,n){return t}getSpan(t){}setSpanContext(t,n){return t}getTracerProvider(){}setGlobalTracerProvider(t){return!1}}class $v{active(){return{}}with(t,n){return n()}}const Wi=Symbol.for("ls:otel_trace"),Ji=Symbol.for("ls:otel_context"),Cu=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Lv=new Rv,jv=new $v;class Dv{getTraceInstance(){return globalThis[Wi]??Lv}getContextInstance(){return globalThis[Ji]??jv}initializeGlobalInstances(t){globalThis[Wi]===void 0&&(globalThis[Wi]=t.trace),globalThis[Ji]===void 0&&(globalThis[Ji]=t.context)}setDefaultOTLPTracerComponents(t){globalThis[Cu]=t}getDefaultOTLPTracerComponents(){return globalThis[Cu]??void 0}}const Xc=new Dv;function zh(){return Xc.getTraceInstance()}function Uv(){return Xc.getContextInstance()}function Fv(){return Xc.getDefaultOTLPTracerComponents()}const Bv={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function zv(e){return Bv[e]||e}class Hv{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(t,n){for(const r of t)try{if(!r.run)continue;if(r.operation==="post"){const s=this.createSpanForRun(r,r.run,n.get(r.id));s&&!r.run.end_time&&this.spans.set(r.id,s)}else this.updateSpanForRun(r,r.run)}catch(s){console.error(`Error processing operation ${r.id}:`,s)}}createSpanForRun(t,n,r){const s=r&&zh().getSpan(r);if(s)try{return this.finishSpanSetup(s,n,t)}catch(a){console.error(`Failed to create span for run ${t.id}:`,a);return}}finishSpanSetup(t,n,r){return this.setSpanAttributes(t,n,r),n.error?(t.setStatus({code:2}),t.recordException(new Error(n.error))):t.setStatus({code:1}),n.end_time&&t.end(new Date(n.end_time)),t}updateSpanForRun(t,n){try{const r=this.spans.get(t.id);if(!r){console.debug(`No span found for run ${t.id} during update`);return}this.setSpanAttributes(r,n,t),n.error?(r.setStatus({code:2}),r.recordException(new Error(n.error))):r.setStatus({code:1});const s=n.end_time;s&&(r.end(new Date(s)),this.spans.delete(t.id))}catch(r){console.error(`Failed to update span for run ${t.id}:`,r)}}extractModelName(t){if(t.extra?.metadata){const n=t.extra.metadata;if(n.ls_model_name)return n.ls_model_name;if(n.invocation_params){const r=n.invocation_params;if(r.model)return r.model;if(r.model_name)return r.model_name}}}setSpanAttributes(t,n,r){if("run_type"in n&&n.run_type){t.setAttribute(wv,n.run_type);const o=zv(n.run_type||"chain");t.setAttribute(qw,o)}"name"in n&&n.name&&t.setAttribute(vv,n.name),"session_id"in n&&n.session_id&&t.setAttribute(yv,n.session_id),"session_name"in n&&n.session_name&&t.setAttribute(_v,n.session_name),this.setGenAiSystem(t,n);const s=this.extractModelName(n);s&&t.setAttribute(vu,s),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&t.setAttribute(bu,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&t.setAttribute(Su,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&t.setAttribute(Tu,n.total_tokens),this.setInvocationParameters(t,n);const a=n.extra?.metadata||{};for(const[o,c]of Object.entries(a))c!=null&&t.setAttribute(`${bv}.${o}`,String(c));const i=n.tags;if(i&&Array.isArray(i)?t.setAttribute(Eu,i.join(", ")):i&&t.setAttribute(Eu,String(i)),"serialized"in n&&typeof n.serialized=="object"){const o=n.serialized;o.name&&t.setAttribute(lv,String(o.name)),o.signature&&t.setAttribute(uv,String(o.signature)),o.doc&&t.setAttribute(dv,String(o.doc))}this.setIOAttributes(t,r)}setGenAiSystem(t,n){let r="langchain";const s=this.extractModelName(n);if(s){const a=s.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?r="anthropic":a.includes("bedrock")?r="aws.bedrock":a.includes("azure")&&a.includes("openai")?r="az.ai.openai":a.includes("azure")&&a.includes("inference")?r="az.ai.inference":a.includes("cohere")?r="cohere":a.includes("deepseek")?r="deepseek":a.includes("gemini")?r="gemini":a.includes("groq")?r="groq":a.includes("watson")||a.includes("ibm")?r="ibm.watsonx.ai":a.includes("mistral")?r="mistral_ai":a.includes("gpt")||a.includes("openai")?r="openai":a.includes("perplexity")||a.includes("sonar")?r="perplexity":a.includes("vertex")?r="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(r="xai")}t.setAttribute(Yw,r)}setInvocationParameters(t,n){if(!n.extra?.metadata?.invocation_params)return;const r=n.extra.metadata.invocation_params;r.max_tokens!==void 0&&t.setAttribute(Qw,r.max_tokens),r.temperature!==void 0&&t.setAttribute(ev,r.temperature),r.top_p!==void 0&&t.setAttribute(tv,r.top_p),r.frequency_penalty!==void 0&&t.setAttribute(nv,r.frequency_penalty),r.presence_penalty!==void 0&&t.setAttribute(rv,r.presence_penalty)}setIOAttributes(t,n){if(n.run.inputs)try{const r=n.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&t.setAttribute(vu,r.model),r.stream!==void 0&&t.setAttribute(Sv,r.stream),r.extra_headers&&t.setAttribute(Tv,JSON.stringify(r.extra_headers)),r.extra_query&&t.setAttribute(ov,JSON.stringify(r.extra_query)),r.extra_body&&t.setAttribute(cv,JSON.stringify(r.extra_body))),t.setAttribute(av,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${n.id}`,r)}if(n.run.outputs)try{const r=n.run.outputs,s=this.getUnifiedRunTokens(r);if(s&&(t.setAttribute(bu,s[0]),t.setAttribute(Su,s[1]),t.setAttribute(Tu,s[0]+s[1])),r&&typeof r=="object"){if(r.model&&t.setAttribute(Xw,String(r.model)),r.id&&t.setAttribute(hv,r.id),r.choices&&Array.isArray(r.choices)){const a=r.choices.map(i=>i.finish_reason).filter(i=>i).map(String);a.length>0&&t.setAttribute(sv,a.join(", "))}if(r.service_tier&&t.setAttribute(pv,r.service_tier),r.system_fingerprint&&t.setAttribute(fv,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const a=r.usage_metadata;a.input_token_details&&t.setAttribute(mv,JSON.stringify(a.input_token_details)),a.output_token_details&&t.setAttribute(gv,JSON.stringify(a.output_token_details))}}t.setAttribute(iv,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${n.id}`,r)}}getUnifiedRunTokens(t){if(!t)return null;let n=this.extractUnifiedRunTokens(t.usage_metadata);if(n)return n;const r=Object.keys(t);for(const i of r){const o=t[i];if(!(!o||typeof o!="object")&&(n=this.extractUnifiedRunTokens(o.usage_metadata),n||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(n=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),n)))return n}const s=t.generations||[];if(!Array.isArray(s))return null;const a=Array.isArray(s[0])?s.flat():s;for(const i of a)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(n=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),n))return n;return null}extractUnifiedRunTokens(t){return!t||typeof t!="object"||typeof t.input_tokens!="number"||typeof t.output_tokens!="number"?null:[t.input_tokens,t.output_tokens]}}const Vv=[429,500,502,503,504];let Au=class{constructor(t){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,"default"in tn?this.queue=new tn.default({concurrency:this.maxConcurrency}):this.queue=new tn({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...n){const r=this.onFailedResponseHook;return this.queue.add(()=>ja(()=>t(...n).catch(s=>{throw s instanceof Error?s:new Error(s)}),{async onFailedAttempt(s){if(s.message.startsWith("Cancel")||s.message.startsWith("TimeoutError")||s.name==="TimeoutError"||s.message.startsWith("AbortError")||s?.code==="ECONNABORTED")throw s;const a=s?.response;if(r&&await r(a))return;const i=a?.status??s?.status;if(i&&!Vv.includes(+i))throw s},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,n,...r){return t.signal?Promise.race([this.call(n,...r),new Promise((s,a)=>{t.signal?.addEventListener("abort",()=>{a(new Error("AbortError"))})})]):this.call(n,...r)}};function ku(e){return typeof e?._getType=="function"}function Ou(e){const t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}const Gv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function V(e,t){if(!Gv.test(e)){const n=t!==void 0?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`;throw new Error(n)}return e}const xu={};function Lo(e){xu[e]||(console.warn(e),xu[e]=!0)}function dn(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);const[t,n]=e.split(":"),r=n||"latest";if(t.includes("/")){const[s,a]=t.split("/",2);if(!s||!a)throw new Error(`Invalid identifier format: ${e}`);return[s,a,r]}else{if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,r]}}class Wv extends Error{constructor(t){super(t),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function D(e,t,n){let r;if(e.ok){n&&(r=await e.text());return}if(e.status===403)try{(await e.json())?.error==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${e.status} ${e.statusText}`);throw o.status=e?.status,o}if(r===void 0)try{r=await e.text()}catch{r=""}const s=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${r}`;if(e.status===409)throw new Wv(s);const a=new Error(s);throw a.status=e.status,a}const Hh="ERR_CONFLICTING_ENDPOINTS";class Jv extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:Hh}),this.name="ConflictingEndpointsError"}}function Kv(e){return typeof e=="object"&&e!==null&&e.code===Hh}var Iu="[...]",Zv={result:"[Circular]"},Fa=[],fr=[];const qv=new TextEncoder;function Yv(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function aa(e){return qv.encode(e)}function Vh(e){if(e&&typeof e=="object"&&e!==null){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if(typeof e=="bigint")return e.toString();return e}function Xv(e){return function(t,n){return Vh(n)}}function lt(e,t,n,r,s){try{const a=JSON.stringify(e,Xv(n),r);return aa(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`
23
23
  Context: ${t}`:""}`),aa("[Unserializable]");Qe("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`
24
24
  Context: ${t}`:""}`),typeof s>"u"&&(s=Yv()),jo(e,"",0,[],void 0,0,s);let i;try{fr.length===0?i=JSON.stringify(e,n,r):i=JSON.stringify(e,Qv(n),r)}catch{return aa("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Fa.length!==0;){const o=Fa.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return aa(i)}}function Ki(e,t,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:e}),Fa.push([r,n,t,s])):fr.push([t,n,e]):(r[n]=e,Fa.push([r,n,t]))}function jo(e,t,n,r,s,a,i){a+=1;var o;if(typeof e=="object"&&e!==null){for(o=0;o<r.length;o++)if(r[o]===e){Ki(Zv,e,t,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){Ki(Iu,e,t,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){Ki(Iu,e,t,s);return}if(r.push(e),Array.isArray(e))for(o=0;o<e.length;o++)jo(e[o],o,o,r,e,a,i);else{e=Vh(e);var c=Object.keys(e);for(o=0;o<c.length;o++){var l=c[o];jo(e[l],l,o,r,e,a,i)}}r.pop()}}function Qv(e){return e=typeof e<"u"?e:function(t,n){return n},function(t,n){if(fr.length>0)for(var r=0;r<fr.length;r++){var s=fr[r];if(s[1]===t&&s[0]===n){n=s[2],fr.splice(r,1);break}}return e.call(this,t,n)}}function Pu(e,t){const n=Uh(),r=t??Fh(),s=e.extra??{},a=s.metadata;return e.extra={...s,runtime:{...n,...s?.runtime},metadata:{...r,...r.revision_id||"revision_id"in e&&e.revision_id?{revision_id:("revision_id"in e?e.revision_id:void 0)??r.revision_id}:{},...a}},e}const eb=e=>{const t=e?.toString()??Qe("TRACING_SAMPLING_RATE");if(t===void 0)return;const n=parseFloat(t);if(n<0||n>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},tb=e=>{const n=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};async function nb(e){const t=[];for await(const n of e)t.push(n);return t}function ia(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const rb=async e=>{if(e?.status===429){const t=parseInt(e.headers.get("retry-after")??"10",10)*1e3;if(t>0)return await new Promise(n=>setTimeout(n,t)),!0}return!1};function Nu(e){return typeof e=="number"?Number(e.toFixed(4)):e}class sb{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(t){let n;const r=new Promise(a=>{n=a}),s=lt(t.item,`Serializing run with id: ${t.item.id}`).length;return this.items.push({action:t.action,payload:t.item,otelContext:t.otelContext,apiKey:t.apiKey,apiUrl:t.apiUrl,itemPromiseResolve:n,itemPromise:r,size:s}),this.sizeBytes+=s,r}pop({upToSizeBytes:t,upToSize:n}){if(t<1)throw new Error("Number of bytes to pop off may not be less than 1.");const r=[];let s=0;for(;s+(this.peek()?.size??0)<t&&this.items.length>0&&r.length<n;){const a=this.items.shift();a&&(r.push(a),s+=a.size,this.sizeBytes-=a.size)}if(r.length===0&&this.items.length>0){const a=this.items.shift();r.push(a),s+=a.size,this.sizeBytes-=a.size}return[r.map(a=>({action:a.action,item:a.payload,otelContext:a.otelContext,apiKey:a.apiKey,apiUrl:a.apiUrl})),()=>r.forEach(a=>a.itemPromiseResolve())]}}const ab=24*1024*1024,ib=1e4,ob=100,Mu="https://api.smith.langchain.com";class zr{get _fetch(){return this.fetchImplementation||Av(this.debug)}constructor(t={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new sb}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Jt("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Jt("LANGSMITH_DEBUG")==="true"});const n=zr.getDefaultClientConfig();if(this.tracingSampleRate=eb(t.tracingSamplingRate),this.apiUrl=ia(t.apiUrl??n.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=ia(t.apiKey??n.apiKey),this.webUrl=ia(t.webUrl??n.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=ia(t.workspaceId??Qe("WORKSPACE_ID")),this.timeout_ms=t.timeout_ms??9e4,this.caller=new Au({...t.callerOptions??{},maxRetries:4,debug:t.debug??this.debug}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=t.debug??this.debug,this.fetchImplementation=t.fetchImplementation,this.batchIngestCaller=new Au({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...t.callerOptions??{},onFailedResponseHook:rb,debug:t.debug??this.debug}),this.hideInputs=t.hideInputs??t.anonymizer??n.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??n.hideOutputs,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.batchSizeLimit=t.batchSizeLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode,Bh()&&(this.langSmithToOTELTranslator=new Hv),this.cachedLSEnvVarsForMetadata=Fh()}static getDefaultClientConfig(){const t=Qe("API_KEY"),n=Qe("ENDPOINT")??Mu,r=Qe("HIDE_INPUTS")==="true",s=Qe("HIDE_OUTPUTS")==="true";return{apiUrl:n,apiKey:t,webUrl:void 0,hideInputs:r,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:tb(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const t={"User-Agent":`langsmith-js/${Lh}`};return this.apiKey&&(t["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(t["x-tenant-id"]=this.workspaceId),t}_getPlatformEndpointPath(t){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${t}`:`/platform/${t}`}async processInputs(t){return this.hideInputs===!1?t:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(t):t}async processOutputs(t){return this.hideOutputs===!1?t:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(t):t}async prepareRunCreateOrUpdateInputs(t){const n={...t};return n.inputs!==void 0&&(n.inputs=await this.processInputs(n.inputs)),n.outputs!==void 0&&(n.outputs=await this.processOutputs(n.outputs)),n}async _getResponse(t,n){const r=n?.toString()??"",s=`${this.apiUrl}${t}?${r}`;return await this.caller.call(async()=>{const i=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await D(i,`fetch ${t}`),i})}async _get(t,n){return(await this._getResponse(t,n)).json()}async*_getPaginated(t,n=new URLSearchParams,r){let s=Number(n.get("offset"))||0;const a=Number(n.get("limit"))||100;for(;;){n.set("offset",String(s)),n.set("limit",String(a));const i=`${this.apiUrl}${t}?${n}`,o=await this.caller.call(async()=>{const l=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await D(l,`fetch ${t}`),l}),c=r?r(await o.json()):await o.json();if(c.length===0||(yield c,c.length<a))break;s+=c.length}}async*_getCursorPaginatedList(t,n=null,r="POST",s="runs"){const a=n?{...n}:{};for(;;){const i=JSON.stringify(a),c=await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}${t}`,{method:r,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await D(u,`fetch ${t}`),u})).json();if(!c||!c[s])break;yield c[s];const l=c.cursors;if(!l||!l.next)break;a.cursor=l.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(t,n=!1){if(this.tracingSampleRate===void 0)return t;if(n){const r=[];for(const s of t)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):r.push(s);return r}else{const r=[];for(const s of t){const a=s.trace_id??s.id;this.filteredPostUuids.has(a)||(s.id===a?this._shouldSample()?r.push(s):this.filteredPostUuids.add(a):r.push(s))}return r}}async _getBatchSizeLimitBytes(){const t=await this._ensureServerInfo();return this.batchSizeBytesLimit??t.batch_ingest_config?.size_limit_bytes??ab}async _getBatchSizeLimit(){const t=await this._ensureServerInfo();return this.batchSizeLimit??t.batch_ingest_config?.size_limit??ob}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:n}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[s,a]=this.autoBatchQueue.pop({upToSizeBytes:t,upToSize:n});if(!s.length){a();break}const i=s.reduce((l,u)=>{const d=u.apiUrl??this.apiUrl,h=u.apiKey??this.apiKey,f=u.apiKey===this.apiKey&&u.apiUrl===this.apiUrl?"default":`${d}|${h}`;return l[f]||(l[f]=[]),l[f].push(u),l},{}),o=[];for(const[l,u]of Object.entries(i)){const d=this._processBatch(u,{apiUrl:l==="default"?void 0:l.split("|")[0],apiKey:l==="default"?void 0:l.split("|")[1]});o.push(d)}const c=Promise.all(o).finally(a);r.push(c)}return Promise.all(r)}async _processBatch(t,n){if(t.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(t);else{const r={runCreates:t.filter(a=>a.action==="create").map(a=>a.item),runUpdates:t.filter(a=>a.action==="update").map(a=>a.item)},s=await this._ensureServerInfo();if(s?.batch_ingest_config?.use_multipart_endpoint){const a=s?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(r,{...n,useGzip:a})}else await this.batchIngestRuns(r,n)}}catch(r){console.error("Error exporting batch:",r)}}_sendBatchToOTELTranslator(t){if(this.langSmithToOTELTranslator!==void 0){const n=new Map,r=[];for(const s of t)s.item.id&&s.otelContext&&(n.set(s.item.id,s.otelContext),s.action==="create"?r.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):r.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(r,n)}}async processRunOperation(t){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,t.item=Pu(t.item,this.cachedLSEnvVarsForMetadata);const n=this.autoBatchQueue.push(t);if(this.manualFlushMode)return n;const r=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>s)&&this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s})},this.autoBatchAggregationDelayMs)),n}async _getServerInfo(){const n=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(ib),...this.fetchOptions});return await D(r,"get server info"),r})).json();return this.debug&&console.log(`
25
25
  === LangSmith Server Configuration ===
@@ -55,11 +55,11 @@ Message: ${Array.isArray(i.detail)?i.detail.join(`
55
55
 
56
56
  ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:n}=Gh(new Date(e.start_time).getTime(),e.id,e.execution_order),r={...e},s=this.getRunById(r.parent_run_id);if(r.parent_run_id!==void 0?s&&(this._addChildRun(s,r),s.child_execution_order=Math.max(s.child_execution_order,r.child_execution_order),r.trace_id=s.trace_id,s.dotted_order!==void 0&&(r.dotted_order=[s.dotted_order,t].join("."),r._serialized_start_time=n)):(r.trace_id=r.id,r.dotted_order=t,r._serialized_start_time=n),this.usesRunTreeMap){const a=Do(r,s);a!==void 0&&this.runTreeMap.set(r.id,a)}else this.runMap.set(r.id,r);return r}async _endTrace(e){const t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,n,r,s,a,i,o){const c=this._getExecutionOrder(r),l=Date.now(),u=i?{...s,metadata:i}:s,d={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleLLMStart(e,t,n,r,s,a,i,o){const c=this.getRunById(n)??this._createRunForLLMStart(e,t,n,r,s,a,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,n,r,s,a,i,o){const c=this._getExecutionOrder(r),l=Date.now(),u=i?{...s,metadata:i}:s,d={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleChatModelStart(e,t,n,r,s,a,i,o){const c=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,r,s,a,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,n,r,s){const a=this.getRunById(t);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=e,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(e,t,n,r,s){const a=this.getRunById(t);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(e,t,n,r,s,a,i,o){const c=this._getExecutionOrder(r),l=Date.now(),u={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:i??"chain",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleChainStart(e,t,n,r,s,a,i,o){const c=this.getRunById(n)??this._createRunForChainStart(e,t,n,r,s,a,i,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,n,r,s){const a=this.getRunById(t);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=qi(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),s?.inputs!==void 0&&(a.inputs=qi(s.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,t,n,r,s){const a=this.getRunById(t);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),s?.inputs!==void 0&&(a.inputs=qi(s.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(e,t,n,r,s,a,i){const o=this._getExecutionOrder(r),c=Date.now(),l={id:n,name:i??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,n,r,s,a,i){const o=this.getRunById(n)??this._createRunForToolStart(e,t,n,r,s,a,i);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="chain")return;const r=n;r.actions=r.actions||[],r.actions.push(e),r.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(n)}async handleAgentEnd(e,t){const n=this.getRunById(t);!n||n?.run_type!=="chain"||(n.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(n))}_createRunForRetrieverStart(e,t,n,r,s,a,i){const o=this._getExecutionOrder(r),c=Date.now(),l={id:n,name:i??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,n,r,s,a,i){const o=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,r,s,a,i);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onRetrieverEnd?.(n),await this._endTrace(n),n}async handleRetrieverError(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onRetrieverError?.(n),await this._endTrace(n),n}async handleText(e,t){const n=this.getRunById(t);!n||n?.run_type!=="chain"||(n.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(n))}async handleLLMNewToken(e,t,n,r,s,a){const i=this.getRunById(n);if(!i||i?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return i.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:a?.chunk}}),await this.onLLMNewToken?.(i,e,{chunk:a?.chunk}),i}},Zh={};F(Zh,{ConsoleCallbackHandler:()=>Uo});function ze(e,t){return`${e.open}${t}${e.close}`}function _t(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function Lu(e){return typeof e=="string"?e.trim():e==null?e:_t(e,e.toString())}function hn(e){if(!e.end_time)return"";const t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}const{color:Xe}=th;var Uo=class extends cn{name="console_callback_handler";persistRun(e){return Promise.resolve()}getParents(e){const t=[];let n=e;for(;n.parent_run_id;){const r=this.runMap.get(n.parent_run_id);if(r)t.push(r),n=r;else break}return t}getBreadcrumbs(e){const n=[...this.getParents(e).reverse(),e].map((r,s,a)=>{const i=`${r.execution_order}:${r.run_type}:${r.name}`;return s===a.length-1?ze(th.bold,i):i}).join(" > ");return ze(Xe.grey,n)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Xe.green,"[chain/start]")} [${t}] Entering Chain run with input: ${_t(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Xe.cyan,"[chain/end]")} [${t}] [${hn(e)}] Exiting Chain run with output: ${_t(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Xe.red,"[chain/error]")} [${t}] [${hn(e)}] Chain run errored with error: ${_t(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),n="prompts"in e.inputs?{prompts:e.inputs.prompts.map(r=>r.trim())}:e.inputs;console.log(`${ze(Xe.green,"[llm/start]")} [${t}] Entering LLM run with input: ${_t(n,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Xe.cyan,"[llm/end]")} [${t}] [${hn(e)}] Exiting LLM run with output: ${_t(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Xe.red,"[llm/error]")} [${t}] [${hn(e)}] LLM run errored with error: ${_t(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Xe.green,"[tool/start]")} [${t}] Entering Tool run with input: "${Lu(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Xe.cyan,"[tool/end]")} [${t}] [${hn(e)}] Exiting Tool run with output: "${Lu(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Xe.red,"[tool/error]")} [${t}] [${hn(e)}] Tool run errored with error: ${_t(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Xe.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${_t(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Xe.cyan,"[retriever/end]")} [${t}] [${hn(e)}] Exiting Retriever run with output: ${_t(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Xe.red,"[retriever/error]")} [${t}] [${hn(e)}] Retriever run errored with error: ${_t(e.error,"[error]")}`)}onAgentAction(e){const t=e,n=this.getBreadcrumbs(e);console.log(`${ze(Xe.blue,"[agent/action]")} [${n}] Agent selected action: ${_t(t.actions[t.actions.length-1],"[action]")}`)}};let Yi;const qh=()=>{if(Yi===void 0){const e=nn("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Yi=new zr(e)}return Yi};let yb=class{getStore(){}run(t,n){return n()}};const Xi=Symbol.for("ls:tracing_async_local_storage"),_b=new yb;let wb=class{getInstance(){return globalThis[Xi]??_b}initializeGlobalInstance(t){globalThis[Xi]===void 0&&(globalThis[Xi]=t)}};const vb=new wb;function bb(e=!1){const t=vb.getInstance().getStore();if(!e&&t===void 0)throw new Error(`Could not get the current run tree.
57
57
 
58
- Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}function Qc(e){return typeof e=="function"&&"langsmith:traceable"in e}var Yh={};F(Yh,{LangChainTracer:()=>ga});var ga=class Xh extends cn{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(t={}){super(t);const{exampleId:n,projectName:r,client:s,replicas:a}=t;this.projectName=r??$h(),this.replicas=a,this.exampleId=n,this.client=s??qh();const i=Xh.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(t){}async onRunCreate(t){await this.getRunTreeWithTracingConfig(t.id)?.postRun()}async onRunUpdate(t){await this.getRunTreeWithTracingConfig(t.id)?.patchRun()}getRun(t){return this.runTreeMap.get(t)}updateFromRunTree(t){this.runTreeMap.set(t.id,t);let n=t;const r=new Set;for(;n.parent_run&&!(r.has(n.id)||(r.add(n.id),!n.parent_run));)n=n.parent_run;r.clear();const s=[n];for(;s.length>0;){const a=s.shift();!a||r.has(a.id)||(r.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&s.push(...a.child_runs))}this.client=t.client??this.client,this.replicas=t.replicas??this.replicas,this.projectName=t.project_name??this.projectName,this.exampleId=t.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(t){const n=this.runTreeMap.get(t);if(n)return new We({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return bb(!0)}catch{return}}};const Qh=Symbol.for("ls:tracing_async_local_storage"),Hn=Symbol.for("lc:context_variables"),Sb=e=>{globalThis[Qh]=e},Hr=()=>globalThis[Qh];let Vn;function Tb(){const e="default"in tn?tn.default:tn;return new e({autoStart:!0,concurrency:1})}function Eb(){return typeof Vn>"u"&&(Vn=Tb()),Vn}async function we(e,t){if(t===!0){const n=Hr();n!==void 0?await n.run(void 0,async()=>e()):await e()}else Vn=Eb(),Vn.add(async()=>{const n=Hr();n!==void 0?await n.run(void 0,async()=>e()):await e()})}async function Cb(){const e=qh();await Promise.allSettled([typeof Vn<"u"?Vn.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}var ep={};F(ep,{awaitAllCallbacks:()=>Cb,consumeCallback:()=>we});const Ab=e=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(n=>nn(n)==="true");function kb(e,t){const n=Hr();if(n===void 0)throw new Error("Internal error: Global shared async local storage instance has not been initialized.");const r=n.getStore(),s={...r?.[Hn]};s[e]=t;let a={};Wh(r)&&(a=new We(r)),a[Hn]=s,n.enterWith(a)}function el(e){const t=Hr();return t===void 0?void 0:t.getStore()?.[Hn]?.[e]}const Ob=Symbol("lc:configure_hooks"),xb=()=>el(Ob)||[];var tp={};F(tp,{BaseCallbackManager:()=>np,BaseRunManager:()=>Ws,CallbackManager:()=>Ze,CallbackManagerForChainRun:()=>sp,CallbackManagerForLLMRun:()=>Fo,CallbackManagerForRetrieverRun:()=>rp,CallbackManagerForToolRun:()=>ap,ensureHandler:()=>Ts,parseCallbackConfigArg:()=>Gs});function Gs(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}var np=class{setHandler(e){return this.setHandlers([e])}},Ws=class{constructor(e,t,n,r,s,a,i,o){this.runId=e,this.handlers=t,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=s,this.metadata=a,this.inheritableMetadata=i,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>we(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleCustomEvent(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{try{await a.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}},rp=class extends Ws{getChild(e){const t=new Ze(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>we(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw n}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>we(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${n}`),t.raiseError)throw e}},t.awaitHandlers)))}},Fo=class extends Ws{async handleLLMNewToken(e,t,n,r,s,a){await Promise.all(this.handlers.map(i=>we(async()=>{if(!i.ignoreLLM)try{await i.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMNewToken: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMError(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{if(!a.ignoreLLM)try{await a.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMError: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}async handleLLMEnd(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{if(!a.ignoreLLM)try{await a.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMEnd: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}},sp=class extends Ws{getChild(e){const t=new Ze(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{if(!a.ignoreChain)try{await a.handleChainError?.(e,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainError: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}async handleChainEnd(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{if(!a.ignoreChain)try{await a.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainEnd: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>we(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>we(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}},ap=class extends Ws{getChild(e){const t=new Ze(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>we(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>we(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}},Ze=class os extends np{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(t,n){super(),this.handlers=n?.handlers??this.handlers,this.inheritableHandlers=n?.inheritableHandlers??this.inheritableHandlers,this.tags=n?.tags??this.tags,this.inheritableTags=n?.inheritableTags??this.inheritableTags,this.metadata=n?.metadata??this.metadata,this.inheritableMetadata=n?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=t}getParentRunId(){return this._parentRunId}async handleLLMStart(t,n,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(l,u)=>{const d=u===0&&r?r:Ce();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return pr(h)&&h._createRunForLLMStart(t,[l],d,this._parentRunId,a,this.tags,this.metadata,c),we(async()=>{try{await h.handleLLMStart?.(t,[l],d,this._parentRunId,a,this.tags,this.metadata,c)}catch(p){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${p}`),h.raiseError)throw p}},h.awaitHandlers)})),new Fo(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,n,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(l,u)=>{const d=u===0&&r?r:Ce();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return pr(h)&&h._createRunForChatModelStart(t,[l],d,this._parentRunId,a,this.tags,this.metadata,c),we(async()=>{try{if(h.handleChatModelStart)await h.handleChatModelStart?.(t,[l],d,this._parentRunId,a,this.tags,this.metadata,c);else if(h.handleLLMStart){const p=Zc(l);await h.handleLLMStart?.(t,[p],d,this._parentRunId,a,this.tags,this.metadata,c)}}catch(p){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${p}`),h.raiseError)throw p}},h.awaitHandlers)})),new Fo(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,n,r=Ce(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return pr(c)&&c._createRunForChainStart(t,n,r,this._parentRunId,this.tags,this.metadata,s,o),we(async()=>{try{await c.handleChainStart?.(t,n,r,this._parentRunId,this.tags,this.metadata,s,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleChainStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new sp(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,n,r=Ce(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return pr(c)&&c._createRunForToolStart(t,n,r,this._parentRunId,this.tags,this.metadata,o),we(async()=>{try{await c.handleToolStart?.(t,n,r,this._parentRunId,this.tags,this.metadata,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new ap(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,n,r=Ce(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return pr(c)&&c._createRunForRetrieverStart(t,n,r,this._parentRunId,this.tags,this.metadata,o),we(async()=>{try{await c.handleRetrieverStart?.(t,n,r,this._parentRunId,this.tags,this.metadata,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new rp(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,n,r,s,a){await Promise.all(this.handlers.map(i=>we(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(t,n,r,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(t,n=!0){this.handlers.push(t),n&&this.inheritableHandlers.push(t)}removeHandler(t){this.handlers=this.handlers.filter(n=>n!==t),this.inheritableHandlers=this.inheritableHandlers.filter(n=>n!==t)}setHandlers(t,n=!0){this.handlers=[],this.inheritableHandlers=[];for(const r of t)this.addHandler(r,n)}addTags(t,n=!0){this.removeTags(t),this.tags.push(...t),n&&this.inheritableTags.push(...t)}removeTags(t){this.tags=this.tags.filter(n=>!t.includes(n)),this.inheritableTags=this.inheritableTags.filter(n=>!t.includes(n))}addMetadata(t,n=!0){this.metadata={...this.metadata,...t},n&&(this.inheritableMetadata={...this.inheritableMetadata,...t})}removeMetadata(t){for(const n of Object.keys(t))delete this.metadata[n],delete this.inheritableMetadata[n]}copy(t=[],n=!0){const r=new os(this._parentRunId);for(const s of this.handlers){const a=this.inheritableHandlers.includes(s);r.addHandler(s,a)}for(const s of this.tags){const a=this.inheritableTags.includes(s);r.addTags([s],a)}for(const s of Object.keys(this.metadata)){const a=Object.keys(this.inheritableMetadata).includes(s);r.addMetadata({[s]:this.metadata[s]},a)}for(const s of t)r.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===s.name)||r.addHandler(s,n);return r}static fromHandlers(t){class n extends es{name=Ce();constructor(){super(),Object.assign(this,t)}}const r=new this;return r.addHandler(new n),r}static configure(t,n,r,s,a,i,o){return this._configureSync(t,n,r,s,a,i,o)}static _configureSync(t,n,r,s,a,i,o){let c;(t||n)&&(Array.isArray(t)||!t?(c=new os,c.setHandlers(t?.map(Ts)??[],!0)):c=t,c=c.copy(Array.isArray(n)?n.map(Ts):n?.handlers,!1));const l=nn("LANGCHAIN_VERBOSE")==="true"||o?.verbose,u=ga.getTraceableRunTree()?.tracingEnabled||Ab(),d=u||(nn("LANGCHAIN_TRACING")??!1);if(l||d){if(c||(c=new os),l&&!c.handlers.some(h=>h.name===Uo.prototype.name)){const h=new Uo;c.addHandler(h,!0)}if(d&&!c.handlers.some(h=>h.name==="langchain_tracer")&&u){const h=new ga;c.addHandler(h,!0)}if(u){const h=ga.getTraceableRunTree();h&&c._parentRunId===void 0&&(c._parentRunId=h.id,c.handlers.find(f=>f.name==="langchain_tracer")?.updateFromRunTree(h))}}for(const{contextVar:h,inheritable:p=!0,handlerClass:f,envVar:y}of xb()){const S=y&&nn(y)==="true"&&f;let b;const v=h!==void 0?el(h):void 0;v&&Mh(v)?b=v:S&&(b=new f({})),b!==void 0&&(c||(c=new os),c.handlers.some(w=>w.name===b.name)||c.addHandler(b,p))}return(r||s)&&c&&(c.addTags(r??[]),c.addTags(s??[],!1)),(a||i)&&c&&(c.addMetadata(a??{}),c.addMetadata(i??{},!1)),c}};function Ts(e){return"name"in e?e:es.fromMethods(e)}var ip=class{getStore(){}run(e,t){return t()}enterWith(e){}};const Ib=new ip,ju=Symbol.for("lc:child_config");var Pb=class{getInstance(){return Hr()??Ib}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[ju]}runWithConfig(e,t,n){const r=Ze._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),s=this.getInstance(),a=s.getStore(),i=r?.getParentRunId(),o=r?.handlers?.find(l=>l?.name==="langchain_tracer");let c;return o&&i?c=o.getRunTreeWithTracingConfig(i):n||(c=new We({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[ju]:e}),a!==void 0&&a[Hn]!==void 0&&(c===void 0&&(c={}),c[Hn]=a[Hn]),s.run(c,t)}initializeGlobalInstance(e){Hr()===void 0&&Sb(e)}};const me=new Pb;var op={};F(op,{AsyncLocalStorageProviderSingleton:()=>me,MockAsyncLocalStorage:()=>ip,_CONTEXT_VARIABLES_KEY:()=>Hn});const Qi=25;async function nt(e){return Ze._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function pt(...e){const t={};for(const n of e.filter(r=>!!r))for(const r of Object.keys(n))if(r==="metadata")t[r]={...t[r],...n[r]};else if(r==="tags"){const s=t[r]??[];t[r]=[...new Set(s.concat(n[r]??[]))]}else if(r==="configurable")t[r]={...t[r],...n[r]};else if(r==="timeout")t.timeout===void 0?t.timeout=n.timeout:n.timeout!==void 0&&(t.timeout=Math.min(t.timeout,n.timeout));else if(r==="signal")t.signal===void 0?t.signal=n.signal:n.signal!==void 0&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,n.signal]):t.signal=n.signal);else if(r==="callbacks"){const s=t.callbacks,a=n.callbacks;if(Array.isArray(a))if(!s)t.callbacks=a;else if(Array.isArray(s))t.callbacks=s.concat(a);else{const i=s.copy();for(const o of a)i.addHandler(Ts(o),!0);t.callbacks=i}else if(a)if(!s)t.callbacks=a;else if(Array.isArray(s)){const i=a.copy();for(const o of s)i.addHandler(Ts(o),!0);t.callbacks=i}else t.callbacks=new Ze(a._parentRunId,{handlers:s.handlers.concat(a.handlers),inheritableHandlers:s.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(s.tags.concat(a.tags))),inheritableTags:Array.from(new Set(s.inheritableTags.concat(a.inheritableTags))),metadata:{...s.metadata,...a.metadata}})}else{const s=r;t[s]=n[s]??t[s]}return t}const Nb=new Set(["string","number","boolean"]);function K(e){const t=me.getRunnableConfig();let n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:r,runName:s,...a}=t;n=Object.entries(a).reduce((i,[o,c])=>(c!==void 0&&(i[o]=c),i),n)}if(e&&(n=Object.entries(e).reduce((r,[s,a])=>(a!==void 0&&(r[s]=a),r),n)),n?.configurable)for(const r of Object.keys(n.configurable))Nb.has(typeof n.configurable[r])&&!n.metadata?.[r]&&(n.metadata||(n.metadata={}),n.metadata[r]=n.configurable[r]);if(n.timeout!==void 0){if(n.timeout<=0)throw new Error("Timeout must be a positive number");const r=AbortSignal.timeout(n.timeout);n.signal!==void 0?"any"in AbortSignal&&(n.signal=AbortSignal.any([n.signal,r])):n.signal=r,delete n.timeout}return n}function ne(e={},{callbacks:t,maxConcurrency:n,recursionLimit:r,runName:s,configurable:a,runId:i}={}){const o=K(e);return t!==void 0&&(delete o.runName,o.callbacks=t),r!==void 0&&(o.recursionLimit=r),n!==void 0&&(o.maxConcurrency=n),s!==void 0&&(o.runName=s),a!==void 0&&(o.configurable={...o.configurable,...a}),i!==void 0&&delete o.runId,o}function on(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}async function On(e,t){if(t===void 0)return e;let n;return Promise.race([e.catch(r=>{if(!t?.aborted)throw r}),new Promise((r,s)=>{n=()=>{s(Es(t))},t.addEventListener("abort",n),t.aborted&&s(Es(t))})]).finally(()=>t.removeEventListener("abort",n))}function Es(e){return e?.reason instanceof Error?e.reason:typeof e?.reason=="string"?new Error(e.reason):new Error("Aborted")}function ge(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_zod"in t))return!1;const n=t._zod;return typeof n=="object"&&n!==null&&"def"in n}function Se(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_def"in t)||"_zod"in t)return!1;const n=t._def;return typeof n=="object"&&n!=null&&"typeName"in n}function Mb(e){return ge(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Se(e)}function er(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(ge(e)||Se(e))}function cp(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function lp(e){return ge(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function Rb(e){return!!(cp(e)||lp(e))}async function tl(e,t){if(ge(e))try{return{success:!0,data:await nh(e,t)}}catch(n){return{success:!1,error:n}}if(Se(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function gi(e,t){if(ge(e))return await nh(e,t);if(Se(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function $b(e,t){if(ge(e))try{return{success:!0,data:Dc(e,t)}}catch(n){return{success:!1,error:n}}if(Se(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function bn(e,t){if(ge(e))return Dc(e,t);if(Se(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Vr(e){if(ge(e))return Re.get(e)?.description;if(Se(e)||"description"in e&&typeof e.description=="string")return e.description}function Lb(e){if(!er(e))return!1;if(Se(e)){const t=e._def;if(t.typeName==="ZodObject"){const n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(ge(e)){const t=e._zod.def;if(t.type==="object"){const n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function nl(e){return er(e)?Se(e)?e._def.typeName==="ZodString":ge(e)?e._zod.def.type==="string":!1:!1}function rl(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function Wt(e){return ge(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function yi(e){return ge(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function et(e){return!!(rl(e)||Wt(e))}function Cs(e){if(Se(e))return e.shape;if(ge(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function up(e,t){if(Se(e))return e.extend(t);if(ge(e))return s_(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function sl(e){if(Se(e))return e.partial();if(ge(e))return a_(jc,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function za(e,t=!1){if(Se(e))return e.strict();if(Wt(e)){const n=e._zod.def.shape;if(t)for(const[a,i]of Object.entries(e._zod.def.shape)){if(Wt(i)){const c=za(i,t);n[a]=c}else if(yi(i)){let c=i._zod.def.element;Wt(c)&&(c=za(c,t)),n[a]=An(i,{...i._zod.def,element:c})}else n[a]=i;const o=Re.get(i);o&&Re.add(n[a],o)}const r=An(e,{...e._zod.def,shape:n,catchall:i_(o_)}),s=Re.get(e);return s&&Re.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Bo(e,t=!1){if(rl(e))return e.passthrough();if(Wt(e)){const n=e._zod.def.shape;if(t)for(const[a,i]of Object.entries(e._zod.def.shape)){if(Wt(i)){const c=Bo(i,t);n[a]=c}else if(yi(i)){let c=i._zod.def.element;Wt(c)&&(c=Bo(c,t)),n[a]=An(i,{...i._zod.def,element:c})}else n[a]=i;const o=Re.get(i);o&&Re.add(n[a],o)}const r=An(e,{...e._zod.def,shape:n,catchall:c_(l_)}),s=Re.get(e);return s&&Re.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function _i(e){if(Se(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(ge(e))try{const t=Dc(e,void 0);return()=>t}catch{return}}function jb(e){return Se(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function Db(e){return ge(e)&&e._zod.def.type==="pipe"}function mr(e,t=!1){if(Se(e))return jb(e)?mr(e._def.schema,t):e;if(ge(e)){let n=e;if(Db(e)&&(n=mr(e._zod.def.in,t)),t){if(Wt(n)){const s=n._zod.def.shape;for(const[a,i]of Object.entries(n._zod.def.shape))s[a]=mr(i,t);n=An(n,{...n._zod.def,shape:s})}else if(yi(n)){const s=mr(n._zod.def.element,t);n=An(n,{...n._zod.def,element:s})}}const r=Re.get(e);return r&&Re.add(n,r),n}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function dp(e,t){if(Se(e)){const n=Cs(e),r={};for(const[s,a]of Object.entries(n))t(s,a)?r[s]=a.optional():r[s]=a;return e.extend(r)}if(ge(e)){const n=Cs(e),r={...e._zod.def.shape};for(const[i,o]of Object.entries(n))t(i,o)&&(r[i]=new jc({type:"optional",innerType:o}));const s=An(e,{...e._zod.def,shape:r}),a=Re.get(e);return a&&Re.add(s,a),s}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}const Ub=Symbol("Let zodToJsonSchema decide on which parser to use"),Fb={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Bb=e=>({...Fb,...e}),zb=e=>{const t=Bb(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},hp=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function st(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?hp(t,e.currentPath):t.join("/")}}function pp(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function se(e,t,n,r,s){e[t]=n,pp(e,t,r,s)}function Hb(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==R.ZodAny&&(n.items=Q(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&se(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&se(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(se(n,"minItems",e.exactLength.value,e.exactLength.message,t),se(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function Vb(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":t.target==="jsonSchema7"?r.inclusive?se(n,"minimum",r.value,r.message,t):se(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),se(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?se(n,"maximum",r.value,r.message,t):se(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),se(n,"maximum",r.value,r.message,t));break;case"multipleOf":se(n,"multipleOf",r.value,r.message,t);break}return n}function Gb(){return{type:"boolean"}}function fp(e,t){return Q(e.type._def,t)}const Wb=(e,t)=>Q(e.innerType._def,t);function mp(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(s=>mp(e,t,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Jb(e,t)}}const Jb=(e,t)=>{const n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(const r of e.checks)switch(r.kind){case"min":se(n,"minimum",r.value,r.message,t);break;case"max":se(n,"maximum",r.value,r.message,t);break}return n};function Kb(e,t){return{...Q(e.innerType._def,t),default:e.defaultValue()}}function Zb(e,t){return t.effectStrategy==="input"?Q(e.schema._def,t):st(t)}function qb(e){return{type:"string",enum:Array.from(e.values)}}const Yb=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function Xb(e,t){const n=[Q(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Q(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a);let r=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(a=>{if(Yb(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function Qb(e,t){const n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}let eo;const At={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(eo===void 0&&(eo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),eo),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function gp(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":se(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":se(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":kt(n,"email",r.message,t);break;case"format:idn-email":kt(n,"idn-email",r.message,t);break;case"pattern:zod":He(n,At.email,r.message,t);break}break;case"url":kt(n,"uri",r.message,t);break;case"uuid":kt(n,"uuid",r.message,t);break;case"regex":He(n,r.regex,r.message,t);break;case"cuid":He(n,At.cuid,r.message,t);break;case"cuid2":He(n,At.cuid2,r.message,t);break;case"startsWith":He(n,RegExp(`^${to(r.value,t)}`),r.message,t);break;case"endsWith":He(n,RegExp(`${to(r.value,t)}$`),r.message,t);break;case"datetime":kt(n,"date-time",r.message,t);break;case"date":kt(n,"date",r.message,t);break;case"time":kt(n,"time",r.message,t);break;case"duration":kt(n,"duration",r.message,t);break;case"length":se(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t),se(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":He(n,RegExp(to(r.value,t)),r.message,t);break;case"ip":r.version!=="v6"&&kt(n,"ipv4",r.message,t),r.version!=="v4"&&kt(n,"ipv6",r.message,t);break;case"base64url":He(n,At.base64url,r.message,t);break;case"jwt":He(n,At.jwt,r.message,t);break;case"cidr":r.version!=="v6"&&He(n,At.ipv4Cidr,r.message,t),r.version!=="v4"&&He(n,At.ipv6Cidr,r.message,t);break;case"emoji":He(n,At.emoji(),r.message,t);break;case"ulid":He(n,At.ulid,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":kt(n,"binary",r.message,t);break;case"contentEncoding:base64":se(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":He(n,At.base64,r.message,t);break}break;case"nanoid":He(n,At.nanoid,r.message,t);break}return n}function to(e,t){return t.patternStrategy==="escape"?t0(e):e}const e0=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function t0(e){let t="";for(let n=0;n<e.length;n++)e0.has(e[n])||(t+="\\"),t+=e[n];return t}function kt(e,t,n,r){e.format||e.anyOf?.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):se(e,"format",t,n,r)}function He(e,t,n,r){e.pattern||e.allOf?.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Du(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):se(e,"pattern",Du(t,r),n,r)}function Du(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,o=!1;for(let c=0;c<r.length;c++){if(a){s+=r[c],a=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){o?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),o=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],o=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){s+=`(^|(?<=[\r
58
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}function Qc(e){return typeof e=="function"&&"langsmith:traceable"in e}var Yh={};F(Yh,{LangChainTracer:()=>ga});var ga=class Xh extends cn{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(t={}){super(t);const{exampleId:n,projectName:r,client:s,replicas:a}=t;this.projectName=r??$h(),this.replicas=a,this.exampleId=n,this.client=s??qh();const i=Xh.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(t){}async onRunCreate(t){await this.getRunTreeWithTracingConfig(t.id)?.postRun()}async onRunUpdate(t){await this.getRunTreeWithTracingConfig(t.id)?.patchRun()}getRun(t){return this.runTreeMap.get(t)}updateFromRunTree(t){this.runTreeMap.set(t.id,t);let n=t;const r=new Set;for(;n.parent_run&&!(r.has(n.id)||(r.add(n.id),!n.parent_run));)n=n.parent_run;r.clear();const s=[n];for(;s.length>0;){const a=s.shift();!a||r.has(a.id)||(r.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&s.push(...a.child_runs))}this.client=t.client??this.client,this.replicas=t.replicas??this.replicas,this.projectName=t.project_name??this.projectName,this.exampleId=t.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(t){const n=this.runTreeMap.get(t);if(n)return new We({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return bb(!0)}catch{return}}};const Qh=Symbol.for("ls:tracing_async_local_storage"),Hn=Symbol.for("lc:context_variables"),Sb=e=>{globalThis[Qh]=e},Hr=()=>globalThis[Qh];let Vn;function Tb(){const e="default"in tn?tn.default:tn;return new e({autoStart:!0,concurrency:1})}function Eb(){return typeof Vn>"u"&&(Vn=Tb()),Vn}async function we(e,t){if(t===!0){const n=Hr();n!==void 0?await n.run(void 0,async()=>e()):await e()}else Vn=Eb(),Vn.add(async()=>{const n=Hr();n!==void 0?await n.run(void 0,async()=>e()):await e()})}async function Cb(){const e=qh();await Promise.allSettled([typeof Vn<"u"?Vn.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}var ep={};F(ep,{awaitAllCallbacks:()=>Cb,consumeCallback:()=>we});const Ab=e=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(n=>nn(n)==="true");function kb(e,t){const n=Hr();if(n===void 0)throw new Error("Internal error: Global shared async local storage instance has not been initialized.");const r=n.getStore(),s={...r?.[Hn]};s[e]=t;let a={};Wh(r)&&(a=new We(r)),a[Hn]=s,n.enterWith(a)}function el(e){const t=Hr();return t===void 0?void 0:t.getStore()?.[Hn]?.[e]}const Ob=Symbol("lc:configure_hooks"),xb=()=>el(Ob)||[];var tp={};F(tp,{BaseCallbackManager:()=>np,BaseRunManager:()=>Ws,CallbackManager:()=>Ze,CallbackManagerForChainRun:()=>sp,CallbackManagerForLLMRun:()=>Fo,CallbackManagerForRetrieverRun:()=>rp,CallbackManagerForToolRun:()=>ap,ensureHandler:()=>Ts,parseCallbackConfigArg:()=>Gs});function Gs(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}var np=class{setHandler(e){return this.setHandlers([e])}},Ws=class{constructor(e,t,n,r,s,a,i,o){this.runId=e,this.handlers=t,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=s,this.metadata=a,this.inheritableMetadata=i,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>we(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleCustomEvent(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{try{await a.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}},rp=class extends Ws{getChild(e){const t=new Ze(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>we(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw n}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>we(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${n}`),t.raiseError)throw e}},t.awaitHandlers)))}},Fo=class extends Ws{async handleLLMNewToken(e,t,n,r,s,a){await Promise.all(this.handlers.map(i=>we(async()=>{if(!i.ignoreLLM)try{await i.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMNewToken: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMError(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{if(!a.ignoreLLM)try{await a.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMError: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}async handleLLMEnd(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{if(!a.ignoreLLM)try{await a.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMEnd: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}},sp=class extends Ws{getChild(e){const t=new Ze(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{if(!a.ignoreChain)try{await a.handleChainError?.(e,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainError: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}async handleChainEnd(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{if(!a.ignoreChain)try{await a.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainEnd: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>we(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>we(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}},ap=class extends Ws{getChild(e){const t=new Ze(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>we(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>we(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}},Ze=class os extends np{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(t,n){super(),this.handlers=n?.handlers??this.handlers,this.inheritableHandlers=n?.inheritableHandlers??this.inheritableHandlers,this.tags=n?.tags??this.tags,this.inheritableTags=n?.inheritableTags??this.inheritableTags,this.metadata=n?.metadata??this.metadata,this.inheritableMetadata=n?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=t}getParentRunId(){return this._parentRunId}async handleLLMStart(t,n,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(l,u)=>{const d=u===0&&r?r:Ce();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return pr(h)&&h._createRunForLLMStart(t,[l],d,this._parentRunId,a,this.tags,this.metadata,c),we(async()=>{try{await h.handleLLMStart?.(t,[l],d,this._parentRunId,a,this.tags,this.metadata,c)}catch(p){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${p}`),h.raiseError)throw p}},h.awaitHandlers)})),new Fo(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,n,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(l,u)=>{const d=u===0&&r?r:Ce();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return pr(h)&&h._createRunForChatModelStart(t,[l],d,this._parentRunId,a,this.tags,this.metadata,c),we(async()=>{try{if(h.handleChatModelStart)await h.handleChatModelStart?.(t,[l],d,this._parentRunId,a,this.tags,this.metadata,c);else if(h.handleLLMStart){const p=Zc(l);await h.handleLLMStart?.(t,[p],d,this._parentRunId,a,this.tags,this.metadata,c)}}catch(p){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${p}`),h.raiseError)throw p}},h.awaitHandlers)})),new Fo(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,n,r=Ce(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return pr(c)&&c._createRunForChainStart(t,n,r,this._parentRunId,this.tags,this.metadata,s,o),we(async()=>{try{await c.handleChainStart?.(t,n,r,this._parentRunId,this.tags,this.metadata,s,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleChainStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new sp(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,n,r=Ce(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return pr(c)&&c._createRunForToolStart(t,n,r,this._parentRunId,this.tags,this.metadata,o),we(async()=>{try{await c.handleToolStart?.(t,n,r,this._parentRunId,this.tags,this.metadata,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new ap(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,n,r=Ce(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return pr(c)&&c._createRunForRetrieverStart(t,n,r,this._parentRunId,this.tags,this.metadata,o),we(async()=>{try{await c.handleRetrieverStart?.(t,n,r,this._parentRunId,this.tags,this.metadata,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new rp(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,n,r,s,a){await Promise.all(this.handlers.map(i=>we(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(t,n,r,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(t,n=!0){this.handlers.push(t),n&&this.inheritableHandlers.push(t)}removeHandler(t){this.handlers=this.handlers.filter(n=>n!==t),this.inheritableHandlers=this.inheritableHandlers.filter(n=>n!==t)}setHandlers(t,n=!0){this.handlers=[],this.inheritableHandlers=[];for(const r of t)this.addHandler(r,n)}addTags(t,n=!0){this.removeTags(t),this.tags.push(...t),n&&this.inheritableTags.push(...t)}removeTags(t){this.tags=this.tags.filter(n=>!t.includes(n)),this.inheritableTags=this.inheritableTags.filter(n=>!t.includes(n))}addMetadata(t,n=!0){this.metadata={...this.metadata,...t},n&&(this.inheritableMetadata={...this.inheritableMetadata,...t})}removeMetadata(t){for(const n of Object.keys(t))delete this.metadata[n],delete this.inheritableMetadata[n]}copy(t=[],n=!0){const r=new os(this._parentRunId);for(const s of this.handlers){const a=this.inheritableHandlers.includes(s);r.addHandler(s,a)}for(const s of this.tags){const a=this.inheritableTags.includes(s);r.addTags([s],a)}for(const s of Object.keys(this.metadata)){const a=Object.keys(this.inheritableMetadata).includes(s);r.addMetadata({[s]:this.metadata[s]},a)}for(const s of t)r.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===s.name)||r.addHandler(s,n);return r}static fromHandlers(t){class n extends es{name=Ce();constructor(){super(),Object.assign(this,t)}}const r=new this;return r.addHandler(new n),r}static configure(t,n,r,s,a,i,o){return this._configureSync(t,n,r,s,a,i,o)}static _configureSync(t,n,r,s,a,i,o){let c;(t||n)&&(Array.isArray(t)||!t?(c=new os,c.setHandlers(t?.map(Ts)??[],!0)):c=t,c=c.copy(Array.isArray(n)?n.map(Ts):n?.handlers,!1));const l=nn("LANGCHAIN_VERBOSE")==="true"||o?.verbose,u=ga.getTraceableRunTree()?.tracingEnabled||Ab(),d=u||(nn("LANGCHAIN_TRACING")??!1);if(l||d){if(c||(c=new os),l&&!c.handlers.some(h=>h.name===Uo.prototype.name)){const h=new Uo;c.addHandler(h,!0)}if(d&&!c.handlers.some(h=>h.name==="langchain_tracer")&&u){const h=new ga;c.addHandler(h,!0)}if(u){const h=ga.getTraceableRunTree();h&&c._parentRunId===void 0&&(c._parentRunId=h.id,c.handlers.find(f=>f.name==="langchain_tracer")?.updateFromRunTree(h))}}for(const{contextVar:h,inheritable:p=!0,handlerClass:f,envVar:y}of xb()){const S=y&&nn(y)==="true"&&f;let b;const v=h!==void 0?el(h):void 0;v&&Mh(v)?b=v:S&&(b=new f({})),b!==void 0&&(c||(c=new os),c.handlers.some(w=>w.name===b.name)||c.addHandler(b,p))}return(r||s)&&c&&(c.addTags(r??[]),c.addTags(s??[],!1)),(a||i)&&c&&(c.addMetadata(a??{}),c.addMetadata(i??{},!1)),c}};function Ts(e){return"name"in e?e:es.fromMethods(e)}var ip=class{getStore(){}run(e,t){return t()}enterWith(e){}};const Ib=new ip,ju=Symbol.for("lc:child_config");var Pb=class{getInstance(){return Hr()??Ib}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[ju]}runWithConfig(e,t,n){const r=Ze._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),s=this.getInstance(),a=s.getStore(),i=r?.getParentRunId(),o=r?.handlers?.find(l=>l?.name==="langchain_tracer");let c;return o&&i?c=o.getRunTreeWithTracingConfig(i):n||(c=new We({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[ju]:e}),a!==void 0&&a[Hn]!==void 0&&(c===void 0&&(c={}),c[Hn]=a[Hn]),s.run(c,t)}initializeGlobalInstance(e){Hr()===void 0&&Sb(e)}};const me=new Pb;var op={};F(op,{AsyncLocalStorageProviderSingleton:()=>me,MockAsyncLocalStorage:()=>ip,_CONTEXT_VARIABLES_KEY:()=>Hn});const Qi=25;async function nt(e){return Ze._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function pt(...e){const t={};for(const n of e.filter(r=>!!r))for(const r of Object.keys(n))if(r==="metadata")t[r]={...t[r],...n[r]};else if(r==="tags"){const s=t[r]??[];t[r]=[...new Set(s.concat(n[r]??[]))]}else if(r==="configurable")t[r]={...t[r],...n[r]};else if(r==="timeout")t.timeout===void 0?t.timeout=n.timeout:n.timeout!==void 0&&(t.timeout=Math.min(t.timeout,n.timeout));else if(r==="signal")t.signal===void 0?t.signal=n.signal:n.signal!==void 0&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,n.signal]):t.signal=n.signal);else if(r==="callbacks"){const s=t.callbacks,a=n.callbacks;if(Array.isArray(a))if(!s)t.callbacks=a;else if(Array.isArray(s))t.callbacks=s.concat(a);else{const i=s.copy();for(const o of a)i.addHandler(Ts(o),!0);t.callbacks=i}else if(a)if(!s)t.callbacks=a;else if(Array.isArray(s)){const i=a.copy();for(const o of s)i.addHandler(Ts(o),!0);t.callbacks=i}else t.callbacks=new Ze(a._parentRunId,{handlers:s.handlers.concat(a.handlers),inheritableHandlers:s.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(s.tags.concat(a.tags))),inheritableTags:Array.from(new Set(s.inheritableTags.concat(a.inheritableTags))),metadata:{...s.metadata,...a.metadata}})}else{const s=r;t[s]=n[s]??t[s]}return t}const Nb=new Set(["string","number","boolean"]);function K(e){const t=me.getRunnableConfig();let n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:r,runName:s,...a}=t;n=Object.entries(a).reduce((i,[o,c])=>(c!==void 0&&(i[o]=c),i),n)}if(e&&(n=Object.entries(e).reduce((r,[s,a])=>(a!==void 0&&(r[s]=a),r),n)),n?.configurable)for(const r of Object.keys(n.configurable))Nb.has(typeof n.configurable[r])&&!n.metadata?.[r]&&(n.metadata||(n.metadata={}),n.metadata[r]=n.configurable[r]);if(n.timeout!==void 0){if(n.timeout<=0)throw new Error("Timeout must be a positive number");const r=AbortSignal.timeout(n.timeout);n.signal!==void 0?"any"in AbortSignal&&(n.signal=AbortSignal.any([n.signal,r])):n.signal=r,delete n.timeout}return n}function ne(e={},{callbacks:t,maxConcurrency:n,recursionLimit:r,runName:s,configurable:a,runId:i}={}){const o=K(e);return t!==void 0&&(delete o.runName,o.callbacks=t),r!==void 0&&(o.recursionLimit=r),n!==void 0&&(o.maxConcurrency=n),s!==void 0&&(o.runName=s),a!==void 0&&(o.configurable={...o.configurable,...a}),i!==void 0&&delete o.runId,o}function on(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}async function On(e,t){if(t===void 0)return e;let n;return Promise.race([e.catch(r=>{if(!t?.aborted)throw r}),new Promise((r,s)=>{n=()=>{s(Es(t))},t.addEventListener("abort",n),t.aborted&&s(Es(t))})]).finally(()=>t.removeEventListener("abort",n))}function Es(e){return e?.reason instanceof Error?e.reason:typeof e?.reason=="string"?new Error(e.reason):new Error("Aborted")}function ge(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_zod"in t))return!1;const n=t._zod;return typeof n=="object"&&n!==null&&"def"in n}function Se(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_def"in t)||"_zod"in t)return!1;const n=t._def;return typeof n=="object"&&n!=null&&"typeName"in n}function Mb(e){return ge(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Se(e)}function er(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(ge(e)||Se(e))}function cp(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function lp(e){return ge(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function Rb(e){return!!(cp(e)||lp(e))}async function tl(e,t){if(ge(e))try{return{success:!0,data:await nh(e,t)}}catch(n){return{success:!1,error:n}}if(Se(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function gi(e,t){if(ge(e))return await nh(e,t);if(Se(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function $b(e,t){if(ge(e))try{return{success:!0,data:Dc(e,t)}}catch(n){return{success:!1,error:n}}if(Se(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function bn(e,t){if(ge(e))return Dc(e,t);if(Se(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Vr(e){if(ge(e))return Re.get(e)?.description;if(Se(e)||"description"in e&&typeof e.description=="string")return e.description}function Lb(e){if(!er(e))return!1;if(Se(e)){const t=e._def;if(t.typeName==="ZodObject"){const n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(ge(e)){const t=e._zod.def;if(t.type==="object"){const n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function nl(e){return er(e)?Se(e)?e._def.typeName==="ZodString":ge(e)?e._zod.def.type==="string":!1:!1}function rl(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function Wt(e){return ge(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function yi(e){return ge(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function et(e){return!!(rl(e)||Wt(e))}function Cs(e){if(Se(e))return e.shape;if(ge(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function up(e,t){if(Se(e))return e.extend(t);if(ge(e))return r_(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function sl(e){if(Se(e))return e.partial();if(ge(e))return s_(jc,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function za(e,t=!1){if(Se(e))return e.strict();if(Wt(e)){const n=e._zod.def.shape;if(t)for(const[a,i]of Object.entries(e._zod.def.shape)){if(Wt(i)){const c=za(i,t);n[a]=c}else if(yi(i)){let c=i._zod.def.element;Wt(c)&&(c=za(c,t)),n[a]=An(i,{...i._zod.def,element:c})}else n[a]=i;const o=Re.get(i);o&&Re.add(n[a],o)}const r=An(e,{...e._zod.def,shape:n,catchall:a_(i_)}),s=Re.get(e);return s&&Re.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Bo(e,t=!1){if(rl(e))return e.passthrough();if(Wt(e)){const n=e._zod.def.shape;if(t)for(const[a,i]of Object.entries(e._zod.def.shape)){if(Wt(i)){const c=Bo(i,t);n[a]=c}else if(yi(i)){let c=i._zod.def.element;Wt(c)&&(c=Bo(c,t)),n[a]=An(i,{...i._zod.def,element:c})}else n[a]=i;const o=Re.get(i);o&&Re.add(n[a],o)}const r=An(e,{...e._zod.def,shape:n,catchall:o_(c_)}),s=Re.get(e);return s&&Re.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function _i(e){if(Se(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(ge(e))try{const t=Dc(e,void 0);return()=>t}catch{return}}function jb(e){return Se(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function Db(e){return ge(e)&&e._zod.def.type==="pipe"}function mr(e,t=!1){if(Se(e))return jb(e)?mr(e._def.schema,t):e;if(ge(e)){let n=e;if(Db(e)&&(n=mr(e._zod.def.in,t)),t){if(Wt(n)){const s=n._zod.def.shape;for(const[a,i]of Object.entries(n._zod.def.shape))s[a]=mr(i,t);n=An(n,{...n._zod.def,shape:s})}else if(yi(n)){const s=mr(n._zod.def.element,t);n=An(n,{...n._zod.def,element:s})}}const r=Re.get(e);return r&&Re.add(n,r),n}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function dp(e,t){if(Se(e)){const n=Cs(e),r={};for(const[s,a]of Object.entries(n))t(s,a)?r[s]=a.optional():r[s]=a;return e.extend(r)}if(ge(e)){const n=Cs(e),r={...e._zod.def.shape};for(const[i,o]of Object.entries(n))t(i,o)&&(r[i]=new jc({type:"optional",innerType:o}));const s=An(e,{...e._zod.def,shape:r}),a=Re.get(e);return a&&Re.add(s,a),s}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}const Ub=Symbol("Let zodToJsonSchema decide on which parser to use"),Fb={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Bb=e=>({...Fb,...e}),zb=e=>{const t=Bb(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},hp=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function st(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?hp(t,e.currentPath):t.join("/")}}function pp(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function se(e,t,n,r,s){e[t]=n,pp(e,t,r,s)}function Hb(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==R.ZodAny&&(n.items=Q(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&se(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&se(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(se(n,"minItems",e.exactLength.value,e.exactLength.message,t),se(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function Vb(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":t.target==="jsonSchema7"?r.inclusive?se(n,"minimum",r.value,r.message,t):se(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),se(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?se(n,"maximum",r.value,r.message,t):se(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),se(n,"maximum",r.value,r.message,t));break;case"multipleOf":se(n,"multipleOf",r.value,r.message,t);break}return n}function Gb(){return{type:"boolean"}}function fp(e,t){return Q(e.type._def,t)}const Wb=(e,t)=>Q(e.innerType._def,t);function mp(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(s=>mp(e,t,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Jb(e,t)}}const Jb=(e,t)=>{const n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(const r of e.checks)switch(r.kind){case"min":se(n,"minimum",r.value,r.message,t);break;case"max":se(n,"maximum",r.value,r.message,t);break}return n};function Kb(e,t){return{...Q(e.innerType._def,t),default:e.defaultValue()}}function Zb(e,t){return t.effectStrategy==="input"?Q(e.schema._def,t):st(t)}function qb(e){return{type:"string",enum:Array.from(e.values)}}const Yb=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function Xb(e,t){const n=[Q(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Q(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a);let r=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(a=>{if(Yb(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function Qb(e,t){const n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}let eo;const At={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(eo===void 0&&(eo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),eo),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function gp(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":se(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":se(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":kt(n,"email",r.message,t);break;case"format:idn-email":kt(n,"idn-email",r.message,t);break;case"pattern:zod":He(n,At.email,r.message,t);break}break;case"url":kt(n,"uri",r.message,t);break;case"uuid":kt(n,"uuid",r.message,t);break;case"regex":He(n,r.regex,r.message,t);break;case"cuid":He(n,At.cuid,r.message,t);break;case"cuid2":He(n,At.cuid2,r.message,t);break;case"startsWith":He(n,RegExp(`^${to(r.value,t)}`),r.message,t);break;case"endsWith":He(n,RegExp(`${to(r.value,t)}$`),r.message,t);break;case"datetime":kt(n,"date-time",r.message,t);break;case"date":kt(n,"date",r.message,t);break;case"time":kt(n,"time",r.message,t);break;case"duration":kt(n,"duration",r.message,t);break;case"length":se(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t),se(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":He(n,RegExp(to(r.value,t)),r.message,t);break;case"ip":r.version!=="v6"&&kt(n,"ipv4",r.message,t),r.version!=="v4"&&kt(n,"ipv6",r.message,t);break;case"base64url":He(n,At.base64url,r.message,t);break;case"jwt":He(n,At.jwt,r.message,t);break;case"cidr":r.version!=="v6"&&He(n,At.ipv4Cidr,r.message,t),r.version!=="v4"&&He(n,At.ipv6Cidr,r.message,t);break;case"emoji":He(n,At.emoji(),r.message,t);break;case"ulid":He(n,At.ulid,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":kt(n,"binary",r.message,t);break;case"contentEncoding:base64":se(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":He(n,At.base64,r.message,t);break}break;case"nanoid":He(n,At.nanoid,r.message,t);break}return n}function to(e,t){return t.patternStrategy==="escape"?t0(e):e}const e0=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function t0(e){let t="";for(let n=0;n<e.length;n++)e0.has(e[n])||(t+="\\"),t+=e[n];return t}function kt(e,t,n,r){e.format||e.anyOf?.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):se(e,"format",t,n,r)}function He(e,t,n,r){e.pattern||e.allOf?.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Du(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):se(e,"pattern",Du(t,r),n,r)}function Du(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,o=!1;for(let c=0;c<r.length;c++){if(a){s+=r[c],a=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){o?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),o=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],o=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){s+=`(^|(?<=[\r
59
59
  ]))`;continue}else if(r[c]==="$"){s+=`($|(?=[\r
60
60
  ]))`;continue}}if(n.s&&r[c]==="."){s+=i?`${r[c]}\r
61
61
  `:`[${r[c]}\r
62
- ]`;continue}s+=r[c],r[c]==="\\"?a=!0:i&&r[c]==="]"?i=!1:!i&&r[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function yp(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===R.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,s)=>({...r,[s]:Q(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??st(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:Q(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===R.ZodString&&e.keyType._def.checks?.length){const{type:r,...s}=gp(e.keyType._def,t);return{...n,propertyNames:s}}else{if(e.keyType?._def.typeName===R.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===R.ZodBranded&&e.keyType._def.type._def.typeName===R.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...s}=fp(e.keyType._def,t);return{...n,propertyNames:s}}}return n}function n0(e,t){if(t.mapStrategy==="record")return yp(e,t);const n=Q(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||st(t),r=Q(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||st(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function r0(e){const t=e.values,r=Object.keys(e.values).filter(a=>typeof t[t[a]]!="number").map(a=>t[a]),s=Array.from(new Set(r.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function s0(e){return e.target==="openAi"?void 0:{not:st({...e,currentPath:[...e.currentPath,"not"]})}}function a0(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ha={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function i0(e,t){if(t.target==="openApi3")return Uu(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Ha&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,a)=>{const i=Ha[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":return a._def.value===null?[...s,"null"]:s;case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===n.length){const s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return Uu(e,t)}const Uu=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,s)=>Q(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function o0(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Ha[e.innerType._def.typeName],nullable:!0}:{type:[Ha[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const r=Q(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=Q(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function c0(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",pp(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?se(n,"minimum",r.value,r.message,t):se(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),se(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?se(n,"maximum",r.value,r.message,t):se(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),se(n,"maximum",r.value,r.message,t));break;case"multipleOf":se(n,"multipleOf",r.value,r.message,t);break}return n}function l0(e,t){const n=t.target==="openAi",r={type:"object",properties:{}},s=[],a=e.shape();for(const o in a){let c=a[o];if(c===void 0||c._def===void 0)continue;let l=d0(c);l&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const u=Q(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});u!==void 0&&(r.properties[o]=u,l||s.push(o))}s.length&&(r.required=s);const i=u0(e,t);return i!==void 0&&(r.additionalProperties=i),r}function u0(e,t){if(e.catchall._def.typeName!=="ZodNever")return Q(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function d0(e){try{return e.isOptional()}catch{return!0}}const h0=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Q(e.innerType._def,t);const n=Q(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:st(t)},n]}:st(t)},p0=(e,t)=>{if(t.pipeStrategy==="input")return Q(e.in._def,t);if(t.pipeStrategy==="output")return Q(e.out._def,t);const n=Q(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=Q(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}};function f0(e,t){return Q(e.type._def,t)}function m0(e,t){const r={type:"array",uniqueItems:!0,items:Q(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&se(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&se(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function g0(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>Q(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Q(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>Q(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function y0(e){return{not:st(e)}}function _0(e){return st(e)}const w0=(e,t)=>Q(e.innerType._def,t),v0=(e,t,n)=>{switch(t){case R.ZodString:return gp(e,n);case R.ZodNumber:return c0(e,n);case R.ZodObject:return l0(e,n);case R.ZodBigInt:return Vb(e,n);case R.ZodBoolean:return Gb();case R.ZodDate:return mp(e,n);case R.ZodUndefined:return y0(n);case R.ZodNull:return a0(n);case R.ZodArray:return Hb(e,n);case R.ZodUnion:case R.ZodDiscriminatedUnion:return i0(e,n);case R.ZodIntersection:return Xb(e,n);case R.ZodTuple:return g0(e,n);case R.ZodRecord:return yp(e,n);case R.ZodLiteral:return Qb(e,n);case R.ZodEnum:return qb(e);case R.ZodNativeEnum:return r0(e);case R.ZodNullable:return o0(e,n);case R.ZodOptional:return h0(e,n);case R.ZodMap:return n0(e,n);case R.ZodSet:return m0(e,n);case R.ZodLazy:return()=>e.getter()._def;case R.ZodPromise:return f0(e,n);case R.ZodNaN:case R.ZodNever:return s0(n);case R.ZodEffects:return Zb(e,n);case R.ZodAny:return st(n);case R.ZodUnknown:return _0(n);case R.ZodDefault:return Kb(e,n);case R.ZodBranded:return fp(e,n);case R.ZodReadonly:return w0(e,n);case R.ZodCatch:return Wb(e,n);case R.ZodPipeline:return p0(e,n);case R.ZodFunction:case R.ZodVoid:case R.ZodSymbol:return;default:return(r=>{})()}};function Q(e,t,n=!1){const r=t.seen.get(e);if(t.override){const o=t.override?.(e,t,r,n);if(o!==Ub)return o}if(r&&!n){const o=b0(r,t);if(o!==void 0)return o}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=v0(e,e.typeName,t),i=typeof a=="function"?Q(a(),t):a;if(i&&S0(e,t,i),t.postProcess){const o=t.postProcess(i,e,t);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const b0=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:hp(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),st(t)):t.$refStrategy==="seen"?st(t):void 0}},S0=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),T0=(e,t)=>{const n=zb(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((o,[c,l])=>({...o,[c]:Q(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??st(n)}),{}):void 0;const s=typeof t=="string"?t:t?.name,a=Q(e._def,n,!1)??st(n);n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const i=s===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:a}};return n.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};var _p={};F(_p,{Validator:()=>Uc,deepCompareStrict:()=>rh,toJsonSchema:()=>ft,validatesOnlyStrings:()=>fs});function ft(e){if(ge(e)){const t=mr(e,!0);if(Wt(t)){const n=za(t,!0);return cu(n)}else return cu(e)}return Se(e)?T0(e):e}function fs(e){if(!e||typeof e!="object"||Object.keys(e).length===0||Array.isArray(e))return!1;if("type"in e)return typeof e.type=="string"?e.type==="string":Array.isArray(e.type)?e.type.every(t=>t==="string"):!1;if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(t=>typeof t=="string");if("const"in e)return typeof e.const=="string";if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(t=>fs(t));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){const t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(n=>fs(n))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){const t=e.$ref,n=u_(e);return n[t]?fs(n[t]):!1}return!1}var wp={};F(wp,{AsyncCaller:()=>Js});const E0=[400,401,402,403,404,405,406,407,409],C0=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e?.code==="ECONNABORTED")throw e;const t=e?.response?.status??e?.status;if(t&&E0.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){const n=new Error(e?.message);throw n.name="InsufficientQuotaError",n}};var Js=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??C0;const t="default"in tn?tn.default:tn;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>Da(()=>e(...t).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((r,s)=>{e.signal?.addEventListener("abort",()=>{s(Es(e.signal))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}},vp={};F(vp,{AsyncGeneratorWithSetup:()=>Mn,IterableReadableStream:()=>Fe,atee:()=>al,concat:()=>xn,pipeGeneratorWithSetup:()=>bp});var Fe=class zo extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){const t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){const n=this.reader.cancel();this.reader.releaseLock(),await n}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){const n=t.getReader();return new zo({start(r){return s();function s(){return n.read().then(({done:a,value:i})=>{if(a){r.close();return}return r.enqueue(i),s()})}},cancel(){n.releaseLock()}})}static fromAsyncGenerator(t){return new zo({async pull(n){const{value:r,done:s}=await t.next();s&&n.close(),n.enqueue(r)},async cancel(n){await t.return(n)}})}};function al(e,t=2){const n=Array.from({length:t},()=>[]);return n.map(async function*(s){for(;;)if(s.length===0){const a=await e.next();for(const i of n)i.push(a)}else{if(s[0].done)return;yield s.shift().value}})}function xn(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e=="string"&&typeof t=="string")return e+t;if(typeof e=="number"&&typeof t=="number")return e+t;if("concat"in e&&typeof e.concat=="function")return e.concat(t);if(typeof e=="object"&&typeof t=="object"){const n={...e};for(const[r,s]of Object.entries(t))r in n&&!Array.isArray(n[r])?n[r]=xn(n[r],s):n[r]=s;return n}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var Mn=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,n)=>{me.runWithConfig(on(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,n):this.firstResult.then(r=>t(void 0),n)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?me.runWithConfig(on(this.config),this.signal?async()=>On(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function bp(e,t,n,r,...s){const a=new Mn({generator:t,startSetup:n,signal:r}),i=await a.setup;return{output:e(a,i,...s),setup:i}}/*!
62
+ ]`;continue}s+=r[c],r[c]==="\\"?a=!0:i&&r[c]==="]"?i=!1:!i&&r[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function yp(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===R.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,s)=>({...r,[s]:Q(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??st(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:Q(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===R.ZodString&&e.keyType._def.checks?.length){const{type:r,...s}=gp(e.keyType._def,t);return{...n,propertyNames:s}}else{if(e.keyType?._def.typeName===R.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===R.ZodBranded&&e.keyType._def.type._def.typeName===R.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...s}=fp(e.keyType._def,t);return{...n,propertyNames:s}}}return n}function n0(e,t){if(t.mapStrategy==="record")return yp(e,t);const n=Q(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||st(t),r=Q(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||st(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function r0(e){const t=e.values,r=Object.keys(e.values).filter(a=>typeof t[t[a]]!="number").map(a=>t[a]),s=Array.from(new Set(r.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function s0(e){return e.target==="openAi"?void 0:{not:st({...e,currentPath:[...e.currentPath,"not"]})}}function a0(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ha={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function i0(e,t){if(t.target==="openApi3")return Uu(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Ha&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,a)=>{const i=Ha[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":return a._def.value===null?[...s,"null"]:s;case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===n.length){const s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return Uu(e,t)}const Uu=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,s)=>Q(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function o0(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Ha[e.innerType._def.typeName],nullable:!0}:{type:[Ha[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const r=Q(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=Q(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function c0(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",pp(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?se(n,"minimum",r.value,r.message,t):se(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),se(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?se(n,"maximum",r.value,r.message,t):se(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),se(n,"maximum",r.value,r.message,t));break;case"multipleOf":se(n,"multipleOf",r.value,r.message,t);break}return n}function l0(e,t){const n=t.target==="openAi",r={type:"object",properties:{}},s=[],a=e.shape();for(const o in a){let c=a[o];if(c===void 0||c._def===void 0)continue;let l=d0(c);l&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const u=Q(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});u!==void 0&&(r.properties[o]=u,l||s.push(o))}s.length&&(r.required=s);const i=u0(e,t);return i!==void 0&&(r.additionalProperties=i),r}function u0(e,t){if(e.catchall._def.typeName!=="ZodNever")return Q(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function d0(e){try{return e.isOptional()}catch{return!0}}const h0=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Q(e.innerType._def,t);const n=Q(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:st(t)},n]}:st(t)},p0=(e,t)=>{if(t.pipeStrategy==="input")return Q(e.in._def,t);if(t.pipeStrategy==="output")return Q(e.out._def,t);const n=Q(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=Q(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}};function f0(e,t){return Q(e.type._def,t)}function m0(e,t){const r={type:"array",uniqueItems:!0,items:Q(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&se(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&se(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function g0(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>Q(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Q(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>Q(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function y0(e){return{not:st(e)}}function _0(e){return st(e)}const w0=(e,t)=>Q(e.innerType._def,t),v0=(e,t,n)=>{switch(t){case R.ZodString:return gp(e,n);case R.ZodNumber:return c0(e,n);case R.ZodObject:return l0(e,n);case R.ZodBigInt:return Vb(e,n);case R.ZodBoolean:return Gb();case R.ZodDate:return mp(e,n);case R.ZodUndefined:return y0(n);case R.ZodNull:return a0(n);case R.ZodArray:return Hb(e,n);case R.ZodUnion:case R.ZodDiscriminatedUnion:return i0(e,n);case R.ZodIntersection:return Xb(e,n);case R.ZodTuple:return g0(e,n);case R.ZodRecord:return yp(e,n);case R.ZodLiteral:return Qb(e,n);case R.ZodEnum:return qb(e);case R.ZodNativeEnum:return r0(e);case R.ZodNullable:return o0(e,n);case R.ZodOptional:return h0(e,n);case R.ZodMap:return n0(e,n);case R.ZodSet:return m0(e,n);case R.ZodLazy:return()=>e.getter()._def;case R.ZodPromise:return f0(e,n);case R.ZodNaN:case R.ZodNever:return s0(n);case R.ZodEffects:return Zb(e,n);case R.ZodAny:return st(n);case R.ZodUnknown:return _0(n);case R.ZodDefault:return Kb(e,n);case R.ZodBranded:return fp(e,n);case R.ZodReadonly:return w0(e,n);case R.ZodCatch:return Wb(e,n);case R.ZodPipeline:return p0(e,n);case R.ZodFunction:case R.ZodVoid:case R.ZodSymbol:return;default:return(r=>{})()}};function Q(e,t,n=!1){const r=t.seen.get(e);if(t.override){const o=t.override?.(e,t,r,n);if(o!==Ub)return o}if(r&&!n){const o=b0(r,t);if(o!==void 0)return o}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=v0(e,e.typeName,t),i=typeof a=="function"?Q(a(),t):a;if(i&&S0(e,t,i),t.postProcess){const o=t.postProcess(i,e,t);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const b0=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:hp(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),st(t)):t.$refStrategy==="seen"?st(t):void 0}},S0=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),T0=(e,t)=>{const n=zb(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((o,[c,l])=>({...o,[c]:Q(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??st(n)}),{}):void 0;const s=typeof t=="string"?t:t?.name,a=Q(e._def,n,!1)??st(n);n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const i=s===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:a}};return n.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};var _p={};F(_p,{Validator:()=>Uc,deepCompareStrict:()=>rh,toJsonSchema:()=>ft,validatesOnlyStrings:()=>fs});function ft(e){if(ge(e)){const t=mr(e,!0);if(Wt(t)){const n=za(t,!0);return ou(n)}else return ou(e)}return Se(e)?T0(e):e}function fs(e){if(!e||typeof e!="object"||Object.keys(e).length===0||Array.isArray(e))return!1;if("type"in e)return typeof e.type=="string"?e.type==="string":Array.isArray(e.type)?e.type.every(t=>t==="string"):!1;if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(t=>typeof t=="string");if("const"in e)return typeof e.const=="string";if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(t=>fs(t));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){const t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(n=>fs(n))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){const t=e.$ref,n=l_(e);return n[t]?fs(n[t]):!1}return!1}var wp={};F(wp,{AsyncCaller:()=>Js});const E0=[400,401,402,403,404,405,406,407,409],C0=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e?.code==="ECONNABORTED")throw e;const t=e?.response?.status??e?.status;if(t&&E0.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){const n=new Error(e?.message);throw n.name="InsufficientQuotaError",n}};var Js=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??C0;const t="default"in tn?tn.default:tn;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>ja(()=>e(...t).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((r,s)=>{e.signal?.addEventListener("abort",()=>{s(Es(e.signal))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}},vp={};F(vp,{AsyncGeneratorWithSetup:()=>Mn,IterableReadableStream:()=>Fe,atee:()=>al,concat:()=>xn,pipeGeneratorWithSetup:()=>bp});var Fe=class zo extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){const t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){const n=this.reader.cancel();this.reader.releaseLock(),await n}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){const n=t.getReader();return new zo({start(r){return s();function s(){return n.read().then(({done:a,value:i})=>{if(a){r.close();return}return r.enqueue(i),s()})}},cancel(){n.releaseLock()}})}static fromAsyncGenerator(t){return new zo({async pull(n){const{value:r,done:s}=await t.next();s&&n.close(),n.enqueue(r)},async cancel(n){await t.return(n)}})}};function al(e,t=2){const n=Array.from({length:t},()=>[]);return n.map(async function*(s){for(;;)if(s.length===0){const a=await e.next();for(const i of n)i.push(a)}else{if(s[0].done)return;yield s.shift().value}})}function xn(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e=="string"&&typeof t=="string")return e+t;if(typeof e=="number"&&typeof t=="number")return e+t;if("concat"in e&&typeof e.concat=="function")return e.concat(t);if(typeof e=="object"&&typeof t=="object"){const n={...e};for(const[r,s]of Object.entries(t))r in n&&!Array.isArray(n[r])?n[r]=xn(n[r],s):n[r]=s;return n}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var Mn=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,n)=>{me.runWithConfig(on(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,n):this.firstResult.then(r=>t(void 0),n)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?me.runWithConfig(on(this.config),this.signal?async()=>On(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function bp(e,t,n,r,...s){const a=new Mn({generator:t,startSetup:n,signal:r}),i=await a.setup;return{output:e(a,i,...s),setup:i}}/*!
63
63
  * https://github.com/Starcounter-Jack/JSON-Patch
64
64
  * (c) 2017-2022 Joachim Wester
65
65
  * MIT licensed
@@ -79,11 +79,11 @@ data: ${JSON.stringify(s)}
79
79
 
80
80
  `));r.enqueue(t.encode(`event: end
81
81
 
82
- `)),r.close()}});return Fe.fromReadableStream(n)}function Gu(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}const H0=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function";function Zo(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function*Wu(e,t){for(;;){const{value:n,done:r}=me.runWithConfig(on(e),t.next.bind(t),!0);if(r)break;yield n}}async function*qo(e,t){const n=t[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await me.runWithConfig(on(e),n.next.bind(t),!0);if(s)break;yield r}}function Ae(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}var J=class extends Tt{lc_runnable=!0;name;getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new cl({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new De({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new Dp({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(K);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const n=Object.fromEntries(Object.entries(e).filter(([r])=>r!=="runId"));return Array.from({length:t},(r,s)=>K(s===0?e:n))}return Array.from({length:t},()=>K(e))}async batch(e,t,n){const r=this._getOptionsList(t??{},e.length),s=r[0]?.maxConcurrency??n?.maxConcurrency,a=new Js({maxConcurrency:s,onFailedAttempt:o=>{throw o}}),i=e.map((o,c)=>a.call(async()=>{try{return await this.invoke(o,r[c])}catch(l){if(n?.returnExceptions)return l;throw l}}));return Promise.all(i)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const n=K(t),r=new Mn({generator:this._streamIterator(e,n),config:n});return await r.setup,Fe.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=K(e):t=K({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){const r=K(n),a=await(await nt(r))?.handleChainStart(this.toJSON(),Ae(t,"input"),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName());delete r.runId;let i;try{const o=e.call(this,t,r,a);i=await On(o,n?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(Ae(i,"output")),i}async _batchWithConfig(e,t,n,r){const s=this._getOptionsList(n??{},t.length),a=await Promise.all(s.map(nt)),i=await Promise.all(a.map(async(c,l)=>{const u=await c?.handleChainStart(this.toJSON(),Ae(t[l],"input"),s[l].runId,s[l].runType,void 0,void 0,s[l].runName??this.getName());return delete s[l].runId,u}));let o;try{const c=e.call(this,t,s,i,r);o=await On(c,s?.[0]?.signal)}catch(c){throw await Promise.all(i.map(l=>l?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(Ae(o,"output")))),o}_concatOutputChunks(e,t){return xn(e,t)}async*_transformStreamWithConfig(e,t,n){let r,s=!0,a,i=!0;const o=K(n),c=await nt(o),l=this;async function*u(){for await(const h of e){if(s)if(r===void 0)r=h;else try{r=l._concatOutputChunks(r,h)}catch{r=void 0,s=!1}yield h}}let d;try{const h=await bp(t.bind(this),u(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),n?.signal,o);delete o.runId,d=h.setup;const p=d?.handlers.find(M0);let f=h.output;p!==void 0&&d!==void 0&&(f=p.tapOutputIterable(d.runId,f));const y=d?.handlers.find(Ap);y!==void 0&&d!==void 0&&(f=y.tapOutputIterable(d.runId,f));for await(const S of f)if(yield S,i)if(a===void 0)a=S;else try{a=this._concatOutputChunks(a,S)}catch{a=void 0,i=!1}}catch(h){throw await d?.handleChainError(h,void 0,void 0,void 0,{inputs:Ae(r,"input")}),h}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:Ae(r,"input")})}getGraph(e){const t=new Os,n=t.addNode({name:`${this.getName()}Input`,schema:ht()}),r=t.addNode(this),s=t.addNode({name:`${this.getName()}Output`,schema:ht()});return t.addEdge(n,r),t.addEdge(r,s),t}pipe(e){return new Et({first:this,last:$e(e)})}pick(e){return this.pipe(new Up(e))}assign(e){return this.pipe(new ll(new ts({steps:e})))}async*transform(e,t){let n;for await(const r of e)n===void 0?n=r:n=this._concatOutputChunks(n,r);yield*this._streamIterator(n,K(t))}async*streamLog(e,t,n){const r=new Ko({...n,autoClose:!1,_schemaFormat:"original"}),s=K(t);yield*this._streamLog(e,r,s)}async*_streamLog(e,t,n){const{callbacks:r}=n;if(r===void 0)n.callbacks=[t];else if(Array.isArray(r))n.callbacks=r.concat([t]);else{const o=r.copy();o.addHandler(t,!0),n.callbacks=o}const s=this.stream(e,n);async function a(){try{const o=await s;for await(const c of o){const l=new qt({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}const i=a();try{for await(const o of t)yield o}finally{await i}}streamEvents(e,t,n){let r;if(t.version==="v1")r=this._streamEventsV1(e,t,n);else if(t.version==="v2")r=this._streamEventsV2(e,t,n);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?z0(r):Fe.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){const r=new R0({...n,autoClose:!1}),s=K(t),a=s.runId??Ce();s.runId=a;const i=s.callbacks;if(i===void 0)s.callbacks=[r];else if(Array.isArray(i))s.callbacks=i.concat(r);else{const p=i.copy();p.addHandler(r,!0),s.callbacks=p}const o=new AbortController,c=this;async function l(){let p,f=null;try{t?.signal?"any"in AbortSignal?p=AbortSignal.any([o.signal,t.signal]):(p=t.signal,f=()=>{o.abort()},t.signal.addEventListener("abort",f,{once:!0})):p=o.signal;const y=await c.stream(e,{...s,signal:p}),S=r.tapOutputIterable(a,y);for await(const b of S)if(o.signal.aborted)break}finally{await r.finish(),p&&f&&p.removeEventListener("abort",f)}}const u=l();let d=!1,h;try{for await(const p of r){if(!d){p.data.input=e,d=!0,h=p.run_id,yield p;continue}p.run_id===h&&p.event.endsWith("_end")&&p.data?.input&&delete p.data.input,yield p}}finally{o.abort(),await u}}async*_streamEventsV1(e,t,n){let r,s=!1;const a=K(t),i=a.tags??[],o=a.metadata??{},c=a.runName??this.getName(),l=new Ko({...n,autoClose:!1,_schemaFormat:"streaming_events"}),u=new $0({...n}),d=this._streamLog(e,l,a);for await(const p of d){if(r?r=r.concat(p):r=il.fromRunLogPatch(p),r.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!s){s=!0;const b={...r.state},v={run_id:b.id,event:`on_${b.type}_start`,name:c,tags:i,metadata:o,data:{input:e}};u.includeEvent(v,b.type)&&(yield v)}const f=p.ops.filter(b=>b.path.startsWith("/logs/")).map(b=>b.path.split("/")[2]),y=[...new Set(f)];for(const b of y){let v,w={};const E=r.state.logs[b];if(E.end_time===void 0?E.streamed_output.length>0?v="stream":v="start":v="end",v==="start")E.inputs!==void 0&&(w.input=E.inputs);else if(v==="end")E.inputs!==void 0&&(w.input=E.inputs),w.output=E.final_output;else if(v==="stream"){const A=E.streamed_output.length;if(A!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${A} instead. Encountered in: "${E.name}"`);w={chunk:E.streamed_output[0]},E.streamed_output=[]}yield{event:`on_${E.type}_${v}`,name:E.name,run_id:E.id,tags:E.tags,metadata:E.metadata,data:w}}const{state:S}=r;if(S.streamed_output.length>0){const b=S.streamed_output.length;if(b!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${b} instead. Encountered in: "${S.name}"`);const v={chunk:S.streamed_output[0]};S.streamed_output=[];const w={event:`on_${S.type}_stream`,run_id:S.id,tags:i,metadata:o,name:c,data:v};u.includeEvent(w,S.type)&&(yield w)}}const h=r?.state;if(h!==void 0){const p={event:`on_${h.type}_end`,name:c,run_id:h.id,tags:i,metadata:o,data:{output:h.final_output}};u.includeEvent(p,h.type)&&(yield p)}}static isRunnable(e){return ol(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new De({bound:this,config:{},configFactories:[r=>({callbacks:[new Ip({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return K0(this,e)}},De=class Mp extends J{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(t){super(t),this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){const n=pt(this.config,...t);return pt(n,...this.configFactories?await Promise.all(this.configFactories.map(async r=>await r(n))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new cl({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t?.stopAfterAttempt,...t})}async invoke(t,n){return this.bound.invoke(t,await this._mergeConfig(n,this.kwargs))}async batch(t,n,r){const s=Array.isArray(n)?await Promise.all(n.map(async a=>this._mergeConfig(K(a),this.kwargs))):await this._mergeConfig(K(n),this.kwargs);return this.bound.batch(t,s,r)}_concatOutputChunks(t,n){return this.bound._concatOutputChunks(t,n)}async*_streamIterator(t,n){yield*this.bound._streamIterator(t,await this._mergeConfig(K(n),this.kwargs))}async stream(t,n){return this.bound.stream(t,await this._mergeConfig(K(n),this.kwargs))}async*transform(t,n){yield*this.bound.transform(t,await this._mergeConfig(K(n),this.kwargs))}streamEvents(t,n,r){const s=this,a=async function*(){yield*s.bound.streamEvents(t,{...await s._mergeConfig(K(n),s.kwargs),version:n.version},r)};return Fe.fromAsyncGenerator(a())}static isRunnableBinding(t){return t.bound&&J.isRunnable(t.bound)}withListeners({onStart:t,onEnd:n,onError:r}){return new Mp({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[s=>({callbacks:[new Ip({config:s,onStart:t,onEnd:n,onError:r})]})]})}},V0=class Rp extends J{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(t){super(t),this.bound=t.bound}async invoke(t,n){return this._callWithConfig(this._invoke.bind(this),t,n)}async _invoke(t,n,r){return this.bound.batch(t,ne(n,{callbacks:r?.getChild()}))}withListeners({onStart:t,onEnd:n,onError:r}){return new Rp({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:r})})}},cl=class extends De{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){const r=e>1?`retry:attempt:${e}`:void 0;return ne(t,{callbacks:n?.getChild(r)})}async _invoke(e,t,n){return Da(r=>super.invoke(e,this._patchConfigForRetry(r,t,n)),{onFailedAttempt:r=>this.onFailedAttempt(r,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,n,r){const s={};try{await Da(async a=>{const i=e.map((d,h)=>h).filter(d=>s[d.toString()]===void 0||s[d.toString()]instanceof Error),o=i.map(d=>e[d]),c=i.map(d=>this._patchConfigForRetry(a,t?.[d],n?.[d])),l=await super.batch(o,c,{...r,returnExceptions:!0});let u;for(let d=0;d<l.length;d+=1){const h=l[d],p=i[d];h instanceof Error&&u===void 0&&(u=h,u.input=o[d]),s[p.toString()]=h}if(u)throw u;return l},{onFailedAttempt:a=>this.onFailedAttempt(a,a.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(a){if(r?.returnExceptions!==!0)throw a}return Object.keys(s).sort((a,i)=>parseInt(a,10)-parseInt(i,10)).map(a=>s[parseInt(a,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},Et=class cs extends J{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(t){super(t),this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,n){const r=K(n),a=await(await nt(r))?.handleChainStart(this.toJSON(),Ae(t,"input"),r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let i=t,o;try{const c=[this.first,...this.middle];for(let l=0;l<c.length;l+=1){const d=c[l].invoke(i,ne(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${l+1}`)}));i=await On(d,n?.signal)}if(n?.signal?.aborted)throw Es(n.signal);o=await this.last.invoke(i,ne(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await a?.handleChainError(c),c}return await a?.handleChainEnd(Ae(o,"output")),o}async batch(t,n,r){const s=this._getOptionsList(n??{},t.length),a=await Promise.all(s.map(nt)),i=await Promise.all(a.map(async(c,l)=>{const u=await c?.handleChainStart(this.toJSON(),Ae(t[l],"input"),s[l].runId,void 0,void 0,void 0,s[l].runName);return delete s[l].runId,u}));let o=t;try{for(let c=0;c<this.steps.length;c+=1){const u=this.steps[c].batch(o,i.map((d,h)=>{const p=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return ne(s[h],{callbacks:p})}),r);o=await On(u,s[0]?.signal)}}catch(c){throw await Promise.all(i.map(l=>l?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(Ae(o,"output")))),o}_concatOutputChunks(t,n){return this.last._concatOutputChunks(t,n)}async*_streamIterator(t,n){const r=await nt(n),{runId:s,...a}=n??{},i=await r?.handleChainStart(this.toJSON(),Ae(t,"input"),s,void 0,void 0,void 0,a?.runName),o=[this.first,...this.middle,this.last];let c=!0,l;async function*u(){yield t}try{let d=o[0].transform(u(),ne(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let h=1;h<o.length;h+=1)d=await o[h].transform(d,ne(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${h+1}`)}));for await(const h of d)if(n?.signal?.throwIfAborted(),yield h,c)if(l===void 0)l=h;else try{l=this._concatOutputChunks(l,h)}catch{l=void 0,c=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(Ae(l,"output"))}getGraph(t){const n=new Os;let r=null;return this.steps.forEach((s,a)=>{const i=s.getGraph(t);a!==0&&i.trimFirstNode(),a!==this.steps.length-1&&i.trimLastNode(),n.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${s} has no first node`);r&&n.addEdge(r,o),r=i.lastNode()}),n}pipe(t){return cs.isRunnableSequence(t)?new cs({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new cs({first:this.first,middle:[...this.middle,this.last],last:$e(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&J.isRunnable(t)}static from([t,...n],r){let s={};return typeof r=="string"?s.name=r:r!==void 0&&(s=r),new cs({...s,first:$e(t),middle:n.slice(0,-1).map($e),last:$e(n[n.length-1])})}},ts=class $p extends J{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(t){super(t),this.steps={};for(const[n,r]of Object.entries(t.steps))this.steps[n]=$e(r)}static from(t){return new $p({steps:t})}async invoke(t,n){const r=K(n),a=await(await nt(r))?.handleChainStart(this.toJSON(),{input:t},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;const i={};try{const o=Object.entries(this.steps).map(async([c,l])=>{i[c]=await l.invoke(t,ne(r,{callbacks:a?.getChild(`map:key:${c}`)}))});await On(Promise.all(o),n?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(i),i}async*_transform(t,n,r){const s={...this.steps},a=al(t,Object.keys(s).length),i=new Map(Object.entries(s).map(([o,c],l)=>{const u=c.transform(a[l],ne(r,{callbacks:n?.getChild(`map:key:${o}`)}));return[o,u.next().then(d=>({key:o,gen:u,result:d}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:c,result:l,gen:u}=await On(o,r?.signal);i.delete(c),l.done||(yield{[c]:l.value},i.set(c,u.next().then(d=>({key:c,gen:u,result:d}))))}}transform(t,n){return this._transformStreamWithConfig(t,this._transform.bind(this),n)}async stream(t,n){async function*r(){yield t}const s=K(n),a=new Mn({generator:this.transform(r(),s),config:s});return await a.setup,Fe.fromAsyncGenerator(a)}},G0=class Lp extends J{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(t){if(super(t),!Qc(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,n){const[r]=this._getOptionsList(n??{},1),s=await nt(r),a=this.func(ne(r,{callbacks:s}),t);return On(a,r?.signal)}async*_streamIterator(t,n){const[r]=this._getOptionsList(n??{},1),s=await this.invoke(t,n);if(Zo(s)){for await(const a of s)r?.signal?.throwIfAborted(),yield a;return}if(H0(s)){for(;;){r?.signal?.throwIfAborted();const a=s.next();if(a.done)break;yield a.value}return}yield s}static from(t){return new Lp({func:t})}};function W0(e){if(Qc(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var at=class jp extends J{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(t){if(Qc(t.func))return G0.from(t.func);super(t),W0(t.func),this.func=t.func}static from(t){return new jp({func:t})}async _invoke(t,n,r){return new Promise((s,a)=>{const i=ne(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??Qi)-1});me.runWithConfig(on(i),async()=>{try{let o=await this.func(t,{...i});if(o&&J.isRunnable(o)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(t,{...i,recursionLimit:(i.recursionLimit??Qi)-1})}else if(Zo(o)){let c;for await(const l of qo(i,o))if(n?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}else if(Gu(o)){let c;for(const l of Wu(i,o))if(n?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}s(o)}catch(o){a(o)}})})}async invoke(t,n){return this._callWithConfig(this._invoke.bind(this),t,n)}async*_transform(t,n,r){let s;for await(const o of t)if(s===void 0)s=o;else try{s=this._concatOutputChunks(s,o)}catch{s=o}const a=ne(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??Qi)-1}),i=await new Promise((o,c)=>{me.runWithConfig(on(a),async()=>{try{const l=await this.func(s,{...a,config:a});o(l)}catch(l){c(l)}})});if(i&&J.isRunnable(i)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await i.stream(s,a);for await(const c of o)yield c}else if(Zo(i))for await(const o of qo(a,i))r?.signal?.throwIfAborted(),yield o;else if(Gu(i))for(const o of Wu(a,i))r?.signal?.throwIfAborted(),yield o;else yield i}transform(t,n){return this._transformStreamWithConfig(t,this._transform.bind(this),n)}async stream(t,n){async function*r(){yield t}const s=K(n),a=new Mn({generator:this.transform(r(),s),config:s});return await a.setup,Fe.fromAsyncGenerator(a)}},J0=class extends ts{},Dp=class extends J{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const n=K(t),r=await nt(n),{runId:s,...a}=n,i=await r?.handleChainStart(this.toJSON(),Ae(e,"input"),s,void 0,void 0,void 0,a?.runName),o=ne(a,{callbacks:i?.getChild()});return await me.runWithConfig(o,async()=>{let l;for(const u of this.runnables()){n?.signal?.throwIfAborted();try{const d=await u.invoke(e,o);return await i?.handleChainEnd(Ae(d,"output")),d}catch(d){l===void 0&&(l=d)}}throw l===void 0?new Error("No error stored at end of fallback."):(await i?.handleChainError(l),l)})}async*_streamIterator(e,t){const n=K(t),r=await nt(n),{runId:s,...a}=n,i=await r?.handleChainStart(this.toJSON(),Ae(e,"input"),s,void 0,void 0,void 0,a?.runName);let o,c;for(const u of this.runnables()){n?.signal?.throwIfAborted();const d=ne(a,{callbacks:i?.getChild()});try{const h=await u.stream(e,d);c=qo(d,h);break}catch(h){o===void 0&&(o=h)}}if(c===void 0){const u=o??new Error("No error stored at end of fallback.");throw await i?.handleChainError(u),u}let l;try{for await(const u of c){yield u;try{l=l===void 0?l:this._concatOutputChunks(l,u)}catch{l=void 0}}}catch(u){throw await i?.handleChainError(u),u}await i?.handleChainEnd(Ae(l,"output"))}async batch(e,t,n){if(n?.returnExceptions)throw new Error("Not implemented.");const r=this._getOptionsList(t??{},e.length),s=await Promise.all(r.map(o=>nt(o))),a=await Promise.all(s.map(async(o,c)=>{const l=await o?.handleChainStart(this.toJSON(),Ae(e[c],"input"),r[c].runId,void 0,void 0,void 0,r[c].runName);return delete r[c].runId,l}));let i;for(const o of this.runnables()){r[0].signal?.throwIfAborted();try{const c=await o.batch(e,a.map((l,u)=>ne(r[u],{callbacks:l?.getChild()})),n);return await Promise.all(a.map((l,u)=>l?.handleChainEnd(Ae(c[u],"output")))),c}catch(c){i===void 0&&(i=c)}}throw i?(await Promise.all(a.map(o=>o?.handleChainError(i))),i):new Error("No error stored at end of fallbacks.")}};function $e(e){if(typeof e=="function")return new at({func:e});if(J.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=$e(r);return new ts({steps:t})}else throw new Error(`Expected a Runnable, function or object.
83
- Instead got an unsupported type.`)}var ll=class extends J{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof ts&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){const n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){const r=this.mapper.getStepsKeys(),[s,a]=al(e),i=this.mapper.transform(a,ne(n,{callbacks:t?.getChild()})),o=i.next();for await(const c of s){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const l=Object.fromEntries(Object.entries(c).filter(([u])=>!r.includes(u)));Object.keys(l).length>0&&(yield l)}yield(await o).value;for await(const c of i)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const r=K(t),s=new Mn({generator:this.transform(n(),r),config:r});return await s.setup,Fe.fromAsyncGenerator(s)}},Up=class extends J{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const t=this.keys.map(n=>[n,e[n]]).filter(n=>n[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const n=await this._pick(t);n!==void 0&&(yield n)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const r=K(t),s=new Mn({generator:this.transform(n(),r),config:r});return await s.setup,Fe.fromAsyncGenerator(s)}},Yo=class extends De{name;description;schema;constructor(e){const t=Et.from([at.from(async n=>{let r;if(ps(n))try{r=await gi(this.schema,n.args)}catch{throw new Ss("Received tool input did not match expected schema",JSON.stringify(n.args))}else r=n;return r}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function K0(e,t){const n=t.name??e.getName(),r=t.description??Vr(t.schema);return nl(t.schema)?new Yo({name:n,description:r,schema:te({input:Oe()}).transform(s=>s.input),bound:e}):new Yo({name:n,description:r,schema:t.schema,bound:e})}var Fp={};F(Fp,{BasePromptValue:()=>vi,ChatPromptValue:()=>dl,ImagePromptValue:()=>Bp,StringPromptValue:()=>ul});var vi=class extends Tt{},ul=class extends vi{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 ue(this.value)]}},dl=class extends vi{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 Zc(this.messages)}toChatMessages(){return this.messages}},Bp=class extends vi{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 ue({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},L="0123456789abcdef".split(""),Z0=[-2147483648,8388608,32768,128],Ot=[24,16,8,0],ca=[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],xe=[];function jt(e,t){t?(xe[0]=xe[16]=xe[1]=xe[2]=xe[3]=xe[4]=xe[5]=xe[6]=xe[7]=xe[8]=xe[9]=xe[10]=xe[11]=xe[12]=xe[13]=xe[14]=xe[15]=0,this.blocks=xe):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}jt.prototype.update=function(e){if(!this.finalized){var t,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);t=!0}for(var r,s=0,a,i=e.length,o=this.blocks;s<i;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),t)for(a=this.start;s<i&&a<64;++s)o[a>>>2]|=e[s]<<Ot[a++&3];else for(a=this.start;s<i&&a<64;++s)r=e.charCodeAt(s),r<128?o[a>>>2]|=r<<Ot[a++&3]:r<2048?(o[a>>>2]|=(192|r>>>6)<<Ot[a++&3],o[a>>>2]|=(128|r&63)<<Ot[a++&3]):r<55296||r>=57344?(o[a>>>2]|=(224|r>>>12)<<Ot[a++&3],o[a>>>2]|=(128|r>>>6&63)<<Ot[a++&3],o[a>>>2]|=(128|r&63)<<Ot[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++s)&1023),o[a>>>2]|=(240|r>>>18)<<Ot[a++&3],o[a>>>2]|=(128|r>>>12&63)<<Ot[a++&3],o[a>>>2]|=(128|r>>>6&63)<<Ot[a++&3],o[a>>>2]|=(128|r&63)<<Ot[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=o[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};jt.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=Z0[t&3],this.block=e[16],t>=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()}};jt.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=this.blocks,l,u,d,h,p,f,y,S,b,v,w;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(w=t&n,l=0;l<64;l+=4)this.first?(this.is224?(S=300032,p=c[0]-1413257819,o=p-150054599<<0,r=p+24177077<<0):(S=704751109,p=c[0]-210244248,o=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),S=e&t,h=S^e&n^w,y=s&a^~s&i,p=o+d+y+ca[l]+c[l],f=u+h,o=r+p<<0,r=p+f<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),b=r&e,h=b^r&t^S,y=i&o^~i&s,p=a+d+y+ca[l+1]+c[l+1],f=u+h,i=n+p<<0,n=p+f<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),v=n&r,h=v^n&e^b,y=a&i^~a&o,p=s+d+y+ca[l+2]+c[l+2],f=u+h,a=t+p<<0,t=p+f<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),w=t&n,h=w^t&r^v,y=a&i^~a&o,p=s+d+y+ca[l+3]+c[l+3],f=u+h,s=e+p<<0,e=p+f<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+s<<0,this.h5=this.h5+a<<0,this.h6=this.h6+i<<0,this.h7=this.h7+o<<0};jt.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=L[e>>>28&15]+L[e>>>24&15]+L[e>>>20&15]+L[e>>>16&15]+L[e>>>12&15]+L[e>>>8&15]+L[e>>>4&15]+L[e&15]+L[t>>>28&15]+L[t>>>24&15]+L[t>>>20&15]+L[t>>>16&15]+L[t>>>12&15]+L[t>>>8&15]+L[t>>>4&15]+L[t&15]+L[n>>>28&15]+L[n>>>24&15]+L[n>>>20&15]+L[n>>>16&15]+L[n>>>12&15]+L[n>>>8&15]+L[n>>>4&15]+L[n&15]+L[r>>>28&15]+L[r>>>24&15]+L[r>>>20&15]+L[r>>>16&15]+L[r>>>12&15]+L[r>>>8&15]+L[r>>>4&15]+L[r&15]+L[s>>>28&15]+L[s>>>24&15]+L[s>>>20&15]+L[s>>>16&15]+L[s>>>12&15]+L[s>>>8&15]+L[s>>>4&15]+L[s&15]+L[a>>>28&15]+L[a>>>24&15]+L[a>>>20&15]+L[a>>>16&15]+L[a>>>12&15]+L[a>>>8&15]+L[a>>>4&15]+L[a&15]+L[i>>>28&15]+L[i>>>24&15]+L[i>>>20&15]+L[i>>>16&15]+L[i>>>12&15]+L[i>>>8&15]+L[i>>>4&15]+L[i&15];return this.is224||(c+=L[o>>>28&15]+L[o>>>24&15]+L[o>>>20&15]+L[o>>>16&15]+L[o>>>12&15]+L[o>>>8&15]+L[o>>>4&15]+L[o&15]),c};jt.prototype.toString=jt.prototype.hex;jt.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};jt.prototype.array=jt.prototype.digest;jt.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};const hl=(...e)=>new jt(!1,!0).update(e.join("")).hex();var zp={};F(zp,{sha256:()=>hl});var Hp={};F(Hp,{BaseCache:()=>Gp,InMemoryCache:()=>Wp,defaultHashKeyEncoder:()=>Vp,deserializeStoredGeneration:()=>q0,serializeGeneration:()=>Y0});const Vp=(...e)=>hl(e.join("_"));function q0(e){return e.message!==void 0?{text:e.text,message:qc(e.message)}:{text:e.text}}function Y0(e){const t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var Gp=class{keyEncoder=Vp;makeDefaultKeyEncoder(t){this.keyEncoder=t}};const X0=new Map;var Wp=class Jp extends Gp{cache;constructor(t){super(),this.cache=t??new Map}lookup(t,n){return Promise.resolve(this.cache.get(this.keyEncoder(t,n))??null)}async update(t,n,r){this.cache.set(this.keyEncoder(t,n),r)}static global(){return new Jp(X0)}},Kp={};F(Kp,{encodingForModel:()=>pl,getEncoding:()=>Zp});const la={},Q0=new Js({});async function Zp(e){return e in la||(la[e]=Q0.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new h_(t)).catch(t=>{throw delete la[e],t})),await la[e]}async function pl(e){return Zp(d_(e))}var qp={};F(qp,{BaseLangChain:()=>fl,BaseLanguageModel:()=>Si,calculateMaxTokens:()=>nS,getEmbeddingContextSize:()=>eS,getModelContextSize:()=>Yp,getModelNameForTiktoken:()=>bi,isOpenAITool:()=>tS});const bi=e=>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,eS=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},Yp=e=>{switch(bi(e)){case"gpt-3.5-turbo-16k":return 16384;case"gpt-3.5-turbo":return 4096;case"gpt-4-32k":return 32768;case"gpt-4":return 8192;case"text-davinci-003":return 4097;case"text-curie-001":return 2048;case"text-babbage-001":return 2048;case"text-ada-001":return 2048;case"code-davinci-002":return 8e3;case"code-cushman-001":return 2048;default:return 4097}};function tS(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 nS=async({prompt:e,modelName:t})=>{let n;try{n=(await pl(bi(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(e.length/4)}return Yp(t)-n},rS=()=>!1;var fl=class extends J{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??rS(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},Si=class extends fl{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...n}){const{cache:r,...s}=n;super({callbacks:e??t,...s}),typeof r=="object"?this.cache=r:r?this.cache=Wp.global():this.cache=void 0,this.caller=new Js(n??{})}_encoding;async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(r=>typeof r=="string"?r:r.type==="text"&&"text"in r?r.text:"").join("");let n=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await pl("modelName"in this?bi(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(t).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 ul(e):Array.isArray(e)?new dl(e.map(Gt)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const n={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([a,i])=>i!==void 0).map(([a,i])=>`${a}:${JSON.stringify(i)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}};function ml(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function gl(e){return e!==void 0&&J.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function yl(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(er(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 _l(e){return yl(e)||gl(e)||ml(e)}var Xp={};F(Xp,{BaseToolkit:()=>sS,DynamicStructuredTool:()=>Ti,DynamicTool:()=>vl,StructuredTool:()=>tr,Tool:()=>wl,ToolInputParsingException:()=>Ss,isLangChainTool:()=>_l,isRunnableToolLike:()=>gl,isStructuredTool:()=>ml,isStructuredToolParams:()=>yl,tool:()=>bl});var tr=class extends fl{returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata}async invoke(e,t){let n,r=K(pt(this.defaultConfig,t));return ps(e)?(n=e.args,r={...r,toolCall:e}):n=e,this.call(n,r)}async call(e,t,n){const r=ps(e)?e.args:e;let s;if(er(this.schema))try{s=await gi(this.schema,r)}catch(p){let f="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(f=`${f}
82
+ `)),r.close()}});return Fe.fromReadableStream(n)}function Gu(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}const H0=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function";function Zo(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function*Wu(e,t){for(;;){const{value:n,done:r}=me.runWithConfig(on(e),t.next.bind(t),!0);if(r)break;yield n}}async function*qo(e,t){const n=t[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await me.runWithConfig(on(e),n.next.bind(t),!0);if(s)break;yield r}}function Ae(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}var J=class extends Tt{lc_runnable=!0;name;getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new cl({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new De({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new Dp({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(K);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const n=Object.fromEntries(Object.entries(e).filter(([r])=>r!=="runId"));return Array.from({length:t},(r,s)=>K(s===0?e:n))}return Array.from({length:t},()=>K(e))}async batch(e,t,n){const r=this._getOptionsList(t??{},e.length),s=r[0]?.maxConcurrency??n?.maxConcurrency,a=new Js({maxConcurrency:s,onFailedAttempt:o=>{throw o}}),i=e.map((o,c)=>a.call(async()=>{try{return await this.invoke(o,r[c])}catch(l){if(n?.returnExceptions)return l;throw l}}));return Promise.all(i)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const n=K(t),r=new Mn({generator:this._streamIterator(e,n),config:n});return await r.setup,Fe.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=K(e):t=K({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){const r=K(n),a=await(await nt(r))?.handleChainStart(this.toJSON(),Ae(t,"input"),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName());delete r.runId;let i;try{const o=e.call(this,t,r,a);i=await On(o,n?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(Ae(i,"output")),i}async _batchWithConfig(e,t,n,r){const s=this._getOptionsList(n??{},t.length),a=await Promise.all(s.map(nt)),i=await Promise.all(a.map(async(c,l)=>{const u=await c?.handleChainStart(this.toJSON(),Ae(t[l],"input"),s[l].runId,s[l].runType,void 0,void 0,s[l].runName??this.getName());return delete s[l].runId,u}));let o;try{const c=e.call(this,t,s,i,r);o=await On(c,s?.[0]?.signal)}catch(c){throw await Promise.all(i.map(l=>l?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(Ae(o,"output")))),o}_concatOutputChunks(e,t){return xn(e,t)}async*_transformStreamWithConfig(e,t,n){let r,s=!0,a,i=!0;const o=K(n),c=await nt(o),l=this;async function*u(){for await(const h of e){if(s)if(r===void 0)r=h;else try{r=l._concatOutputChunks(r,h)}catch{r=void 0,s=!1}yield h}}let d;try{const h=await bp(t.bind(this),u(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),n?.signal,o);delete o.runId,d=h.setup;const p=d?.handlers.find(M0);let f=h.output;p!==void 0&&d!==void 0&&(f=p.tapOutputIterable(d.runId,f));const y=d?.handlers.find(Ap);y!==void 0&&d!==void 0&&(f=y.tapOutputIterable(d.runId,f));for await(const S of f)if(yield S,i)if(a===void 0)a=S;else try{a=this._concatOutputChunks(a,S)}catch{a=void 0,i=!1}}catch(h){throw await d?.handleChainError(h,void 0,void 0,void 0,{inputs:Ae(r,"input")}),h}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:Ae(r,"input")})}getGraph(e){const t=new Os,n=t.addNode({name:`${this.getName()}Input`,schema:ht()}),r=t.addNode(this),s=t.addNode({name:`${this.getName()}Output`,schema:ht()});return t.addEdge(n,r),t.addEdge(r,s),t}pipe(e){return new Et({first:this,last:$e(e)})}pick(e){return this.pipe(new Up(e))}assign(e){return this.pipe(new ll(new ts({steps:e})))}async*transform(e,t){let n;for await(const r of e)n===void 0?n=r:n=this._concatOutputChunks(n,r);yield*this._streamIterator(n,K(t))}async*streamLog(e,t,n){const r=new Ko({...n,autoClose:!1,_schemaFormat:"original"}),s=K(t);yield*this._streamLog(e,r,s)}async*_streamLog(e,t,n){const{callbacks:r}=n;if(r===void 0)n.callbacks=[t];else if(Array.isArray(r))n.callbacks=r.concat([t]);else{const o=r.copy();o.addHandler(t,!0),n.callbacks=o}const s=this.stream(e,n);async function a(){try{const o=await s;for await(const c of o){const l=new qt({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}const i=a();try{for await(const o of t)yield o}finally{await i}}streamEvents(e,t,n){let r;if(t.version==="v1")r=this._streamEventsV1(e,t,n);else if(t.version==="v2")r=this._streamEventsV2(e,t,n);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?z0(r):Fe.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){const r=new R0({...n,autoClose:!1}),s=K(t),a=s.runId??Ce();s.runId=a;const i=s.callbacks;if(i===void 0)s.callbacks=[r];else if(Array.isArray(i))s.callbacks=i.concat(r);else{const p=i.copy();p.addHandler(r,!0),s.callbacks=p}const o=new AbortController,c=this;async function l(){let p,f=null;try{t?.signal?"any"in AbortSignal?p=AbortSignal.any([o.signal,t.signal]):(p=t.signal,f=()=>{o.abort()},t.signal.addEventListener("abort",f,{once:!0})):p=o.signal;const y=await c.stream(e,{...s,signal:p}),S=r.tapOutputIterable(a,y);for await(const b of S)if(o.signal.aborted)break}finally{await r.finish(),p&&f&&p.removeEventListener("abort",f)}}const u=l();let d=!1,h;try{for await(const p of r){if(!d){p.data.input=e,d=!0,h=p.run_id,yield p;continue}p.run_id===h&&p.event.endsWith("_end")&&p.data?.input&&delete p.data.input,yield p}}finally{o.abort(),await u}}async*_streamEventsV1(e,t,n){let r,s=!1;const a=K(t),i=a.tags??[],o=a.metadata??{},c=a.runName??this.getName(),l=new Ko({...n,autoClose:!1,_schemaFormat:"streaming_events"}),u=new $0({...n}),d=this._streamLog(e,l,a);for await(const p of d){if(r?r=r.concat(p):r=il.fromRunLogPatch(p),r.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!s){s=!0;const b={...r.state},v={run_id:b.id,event:`on_${b.type}_start`,name:c,tags:i,metadata:o,data:{input:e}};u.includeEvent(v,b.type)&&(yield v)}const f=p.ops.filter(b=>b.path.startsWith("/logs/")).map(b=>b.path.split("/")[2]),y=[...new Set(f)];for(const b of y){let v,w={};const E=r.state.logs[b];if(E.end_time===void 0?E.streamed_output.length>0?v="stream":v="start":v="end",v==="start")E.inputs!==void 0&&(w.input=E.inputs);else if(v==="end")E.inputs!==void 0&&(w.input=E.inputs),w.output=E.final_output;else if(v==="stream"){const A=E.streamed_output.length;if(A!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${A} instead. Encountered in: "${E.name}"`);w={chunk:E.streamed_output[0]},E.streamed_output=[]}yield{event:`on_${E.type}_${v}`,name:E.name,run_id:E.id,tags:E.tags,metadata:E.metadata,data:w}}const{state:S}=r;if(S.streamed_output.length>0){const b=S.streamed_output.length;if(b!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${b} instead. Encountered in: "${S.name}"`);const v={chunk:S.streamed_output[0]};S.streamed_output=[];const w={event:`on_${S.type}_stream`,run_id:S.id,tags:i,metadata:o,name:c,data:v};u.includeEvent(w,S.type)&&(yield w)}}const h=r?.state;if(h!==void 0){const p={event:`on_${h.type}_end`,name:c,run_id:h.id,tags:i,metadata:o,data:{output:h.final_output}};u.includeEvent(p,h.type)&&(yield p)}}static isRunnable(e){return ol(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new De({bound:this,config:{},configFactories:[r=>({callbacks:[new Ip({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return K0(this,e)}},De=class Mp extends J{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(t){super(t),this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){const n=pt(this.config,...t);return pt(n,...this.configFactories?await Promise.all(this.configFactories.map(async r=>await r(n))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new cl({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t?.stopAfterAttempt,...t})}async invoke(t,n){return this.bound.invoke(t,await this._mergeConfig(n,this.kwargs))}async batch(t,n,r){const s=Array.isArray(n)?await Promise.all(n.map(async a=>this._mergeConfig(K(a),this.kwargs))):await this._mergeConfig(K(n),this.kwargs);return this.bound.batch(t,s,r)}_concatOutputChunks(t,n){return this.bound._concatOutputChunks(t,n)}async*_streamIterator(t,n){yield*this.bound._streamIterator(t,await this._mergeConfig(K(n),this.kwargs))}async stream(t,n){return this.bound.stream(t,await this._mergeConfig(K(n),this.kwargs))}async*transform(t,n){yield*this.bound.transform(t,await this._mergeConfig(K(n),this.kwargs))}streamEvents(t,n,r){const s=this,a=async function*(){yield*s.bound.streamEvents(t,{...await s._mergeConfig(K(n),s.kwargs),version:n.version},r)};return Fe.fromAsyncGenerator(a())}static isRunnableBinding(t){return t.bound&&J.isRunnable(t.bound)}withListeners({onStart:t,onEnd:n,onError:r}){return new Mp({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[s=>({callbacks:[new Ip({config:s,onStart:t,onEnd:n,onError:r})]})]})}},V0=class Rp extends J{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(t){super(t),this.bound=t.bound}async invoke(t,n){return this._callWithConfig(this._invoke.bind(this),t,n)}async _invoke(t,n,r){return this.bound.batch(t,ne(n,{callbacks:r?.getChild()}))}withListeners({onStart:t,onEnd:n,onError:r}){return new Rp({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:r})})}},cl=class extends De{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){const r=e>1?`retry:attempt:${e}`:void 0;return ne(t,{callbacks:n?.getChild(r)})}async _invoke(e,t,n){return ja(r=>super.invoke(e,this._patchConfigForRetry(r,t,n)),{onFailedAttempt:r=>this.onFailedAttempt(r,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,n,r){const s={};try{await ja(async a=>{const i=e.map((d,h)=>h).filter(d=>s[d.toString()]===void 0||s[d.toString()]instanceof Error),o=i.map(d=>e[d]),c=i.map(d=>this._patchConfigForRetry(a,t?.[d],n?.[d])),l=await super.batch(o,c,{...r,returnExceptions:!0});let u;for(let d=0;d<l.length;d+=1){const h=l[d],p=i[d];h instanceof Error&&u===void 0&&(u=h,u.input=o[d]),s[p.toString()]=h}if(u)throw u;return l},{onFailedAttempt:a=>this.onFailedAttempt(a,a.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(a){if(r?.returnExceptions!==!0)throw a}return Object.keys(s).sort((a,i)=>parseInt(a,10)-parseInt(i,10)).map(a=>s[parseInt(a,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},Et=class cs extends J{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(t){super(t),this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,n){const r=K(n),a=await(await nt(r))?.handleChainStart(this.toJSON(),Ae(t,"input"),r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let i=t,o;try{const c=[this.first,...this.middle];for(let l=0;l<c.length;l+=1){const d=c[l].invoke(i,ne(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${l+1}`)}));i=await On(d,n?.signal)}if(n?.signal?.aborted)throw Es(n.signal);o=await this.last.invoke(i,ne(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await a?.handleChainError(c),c}return await a?.handleChainEnd(Ae(o,"output")),o}async batch(t,n,r){const s=this._getOptionsList(n??{},t.length),a=await Promise.all(s.map(nt)),i=await Promise.all(a.map(async(c,l)=>{const u=await c?.handleChainStart(this.toJSON(),Ae(t[l],"input"),s[l].runId,void 0,void 0,void 0,s[l].runName);return delete s[l].runId,u}));let o=t;try{for(let c=0;c<this.steps.length;c+=1){const u=this.steps[c].batch(o,i.map((d,h)=>{const p=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return ne(s[h],{callbacks:p})}),r);o=await On(u,s[0]?.signal)}}catch(c){throw await Promise.all(i.map(l=>l?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(Ae(o,"output")))),o}_concatOutputChunks(t,n){return this.last._concatOutputChunks(t,n)}async*_streamIterator(t,n){const r=await nt(n),{runId:s,...a}=n??{},i=await r?.handleChainStart(this.toJSON(),Ae(t,"input"),s,void 0,void 0,void 0,a?.runName),o=[this.first,...this.middle,this.last];let c=!0,l;async function*u(){yield t}try{let d=o[0].transform(u(),ne(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let h=1;h<o.length;h+=1)d=await o[h].transform(d,ne(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${h+1}`)}));for await(const h of d)if(n?.signal?.throwIfAborted(),yield h,c)if(l===void 0)l=h;else try{l=this._concatOutputChunks(l,h)}catch{l=void 0,c=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(Ae(l,"output"))}getGraph(t){const n=new Os;let r=null;return this.steps.forEach((s,a)=>{const i=s.getGraph(t);a!==0&&i.trimFirstNode(),a!==this.steps.length-1&&i.trimLastNode(),n.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${s} has no first node`);r&&n.addEdge(r,o),r=i.lastNode()}),n}pipe(t){return cs.isRunnableSequence(t)?new cs({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new cs({first:this.first,middle:[...this.middle,this.last],last:$e(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&J.isRunnable(t)}static from([t,...n],r){let s={};return typeof r=="string"?s.name=r:r!==void 0&&(s=r),new cs({...s,first:$e(t),middle:n.slice(0,-1).map($e),last:$e(n[n.length-1])})}},ts=class $p extends J{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(t){super(t),this.steps={};for(const[n,r]of Object.entries(t.steps))this.steps[n]=$e(r)}static from(t){return new $p({steps:t})}async invoke(t,n){const r=K(n),a=await(await nt(r))?.handleChainStart(this.toJSON(),{input:t},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;const i={};try{const o=Object.entries(this.steps).map(async([c,l])=>{i[c]=await l.invoke(t,ne(r,{callbacks:a?.getChild(`map:key:${c}`)}))});await On(Promise.all(o),n?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(i),i}async*_transform(t,n,r){const s={...this.steps},a=al(t,Object.keys(s).length),i=new Map(Object.entries(s).map(([o,c],l)=>{const u=c.transform(a[l],ne(r,{callbacks:n?.getChild(`map:key:${o}`)}));return[o,u.next().then(d=>({key:o,gen:u,result:d}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:c,result:l,gen:u}=await On(o,r?.signal);i.delete(c),l.done||(yield{[c]:l.value},i.set(c,u.next().then(d=>({key:c,gen:u,result:d}))))}}transform(t,n){return this._transformStreamWithConfig(t,this._transform.bind(this),n)}async stream(t,n){async function*r(){yield t}const s=K(n),a=new Mn({generator:this.transform(r(),s),config:s});return await a.setup,Fe.fromAsyncGenerator(a)}},G0=class Lp extends J{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(t){if(super(t),!Qc(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,n){const[r]=this._getOptionsList(n??{},1),s=await nt(r),a=this.func(ne(r,{callbacks:s}),t);return On(a,r?.signal)}async*_streamIterator(t,n){const[r]=this._getOptionsList(n??{},1),s=await this.invoke(t,n);if(Zo(s)){for await(const a of s)r?.signal?.throwIfAborted(),yield a;return}if(H0(s)){for(;;){r?.signal?.throwIfAborted();const a=s.next();if(a.done)break;yield a.value}return}yield s}static from(t){return new Lp({func:t})}};function W0(e){if(Qc(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var at=class jp extends J{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(t){if(Qc(t.func))return G0.from(t.func);super(t),W0(t.func),this.func=t.func}static from(t){return new jp({func:t})}async _invoke(t,n,r){return new Promise((s,a)=>{const i=ne(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??Qi)-1});me.runWithConfig(on(i),async()=>{try{let o=await this.func(t,{...i});if(o&&J.isRunnable(o)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(t,{...i,recursionLimit:(i.recursionLimit??Qi)-1})}else if(Zo(o)){let c;for await(const l of qo(i,o))if(n?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}else if(Gu(o)){let c;for(const l of Wu(i,o))if(n?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}s(o)}catch(o){a(o)}})})}async invoke(t,n){return this._callWithConfig(this._invoke.bind(this),t,n)}async*_transform(t,n,r){let s;for await(const o of t)if(s===void 0)s=o;else try{s=this._concatOutputChunks(s,o)}catch{s=o}const a=ne(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??Qi)-1}),i=await new Promise((o,c)=>{me.runWithConfig(on(a),async()=>{try{const l=await this.func(s,{...a,config:a});o(l)}catch(l){c(l)}})});if(i&&J.isRunnable(i)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await i.stream(s,a);for await(const c of o)yield c}else if(Zo(i))for await(const o of qo(a,i))r?.signal?.throwIfAborted(),yield o;else if(Gu(i))for(const o of Wu(a,i))r?.signal?.throwIfAborted(),yield o;else yield i}transform(t,n){return this._transformStreamWithConfig(t,this._transform.bind(this),n)}async stream(t,n){async function*r(){yield t}const s=K(n),a=new Mn({generator:this.transform(r(),s),config:s});return await a.setup,Fe.fromAsyncGenerator(a)}},J0=class extends ts{},Dp=class extends J{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const n=K(t),r=await nt(n),{runId:s,...a}=n,i=await r?.handleChainStart(this.toJSON(),Ae(e,"input"),s,void 0,void 0,void 0,a?.runName),o=ne(a,{callbacks:i?.getChild()});return await me.runWithConfig(o,async()=>{let l;for(const u of this.runnables()){n?.signal?.throwIfAborted();try{const d=await u.invoke(e,o);return await i?.handleChainEnd(Ae(d,"output")),d}catch(d){l===void 0&&(l=d)}}throw l===void 0?new Error("No error stored at end of fallback."):(await i?.handleChainError(l),l)})}async*_streamIterator(e,t){const n=K(t),r=await nt(n),{runId:s,...a}=n,i=await r?.handleChainStart(this.toJSON(),Ae(e,"input"),s,void 0,void 0,void 0,a?.runName);let o,c;for(const u of this.runnables()){n?.signal?.throwIfAborted();const d=ne(a,{callbacks:i?.getChild()});try{const h=await u.stream(e,d);c=qo(d,h);break}catch(h){o===void 0&&(o=h)}}if(c===void 0){const u=o??new Error("No error stored at end of fallback.");throw await i?.handleChainError(u),u}let l;try{for await(const u of c){yield u;try{l=l===void 0?l:this._concatOutputChunks(l,u)}catch{l=void 0}}}catch(u){throw await i?.handleChainError(u),u}await i?.handleChainEnd(Ae(l,"output"))}async batch(e,t,n){if(n?.returnExceptions)throw new Error("Not implemented.");const r=this._getOptionsList(t??{},e.length),s=await Promise.all(r.map(o=>nt(o))),a=await Promise.all(s.map(async(o,c)=>{const l=await o?.handleChainStart(this.toJSON(),Ae(e[c],"input"),r[c].runId,void 0,void 0,void 0,r[c].runName);return delete r[c].runId,l}));let i;for(const o of this.runnables()){r[0].signal?.throwIfAborted();try{const c=await o.batch(e,a.map((l,u)=>ne(r[u],{callbacks:l?.getChild()})),n);return await Promise.all(a.map((l,u)=>l?.handleChainEnd(Ae(c[u],"output")))),c}catch(c){i===void 0&&(i=c)}}throw i?(await Promise.all(a.map(o=>o?.handleChainError(i))),i):new Error("No error stored at end of fallbacks.")}};function $e(e){if(typeof e=="function")return new at({func:e});if(J.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=$e(r);return new ts({steps:t})}else throw new Error(`Expected a Runnable, function or object.
83
+ Instead got an unsupported type.`)}var ll=class extends J{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof ts&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){const n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){const r=this.mapper.getStepsKeys(),[s,a]=al(e),i=this.mapper.transform(a,ne(n,{callbacks:t?.getChild()})),o=i.next();for await(const c of s){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const l=Object.fromEntries(Object.entries(c).filter(([u])=>!r.includes(u)));Object.keys(l).length>0&&(yield l)}yield(await o).value;for await(const c of i)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const r=K(t),s=new Mn({generator:this.transform(n(),r),config:r});return await s.setup,Fe.fromAsyncGenerator(s)}},Up=class extends J{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const t=this.keys.map(n=>[n,e[n]]).filter(n=>n[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const n=await this._pick(t);n!==void 0&&(yield n)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const r=K(t),s=new Mn({generator:this.transform(n(),r),config:r});return await s.setup,Fe.fromAsyncGenerator(s)}},Yo=class extends De{name;description;schema;constructor(e){const t=Et.from([at.from(async n=>{let r;if(ps(n))try{r=await gi(this.schema,n.args)}catch{throw new Ss("Received tool input did not match expected schema",JSON.stringify(n.args))}else r=n;return r}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function K0(e,t){const n=t.name??e.getName(),r=t.description??Vr(t.schema);return nl(t.schema)?new Yo({name:n,description:r,schema:te({input:Oe()}).transform(s=>s.input),bound:e}):new Yo({name:n,description:r,schema:t.schema,bound:e})}var Fp={};F(Fp,{BasePromptValue:()=>vi,ChatPromptValue:()=>dl,ImagePromptValue:()=>Bp,StringPromptValue:()=>ul});var vi=class extends Tt{},ul=class extends vi{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 ue(this.value)]}},dl=class extends vi{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 Zc(this.messages)}toChatMessages(){return this.messages}},Bp=class extends vi{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 ue({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},L="0123456789abcdef".split(""),Z0=[-2147483648,8388608,32768,128],Ot=[24,16,8,0],ca=[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],xe=[];function jt(e,t){t?(xe[0]=xe[16]=xe[1]=xe[2]=xe[3]=xe[4]=xe[5]=xe[6]=xe[7]=xe[8]=xe[9]=xe[10]=xe[11]=xe[12]=xe[13]=xe[14]=xe[15]=0,this.blocks=xe):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}jt.prototype.update=function(e){if(!this.finalized){var t,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);t=!0}for(var r,s=0,a,i=e.length,o=this.blocks;s<i;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),t)for(a=this.start;s<i&&a<64;++s)o[a>>>2]|=e[s]<<Ot[a++&3];else for(a=this.start;s<i&&a<64;++s)r=e.charCodeAt(s),r<128?o[a>>>2]|=r<<Ot[a++&3]:r<2048?(o[a>>>2]|=(192|r>>>6)<<Ot[a++&3],o[a>>>2]|=(128|r&63)<<Ot[a++&3]):r<55296||r>=57344?(o[a>>>2]|=(224|r>>>12)<<Ot[a++&3],o[a>>>2]|=(128|r>>>6&63)<<Ot[a++&3],o[a>>>2]|=(128|r&63)<<Ot[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++s)&1023),o[a>>>2]|=(240|r>>>18)<<Ot[a++&3],o[a>>>2]|=(128|r>>>12&63)<<Ot[a++&3],o[a>>>2]|=(128|r>>>6&63)<<Ot[a++&3],o[a>>>2]|=(128|r&63)<<Ot[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=o[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};jt.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=Z0[t&3],this.block=e[16],t>=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()}};jt.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=this.blocks,l,u,d,h,p,f,y,S,b,v,w;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(w=t&n,l=0;l<64;l+=4)this.first?(this.is224?(S=300032,p=c[0]-1413257819,o=p-150054599<<0,r=p+24177077<<0):(S=704751109,p=c[0]-210244248,o=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),S=e&t,h=S^e&n^w,y=s&a^~s&i,p=o+d+y+ca[l]+c[l],f=u+h,o=r+p<<0,r=p+f<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),b=r&e,h=b^r&t^S,y=i&o^~i&s,p=a+d+y+ca[l+1]+c[l+1],f=u+h,i=n+p<<0,n=p+f<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),v=n&r,h=v^n&e^b,y=a&i^~a&o,p=s+d+y+ca[l+2]+c[l+2],f=u+h,a=t+p<<0,t=p+f<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),w=t&n,h=w^t&r^v,y=a&i^~a&o,p=s+d+y+ca[l+3]+c[l+3],f=u+h,s=e+p<<0,e=p+f<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+s<<0,this.h5=this.h5+a<<0,this.h6=this.h6+i<<0,this.h7=this.h7+o<<0};jt.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=L[e>>>28&15]+L[e>>>24&15]+L[e>>>20&15]+L[e>>>16&15]+L[e>>>12&15]+L[e>>>8&15]+L[e>>>4&15]+L[e&15]+L[t>>>28&15]+L[t>>>24&15]+L[t>>>20&15]+L[t>>>16&15]+L[t>>>12&15]+L[t>>>8&15]+L[t>>>4&15]+L[t&15]+L[n>>>28&15]+L[n>>>24&15]+L[n>>>20&15]+L[n>>>16&15]+L[n>>>12&15]+L[n>>>8&15]+L[n>>>4&15]+L[n&15]+L[r>>>28&15]+L[r>>>24&15]+L[r>>>20&15]+L[r>>>16&15]+L[r>>>12&15]+L[r>>>8&15]+L[r>>>4&15]+L[r&15]+L[s>>>28&15]+L[s>>>24&15]+L[s>>>20&15]+L[s>>>16&15]+L[s>>>12&15]+L[s>>>8&15]+L[s>>>4&15]+L[s&15]+L[a>>>28&15]+L[a>>>24&15]+L[a>>>20&15]+L[a>>>16&15]+L[a>>>12&15]+L[a>>>8&15]+L[a>>>4&15]+L[a&15]+L[i>>>28&15]+L[i>>>24&15]+L[i>>>20&15]+L[i>>>16&15]+L[i>>>12&15]+L[i>>>8&15]+L[i>>>4&15]+L[i&15];return this.is224||(c+=L[o>>>28&15]+L[o>>>24&15]+L[o>>>20&15]+L[o>>>16&15]+L[o>>>12&15]+L[o>>>8&15]+L[o>>>4&15]+L[o&15]),c};jt.prototype.toString=jt.prototype.hex;jt.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};jt.prototype.array=jt.prototype.digest;jt.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};const hl=(...e)=>new jt(!1,!0).update(e.join("")).hex();var zp={};F(zp,{sha256:()=>hl});var Hp={};F(Hp,{BaseCache:()=>Gp,InMemoryCache:()=>Wp,defaultHashKeyEncoder:()=>Vp,deserializeStoredGeneration:()=>q0,serializeGeneration:()=>Y0});const Vp=(...e)=>hl(e.join("_"));function q0(e){return e.message!==void 0?{text:e.text,message:qc(e.message)}:{text:e.text}}function Y0(e){const t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var Gp=class{keyEncoder=Vp;makeDefaultKeyEncoder(t){this.keyEncoder=t}};const X0=new Map;var Wp=class Jp extends Gp{cache;constructor(t){super(),this.cache=t??new Map}lookup(t,n){return Promise.resolve(this.cache.get(this.keyEncoder(t,n))??null)}async update(t,n,r){this.cache.set(this.keyEncoder(t,n),r)}static global(){return new Jp(X0)}},Kp={};F(Kp,{encodingForModel:()=>pl,getEncoding:()=>Zp});const la={},Q0=new Js({});async function Zp(e){return e in la||(la[e]=Q0.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new d_(t)).catch(t=>{throw delete la[e],t})),await la[e]}async function pl(e){return Zp(u_(e))}var qp={};F(qp,{BaseLangChain:()=>fl,BaseLanguageModel:()=>Si,calculateMaxTokens:()=>nS,getEmbeddingContextSize:()=>eS,getModelContextSize:()=>Yp,getModelNameForTiktoken:()=>bi,isOpenAITool:()=>tS});const bi=e=>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,eS=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},Yp=e=>{switch(bi(e)){case"gpt-3.5-turbo-16k":return 16384;case"gpt-3.5-turbo":return 4096;case"gpt-4-32k":return 32768;case"gpt-4":return 8192;case"text-davinci-003":return 4097;case"text-curie-001":return 2048;case"text-babbage-001":return 2048;case"text-ada-001":return 2048;case"code-davinci-002":return 8e3;case"code-cushman-001":return 2048;default:return 4097}};function tS(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 nS=async({prompt:e,modelName:t})=>{let n;try{n=(await pl(bi(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(e.length/4)}return Yp(t)-n},rS=()=>!1;var fl=class extends J{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??rS(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},Si=class extends fl{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...n}){const{cache:r,...s}=n;super({callbacks:e??t,...s}),typeof r=="object"?this.cache=r:r?this.cache=Wp.global():this.cache=void 0,this.caller=new Js(n??{})}_encoding;async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(r=>typeof r=="string"?r:r.type==="text"&&"text"in r?r.text:"").join("");let n=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await pl("modelName"in this?bi(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(t).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 ul(e):Array.isArray(e)?new dl(e.map(Gt)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const n={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([a,i])=>i!==void 0).map(([a,i])=>`${a}:${JSON.stringify(i)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}};function ml(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function gl(e){return e!==void 0&&J.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function yl(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(er(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 _l(e){return yl(e)||gl(e)||ml(e)}var Xp={};F(Xp,{BaseToolkit:()=>sS,DynamicStructuredTool:()=>Ti,DynamicTool:()=>vl,StructuredTool:()=>tr,Tool:()=>wl,ToolInputParsingException:()=>Ss,isLangChainTool:()=>_l,isRunnableToolLike:()=>gl,isStructuredTool:()=>ml,isStructuredToolParams:()=>yl,tool:()=>bl});var tr=class extends fl{returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata}async invoke(e,t){let n,r=K(pt(this.defaultConfig,t));return ps(e)?(n=e.args,r={...r,toolCall:e}):n=e,this.call(n,r)}async call(e,t,n){const r=ps(e)?e.args:e;let s;if(er(this.schema))try{s=await gi(this.schema,r)}catch(p){let f="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(f=`${f}
84
84
  Details: ${p.message}`),p instanceof Error&&p.constructor.name==="ZodError"&&(f=`${f}
85
85
 
86
- ${p_(p)}`),new Ss(f,JSON.stringify(e))}else{const p=f_(r,this.schema);if(!p.valid){let f="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(f=`${f}
86
+ ${h_(p)}`),new Ss(f,JSON.stringify(e))}else{const p=p_(r,this.schema);if(!p.valid){let f="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(f=`${f}
87
87
  Details: ${p.errors.map(y=>`${y.keywordLocation}: ${y.error}`).join(`
88
88
  `)}`),new Ss(f,JSON.stringify(e))}s=r}const a=Gs(t),o=await Ze.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName);delete a.runId;let c;try{c=await this._call(s,o,a)}catch(p){throw await o?.handleToolError(p),p}let l,u;if(this.responseFormat==="content_and_artifact")if(Array.isArray(c)&&c.length===2)[l,u]=c;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
89
89
  Result: ${JSON.stringify(c)}`);else l=c;let d;ps(e)&&(d=e.id),!d&&Cw(a)&&(d=a.toolCall.id);const h=aS({content:l,artifact:u,toolCallId:d,name:this.name,metadata:this.metadata});return await o?.handleToolEnd(h),h}},wl=class extends tr{schema=te({input:Oe().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){const n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,t)}},vl=class extends wl{static lc_name(){return"DynamicTool"}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){const n=Gs(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}async _call(e,t,n){return this.func(e,t,n)}},Ti=class extends tr{static lc_name(){return"DynamicStructuredTool"}name;description;func;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,n){const r=Gs(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r,n)}_call(e,t,n){return this.func(e,t,n)}},sS=class{getTools(){return this.tools}};function bl(e,t){const n=nl(t.schema),r=fs(t.schema);if(!t.schema||n||r)return new vl({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(i,o,c)=>new Promise((l,u)=>{const d=ne(c,{callbacks:o?.getChild()});me.runWithConfig(on(d),async()=>{try{l(e(i,d))}catch(h){u(h)}})})});const s=t.schema,a=t.description??t.schema.description??`${t.name} tool`;return new Ti({...t,description:a,schema:s,func:async(i,o,c)=>new Promise((l,u)=>{c?.signal&&c.signal.addEventListener("abort",()=>u(Es(c.signal)));const d=ne(c,{callbacks:o?.getChild()});me.runWithConfig(on(d),async()=>{try{const h=await e(i,d);if(c?.signal?.aborted)return;l(h)}catch(h){u(h)}})})})}function aS(e){const{content:t,artifact:n,toolCallId:r,metadata:s}=e;return r&&!Vc(t)?typeof t=="string"||Array.isArray(t)&&t.every(a=>typeof a=="object")?new X({status:"success",content:t,artifact:n,tool_call_id:r,name:e.name,metadata:s}):new X({status:"success",content:iS(t),artifact:n,tool_call_id:r,name:e.name,metadata:s}):t}function iS(e){try{return JSON.stringify(e,null,2)??""}catch{return`${e}`}}var Qp=typeof globalThis=="object"&&globalThis&&globalThis.Object===Object&&globalThis,oS=typeof self=="object"&&self&&self.Object===Object&&self,ln=Qp||oS||Function("return this")(),Kr=ln.Symbol,ef=Object.prototype,cS=ef.hasOwnProperty,lS=ef.toString,as=Kr?Kr.toStringTag:void 0;function uS(e){var t=cS.call(e,as),n=e[as];try{e[as]=void 0;var r=!0}catch{}var s=lS.call(e);return r&&(t?e[as]=n:delete e[as]),s}var dS=Object.prototype,hS=dS.toString;function pS(e){return hS.call(e)}var fS="[object Null]",mS="[object Undefined]",Ju=Kr?Kr.toStringTag:void 0;function Ks(e){return e==null?e===void 0?mS:fS:Ju&&Ju in Object(e)?uS(e):pS(e)}function xs(e){return e!=null&&typeof e=="object"}var Wa=Array.isArray;function tf(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var gS="[object AsyncFunction]",yS="[object Function]",_S="[object GeneratorFunction]",wS="[object Proxy]";function nf(e){if(!tf(e))return!1;var t=Ks(e);return t==yS||t==_S||t==gS||t==wS}var ro=ln["__core-js_shared__"],Ku=(function(){var e=/[^.]+$/.exec(ro&&ro.keys&&ro.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function vS(e){return!!Ku&&Ku in e}var bS=Function.prototype,SS=bS.toString;function nr(e){if(e!=null){try{return SS.call(e)}catch{}try{return e+""}catch{}}return""}var TS=/[\\^$.*+?()[\]{}|]/g,ES=/^\[object .+?Constructor\]$/,CS=Function.prototype,AS=Object.prototype,kS=CS.toString,OS=AS.hasOwnProperty,xS=RegExp("^"+kS.call(OS).replace(TS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function IS(e){if(!tf(e)||vS(e))return!1;var t=nf(e)?xS:ES;return t.test(nr(e))}function PS(e,t){return e?.[t]}function ns(e,t){var n=PS(e,t);return IS(n)?n:void 0}var Xo=ns(ln,"WeakMap"),NS=9007199254740991,MS=/^(?:0|[1-9]\d*)$/;function RS(e,t){var n=typeof e;return t=t??NS,!!t&&(n=="number"||n!="symbol"&&MS.test(e))&&e>-1&&e%1==0&&e<t}function rf(e,t){return e===t||e!==e&&t!==t}var $S=9007199254740991;function sf(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=$S}function LS(e){return e!=null&&sf(e.length)&&!nf(e)}var jS=Object.prototype;function DS(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||jS;return e===n}function US(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}var FS="[object Arguments]";function Zu(e){return xs(e)&&Ks(e)==FS}var af=Object.prototype,BS=af.hasOwnProperty,zS=af.propertyIsEnumerable,HS=Zu((function(){return arguments})())?Zu:function(e){return xs(e)&&BS.call(e,"callee")&&!zS.call(e,"callee")};function VS(){return!1}var of=typeof exports=="object"&&exports&&!exports.nodeType&&exports,qu=of&&typeof module=="object"&&module&&!module.nodeType&&module,GS=qu&&qu.exports===of,Yu=GS?ln.Buffer:void 0,WS=Yu?Yu.isBuffer:void 0,Qo=WS||VS,JS="[object Arguments]",KS="[object Array]",ZS="[object Boolean]",qS="[object Date]",YS="[object Error]",XS="[object Function]",QS="[object Map]",eT="[object Number]",tT="[object Object]",nT="[object RegExp]",rT="[object Set]",sT="[object String]",aT="[object WeakMap]",iT="[object ArrayBuffer]",oT="[object DataView]",cT="[object Float32Array]",lT="[object Float64Array]",uT="[object Int8Array]",dT="[object Int16Array]",hT="[object Int32Array]",pT="[object Uint8Array]",fT="[object Uint8ClampedArray]",mT="[object Uint16Array]",gT="[object Uint32Array]",le={};le[cT]=le[lT]=le[uT]=le[dT]=le[hT]=le[pT]=le[fT]=le[mT]=le[gT]=!0;le[JS]=le[KS]=le[iT]=le[ZS]=le[oT]=le[qS]=le[YS]=le[XS]=le[QS]=le[eT]=le[tT]=le[nT]=le[rT]=le[sT]=le[aT]=!1;function yT(e){return xs(e)&&sf(e.length)&&!!le[Ks(e)]}function _T(e){return function(t){return e(t)}}var cf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ms=cf&&typeof module=="object"&&module&&!module.nodeType&&module,wT=ms&&ms.exports===cf,so=wT&&Qp.process,Xu=(function(){try{var e=ms&&ms.require&&ms.require("util").types;return e||so&&so.binding&&so.binding("util")}catch{}})(),Qu=Xu&&Xu.isTypedArray,lf=Qu?_T(Qu):yT,vT=Object.prototype,bT=vT.hasOwnProperty;function ST(e,t){var n=Wa(e),r=!n&&HS(e),s=!n&&!r&&Qo(e),a=!n&&!r&&!s&&lf(e),i=n||r||s||a,o=i?US(e.length,String):[],c=o.length;for(var l in e)bT.call(e,l)&&!(i&&(l=="length"||s&&(l=="offset"||l=="parent")||a&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||RS(l,c)))&&o.push(l);return o}function TT(e,t){return function(n){return e(t(n))}}var ET=TT(Object.keys,Object),CT=Object.prototype,AT=CT.hasOwnProperty;function kT(e){if(!DS(e))return ET(e);var t=[];for(var n in Object(e))AT.call(e,n)&&n!="constructor"&&t.push(n);return t}function OT(e){return LS(e)?ST(e):kT(e)}var Is=ns(Object,"create");function xT(){this.__data__=Is?Is(null):{},this.size=0}function IT(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var PT="__lodash_hash_undefined__",NT=Object.prototype,MT=NT.hasOwnProperty;function RT(e){var t=this.__data__;if(Is){var n=t[e];return n===PT?void 0:n}return MT.call(t,e)?t[e]:void 0}var $T=Object.prototype,LT=$T.hasOwnProperty;function jT(e){var t=this.__data__;return Is?t[e]!==void 0:LT.call(t,e)}var DT="__lodash_hash_undefined__";function UT(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=Is&&t===void 0?DT:t,this}function Zn(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Zn.prototype.clear=xT;Zn.prototype.delete=IT;Zn.prototype.get=RT;Zn.prototype.has=jT;Zn.prototype.set=UT;function FT(){this.__data__=[],this.size=0}function Ei(e,t){for(var n=e.length;n--;)if(rf(e[n][0],t))return n;return-1}var BT=Array.prototype,zT=BT.splice;function HT(e){var t=this.__data__,n=Ei(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():zT.call(t,n,1),--this.size,!0}function VT(e){var t=this.__data__,n=Ei(t,e);return n<0?void 0:t[n][1]}function GT(e){return Ei(this.__data__,e)>-1}function WT(e,t){var n=this.__data__,r=Ei(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}function un(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}un.prototype.clear=FT;un.prototype.delete=HT;un.prototype.get=VT;un.prototype.has=GT;un.prototype.set=WT;var Ps=ns(ln,"Map");function JT(){this.size=0,this.__data__={hash:new Zn,map:new(Ps||un),string:new Zn}}function KT(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Ci(e,t){var n=e.__data__;return KT(t)?n[typeof t=="string"?"string":"hash"]:n.map}function ZT(e){var t=Ci(this,e).delete(e);return this.size-=t?1:0,t}function qT(e){return Ci(this,e).get(e)}function YT(e){return Ci(this,e).has(e)}function XT(e,t){var n=Ci(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}function rr(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}rr.prototype.clear=JT;rr.prototype.delete=ZT;rr.prototype.get=qT;rr.prototype.has=YT;rr.prototype.set=XT;function QT(e,t){for(var n=-1,r=t.length,s=e.length;++n<r;)e[s+n]=t[n];return e}function eE(){this.__data__=new un,this.size=0}function tE(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}function nE(e){return this.__data__.get(e)}function rE(e){return this.__data__.has(e)}var sE=200;function aE(e,t){var n=this.__data__;if(n instanceof un){var r=n.__data__;if(!Ps||r.length<sE-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new rr(r)}return n.set(e,t),this.size=n.size,this}function Sn(e){var t=this.__data__=new un(e);this.size=t.size}Sn.prototype.clear=eE;Sn.prototype.delete=tE;Sn.prototype.get=nE;Sn.prototype.has=rE;Sn.prototype.set=aE;function iE(e,t){for(var n=-1,r=e==null?0:e.length,s=0,a=[];++n<r;){var i=e[n];t(i,n,e)&&(a[s++]=i)}return a}function oE(){return[]}var cE=Object.prototype,lE=cE.propertyIsEnumerable,ed=Object.getOwnPropertySymbols,uE=ed?function(e){return e==null?[]:(e=Object(e),iE(ed(e),function(t){return lE.call(e,t)}))}:oE;function dE(e,t,n){var r=t(e);return Wa(e)?r:QT(r,n(e))}function td(e){return dE(e,OT,uE)}var ec=ns(ln,"DataView"),tc=ns(ln,"Promise"),nc=ns(ln,"Set"),nd="[object Map]",hE="[object Object]",rd="[object Promise]",sd="[object Set]",ad="[object WeakMap]",id="[object DataView]",pE=nr(ec),fE=nr(Ps),mE=nr(tc),gE=nr(nc),yE=nr(Xo),fn=Ks;(ec&&fn(new ec(new ArrayBuffer(1)))!=id||Ps&&fn(new Ps)!=nd||tc&&fn(tc.resolve())!=rd||nc&&fn(new nc)!=sd||Xo&&fn(new Xo)!=ad)&&(fn=function(e){var t=Ks(e),n=t==hE?e.constructor:void 0,r=n?nr(n):"";if(r)switch(r){case pE:return id;case fE:return nd;case mE:return rd;case gE:return sd;case yE:return ad}return t});var od=ln.Uint8Array,_E="__lodash_hash_undefined__";function wE(e){return this.__data__.set(e,_E),this}function vE(e){return this.__data__.has(e)}function Ja(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new rr;++t<n;)this.add(e[t])}Ja.prototype.add=Ja.prototype.push=wE;Ja.prototype.has=vE;function bE(e,t){for(var n=-1,r=e==null?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}function SE(e,t){return e.has(t)}var TE=1,EE=2;function uf(e,t,n,r,s,a){var i=n&TE,o=e.length,c=t.length;if(o!=c&&!(i&&c>o))return!1;var l=a.get(e),u=a.get(t);if(l&&u)return l==t&&u==e;var d=-1,h=!0,p=n&EE?new Ja:void 0;for(a.set(e,t),a.set(t,e);++d<o;){var f=e[d],y=t[d];if(r)var S=i?r(y,f,d,t,e,a):r(f,y,d,e,t,a);if(S!==void 0){if(S)continue;h=!1;break}if(p){if(!bE(t,function(b,v){if(!SE(p,v)&&(f===b||s(f,b,n,r,a)))return p.push(v)})){h=!1;break}}else if(!(f===y||s(f,y,n,r,a))){h=!1;break}}return a.delete(e),a.delete(t),h}function CE(e){var t=-1,n=Array(e.size);return e.forEach(function(r,s){n[++t]=[s,r]}),n}function AE(e){var t=-1,n=Array(e.size);return e.forEach(function(r){n[++t]=r}),n}var kE=1,OE=2,xE="[object Boolean]",IE="[object Date]",PE="[object Error]",NE="[object Map]",ME="[object Number]",RE="[object RegExp]",$E="[object Set]",LE="[object String]",jE="[object Symbol]",DE="[object ArrayBuffer]",UE="[object DataView]",cd=Kr?Kr.prototype:void 0,ao=cd?cd.valueOf:void 0;function FE(e,t,n,r,s,a,i){switch(n){case UE:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case DE:return!(e.byteLength!=t.byteLength||!a(new od(e),new od(t)));case xE:case IE:case ME:return rf(+e,+t);case PE:return e.name==t.name&&e.message==t.message;case RE:case LE:return e==t+"";case NE:var o=CE;case $E:var c=r&kE;if(o||(o=AE),e.size!=t.size&&!c)return!1;var l=i.get(e);if(l)return l==t;r|=OE,i.set(e,t);var u=uf(o(e),o(t),r,s,a,i);return i.delete(e),u;case jE:if(ao)return ao.call(e)==ao.call(t)}return!1}var BE=1,zE=Object.prototype,HE=zE.hasOwnProperty;function VE(e,t,n,r,s,a){var i=n&BE,o=td(e),c=o.length,l=td(t),u=l.length;if(c!=u&&!i)return!1;for(var d=c;d--;){var h=o[d];if(!(i?h in t:HE.call(t,h)))return!1}var p=a.get(e),f=a.get(t);if(p&&f)return p==t&&f==e;var y=!0;a.set(e,t),a.set(t,e);for(var S=i;++d<c;){h=o[d];var b=e[h],v=t[h];if(r)var w=i?r(v,b,h,t,e,a):r(b,v,h,e,t,a);if(!(w===void 0?b===v||s(b,v,n,r,a):w)){y=!1;break}S||(S=h=="constructor")}if(y&&!S){var E=e.constructor,A=t.constructor;E!=A&&"constructor"in e&&"constructor"in t&&!(typeof E=="function"&&E instanceof E&&typeof A=="function"&&A instanceof A)&&(y=!1)}return a.delete(e),a.delete(t),y}var GE=1,ld="[object Arguments]",ud="[object Array]",ua="[object Object]",WE=Object.prototype,dd=WE.hasOwnProperty;function JE(e,t,n,r,s,a){var i=Wa(e),o=Wa(t),c=i?ud:fn(e),l=o?ud:fn(t);c=c==ld?ua:c,l=l==ld?ua:l;var u=c==ua,d=l==ua,h=c==l;if(h&&Qo(e)){if(!Qo(t))return!1;i=!0,u=!1}if(h&&!u)return a||(a=new Sn),i||lf(e)?uf(e,t,n,r,s,a):FE(e,t,c,n,r,s,a);if(!(n&GE)){var p=u&&dd.call(e,"__wrapped__"),f=d&&dd.call(t,"__wrapped__");if(p||f){var y=p?e.value():e,S=f?t.value():t;return a||(a=new Sn),s(y,S,n,r,a)}}return h?(a||(a=new Sn),VE(e,t,n,r,s,a)):!1}function df(e,t,n,r,s){return e===t?!0:e==null||t==null||!xs(e)&&!xs(t)?e!==e&&t!==t:JE(e,t,n,r,df,s)}function KE(e,t){return df(e,t)}class ZE{capture(){}shutdown(){return Promise.resolve()}}const qE=Symbol("Let zodToJsonSchema decide on which parser to use"),YE={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},XE=e=>({...YE,...e}),QE=e=>{const t=XE(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}};function hf(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function ae(e,t,n,r,s){e[t]=n,hf(e,t,r,s)}const pf=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function it(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?pf(t,e.currentPath):t.join("/")}}function eC(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==R.ZodAny&&(n.items=ee(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ae(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ae(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ae(n,"minItems",e.exactLength.value,e.exactLength.message,t),ae(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function tC(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":t.target==="jsonSchema7"?r.inclusive?ae(n,"minimum",r.value,r.message,t):ae(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,t):ae(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,t));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,t);break}return n}function nC(){return{type:"boolean"}}function ff(e,t){return ee(e.type._def,t)}const rC=(e,t)=>ee(e.innerType._def,t);function mf(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,a)=>mf(e,t,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return sC(e,t)}}const sC=(e,t)=>{const n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(const r of e.checks)switch(r.kind){case"min":ae(n,"minimum",r.value,r.message,t);break;case"max":ae(n,"maximum",r.value,r.message,t);break}return n};function aC(e,t){return{...ee(e.innerType._def,t),default:e.defaultValue()}}function iC(e,t){return t.effectStrategy==="input"?ee(e.schema._def,t):it(t)}function oC(e){return{type:"string",enum:Array.from(e.values)}}const cC=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function lC(e,t){const n=[ee(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ee(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a);let r=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(a=>{if(cC(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function uC(e,t){const n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}let io;const xt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(io===void 0&&(io=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),io),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function gf(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":ae(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":It(n,"email",r.message,t);break;case"format:idn-email":It(n,"idn-email",r.message,t);break;case"pattern:zod":Ve(n,xt.email,r.message,t);break}break;case"url":It(n,"uri",r.message,t);break;case"uuid":It(n,"uuid",r.message,t);break;case"regex":Ve(n,r.regex,r.message,t);break;case"cuid":Ve(n,xt.cuid,r.message,t);break;case"cuid2":Ve(n,xt.cuid2,r.message,t);break;case"startsWith":Ve(n,RegExp(`^${oo(r.value,t)}`),r.message,t);break;case"endsWith":Ve(n,RegExp(`${oo(r.value,t)}$`),r.message,t);break;case"datetime":It(n,"date-time",r.message,t);break;case"date":It(n,"date",r.message,t);break;case"time":It(n,"time",r.message,t);break;case"duration":It(n,"duration",r.message,t);break;case"length":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t),ae(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":{Ve(n,RegExp(oo(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&It(n,"ipv4",r.message,t),r.version!=="v4"&&It(n,"ipv6",r.message,t);break}case"base64url":Ve(n,xt.base64url,r.message,t);break;case"jwt":Ve(n,xt.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&Ve(n,xt.ipv4Cidr,r.message,t),r.version!=="v4"&&Ve(n,xt.ipv6Cidr,r.message,t);break}case"emoji":Ve(n,xt.emoji(),r.message,t);break;case"ulid":{Ve(n,xt.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{It(n,"binary",r.message,t);break}case"contentEncoding:base64":{ae(n,"contentEncoding","base64",r.message,t);break}case"pattern:zod":{Ve(n,xt.base64,r.message,t);break}}break}case"nanoid":Ve(n,xt.nanoid,r.message,t)}return n}function oo(e,t){return t.patternStrategy==="escape"?hC(e):e}const dC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function hC(e){let t="";for(let n=0;n<e.length;n++)dC.has(e[n])||(t+="\\"),t+=e[n];return t}function It(e,t,n,r){e.format||e.anyOf?.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):ae(e,"format",t,n,r)}function Ve(e,t,n,r){e.pattern||e.allOf?.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:hd(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ae(e,"pattern",hd(t,r),n,r)}function hd(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,o=!1;for(let c=0;c<r.length;c++){if(a){s+=r[c],a=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){o?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),o=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],o=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){s+=`(^|(?<=[\r
@@ -203,7 +203,7 @@ data: ${hx(s.data)}
203
203
 
204
204
  `))};try{for await(const s of e){const[a,i,o]=s;let c=o;if(i==="debug"){const u=o;u.type==="checkpoint"&&(c={...u,payload:Rd(u.payload)})}i==="checkpoints"&&(c=Rd(o));const l=a?.length?`${i}|${a.join("|")}`:i;r({event:l,data:c})}}catch(s){r({event:"error",data:px(s)})}n.close()}})}const ma=Symbol.for("INPUT_DONE"),Co=Symbol.for("INPUT_RESUMING"),mx=25;function gx(...e){return new Og({passthroughFn:t=>{for(const n of e)n.modes.has(t[1])&&n.push(t)},modes:new Set(e.flatMap(t=>Array.from(t.modes)))})}var yx=class extends oO{cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation("get",e)}async set(e){return this.enqueueOperation("set",e)}async clear(e){return this.enqueueOperation("clear",e)}async stop(){await this.queue}enqueueOperation(e,...t){const n=this.queue.then(()=>this.cache[e](...t));return this.queue=n.then(()=>{},()=>{}),n}},_x=class xg{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status="pending";tasks={};stream;checkpointerPromises=[];isNested;_checkpointerChainedPromise=Promise.resolve();store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let t=!1;if(ie in this.checkpoint.channel_versions)t=!0;else for(const c in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,c)){t=!0;break}const r=this.config.configurable?.[gn]!==void 0&&this.config.configurable?.[gn],s=this.input===null||this.input===void 0,a=Pe(this.input)&&this.input.resume!=null,i=this.input===Co,o=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return t&&(r||s||a||i||o)}constructor(t){this.input=t.input,this.checkpointer=t.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=tx,this.checkpoint=t.checkpoint,this.checkpointMetadata=t.checkpointMetadata,this.checkpointPreviousVersions=t.checkpointPreviousVersions,this.channels=t.channels,this.checkpointPendingWrites=t.checkpointPendingWrites,this.step=t.step,this.stop=t.stop,this.config=t.config,this.checkpointConfig=t.checkpointConfig,this.isNested=t.isNested,this.manager=t.manager,this.outputKeys=t.outputKeys,this.streamKeys=t.streamKeys,this.nodes=t.nodes,this.skipDoneTasks=t.skipDoneTasks,this.store=t.store,this.cache=t.cache?new yx(t.cache):void 0,this.stream=t.stream,this.checkpointNamespace=t.checkpointNamespace,this.prevCheckpointConfig=t.prevCheckpointConfig,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.durability=t.durability,this.debug=t.debug,this.triggerToNodes=t.triggerToNodes}static async initialize(t){let{config:n,stream:r}=t;r!==void 0&&n.configurable?.[ri]!==void 0&&(r=gx(r,n.configurable[ri]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,a=n.configurable?.[Cn];n.configurable&&a&&(a.subgraphCounter>0&&(n=Nt(n,{[Bt]:[n.configurable[Bt],a.subgraphCounter.toString()].join(ke)})),a.subgraphCounter+=1);const i=Wn in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=Nt(n,{checkpoint_ns:"",checkpoint_id:void 0}));let o=n;n.configurable?.[wt]!==void 0&&n.configurable?.[wt]?.[n.configurable?.checkpoint_ns]&&(o=Nt(n,{checkpoint_id:n.configurable[wt][n.configurable?.checkpoint_ns]}));const c=n.configurable?.checkpoint_ns?.split(ke)??[],l=await t.checkpointer?.getTuple(o)??{config:n,checkpoint:eg(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};o={...n,...l.config,configurable:{checkpoint_ns:"",...n.configurable,...l.config.configurable}};const u=l.parentConfig,d=ti(l.checkpoint),h={...l.metadata},p=l.pendingWrites??[],f=ni(t.channelSpecs,d),y=(h.step??0)+1,S=y+(n.recursionLimit??mx)+1,b={...d.channel_versions},v=t.store?new iO(t.store):void 0;return v&&await v.start(),new xg({input:t.input,config:n,checkpointer:t.checkpointer,checkpoint:d,checkpointMetadata:h,checkpointConfig:o,prevCheckpointConfig:u,checkpointNamespace:c,channels:f,isNested:i,manager:t.manager,skipDoneTasks:s,step:y,stop:S,checkpointPreviousVersions:b,checkpointPendingWrites:p,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:r,store:v,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes})}_checkpointerPutAfterPrevious(t){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(t.config,t.checkpoint,t.metadata,t.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(t,n){let r=n;if(r.length===0)return;r.every(([i])=>i in nO)&&(r=Array.from(new Map(r.map(i=>[i[0],i])).values())),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(i=>i[0]!==t);for(const[i,o]of r)this.checkpointPendingWrites.push([t,i,o]);const s=Nt(this.checkpointConfig,{[Bt]:this.config.configurable?.checkpoint_ns??"",[Sc]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(s,r,t)),this.tasks&&this._outputWrites(t,r),!n.length||!this.cache||!this.tasks)return;const a=this.tasks[t];a==null||a.cache_key==null||n[0][0]===tt||n[0][0]===Y||this.cache.set([{key:[a.cache_key.ns,a.cache_key.key],value:a.writes,ttl:a.cache_key.ttl}])}_outputWrites(t,n,r=!1){const s=this.tasks[t];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes(ve))return;if(n.length>0)if(n[0][0]===Y){if(s.path?.[0]===dt&&s.path?.at(-1)===!0)return;const a=n.filter(i=>i[0]===Y).flatMap(i=>i[1]);this._emit([["updates",{[Y]:a}],["values",{[Y]:a}]])}else n[0][0]!==tt&&this._emit(ds(pn(ZO(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(ds(pn(cx([[s,n]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const t=[],n=([i,o])=>`ns:${i.join(",")}|key:${o}`,r=[],s={};for(const i of Object.values(this.tasks))i.cache_key!=null&&!i.writes.length&&(r.push([i.cache_key.ns,i.cache_key.key]),s[n([i.cache_key.ns,i.cache_key.key])]=i);if(r.length===0)return[];const a=await this.cache.get(r);for(const{key:i,value:o}of a){const c=s[n(i)];c!=null&&(c.writes.push(...o),t.push({task:c,result:o}))}return t}async tick(t){this.store&&!this.store.isRunning&&await this.store?.start();const{inputKeys:n=[]}=t;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![ma,Co].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new Sr;if(Object.values(this.tasks).every(a=>a.writes.length>0)){const a=Object.values(this.tasks).flatMap(o=>o.writes);this.updatedChannels=ut(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const i=await yn(pn(bo(this.outputKeys,a,this.channels),"values"));if(this._emit(i),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),fa(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new Sr;this.config.configurable?.[gn]!==void 0&&delete this.config.configurable?.[gn]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const r=vr(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels});if(this.tasks=r,this.checkpointer&&this._emit(await yn(pn(lx(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[a,i,o]of this.checkpointPendingWrites){if(i===tt||i===Y||i===rt)continue;const c=Object.values(this.tasks).find(l=>l.id===a);c&&c.writes.push([i,o])}for(const a of Object.values(this.tasks))a.writes.length>0&&this._outputWrites(a.id,a.writes,!0)}if(Object.values(this.tasks).every(a=>a.writes.length>0))return this.tick({inputKeys:n});if(fa(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new Sr;const s=await yn(pn(Pd(Object.values(this.tasks)),"tasks"));return this._emit(s),!0}async finishAndHandleError(t){this.durability==="exit"&&(!this.isNested||typeof t<"u"||this.checkpointNamespace.every(r=>!r.includes(an)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(t);return(n||t===void 0)&&(this.output=Yn(this.channels,this.outputKeys)),n&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(r=>r.writes.length>0)&&(this.updatedChannels=ut(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(ds(pn(bo(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),Bn(t)&&!t.interrupts.length&&this._emit([["updates",{[Y]:[]}],["values",{[Y]:[]}]])),n}async acceptPush(t,n,r){if(this.interruptAfter?.length>0&&fa(this.checkpoint,this.interruptAfter,[t])){this.toInterrupt.push(t);return}const s=kc([dt,t.path??[],n,t.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,t.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!s)return;if(this.interruptBefore?.length>0&&fa(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(ds(pn(Pd([s]),"tasks"))),this.debug&&kg(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});const a=await this._matchCachedWrites();for(const{task:i}of a)this._outputWrites(i.id,i.writes,!0);return s}_suppressInterrupt(t){return Bn(t)&&!this.isNested}async _first(t){const{configurable:n}=this.config,r=n?.[Cn];if(r&&r.nullResume!==void 0&&this.putWrites(bt,[[rt,r.nullResume]]),Pe(this.input)){const i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(vg)&&(this.config.configurable??={},this.config.configurable[ka]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const o={};for(const[c,l,u]of KO(this.input,this.checkpointPendingWrites))o[c]??=[],o[c].push([l,u]);if(Object.keys(o).length===0)throw new Ed("Received empty Command input");for(const[c,l]of Object.entries(o))this.putWrites(c,l)}const s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===bt).map(i=>i.slice(1));s.length>0&&ut(this.checkpoint,this.channels,[{name:Yt,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const a=Pe(this.input)&&s.length>0;if(this.isResuming||a){for(const o in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,o)&&this.checkpoint.channel_versions[o]!==void 0){const c=this.checkpoint.channel_versions[o];this.checkpoint.versions_seen[Y]={...this.checkpoint.versions_seen[Y],[o]:c}}const i=await yn(pn(bo(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=Co;else if(a)await this._putCheckpoint({source:"input"}),this.input=ma;else{const i=await yn(Eg(t,this.input));if(i.length>0){const o=vr(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=ut(this.checkpoint,this.channels,Object.values(o).concat([{name:Yt,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=ma}else if(gn in(this.config.configurable??{}))this.input=ma;else throw new Ed(`Received no input writes for ${JSON.stringify(t,null,2)}`)}this.isNested||(this.config=Nt(this.config,{[gn]:this.isResuming}))}_emit(t){for(const[n,r]of t)if(this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){const s=n==="checkpoints"?this.step-1:this.step,a=new Date().toISOString(),i=n==="checkpoints"?"checkpoint":typeof r=="object"&&r!=null&&"result"in r?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:s,type:i,timestamp:a,payload:r}])}}_putCheckpoint(t){const n=this.checkpointMetadata===t,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=a=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=Nt(this.checkpointConfig,{[Bt]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},o=Na(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:ti(a),metadata:{...this.checkpointMetadata},newVersions:o}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};n||(this.checkpointMetadata={...t,step:this.step,parents:this.config.configurable?.[wt]??{}}),this.checkpoint=Un(this.checkpoint,r?this.channels:void 0,this.step,n?{id:this.checkpoint.id}:void 0),r&&s(this.checkpoint),n||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;const t=Nt(this.checkpointConfig,{[Bt]:this.config.configurable?.checkpoint_ns??"",[Sc]:this.checkpoint.id}),n={};for(const[r,s,a]of this.checkpointPendingWrites)n[r]??=[],n[r].push([s,a]);for(const[r,s]of Object.entries(n))this.checkpointerPromises.push(this.checkpointer.putWrites(t,s,r))}_matchWrites(t){for(const[n,r,s]of this.checkpointPendingWrites){if(r===tt||r===Y||r===rt)continue;const a=Object.values(t).find(i=>i.id===n);a&&a.writes.push([r,s])}for(const n of Object.values(t))n.writes.length>0&&this._outputWrites(n.id,n.writes,!0)}};function wx(e){return Ie(e?.message)}var vx=class extends es{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,n,r=!1){if(r&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let s=t.id;n!=null&&(Wc(t)?s??=`run-${n}-tool-${t.tool_call_id}`:((s==null||s===`run-${n}`)&&(s=this.stableMessageIdMap[n]??s??`run-${n}`),this.stableMessageIdMap[n]??=s)),s!==t.id&&(t.id=s,t.lc_kwargs.id=s),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,n,r,s,a,i,o){i&&(!a||!a.includes(_O)&&!a.includes("nostream"))&&(this.metadatas[n]=[i.langgraph_checkpoint_ns.split("|"),{tags:a,name:o,...i}])}handleLLMNewToken(e,t,n,r,s,a){const i=a?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(wx(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new mt({content:e}),n))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){const n=e.generations?.[0]?.[0];Ie(n?.message)&&this._emit(this.metadatas[t],n?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,n,r,s,a,i,o){if(a!==void 0&&o===a.langgraph_node&&(s===void 0||!s.includes(ve))&&(this.metadatas[n]=[a.langgraph_checkpoint_ns.split("|"),{tags:s,name:o,...a}],typeof t=="object")){for(const c of Object.values(t))if((Ie(c)||bs(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(const l of c)(Ie(l)||bs(l))&&l.id!==void 0&&(this.seen[l.id]=l)}}handleChainEnd(e,t){const n=this.metadatas[t];if(delete this.metadatas[t],n!==void 0){if(Ie(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(const r of e)Ie(r)&&this._emit(n,r,t,!0);else if(e!=null&&typeof e=="object"){for(const r of Object.values(e))if(Ie(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(const s of r)Ie(s)&&this._emit(n,s,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};const bx=500,Sx=2,Tx=128e3,Ex=3,Cx=[400,401,402,403,404,405,406,407,409],Ax=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e.name==="GraphValueError"||e?.code==="ECONNABORTED")return!1;const t=e?.response?.status??e?.status;return!(t&&Cx.includes(+t)||e?.error?.code==="insufficient_quota")};async function Ig(e,t,n,r){const s=e.retry_policy??t;let a=s!==void 0?s.initialInterval??bx:0,i=0,o,c,{config:l}=e;for(n&&(l=Nt(l,n)),l={...l,signal:r};!r?.aborted;){e.writes.splice(0,e.writes.length),o=void 0;try{c=await e.proc.invoke(e.input,l);break}catch(u){if(o=u,o.pregelTaskId=e.id,dO(o)){const f=l?.configurable?.checkpoint_ns,y=o.command;if(y.graph===f){for(const S of e.writers)await S.invoke(y,l);o=void 0;break}else if(y.graph===be.PARENT){const S=CO(f);o.command=new be({...o.command,graph:S})}}if(Aa(o)||s===void 0||(i+=1,i>=(s.maxAttempts??Ex))||!(s.retryOn??Ax)(o))break;a=Math.min(s.maxInterval??Tx,a*(s.backoffFactor??Sx));const h=s.jitter?Math.floor(a+Math.random()*1e3):a;await new Promise(f=>setTimeout(f,h));const p=o.name??o.constructor.unminifiable_name??o.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${a.toFixed(2)}ms (attempt ${i}) after ${p}: ${o}`),l=Nt(l,{[gn]:!0})}}return{task:e,result:c,error:o,signalAborted:r?.aborted}}const Oc=Symbol.for("promiseAdded");function kx(){const e={next:()=>{},wait:Promise.resolve(Oc)};function t(n){e.next=()=>{e.wait=new Promise(t),n(Oc)}}return e.wait=new Promise(t),e}var Ox=class{nodeFinished;loop;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){const{timeout:t,retryPolicy:n,onStepWrite:r,maxConcurrency:s}=e,a=new Set;let i;const o=new AbortController,c=o.signal,l=t?AbortSignal.timeout(t):void 0,u=Object.values(this.loop.tasks).filter(f=>f.writes.length===0),{signals:d,disposeCombinedSignal:h}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:l,signal:e.signal}),p=this._executeTasksWithRetry(u,{signals:d,retryPolicy:n,maxConcurrency:s});for await(const{task:f,error:y,signalAborted:S}of p)this._commit(f,y),Bn(y)||Aa(y)&&!Bn(i)?i=y:y&&(a.size===0||!S)&&(o.abort(),a.add(y));if(h?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(f=>f.writes).flat()),a.size===1)throw Array.from(a)[0];if(a.size>1)throw new AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(Bn(i)||Aa(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:n}){const r=this.loop.config.configurable?.[Cd]??{},s=r.externalAbortSignal??n,a=t??r.timeoutAbortSignal,{signal:i,dispose:o}=ii(s,a,e),c={externalAbortSignal:s,timeoutAbortSignal:a,composedAbortSignal:i};return this.loop.config=Nt(this.loop.config,{[Cd]:c}),{signals:c,disposeCombinedSignal:o}}async*_executeTasksWithRetry(e,t){const{retryPolicy:n,maxConcurrency:r,signals:s}=t??{},a=kx(),i={},o={executingTasksMap:i,barrier:a,retryPolicy:n,scheduleTask:async(h,p,f)=>this.loop.acceptPush(h,p,f)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let c=0,l;const u=ii(s?.externalAbortSignal,s?.timeoutAbortSignal),d=u.signal?new Promise((h,p)=>{l=()=>p(new Error("Abort")),u.signal?.addEventListener("abort",l,{once:!0})}):void 0;for(;(c===0||Object.keys(i).length>0)&&e.length;){for(;Object.values(i).length<(r??e.length)&&c<e.length;c+=1){const p=e[c];i[p.id]=Ig(p,n,{[Gl]:Pg?.bind(o,this,p)},s?.composedAbortSignal).catch(f=>({task:p,error:f,signalAborted:s?.composedAbortSignal?.aborted}))}const h=await Promise.race([...Object.values(i),...d?[d]:[],a.wait]);h!==Oc&&(yield h,l!=null&&(u.signal?.removeEventListener("abort",l),u.dispose?.()),delete i[h.task.id])}}_commit(e,t){if(t!==void 0)if(Bn(t)){if(t.interrupts.length){const n=t.interrupts.map(s=>[Y,s]),r=e.writes.filter(s=>s[0]===rt);r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else Aa(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[tt,{message:t.message,name:t.name}]]);else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes(ve))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([Wl,null]),this.loop.putWrites(e.id,e.writes)}};async function Pg(e,t,n,r,s,a={}){const i=t.config?.configurable?.[Cn];if(!i)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);const o=i.callCounter;i.callCounter+=1;const c=new XO({func:n,name:r,input:s,cache:a.cache,retry:a.retry,callbacks:a.callbacks}),l=await this.scheduleTask(t,o,c);if(!l)return;const u=this.executingTasksMap[l.id];if(u!==void 0)return u;if(l.writes.length>0){const d=l.writes.filter(([p])=>p===qr),h=l.writes.filter(([p])=>p===tt);if(d.length>0){if(d.length===1)return Promise.resolve(d[0][1]);throw new Error(`BUG: multiple returns found for task ${l.name}__${l.id}`)}if(h.length>0){if(h.length===1){const p=h[0][1],f=p instanceof Error?p:new Error(String(p));return Promise.reject(f)}throw new Error(`BUG: multiple errors found for task ${l.name}__${l.id}`)}return}else{const d=Ig(l,a.retry,{[Gl]:Pg.bind(this,e,l)});return this.executingTasksMap[l.id]=d,this.barrier.next(),d.then(({result:h,error:p})=>p?Promise.reject(p):h)}}var Zt=class extends Error{constructor(e){super(e),this.name="GraphValidationError"}};function xx({nodes:e,channels:t,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:a,interruptBeforeNodes:i}){if(!t)throw new Zt("Channels not provided");const o=new Set,c=new Set;for(const[l,u]of Object.entries(e)){if(l===Y)throw new Zt(`"Node name ${Y} is reserved"`);if(u.constructor===js)u.triggers.forEach(d=>o.add(d));else throw new Zt(`Invalid node type ${typeof u}, expected PregelNode`)}for(const l of o)if(!(l in t))throw new Zt(`Subscribed channel '${String(l)}' not in channels`);if(Array.isArray(n)){if(n.every(l=>!o.has(l)))throw new Zt(`None of the input channels ${n} are subscribed to by any node`)}else if(!o.has(n))throw new Zt(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(l=>c.add(l)):c.add(r),s&&!Array.isArray(s)?c.add(s):Array.isArray(s)&&s.forEach(l=>c.add(l));for(const l of c)if(!(l in t))throw new Zt(`Output channel '${String(l)}' not in channels`);if(a&&a!=="*"){for(const l of a)if(!(l in e))throw new Zt(`Node ${String(l)} not in nodes`)}if(i&&i!=="*"){for(const l of i)if(!(l in e))throw new Zt(`Node ${String(l)} not in nodes`)}}function $d(e,t){if(Array.isArray(e)){for(const n of e)if(!(n in t))throw new Error(`Key ${String(n)} not found in channels`)}else if(!(e in t))throw new Error(`Key ${String(e)} not found in channels`)}var Ix=class Ng extends ir{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(t){super(),this.unique=t?.unique??this.unique,this.accumulate=t?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){const n=new Ng({unique:this.unique,accumulate:this.accumulate});return typeof t<"u"&&(n.seen=new Set(t[0]),n.values=t[1]),n}update(t){let n=!1;this.accumulate||(n=this.values.length>0,this.values=[]);const r=t.flat();if(r.length>0)if(this.unique)for(const s of r)this.seen.has(s)||(n=!0,this.seen.add(s),this.values.push(s));else n=!0,this.values.push(...r);return n}get(){if(this.values.length===0)throw new Le;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},Px=class{static subscribeTo(e,t){const{key:n,tags:r}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&n!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;typeof e=="string"?n?s={[n]:e}:s=[e]:s=Object.fromEntries(e.map(i=>[i,i]));const a=Array.isArray(e)?e:[e];return new js({channels:s,triggers:a,tags:r})}static writeTo(e,t){const n=[];for(const r of e)n.push({channel:r,value:Jn,skipNone:!1});for(const[r,s]of Object.entries(t??{}))J.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:Jn,skipNone:!0,mapper:$e(s)}):n.push({channel:r,value:s,skipNone:!1});return new Je(n)}},Nx=class extends J{lc_namespace=["langgraph","pregel"];invoke(e,t){throw new Error("Not implemented")}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},Mx=class extends Nx{static lc_name(){return"LangGraph"}lc_namespace=["langgraph","pregel"];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=["values"];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,vt in this.channels&&"lc_graph_name"in this.channels[vt]&&this.channels[vt].lc_graph_name!=="Topic")throw new Error(`Channel '${vt}' is reserved and cannot be used in the graph.`);this.channels[vt]=new Ix({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.autoValidate&&this.validate()}withConfig(e){const t=pt(this.config,e);return new this.constructor({...this,config:t})}validate(){xx({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(const[e,t]of Object.entries(this.nodes))for(const n of t.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(e);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(const[n,r]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(n))continue;const s=r.subgraphs?.length?r.subgraphs:[r.bound];for(const a of s){const i=Tg(a);if(i!==void 0){if(n===e){yield[n,i];return}if(e===void 0&&(yield[n,i]),t){let o=e;e!==void 0&&(o=e.slice(n.length+1));for(const[c,l]of i.getSubgraphs(o,t))yield[`${n}${ke}${c}`,l]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};const s=ni(this.channels,t.checkpoint);if(t.pendingWrites?.length){const d=t.pendingWrites.filter(([h,p])=>h===bt).map(([h,p,f])=>[String(p),f]);d.length>0&&ut(t.checkpoint,s,[{name:Yt,writes:d,triggers:[]}],void 0,this.triggerToNodes)}const a=Object.values(vr(t.checkpoint,t.pendingWrites,this.nodes,s,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),i=await yn(this.getSubgraphsAsync()),o=t.config.configurable?.checkpoint_ns??"",c={};for(const d of a){const h=i.find(([f])=>f===d.name);if(!h)continue;let p=`${String(d.name)}${an}${d.id}`;if(o&&(p=`${o}${ke}${p}`),n===void 0){const f={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:p}};c[d.id]=f}else{const f={configurable:{[_e]:n,thread_id:t.config.configurable?.thread_id,checkpoint_ns:p}},y=h[1];c[d.id]=await y.getState(f,{subgraphs:!0})}}if(r&&t.pendingWrites?.length){const d=Object.fromEntries(a.map(p=>[p.id,p]));for(const[p,f,y]of t.pendingWrites)[tt,Y,wa].includes(f)||p in d&&d[p].writes.push([String(f),y]);const h=a.filter(p=>p.writes.length>0);h.length>0&&ut(t.checkpoint,s,h,void 0,this.triggerToNodes)}let l=t?.metadata;l&&t?.config?.configurable?.thread_id&&(l={...l,thread_id:t.config.configurable.thread_id});const u=a.filter(d=>d.writes.length===0).map(d=>d.name);return{values:Yn(s,this.streamChannelsAsIs),next:u,tasks:Ag(a,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:$n(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){const n=e.configurable?.[_e]??this.checkpointer;if(!n)throw new Ca("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=e.configurable?.checkpoint_ns??"";if(r!==""&&e.configurable?.[_e]===void 0){const o=_o(r);for await(const[c,l]of this.getSubgraphsAsync(o,!0))if(c===o)return await l.getState(dr(e,{[_e]:n}),{subgraphs:t?.subgraphs});throw new Error(`Subgraph with namespace "${o}" not found.`)}const s=pt(this.config,e),a=await n.getTuple(e);return await this._prepareStateSnapshot({config:s,saved:a,subgraphCheckpointer:t?.subgraphs?n:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){const n=e.configurable?.[_e]??this.checkpointer;if(!n)throw new Ca("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=e.configurable?.checkpoint_ns??"";if(r!==""&&e.configurable?.[_e]===void 0){const a=_o(r);for await(const[i,o]of this.getSubgraphsAsync(a,!0))if(i===a){yield*o.getStateHistory(dr(e,{[_e]:n}),t);return}throw new Error(`Subgraph with namespace "${a}" not found.`)}const s=pt(this.config,e,{configurable:{checkpoint_ns:r}});for await(const a of n.list(s,t))yield this._prepareStateSnapshot({config:a.config,saved:a})}async bulkUpdateState(e,t){const n=e.configurable?.[_e]??this.checkpointer;if(!n)throw new Ca("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(t.length===0)throw new Error("No supersteps provided");if(t.some(i=>i.updates.length===0))throw new Error("No updates provided");const r=e.configurable?.checkpoint_ns??"";if(r!==""&&e.configurable?.[_e]===void 0){const i=_o(r);for await(const[,o]of this.getSubgraphsAsync(i,!0))return await o.bulkUpdateState(dr(e,{[_e]:n}),t);throw new Error(`Subgraph "${i}" not found`)}const s=async(i,o)=>{const c=this.config?pt(this.config,i):i,l=await n.getTuple(c),u=l!==void 0?ti(l.checkpoint):eg(),d={...l?.checkpoint.channel_versions},h=l?.metadata?.step??-1;let p=dr(c,{checkpoint_ns:c.configurable?.checkpoint_ns??""}),f=c.metadata??{};l?.config.configurable&&(p=dr(c,l.config.configurable),f={...l.metadata,...f});const{values:y,asNode:S}=o[0];if(y==null&&S===void 0){if(o.length>1)throw new de("Cannot create empty checkpoint with multiple updates");const k=await n.put(p,Un(u,void 0,h),{source:"update",step:h+1,parents:l?.metadata?.parents??{}},{});return $n(k,l?l.metadata:void 0)}const b=ni(this.channels,u);if(y===null&&S===B){if(o.length>1)throw new de("Cannot apply multiple updates when clearing state");if(l){const g=vr(u,l.pendingWrites||[],this.nodes,b,l.config,!0,{step:(l.metadata?.step??-1)+1,checkpointer:n,store:this.store}),N=(l.pendingWrites||[]).filter(x=>x[0]===bt).map(x=>x.slice(1));N.length>0&&ut(u,b,[{name:Yt,writes:N,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[x,M,z]of l.pendingWrites||[])[tt,Y,wa].includes(M)||x in g&&g[x].writes.push([M,z]);ut(u,b,Object.values(g),n.getNextVersion.bind(n),this.triggerToNodes)}const k=await n.put(p,Un(u,b,h),{...f,source:"update",step:h+1,parents:l?.metadata?.parents??{}},Na(d,u.channel_versions));return $n(k,l?l.metadata:void 0)}if(S===mO){if(o.length>1)throw new de("Cannot copy checkpoint with multiple updates");if(l==null)throw new de("Cannot copy a non-existent checkpoint");const k=x=>!Array.isArray(x)||x.length===0?!1:x.every(M=>Array.isArray(M)&&M.length===2),g=Un(u,void 0,h),N=await n.put(l.parentConfig??dr(l.config,{checkpoint_id:void 0}),g,{source:"fork",step:h+1,parents:l.metadata?.parents??{}},{});if(k(y)){const x=vr(g,l.pendingWrites,this.nodes,b,N,!1,{step:h+2}),M=Object.values(x).reduce((ce,{name:he,id:cr})=>(ce[he]??=[],ce[he].push({id:cr}),ce),{}),z=y.reduce((ce,he)=>{const[cr,q]=he;ce[q]??=[];const Mi=ce[q].length,ss=M[q]?.[Mi]?.id;return ce[q].push({values:cr,asNode:q,taskId:ss}),ce},{});return s($n(N,l.metadata),Object.values(z).flat())}return $n(N,l.metadata)}if(S===Yt){if(o.length>1)throw new de("Cannot apply multiple updates when updating as input");const k=await yn(Eg(this.inputChannels,y));if(k.length===0)throw new de(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);ut(u,b,[{name:Yt,writes:k,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const g=l?.metadata?.step!=null?l.metadata.step+1:-1,N=await n.put(p,Un(u,b,g),{source:"input",step:g,parents:l?.metadata?.parents??{}},Na(d,u.channel_versions));return await n.putWrites(N,k,yr(Yt,u.id)),$n(N,l?l.metadata:void 0)}if(c.configurable?.checkpoint_id===void 0&&l?.pendingWrites!==void 0&&l.pendingWrites.length>0){const k=vr(u,l.pendingWrites,this.nodes,b,l.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(l.metadata?.step??-1)+1}),g=(l.pendingWrites??[]).filter(x=>x[0]===bt).map(x=>x.slice(1));g.length>0&&ut(l.checkpoint,b,[{name:Yt,writes:g,triggers:[]}],void 0,this.triggerToNodes);for(const[x,M,z]of l.pendingWrites)[tt,Y,wa].includes(M)||k[x]===void 0||k[x].writes.push([M,z]);const N=Object.values(k).filter(x=>x.writes.length>0);N.length>0&&ut(u,b,N,void 0,this.triggerToNodes)}const v=Object.values(u.versions_seen).map(k=>Object.values(k)).flat().find(k=>!!k),w=[];if(o.length===1){let{values:k,asNode:g,taskId:N}=o[0];if(g===void 0&&Object.keys(this.nodes).length===1)[g]=Object.keys(this.nodes);else if(g===void 0&&v===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(g=this.inputChannels);else if(g===void 0){const x=Object.entries(u.versions_seen).map(([M,z])=>Object.values(z).map(ce=>[ce,M])).flat().filter(([M,z])=>z!==Y).sort(([M],[z])=>tg(M,z));x&&(x.length===1?g=x[0][1]:x[x.length-1][0]!==x[x.length-2][0]&&(g=x[x.length-1][1]))}if(g===void 0)throw new de('Ambiguous update, specify "asNode"');w.push({values:k,asNode:g,taskId:N})}else for(const{asNode:k,values:g,taskId:N}of o){if(k==null)throw new de('"asNode" is required when applying multiple updates');w.push({values:g,asNode:k,taskId:N})}const E=[];for(const{asNode:k,values:g,taskId:N}of w){if(this.nodes[k]===void 0)throw new de(`Node "${k.toString()}" does not exist`);const x=this.nodes[k].getWriters();if(!x.length)throw new de(`No writers found for node "${k.toString()}"`);E.push({name:k,input:g,proc:x.length>1?Et.from(x,{omitSequenceTags:!0}):x[0],writes:[],triggers:[Y],id:N??yr(Y,u.id),writers:[]})}for(const k of E)await k.proc.invoke(k.input,ne({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[En]:g=>k.writes.push(...g),[Wn]:(g,N=!1)=>Ma(u,b,k,g,N)}}));for(const k of E){const g=k.writes.filter(N=>N[0]!==dt);l!==void 0&&g.length>0&&await n.putWrites(p,g,k.id)}ut(u,b,E,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const A=Na(d,u.channel_versions),I=await n.put(p,Un(u,b,h+1),{source:"update",step:h+1,parents:l?.metadata?.parents??{}},A);for(const k of E){const g=k.writes.filter(N=>N[0]===dt);g.length>0&&await n.putWrites(I,g,k.id)}return $n(I,l?l.metadata:void 0)};let a=e;for(const{updates:i}of t)a=await s(a,i);return a}async updateState(e,t,n){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:n}]}])}_defaults(e){const{debug:t,streamMode:n,inputKeys:r,outputKeys:s,interruptAfter:a,interruptBefore:i,...o}=e;let c=!0;const l=t!==void 0?t:this.debug;let u=s;u===void 0?u=this.streamChannelsAsIs:$d(u,this.channels);let d=r;d===void 0?d=this.inputChannels:$d(d,this.channels);const h=i??this.interruptBefore??[],p=a??this.interruptAfter??[];let f;n!==void 0?(f=Array.isArray(n)?n:[n],c=typeof n=="string"):(e.configurable?.[gs]!==void 0?f=["values"]:f=this.streamMode,c=!0);let y;if(this.checkpointer===!1)y=void 0;else if(e!==void 0&&e.configurable?.[_e]!==void 0)y=e.configurable[_e];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");y=this.checkpointer}const S=e.store??this.store,b=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");const v=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),w=e.durability??v??e?.configurable?.[dg]??"async";return[l,f,d,u,o,h,p,y,S,c,b,w]}async stream(e,t){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...t,signal:ii(t?.signal,n.signal).signal},s=await super.stream(e,r);return new Nd(t?.encoding==="text/event-stream"?fx(s):s,n)}streamEvents(e,t,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...t,callbacks:YO(this.config?.callbacks,t?.callbacks),signal:ii(t?.signal,r.signal).signal};return new Nd(super.streamEvents(e,s,n),r)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){const n="version"in(t??{})?void 0:t?.encoding??void 0,r=t?.subgraphs,s=pg(this.config,t);if(s.recursionLimit===void 0||s.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&s.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const a=await this._validateInput(e),{runId:i,...o}=s,[c,l,,u,d,h,p,f,y,S,b,v]=this._defaults(o);typeof d.context<"u"?d.context=await this._validateContext(d.context):d.configurable=await this._validateContext(d.configurable);const w=new Og({modes:new Set(l)});if(this.checkpointer===!0){d.configurable??={};const M=d.configurable[Bt]??"";d.configurable[Bt]=M.split(ke).map(z=>z.split(an)[0]).join(ke)}if(l.includes("messages")){const M=new vx(ce=>w.push(ce)),{callbacks:z}=d;if(z===void 0)d.callbacks=[M];else if(Array.isArray(z))d.callbacks=z.concat(M);else{const ce=z.copy();ce.addHandler(M,!0),d.callbacks=ce}}d.writer??=M=>{if(!l.includes("custom"))return;const z=EO()?.configurable?.[Bt]?.split(ke).slice(0,-1);w.push([z??[],"custom",M])},d.interrupt??=this.userInterrupt??bg;const A=await(await nt(d))?.handleChainStart(this.toJSON(),qO(e,"input"),i,void 0,void 0,void 0,d?.runName??this.getName()),I=Hl(this.channels);let k,g;const x=(async()=>{try{k=await _x.initialize({input:a,config:d,checkpointer:f,nodes:this.nodes,channelSpecs:I,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:y,cache:b,stream:w,interruptAfter:p,interruptBefore:h,manager:A,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:v});const M=new Ox({loop:k,nodeFinished:d.configurable?.[yO]});t?.subgraphs&&(k.config.configurable={...k.config.configurable,[ri]:k.stream}),await this._runLoop({loop:k,runner:M,debug:c,config:d}),v==="sync"&&await Promise.all(k?.checkpointerPromises??[])}catch(M){g=M}finally{try{k&&(await k.store?.stop(),await k.cache?.stop()),await Promise.all(k?.checkpointerPromises??[])}catch(M){g=g??M}g?w.error(g):w.close()}})();try{for await(const M of w){if(M===void 0)throw new Error("Data structure error.");const[z,ce,he]=M;if(l.includes(ce)){if(n==="text/event-stream"){r?yield[z,ce,he]:yield[null,ce,he];continue}r&&!S?yield[z,ce,he]:S?r?yield[z,he]:yield he:yield[ce,he]}}}catch(M){throw await A?.handleChainError(g),M}finally{await x}await A?.handleChainEnd(k?.output??{},i,void 0,void 0,void 0)}async invoke(e,t){const n=t?.streamMode??"values",r={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},s=[],a=await this.stream(e,r),i=[];let o;for await(const c of a)n==="values"?hg(c)?i.push(c[Y]):o=c:s.push(c);if(n==="values"){if(i.length>0){const c=i.flat(1);if(o==null)return{[Y]:c};if(typeof o=="object")return{...o,[Y]:c}}return o}return s}async _runLoop(e){const{loop:t,runner:n,debug:r,config:s}=e;let a;try{for(;await t.tick({inputKeys:this.inputChannels});){for(const{task:i}of await t._matchCachedWrites())t._outputWrites(i.id,i.writes,!0);r&&ux(t.checkpointMetadata.step,t.channels,this.streamChannelsList),r&&kg(t.step,Object.values(t.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,o)=>{r&&dx(i,o,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(t.status==="out_of_steps")throw new uO([`Recursion limit of ${s.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(i){if(a=i,!await t.finishAndHandleError(a))throw i}finally{a===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}},Xr=class Mg extends ir{lc_graph_name="EphemeralValue";guard;value=[];constructor(t=!0){super(),this.guard=t}fromCheckpoint(t){const n=new Mg(this.guard);return typeof t<"u"&&(n.value=[t]),n}update(t){if(t.length===0){const n=this.value.length>0;return this.value=[],n}if(t.length!==1&&this.guard)throw new de("EphemeralValue can only receive one value per step.");return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new Le;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Le;return this.value[0]}isAvailable(){return this.value.length!==0}},Rg=class{path;ends;constructor(e){J.isRunnable(e.path)?this.path=e.path:this.path=$e(e.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((t,n)=>(t[n]=n,t),{}):e.pathMap}run(e,t){return Je.registerWriter(new or({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,e,t)}catch(s){throw s.name===ag.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
205
205
  NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(e,t,n,r){let s=await this.path.invoke(r?r(t):e,t);Array.isArray(s)||(s=[s]);let a;if(this.ends?a=s.map(o=>gt(o)?o:this.ends[o]):a=s,a.some(o=>!o))throw new Error("Branch condition returned unknown or null destination");if(a.filter(gt).some(o=>o.node===B))throw new de("Cannot send a packet to the END node");return await n(a,t)??e}},Rx=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(r){return r.length>=1&&typeof r[0]!="string"}const n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,a]of n){for(const o of[ke,an])if(r.includes(o))throw new Error(`"${o}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===B)throw new Error(`Node \`${r}\` is reserved.`);const i=$e(s);this.nodes[r]={runnable:i,metadata:a?.metadata,subgraphs:Kl(i)?[i]:a?.subgraphs,ends:a?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),e===B)throw new Error("END cannot be a start node");if(t===ie)throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([n])=>n===e)&&!("channels"in this))throw new Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,n){const r=typeof e=="object"?e:{source:e,path:t,pathMap:n};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!J.isRunnable(r.path)){const a=Array.isArray(r.pathMap)?r.pathMap.join(","):Object.keys(r.pathMap??{}).join(",");r.path=$e(r.path).withConfig({runName:`Branch<${r.source}${a!==""?`,${a}`:""}>`.slice(0,63)})}const s=r.path.getName()==="RunnableLambda"?"condition":r.path.getName();if(this.branches[r.source]&&this.branches[r.source][s])throw new Error(`Condition \`${s}\` already present for node \`${e}\``);return this.branches[r.source]??={},this.branches[r.source][s]=new Rg(r),this}setEntryPoint(e){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(ie,e)}setFinishPoint(e){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(e,B)}compile({checkpointer:e,interruptBefore:t,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]]);const s=new $g({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[ie]:new Xr,[B]:new Xr},inputChannels:ie,outputChannels:B,streamChannels:[],streamMode:"values",name:r});for(const[a,i]of Object.entries(this.nodes))s.attachNode(a,i);for(const[a,i]of this.edges)s.attachEdge(a,i);for(const[a,i]of Object.entries(this.branches))for(const[o,c]of Object.entries(i))s.attachBranch(a,o,c);return s.validate()}validate(e){const t=new Set([...this.allEdges].map(([r,s])=>r));for(const[r]of Object.entries(this.branches))t.add(r);for(const r of t)if(r!==ie&&!(r in this.nodes))throw new Error(`Found edge starting at unknown node \`${r}\``);const n=new Set([...this.allEdges].map(([r,s])=>s));for(const[r,s]of Object.entries(this.branches))for(const a of Object.values(s))if(a.ends!=null)for(const i of Object.values(a.ends))n.add(i);else{n.add(B);for(const i of Object.keys(this.nodes))i!==r&&n.add(i)}for(const r of Object.values(this.nodes))for(const s of r.ends??[])n.add(s);for(const r of Object.keys(this.nodes))if(!n.has(r))throw new hO([`Node \`${r}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join(`
206
- `),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!==B&&!(r in this.nodes))throw new Error(`Found edge ending at unknown node \`${r}\``);if(e){for(const r of e)if(!(r in this.nodes))throw new Error(`Interrupt node \`${r}\` is not present`)}this.compiled=!0}},$g=class extends Mx{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new Xr,this.nodes[e]=new js({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new Je([{channel:e,value:Jn}],[ve])),this.streamChannels.push(e)}attachEdge(e,t){if(t===B){if(e===ie)throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new Je([{channel:B,value:Jn}],[ve]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e===ie&&!this.nodes[ie]&&(this.nodes[ie]=Px.subscribeTo(ie,{tags:[ve]})),this.nodes[e].pipe(n.run(s=>{const a=s.map(i=>gt(i)?i:{channel:i===B?B:`branch:${e}:${t}:${i}`,value:Jn});return new Je(a,[ve])}));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const s of r)if(s!==B){const a=`branch:${e}:${t}:${s}`;this.channels[a]=new Xr,this.nodes[s].triggers.push(a),this.nodes[s].channels.push(a)}}async getGraphAsync(e){const t=e?.xray,n=new Os,r={[ie]:n.addNode({schema:sa()},ie)},s={};let a={};t&&(a=Object.fromEntries((await yn(this.getSubgraphsAsync())).filter(c=>Ld(c[1]))));function i(c,l,u,d=!1){if(l===B&&s[B]===void 0&&(s[B]=n.addNode({schema:sa()},B)),r[c]!==void 0){if(s[l]===void 0)throw new Error(`End node ${l} not found!`);return n.addEdge(r[c],s[l],u!==l?u:void 0,d)}}for(const[c,l]of Object.entries(this.builder.nodes)){const u=je(c),d=l.runnable,h=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?h.__interrupt="before,after":this.interruptBefore?.includes(c)?h.__interrupt="before":this.interruptAfter?.includes(c)&&(h.__interrupt="after"),t){const p=typeof t=="number"?t-1:t,f=a[c]!==void 0?await a[c].getGraphAsync({...e,xray:p}):d.getGraph(e);if(f.trimFirstNode(),f.trimLastNode(),Object.keys(f.nodes).length>1){let b=function(w){return w?w.lc_runnable:!1},v=function(w,E){if(w!==void 0&&!br(w))return w;if(b(E))try{let A=E.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return E.getName()}else return E.name??"UnknownSchema"};const[y,S]=n.extend(f,u);if(y===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:v(S.id,S.data),...S}),s[u]={name:v(y.id,y.data),...y}}else{const y=n.addNode(d,u,h);r[u]=y,s[u]=y}}else{const p=n.addNode(d,u,h);r[u]=p,s[u]=p}}const o=[...this.builder.allEdges].sort(([c],[l])=>c<l?-1:l>c?1:0);for(const[c,l]of o)i(je(c),je(l));for(const[c,l]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[je(d),je(d)])),[B]:B};for(const d of Object.values(l)){let h;d.ends!==void 0?h=d.ends:h=u;for(const[p,f]of Object.entries(h))i(je(c),je(f),p,!0)}}for(const[c,l]of Object.entries(this.builder.nodes))if(l.ends!==void 0)for(const u of l.ends)i(je(c),je(u),void 0,!0);return n}getGraph(e){const t=e?.xray,n=new Os,r={[ie]:n.addNode({schema:sa()},ie)},s={};let a={};t&&(a=Object.fromEntries(ds(this.getSubgraphs()).filter(c=>Ld(c[1]))));function i(c,l,u,d=!1){return l===B&&s[B]===void 0&&(s[B]=n.addNode({schema:sa()},B)),n.addEdge(r[c],s[l],u!==l?u:void 0,d)}for(const[c,l]of Object.entries(this.builder.nodes)){const u=je(c),d=l.runnable,h=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?h.__interrupt="before,after":this.interruptBefore?.includes(c)?h.__interrupt="before":this.interruptAfter?.includes(c)&&(h.__interrupt="after"),t){const p=typeof t=="number"?t-1:t,f=a[c]!==void 0?a[c].getGraph({...e,xray:p}):d.getGraph(e);if(f.trimFirstNode(),f.trimLastNode(),Object.keys(f.nodes).length>1){let b=function(w){return w?w.lc_runnable:!1},v=function(w,E){if(w!==void 0&&!br(w))return w;if(b(E))try{let A=E.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return E.getName()}else return E.name??"UnknownSchema"};const[y,S]=n.extend(f,u);if(y===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:v(S.id,S.data),...S}),s[u]={name:v(y.id,y.data),...y}}else{const y=n.addNode(d,u,h);r[u]=y,s[u]=y}}else{const p=n.addNode(d,u,h);r[u]=p,s[u]=p}}const o=[...this.builder.allEdges].sort(([c],[l])=>c<l?-1:l>c?1:0);for(const[c,l]of o)i(je(c),je(l));for(const[c,l]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[je(d),je(d)])),[B]:B};for(const d of Object.values(l)){let h;d.ends!==void 0?h=d.ends:h=u;for(const[p,f]of Object.entries(h))i(je(c),je(f),p,!0)}}return n}};function Ld(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function je(e){return e==="subgraph"?`"${e}"`:e}const zn=(e,t)=>e.size===t.size&&[...e].every(n=>t.has(n));var $x=class Lg extends ir{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){const n=new Lg(this.names);return typeof t<"u"&&(n.seen=new Set(t)),n}update(t){let n=!1;for(const r of t)if(this.names.has(r))this.seen.has(r)||(this.seen.add(r),n=!0);else throw new de(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!zn(this.names,this.seen))throw new Le}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&zn(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&zn(this.names,this.seen)}},Lx=class jg extends ir{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(t){super(),this.names=t,this.seen=new Set,this.finished=!1}fromCheckpoint(t){const n=new jg(this.names);if(typeof t<"u"){const[r,s]=t;n.seen=new Set(r),n.finished=s}return n}update(t){let n=!1;for(const r of t)if(this.names.has(r)&&!this.seen.has(r))this.seen.add(r),n=!0;else if(!this.names.has(r))throw new de(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!zn(this.names,this.seen))throw new Le}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&zn(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&zn(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&zn(this.names,this.seen)}};const jx="lg:";var Dx=class{_map=new WeakMap;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){const n=this.get(e);this._map.set(e,t(n))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){const t={},n=Cs(e);for(const[r,s]of Object.entries(n)){const a=this.get(s);a?.reducer?t[r]=new wc(a.reducer.fn,a.default):t[r]=new Vl}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;const n=Object.entries(t).filter(([,a])=>a===!0).sort(([a],[i])=>a.localeCompare(i)).map(([a,i])=>`${a}:${i}`).join("|"),r=this._extensionCache.get(n)??new WeakMap;if(r.has(e))return r.get(e);let s=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){const a=Object.entries(Cs(e)).map(([i,o])=>{const c=this.get(o);let l=t.withReducerSchema?c?.reducer?.schema??o:o;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){const u=Vr(l)??Vr(o),d=JSON.stringify({...c.jsonSchemaExtra,description:u});l=l.describe(`${jx}${d}`)}return[i,l]});s=up(e,Object.fromEntries(a)),Se(s)&&(s._def.unknownKeys="strip")}return t.asPartial&&(s=sl(s)),r.set(e,s),this._extensionCache.set(n,r),s}};const Fs=new Dx;function Qr(e,t){if(t.reducer&&!t.default){const n=_i(e);n!=null&&(t.default=n)}if(t.reducer){const n=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return Fs.extend(n,()=>t),n}else return Fs.extend(e,()=>t),e}const Qt="__root__",xc=Symbol.for("langgraph.state.partial");var Ux=class extends Rx{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=Fs;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){if(super(),Wx(e)){const r=this._metaRegistry.getChannelsForSchema(e.state),s=e.input!=null?this._metaRegistry.getChannelsForSchema(e.input):r,a=e.output!=null?this._metaRegistry.getChannelsForSchema(e.output):r;this._schemaDefinition=r,this._schemaRuntimeDefinition=e.state,this._inputDefinition=s,this._inputRuntimeDefinition=e.input??xc,this._outputDefinition=a,this._outputRuntimeDefinition=e.output??e.state}else if(et(e)){const r=this._metaRegistry.getChannelsForSchema(e);this._schemaDefinition=r,this._schemaRuntimeDefinition=e,this._inputDefinition=r,this._inputRuntimeDefinition=xc,this._outputDefinition=r,this._outputRuntimeDefinition=e}else if(Gx(e))this._schemaDefinition=e.input.spec,this._inputDefinition=e.input.spec,this._outputDefinition=e.output.spec;else if(Vx(e))this._schemaDefinition=e.stateSchema.spec,this._inputDefinition=e.input?.spec??this._schemaDefinition,this._outputDefinition=e.output?.spec??this._schemaDefinition;else if(zx(e)||jd(e)){const r=jd(e)?e.spec:e;this._schemaDefinition=r}else if(Hx(e)){const r=Fx(e.channels);this._schemaDefinition=r}else throw new Error("Invalid StateGraph input. Make sure to pass a valid Annotation.Root or Zod schema.");this._inputDefinition??=this._schemaDefinition,this._outputDefinition??=this._schemaDefinition,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition);function n(r){return typeof r=="object"&&r!=null&&!("spec"in r)&&!et(r)}n(t)?(et(t.context)&&(this._configRuntimeSchema=t.context),this._interrupt=t.interrupt,this._writer=t.writer):et(t)&&(this._configRuntimeSchema=t)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(n=>[n,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(const[t,n]of Object.entries(e)){let r;if(typeof n=="function"?r=n():r=n,this.channels[t]!==void 0){if(this.channels[t]!==r&&r.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=r}}}addNode(...e){function t(r){return r.length>=1&&typeof r[0]!="string"}const n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([r,s])=>[r,s]):[[e[0],e[1],e[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,a]of n){if(r in this.channels)throw new Error(`${r} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const u of[ke,an])if(r.includes(u))throw new Error(`"${u}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===B||r===ie)throw new Error(`Node \`${r}\` is reserved.`);let i=this._schemaDefinition;a?.input!==void 0&&(et(a.input)?i=this._metaRegistry.getChannelsForSchema(a.input):a.input.spec!==void 0&&(i=a.input.spec)),i!==void 0&&this._addSchema(i);let o;J.isRunnable(s)?o=s:typeof s=="function"?o=new or({func:s,name:r,trace:!1}):o=$e(s);let c=a?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);const l={runnable:o,retryPolicy:a?.retryPolicy,cachePolicy:c,metadata:a?.metadata,input:i??this._schemaDefinition,subgraphs:Kl(o)?[o]:a?.subgraphs,ends:a?.ends,defer:a?.defer};this.nodes[r]=l}return this}addEdge(e,t){if(typeof e=="string")return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(const n of e){if(n===B)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(r=>r===n))throw new Error(`Need to add a node named "${n}" first`)}if(t===B)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(n=>n===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){const t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let n;for(const[r,s,a]of t){if(r in this.nodes)throw new Error(`Node names must be unique: node with the name "${r}" already exists.`);const i=r;this.addNode(i,s,a),n!=null&&this.addEdge(n,i),n=i}return this}compile({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:s,name:a,description:i}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(s)?s:[]]);const o=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=o.length===1&&o[0]===Qt?Qt:o,l=Object.keys(this.channels),u=l.length===1&&l[0]===Qt?Qt:l,d=this._interrupt,h=new Bx({builder:this,checkpointer:e,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[ie]:new Xr},inputChannels:ie,outputChannels:c,streamChannels:u,streamMode:"updates",store:t,cache:n,name:a,description:i,userInterrupt:d});h.attachNode(ie);for(const[p,f]of Object.entries(this.nodes))h.attachNode(p,f);h.attachBranch(ie,Ad,Dd(),{withReader:!1});for(const[p]of Object.entries(this.nodes))h.attachBranch(p,Ad,Dd(),{withReader:!1});for(const[p,f]of this.edges)h.attachEdge(p,f);for(const[p,f]of this.waitingEdges)h.attachEdge(p,f);for(const[p,f]of Object.entries(this.branches))for(const[y,S]of Object.entries(f))h.attachBranch(p,y,S);return h.validate()}};function Fx(e){const t={};for(const[n,r]of Object.entries(e))t[n]=bc(r);return t}var Bx=class extends $g{description;_metaRegistry=Fs;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let n;e===ie?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([o])=>o):n=Object.keys(this.builder.channels);function r(o){if(Pe(o))return o.graph===be.PARENT?null:o._updateAsTuples();if(Array.isArray(o)&&o.length>0&&o.some(c=>Pe(c))){const c=[];for(const l of o)if(Pe(l)){if(l.graph===be.PARENT)continue;c.push(...l._updateAsTuples())}else c.push([Qt,l]);return c}else if(o!=null)return[[Qt,o]];return null}const s=e;function a(o){if(o){if(Pe(o))return o.graph===be.PARENT?null:o._updateAsTuples().filter(([c])=>n.includes(c));if(Array.isArray(o)&&o.length>0&&o.some(Pe)){const c=[];for(const l of o)if(Pe(l)){if(l.graph===be.PARENT)continue;c.push(...l._updateAsTuples().filter(([u])=>n.includes(u)))}else{const u=a(l);u&&c.push(...u??[])}return c}else{if(typeof o=="object"&&!Array.isArray(o))return Object.entries(o).filter(([c])=>n.includes(c));{const c=Array.isArray(o)?"array":typeof o;throw new de(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${c}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const i=[{value:Jn,mapper:new or({func:n.length&&n[0]===Qt?r:a,trace:!1,recurse:!1})}];if(e===ie)this.nodes[e]=new js({tags:[ve],triggers:[ie],channels:[ie],writers:[new Je(i,[ve])]});else{const o=t?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(o)).map(d=>[d,d])),l=Object.keys(c).length===1&&Qt in c,u=`branch:to:${e}`;this.channels[u]=t?.defer?new pO:new Xr(!1),this.nodes[e]=new js({triggers:[u],channels:l?Object.keys(c):c,writers:[new Je(i,[ve])],mapper:l?void 0:d=>Object.fromEntries(Object.entries(d).filter(([h])=>h in c)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:t?.cachePolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!==B){if(typeof e=="string")this.nodes[e].writers.push(new Je([{channel:`branch:to:${t}`,value:null}],[ve]));else if(Array.isArray(e)){const n=`join:${e.join("+")}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new Lx(new Set(e)):new $x(new Set(e)),this.nodes[t].triggers.push(n);for(const r of e)this.nodes[r].writers.push(new Je([{channel:n,value:r}],[ve]))}}}attachBranch(e,t,n,r={withReader:!0}){const s=async(a,i)=>{const o=a.filter(l=>l!==B);if(!o.length)return;const c=o.map(l=>gt(l)?l:{channel:l===B?l:`branch:to:${l}`,value:e});await Je.doWrite({...i,tags:(i.tags??[]).concat([ve])},c)};this.nodes[e].writers.push(n.run(s,r.withReader?a=>WO.doRead(a,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;const t=(()=>{const n=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition,s=a=>{if(a!=null)return this._metaRegistry.getExtendedChannelSchemas(a,{withReducerSchema:!0})};if(et(n))return s(n);if(n===xc)return sl(s(r))})();if(Pe(e)){const n=e;return e.update&&t!=null&&(n.update=bn(t,e.update)),n}return t!=null?bn(t,e):e}isInterrupted(e){return hg(e)}async _validateContext(e){const t=this.builder._configRuntimeSchema;return et(t)&&bn(t,e),e}};function zx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||og(t))}function jd(e){return typeof e=="object"&&e!==null&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"}function Hx(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function Vx(e){return typeof e=="object"&&e!==null&&e.stateSchema!==void 0}function Gx(e){return typeof e=="object"&&e!==null&&e.stateSchema===void 0&&e.input!==void 0&&e.output!==void 0}function Wx(e){return!(typeof e!="object"||e==null||!("state"in e)||!et(e.state)||"input"in e&&!et(e.input)||"output"in e&&!et(e.output))}function Jx(e){if(gt(e))return[e];const t=[];Pe(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(Pe));const n=[];for(const r of t){if(r.graph===be.PARENT)throw new ig(r);gt(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Dd(){const e=new or({func:Jx,tags:[ve],trace:!1,recurse:!1,name:"<control_branch>"});return new Rg({path:e})}const Dg="__remove_all__";function Ug(e,t){const n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],s=n.map(Gt),a=r.map(Gt);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=Ce(),u.lc_kwargs.id=u.id);let i;for(let u=0;u<a.length;u+=1){const d=a[u];(d.id===null||d.id===void 0)&&(d.id=Ce(),d.lc_kwargs.id=d.id),d.getType()==="remove"&&d.id===Dg&&(i=u)}if(i!=null)return a.slice(i+1);const o=[...s],c=new Map(o.map((u,d)=>[u.id,d])),l=new Set;for(const u of a){const d=c.get(u.id);if(d!==void 0)u.getType()==="remove"?l.add(u.id):(l.delete(u.id),o[d]=u);else{if(u.getType()==="remove")throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);c.set(u.id,o.length),o.push(u)}}return o.filter(u=>!l.has(u.id))}vc.Root({messages:vc({reducer:Ug,default:()=>[]})});const oi={reducer:{fn:Ug},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};te({messages:Qr(Ht(),oi)});lO();const Ic=Symbol.for("langgraph-zod");Ic in globalThis||(globalThis[Ic]=new WeakSet);function Ud(e){const t=globalThis[Ic];t.has(e)||(Object.defineProperty(e,"langgraph",{get(){const n=this;return{metadata(r){return Qr(n,{jsonSchemaExtra:r})},reducer(r,s){const a=_i(n);return Qr(n,{default:a,reducer:{schema:s,fn:r}})}}}}),t.add(e))}try{Ud(au.prototype),Ud(au.prototype)}catch(e){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:e})}var Kx=class extends m_{constructor(e){super(),this.parent=e,this._map=this.parent._map}add(e,...t){const n=t[0];if(n&&!n?.default){const r=_i(e);r!=null&&(n.default=r)}return super.add(e,...t)}};new Kx(Fs);function Zx(e=!0,t,n=[]){const r={messages:Qr(Ht(),oi),jumpTo:en([Io("model_request"),Io("tools"),my()]).optional()},s=a=>{const{shape:i}=a;for(const[o,c]of Object.entries(i))o.startsWith("_")||o in r||(r[o]=c)};t&&"shape"in t&&s(t);for(const a of n)a.stateSchema&&s(a.stateSchema);return e&&(r.structuredResponse=ht().optional()),te(r)}te({llmInputMessages:Qr(Ht(),{reducer:{fn:(e,t)=>oi.reducer.fn([],t)},default:()=>[]}),messages:Qr(Ht(),oi)});const Fd="prompt",Ao=/<name>(.*?)<\/name>/s,ko=/<content>(.*?)<\/content>/s;function qx(e){if(!j.isInstance(e)||mt.isInstance(e)||!e.name)return e;const{name:t}=e;if(typeof e.content=="string")return new j({...e.lc_kwargs,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});const n=[];let r=0;for(const s of e.content)typeof s=="string"?(r+=1,n.push(`<name>${t}</name><content>${s}</content>`)):typeof s=="object"&&"type"in s&&s.type==="text"?(r+=1,n.push({...s,text:`<name>${t}</name><content>${s.text}</content>`})):n.push(s);return r||n.unshift({type:"text",text:`<name>${t}</name><content></content>`}),new j({...e.lc_kwargs,content:n,name:void 0})}function Yx(e){if(!j.isInstance(e)||!e.content)return e;let t=[],n;if(Array.isArray(e.content))t=e.content.filter(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(Ao),a=r.text.match(ko);return s&&(!a||a[1]==="")?(n=s[1],!1):!0}return!0}).map(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(Ao),a=r.text.match(ko);return!s||!a?r:(n=s[1],{...r,text:a[1]})}return r});else{const r=e.content,s=r.match(Ao),a=r.match(ko);if(!s||!a)return e;n=s[1],t=a[1]}return new j({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function ye(e){return J.isRunnable(e)}function Bd(e){return Cl(e)?"bindTools"in e&&typeof e.bindTools=="function":!1}const Oo=(e,t,n={})=>{if(Bd(e))return e.bindTools(t,n);if(De.isRunnableBinding(e)&&Bd(e.bound)){const r=e.bound.bindTools(t,n);return De.isRunnableBinding(r)?new De({bound:r.bound,config:{...e.config,...r.config},kwargs:{...e.kwargs,...r.kwargs},configFactories:r.configFactories??e.configFactories}):new De({bound:r,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};function Fg(e){if(typeof e=="function")return;let t=e;if(Et.isRunnableSequence(t)&&(t=t.steps.find(n=>De.isRunnableBinding(n))||t),!qa(t)){if(De.isRunnableBinding(t)){const n=t.kwargs!=null&&typeof t.kwargs=="object"&&"tools"in t.kwargs&&Array.isArray(t.kwargs.tools)&&t.kwargs.tools.length>0,r=t.config!=null&&typeof t.config=="object"&&"tools"in t.config&&Array.isArray(t.config.tools)&&t.config.tools.length>0;if(n||r)throw new sc}if("tools"in t&&t.tools!==void 0&&Array.isArray(t.tools)&&t.tools.length>0)throw new sc}}function Bg(e){return!!(j.isInstance(e)&&e.tool_calls&&e.tool_calls.length>0)}function Xx(e){let t;if(e==null)t=at.from(n=>n.messages).withConfig({runName:Fd});else if(typeof e=="string"){const n=new fe(e);t=at.from(r=>[n,...r.messages??[]]).withConfig({runName:Fd})}else throw new Error(`Got unexpected type for 'prompt': ${typeof e}`);return t}async function Qx(e,t,n={}){const r=Oo(e,t,n);if(r)return r;if(qa(e)){const s=Oo(await e._model(),t,n);if(s)return s}if(Et.isRunnableSequence(e)){const s=e.steps.findIndex(a=>De.isRunnableBinding(a)||Cl(a)||qa(a));if(s>=0){const a=Oo(e.steps[s],t,n);if(a){const i=e.steps.slice();return i.splice(s,1,a),Et.from(i)}}}throw new Error(`llm ${e} must define bindTools method.`)}function eI(e){if(e.length===0)return;if(e.length===1)return e[0];function t(r,s){return async(a,i)=>r(a,async c=>s(c,async l=>i(l)))}let n=e[e.length-1];for(let r=e.length-2;r>=0;r--)n=t(e[r],n);return n}function tI(e){const t=e.filter(n=>n.wrapToolCall);if(t.length!==0)return eI(t.map(n=>{const r=n.wrapToolCall;return async(a,i)=>{try{const o=await r(a,i);if(!X.isInstance(o)&&!Pe(o))throw new Error(`Invalid response from "wrapToolCall" in middleware "${n.name}": expected ToolMessage or Command, got ${typeof o}`);return o}catch(o){throw o instanceof Error&&!o.message.includes(`middleware "${n.name}"`)&&(o.message=`Error in middleware "${n.name}": ${o.message}`),o}}}))}async function nI(e,t){const n={};for(const r of e)if(r.stateSchema){const s=dp(r.stateSchema,o=>o.startsWith("_")),a=await tl(s,t);if(a.success){Object.assign(n,a.data);continue}const i=a.error.issues.filter(o=>o.code==="invalid_type"&&o.message==="Required").map(o=>` - ${o.path.join(".")}: ${o.message}`).join(`
206
+ `),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!==B&&!(r in this.nodes))throw new Error(`Found edge ending at unknown node \`${r}\``);if(e){for(const r of e)if(!(r in this.nodes))throw new Error(`Interrupt node \`${r}\` is not present`)}this.compiled=!0}},$g=class extends Mx{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new Xr,this.nodes[e]=new js({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new Je([{channel:e,value:Jn}],[ve])),this.streamChannels.push(e)}attachEdge(e,t){if(t===B){if(e===ie)throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new Je([{channel:B,value:Jn}],[ve]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e===ie&&!this.nodes[ie]&&(this.nodes[ie]=Px.subscribeTo(ie,{tags:[ve]})),this.nodes[e].pipe(n.run(s=>{const a=s.map(i=>gt(i)?i:{channel:i===B?B:`branch:${e}:${t}:${i}`,value:Jn});return new Je(a,[ve])}));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const s of r)if(s!==B){const a=`branch:${e}:${t}:${s}`;this.channels[a]=new Xr,this.nodes[s].triggers.push(a),this.nodes[s].channels.push(a)}}async getGraphAsync(e){const t=e?.xray,n=new Os,r={[ie]:n.addNode({schema:sa()},ie)},s={};let a={};t&&(a=Object.fromEntries((await yn(this.getSubgraphsAsync())).filter(c=>Ld(c[1]))));function i(c,l,u,d=!1){if(l===B&&s[B]===void 0&&(s[B]=n.addNode({schema:sa()},B)),r[c]!==void 0){if(s[l]===void 0)throw new Error(`End node ${l} not found!`);return n.addEdge(r[c],s[l],u!==l?u:void 0,d)}}for(const[c,l]of Object.entries(this.builder.nodes)){const u=je(c),d=l.runnable,h=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?h.__interrupt="before,after":this.interruptBefore?.includes(c)?h.__interrupt="before":this.interruptAfter?.includes(c)&&(h.__interrupt="after"),t){const p=typeof t=="number"?t-1:t,f=a[c]!==void 0?await a[c].getGraphAsync({...e,xray:p}):d.getGraph(e);if(f.trimFirstNode(),f.trimLastNode(),Object.keys(f.nodes).length>1){let b=function(w){return w?w.lc_runnable:!1},v=function(w,E){if(w!==void 0&&!br(w))return w;if(b(E))try{let A=E.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return E.getName()}else return E.name??"UnknownSchema"};const[y,S]=n.extend(f,u);if(y===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:v(S.id,S.data),...S}),s[u]={name:v(y.id,y.data),...y}}else{const y=n.addNode(d,u,h);r[u]=y,s[u]=y}}else{const p=n.addNode(d,u,h);r[u]=p,s[u]=p}}const o=[...this.builder.allEdges].sort(([c],[l])=>c<l?-1:l>c?1:0);for(const[c,l]of o)i(je(c),je(l));for(const[c,l]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[je(d),je(d)])),[B]:B};for(const d of Object.values(l)){let h;d.ends!==void 0?h=d.ends:h=u;for(const[p,f]of Object.entries(h))i(je(c),je(f),p,!0)}}for(const[c,l]of Object.entries(this.builder.nodes))if(l.ends!==void 0)for(const u of l.ends)i(je(c),je(u),void 0,!0);return n}getGraph(e){const t=e?.xray,n=new Os,r={[ie]:n.addNode({schema:sa()},ie)},s={};let a={};t&&(a=Object.fromEntries(ds(this.getSubgraphs()).filter(c=>Ld(c[1]))));function i(c,l,u,d=!1){return l===B&&s[B]===void 0&&(s[B]=n.addNode({schema:sa()},B)),n.addEdge(r[c],s[l],u!==l?u:void 0,d)}for(const[c,l]of Object.entries(this.builder.nodes)){const u=je(c),d=l.runnable,h=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?h.__interrupt="before,after":this.interruptBefore?.includes(c)?h.__interrupt="before":this.interruptAfter?.includes(c)&&(h.__interrupt="after"),t){const p=typeof t=="number"?t-1:t,f=a[c]!==void 0?a[c].getGraph({...e,xray:p}):d.getGraph(e);if(f.trimFirstNode(),f.trimLastNode(),Object.keys(f.nodes).length>1){let b=function(w){return w?w.lc_runnable:!1},v=function(w,E){if(w!==void 0&&!br(w))return w;if(b(E))try{let A=E.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return E.getName()}else return E.name??"UnknownSchema"};const[y,S]=n.extend(f,u);if(y===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:v(S.id,S.data),...S}),s[u]={name:v(y.id,y.data),...y}}else{const y=n.addNode(d,u,h);r[u]=y,s[u]=y}}else{const p=n.addNode(d,u,h);r[u]=p,s[u]=p}}const o=[...this.builder.allEdges].sort(([c],[l])=>c<l?-1:l>c?1:0);for(const[c,l]of o)i(je(c),je(l));for(const[c,l]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[je(d),je(d)])),[B]:B};for(const d of Object.values(l)){let h;d.ends!==void 0?h=d.ends:h=u;for(const[p,f]of Object.entries(h))i(je(c),je(f),p,!0)}}return n}};function Ld(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function je(e){return e==="subgraph"?`"${e}"`:e}const zn=(e,t)=>e.size===t.size&&[...e].every(n=>t.has(n));var $x=class Lg extends ir{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){const n=new Lg(this.names);return typeof t<"u"&&(n.seen=new Set(t)),n}update(t){let n=!1;for(const r of t)if(this.names.has(r))this.seen.has(r)||(this.seen.add(r),n=!0);else throw new de(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!zn(this.names,this.seen))throw new Le}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&zn(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&zn(this.names,this.seen)}},Lx=class jg extends ir{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(t){super(),this.names=t,this.seen=new Set,this.finished=!1}fromCheckpoint(t){const n=new jg(this.names);if(typeof t<"u"){const[r,s]=t;n.seen=new Set(r),n.finished=s}return n}update(t){let n=!1;for(const r of t)if(this.names.has(r)&&!this.seen.has(r))this.seen.add(r),n=!0;else if(!this.names.has(r))throw new de(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!zn(this.names,this.seen))throw new Le}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&zn(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&zn(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&zn(this.names,this.seen)}};const jx="lg:";var Dx=class{_map=new WeakMap;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){const n=this.get(e);this._map.set(e,t(n))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){const t={},n=Cs(e);for(const[r,s]of Object.entries(n)){const a=this.get(s);a?.reducer?t[r]=new wc(a.reducer.fn,a.default):t[r]=new Vl}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;const n=Object.entries(t).filter(([,a])=>a===!0).sort(([a],[i])=>a.localeCompare(i)).map(([a,i])=>`${a}:${i}`).join("|"),r=this._extensionCache.get(n)??new WeakMap;if(r.has(e))return r.get(e);let s=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){const a=Object.entries(Cs(e)).map(([i,o])=>{const c=this.get(o);let l=t.withReducerSchema?c?.reducer?.schema??o:o;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){const u=Vr(l)??Vr(o),d=JSON.stringify({...c.jsonSchemaExtra,description:u});l=l.describe(`${jx}${d}`)}return[i,l]});s=up(e,Object.fromEntries(a)),Se(s)&&(s._def.unknownKeys="strip")}return t.asPartial&&(s=sl(s)),r.set(e,s),this._extensionCache.set(n,r),s}};const Fs=new Dx;function Qr(e,t){if(t.reducer&&!t.default){const n=_i(e);n!=null&&(t.default=n)}if(t.reducer){const n=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return Fs.extend(n,()=>t),n}else return Fs.extend(e,()=>t),e}const Qt="__root__",xc=Symbol.for("langgraph.state.partial");var Ux=class extends Rx{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=Fs;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){if(super(),Wx(e)){const r=this._metaRegistry.getChannelsForSchema(e.state),s=e.input!=null?this._metaRegistry.getChannelsForSchema(e.input):r,a=e.output!=null?this._metaRegistry.getChannelsForSchema(e.output):r;this._schemaDefinition=r,this._schemaRuntimeDefinition=e.state,this._inputDefinition=s,this._inputRuntimeDefinition=e.input??xc,this._outputDefinition=a,this._outputRuntimeDefinition=e.output??e.state}else if(et(e)){const r=this._metaRegistry.getChannelsForSchema(e);this._schemaDefinition=r,this._schemaRuntimeDefinition=e,this._inputDefinition=r,this._inputRuntimeDefinition=xc,this._outputDefinition=r,this._outputRuntimeDefinition=e}else if(Gx(e))this._schemaDefinition=e.input.spec,this._inputDefinition=e.input.spec,this._outputDefinition=e.output.spec;else if(Vx(e))this._schemaDefinition=e.stateSchema.spec,this._inputDefinition=e.input?.spec??this._schemaDefinition,this._outputDefinition=e.output?.spec??this._schemaDefinition;else if(zx(e)||jd(e)){const r=jd(e)?e.spec:e;this._schemaDefinition=r}else if(Hx(e)){const r=Fx(e.channels);this._schemaDefinition=r}else throw new Error("Invalid StateGraph input. Make sure to pass a valid Annotation.Root or Zod schema.");this._inputDefinition??=this._schemaDefinition,this._outputDefinition??=this._schemaDefinition,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition);function n(r){return typeof r=="object"&&r!=null&&!("spec"in r)&&!et(r)}n(t)?(et(t.context)&&(this._configRuntimeSchema=t.context),this._interrupt=t.interrupt,this._writer=t.writer):et(t)&&(this._configRuntimeSchema=t)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(n=>[n,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(const[t,n]of Object.entries(e)){let r;if(typeof n=="function"?r=n():r=n,this.channels[t]!==void 0){if(this.channels[t]!==r&&r.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=r}}}addNode(...e){function t(r){return r.length>=1&&typeof r[0]!="string"}const n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([r,s])=>[r,s]):[[e[0],e[1],e[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,a]of n){if(r in this.channels)throw new Error(`${r} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const u of[ke,an])if(r.includes(u))throw new Error(`"${u}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===B||r===ie)throw new Error(`Node \`${r}\` is reserved.`);let i=this._schemaDefinition;a?.input!==void 0&&(et(a.input)?i=this._metaRegistry.getChannelsForSchema(a.input):a.input.spec!==void 0&&(i=a.input.spec)),i!==void 0&&this._addSchema(i);let o;J.isRunnable(s)?o=s:typeof s=="function"?o=new or({func:s,name:r,trace:!1}):o=$e(s);let c=a?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);const l={runnable:o,retryPolicy:a?.retryPolicy,cachePolicy:c,metadata:a?.metadata,input:i??this._schemaDefinition,subgraphs:Kl(o)?[o]:a?.subgraphs,ends:a?.ends,defer:a?.defer};this.nodes[r]=l}return this}addEdge(e,t){if(typeof e=="string")return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(const n of e){if(n===B)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(r=>r===n))throw new Error(`Need to add a node named "${n}" first`)}if(t===B)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(n=>n===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){const t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let n;for(const[r,s,a]of t){if(r in this.nodes)throw new Error(`Node names must be unique: node with the name "${r}" already exists.`);const i=r;this.addNode(i,s,a),n!=null&&this.addEdge(n,i),n=i}return this}compile({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:s,name:a,description:i}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(s)?s:[]]);const o=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=o.length===1&&o[0]===Qt?Qt:o,l=Object.keys(this.channels),u=l.length===1&&l[0]===Qt?Qt:l,d=this._interrupt,h=new Bx({builder:this,checkpointer:e,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[ie]:new Xr},inputChannels:ie,outputChannels:c,streamChannels:u,streamMode:"updates",store:t,cache:n,name:a,description:i,userInterrupt:d});h.attachNode(ie);for(const[p,f]of Object.entries(this.nodes))h.attachNode(p,f);h.attachBranch(ie,Ad,Dd(),{withReader:!1});for(const[p]of Object.entries(this.nodes))h.attachBranch(p,Ad,Dd(),{withReader:!1});for(const[p,f]of this.edges)h.attachEdge(p,f);for(const[p,f]of this.waitingEdges)h.attachEdge(p,f);for(const[p,f]of Object.entries(this.branches))for(const[y,S]of Object.entries(f))h.attachBranch(p,y,S);return h.validate()}};function Fx(e){const t={};for(const[n,r]of Object.entries(e))t[n]=bc(r);return t}var Bx=class extends $g{description;_metaRegistry=Fs;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let n;e===ie?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([o])=>o):n=Object.keys(this.builder.channels);function r(o){if(Pe(o))return o.graph===be.PARENT?null:o._updateAsTuples();if(Array.isArray(o)&&o.length>0&&o.some(c=>Pe(c))){const c=[];for(const l of o)if(Pe(l)){if(l.graph===be.PARENT)continue;c.push(...l._updateAsTuples())}else c.push([Qt,l]);return c}else if(o!=null)return[[Qt,o]];return null}const s=e;function a(o){if(o){if(Pe(o))return o.graph===be.PARENT?null:o._updateAsTuples().filter(([c])=>n.includes(c));if(Array.isArray(o)&&o.length>0&&o.some(Pe)){const c=[];for(const l of o)if(Pe(l)){if(l.graph===be.PARENT)continue;c.push(...l._updateAsTuples().filter(([u])=>n.includes(u)))}else{const u=a(l);u&&c.push(...u??[])}return c}else{if(typeof o=="object"&&!Array.isArray(o))return Object.entries(o).filter(([c])=>n.includes(c));{const c=Array.isArray(o)?"array":typeof o;throw new de(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${c}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const i=[{value:Jn,mapper:new or({func:n.length&&n[0]===Qt?r:a,trace:!1,recurse:!1})}];if(e===ie)this.nodes[e]=new js({tags:[ve],triggers:[ie],channels:[ie],writers:[new Je(i,[ve])]});else{const o=t?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(o)).map(d=>[d,d])),l=Object.keys(c).length===1&&Qt in c,u=`branch:to:${e}`;this.channels[u]=t?.defer?new pO:new Xr(!1),this.nodes[e]=new js({triggers:[u],channels:l?Object.keys(c):c,writers:[new Je(i,[ve])],mapper:l?void 0:d=>Object.fromEntries(Object.entries(d).filter(([h])=>h in c)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:t?.cachePolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!==B){if(typeof e=="string")this.nodes[e].writers.push(new Je([{channel:`branch:to:${t}`,value:null}],[ve]));else if(Array.isArray(e)){const n=`join:${e.join("+")}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new Lx(new Set(e)):new $x(new Set(e)),this.nodes[t].triggers.push(n);for(const r of e)this.nodes[r].writers.push(new Je([{channel:n,value:r}],[ve]))}}}attachBranch(e,t,n,r={withReader:!0}){const s=async(a,i)=>{const o=a.filter(l=>l!==B);if(!o.length)return;const c=o.map(l=>gt(l)?l:{channel:l===B?l:`branch:to:${l}`,value:e});await Je.doWrite({...i,tags:(i.tags??[]).concat([ve])},c)};this.nodes[e].writers.push(n.run(s,r.withReader?a=>WO.doRead(a,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;const t=(()=>{const n=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition,s=a=>{if(a!=null)return this._metaRegistry.getExtendedChannelSchemas(a,{withReducerSchema:!0})};if(et(n))return s(n);if(n===xc)return sl(s(r))})();if(Pe(e)){const n=e;return e.update&&t!=null&&(n.update=bn(t,e.update)),n}return t!=null?bn(t,e):e}isInterrupted(e){return hg(e)}async _validateContext(e){const t=this.builder._configRuntimeSchema;return et(t)&&bn(t,e),e}};function zx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||og(t))}function jd(e){return typeof e=="object"&&e!==null&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"}function Hx(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function Vx(e){return typeof e=="object"&&e!==null&&e.stateSchema!==void 0}function Gx(e){return typeof e=="object"&&e!==null&&e.stateSchema===void 0&&e.input!==void 0&&e.output!==void 0}function Wx(e){return!(typeof e!="object"||e==null||!("state"in e)||!et(e.state)||"input"in e&&!et(e.input)||"output"in e&&!et(e.output))}function Jx(e){if(gt(e))return[e];const t=[];Pe(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(Pe));const n=[];for(const r of t){if(r.graph===be.PARENT)throw new ig(r);gt(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Dd(){const e=new or({func:Jx,tags:[ve],trace:!1,recurse:!1,name:"<control_branch>"});return new Rg({path:e})}const Dg="__remove_all__";function Ug(e,t){const n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],s=n.map(Gt),a=r.map(Gt);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=Ce(),u.lc_kwargs.id=u.id);let i;for(let u=0;u<a.length;u+=1){const d=a[u];(d.id===null||d.id===void 0)&&(d.id=Ce(),d.lc_kwargs.id=d.id),d.getType()==="remove"&&d.id===Dg&&(i=u)}if(i!=null)return a.slice(i+1);const o=[...s],c=new Map(o.map((u,d)=>[u.id,d])),l=new Set;for(const u of a){const d=c.get(u.id);if(d!==void 0)u.getType()==="remove"?l.add(u.id):(l.delete(u.id),o[d]=u);else{if(u.getType()==="remove")throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);c.set(u.id,o.length),o.push(u)}}return o.filter(u=>!l.has(u.id))}vc.Root({messages:vc({reducer:Ug,default:()=>[]})});const oi={reducer:{fn:Ug},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};te({messages:Qr(Ht(),oi)});lO();const Ic=Symbol.for("langgraph-zod");Ic in globalThis||(globalThis[Ic]=new WeakSet);function Ud(e){const t=globalThis[Ic];t.has(e)||(Object.defineProperty(e,"langgraph",{get(){const n=this;return{metadata(r){return Qr(n,{jsonSchemaExtra:r})},reducer(r,s){const a=_i(n);return Qr(n,{default:a,reducer:{schema:s,fn:r}})}}}}),t.add(e))}try{Ud(au.prototype),Ud(au.prototype)}catch(e){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:e})}var Kx=class extends f_{constructor(e){super(),this.parent=e,this._map=this.parent._map}add(e,...t){const n=t[0];if(n&&!n?.default){const r=_i(e);r!=null&&(n.default=r)}return super.add(e,...t)}};new Kx(Fs);function Zx(e=!0,t,n=[]){const r={messages:Qr(Ht(),oi),jumpTo:en([Io("model_request"),Io("tools"),my()]).optional()},s=a=>{const{shape:i}=a;for(const[o,c]of Object.entries(i))o.startsWith("_")||o in r||(r[o]=c)};t&&"shape"in t&&s(t);for(const a of n)a.stateSchema&&s(a.stateSchema);return e&&(r.structuredResponse=ht().optional()),te(r)}te({llmInputMessages:Qr(Ht(),{reducer:{fn:(e,t)=>oi.reducer.fn([],t)},default:()=>[]}),messages:Qr(Ht(),oi)});const Fd="prompt",Ao=/<name>(.*?)<\/name>/s,ko=/<content>(.*?)<\/content>/s;function qx(e){if(!j.isInstance(e)||mt.isInstance(e)||!e.name)return e;const{name:t}=e;if(typeof e.content=="string")return new j({...e.lc_kwargs,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});const n=[];let r=0;for(const s of e.content)typeof s=="string"?(r+=1,n.push(`<name>${t}</name><content>${s}</content>`)):typeof s=="object"&&"type"in s&&s.type==="text"?(r+=1,n.push({...s,text:`<name>${t}</name><content>${s.text}</content>`})):n.push(s);return r||n.unshift({type:"text",text:`<name>${t}</name><content></content>`}),new j({...e.lc_kwargs,content:n,name:void 0})}function Yx(e){if(!j.isInstance(e)||!e.content)return e;let t=[],n;if(Array.isArray(e.content))t=e.content.filter(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(Ao),a=r.text.match(ko);return s&&(!a||a[1]==="")?(n=s[1],!1):!0}return!0}).map(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(Ao),a=r.text.match(ko);return!s||!a?r:(n=s[1],{...r,text:a[1]})}return r});else{const r=e.content,s=r.match(Ao),a=r.match(ko);if(!s||!a)return e;n=s[1],t=a[1]}return new j({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function ye(e){return J.isRunnable(e)}function Bd(e){return Cl(e)?"bindTools"in e&&typeof e.bindTools=="function":!1}const Oo=(e,t,n={})=>{if(Bd(e))return e.bindTools(t,n);if(De.isRunnableBinding(e)&&Bd(e.bound)){const r=e.bound.bindTools(t,n);return De.isRunnableBinding(r)?new De({bound:r.bound,config:{...e.config,...r.config},kwargs:{...e.kwargs,...r.kwargs},configFactories:r.configFactories??e.configFactories}):new De({bound:r,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};function Fg(e){if(typeof e=="function")return;let t=e;if(Et.isRunnableSequence(t)&&(t=t.steps.find(n=>De.isRunnableBinding(n))||t),!qa(t)){if(De.isRunnableBinding(t)){const n=t.kwargs!=null&&typeof t.kwargs=="object"&&"tools"in t.kwargs&&Array.isArray(t.kwargs.tools)&&t.kwargs.tools.length>0,r=t.config!=null&&typeof t.config=="object"&&"tools"in t.config&&Array.isArray(t.config.tools)&&t.config.tools.length>0;if(n||r)throw new sc}if("tools"in t&&t.tools!==void 0&&Array.isArray(t.tools)&&t.tools.length>0)throw new sc}}function Bg(e){return!!(j.isInstance(e)&&e.tool_calls&&e.tool_calls.length>0)}function Xx(e){let t;if(e==null)t=at.from(n=>n.messages).withConfig({runName:Fd});else if(typeof e=="string"){const n=new fe(e);t=at.from(r=>[n,...r.messages??[]]).withConfig({runName:Fd})}else throw new Error(`Got unexpected type for 'prompt': ${typeof e}`);return t}async function Qx(e,t,n={}){const r=Oo(e,t,n);if(r)return r;if(qa(e)){const s=Oo(await e._model(),t,n);if(s)return s}if(Et.isRunnableSequence(e)){const s=e.steps.findIndex(a=>De.isRunnableBinding(a)||Cl(a)||qa(a));if(s>=0){const a=Oo(e.steps[s],t,n);if(a){const i=e.steps.slice();return i.splice(s,1,a),Et.from(i)}}}throw new Error(`llm ${e} must define bindTools method.`)}function eI(e){if(e.length===0)return;if(e.length===1)return e[0];function t(r,s){return async(a,i)=>r(a,async c=>s(c,async l=>i(l)))}let n=e[e.length-1];for(let r=e.length-2;r>=0;r--)n=t(e[r],n);return n}function tI(e){const t=e.filter(n=>n.wrapToolCall);if(t.length!==0)return eI(t.map(n=>{const r=n.wrapToolCall;return async(a,i)=>{try{const o=await r(a,i);if(!X.isInstance(o)&&!Pe(o))throw new Error(`Invalid response from "wrapToolCall" in middleware "${n.name}": expected ToolMessage or Command, got ${typeof o}`);return o}catch(o){throw o instanceof Error&&!o.message.includes(`middleware "${n.name}"`)&&(o.message=`Error in middleware "${n.name}": ${o.message}`),o}}}))}async function nI(e,t){const n={};for(const r of e)if(r.stateSchema){const s=dp(r.stateSchema,o=>o.startsWith("_")),a=await tl(s,t);if(a.success){Object.assign(n,a.data);continue}const i=a.error.issues.filter(o=>o.code==="invalid_type"&&o.message==="Required").map(o=>` - ${o.path.join(".")}: ${o.message}`).join(`
207
207
  `);throw new Error(`Middleware "${r.name}" has required state fields that must be initialized:
208
208
  ${i}
209
209
 
@@ -488,7 +488,7 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
488
488
  ${i.map(c=>c.name).join(`
489
489
  `)}`,T.info(r),r}catch(r){return T.error(`Failed to add or connect to server '${t}': ${r.message}`),`Failed to add or connect to server '${t}': ${r.message}`}}},G(xr,"AddMCPServerFromConfigTool"),xr),dP=te({serverName:Oe().describe("The name of the MCP server.")}),Ir,hP=(Ir=class extends Ni{name="connect_to_mcp_server";description="Connect to a specific MCP (Model Context Protocol) server to use its tools. Use this tool to connect to a specific server and use its tools.";schema=dP;constructor(t){super(t)}async _call({serverName:t}){const n=this.manager.client.getServerNames();if(!n.includes(t)){const r=n.length>0?n.join(", "):"none";return`Server '${t}' not found. Available servers: ${r}`}if(this.manager.activeServer===t)return`Already connected to MCP server '${t}'`;try{let r=this.manager.client.getSession(t);if(T.debug(`Using existing session for server '${t}'`),r||(T.debug(`Creating new session for server '${t}'`),r=await this.manager.client.createSession(t)),this.manager.activeServer=t,this.manager.serverTools[t]){const i=r.connector,o=await this.manager.adapter.createToolsFromConnectors([i]);this.manager.serverTools[t]=o,this.manager.initializedServers[t]=!0}const a=(this.manager.serverTools[t]||[]).length;return`Connected to MCP server '${t}'. ${a} tools are now available.`}catch(r){return T.error(`Error connecting to server '${t}': ${String(r)}`),`Failed to connect to server '${t}': ${String(r)}`}}},G(Ir,"ConnectMCPServerTool"),Ir),pP=te({}),Pr,fP=(Pr=class extends Ni{name="list_mcp_servers";description="Lists all available MCP (Model Context Protocol) servers that can be connected to, along with the tools available on each server. Use this tool to discover servers and see what functionalities they offer.";schema=pP;constructor(t){super(t)}async _call(){const t=this.manager.client.getServerNames();if(t.length===0)return"No MCP servers are currently defined.";const n=["Available MCP servers:"];for(const r of t){const a=r===this.manager.activeServer?" (ACTIVE)":"";n.push(`- ${r}${a}`);try{const i=this.manager.serverTools?.[r]??[],o=Array.isArray(i)?i.length:0;n.push(`${o} tools available for this server
490
490
  `)}catch(i){T.error(`Unexpected error listing tools for server '${r}': ${String(i)}`)}}return n.join(`
491
- `)}},G(Pr,"ListMCPServersTool"),Pr),mP=te({}),Nr,gP=(Nr=class extends Ni{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=mP;constructor(t){super(t)}async _call(){if(!this.manager.activeServer)return"No MCP server is currently active, so there's nothing to disconnect from.";const t=this.manager.activeServer;return this.manager.activeServer=null,`Successfully disconnected from MCP server '${t}'.`}},G(Nr,"ReleaseMCPServerConnectionTool"),Nr),Mr,yP=(Mr=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(t,n,r){this.client=t,this.adapter=n,this.overrideManagementTools=r}setManagementTools(t){this.overrideManagementTools=t,T.info(`Overriding default management tools with a new set of ${t.length} tools.`)}logState(t){const n=this.client.getServerNames(),r=Object.keys(this.client.getAllActiveSessions());if(n.length===0){T.info("Server Manager State: No servers configured.");return}const s=n.map(a=>({"Server Name":a,Connected:r.includes(a)?"✅":"❌",Initialized:this.initializedServers[a]?"✅":"❌","Tool Count":this.serverTools[a]?.length??0,Active:this.activeServer===a?"✅":"❌"}));T.info(`Server Manager State: [${t}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&T.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const t=this.client.getServerNames();for(const n of t)try{let r=null;if(r=this.client.getSession(n),T.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(T.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),T.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let a=[];try{a=await this.adapter.createToolsFromConnectors([s])}catch(c){T.error(`Failed to create tools from connector for server '${n}': ${c}`);continue}const i=this.serverTools[n];!i||!KE(i,a)?(this.serverTools[n]=a,this.initializedServers[n]=!0,T.debug(`Prefetched ${a.length} tools for server '${n}'.`)):T.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){T.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){T.level==="debug"&&this.logState("Providing tools to agent");const t=this.overrideManagementTools??[new uP(this),new fP(this),new hP(this),new lP(this),new gP(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return T.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...t,...n]}return t}},G(Mr,"ServerManager"),Mr),Rr,Pc=(Rr=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(t={}){this.customCallbacks=t.customCallbacks,this.verbose=t.verbose??!1,this.observe=t.observe??!0,this.agentId=t.agentId,this.metadata=t.metadata,this.metadataProvider=t.metadataProvider,this.tagsProvider=t.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:t,langfuseInitPromise:n}=await La(async()=>{const{langfuseHandler:s,langfuseInitPromise:a}=await Promise.resolve().then(()=>qd);return{langfuseHandler:s,langfuseInitPromise:a}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await La(async()=>{const{initializeLangfuse:a}=await Promise.resolve().then(()=>qd);return{initializeLangfuse:a}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),T.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const s=n();s&&await s}const r=t();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),T.debug("ObservabilityManager: Langfuse handler available"))}catch{T.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(T.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?T.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):T.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(T.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(t=>t.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const t=await this.getCallbacks(),n=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},s=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&t.length>0,callbackCount:t.length,handlerNames:n,metadata:r,tags:s}}addCallback(t){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(t),T.debug(`ObservabilityManager: Added custom callback: ${t.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],T.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const t=await this.getCallbacks();for(const n of t)"flushAsync"in n&&typeof n.flushAsync=="function"&&await n.flushAsync();T.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const t=await this.getCallbacks();for(const n of t)"shutdownAsync"in n&&typeof n.shutdownAsync=="function"?await n.shutdownAsync():"shutdown"in n&&typeof n.shutdown=="function"&&await n.shutdown();T.debug("ObservabilityManager: All handlers shutdown")}toString(){const t=this.handlerNames;return t.length>0?`ObservabilityManager(handlers=${t.join(", ")})`:"ObservabilityManager(no handlers)"}},G(Rr,"ObservabilityManager"),Rr),$r,_P=($r=class{},G($r,"BaseTelemetryEvent"),$r),Lr,wP=(Lr=class extends _P{constructor(t){super(),this.data=t}get name(){return"mcp_agent_execution"}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}},G(Lr,"MCPAgentExecutionEvent"),Lr);function Ra(){try{if(typeof __dirname>"u"||typeof Po>"u")return"unknown";const e=$a(__dirname,"../../package.json");return JSON.parse((void 0)(e,"utf-8")).version||"unknown"}catch{return"unknown"}}G(Ra,"getPackageVersion");function ry(e){return e._llm_type||e.constructor.name.toLowerCase()}G(ry,"getModelProvider");function sy(e){if("_identifyingParams"in e){const t=e._identifyingParams;if(typeof t=="object"&&t!==null){for(const n of["model","modelName","model_name","modelId","model_id","deploymentName","deployment_name"])if(n in t)return String(t[n])}}return e.model||e.modelName||e.constructor.name}G(sy,"getModelName");function ay(e){return[ry(e),sy(e)]}G(ay,"extractModelInfo");function _s(){try{return typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")||typeof globalThis.EdgeRuntime<"u"||typeof globalThis.Deno<"u"?!1:typeof process<"u"&&!0&&typeof __dirname<"u"&&(typeof Po<"u"&&typeof Po<"u"&&!1)}catch{return!1}}G(_s,"isNodeJSEnvironment");var jr,vP=(jr=class{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,r=setTimeout(()=>n.abort(),this.timeout),s=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(r),!s.ok)throw new Error(`HTTP error! status: ${s.status}`)}catch(n){T.debug(`Failed to send Scarf event: ${n}`)}}},G(jr,"ScarfEventLogger"),jr);function Nc(){if(!_s())return"/tmp/mcp_use_cache";const e=ci.XDG_CACHE_HOME;if(e&&yy(e))return e;const t=(void 0)();return $a(t,".cache")}G(Nc,"getCacheHome");var Rt,Mc=(Rt=class{USER_ID_PATH=$a(Nc(),"mcp_use_3","telemetry_user_id");VERSION_DOWNLOAD_PATH=$a(Nc(),"mcp_use","download_version");PROJECT_API_KEY="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";HOST="https://eu.i.posthog.com";SCARF_GATEWAY_URL="https://mcpuse.gateway.scarf.sh/events-ts";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogClient=null;_scarfClient=null;_source="typescript";constructor(){const t=_s(),n=typeof process<"u"&&ci?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()==="false"||!1;if(this._source=typeof process<"u"&&ci?.MCP_USE_TELEMETRY_SOURCE||"typescript",n)this._posthogClient=null,this._scarfClient=null,T.debug("Telemetry disabled via environment variable");else if(!t)this._posthogClient=null,this._scarfClient=null,T.debug("Telemetry disabled - non-Node.js environment detected (e.g., Cloudflare Workers)");else{T.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.");try{this._posthogClient=new ZE(this.PROJECT_API_KEY,{host:this.HOST,disableGeoip:!1})}catch(r){T.warn(`Failed to initialize PostHog telemetry: ${r}`),this._posthogClient=null}try{this._scarfClient=new vP(this.SCARF_GATEWAY_URL,3e3)}catch(r){T.warn(`Failed to initialize Scarf telemetry: ${r}`),this._scarfClient=null}}}static getInstance(){return Rt.instance||(Rt.instance=new Rt),Rt.instance}setSource(t){this._source=t,T.debug(`Telemetry source set to: ${t}`)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!_s())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{if(!(void 0)(this.USER_ID_PATH)){T.debug(`Creating user ID path: ${this.USER_ID_PATH}`),(void 0)(iu(this.USER_ID_PATH),{recursive:!0});const n=gy();(void 0)(this.USER_ID_PATH,n),this._currUserId=n,T.debug(`User ID path created: ${this.USER_ID_PATH}`)}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(n=>T.debug(`Failed to track package download: ${n}`))}catch(t){T.debug(`Failed to get/create user ID: ${t}`),this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}async capture(t){if(!(!this._posthogClient&&!this._scarfClient)){if(this._posthogClient)try{const n={...t.properties};n.mcp_use_version=Ra(),n.language="typescript",n.source=this._source,this._posthogClient.capture({distinctId:this.userId,event:t.name,properties:n})}catch(n){T.debug(`Failed to track PostHog event ${t.name}: ${n}`)}if(this._scarfClient)try{const n={};n.mcp_use_version=Ra(),n.user_id=this.userId,n.event=t.name,n.language="typescript",n.source=this._source,await this._scarfClient.logEvent(n)}catch(n){T.debug(`Failed to track Scarf event ${t.name}: ${n}`)}}}async trackPackageDownload(t){if(this._scarfClient&&_s())try{const n=Ra();let r=!1,s=!1;if((void 0)(this.VERSION_DOWNLOAD_PATH)||(r=!0,s=!0,(void 0)(iu(this.VERSION_DOWNLOAD_PATH),{recursive:!0}),(void 0)(this.VERSION_DOWNLOAD_PATH,n)),r){T.debug(`Tracking package download event with properties: ${JSON.stringify(t)}`);const a={...t||{}};a.mcp_use_version=n,a.user_id=this.userId,a.event="package_download",a.first_download=s,a.language="typescript",a.source=this._source,await this._scarfClient.logEvent(a)}}catch(n){T.debug(`Failed to track Scarf package_download event: ${n}`)}}async trackAgentExecution(t){const n=new wP(t);await this.capture(n)}flush(){if(this._posthogClient)try{this._posthogClient.flush(),T.debug("PostHog client telemetry queue flushed")}catch(t){T.debug(`Failed to flush PostHog client: ${t}`)}this._scarfClient&&T.debug("Scarf telemetry events sent immediately (no flush needed)")}shutdown(){if(this._posthogClient)try{this._posthogClient.shutdown(),T.debug("PostHog client shutdown successfully")}catch(t){T.debug(`Error shutting down PostHog client: ${t}`)}this._scarfClient&&T.debug("Scarf telemetry client shutdown (no action needed)")}},G(Rt,"Telemetry"),su(Rt,"instance",null),Rt);function bP(e){Mc.getInstance().setSource(e)}G(bP,"setTelemetrySource");var SP="/api/v1/chats",TP="/api/v1/chats/{chat_id}/execute",Dr,iy=(Dr=class{agentId;apiKey;baseUrl;chatId=null;constructor(t){this.agentId=t.agentId,this.baseUrl=t.baseUrl??"https://cloud.mcp-use.com";const n=t.apiKey??ci.MCP_USE_API_KEY;if(!n)throw new Error("API key is required for remote execution. Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. You can get an API key from https://cloud.mcp-use.com");this.apiKey=n}pydanticToJsonSchema(t){return ya(t)}parseStructuredResponse(t,n){let r;if(typeof t=="object"&&t!==null)if("result"in t){const s=t.result;typeof s=="object"&&s!==null&&"result"in s?r=s.result:r=s}else r=t;else if(typeof t=="string")try{r=JSON.parse(t)}catch{r={content:t}}else r=t;try{return n.parse(r)}catch(s){T.warn(`Failed to parse structured output: ${s}`);const a=n._def?.shape();if(a&&"content"in a)return n.parse({content:String(r)});throw s}}async createChatSession(){const t={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},n={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${SP}`;T.info(`📝 Creating chat session for agent ${this.agentId}`);try{const s=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(t)});if(!s.ok){const o=await s.text(),c=s.status;throw c===404?new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`):new Error(`Failed to create chat session: ${c} - ${o}`)}const i=(await s.json()).id;return T.info(`✅ Chat session created: ${i}`),i}catch(s){throw s instanceof Error?new TypeError(`Failed to create chat session: ${s.message}`):new Error(`Failed to create chat session: ${String(s)}`)}}async run(t,n,r,s,a){s!==void 0&&T.warn("External history is not yet supported for remote execution");try{T.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const i=this.chatId,o={query:t,max_steps:n??10};a&&(o.output_schema=this.pydanticToJsonSchema(a),T.info("🔧 Using structured output with schema"));const c={"Content-Type":"application/json","x-api-key":this.apiKey},l=`${this.baseUrl}${TP.replace("{chat_id}",i)}`;T.info(`🚀 Executing agent in chat ${i}`);const u=await fetch(l,{method:"POST",headers:c,body:JSON.stringify(o),signal:AbortSignal.timeout(3e5)});if(!u.ok){const h=await u.text(),p=u.status;throw p===401?(T.error(`❌ Authentication failed: ${h}`),new Error("Authentication failed: Invalid or missing API key. Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.")):p===403?(T.error(`❌ Access forbidden: ${h}`),new Error(`Access denied: You don't have permission to execute agent '${this.agentId}'. Check if the agent exists and you have the necessary permissions.`)):p===404?(T.error(`❌ Agent not found: ${h}`),new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`)):p===422?(T.error(`❌ Validation error: ${h}`),new Error(`Request validation failed: ${h}. Please check your query parameters and output schema format.`)):p===500?(T.error(`❌ Server error: ${h}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(T.error(`❌ Remote execution failed with status ${p}: ${h}`),new Error(`Remote agent execution failed: ${p} - ${h}`))}const d=await u.json();if(T.info(`🔧 Response: ${JSON.stringify(d)}`),T.info("✅ Remote execution completed successfully"),typeof d=="object"&&d!==null){if(d.status==="error"||d.error!==null){const h=d.error??String(d);throw T.error(`❌ Remote agent execution failed: ${h}`),new Error(`Remote agent execution failed: ${h}`)}if(String(d).includes("failed to initialize"))throw T.error(`❌ Agent initialization failed: ${d}`),new Error(`Agent initialization failed on remote server. This usually indicates:
491
+ `)}},G(Pr,"ListMCPServersTool"),Pr),mP=te({}),Nr,gP=(Nr=class extends Ni{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=mP;constructor(t){super(t)}async _call(){if(!this.manager.activeServer)return"No MCP server is currently active, so there's nothing to disconnect from.";const t=this.manager.activeServer;return this.manager.activeServer=null,`Successfully disconnected from MCP server '${t}'.`}},G(Nr,"ReleaseMCPServerConnectionTool"),Nr),Mr,yP=(Mr=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(t,n,r){this.client=t,this.adapter=n,this.overrideManagementTools=r}setManagementTools(t){this.overrideManagementTools=t,T.info(`Overriding default management tools with a new set of ${t.length} tools.`)}logState(t){const n=this.client.getServerNames(),r=Object.keys(this.client.getAllActiveSessions());if(n.length===0){T.info("Server Manager State: No servers configured.");return}const s=n.map(a=>({"Server Name":a,Connected:r.includes(a)?"✅":"❌",Initialized:this.initializedServers[a]?"✅":"❌","Tool Count":this.serverTools[a]?.length??0,Active:this.activeServer===a?"✅":"❌"}));T.info(`Server Manager State: [${t}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&T.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const t=this.client.getServerNames();for(const n of t)try{let r=null;if(r=this.client.getSession(n),T.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(T.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),T.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let a=[];try{a=await this.adapter.createToolsFromConnectors([s])}catch(c){T.error(`Failed to create tools from connector for server '${n}': ${c}`);continue}const i=this.serverTools[n];!i||!KE(i,a)?(this.serverTools[n]=a,this.initializedServers[n]=!0,T.debug(`Prefetched ${a.length} tools for server '${n}'.`)):T.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){T.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){T.level==="debug"&&this.logState("Providing tools to agent");const t=this.overrideManagementTools??[new uP(this),new fP(this),new hP(this),new lP(this),new gP(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return T.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...t,...n]}return t}},G(Mr,"ServerManager"),Mr),Rr,Pc=(Rr=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(t={}){this.customCallbacks=t.customCallbacks,this.verbose=t.verbose??!1,this.observe=t.observe??!0,this.agentId=t.agentId,this.metadata=t.metadata,this.metadataProvider=t.metadataProvider,this.tagsProvider=t.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:t,langfuseInitPromise:n}=await $a(async()=>{const{langfuseHandler:s,langfuseInitPromise:a}=await Promise.resolve().then(()=>qd);return{langfuseHandler:s,langfuseInitPromise:a}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await $a(async()=>{const{initializeLangfuse:a}=await Promise.resolve().then(()=>qd);return{initializeLangfuse:a}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),T.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const s=n();s&&await s}const r=t();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),T.debug("ObservabilityManager: Langfuse handler available"))}catch{T.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(T.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?T.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):T.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(T.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(t=>t.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const t=await this.getCallbacks(),n=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},s=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&t.length>0,callbackCount:t.length,handlerNames:n,metadata:r,tags:s}}addCallback(t){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(t),T.debug(`ObservabilityManager: Added custom callback: ${t.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],T.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const t=await this.getCallbacks();for(const n of t)"flushAsync"in n&&typeof n.flushAsync=="function"&&await n.flushAsync();T.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const t=await this.getCallbacks();for(const n of t)"shutdownAsync"in n&&typeof n.shutdownAsync=="function"?await n.shutdownAsync():"shutdown"in n&&typeof n.shutdown=="function"&&await n.shutdown();T.debug("ObservabilityManager: All handlers shutdown")}toString(){const t=this.handlerNames;return t.length>0?`ObservabilityManager(handlers=${t.join(", ")})`:"ObservabilityManager(no handlers)"}},G(Rr,"ObservabilityManager"),Rr),$r,_P=($r=class{},G($r,"BaseTelemetryEvent"),$r),Lr,wP=(Lr=class extends _P{constructor(t){super(),this.data=t}get name(){return"mcp_agent_execution"}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}},G(Lr,"MCPAgentExecutionEvent"),Lr);function Ra(){try{if(typeof __dirname>"u"||typeof Po>"u")return"unknown";const e=Da(__dirname,"../../package.json");return JSON.parse((void 0)(e,"utf-8")).version||"unknown"}catch{return"unknown"}}G(Ra,"getPackageVersion");function ry(e){return e._llm_type||e.constructor.name.toLowerCase()}G(ry,"getModelProvider");function sy(e){if("_identifyingParams"in e){const t=e._identifyingParams;if(typeof t=="object"&&t!==null){for(const n of["model","modelName","model_name","modelId","model_id","deploymentName","deployment_name"])if(n in t)return String(t[n])}}return e.model||e.modelName||e.constructor.name}G(sy,"getModelName");function ay(e){return[ry(e),sy(e)]}G(ay,"extractModelInfo");function _s(){try{return typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")||typeof globalThis.EdgeRuntime<"u"||typeof globalThis.Deno<"u"?!1:typeof process<"u"&&!0&&typeof __dirname<"u"&&(typeof Po<"u"&&typeof Po<"u"&&!1)}catch{return!1}}G(_s,"isNodeJSEnvironment");var jr,vP=(jr=class{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,r=setTimeout(()=>n.abort(),this.timeout),s=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(r),!s.ok)throw new Error(`HTTP error! status: ${s.status}`)}catch(n){T.debug(`Failed to send Scarf event: ${n}`)}}},G(jr,"ScarfEventLogger"),jr);function Nc(){if(!_s())return"/tmp/mcp_use_cache";const e=ci.XDG_CACHE_HOME;if(e&&m_(e))return e;const t=(void 0)();return Da(t,".cache")}G(Nc,"getCacheHome");var Rt,Mc=(Rt=class{USER_ID_PATH=Da(Nc(),"mcp_use_3","telemetry_user_id");VERSION_DOWNLOAD_PATH=Da(Nc(),"mcp_use","download_version");PROJECT_API_KEY="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";HOST="https://eu.i.posthog.com";SCARF_GATEWAY_URL="https://mcpuse.gateway.scarf.sh/events-ts";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogClient=null;_scarfClient=null;_source="typescript";constructor(){const t=_s(),n=typeof process<"u"&&ci?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()==="false"||!1;if(this._source=typeof process<"u"&&ci?.MCP_USE_TELEMETRY_SOURCE||"typescript",n)this._posthogClient=null,this._scarfClient=null,T.debug("Telemetry disabled via environment variable");else if(!t)this._posthogClient=null,this._scarfClient=null,T.debug("Telemetry disabled - non-Node.js environment detected (e.g., Cloudflare Workers)");else{T.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.");try{this._posthogClient=new ZE(this.PROJECT_API_KEY,{host:this.HOST,disableGeoip:!1})}catch(r){T.warn(`Failed to initialize PostHog telemetry: ${r}`),this._posthogClient=null}try{this._scarfClient=new vP(this.SCARF_GATEWAY_URL,3e3)}catch(r){T.warn(`Failed to initialize Scarf telemetry: ${r}`),this._scarfClient=null}}}static getInstance(){return Rt.instance||(Rt.instance=new Rt),Rt.instance}setSource(t){this._source=t,T.debug(`Telemetry source set to: ${t}`)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!_s())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{if(!(void 0)(this.USER_ID_PATH)){T.debug(`Creating user ID path: ${this.USER_ID_PATH}`),(void 0)(cu(this.USER_ID_PATH),{recursive:!0});const n=gy();(void 0)(this.USER_ID_PATH,n),this._currUserId=n,T.debug(`User ID path created: ${this.USER_ID_PATH}`)}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(n=>T.debug(`Failed to track package download: ${n}`))}catch(t){T.debug(`Failed to get/create user ID: ${t}`),this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}async capture(t){if(!(!this._posthogClient&&!this._scarfClient)){if(this._posthogClient)try{const n={...t.properties};n.mcp_use_version=Ra(),n.language="typescript",n.source=this._source,this._posthogClient.capture({distinctId:this.userId,event:t.name,properties:n})}catch(n){T.debug(`Failed to track PostHog event ${t.name}: ${n}`)}if(this._scarfClient)try{const n={};n.mcp_use_version=Ra(),n.user_id=this.userId,n.event=t.name,n.language="typescript",n.source=this._source,await this._scarfClient.logEvent(n)}catch(n){T.debug(`Failed to track Scarf event ${t.name}: ${n}`)}}}async trackPackageDownload(t){if(this._scarfClient&&_s())try{const n=Ra();let r=!1,s=!1;if((void 0)(this.VERSION_DOWNLOAD_PATH)||(r=!0,s=!0,(void 0)(cu(this.VERSION_DOWNLOAD_PATH),{recursive:!0}),(void 0)(this.VERSION_DOWNLOAD_PATH,n)),r){T.debug(`Tracking package download event with properties: ${JSON.stringify(t)}`);const a={...t||{}};a.mcp_use_version=n,a.user_id=this.userId,a.event="package_download",a.first_download=s,a.language="typescript",a.source=this._source,await this._scarfClient.logEvent(a)}}catch(n){T.debug(`Failed to track Scarf package_download event: ${n}`)}}async trackAgentExecution(t){const n=new wP(t);await this.capture(n)}flush(){if(this._posthogClient)try{this._posthogClient.flush(),T.debug("PostHog client telemetry queue flushed")}catch(t){T.debug(`Failed to flush PostHog client: ${t}`)}this._scarfClient&&T.debug("Scarf telemetry events sent immediately (no flush needed)")}shutdown(){if(this._posthogClient)try{this._posthogClient.shutdown(),T.debug("PostHog client shutdown successfully")}catch(t){T.debug(`Error shutting down PostHog client: ${t}`)}this._scarfClient&&T.debug("Scarf telemetry client shutdown (no action needed)")}},G(Rt,"Telemetry"),su(Rt,"instance",null),Rt);function bP(e){Mc.getInstance().setSource(e)}G(bP,"setTelemetrySource");var SP="/api/v1/chats",TP="/api/v1/chats/{chat_id}/execute",Dr,iy=(Dr=class{agentId;apiKey;baseUrl;chatId=null;constructor(t){this.agentId=t.agentId,this.baseUrl=t.baseUrl??"https://cloud.mcp-use.com";const n=t.apiKey??ci.MCP_USE_API_KEY;if(!n)throw new Error("API key is required for remote execution. Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. You can get an API key from https://cloud.mcp-use.com");this.apiKey=n}pydanticToJsonSchema(t){return ya(t)}parseStructuredResponse(t,n){let r;if(typeof t=="object"&&t!==null)if("result"in t){const s=t.result;typeof s=="object"&&s!==null&&"result"in s?r=s.result:r=s}else r=t;else if(typeof t=="string")try{r=JSON.parse(t)}catch{r={content:t}}else r=t;try{return n.parse(r)}catch(s){T.warn(`Failed to parse structured output: ${s}`);const a=n._def?.shape();if(a&&"content"in a)return n.parse({content:String(r)});throw s}}async createChatSession(){const t={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},n={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${SP}`;T.info(`📝 Creating chat session for agent ${this.agentId}`);try{const s=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(t)});if(!s.ok){const o=await s.text(),c=s.status;throw c===404?new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`):new Error(`Failed to create chat session: ${c} - ${o}`)}const i=(await s.json()).id;return T.info(`✅ Chat session created: ${i}`),i}catch(s){throw s instanceof Error?new TypeError(`Failed to create chat session: ${s.message}`):new Error(`Failed to create chat session: ${String(s)}`)}}async run(t,n,r,s,a){s!==void 0&&T.warn("External history is not yet supported for remote execution");try{T.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const i=this.chatId,o={query:t,max_steps:n??10};a&&(o.output_schema=this.pydanticToJsonSchema(a),T.info("🔧 Using structured output with schema"));const c={"Content-Type":"application/json","x-api-key":this.apiKey},l=`${this.baseUrl}${TP.replace("{chat_id}",i)}`;T.info(`🚀 Executing agent in chat ${i}`);const u=await fetch(l,{method:"POST",headers:c,body:JSON.stringify(o),signal:AbortSignal.timeout(3e5)});if(!u.ok){const h=await u.text(),p=u.status;throw p===401?(T.error(`❌ Authentication failed: ${h}`),new Error("Authentication failed: Invalid or missing API key. Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.")):p===403?(T.error(`❌ Access forbidden: ${h}`),new Error(`Access denied: You don't have permission to execute agent '${this.agentId}'. Check if the agent exists and you have the necessary permissions.`)):p===404?(T.error(`❌ Agent not found: ${h}`),new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`)):p===422?(T.error(`❌ Validation error: ${h}`),new Error(`Request validation failed: ${h}. Please check your query parameters and output schema format.`)):p===500?(T.error(`❌ Server error: ${h}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(T.error(`❌ Remote execution failed with status ${p}: ${h}`),new Error(`Remote agent execution failed: ${p} - ${h}`))}const d=await u.json();if(T.info(`🔧 Response: ${JSON.stringify(d)}`),T.info("✅ Remote execution completed successfully"),typeof d=="object"&&d!==null){if(d.status==="error"||d.error!==null){const h=d.error??String(d);throw T.error(`❌ Remote agent execution failed: ${h}`),new Error(`Remote agent execution failed: ${h}`)}if(String(d).includes("failed to initialize"))throw T.error(`❌ Agent initialization failed: ${d}`),new Error(`Agent initialization failed on remote server. This usually indicates:
492
492
  • Invalid agent configuration (LLM model, system prompt)
493
493
  • Missing or invalid MCP server configurations
494
494
  • Network connectivity issues with MCP servers
@@ -567,4 +567,4 @@ ${f}`);const S=await s.stream(f);let b=null,v=0;for await(const E of S){if(v++,T
567
567
 
568
568
  Make sure you gather ALL the required information during your task execution.
569
569
  If any required information is missing, continue working to find it.
570
- `}catch(r){return T.warn(`Could not extract schema details: ${r}`),t}}},G(Ur,"MCPAgent"),Ur),Me={},kP=Me.MCP_USE_LANGFUSE?.toLowerCase()==="false",Bs={handler:null,client:null,initPromise:null};async function Xl(e,t,n,r){try{const s=await La(()=>import("./index-DGitogYY.js"),__vite__mapDeps([0,1,2,3,4])).catch(()=>null);if(!s){T.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:a}=s,u=class u extends a{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(h,p,f,y,S){super(h),this.agentId=p,this.metadata=f,this.metadataProvider=y,this.tagsProvider=S,this.verbose=h?.verbose??!1}async handleChainStart(h,p,f,y,S,b,v,w){T.debug("Langfuse: Chain start intercepted");const E=this.getCustomTags(),A=this.getMetadata(),I=[...S||[],...E],k={...b||{},...A};return this.verbose&&(T.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(I)}`),T.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(k)}`)),super.handleChainStart(h,p,f,y,I,k,v,w)}getCustomTags(){const h=[],p=this.getEnvironmentTag();if(p&&h.push(`env:${p}`),this.agentId&&h.push(`agent_id:${this.agentId}`),this.tagsProvider){const f=this.tagsProvider();f&&f.length>0&&h.push(...f)}return h}getMetadata(){const h={},p=this.getEnvironmentTag();if(p&&(h.env=p),this.agentId&&(h.agent_id=this.agentId),this.metadata&&Object.assign(h,this.metadata),this.metadataProvider){const f=this.metadataProvider();f&&Object.assign(h,f)}return h}getEnvironmentTag(){const h=Me.MCP_USE_AGENT_ENV;if(!h)return"unknown";const p=h.toLowerCase();return p==="local"||p==="development"?"local":p==="production"||p==="prod"?"production":p==="staging"||p==="stage"?"staging":p==="hosted"||p==="cloud"?"hosted":p.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...h){return T.debug("Langfuse: LLM start intercepted"),this.verbose&&T.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return T.debug("Langfuse: Tool start intercepted"),this.verbose&&T.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return T.debug("Langfuse: Retriever start intercepted"),this.verbose&&T.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return T.debug("Langfuse: Agent action intercepted"),this.verbose&&T.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return T.debug("Langfuse: Agent end intercepted"),this.verbose&&T.debug(`Langfuse: Agent end args: ${JSON.stringify(h)}`),super.handleAgentEnd(...h)}};G(u,"LoggingCallbackHandler");let i=u;const o=t||(n?n():{}),c=r?r():[],l={publicKey:Me.LANGFUSE_PUBLIC_KEY,secretKey:Me.LANGFUSE_SECRET_KEY,baseUrl:Me.LANGFUSE_HOST||Me.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Me.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Me.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Me.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Me.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Me.LANGFUSE_ENABLED!=="false",traceName:o.trace_name||Me.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:o.session_id||void 0,userId:o.user_id||void 0,tags:c.length>0?c:void 0,metadata:o||void 0};T.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Bs.handler=new i(l,e,t,n,r),T.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await La(()=>import("./index-Ah_aViv6.js"),__vite__mapDeps([1,2,3,4])).catch(()=>null);if(d){const{Langfuse:h}=d;Bs.client=new h({publicKey:Me.LANGFUSE_PUBLIC_KEY,secretKey:Me.LANGFUSE_SECRET_KEY,baseUrl:Me.LANGFUSE_HOST||"https://cloud.langfuse.com"}),T.debug("Langfuse client initialized")}}catch(d){T.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){T.debug(`Langfuse initialization error: ${s}`)}}G(Xl,"initializeLangfuse");kP?T.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Me.LANGFUSE_PUBLIC_KEY||!Me.LANGFUSE_SECRET_KEY?T.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Bs.initPromise=Xl();var OP=G(()=>Bs.handler,"langfuseHandler"),xP=G(()=>Bs.initPromise,"langfuseInitPromise");const UP=Object.freeze(Object.defineProperty({__proto__:null,AIMessage:j,BaseAdapter:ty,BaseConnector:_y,BaseMessage:Ke,BrowserOAuthClientProvider:wy,HttpConnector:vy,HumanMessage:ue,LangChainAdapter:Dn,Logger:by,MCPAgent:AP,MCPClient:Sy,MCPSession:Ty,ObservabilityManager:Pc,RemoteAgent:iy,SystemMessage:fe,ToolMessage:X,WebSocketConnector:Ey,createReadableStreamFromGenerator:ah,logger:T,onMcpAuthorization:Cy,streamEventsToAISDK:sh,streamEventsToAISDKWithTools:ih},Symbol.toStringTag,{value:"Module"})),qd=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:Xl,langfuseHandler:OP,langfuseInitPromise:xP},Symbol.toStringTag,{value:"Module"}));export{j as A,es as B,Qn as C,hi as F,ue as H,fe as S,X as T,Ke as a,mt as b,UP as c,ot as m};
570
+ `}catch(r){return T.warn(`Could not extract schema details: ${r}`),t}}},G(Ur,"MCPAgent"),Ur),Me={},kP=Me.MCP_USE_LANGFUSE?.toLowerCase()==="false",Bs={handler:null,client:null,initPromise:null};async function Xl(e,t,n,r){try{const s=await $a(()=>import("./index-CvPVR03j.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).catch(()=>null);if(!s){T.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:a}=s,u=class u extends a{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(h,p,f,y,S){super(h),this.agentId=p,this.metadata=f,this.metadataProvider=y,this.tagsProvider=S,this.verbose=h?.verbose??!1}async handleChainStart(h,p,f,y,S,b,v,w){T.debug("Langfuse: Chain start intercepted");const E=this.getCustomTags(),A=this.getMetadata(),I=[...S||[],...E],k={...b||{},...A};return this.verbose&&(T.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(I)}`),T.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(k)}`)),super.handleChainStart(h,p,f,y,I,k,v,w)}getCustomTags(){const h=[],p=this.getEnvironmentTag();if(p&&h.push(`env:${p}`),this.agentId&&h.push(`agent_id:${this.agentId}`),this.tagsProvider){const f=this.tagsProvider();f&&f.length>0&&h.push(...f)}return h}getMetadata(){const h={},p=this.getEnvironmentTag();if(p&&(h.env=p),this.agentId&&(h.agent_id=this.agentId),this.metadata&&Object.assign(h,this.metadata),this.metadataProvider){const f=this.metadataProvider();f&&Object.assign(h,f)}return h}getEnvironmentTag(){const h=Me.MCP_USE_AGENT_ENV;if(!h)return"unknown";const p=h.toLowerCase();return p==="local"||p==="development"?"local":p==="production"||p==="prod"?"production":p==="staging"||p==="stage"?"staging":p==="hosted"||p==="cloud"?"hosted":p.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...h){return T.debug("Langfuse: LLM start intercepted"),this.verbose&&T.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return T.debug("Langfuse: Tool start intercepted"),this.verbose&&T.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return T.debug("Langfuse: Retriever start intercepted"),this.verbose&&T.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return T.debug("Langfuse: Agent action intercepted"),this.verbose&&T.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return T.debug("Langfuse: Agent end intercepted"),this.verbose&&T.debug(`Langfuse: Agent end args: ${JSON.stringify(h)}`),super.handleAgentEnd(...h)}};G(u,"LoggingCallbackHandler");let i=u;const o=t||(n?n():{}),c=r?r():[],l={publicKey:Me.LANGFUSE_PUBLIC_KEY,secretKey:Me.LANGFUSE_SECRET_KEY,baseUrl:Me.LANGFUSE_HOST||Me.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Me.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Me.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Me.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Me.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Me.LANGFUSE_ENABLED!=="false",traceName:o.trace_name||Me.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:o.session_id||void 0,userId:o.user_id||void 0,tags:c.length>0?c:void 0,metadata:o||void 0};T.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Bs.handler=new i(l,e,t,n,r),T.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await $a(()=>import("./index-x_xzGcAx.js"),__vite__mapDeps([1,2,3,4,5,6,7])).catch(()=>null);if(d){const{Langfuse:h}=d;Bs.client=new h({publicKey:Me.LANGFUSE_PUBLIC_KEY,secretKey:Me.LANGFUSE_SECRET_KEY,baseUrl:Me.LANGFUSE_HOST||"https://cloud.langfuse.com"}),T.debug("Langfuse client initialized")}}catch(d){T.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){T.debug(`Langfuse initialization error: ${s}`)}}G(Xl,"initializeLangfuse");kP?T.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Me.LANGFUSE_PUBLIC_KEY||!Me.LANGFUSE_SECRET_KEY?T.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Bs.initPromise=Xl();var OP=G(()=>Bs.handler,"langfuseHandler"),xP=G(()=>Bs.initPromise,"langfuseInitPromise");const BP=Object.freeze(Object.defineProperty({__proto__:null,AIMessage:j,BaseAdapter:ty,BaseConnector:yy,BaseMessage:Ke,BrowserOAuthClientProvider:_y,HttpConnector:wy,HumanMessage:ue,LangChainAdapter:Dn,Logger:vy,MCPAgent:AP,MCPClient:by,MCPSession:Sy,ObservabilityManager:Pc,RemoteAgent:iy,SystemMessage:fe,ToolMessage:X,WebSocketConnector:Ty,createReadableStreamFromGenerator:ah,logger:T,onMcpAuthorization:Ey,streamEventsToAISDK:sh,streamEventsToAISDKWithTools:ih},Symbol.toStringTag,{value:"Module"})),qd=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:Xl,langfuseHandler:OP,langfuseInitPromise:xP},Symbol.toStringTag,{value:"Module"}));export{j as A,es as B,Qn as C,hi as F,ue as H,fe as S,X as T,Ke as a,mt as b,BP as c,ot as m};