@mcp-use/inspector 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/cli.js +295 -19
  2. package/dist/client/assets/__vite-browser-external-CHS79mP1.js +8 -0
  3. package/dist/client/assets/browser-BdCJ_qyB.js +38211 -0
  4. package/dist/client/assets/chunk-VL2OQCWN-CxD8xDNw.js +6475 -0
  5. package/dist/client/assets/display-YIYC6WJE-B6ZSv77R.js +44742 -0
  6. package/dist/client/assets/embeddings-DlCMB9po.js +21 -0
  7. package/dist/client/assets/index-B0NYybvW.js +5371 -0
  8. package/dist/client/assets/index-CKXUnlZB.js +94617 -0
  9. package/dist/client/assets/index-Cb09SlUY.js +17535 -0
  10. package/dist/client/assets/index-CsP5AdwX.js +10699 -0
  11. package/dist/client/assets/index-DX0TIfSM.js +102 -0
  12. package/dist/client/assets/index-Q_pqNaNk.js +1780 -0
  13. package/dist/client/assets/index-kVFYovMy.css +5752 -0
  14. package/dist/client/assets/path-QsnVvLoj.js +62 -0
  15. package/dist/client/assets/transport-wrapper-browser-ChPHVnHg.js +165 -0
  16. package/dist/client/assets/winston-qgF6niUt.js +12326 -0
  17. package/dist/client/index.html +3 -3
  18. package/dist/server/{chunk-37X7HLUV.js → chunk-3T2VCYG6.js} +87 -13
  19. package/dist/server/chunk-CVECQ7BJ.js +78 -0
  20. package/dist/server/{chunk-555LGZ3I.js → chunk-FS77NTZN.js} +133 -10
  21. package/dist/server/chunk-PKBMQBKP.js +7 -0
  22. package/dist/server/{chunk-WYBXXYSP.js → chunk-RRPLH7DL.js} +1 -1
  23. package/dist/server/{chunk-PYGYQT2G.js → chunk-S7NOZBMG.js} +3 -3
  24. package/dist/server/{chunk-DGUMOD7P.js → chunk-ZONLXYBO.js} +92 -10
  25. package/dist/server/cli.js +6 -4
  26. package/dist/server/index.js +7 -5
  27. package/dist/server/middleware.js +7 -5
  28. package/dist/server/rpc-log-bus.d.ts +17 -0
  29. package/dist/server/rpc-log-bus.d.ts.map +1 -0
  30. package/dist/server/rpc-log-bus.js +7 -0
  31. package/dist/server/server.js +6 -4
  32. package/dist/server/shared-routes.d.ts.map +1 -1
  33. package/dist/server/shared-routes.js +4 -2
  34. package/dist/server/shared-static.js +3 -2
  35. package/dist/server/shared-utils-browser.d.ts +2 -1
  36. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  37. package/dist/server/shared-utils-browser.js +2 -1
  38. package/dist/server/shared-utils.d.ts +4 -1
  39. package/dist/server/shared-utils.d.ts.map +1 -1
  40. package/dist/server/shared-utils.js +2 -1
  41. package/dist/server/transport-wrapper.d.ts +6 -0
  42. package/dist/server/transport-wrapper.d.ts.map +1 -0
  43. package/dist/server/transport-wrapper.js +68 -0
  44. package/dist/server/utils.js +1 -0
  45. package/package.json +12 -3
  46. package/dist/client/assets/__vite-browser-external-DFygW7-s.js +0 -1
  47. package/dist/client/assets/chunk-VL2OQCWN-iRVOQjqe.js +0 -8
  48. package/dist/client/assets/display-LIYVTGEU-D2dm8q2H.js +0 -30
  49. package/dist/client/assets/embeddings-Dcyp0Vlp.js +0 -1
  50. package/dist/client/assets/index-6zrNEwtM.js +0 -4
  51. package/dist/client/assets/index-CAnbiFOL.css +0 -1
  52. package/dist/client/assets/index-CB1s6Wr6.js +0 -146
  53. package/dist/client/assets/index-CoMldIFv.js +0 -2
  54. package/dist/client/assets/index-DRz5BQNA.js +0 -1
  55. package/dist/client/assets/index-DUf1336L.js +0 -1559
  56. package/dist/client/assets/index-DmIKR5St.js +0 -1
  57. package/dist/client/assets/index-DpUpZFq2.js +0 -25
  58. package/dist/client/assets/index-DzegZXPW.js +0 -40
  59. package/dist/client/assets/langfuse-C4HKZ3NL-vCtAvQQV.js +0 -564
  60. package/dist/client/assets/path-C9FudP8b.js +0 -1
  61. package/dist/client/assets/winston-BVJ8PyEn.js +0 -37
@@ -1,564 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-LIYVTGEU-D2dm8q2H.js","assets/index-DUf1336L.js","assets/index-CAnbiFOL.css","assets/index-6zrNEwtM.js","assets/index-DmIKR5St.js","assets/chunk-VL2OQCWN-iRVOQjqe.js","assets/index-DRz5BQNA.js","assets/__vite-browser-external-DFygW7-s.js","assets/path-C9FudP8b.js"])))=>i.map(i=>d[i]);
2
- var yy=Object.defineProperty;var _y=(e,t,n)=>t in e?yy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var du=(e,t,n)=>_y(e,typeof t!="symbol"?t+"":t,n);import{_ as G,c as Wi,u as gt,a as Tt,d as bs,n as le,s as pe,e as Jt,o as Y,f as wy,Z as M,h as nt,i as hu,l as vr,j as vy,k as Ua,p as sh,m as Ur,r as Ss,q as Ba,t as E,w as Ts,v as by,B as Sy,x as Ty,H as Ey,L as Cy,y as Ay,M as ky,W as Oy,z as xy}from"./index-DUf1336L.js";import{u as Iy,w as Hc,x as Py,y as ze,z as Ny,A as My,B as Ry,C as $y,D as Ly,E as jy,F as Dy,G as Fy,H as Uy,I as By,d as kn,J as zy,g as $e,K as Hy,L as ah,M as Vy,N as Gy,O as za,h as Vc,Q as Wy,R as Jy,S as Ky,U as Zy,W as qy,X as Yy,Y as Xy,Z as Qy,a0 as e_,a1 as t_,a2 as n_,a3 as pu,a4 as r_,a5 as s_,a6 as a_,a7 as i_,s as o_,v as ke,P as nn,p as Ha,a as Es,b as ih,c as oh,i as Gc,j as c_,f as l_,_ as u_,$ as d_,e as h_,k as p_,t as fu,l as ch,V as Wc,m as f_,n as br,o as m_,T as g_,q as Jc,r as y_,a8 as __}from"./chunk-VL2OQCWN-iRVOQjqe.js";import{o as Fo}from"./__vite-browser-external-DFygW7-s.js";import{j as Va,d as mu,i as w_}from"./path-C9FudP8b.js";var Ji,oa,Ki=0,Zi=0;function v_(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=Ji),i==null&&(i=oa)),a==null||i==null){var o=e.random||(e.rng||Iy)();a==null&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],!Ji&&!e._v6&&(a[0]|=1,Ji=a)),i==null&&(i=(o[6]<<8|o[7])&16383,oa===void 0&&!e._v6&&(oa=i))}var c=e.msecs!==void 0?e.msecs:Date.now(),l=e.nsecs!==void 0?e.nsecs:Zi+1,u=c-Ki+(l-Zi)/1e4;if(u<0&&e.clockseq===void 0&&(i=i+1&16383),(u<0||c>Ki)&&e.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ki=c,Zi=l,oa=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||Hc(s)}function b_(e){var t=typeof e=="string"?Py(e):e,n=S_(t);return typeof e=="string"?Hc(n):n}function S_(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 gu(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 yu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?gu(Object(n),!0).forEach(function(r){T_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gu(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function T_(e,t,n){return(t=E_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function E_(e){var t=C_(e,"string");return typeof t=="symbol"?t:t+""}function C_(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 A_(e={},t,n=0){var r=v_(yu(yu({},e),{},{_v6:!0}),new Uint8Array(16));return r=b_(r),Hc(r)}const k_=(e,t)=>{Ny.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Ry(e,n)},flatten:{value:n=>My(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},yi=ze("ZodError",k_,{Parent:Error}),O_=$y(yi),x_=jy(yi),I_=Ly(yi),P_=Dy(yi),ut=ze("ZodType",(e,t)=>(By.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)=>kn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>O_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>I_(e,n,r),e.parseAsync=async(n,r)=>x_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>P_(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(nw(n,r)),e.superRefine=n=>e.check(rw(n)),e.overwrite=n=>e.check(zy(n)),e.optional=()=>_u(e),e.nullable=()=>wu(e),e.nullish=()=>_u(wu(e)),e.nonoptional=n=>K_(e,n),e.array=()=>R_(e),e.or=n=>L_([e,n]),e.and=n=>D_(e,n),e.transform=n=>vu(e,U_(n)),e.default=n=>V_(e,n),e.prefault=n=>W_(e,n),e.catch=n=>q_(e,n),e.pipe=n=>vu(e,n),e.readonly=()=>Q_(e),e.describe=n=>{const r=e.clone();return $e.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return $e.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return $e.get(e);const r=e.clone();return $e.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),N_=ze("ZodAny",(e,t)=>{Uy.init(e,t),ut.init(e,t)});function ca(){return Fy(N_)}const M_=ze("ZodArray",(e,t)=>{n_.init(e,t),ut.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(pu(n,r)),e.nonempty=n=>e.check(pu(1,n)),e.max=(n,r)=>e.check(r_(n,r)),e.length=(n,r)=>e.check(s_(n,r)),e.unwrap=()=>e.element});function R_(e,t){return Vy(M_,e,t)}const $_=ze("ZodUnion",(e,t)=>{Ky.init(e,t),ut.init(e,t),e.options=t.options});function L_(e,t){return new $_({type:"union",options:e,...ah(t)})}const j_=ze("ZodIntersection",(e,t)=>{Zy.init(e,t),ut.init(e,t)});function D_(e,t){return new j_({type:"intersection",left:e,right:t})}const F_=ze("ZodTransform",(e,t)=>{Yy.init(e,t),ut.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(za(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(za(i))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function U_(e){return new F_({type:"transform",transform:e})}const B_=ze("ZodOptional",(e,t)=>{Vc.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _u(e){return new B_({type:"optional",innerType:e})}const z_=ze("ZodNullable",(e,t)=>{Wy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function wu(e){return new z_({type:"nullable",innerType:e})}const H_=ze("ZodDefault",(e,t)=>{Xy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function V_(e,t){return new H_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const G_=ze("ZodPrefault",(e,t)=>{Qy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function W_(e,t){return new G_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const J_=ze("ZodNonOptional",(e,t)=>{Jy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function K_(e,t){return new J_({type:"nonoptional",innerType:e,...ah(t)})}const Z_=ze("ZodCatch",(e,t)=>{e_.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function q_(e,t){return new Z_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Y_=ze("ZodPipe",(e,t)=>{qy.init(e,t),ut.init(e,t),e.in=t.in,e.out=t.out});function vu(e,t){return new Y_({type:"pipe",in:e,out:t})}const X_=ze("ZodReadonly",(e,t)=>{t_.init(e,t),ut.init(e,t)});function Q_(e){return new X_({type:"readonly",innerType:e})}const ew=ze("ZodCustom",(e,t)=>{a_.init(e,t),ut.init(e,t)});function tw(e){const t=new Gy({check:"custom"});return t._zod.check=e,t}function nw(e,t={}){return Hy(ew,e,t)}function rw(e){const t=tw(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(za(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(za(s))}},e(n.value,n)));return t}async function*lh(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(lh,"streamEventsToAISDK");function uh(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(uh,"createReadableStreamFromGenerator");async function*dh(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
- 🔧 Using tool: ${t.name}
4
- `;break;case"on_tool_end":yield`
5
- ✅ Tool completed: ${t.name}
6
- `;break}}G(dh,"streamEventsToAISDKWithTools");class sw{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:Wi.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in t||r.addIssue({code:Wi.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:Wi.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 gt(r)}static handleSingleType(t){if(t.type===void 0)return t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.properties?this.parseObject(t):Tt();switch(t.type){case"string":return this.parseString(t);case"number":case"integer":return this.parseNumberSchema(t);case"boolean":return bs();case"array":return this.parseArray(t);case"object":return this.parseObject(t);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(t){let n=le(),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=pe(),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 gt(a)}const n=t.items?this.parseSchema(t.items):Tt();let r=Jt(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,Y(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=Y(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 Tt();if(t.length===1)return this.parseSchema(t[0]);const n=[];for(const r of t)r.type==="null"?n.push(wy()):n.push(this.parseSchema(r));return n.length>=2?gt(n):n.length===1?n[0]:Tt()}static parseAllOf(t){if(t.length===0)return Tt();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 aw=Object.defineProperty,U=(e,t)=>{for(var n in t)aw(e,n,{get:t[n],enumerable:!0})};function iw(e,t){return t?.[e]||o_(e)}function ow(e,t){return t?.[e]||i_(e)}function hh(e,t,n){const r={};for(const s in e)Object.hasOwn(e,s)&&(r[t(s,n)]=e[s]);return r}var ph={};U(ph,{Serializable:()=>At,get_lc_unique_name:()=>_i});function bu(e){return Array.isArray(e)?[...e]:{...e}}function cw(e,t){const n=bu(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]=bu(o[c]),o=o[c]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return n}function _i(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 At=class fh{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,_i(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 fh||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:hh(Object.keys(n).length?cw(r,n):r,iw,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function On(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 Kc(e){return On(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function Zc(e){return On(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function lw(e){return On(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function mh(e){return On(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function gh(e){if(On(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 uw(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 Uo({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 dw(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 F(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 Mt(e){return typeof e=="number"}function qc(e){return e instanceof Uint8Array}function Su(e){try{return JSON.parse(e)}catch{return}}const Cs=e=>e();function hw(e){if(e.type==="char_location"&&$(e.document_title)&&Mt(e.start_char_index)&&Mt(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)&&Mt(e.start_page_number)&&Mt(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)&&Mt(e.start_block_index)&&Mt(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)&&Mt(e.start_block_index)&&Mt(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 yh(e){if(F(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(F(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 pw(e){function*t(){for(const n of e){const r=yh(n);r?yield r:yield n}}return Array.from(t())}function Tu(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n){if(F(r,"text")&&$(r.text)){const{text:s,citations:a,...i}=r;if(Vt(a)&&a.length){const o=a.reduce((c,l)=>{const u=hw(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(F(r,"thinking")&&$(r.thinking)){const{thinking:s,signature:a,...i}=r;yield{...i,type:"reasoning",reasoning:s,signature:a};continue}else if(F(r,"redacted_thinking")){yield{type:"non_standard",value:r};continue}else if(F(r,"tool_use")&&$(r.name)&&$(r.id)){yield{type:"tool_call",id:r.id,name:r.name,args:r.input};continue}else if(F(r,"input_json_delta")){if(mw(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(F(r,"server_tool_use")&&$(r.name)&&$(r.id)){const{name:s,id:a}=r;if(s==="web_search"){const i=Cs(()=>{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=Su(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=Cs(()=>{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=Su(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(F(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)=>F(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(F(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(F(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}else if(F(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(F(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}else if(F(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}else if(F(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}else{const s=yh(r);if(s){yield s;continue}}yield{type:"non_standard",value:r}}}return Array.from(t())}const fw={translateContent:Tu,translateContentChunk:Tu};function mw(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function gw(e){return Kc(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:Zc(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:mh(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function yw(e){return e.map(gw)}function _w(e){return!!(F(e,"image_url")&&H(e.image_url)||F(e,"input_audio")&&H(e.input_audio)||F(e,"file")&&H(e.file))}function ww(e){if(F(e,"image_url")&&H(e.image_url)&&$(e.image_url.url)){const t=Uo({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(F(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(F(e,"file")&&H(e.file)&&$(e.file.data)){const t=Uo({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 vw(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...Yc(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 bw(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...Yc(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 Yc(e){const t=[];for(const n of e)_w(n)?t.push(ww(n)):t.push(n);return t}function Sw(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 _h(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(F(r,"text")){const{text:s,annotations:a,...i}=r;Array.isArray(a)?yield{...i,type:"text",text:String(s),annotations:a.map(Sw)}: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(F(r,"web_search_call")){yield{id:r.id,type:"server_tool_call",name:"web_search",args:{query:r.query}};continue}else if(F(r,"file_search_call")){yield{id:r.id,type:"server_tool_call",name:"file_search",args:{query:r.query}};continue}else if(F(r,"computer_call")){yield{type:"non_standard",value:r};continue}else if(F(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=Cs(()=>{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(F(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(F(r,"mcp_call")){yield{id:r.id,type:"server_tool_call",name:"mcp_call",args:r.input};continue}else if(F(r,"mcp_list_tools")){yield{id:r.id,type:"server_tool_call",name:"mcp_list_tools",args:r.input};continue}else if(F(r,"mcp_approval_request")){yield{type:"non_standard",value:r};continue}else if(F(r,"image_generation_call")){yield{type:"non_standard",value:r};continue}H(r)&&(yield{type:"non_standard",value:r})}}return Array.from(t())}function Tw(e){function*t(){yield*_h(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 Ew={translateContent:e=>typeof e.content=="string"?vw(e):_h(e),translateContentChunk:e=>typeof e.content=="string"?bw(e):Tw(e)};function wh(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function Cw(e,t="pretty"){return t==="pretty"?Aw(e):JSON.stringify(e)}function Aw(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
- `)}const qi=Symbol.for("langchain.message");function Yn(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.some(n=>On(n))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?Js(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(n=>On(n))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function vh(e,t){return e==="error"||t==="error"?"error":"success"}function kw(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 rt=class extends At{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[qi]=!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[yw,Yc,pw].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&&qi in e&&e[qi]===!0&&wh(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=kw(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return Cw(this,e)}};function Ow(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]=Js(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 Js(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 bh(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
- Left ${typeof e}
9
- Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return Js(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.
10
- Left ${e}
11
- Right ${t}`)}var Nn=class extends rt{static isInstance(e){return super.isInstance(e)&&"concat"in e&&typeof e.concat=="function"}};function Sh(e){return typeof e.role=="string"}function Pe(e){return typeof e?._getType=="function"}function As(e){return Pe(e)&&typeof e.concat=="function"}var Th={};U(Th,{ToolMessage:()=>X,ToolMessageChunk:()=>Ks,defaultToolCallParser:()=>Qc,isDirectToolOutput:()=>Xc,isToolMessage:()=>el,isToolMessageChunk:()=>Eh});function Xc(e){return e!=null&&typeof e=="object"&&"lc_direct_tool_output"in e&&e.lc_direct_tool_output===!0}var X=class extends rt{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(e,t,n){const r=typeof e=="string"||Array.isArray(e)?{content:e,name:n,tool_call_id:t}:e;super(r),this.tool_call_id=r.tool_call_id,this.artifact=r.artifact,this.status=r.status,this.metadata=r.metadata}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Ks=class extends Nn{type="tool";tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){const t=this.constructor;return new t({content:Yn(this.content,e.content),additional_kwargs:Ue(this.additional_kwargs,e.additional_kwargs),response_metadata:Ue(this.response_metadata,e.response_metadata),artifact:bh(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:vh(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function Qc(e){const t=[],n=[];for(const r of e)if(r.function){const s=r.function.name;try{const a=JSON.parse(r.function.arguments);t.push({name:s||"",args:a||{},id:r.id})}catch{n.push({name:s,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[t,n]}function el(e){return typeof e=="object"&&e!==null&&"getType"in e&&typeof e.getType=="function"&&e.getType()==="tool"}function Eh(e){return e._getType()==="tool"}function fs(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="tool_call")}function xw(e){return!!(e&&typeof e=="object"&&"toolCall"in e&&e.toolCall!=null&&typeof e.toolCall=="object"&&"id"in e.toolCall&&typeof e.toolCall.id=="string")}var ks=class extends Error{output;constructor(e,t){super(e),this.output=t}};function Bo(e,t=Br){e=e.trim();const n=e.indexOf("```");if(n===-1)return t(e);let r=e.substring(n+3);r.startsWith(`json
12
- `)?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith(`
13
- `)&&(r=r.substring(1));const s=r.indexOf("```");let a=r;return s!==-1&&(a=r.substring(0,s)),t(a.trim())}function Br(e){if(typeof e>"u")return null;try{return JSON.parse(e)}catch{}let t="";const n=[];let r=!1,s=!1;for(let a of e){if(r)a==='"'&&!s?r=!1:a===`
14
- `&&!s?a="\\n":a==="\\"?s=!s:s=!1;else if(a==='"')r=!0,s=!1;else if(a==="{")n.push("}");else if(a==="[")n.push("]");else if(a==="}"||a==="]")if(n&&n[n.length-1]===a)n.pop();else return null;t+=a}r&&(t+='"');for(let a=n.length-1;a>=0;a-=1)t+=n[a];try{return JSON.parse(t)}catch{return null}}function tl(e){switch(e){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function Iw(e){if(H(e.document)&&H(e.document.source)){const t=H(e.document)&&$(e.document.format)?e.document.format:"",n=tl(t);if(H(e.document.source)){if(H(e.document.source.s3Location)&&$(e.document.source.s3Location.uri))return{type:"file",mimeType:n,fileId:e.document.source.s3Location.uri};if(qc(e.document.source.bytes))return{type:"file",mimeType:n,data:e.document.source.bytes};if($(e.document.source.text))return{type:"file",mimeType:n,data:Buffer.from(e.document.source.text).toString("base64")};if(Vt(e.document.source.content)){const r=e.document.source.content.reduce((s,a)=>H(a)&&$(a.text)?s+a.text:s,"");return{type:"file",mimeType:n,data:r}}}}return{type:"non_standard",value:e}}function Pw(e){if(F(e,"image")&&H(e.image)){const t=H(e.image)&&$(e.image.format)?e.image.format:"",n=tl(t);if(H(e.image.source)){if(H(e.image.source.s3Location)&&$(e.image.source.s3Location.uri))return{type:"image",mimeType:n,fileId:e.image.source.s3Location.uri};if(qc(e.image.source.bytes))return{type:"image",mimeType:n,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}function Nw(e){if(F(e,"video")&&H(e.video)){const t=H(e.video)&&$(e.video.format)?e.video.format:"",n=tl(t);if(H(e.video.source)){if(H(e.video.source.s3Location)&&$(e.video.source.s3Location.uri))return{type:"video",mimeType:n,fileId:e.video.source.s3Location.uri};if(qc(e.video.source.bytes))return{type:"video",mimeType:n,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}function Eu(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n){if(F(r,"cache_point")){yield{type:"non_standard",value:r};continue}else if(F(r,"citations_content")&&H(r.citationsContent)){const s=Vt(r.citationsContent.content)?r.citationsContent.content.reduce((i,o)=>H(o)&&$(o.text)?i+o.text:i,""):"",a=Vt(r.citationsContent.citations)?r.citationsContent.citations.reduce((i,o)=>{if(H(o)){const c=Vt(o.sourceContent)?o.sourceContent.reduce((u,d)=>H(d)&&$(d.text)?u+d.text:u,""):"",l=Cs(()=>{if(H(o.location)){const u=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(H(u))return{source:Mt(u.documentIndex)?u.documentIndex.toString():void 0,startIndex:Mt(u.start)?u.start:void 0,endIndex:Mt(u.end)?u.end:void 0}}return{}});i.push({type:"citation",citedText:c,...l})}return i},[]):[];yield{type:"text",text:s,annotations:a};continue}else if(F(r,"document")&&H(r.document)){yield Iw(r);continue}else if(F(r,"guard_content")){yield{type:"non_standard",value:r};continue}else if(F(r,"image")&&H(r.image)){yield Pw(r);continue}else if(F(r,"reasoning_content")&&$(r.reasoningText)){yield{type:"reasoning",reasoning:r.reasoningText};continue}else if(F(r,"text")&&$(r.text)){yield{type:"text",text:r.text};continue}else if(F(r,"tool_result")){yield{type:"non_standard",value:r};continue}else{if(F(r,"tool_call"))continue;if(F(r,"video")&&H(r.video)){yield Nw(r);continue}}yield{type:"non_standard",value:r}}}return Array.from(t())}const Mw={translateContent:Eu,translateContentChunk:Eu};function Cu(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n){if(F(r,"text")&&$(r.text)){yield{type:"text",text:r.text};continue}else if(F(r,"inlineData")&&H(r.inlineData)&&$(r.inlineData.mimeType)&&$(r.inlineData.data)){yield{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data};continue}else if(F(r,"functionCall")&&H(r.functionCall)&&$(r.functionCall.name)&&H(r.functionCall.args)){yield{type:"tool_call",id:e.id,name:r.functionCall.name,args:r.functionCall.args};continue}else if(F(r,"functionResponse")){yield{type:"non_standard",value:r};continue}else if(F(r,"fileData")&&H(r.fileData)&&$(r.fileData.mimeType)&&$(r.fileData.fileUri)){yield{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri};continue}else if(F(r,"executableCode")){yield{type:"non_standard",value:r};continue}else if(F(r,"codeExecutionResult")){yield{type:"non_standard",value:r};continue}yield{type:"non_standard",value:r}}}return Array.from(t())}const Rw={translateContent:Cu,translateContentChunk:Cu};function Au(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n){if(F(r,"reasoning")&&$(r.reasoning)){const s=Cs(()=>{const a=n.indexOf(r);if(Vt(e.additional_kwargs?.signatures)&&a>=0)return e.additional_kwargs.signatures.at(a)});$(s)?yield{type:"reasoning",reasoning:r.reasoning,signature:s}:yield{type:"reasoning",reasoning:r.reasoning};continue}else if(F(r,"text")&&$(r.text)){yield{type:"text",text:r.text};continue}else if(F(r,"image_url")){if($(r.image_url))if(r.image_url.startsWith("data:")){const s=/^data:([^;]+);base64,(.+)$/,a=r.image_url.match(s);a?yield{type:"image",data:a[2],mimeType:a[1]}:yield{type:"image",url:r.image_url}}else yield{type:"image",url:r.image_url};continue}else if(F(r,"media")&&$(r.mimeType)&&$(r.data)){yield{type:"file",mimeType:r.mimeType,data:r.data};continue}yield{type:"non_standard",value:r}}}return Array.from(t())}const $w={translateContent:Au,translateContentChunk:Au};globalThis.lc_block_translators_registry??=new Map([["anthropic",fw],["bedrock-converse",Mw],["google-genai",Rw],["google-vertexai",$w],["openai",Ew]]);function Ch(e){return globalThis.lc_block_translators_registry.get(e)}function Ah(e,t){return Ue(e??{},t??{})}function kh(e,t){const n={};return(e?.audio!==void 0||t?.audio!==void 0)&&(n.audio=(e?.audio??0)+(t?.audio??0)),(e?.image!==void 0||t?.image!==void 0)&&(n.image=(e?.image??0)+(t?.image??0)),(e?.video!==void 0||t?.video!==void 0)&&(n.video=(e?.video??0)+(t?.video??0)),(e?.document!==void 0||t?.document!==void 0)&&(n.document=(e?.document??0)+(t?.document??0)),(e?.text!==void 0||t?.text!==void 0)&&(n.text=(e?.text??0)+(t?.text??0)),n}function Lw(e,t){const n={...kh(e,t)};return(e?.cache_read!==void 0||t?.cache_read!==void 0)&&(n.cache_read=(e?.cache_read??0)+(t?.cache_read??0)),(e?.cache_creation!==void 0||t?.cache_creation!==void 0)&&(n.cache_creation=(e?.cache_creation??0)+(t?.cache_creation??0)),n}function jw(e,t){const n={...kh(e,t)};return(e?.reasoning!==void 0||t?.reasoning!==void 0)&&(n.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),n}function Oh(e,t){return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:Lw(e?.input_token_details,t?.input_token_details),output_token_details:jw(e?.output_token_details,t?.output_token_details)}}var D=class extends rt{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;const n=t.additional_kwargs?.tool_calls,r=t.tool_calls;n!=null&&n.length>0&&(r===void 0||r.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
15
-
16
- Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(n!=null&&r===void 0){const[s,a]=Qc(n);t.tool_calls=s??[],t.invalid_tool_calls=a??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(t.response_metadata!==void 0&&"output_version"in t.response_metadata&&t.response_metadata.output_version==="v1"&&(t.contentBlocks=t.content,t.content=void 0),t.contentBlocks!==void 0){t.contentBlocks.push(...t.tool_calls.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})));const s=t.contentBlocks.filter(a=>a.type==="tool_call").filter(a=>!t.tool_calls?.some(i=>i.id===a.id&&i.name===a.name));s.length>0&&(t.tool_calls=s.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}}super(t),typeof t!="string"&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const t=Ch(this.response_metadata.model_provider);if(t)return t.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls){const t=this.tool_calls.filter(n=>!e.some(r=>r.id===n.id&&r.name===n.name));e.push(...t.map(n=>({...n,type:"tool_call",id:n.id,name:n.name,args:n.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};function nl(e){return e._getType()==="ai"}function zo(e){return e._getType()==="ai"}var yt=class extends Nn{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{const r=(e.tool_call_chunks??[]).reduce((i,o)=>{const c=i.findIndex(([l])=>"id"in o&&o.id&&"index"in o&&o.index!==void 0?o.id===l.id&&o.index===l.index:"id"in o&&o.id?o.id===l.id:"index"in o&&o.index!==void 0?o.index===l.index:!1);return c!==-1?i[c].push(o):i.push([o]),i},[]),s=[],a=[];for(const i of r){let o=null;const c=i[0]?.name??"",l=i.map(h=>h.args||"").join(""),u=l.length?l:"{}",d=i[0]?.id;try{if(o=Br(u),!d||o===null||typeof o!="object"||Array.isArray(o))throw new Error("Malformed tool call chunk args.");s.push({name:c,args:o,id:d,type:"tool_call"})}catch{a.push({name:c,args:u,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:s,invalid_tool_calls:a,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const t=Ch(this.response_metadata.model_provider);if(t)return t.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const t=this.content.filter(n=>n.type==="tool_call").map(n=>n.id);for(const n of this.tool_calls)n.id&&!t.includes(n.id)&&e.push({...n,type:"tool_call",id:n.id,name:n.name,args:n.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){const t={content:Yn(this.content,e.content),additional_kwargs:Ue(this.additional_kwargs,e.additional_kwargs),response_metadata:Ah(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const r=Js(this.tool_call_chunks,e.tool_call_chunks);r!==void 0&&r.length>0&&(t.tool_call_chunks=r)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(t.usage_metadata=Oh(this.usage_metadata,e.usage_metadata));const n=this.constructor;return new n(t)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}},Xn=class xh extends rt{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return xh}constructor(t,n){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:n}),super(t),this.role=t.role}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},wi=class extends Nn{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(e,t){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){const t=this.constructor;return new t({content:Yn(this.content,e.content),additional_kwargs:Ue(this.additional_kwargs,e.additional_kwargs),response_metadata:Ue(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function Dw(e){return e._getType()==="generic"}function Fw(e){return e._getType()==="generic"}var vi=class extends rt{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},bi=class extends Nn{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){const t=this.constructor;return new t({content:Yn(this.content,e.content),additional_kwargs:Ue(this.additional_kwargs,e.additional_kwargs),response_metadata:Ue(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function Uw(e){return e._getType()==="function"}function Bw(e){return e._getType()==="function"}var he=class extends rt{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},Zs=class extends Nn{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){const t=this.constructor;return new t({content:Yn(this.content,e.content),additional_kwargs:Ue(this.additional_kwargs,e.additional_kwargs),response_metadata:Ue(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}};function zw(e){return e.getType()==="human"}function Hw(e){return e.getType()==="human"}var Se=class extends rt{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="system"}},Jn=class extends Nn{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){const t=this.constructor;return new t({content:Yn(this.content,e.content),additional_kwargs:Ue(this.additional_kwargs,e.additional_kwargs),response_metadata:Ue(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}};function Vw(e){return e._getType()==="system"}function Gw(e){return e._getType()==="system"}function Si(e,t){return e.lc_error_code=t,e.message=`${e.message}
17
-
18
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/
19
- `,e}var Sn=class extends rt{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 Ww=e=>e();function Jw(e){return fs(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 Kw(e){return typeof e=="object"&&e!=null&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs=="object"}function Yi(e){let t,n;if(Kw(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 he(n);if(t==="ai"||t==="assistant"){const{tool_calls:r,...s}=n;if(!Array.isArray(r))return new D(n);const a=r.map(Jw);return new D({...s,tool_calls:a})}else{if(t==="system")return new Se(n);if(t==="developer")return new Se({...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 Sn({...n,id:n.id});throw Si(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
20
-
21
- Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Gt(e){if(typeof e=="string")return new he(e);if(Pe(e))return e;if(Array.isArray(e)){const[t,n]=e;return Yi({type:t,content:n})}else if(Sh(e)){const{role:t,...n}=e;return Yi({...n,type:t})}else return Yi(e)}function rl(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 Zw(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 sl(e){const t=Zw(e);switch(t.type){case"human":return new he(t.data);case"ai":return new D(t.data);case"system":return new Se(t.data);case"function":if(t.data.name===void 0)throw new Error("Name must be defined for function messages");return new vi(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 Xn(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function qw(e){return e.map(sl)}function Yw(e){return e.map(t=>t.toDict())}function Ga(e){const t=e._getType();if(t==="human")return new Zs({...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 yt({...n})}else{if(t==="system")return new Jn({...e});if(t==="function")return new bi({...e});if(Xn.isInstance(e))return new wi({...e});throw new Error("Unknown message type.")}}var Xw={},Ih={};U(Ih,{getEnv:()=>$h,getEnvironmentVariable:()=>rn,getRuntimeEnvironment:()=>Lh,isBrowser:()=>Ph,isDeno:()=>Ti,isJsDom:()=>Mh,isNode:()=>Rh,isWebWorker:()=>Nh});const Ph=()=>typeof window<"u"&&typeof window.document<"u",Nh=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Mh=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Ti=()=>typeof Deno<"u",Rh=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Ti(),$h=()=>{let e;return Ph()?e="browser":Rh()?e="node":Nh()?e="webworker":Mh()?e="jsdom":Ti()?e="deno":e="other",e};let Xi;function Lh(){return Xi===void 0&&(Xi={library:"langchain-js",runtime:$h()}),Xi}function rn(e){try{return typeof process<"u"?Xw?.[e]:Ti()?Deno?.env.get(e):void 0}catch{return}}var jh={};U(jh,{BaseCallbackHandler:()=>es,callbackHandlerPrefersStreaming:()=>al,isBaseCallbackHandler:()=>Dh});var Qw=class{};function al(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var es=class extends Qw{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,_i(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=rn("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 At.prototype.toJSON.call(this)}toJSONNotImplemented(){return At.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends es{name=ke();constructor(){super(),Object.assign(this,e)}}return new t}};const Dh=e=>{const t=e;return t!==void 0&&typeof t.copy=="function"&&typeof t.name=="string"&&typeof t.awaitHandlers=="boolean"},ev="gen_ai.operation.name",tv="gen_ai.system",ku="gen_ai.request.model",nv="gen_ai.response.model",Ou="gen_ai.usage.input_tokens",xu="gen_ai.usage.output_tokens",Iu="gen_ai.usage.total_tokens",rv="gen_ai.request.max_tokens",sv="gen_ai.request.temperature",av="gen_ai.request.top_p",iv="gen_ai.request.frequency_penalty",ov="gen_ai.request.presence_penalty",cv="gen_ai.response.finish_reasons",lv="gen_ai.prompt",uv="gen_ai.completion",dv="gen_ai.request.extra_query",hv="gen_ai.request.extra_body",pv="gen_ai.serialized.name",fv="gen_ai.serialized.signature",mv="gen_ai.serialized.doc",gv="gen_ai.response.id",yv="gen_ai.response.service_tier",_v="gen_ai.response.system_fingerprint",wv="gen_ai.usage.input_token_details",vv="gen_ai.usage.output_token_details",bv="langsmith.trace.session_id",Sv="langsmith.trace.session_name",Tv="langsmith.span.kind",Ev="langsmith.trace.name",Cv="langsmith.metadata",Pu="langsmith.span.tags",Av="langsmith.request.streaming",kv="langsmith.request.headers",Ov=(...e)=>fetch(...e),Fh=Symbol.for("ls:fetch_implementation"),xv=()=>{const e=globalThis[Fh];return e?typeof e=="function"&&"Headers"in e&&"Request"in e&&"Response"in e:!1},Iv=e=>async(...t)=>{if(e||Qe("DEBUG")==="true"){const[r,s]=t;console.log(`→ ${s?.method||"GET"} ${r}`)}const n=await(globalThis[Fh]??Ov)(...t);return(e||Qe("DEBUG")==="true")&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},Uh=()=>Qe("PROJECT")??Kt("LANGCHAIN_SESSION")??"default",Bh="0.3.79";var Ho={};let Ut;const Pv=()=>typeof window<"u"&&typeof window.document<"u",Nv=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Mv=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),zh=()=>typeof Deno<"u",Rv=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!zh(),Hh=()=>Ut||(typeof Bun<"u"?Ut="bun":Pv()?Ut="browser":Rv()?Ut="node":Nv()?Ut="webworker":Mv()?Ut="jsdom":zh()?Ut="deno":Ut="other",Ut);let Qi;function Vh(){if(Qi===void 0){const e=Hh(),t=Lv();Qi={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:Bh,...t}}return Qi}function Gh(){const e=$v(),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 $v(){const e={};try{if(typeof process<"u"&&Ho)for(const[t,n]of Object.entries(Ho))(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 Kt(e){try{return typeof process<"u"?Ho?.[e]:void 0}catch{return}}function Qe(e){return Kt(`LANGSMITH_${e}`)||Kt(`LANGCHAIN_${e}`)}let eo;function Lv(){if(eo!==void 0)return eo;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=Kt(n);r!==void 0&&(t[n]=r)}return eo=t,t}function Wh(){return Kt("OTEL_ENABLED")==="true"||Qe("OTEL_ENABLED")==="true"}class jv{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(t,...n){!this.hasWarned&&Wh()&&(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 Dv{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new jv})}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 Fv{active(){return{}}with(t,n){return n()}}const to=Symbol.for("ls:otel_trace"),no=Symbol.for("ls:otel_context"),Nu=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Uv=new Dv,Bv=new Fv;class zv{getTraceInstance(){return globalThis[to]??Uv}getContextInstance(){return globalThis[no]??Bv}initializeGlobalInstances(t){globalThis[to]===void 0&&(globalThis[to]=t.trace),globalThis[no]===void 0&&(globalThis[no]=t.context)}setDefaultOTLPTracerComponents(t){globalThis[Nu]=t}getDefaultOTLPTracerComponents(){return globalThis[Nu]??void 0}}const il=new zv;function Jh(){return il.getTraceInstance()}function Hv(){return il.getContextInstance()}function Vv(){return il.getDefaultOTLPTracerComponents()}const Gv={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Wv(e){return Gv[e]||e}class Jv{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&&Jh().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(Tv,n.run_type);const o=Wv(n.run_type||"chain");t.setAttribute(ev,o)}"name"in n&&n.name&&t.setAttribute(Ev,n.name),"session_id"in n&&n.session_id&&t.setAttribute(bv,n.session_id),"session_name"in n&&n.session_name&&t.setAttribute(Sv,n.session_name),this.setGenAiSystem(t,n);const s=this.extractModelName(n);s&&t.setAttribute(ku,s),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&t.setAttribute(Ou,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&t.setAttribute(xu,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&t.setAttribute(Iu,n.total_tokens),this.setInvocationParameters(t,n);const a=n.extra?.metadata||{};for(const[o,c]of Object.entries(a))c!=null&&t.setAttribute(`${Cv}.${o}`,String(c));const i=n.tags;if(i&&Array.isArray(i)?t.setAttribute(Pu,i.join(", ")):i&&t.setAttribute(Pu,String(i)),"serialized"in n&&typeof n.serialized=="object"){const o=n.serialized;o.name&&t.setAttribute(pv,String(o.name)),o.signature&&t.setAttribute(fv,String(o.signature)),o.doc&&t.setAttribute(mv,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(tv,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(rv,r.max_tokens),r.temperature!==void 0&&t.setAttribute(sv,r.temperature),r.top_p!==void 0&&t.setAttribute(av,r.top_p),r.frequency_penalty!==void 0&&t.setAttribute(iv,r.frequency_penalty),r.presence_penalty!==void 0&&t.setAttribute(ov,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(ku,r.model),r.stream!==void 0&&t.setAttribute(Av,r.stream),r.extra_headers&&t.setAttribute(kv,JSON.stringify(r.extra_headers)),r.extra_query&&t.setAttribute(dv,JSON.stringify(r.extra_query)),r.extra_body&&t.setAttribute(hv,JSON.stringify(r.extra_body))),t.setAttribute(lv,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(Ou,s[0]),t.setAttribute(xu,s[1]),t.setAttribute(Iu,s[0]+s[1])),r&&typeof r=="object"){if(r.model&&t.setAttribute(nv,String(r.model)),r.id&&t.setAttribute(gv,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(cv,a.join(", "))}if(r.service_tier&&t.setAttribute(yv,r.service_tier),r.system_fingerprint&&t.setAttribute(_v,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const a=r.usage_metadata;a.input_token_details&&t.setAttribute(wv,JSON.stringify(a.input_token_details)),a.output_token_details&&t.setAttribute(vv,JSON.stringify(a.output_token_details))}}t.setAttribute(uv,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 Kv=[429,500,502,503,504];let Mu=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 nn?this.queue=new nn.default({concurrency:this.maxConcurrency}):this.queue=new nn({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...n){const r=this.onFailedResponseHook;return this.queue.add(()=>Ha(()=>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&&!Kv.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 Ru(e){return typeof e?._getType=="function"}function $u(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 Zv=/^[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(!Zv.test(e)){const n=t!==void 0?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`;throw new Error(n)}return e}const Lu={};function Vo(e){Lu[e]||(console.warn(e),Lu[e]=!0)}function pn(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 qv 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 j(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 qv(s);const a=new Error(s);throw a.status=e.status,a}const Kh="ERR_CONFLICTING_ENDPOINTS";class Yv 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:Kh}),this.name="ConflictingEndpointsError"}}function Xv(e){return typeof e=="object"&&e!==null&&e.code===Kh}var ju="[...]",Qv={result:"[Circular]"},Wa=[],pr=[];const eb=new TextEncoder;function tb(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function la(e){return eb.encode(e)}function Zh(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 nb(e){return function(t,n){return Zh(n)}}function dt(e,t,n,r,s){try{const a=JSON.stringify(e,nb(n),r);return la(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`
23
- Context: ${t}`:""}`),la("[Unserializable]");Qe("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`
24
- Context: ${t}`:""}`),typeof s>"u"&&(s=tb()),Go(e,"",0,[],void 0,0,s);let i;try{pr.length===0?i=JSON.stringify(e,n,r):i=JSON.stringify(e,rb(n),r)}catch{return la("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Wa.length!==0;){const o=Wa.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return la(i)}}function ro(e,t,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:e}),Wa.push([r,n,t,s])):pr.push([t,n,e]):(r[n]=e,Wa.push([r,n,t]))}function Go(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){ro(Qv,e,t,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){ro(ju,e,t,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){ro(ju,e,t,s);return}if(r.push(e),Array.isArray(e))for(o=0;o<e.length;o++)Go(e[o],o,o,r,e,a,i);else{e=Zh(e);var c=Object.keys(e);for(o=0;o<c.length;o++){var l=c[o];Go(e[l],l,o,r,e,a,i)}}r.pop()}}function rb(e){return e=typeof e<"u"?e:function(t,n){return n},function(t,n){if(pr.length>0)for(var r=0;r<pr.length;r++){var s=pr[r];if(s[1]===t&&s[0]===n){n=s[2],pr.splice(r,1);break}}return e.call(this,t,n)}}function Du(e,t){const n=Vh(),r=t??Gh(),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 sb=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},ab=e=>{const n=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};async function ib(e){const t=[];for await(const n of e)t.push(n);return t}function ua(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const ob=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 Fu(e){return typeof e=="number"?Number(e.toFixed(4)):e}class cb{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=dt(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 lb=24*1024*1024,ub=1e4,db=100,Uu="https://api.smith.langchain.com";class zr{get _fetch(){return this.fetchImplementation||Iv(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 cb}),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:Kt("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:Kt("LANGSMITH_DEBUG")==="true"});const n=zr.getDefaultClientConfig();if(this.tracingSampleRate=sb(t.tracingSamplingRate),this.apiUrl=ua(t.apiUrl??n.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=ua(t.apiKey??n.apiKey),this.webUrl=ua(t.webUrl??n.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=ua(t.workspaceId??Qe("WORKSPACE_ID")),this.timeout_ms=t.timeout_ms??9e4,this.caller=new Mu({...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 Mu({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...t.callerOptions??{},onFailedResponseHook:ob,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,Wh()&&(this.langSmithToOTELTranslator=new Jv),this.cachedLSEnvVarsForMetadata=Gh()}static getDefaultClientConfig(){const t=Qe("API_KEY"),n=Qe("ENDPOINT")??Uu,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:ab(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/${Bh}`};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 j(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 j(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 j(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??lb}async _getBatchSizeLimit(){const t=await this._ensureServerInfo();return this.batchSizeLimit??t.batch_ingest_config?.size_limit??db}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=Du(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(ub),...this.fetchOptions});return await j(r,"get server info"),r})).json();return this.debug&&console.log(`
25
- === LangSmith Server Configuration ===
26
- `+JSON.stringify(n,null,2)+`
27
- `),n}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(t){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${t.status??"Unspecified status code"} ${t.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(t=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),t))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const t=await this._getBatchSizeLimitBytes(),n=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:n})}_cloneCurrentOTELContext(){const t=Jh(),n=Hv();if(this.langSmithToOTELTranslator!==void 0){const r=t.getActiveSpan();if(r)return t.setSpan(n.active(),r)}}async createRun(t,n){if(!this._filterForSampling([t]).length)return;const r={...this.headers,"Content-Type":"application/json"},s=t.project_name;delete t.project_name;const a=await this.prepareRunCreateOrUpdateInputs({session_name:s,...t,start_time:t.start_time??Date.now()});if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){const c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:a,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}const i=Du(a,this.cachedLSEnvVarsForMetadata);n?.apiKey!==void 0&&(r["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(r["x-tenant-id"]=n.workspaceId);const o=dt(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await j(c,"create run",!0),c})}async batchIngestRuns({runCreates:t,runUpdates:n},r){if(t===void 0&&n===void 0)return;let s=await Promise.all(t?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),a=await Promise.all(n?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(s.length>0&&a.length>0){const c=s.reduce((u,d)=>(d.id&&(u[d.id]=d),u),{}),l=[];for(const u of a)u.id!==void 0&&c[u.id]?c[u.id]={...c[u.id],...u}:l.push(u);s=Object.values(c),a=l}const i={post:s,patch:a};if(!i.post.length&&!i.patch.length)return;const o={post:[],patch:[]};for(const c of["post","patch"]){const l=c,u=i[l].reverse();let d=u.pop();for(;d!==void 0;)o[l].push(d),d=u.pop()}if(o.post.length>0||o.patch.length>0){const c=o.post.map(l=>l.id).concat(o.patch.map(l=>l.id)).join(",");await this._postBatchIngestRuns(dt(o,`Ingesting runs with ids: ${c}`),r)}}async _postBatchIngestRuns(t,n){const r={...this.headers,"Content-Type":"application/json",Accept:"application/json"};n?.apiKey!==void 0&&(r["x-api-key"]=n.apiKey),await this.batchIngestCaller.call(async()=>{const s=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await j(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:t,runUpdates:n},r){if(t===void 0&&n===void 0)return;const s={};let a=[];for(const d of t??[]){const h=await this.prepareRunCreateOrUpdateInputs(d);h.id!==void 0&&h.attachments!==void 0&&(s[h.id]=h.attachments),delete h.attachments,a.push(h)}let i=[];for(const d of n??[])i.push(await this.prepareRunCreateOrUpdateInputs(d));if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(a.length>0&&i.length>0){const d=a.reduce((p,f)=>(f.id&&(p[f.id]=f),p),{}),h=[];for(const p of i)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:h.push(p);a=Object.values(d),i=h}if(a.length===0&&i.length===0)return;const l=[],u=[];for(const[d,h]of[["post",a],["patch",i]])for(const p of h){const{inputs:f,outputs:g,events:b,extra:S,error:w,serialized:v,attachments:T,...k}=p,O={inputs:f,outputs:g,events:b,extra:S,error:w,serialized:v},C=dt(k,`Serializing for multipart ingestion of run with id: ${k.id}`);u.push({name:`${d}.${k.id}`,payload:new Blob([C],{type:`application/json; length=${C.length}`})});for(const[y,N]of Object.entries(O)){if(N===void 0)continue;const I=dt(N,`Serializing ${y} for multipart ingestion of run with id: ${k.id}`);u.push({name:`${d}.${k.id}.${y}`,payload:new Blob([I],{type:`application/json; length=${I.length}`})})}if(k.id!==void 0){const y=s[k.id];if(y){delete s[k.id];for(const[N,I]of Object.entries(y)){let R,z;if(Array.isArray(I)?[R,z]=I:(R=I.mimeType,z=I.data),N.includes(".")){console.warn(`Skipping attachment '${N}' for run ${k.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}u.push({name:`attachment.${k.id}.${N}`,payload:new Blob([z],{type:`${R}; length=${z.byteLength}`})})}}}l.push(`trace=${k.trace_id},id=${k.id}`)}await this._sendMultipartRequest(u,l.join("; "),r)}async _createNodeFetchBody(t,n){const r=[];for(const i of t)r.push(new Blob([`--${n}\r
28
- `])),r.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
29
- `,`Content-Type: ${i.payload.type}\r
30
- \r
31
- `])),r.push(i.payload),r.push(new Blob([`\r
32
- `]));return r.push(new Blob([`--${n}--\r
33
- `])),await new Blob(r).arrayBuffer()}async _createMultipartStream(t,n){const r=new TextEncoder;return new ReadableStream({async start(a){const i=async o=>{typeof o=="string"?a.enqueue(r.encode(o)):a.enqueue(o)};for(const o of t){await i(`--${n}\r
34
- `),await i(`Content-Disposition: form-data; name="${o.name}"\r
35
- `),await i(`Content-Type: ${o.payload.type}\r
36
- \r
37
- `);const l=o.payload.stream().getReader();try{let u;for(;!(u=await l.read()).done;)a.enqueue(u.value)}finally{l.releaseLock()}await i(`\r
38
- `)}await i(`--${n}--\r
39
- `),a.close()}})}async _sendMultipartRequest(t,n,r){const s="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=xv(),i=()=>this._createNodeFetchBody(t,s),o=()=>this._createMultipartStream(t,s),c=async l=>this.batchIngestCaller.call(async()=>{const u=await l(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${s}`};r?.apiKey!==void 0&&(d["x-api-key"]=r.apiKey);let h=u;r?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(h=u.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const p=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:h,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(p,"Failed to send multipart request",!0),p});try{let l,u=!1;!a&&!this.multipartStreamingDisabled&&Hh()!=="bun"?(u=!0,l=await c(o)):l=await c(i),(!this.multipartStreamingDisabled||u)&&l.status===422&&(r?.apiUrl??this.apiUrl)!==Uu&&(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${n}".`),this.multipartStreamingDisabled=!0,l=await c(i))}catch(l){console.warn(`${l.message.trim()}
40
-
41
- Context: ${n}`)}}async updateRun(t,n,r){V(t),n.inputs&&(n.inputs=await this.processInputs(n.inputs)),n.outputs&&(n.outputs=await this.processOutputs(n.outputs));const s={...n,id:t};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(n.end_time!==void 0&&s.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}const a={...this.headers,"Content-Type":"application/json"};r?.apiKey!==void 0&&(a["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(a["x-tenant-id"]=r.workspaceId);const i=dt(n,`Serializing payload to update run with id: ${t}`);await this.caller.call(async()=>{const o=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${t}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await j(o,"update run",!0),o})}async readRun(t,{loadChildRuns:n}={loadChildRuns:!1}){V(t);let r=await this._get(`/runs/${t}`);return n&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:t,run:n,projectOpts:r}){if(n!==void 0){let s;n.session_id?s=n.session_id:r?.projectName?s=(await this.readProject({projectName:r?.projectName})).id:r?.projectId?s=r?.projectId:s=(await this.readProject({projectName:Qe("PROJECT")||"default"})).id;const a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${s}/r/${n.id}?poll=true`}else if(t!==void 0){const s=await this.readRun(t);if(!s.app_path)throw new Error(`Run ${t} has no app_path`);return`${this.getHostUrl()}${s.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(t){const n=await ib(this.listRuns({isRoot:!1,projectId:t.session_id,traceId:t.trace_id})),r={},s={};n.sort((a,i)=>(a?.dotted_order??"").localeCompare(i?.dotted_order??""));for(const a of n){if(a.parent_run_id===null||a.parent_run_id===void 0)throw new Error(`Child run ${a.id} has no parent`);a.dotted_order?.startsWith(t.dotted_order??"")&&a.id!==t.id&&(a.parent_run_id in r||(r[a.parent_run_id]=[]),r[a.parent_run_id].push(a),s[a.id]=a)}t.child_runs=r[t.id]||[];for(const a in r)a!==t.id&&(s[a].child_runs=r[a]);return t}async*listRuns(t){const{projectId:n,projectName:r,parentRunId:s,traceId:a,referenceExampleId:i,startTime:o,executionOrder:c,isRoot:l,runType:u,error:d,id:h,query:p,filter:f,traceFilter:g,treeFilter:b,limit:S,select:w,order:v}=t;let T=[];if(n&&(T=Array.isArray(n)?n:[n]),r){const y=Array.isArray(r)?r:[r],N=await Promise.all(y.map(I=>this.readProject({projectName:I}).then(R=>R.id)));T.push(...N)}const k=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],O={session:T.length?T:null,run_type:u,reference_example:i,query:p,filter:f,trace_filter:g,tree_filter:b,execution_order:c,parent_run:s,start_time:o?o.toISOString():null,error:d,id:h,limit:S,trace:a,select:w||k,is_root:l,order:v};O.select.includes("child_run_ids")&&Vo("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let C=0;for await(const y of this._getCursorPaginatedList("/runs/query",O))if(S){if(C>=S)break;if(y.length+C>S){yield*y.slice(0,S-C);break}C+=y.length,yield*y}else yield*y}async*listGroupRuns(t){const{projectId:n,projectName:r,groupBy:s,filter:a,startTime:i,endTime:o,limit:c,offset:l}=t,d={session_id:n||(await this.readProject({projectName:r})).id,group_by:s,filter:a,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let h=Number(l)||0;const p="/runs/group",f=`${this.apiUrl}${p}`;for(;;){const g={...d,offset:h},b=Object.fromEntries(Object.entries(g).filter(([O,C])=>C!==void 0)),S=JSON.stringify(b),v=await(await this.caller.call(async()=>{const O=await this._fetch(f,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:S});return await j(O,`Failed to fetch ${p}`),O})).json(),{groups:T,total:k}=v;if(T.length===0)break;for(const O of T)yield O;if(h+=T.length,h>=k)break}}async getRunStats({id:t,trace:n,parentRun:r,runType:s,projectNames:a,projectIds:i,referenceExampleIds:o,startTime:c,endTime:l,error:u,query:d,filter:h,traceFilter:p,treeFilter:f,isRoot:g,dataSourceType:b}){let S=i||[];a&&(S=[...i||[],...await Promise.all(a.map(C=>this.readProject({projectName:C}).then(y=>y.id)))]);const v=Object.fromEntries(Object.entries({id:t,trace:n,parent_run:r,run_type:s,session:S,reference_example:o,start_time:c,end_time:l,error:u,query:d,filter:h,trace_filter:p,tree_filter:f,is_root:g,data_source_type:b}).filter(([C,y])=>y!==void 0)),T=JSON.stringify(v);return await(await this.caller.call(async()=>{const C=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:T});return await j(C,"get run stats"),C})).json()}async shareRun(t,{shareId:n}={}){const r={run_id:t,share_token:n||ke()};V(t);const s=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await j(o,"share run"),o})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(t){V(t),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,"unshare run",!0),n})}async readRunSharedLink(t){V(t);const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(s,"read run shared link"),s})).json();if(!(r===null||!("share_token"in r)))return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(t,{runIds:n}={}){const r=new URLSearchParams({share_token:t});if(n!==void 0)for(const i of n)r.append("id",i);return V(t),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${t}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(i,"list shared runs"),i})).json()}async readDatasetSharedSchema(t,n){if(!t&&!n)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:n})).id),V(t);const s=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(a,"read dataset shared schema"),a})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(t,n){if(!t&&!n)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:n})).id);const r={dataset_id:t};V(t);const s=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await j(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(t){V(t),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,"unshare dataset",!0),n})}async readSharedDataset(t){return V(t),await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/public/${t}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(s,"read shared dataset"),s})).json()}async listSharedExamples(t,n){const r={};n?.exampleIds&&(r.id=n.exampleIds);const s=new URLSearchParams;Object.entries(r).forEach(([o,c])=>{Array.isArray(c)?c.forEach(l=>s.append(o,l)):s.append(o,c)});const a=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${t}/examples?${s.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(o,"list shared examples"),o}),i=await a.json();if(!a.ok)throw"detail"in i?new Error(`Failed to list shared examples.
42
- Status: ${a.status}
43
- Message: ${Array.isArray(i.detail)?i.detail.join(`
44
- `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${a.status} ${a.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:t,description:n=null,metadata:r=null,upsert:s=!1,projectExtra:a=null,referenceDatasetId:i=null}){const o=s?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,l=a||{};r&&(l.metadata=r);const u={name:t,extra:l,description:n};i!==null&&(u.reference_dataset_id=i);const d=JSON.stringify(u);return await(await this.caller.call(async()=>{const f=await this._fetch(c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await j(f,"create project"),f})).json()}async updateProject(t,{name:n=null,description:r=null,metadata:s=null,projectExtra:a=null,endTime:i=null}){const o=`${this.apiUrl}/sessions/${t}`;let c=a;s&&(c={...c||{},metadata:s});const l=JSON.stringify({name:n,extra:c,description:r,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const h=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await j(h,"update project"),h})).json()}async hasProject({projectId:t,projectName:n}){let r="/sessions";const s=new URLSearchParams;if(t!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)V(t),r+=`/${t}`;else if(n!==void 0)s.append("name",n);else throw new Error("Must provide projectName or projectId");const a=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${r}?${s}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(i,"has project"),i});try{const i=await a.json();return a.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:t,projectName:n,includeStats:r}){let s="/sessions";const a=new URLSearchParams;if(t!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)V(t),s+=`/${t}`;else if(n!==void 0)a.append("name",n);else throw new Error("Must provide projectName or projectId");r!==void 0&&a.append("include_stats",r.toString());const i=await this._get(s,a);let o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${t}, name=${n}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:t,projectName:n}){if(t===void 0&&n===void 0)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:t,projectName:n}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${r.id}`}async getDatasetUrl({datasetId:t,datasetName:n}){if(t===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:t,datasetName:n}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const t=new URLSearchParams({limit:"1"});for await(const n of this._getPaginated("/sessions",t))return this._tenantId=n[0].tenant_id,n[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:t,name:n,nameContains:r,referenceDatasetId:s,referenceDatasetName:a,includeStats:i,datasetVersion:o,referenceFree:c,metadata:l}={}){const u=new URLSearchParams;if(t!==void 0)for(const d of t)u.append("id",d);if(n!==void 0&&u.append("name",n),r!==void 0&&u.append("name_contains",r),s!==void 0)u.append("reference_dataset",s);else if(a!==void 0){const d=await this.readDataset({datasetName:a});u.append("reference_dataset",d.id)}i!==void 0&&u.append("include_stats",i.toString()),o!==void 0&&u.append("dataset_version",o),c!==void 0&&u.append("reference_free",c.toString()),l!==void 0&&u.append("metadata",JSON.stringify(l));for await(const d of this._getPaginated("/sessions",u))yield*d}async deleteProject({projectId:t,projectName:n}){let r;if(t===void 0&&n===void 0)throw new Error("Must provide projectName or projectId");if(t!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");t===void 0?r=(await this.readProject({projectName:n})).id:r=t,V(r),await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(s,`delete session ${r} (${n})`,!0),s})}async uploadCsv({csvFile:t,fileName:n,inputKeys:r,outputKeys:s,description:a,dataType:i,name:o}){const c=`${this.apiUrl}/datasets/upload`,l=new FormData;return l.append("file",t,n),r.forEach(h=>{l.append("input_keys",h)}),s.forEach(h=>{l.append("output_keys",h)}),a&&l.append("description",a),i&&l.append("data_type",i),o&&l.append("name",o),await(await this.caller.call(async()=>{const h=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await j(h,"upload CSV"),h})).json()}async createDataset(t,{description:n,dataType:r,inputsSchema:s,outputsSchema:a,metadata:i}={}){const o={name:t,description:n,extra:i?{metadata:i}:void 0};r&&(o.data_type=r),s&&(o.inputs_schema_definition=s),a&&(o.outputs_schema_definition=a);const c=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await j(d,"create dataset"),d})).json()}async readDataset({datasetId:t,datasetName:n}){let r="/datasets";const s=new URLSearchParams({limit:"1"});if(t&&n)throw new Error("Must provide either datasetName or datasetId, not both");if(t)V(t),r+=`/${t}`;else if(n)s.append("name",n);else throw new Error("Must provide datasetName or datasetId");const a=await this._get(r,s);let i;if(Array.isArray(a)){if(a.length===0)throw new Error(`Dataset[id=${t}, name=${n}] not found`);i=a[0]}else i=a;return i}async hasDataset({datasetId:t,datasetName:n}){try{return await this.readDataset({datasetId:t,datasetName:n}),!0}catch(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:t,datasetName:n,fromVersion:r,toVersion:s}){let a=t;if(a===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:n})).id);const i=new URLSearchParams({from_version:typeof r=="string"?r:r.toISOString(),to_version:typeof s=="string"?s:s.toISOString()});return await this._get(`/datasets/${a}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:t,datasetName:n}){const r="/datasets";if(t===void 0)if(n!==void 0)t=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${r}/${t}/openai_ft`)).text()).trim().split(`
45
- `).map(o=>JSON.parse(o))}async*listDatasets({limit:t=100,offset:n=0,datasetIds:r,datasetName:s,datasetNameContains:a,metadata:i}={}){const o="/datasets",c=new URLSearchParams({limit:t.toString(),offset:n.toString()});if(r!==void 0)for(const l of r)c.append("id",l);s!==void 0&&c.append("name",s),a!==void 0&&c.append("name_contains",a),i!==void 0&&c.append("metadata",JSON.stringify(i));for await(const l of this._getPaginated(o,c))yield*l}async updateDataset(t){const{datasetId:n,datasetName:r,...s}=t;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");const a=n??(await this.readDataset({datasetName:r})).id;V(a);const i=JSON.stringify(s);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await j(c,"update dataset"),c})).json()}async updateDatasetTag(t){const{datasetId:n,datasetName:r,asOf:s,tag:a}=t;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");const i=n??(await this.readDataset({datasetName:r})).id;V(i);const o=JSON.stringify({as_of:typeof s=="string"?s:s.toISOString(),tag:a});await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await j(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:t,datasetName:n}){let r="/datasets",s=t;if(t!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(n!==void 0&&(s=(await this.readDataset({datasetName:n})).id),s!==void 0)V(s),r+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const a=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(a,`delete ${r}`,!0),a})}async indexDataset({datasetId:t,datasetName:n,tag:r}){let s=t;if(!s&&!n)throw new Error("Must provide either datasetName or datasetId");if(s&&n)throw new Error("Must provide either datasetName or datasetId, not both");s||(s=(await this.readDataset({datasetName:n})).id),V(s);const i=JSON.stringify({tag:r});await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await j(c,"index dataset"),c})).json()}async similarExamples(t,n,r,{filter:s}={}){const a={limit:r,inputs:t};s!==void 0&&(a.filter=s),V(n);const i=JSON.stringify(a);return(await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${n}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await j(l,"fetch similar examples"),l})).json()).examples}async createExample(t,n,r){if(Bu(t)&&(n!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=n?r?.datasetId:t.dataset_id;const a=n?r?.datasetName:t.dataset_name;if(s===void 0&&a===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&a!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:a})).id);const i=(n?r?.createdAt:t.created_at)||new Date;let o;Bu(t)?o=t:o={inputs:t,outputs:n,created_at:i?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};const c=await this._uploadExamplesMultipart(s,[o]);return await this.readExample(c.example_ids?.[0]??ke())}async createExamples(t){if(Array.isArray(t)){if(t.length===0)return[];const w=t;let v=w[0].dataset_id;const T=w[0].dataset_name;if(v===void 0&&T===void 0)throw new Error("Must provide either datasetName or datasetId");if(v!==void 0&&T!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");v===void 0&&(v=(await this.readDataset({datasetName:T})).id);const k=await this._uploadExamplesMultipart(v,w);return await Promise.all(k.example_ids.map(C=>this.readExample(C)))}const{inputs:n,outputs:r,metadata:s,splits:a,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:l,exampleIds:u,datasetId:d,datasetName:h}=t;if(n===void 0)throw new Error("Must provide inputs when using legacy parameters");let p=d;const f=h;if(p===void 0&&f===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&f!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:f})).id);const g=n.map((w,v)=>({dataset_id:p,inputs:w,outputs:r?.[v],metadata:s?.[v],split:a?.[v],id:u?.[v],attachments:l?.[v],source_run_id:i?.[v],use_source_run_io:o?.[v],use_source_run_attachments:c?.[v]})),b=await this._uploadExamplesMultipart(p,g);return await Promise.all(b.example_ids.map(w=>this.readExample(w)))}async createLLMExample(t,n,r){return this.createExample({input:t},{output:n},r)}async createChatExample(t,n,r){const s=t.map(i=>Ru(i)?$u(i):i),a=Ru(n)?$u(n):n;return this.createExample({input:s},{output:a},r)}async readExample(t){V(t);const n=`/examples/${t}`,r=await this._get(n),{attachment_urls:s,...a}=r,i=a;return s&&(i.attachments=Object.entries(s).reduce((o,[c,l])=>(o[c.slice(11)]={presigned_url:l.presigned_url,mime_type:l.mime_type},o),{})),i}async*listExamples({datasetId:t,datasetName:n,exampleIds:r,asOf:s,splits:a,inlineS3Urls:i,metadata:o,limit:c,offset:l,filter:u,includeAttachments:d}={}){let h;if(t!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0)h=t;else if(n!==void 0)h=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide a datasetName or datasetId");const p=new URLSearchParams({dataset:h}),f=s?typeof s=="string"?s:s?.toISOString():void 0;f&&p.append("as_of",f);const g=i??!0;if(p.append("inline_s3_urls",g.toString()),r!==void 0)for(const S of r)p.append("id",S);if(a!==void 0)for(const S of a)p.append("splits",S);if(o!==void 0){const S=JSON.stringify(o);p.append("metadata",S)}c!==void 0&&p.append("limit",c.toString()),l!==void 0&&p.append("offset",l.toString()),u!==void 0&&p.append("filter",u),d===!0&&["attachment_urls","outputs","metadata"].forEach(S=>p.append("select",S));let b=0;for await(const S of this._getPaginated("/examples",p)){for(const w of S){const{attachment_urls:v,...T}=w,k=T;v&&(k.attachments=Object.entries(v).reduce((O,[C,y])=>(O[C.slice(11)]={presigned_url:y.presigned_url,mime_type:y.mime_type||void 0},O),{})),yield k,b++}if(c!==void 0&&b>=c)break}}async deleteExample(t){V(t);const n=`/examples/${t}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(r,`delete ${n}`,!0),r})}async updateExample(t,n){let r;n?r=t:r=t.id,V(r);let s;n?s={id:r,...n}:s=t;let a;return s.dataset_id!==void 0?a=s.dataset_id:a=(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(a,[s])}async updateExamples(t){let n;return t[0].dataset_id===void 0?n=(await this.readExample(t[0].id)).dataset_id:n=t[0].dataset_id,this._updateExamplesMultipart(n,t)}async readDatasetVersion({datasetId:t,datasetName:n,asOf:r,tag:s}){let a;if(t?a=t:a=(await this.readDataset({datasetName:n})).id,V(a),r&&s||!r&&!s)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return r!==void 0&&i.append("as_of",typeof r=="string"?r:r.toISOString()),s!==void 0&&i.append("tag",s),await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${a}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:t,datasetName:n,asOf:r}){let s;if(t===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?s=(await this.readDataset({datasetName:n})).id:s=t,V(s);const a=new URLSearchParams,i=r?typeof r=="string"?r:r?.toISOString():void 0;return i&&a.append("as_of",i),await this._get(`/datasets/${s}/splits`,a)}async updateDatasetSplits({datasetId:t,datasetName:n,splitName:r,exampleIds:s,remove:a=!1}){let i;if(t===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?i=(await this.readDataset({datasetName:n})).id:i=t,V(i);const o={split_name:r,examples:s.map(l=>(V(l),l)),remove:a},c=JSON.stringify(o);await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await j(l,"update dataset splits",!0),l})}async evaluateRun(t,n,{sourceInfo:r,loadChildRuns:s,referenceExample:a}={loadChildRuns:!1}){Vo("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let i;if(typeof t=="string")i=await this.readRun(t,{loadChildRuns:s});else if(typeof t=="object"&&"id"in t)i=t;else throw new Error(`Invalid run type: ${typeof t}`);i.reference_example_id!==null&&i.reference_example_id!==void 0&&(a=await this.readExample(i.reference_example_id));const o=await n.evaluateRun(i,a),[c,l]=await this._logEvaluationFeedback(o,i,r);return l[0]}async createFeedback(t,n,{score:r,value:s,correction:a,comment:i,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:l,feedbackId:u,feedbackConfig:d,projectId:h,comparativeExperimentId:p}){if(!t&&!h)throw new Error("One of runId or projectId must be provided");if(t&&h)throw new Error("Only one of runId or projectId can be provided");const f={type:c??"api",metadata:o??{}};l!==void 0&&f?.metadata!==void 0&&!f.metadata.__run&&(f.metadata.__run={run_id:l}),f?.metadata!==void 0&&f.metadata.__run?.run_id!==void 0&&V(f.metadata.__run.run_id);const g={id:u??ke(),run_id:t,key:n,score:Fu(r),value:s,correction:a,comment:i,feedback_source:f,comparative_experiment_id:p,feedbackConfig:d,session_id:h},b=JSON.stringify(g),S=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const w=await this._fetch(S,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await j(w,"create feedback",!0),w}),g}async updateFeedback(t,{score:n,value:r,correction:s,comment:a}){const i={};n!=null&&(i.score=Fu(n)),r!=null&&(i.value=r),s!=null&&(i.correction=s),a!=null&&(i.comment=a),V(t);const o=JSON.stringify(i);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/${t}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await j(c,"update feedback",!0),c})}async readFeedback(t){V(t);const n=`/feedback/${t}`;return await this._get(n)}async deleteFeedback(t){V(t);const n=`/feedback/${t}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(r,`delete ${n}`,!0),r})}async*listFeedback({runIds:t,feedbackKeys:n,feedbackSourceTypes:r}={}){const s=new URLSearchParams;if(t)for(const a of t)V(a),s.append("run",a);if(n)for(const a of n)s.append("key",a);if(r)for(const a of r)s.append("source",a);for await(const a of this._getPaginated("/feedback",s))yield*a}async createPresignedFeedbackToken(t,n,{expiration:r,feedbackConfig:s}={}){const a={run_id:t,feedback_key:n,feedback_config:s};r?typeof r=="string"?a.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(a.expires_in=r):a.expires_in={hours:3};const i=JSON.stringify(a);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await j(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:t,experimentIds:n,referenceDatasetId:r,createdAt:s,description:a,metadata:i,id:o}){if(n.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:n[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");const c={id:o,name:t,experiment_ids:n,reference_dataset_id:r,description:a,created_at:(s??new Date)?.toISOString(),extra:{}};i&&(c.extra.metadata=i);const l=JSON.stringify(c);return(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await j(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(t){V(t);const n=new URLSearchParams({run_id:t});for await(const r of this._getPaginated("/feedback/tokens",n))yield*r}_selectEvalResults(t){let n;return"results"in t?n=t.results:Array.isArray(t)?n=t:n=[t],n}async _logEvaluationFeedback(t,n,r){const s=this._selectEvalResults(t),a=[];for(const i of s){let o=r||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let c=null;i.targetRunId?c=i.targetRunId:n&&(c=n.id),a.push(await this.createFeedback(c,i.key,{score:i.score,value:i.value,comment:i.comment,correction:i.correction,sourceInfo:o,sourceRunId:i.sourceRunId,feedbackConfig:i.feedbackConfig,feedbackSourceType:"model"}))}return[s,a]}async logEvaluationFeedback(t,n,r){const[s]=await this._logEvaluationFeedback(t,n,r);return s}async*listAnnotationQueues(t={}){const{queueIds:n,name:r,nameContains:s,limit:a}=t,i=new URLSearchParams;n&&n.forEach((c,l)=>{V(c,`queueIds[${l}]`),i.append("ids",c)}),r&&i.append("name",r),s&&i.append("name_contains",s),i.append("limit",(a!==void 0?Math.min(a,100):100).toString());let o=0;for await(const c of this._getPaginated("/annotation-queues",i))if(yield*c,o++,a!==void 0&&o>=a)break}async createAnnotationQueue(t){const{name:n,description:r,queueId:s,rubricInstructions:a}=t,i={name:n,description:r,id:s||ke(),rubric_instructions:a},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([l,u])=>u!==void 0)));return(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await j(l,"create annotation queue"),l})).json()}async readAnnotationQueue(t){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${V(t,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(t,n){const{name:r,description:s,rubricInstructions:a}=n,i=JSON.stringify({name:r,description:s,rubric_instructions:a});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${V(t,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await j(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(t){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${V(t,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,"delete annotation queue",!0),n})}async addRunsToAnnotationQueue(t,n){const r=JSON.stringify(n.map((s,a)=>V(s,`runIds[${a}]`).toString()));await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/annotation-queues/${V(t,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await j(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(t,n){const r=`/annotation-queues/${V(t,"queueId")}/run`;return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(a,"get run from annotation queue"),a})).json()}async deleteRunFromAnnotationQueue(t,n){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${V(t,"queueId")}/runs/${V(n,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(t){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${V(t,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(t){const n=await this._getSettings();return t=="-"||n.tenant_handle===t}async _ownerConflictError(t,n){const r=await this._getSettings();return new Error(`Cannot ${t} for another tenant.
46
-
47
- Current tenant: ${r.tenant_handle}
48
-
49
- Requested tenant: ${n}`)}async _getLatestCommitHash(t){const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/commits/${t}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(s,"get latest commit hash"),s})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(t,n){const[r,s,a]=pn(t),i=JSON.stringify({like:n});return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/likes/${r}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await j(c,`${n?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(t){const[n,r,s]=pn(t);if(await this._currentTenantIsOwner(n)){const a=await this._getSettings();return s!=="latest"?`${this.getHostUrl()}/prompts/${r}/${s.substring(0,8)}?organizationId=${a.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${a.id}`}else return s!=="latest"?`${this.getHostUrl()}/hub/${n}/${r}/${s.substring(0,8)}`:`${this.getHostUrl()}/hub/${n}/${r}`}async promptExists(t){return!!await this.getPrompt(t)}async likePrompt(t){return this._likeOrUnlikePrompt(t,!0)}async unlikePrompt(t){return this._likeOrUnlikePrompt(t,!1)}async*listCommits(t){for await(const n of this._getPaginated(`/commits/${t}/`,new URLSearchParams,r=>r.commits))yield*n}async*listPrompts(t){const n=new URLSearchParams;n.append("sort_field",t?.sortField??"updated_at"),n.append("sort_direction","desc"),n.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&n.append("is_public",t.isPublic.toString()),t?.query&&n.append("query",t.query);for await(const r of this._getPaginated("/repos",n,s=>s.repos))yield*r}async getPrompt(t){const[n,r,s]=pn(t),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await j(o,"get prompt"),o)}))?.json();return i?.repo?i.repo:null}async createPrompt(t,n){const r=await this._getSettings();if(n?.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first
50
-
51
- creating a LangChain Hub handle.
52
- You can add a handle by creating a public prompt at:
53
-
54
- https://smith.langchain.com/prompts`);const[s,a,i]=pn(t);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);const o={repo_handle:a,...n?.description&&{description:n.description},...n?.readme&&{readme:n.readme},...n?.tags&&{tags:n.tags},is_public:!!n?.isPublic},c=JSON.stringify(o),l=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await j(d,"create prompt"),d}),{repo:u}=await l.json();return u}async createCommit(t,n,r){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");const[s,a,i]=pn(t),o=r?.parentCommitHash==="latest"||!r?.parentCommitHash?await this._getLatestCommitHash(`${s}/${a}`):r?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(n)),parent_commit:o},l=JSON.stringify(c),d=await(await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/commits/${s}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await j(h,"create commit"),h})).json();return this._getPromptUrl(`${s}/${a}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(t,n=[]){return this._updateExamplesMultipart(t,n)}async _updateExamplesMultipart(t,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const i of n){const o=i.id,c={...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split}},l=dt(c,`Serializing body for example with id: ${o}`),u=new Blob([l],{type:"application/json"});if(r.append(o,u),i.inputs){const d=dt(i.inputs,`Serializing inputs for example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.inputs`,h)}if(i.outputs){const d=dt(i.outputs,`Serializing outputs whle updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.outputs`,h)}if(i.attachments)for(const[d,h]of Object.entries(i.attachments)){let p,f;Array.isArray(h)?[p,f]=h:(p=h.mimeType,f=h.data);const g=new Blob([f],{type:`${p}; length=${f.byteLength}`});r.append(`${o}.attachment.${d}`,g)}if(i.attachments_operations){const d=dt(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.attachments_operations`,h)}}const s=t??n[0]?.dataset_id;return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${s}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await j(i,"update examples"),i})).json()}async uploadExamplesMultipart(t,n=[]){return this._uploadExamplesMultipart(t,n)}async _uploadExamplesMultipart(t,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const a of n){const i=(a.id??ke()).toString(),o={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},c=dt(o,`Serializing body for uploaded example with id: ${i}`),l=new Blob([c],{type:"application/json"});if(r.append(i,l),a.inputs){const u=dt(a.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([u],{type:"application/json"});r.append(`${i}.inputs`,d)}if(a.outputs){const u=dt(a.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([u],{type:"application/json"});r.append(`${i}.outputs`,d)}if(a.attachments)for(const[u,d]of Object.entries(a.attachments)){let h,p;Array.isArray(d)?[h,p]=d:(h=d.mimeType,p=d.data);const f=new Blob([p],{type:`${h}; length=${p.byteLength}`});r.append(`${i}.attachment.${u}`,f)}}return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${t}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await j(a,"upload examples"),a})).json()}async updatePrompt(t,n){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");const[r,s]=pn(t);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const a={};if(n?.description!==void 0&&(a.description=n.description),n?.readme!==void 0&&(a.readme=n.readme),n?.tags!==void 0&&(a.tags=n.tags),n?.isPublic!==void 0&&(a.is_public=n.isPublic),n?.isArchived!==void 0&&(a.is_archived=n.isArchived),Object.keys(a).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(a);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${r}/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await j(c,"update prompt"),c})).json()}async deletePrompt(t){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");const[n,r,s]=pn(t);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete a prompt",n);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(i,"delete prompt"),i})).json()}async pullPromptCommit(t,n){const[r,s,a]=pn(t),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${r}/${s}/${a}${n?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(c,"pull prompt commit"),c})).json();return{owner:r,repo:s,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(t,n){const r=await this.pullPromptCommit(t,{includeModel:n?.includeModel});return JSON.stringify(r.manifest)}async pushPrompt(t,n){return await this.promptExists(t)?n&&Object.keys(n).some(s=>s!=="object")&&await this.updatePrompt(t,{description:n?.description,readme:n?.readme,tags:n?.tags,isPublic:n?.isPublic}):await this.createPrompt(t,{description:n?.description,readme:n?.readme,tags:n?.tags,isPublic:n?.isPublic}),n?.object?await this.createCommit(t,n?.object,{parentCommitHash:n?.parentCommitHash}):await this._getPromptUrl(t)}async clonePublicDataset(t,n={}){const{sourceApiUrl:r=this.apiUrl,datasetName:s}=n,[a,i]=this.parseTokenOrUrl(t,r),o=new zr({apiUrl:a,apiKey:"placeholder"}),c=await o.readSharedDataset(i),l=s||c.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}const u=await o.listSharedExamples(i),d=await this.createDataset(l,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(h=>h.inputs),outputs:u.flatMap(h=>h.outputs?[h.outputs]:[]),datasetId:d.id})}catch(h){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),h}}parseTokenOrUrl(t,n,r=2,s="dataset"){try{return V(t),[n,t]}catch{}try{const i=new URL(t).pathname.split("/").filter(o=>o!=="");if(i.length>=r){const o=i[i.length-r];return[n,o]}else throw new Error(`Invalid public ${s} URL: ${t}`)}catch{throw new Error(`Invalid public ${s} URL or token: ${t}`)}}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:t})=>t),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Vv()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function Bu(e){return"dataset_id"in e||"dataset_name"in e}const hb=e=>!!["TRACING_V2","TRACING"].find(n=>Qe(n)==="true"),so=Symbol.for("lc:context_variables");function pb(e){return e.replace(/[-:.]/g,"")}function qh(e,t,n=1){const r=n.toFixed(0).slice(0,3).padStart(3,"0"),s=`${new Date(e).toISOString().slice(0,-1)}${r}Z`;return{dottedOrder:pb(s)+t,microsecondPrecisionDatestring:s}}class Ja{constructor(t,n,r,s){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=t,this.tags=n,this.project_name=r,this.replicas=s}static fromHeader(t){const n=t.split(",");let r={},s=[],a,i;for(const o of n){const[c,l]=o.split("="),u=decodeURIComponent(l);c==="langsmith-metadata"?r=JSON.parse(u):c==="langsmith-tags"?s=u.split(","):c==="langsmith-project"?a=u:c==="langsmith-replicas"&&(i=JSON.parse(u))}return new Ja(r,s,a,i)}toHeader(){const t=[];return this.metadata&&Object.keys(this.metadata).length>0&&t.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&t.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&t.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),t.join(",")}}class Xe{constructor(t){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),fb(t)){Object.assign(this,{...t});return}const n=Xe.getDefaultConfig(),{metadata:r,...s}=t,a=s.client??Xe.getSharedClient(),i={...r,...s?.extra?.metadata};if(s.extra={...s.extra,metadata:i},"id"in s&&s.id==null&&delete s.id,Object.assign(this,{...n,...s,client:a}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=wb(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:c}=qh(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o,this._serialized_start_time=c}}set metadata(t){this.extra={...this.extra,metadata:{...this.extra?.metadata,...t}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:ke(),run_type:"chain",project_name:Uh(),child_runs:[],api_url:Kt("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Kt("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return Xe.sharedClient||(Xe.sharedClient=new zr),Xe.sharedClient}createChild(t){const n=this.child_execution_order+1,r=new Xe({...t,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n});so in this&&(r[so]=this[so]);const s=Symbol.for("lc:child_config"),a=t.extra?.[s]??this.extra[s];if(gb(a)){const c={...a},l=mb(c.callbacks)?c.callbacks.copy?.():void 0;l&&(Object.assign(l,{_parentRunId:r.id}),l.handlers?.find(Yh)?.updateFromRunTree?.(r),c.callbacks=l),r.extra[s]=c}const i=new Set;let o=this;for(;o!=null&&!i.has(o.id);)i.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,n),o=o.parent_run;return this.child_runs.push(r),r}async end(t,n,r=Date.now(),s){this.outputs=this.outputs??t,this.error=this.error??n,this.end_time=this.end_time??r,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(t,n,r=!0){const s=t.extra??{};if(s?.runtime?.library===void 0&&(s.runtime||(s.runtime={}),n))for(const[o,c]of Object.entries(n))s.runtime[o]||(s.runtime[o]=c);let a,i;return r?(i=t.parent_run?.id??t.parent_run_id,a=[]):(a=t.child_runs.map(o=>this._convertToCreate(o,n,r)),i=void 0),{id:t.id,name:t.name,start_time:t._serialized_start_time??t.start_time,end_time:t.end_time,run_type:t.run_type,reference_example_id:t.reference_example_id,extra:s,serialized:t.serialized,error:t.error,inputs:t.inputs,outputs:t.outputs,session_name:t.project_name,child_runs:a,parent_run_id:i,trace_id:t.trace_id,dotted_order:t.dotted_order,tags:t.tags,attachments:t.attachments,events:t.events}}_remapForProject(t,n,r=!0){const s=this._convertToCreate(this,n,r);if(t===this.project_name)return s;const a=d=>Es(`${d}:${t}`,Es.DNS),i=a(s.id),o=s.trace_id?a(s.trace_id):void 0,c=s.parent_run_id?a(s.parent_run_id):void 0;let l;if(s.dotted_order){const d=yb(s.dotted_order),h=[];for(let f=0;f<d.length-1;f++){const[g,b]=d[f],S=a(b);h.push(g.toISOString().replace(/[-:]/g,"").replace(".","")+S)}const[p]=d[d.length-1];h.push(p.toISOString().replace(/[-:]/g,"").replace(".","")+i),l=h.join(".")}else l=void 0;return{...s,id:i,trace_id:o,parent_run_id:c,dotted_order:l,session_name:t}}async postRun(t=!0){try{const n=Vh();if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:s,apiUrl:a,workspaceId:i}of this.replicas){const o=this._remapForProject(r??this.project_name,n,!0);await this.client.createRun(o,{apiKey:s,apiUrl:a,workspaceId:i})}else{const r=this._convertToCreate(this,n,t);await this.client.createRun(r)}if(!t){Vo("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const r of this.child_runs)await r.postRun(!1)}}catch(n){console.error(`Error in postRun for run ${this.id}:`,n)}}async patchRun(t){if(this.replicas&&this.replicas.length>0)for(const{projectName:n,apiKey:r,apiUrl:s,workspaceId:a,updates:i}of this.replicas){const o=this._remapForProject(n??this.project_name),c={id:o.id,outputs:o.outputs,error:o.error,parent_run_id:o.parent_run_id,session_name:o.session_name,reference_example_id:o.reference_example_id,end_time:o.end_time,dotted_order:o.dotted_order,trace_id:o.trace_id,events:o.events,tags:o.tags,extra:o.extra,attachments:this.attachments,...i};t?.excludeInputs||(c.inputs=o.inputs),await this.client.updateRun(o.id,c,{apiKey:r,apiUrl:s,workspaceId:a})}else try{const n={end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};t?.excludeInputs||(n.inputs=this.inputs),await this.client.updateRun(this.id,n)}catch(n){console.error(`Error in patchRun for run ${this.id}`,n)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(t){this.events||(this.events=[]),typeof t=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:t}):this.events.push({...t,time:t.time??new Date().toISOString()})}static fromRunnableConfig(t,n){const r=t?.callbacks;let s,a,i,o=hb();if(r){const l=r?.getParentRunId?.()??"",u=r?.handlers?.find(d=>d?.name=="langchain_tracer");s=u?.getRun?.(l),a=u?.projectName,i=u?.client,o=o||!!u}return s?new Xe({name:s.name,id:s.id,trace_id:s.trace_id,dotted_order:s.dotted_order,client:i,tracingEnabled:o,project_name:a,tags:[...new Set((s?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...s?.extra?.metadata,...t?.metadata}}}).createChild(n):new Xe({...n,client:i,tracingEnabled:o,project_name:a})}static fromDottedOrder(t){return this.fromHeaders({"langsmith-trace":t})}static fromHeaders(t,n){const r="get"in t&&typeof t.get=="function"?{"langsmith-trace":t.get("langsmith-trace"),baggage:t.get("baggage")}:t,s=r["langsmith-trace"];if(!s||typeof s!="string")return;const a=s.trim(),i=a.split(".").map(l=>{const[u,d]=l.split("Z");return{strTime:u,time:Date.parse(u+"Z"),uuid:d}}),o=i[0].uuid,c={...n,name:n?.name??"parent",run_type:n?.run_type??"chain",start_time:n?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:o,dotted_order:a};if(r.baggage&&typeof r.baggage=="string"){const l=Ja.fromHeader(r.baggage);c.metadata=l.metadata,c.tags=l.tags,c.project_name=l.project_name,c.replicas=l.replicas}return new Xe(c)}toHeaders(t){const n={"langsmith-trace":this.dotted_order,baggage:new Ja(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(t)for(const[r,s]of Object.entries(n))t.set(r,s);return n}}Object.defineProperty(Xe,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function fb(e){return e!=null&&typeof e.createChild=="function"&&typeof e.postRun=="function"}function Yh(e){return typeof e=="object"&&e!=null&&typeof e.name=="string"&&e.name==="langchain_tracer"}function zu(e){return Array.isArray(e)&&e.some(t=>Yh(t))}function mb(e){return typeof e=="object"&&e!=null&&Array.isArray(e.handlers)}function gb(e){return e!=null&&typeof e.callbacks=="object"&&(zu(e.callbacks?.handlers)||zu(e.callbacks))}function yb(e){return e.split(".").map(n=>{const r=n.slice(0,-36),s=n.slice(-36),a=parseInt(r.slice(0,4)),i=parseInt(r.slice(4,6))-1,o=parseInt(r.slice(6,8)),c=parseInt(r.slice(9,11)),l=parseInt(r.slice(11,13)),u=parseInt(r.slice(13,15)),d=parseInt(r.slice(15,21));return[new Date(a,i,o,c,l,u,d/1e3),s]})}function _b(){const e=Kt("LANGSMITH_RUNS_ENDPOINTS");if(!e)return[];try{const t=JSON.parse(e);if(Array.isArray(t)){const n=[];for(const r of t){if(typeof r!="object"||r===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof r}`);continue}if(typeof r.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_url}`);continue}if(typeof r.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_key}`);continue}n.push({apiUrl:r.api_url.replace(/\/$/,""),apiKey:r.api_key})}return n}else if(typeof t=="object"&&t!==null){vb(t);const n=[];for(const[r,s]of Object.entries(t)){const a=r.replace(/\/$/,"");if(typeof s=="string")n.push({apiUrl:a,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got ${typeof s}`);continue}}return n}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof t}`),[]}catch(t){if(Xv(t))throw t;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function wb(e){return e?e.map(t=>Array.isArray(t)?{projectName:t[0],updates:t[1]}:t):_b()}function vb(e){if(Object.keys(e).length>0&&Qe("ENDPOINT"))throw new Yv}var Xh={};U(Xh,{BaseTracer:()=>un,isBaseTracer:()=>hr});const bb=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function Wo(e,t){if(e)return new Xe({...e,start_time:e._serialized_start_time??e.start_time,parent_run:Wo(t),child_runs:e.child_runs.map(n=>Wo(n)).filter(n=>n!==void 0),extra:{...e.extra,runtime:Lh()},tracingEnabled:!1})}function ao(e,t){return e&&!Array.isArray(e)&&typeof e=="object"?e:{[t]:e}}function hr(e){return typeof e._addRunToRunMap=="function"}var un=class extends es{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?bb(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
55
-
56
- ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:n}=qh(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=Wo(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=ao(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),s?.inputs!==void 0&&(a.inputs=ao(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=ao(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}},Qh={};U(Qh,{ConsoleCallbackHandler:()=>Jo});function He(e,t){return`${e.open}${t}${e.close}`}function bt(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function Hu(e){return typeof e=="string"?e.trim():e==null?e:bt(e,e.toString())}function fn(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:Ye}=ih;var Jo=class extends un{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?He(ih.bold,i):i}).join(" > ");return He(Ye.grey,n)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${He(Ye.green,"[chain/start]")} [${t}] Entering Chain run with input: ${bt(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${He(Ye.cyan,"[chain/end]")} [${t}] [${fn(e)}] Exiting Chain run with output: ${bt(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${He(Ye.red,"[chain/error]")} [${t}] [${fn(e)}] Chain run errored with error: ${bt(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(`${He(Ye.green,"[llm/start]")} [${t}] Entering LLM run with input: ${bt(n,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${He(Ye.cyan,"[llm/end]")} [${t}] [${fn(e)}] Exiting LLM run with output: ${bt(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${He(Ye.red,"[llm/error]")} [${t}] [${fn(e)}] LLM run errored with error: ${bt(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${He(Ye.green,"[tool/start]")} [${t}] Entering Tool run with input: "${Hu(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${He(Ye.cyan,"[tool/end]")} [${t}] [${fn(e)}] Exiting Tool run with output: "${Hu(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${He(Ye.red,"[tool/error]")} [${t}] [${fn(e)}] Tool run errored with error: ${bt(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${He(Ye.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${bt(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${He(Ye.cyan,"[retriever/end]")} [${t}] [${fn(e)}] Exiting Retriever run with output: ${bt(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${He(Ye.red,"[retriever/error]")} [${t}] [${fn(e)}] Retriever run errored with error: ${bt(e.error,"[error]")}`)}onAgentAction(e){const t=e,n=this.getBreadcrumbs(e);console.log(`${He(Ye.blue,"[agent/action]")} [${n}] Agent selected action: ${bt(t.actions[t.actions.length-1],"[action]")}`)}};let io;const ep=()=>{if(io===void 0){const e=rn("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};io=new zr(e)}return io};let Sb=class{getStore(){}run(t,n){return n()}};const oo=Symbol.for("ls:tracing_async_local_storage"),Tb=new Sb;let Eb=class{getInstance(){return globalThis[oo]??Tb}initializeGlobalInstance(t){globalThis[oo]===void 0&&(globalThis[oo]=t)}};const Cb=new Eb;function Ab(e=!1){const t=Cb.getInstance().getStore();if(!e&&t===void 0)throw new Error(`Could not get the current run tree.
57
-
58
- Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}function ol(e){return typeof e=="function"&&"langsmith:traceable"in e}var tp={};U(tp,{LangChainTracer:()=>va});var va=class np extends un{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??Uh(),this.replicas=a,this.exampleId=n,this.client=s??ep();const i=np.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 Xe({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Ab(!0)}catch{return}}};const rp=Symbol.for("ls:tracing_async_local_storage"),ms=Symbol.for("lc:context_variables"),kb=e=>{globalThis[rp]=e},Os=()=>globalThis[rp];let Hn;function Ob(){const e="default"in nn?nn.default:nn;return new e({autoStart:!0,concurrency:1})}function xb(){return typeof Hn>"u"&&(Hn=Ob()),Hn}async function we(e,t){if(t===!0){const n=Os();n!==void 0?await n.run(void 0,async()=>e()):await e()}else Hn=xb(),Hn.add(async()=>{const n=Os();n!==void 0?await n.run(void 0,async()=>e()):await e()})}async function Ib(){const e=ep();await Promise.allSettled([typeof Hn<"u"?Hn.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}var sp={};U(sp,{awaitAllCallbacks:()=>Ib,consumeCallback:()=>we});const Pb=e=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(n=>rn(n)==="true");function ap(e){const t=Os();return t===void 0?void 0:t.getStore()?.[ms]?.[e]}const Nb=Symbol("lc:configure_hooks"),Mb=()=>ap(Nb)||[];var ip={};U(ip,{BaseCallbackManager:()=>op,BaseRunManager:()=>Ys,CallbackManager:()=>Ke,CallbackManagerForChainRun:()=>lp,CallbackManagerForLLMRun:()=>Ko,CallbackManagerForRetrieverRun:()=>cp,CallbackManagerForToolRun:()=>up,ensureHandler:()=>xs,parseCallbackConfigArg:()=>qs});function qs(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}var op=class{setHandler(e){return this.setHandlers([e])}},Ys=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)))}},cp=class extends Ys{getChild(e){const t=new Ke(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)))}},Ko=class extends Ys{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)))}},lp=class extends Ys{getChild(e){const t=new Ke(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)))}},up=class extends Ys{getChild(e){const t=new Ke(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)))}},Ke=class cs extends op{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:ke();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return hr(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 Ko(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:ke();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return hr(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=rl(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 Ko(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,n,r=ke(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return hr(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 lp(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,n,r=ke(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return hr(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 up(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,n,r=ke(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return hr(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 cp(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 cs(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=ke();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 cs,c.setHandlers(t?.map(xs)??[],!0)):c=t,c=c.copy(Array.isArray(n)?n.map(xs):n?.handlers,!1));const l=rn("LANGCHAIN_VERBOSE")==="true"||o?.verbose,u=va.getTraceableRunTree()?.tracingEnabled||Pb(),d=u||(rn("LANGCHAIN_TRACING")??!1);if(l||d){if(c||(c=new cs),l&&!c.handlers.some(h=>h.name===Jo.prototype.name)){const h=new Jo;c.addHandler(h,!0)}if(d&&!c.handlers.some(h=>h.name==="langchain_tracer")&&u){const h=new va;c.addHandler(h,!0)}if(u){const h=va.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:g}of Mb()){const b=g&&rn(g)==="true"&&f;let S;const w=h!==void 0?ap(h):void 0;w&&Dh(w)?S=w:b&&(S=new f({})),S!==void 0&&(c||(c=new cs),c.handlers.some(v=>v.name===S.name)||c.addHandler(S,p))}return(r||s)&&c&&(c.addTags(r??[]),c.addTags(s??[],!1)),(a||i)&&c&&(c.addMetadata(a??{}),c.addMetadata(i??{},!1)),c}};function xs(e){return"name"in e?e:es.fromMethods(e)}var dp=class{getStore(){}run(e,t){return t()}enterWith(e){}};const Rb=new dp,Vu=Symbol.for("lc:child_config");var $b=class{getInstance(){return Os()??Rb}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Vu]}runWithConfig(e,t,n){const r=Ke._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 Xe({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[Vu]:e}),a!==void 0&&a[ms]!==void 0&&(c===void 0&&(c={}),c[ms]=a[ms]),s.run(c,t)}initializeGlobalInstance(e){Os()===void 0&&kb(e)}};const Te=new $b;var hp={};U(hp,{AsyncLocalStorageProviderSingleton:()=>Te,MockAsyncLocalStorage:()=>dp,_CONTEXT_VARIABLES_KEY:()=>ms});const co=25;async function st(e){return Ke._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function ft(...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(xs(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(xs(o),!0);t.callbacks=i}else t.callbacks=new Ke(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 Lb=new Set(["string","number","boolean"]);function K(e){const t=Te.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))Lb.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 ln(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 xn(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(Is(t))},t.addEventListener("abort",n),t.aborted&&s(Is(t))})]).finally(()=>t.removeEventListener("abort",n))}function Is(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 Ee(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 jb(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."),Ee(e)}function Qn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(ge(e)||Ee(e))}function pp(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 fp(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 Db(e){return!!(pp(e)||fp(e))}async function cl(e,t){if(ge(e))try{return{success:!0,data:await oh(e,t)}}catch(n){return{success:!1,error:n}}if(Ee(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Ei(e,t){if(ge(e))return await oh(e,t);if(Ee(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function mp(e,t){if(ge(e))try{return{success:!0,data:Gc(e,t)}}catch(n){return{success:!1,error:n}}if(Ee(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function sn(e,t){if(ge(e))return Gc(e,t);if(Ee(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Hr(e){if(ge(e))return $e.get(e)?.description;if(Ee(e)||"description"in e&&typeof e.description=="string")return e.description}function Fb(e){if(!Qn(e))return!1;if(Ee(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 ll(e){return Qn(e)?Ee(e)?e._def.typeName==="ZodString":ge(e)?e._zod.def.type==="string":!1:!1}function ul(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 Ci(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!!(ul(e)||Wt(e))}function Ps(e){if(Ee(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 gp(e,t){if(Ee(e))return e.extend(t);if(ge(e))return c_(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ai(e){if(Ee(e))return e.partial();if(ge(e))return l_(Vc,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ka(e,t=!1){if(Ee(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=Ka(i,t);n[a]=c}else if(Ci(i)){let c=i._zod.def.element;Wt(c)&&(c=Ka(c,t)),n[a]=kn(i,{...i._zod.def,element:c})}else n[a]=i;const o=$e.get(i);o&&$e.add(n[a],o)}const r=kn(e,{...e._zod.def,shape:n,catchall:u_(d_)}),s=$e.get(e);return s&&$e.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Zo(e,t=!1){if(ul(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=Zo(i,t);n[a]=c}else if(Ci(i)){let c=i._zod.def.element;Wt(c)&&(c=Zo(c,t)),n[a]=kn(i,{...i._zod.def,element:c})}else n[a]=i;const o=$e.get(i);o&&$e.add(n[a],o)}const r=kn(e,{...e._zod.def,shape:n,catchall:h_(p_)}),s=$e.get(e);return s&&$e.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ki(e){if(Ee(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(ge(e))try{const t=Gc(e,void 0);return()=>t}catch{return}}function Ub(e){return Ee(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function Bb(e){return ge(e)&&e._zod.def.type==="pipe"}function fr(e,t=!1){if(Ee(e))return Ub(e)?fr(e._def.schema,t):e;if(ge(e)){let n=e;if(Bb(e)&&(n=fr(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]=fr(i,t);n=kn(n,{...n._zod.def,shape:s})}else if(Ci(n)){const s=fr(n._zod.def.element,t);n=kn(n,{...n._zod.def,element:s})}}const r=$e.get(e);return r&&$e.add(n,r),n}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function yp(e,t){if(Ee(e)){const n=Ps(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=Ps(e),r={...e._zod.def.shape};for(const[i,o]of Object.entries(n))t(i,o)&&(r[i]=new Vc({type:"optional",innerType:o}));const s=kn(e,{...e._zod.def,shape:r}),a=$e.get(e);return a&&$e.add(s,a),s}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}const zb=Symbol("Let zodToJsonSchema decide on which parser to use"),Hb={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"},Vb=e=>({...Hb,...e}),Gb=e=>{const t=Vb(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}]))}},_p=(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"?_p(t,e.currentPath):t.join("/")}}function wp(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function se(e,t,n,r,s){e[t]=n,wp(e,t,r,s)}function Wb(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==M.ZodAny&&(n.items=ee(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 Jb(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 Kb(){return{type:"boolean"}}function vp(e,t){return ee(e.type._def,t)}const Zb=(e,t)=>ee(e.innerType._def,t);function bp(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(s=>bp(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 qb(e,t)}}const qb=(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 Yb(e,t){return{...ee(e.innerType._def,t),default:e.defaultValue()}}function Xb(e,t){return t.effectStrategy==="input"?ee(e.schema._def,t):it(t)}function Qb(e){return{type:"string",enum:Array.from(e.values)}}const e0=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function t0(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(e0(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 n0(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 lo;const Ot={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:()=>(lo===void 0&&(lo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),lo),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 Sp(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":xt(n,"email",r.message,t);break;case"format:idn-email":xt(n,"idn-email",r.message,t);break;case"pattern:zod":Ve(n,Ot.email,r.message,t);break}break;case"url":xt(n,"uri",r.message,t);break;case"uuid":xt(n,"uuid",r.message,t);break;case"regex":Ve(n,r.regex,r.message,t);break;case"cuid":Ve(n,Ot.cuid,r.message,t);break;case"cuid2":Ve(n,Ot.cuid2,r.message,t);break;case"startsWith":Ve(n,RegExp(`^${uo(r.value,t)}`),r.message,t);break;case"endsWith":Ve(n,RegExp(`${uo(r.value,t)}$`),r.message,t);break;case"datetime":xt(n,"date-time",r.message,t);break;case"date":xt(n,"date",r.message,t);break;case"time":xt(n,"time",r.message,t);break;case"duration":xt(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":Ve(n,RegExp(uo(r.value,t)),r.message,t);break;case"ip":r.version!=="v6"&&xt(n,"ipv4",r.message,t),r.version!=="v4"&&xt(n,"ipv6",r.message,t);break;case"base64url":Ve(n,Ot.base64url,r.message,t);break;case"jwt":Ve(n,Ot.jwt,r.message,t);break;case"cidr":r.version!=="v6"&&Ve(n,Ot.ipv4Cidr,r.message,t),r.version!=="v4"&&Ve(n,Ot.ipv6Cidr,r.message,t);break;case"emoji":Ve(n,Ot.emoji(),r.message,t);break;case"ulid":Ve(n,Ot.ulid,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":xt(n,"binary",r.message,t);break;case"contentEncoding:base64":se(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":Ve(n,Ot.base64,r.message,t);break}break;case"nanoid":Ve(n,Ot.nanoid,r.message,t);break}return n}function uo(e,t){return t.patternStrategy==="escape"?s0(e):e}const r0=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function s0(e){let t="";for(let n=0;n<e.length;n++)r0.has(e[n])||(t+="\\"),t+=e[n];return t}function xt(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 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:Gu(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):se(e,"pattern",Gu(t,r),n,r)}function Gu(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
- ]))`;continue}else if(r[c]==="$"){s+=`($|(?=[\r
60
- ]))`;continue}}if(n.s&&r[c]==="."){s+=i?`${r[c]}\r
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 Tp(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===M.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,s)=>({...r,[s]:ee(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??it(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:ee(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===M.ZodString&&e.keyType._def.checks?.length){const{type:r,...s}=Sp(e.keyType._def,t);return{...n,propertyNames:s}}else{if(e.keyType?._def.typeName===M.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===M.ZodBranded&&e.keyType._def.type._def.typeName===M.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...s}=vp(e.keyType._def,t);return{...n,propertyNames:s}}}return n}function a0(e,t){if(t.mapStrategy==="record")return Tp(e,t);const n=ee(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||it(t),r=ee(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||it(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function i0(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 o0(e){return e.target==="openAi"?void 0:{not:it({...e,currentPath:[...e.currentPath,"not"]})}}function c0(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Za={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function l0(e,t){if(t.target==="openApi3")return Wu(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Za&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,a)=>{const i=Za[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 Wu(e,t)}const Wu=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,s)=>ee(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 u0(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:Za[e.innerType._def.typeName],nullable:!0}:{type:[Za[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const r=ee(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=ee(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function d0(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",wp(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 h0(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=f0(c);l&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const u=ee(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=p0(e,t);return i!==void 0&&(r.additionalProperties=i),r}function p0(e,t){if(e.catchall._def.typeName!=="ZodNever")return ee(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 f0(e){try{return e.isOptional()}catch{return!0}}const m0=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return ee(e.innerType._def,t);const n=ee(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:it(t)},n]}:it(t)},g0=(e,t)=>{if(t.pipeStrategy==="input")return ee(e.in._def,t);if(t.pipeStrategy==="output")return ee(e.out._def,t);const n=ee(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=ee(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}};function y0(e,t){return ee(e.type._def,t)}function _0(e,t){const r={type:"array",uniqueItems:!0,items:ee(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 w0(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>ee(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:ee(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>ee(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function v0(e){return{not:it(e)}}function b0(e){return it(e)}const S0=(e,t)=>ee(e.innerType._def,t),T0=(e,t,n)=>{switch(t){case M.ZodString:return Sp(e,n);case M.ZodNumber:return d0(e,n);case M.ZodObject:return h0(e,n);case M.ZodBigInt:return Jb(e,n);case M.ZodBoolean:return Kb();case M.ZodDate:return bp(e,n);case M.ZodUndefined:return v0(n);case M.ZodNull:return c0(n);case M.ZodArray:return Wb(e,n);case M.ZodUnion:case M.ZodDiscriminatedUnion:return l0(e,n);case M.ZodIntersection:return t0(e,n);case M.ZodTuple:return w0(e,n);case M.ZodRecord:return Tp(e,n);case M.ZodLiteral:return n0(e,n);case M.ZodEnum:return Qb(e);case M.ZodNativeEnum:return i0(e);case M.ZodNullable:return u0(e,n);case M.ZodOptional:return m0(e,n);case M.ZodMap:return a0(e,n);case M.ZodSet:return _0(e,n);case M.ZodLazy:return()=>e.getter()._def;case M.ZodPromise:return y0(e,n);case M.ZodNaN:case M.ZodNever:return o0(n);case M.ZodEffects:return Xb(e,n);case M.ZodAny:return it(n);case M.ZodUnknown:return b0(n);case M.ZodDefault:return Yb(e,n);case M.ZodBranded:return vp(e,n);case M.ZodReadonly:return S0(e,n);case M.ZodCatch:return Zb(e,n);case M.ZodPipeline:return g0(e,n);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(r=>{})()}};function ee(e,t,n=!1){const r=t.seen.get(e);if(t.override){const o=t.override?.(e,t,r,n);if(o!==zb)return o}if(r&&!n){const o=E0(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=T0(e,e.typeName,t),i=typeof a=="function"?ee(a(),t):a;if(i&&C0(e,t,i),t.postProcess){const o=t.postProcess(i,e,t);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const E0=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:_p(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`),it(t)):t.$refStrategy==="seen"?it(t):void 0}},C0=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),A0=(e,t)=>{const n=Gb(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((o,[c,l])=>({...o,[c]:ee(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??it(n)}),{}):void 0;const s=typeof t=="string"?t:t?.name,a=ee(e._def,n,!1)??it(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 Ep={};U(Ep,{Validator:()=>Wc,deepCompareStrict:()=>ch,toJsonSchema:()=>mt,validatesOnlyStrings:()=>gs});function mt(e){if(ge(e)){const t=fr(e,!0);if(Wt(t)){const n=Ka(t,!0);return fu(n)}else return fu(e)}return Ee(e)?A0(e):e}function gs(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=>gs(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=>gs(n))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){const t=e.$ref,n=f_(e);return n[t]?gs(n[t]):!1}return!1}var Cp={};U(Cp,{AsyncCaller:()=>Xs});const k0=[400,401,402,403,404,405,406,407,409],O0=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&&k0.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){const n=new Error(e?.message);throw n.name="InsufficientQuotaError",n}};var Xs=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??O0;const t="default"in nn?nn.default:nn;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>Ha(()=>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){if(e.signal){let r;return Promise.race([this.call(t,...n),new Promise((s,a)=>{r=()=>{a(Is(e.signal))},e.signal?.addEventListener("abort",r)})]).finally(()=>{e.signal&&r&&e.signal.removeEventListener("abort",r)})}return this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}},Ap={};U(Ap,{AsyncGeneratorWithSetup:()=>Mn,IterableReadableStream:()=>Be,atee:()=>dl,concat:()=>In,pipeGeneratorWithSetup:()=>kp});var Be=class qo 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 qo({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 qo({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 dl(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 In(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]=In(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)=>{Te.runWithConfig(ln(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?Te.runWithConfig(ln(this.config),this.signal?async()=>xn(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 kp(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}}const x0=Object.prototype.hasOwnProperty;function Yo(e,t){return x0.call(e,t)}function Xo(e){if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=""+r;return n}if(Object.keys)return Object.keys(e);let t=[];for(let n in e)Yo(e,n)&&t.push(n);return t}function jt(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function Qo(e){let t=0;const n=e.length;let r;for(;t<n;){if(r=e.charCodeAt(t),r>=48&&r<=57){t++;continue}return!1}return!0}function lr(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function I0(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function ec(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let n=0,r=e.length;n<r;n++)if(ec(e[n]))return!0}else if(typeof e=="object"){const n=Xo(e),r=n.length;for(var t=0;t<r;t++)if(ec(e[n[t]]))return!0}}return!1}function Ju(e,t){const n=[e];for(const r in t){const s=typeof t[r]=="object"?JSON.stringify(t[r],null,2):t[r];typeof s<"u"&&n.push(`${r}: ${s}`)}return n.join(`
63
- `)}var P0=class extends Error{constructor(e,t,n,r,s){super(Ju(e,{name:t,index:n,operation:r,tree:s})),this.name=t,this.index=n,this.operation=r,this.tree=s,Object.setPrototypeOf(this,new.target.prototype),this.message=Ju(e,{name:t,index:n,operation:r,tree:s})}},Op={};U(Op,{JsonPatchError:()=>me,_areEquals:()=>Ns,applyOperation:()=>Vn,applyPatch:()=>Vr,applyReducer:()=>R0,deepClone:()=>N0,getValueByPointer:()=>qa,validate:()=>xp,validator:()=>Ya});const me=P0,N0=jt,mr={add:function(e,t,n){return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){let r=qa(n,this.path);r&&(r=jt(r));const s=Vn(n,{op:"remove",path:this.from}).removed;return Vn(n,{op:"add",path:this.path,value:s}),{newDocument:n,removed:r}},copy:function(e,t,n){const r=qa(n,this.from);return Vn(n,{op:"add",path:this.path,value:jt(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:Ns(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}};var M0={add:function(e,t,n){return Qo(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){var r=e.splice(t,1);return{newDocument:n,removed:r[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:mr.move,copy:mr.copy,test:mr.test,_get:mr._get};function qa(e,t){if(t=="")return e;var n={op:"_get",path:t};return Vn(e,n),n.value}function Vn(e,t,n=!1,r=!0,s=!0,a=0){if(n&&(typeof n=="function"?n(t,0,e,t.path):Ya(t,0)),t.path===""){let i={newDocument:e};if(t.op==="add")return i.newDocument=t.value,i;if(t.op==="replace")return i.newDocument=t.value,i.removed=e,i;if(t.op==="move"||t.op==="copy")return i.newDocument=qa(e,t.from),t.op==="move"&&(i.removed=e),i;if(t.op==="test"){if(i.test=Ns(e,t.value),i.test===!1)throw new me("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return i.newDocument=e,i}else{if(t.op==="remove")return i.removed=e,i.newDocument=null,i;if(t.op==="_get")return t.value=e,i;if(n)throw new me("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,t,e);return i}}else{r||(e=jt(e));const o=(t.path||"").split("/");let c=e,l=1,u=o.length,d,h,p;for(typeof n=="function"?p=n:p=Ya;;){if(h=o[l],h&&h.indexOf("~")!=-1&&(h=I0(h)),s&&(h=="__proto__"||h=="prototype"&&l>0&&o[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&d===void 0&&(c[h]===void 0?d=o.slice(0,l).join("/"):l==u-1&&(d=t.path),d!==void 0&&p(t,0,e,d)),l++,Array.isArray(c)){if(h==="-")h=c.length;else{if(n&&!Qo(h))throw new me("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",a,t,e);Qo(h)&&(h=~~h)}if(l>=u){if(n&&t.op==="add"&&h>c.length)throw new me("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,t,e);const f=M0[t.op].call(t,c,h,e);if(f.test===!1)throw new me("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return f}}else if(l>=u){const f=mr[t.op].call(t,c,h,e);if(f.test===!1)throw new me("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return f}if(c=c[h],n&&l<u&&(!c||typeof c!="object"))throw new me("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,t,e)}}}function Vr(e,t,n,r=!0,s=!0){if(n&&!Array.isArray(t))throw new me("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(e=jt(e));const a=new Array(t.length);for(let i=0,o=t.length;i<o;i++)a[i]=Vn(e,t[i],n,!0,s,i),e=a[i].newDocument;return a.newDocument=e,a}function R0(e,t,n){const r=Vn(e,t);if(r.test===!1)throw new me("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return r.newDocument}function Ya(e,t,n,r){if(typeof e!="object"||e===null||Array.isArray(e))throw new me("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,n);if(mr[e.op]){if(typeof e.path!="string")throw new me("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,n);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new me('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,n);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new me("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new me("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&ec(e.value))throw new me("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,n);if(n){if(e.op=="add"){var s=e.path.split("/").length,a=r.split("/").length;if(s!==a+1&&s!==a)throw new me("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,n)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==r)throw new me("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,n)}else if(e.op==="move"||e.op==="copy"){var i={op:"_get",path:e.from,value:void 0},o=xp([i],n);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new me("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}}else throw new me("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n)}function xp(e,t,n){try{if(!Array.isArray(e))throw new me("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)Vr(jt(t),jt(e),n||!0);else{n=n||Ya;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(s){if(s instanceof me)return s;throw s}}function Ns(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var n=Array.isArray(e),r=Array.isArray(t),s,a,i;if(n&&r){if(a=e.length,a!=t.length)return!1;for(s=a;s--!==0;)if(!Ns(e[s],t[s]))return!1;return!0}if(n!=r)return!1;var o=Object.keys(e);if(a=o.length,a!==Object.keys(t).length)return!1;for(s=a;s--!==0;)if(!t.hasOwnProperty(o[s]))return!1;for(s=a;s--!==0;)if(i=o[s],!Ns(e[i],t[i]))return!1;return!0}return e!==e&&t!==t}function Ip(e,t,n,r,s){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var a=Xo(t),i=Xo(e),o=!1,c=i.length-1;c>=0;c--){var l=i[c],u=e[l];if(Yo(t,l)&&!(t[l]===void 0&&u!==void 0&&Array.isArray(t)===!1)){var d=t[l];typeof u=="object"&&u!=null&&typeof d=="object"&&d!=null&&Array.isArray(u)===Array.isArray(d)?Ip(u,d,n,r+"/"+lr(l),s):u!==d&&(s&&n.push({op:"test",path:r+"/"+lr(l),value:jt(u)}),n.push({op:"replace",path:r+"/"+lr(l),value:jt(d)}))}else Array.isArray(e)===Array.isArray(t)?(s&&n.push({op:"test",path:r+"/"+lr(l),value:jt(u)}),n.push({op:"remove",path:r+"/"+lr(l)}),o=!0):(s&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:t}))}if(!(!o&&a.length==i.length))for(var c=0;c<a.length;c++){var l=a[c];!Yo(e,l)&&t[l]!==void 0&&n.push({op:"add",path:r+"/"+lr(l),value:jt(t[l])})}}}function Oi(e,t,n=!1){var r=[];return Ip(e,t,r,"",n),r}({...Op});var Pp={};U(Pp,{LogStreamCallbackHandler:()=>nc,RunLog:()=>hl,RunLogPatch:()=>Xt,isLogStreamHandler:()=>Np});var Xt=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),n=Vr({},t);return new hl({ops:t,state:n[n.length-1].newDocument})}},hl=class tc extends Xt{state;constructor(t){super(t),this.state=t.state}concat(t){const n=this.ops.concat(t.ops),r=Vr(this.state,t.ops);return new tc({ops:n,state:r[r.length-1].newDocument})}static fromRunLogPatch(t){const n=Vr({},t.ops);return new tc({ops:t.ops,state:n[n.length-1].newDocument})}};const Np=e=>e.name==="log_stream_tracer";async function Ku(e,t){if(t==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:n}=e;if(["retriever","llm","prompt"].includes(e.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===""))return n.input}async function Zu(e,t){const{outputs:n}=e;return t==="original"||["retriever","llm","prompt"].includes(e.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function $0(e){return e!==void 0&&e.message!==void 0}var nc=class extends un{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Be.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n=n||t.find(r=>this.includeTags?.includes(r))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n=n&&t.every(r=>!this.excludeTags?.includes(r))),n}async*tapOutputIterable(e,t){for await(const n of t){if(e!==this.rootId){const r=this.keyMapByRunId[e];r&&await this.writer.write(new Xt({ops:[{op:"add",path:`/logs/${r}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new Xt({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;const n={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(n.inputs=await Ku(e,this._schemaFormat)),await this.writer.write(new Xt({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(t===void 0)return;const n=[];this._schemaFormat==="streaming_events"&&n.push({op:"replace",path:`/logs/${t}/inputs`,value:await Ku(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await Zu(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const r=new Xt({ops:n});await this.writer.write(r)}finally{if(e.id===this.rootId){const t=new Xt({ops:[{op:"replace",path:"/final_output",value:await Zu(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){const r=this.keyMapByRunId[e.id];if(r===void 0)return;const s=e.inputs.messages!==void 0;let a;s?$0(n?.chunk)?a=n?.chunk:a=new yt({id:`run-${e.id}`,content:t}):a=t;const i=new Xt({ops:[{op:"add",path:`/logs/${r}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${r}/streamed_output/-`,value:a}]});await this.writer.write(i)}},Mp={};U(Mp,{ChatGenerationChunk:()=>Wr,GenerationChunk:()=>Gr,RUN_KEY:()=>Ms});const Ms="__run";var Gr=class Rp{text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new Rp({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},Wr=class $p extends Gr{message;constructor(t){super(t),this.message=t.message}concat(t){return new $p({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function da({name:e,serialized:t}){return e!==void 0?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const L0=e=>e.name==="event_stream_tracer";var j0=class extends un{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Be.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(n=n||t.find(r=>this.includeTags?.includes(r))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(n=n&&t.every(r=>!this.excludeTags?.includes(r))),n}async*tapOutputIterable(e,t){const n=await t.next();if(n.done)return;const r=this.runInfoMap.get(e);if(r===void 0){yield n.value;return}function s(i,o){return i==="llm"&&typeof o=="string"?new Gr({text:o}):o}let a=this.tappedPromises.get(e);if(a===void 0){let i;a=new Promise(o=>{i=o}),this.tappedPromises.set(e,a);try{const o={event:`on_${r.runType}_stream`,run_id:e,name:r.name,tags:r.tags,metadata:r.metadata,data:{}};await this.send({...o,data:{chunk:s(r.runType,n.value)}},r),yield n.value;for await(const c of t)r.runType!=="tool"&&r.runType!=="retriever"&&await this.send({...o,data:{chunk:s(r.runType,c)}},r),yield c}finally{i?.()}}else{yield n.value;for await(const i of t)yield i}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const n=this.tappedPromises.get(e.run_id);n!==void 0?n.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){const t=da(e),n=e.inputs.messages!==void 0?"chat_model":"llm",r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,r);const s=`on_${n}_start`;await this.send({event:s,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onLLMNewToken(e,t,n){const r=this.runInfoMap.get(e.id);let s,a;if(r===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(r.runType==="chat_model")a="on_chat_model_stream",n?.chunk===void 0?s=new yt({content:t,id:`run-${e.id}`}):s=n.chunk.message;else if(r.runType==="llm")a="on_llm_stream",n?.chunk===void 0?s=new Gr({text:t}):s=n.chunk;else throw new Error(`Unexpected run type ${r.runType}`);await this.send({event:a,data:{chunk:s},run_id:e.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let n;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const r=e.outputs?.generations;let s;if(t.runType==="chat_model"){for(const a of r??[]){if(s!==void 0)break;s=a[0]?.message}n="on_chat_model_end"}else if(t.runType==="llm")s={generations:r?.map(a=>a.map(i=>({text:i.text,generationInfo:i.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:s,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=da(e),n=e.run_type??"chain",r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let s={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(s={},r.inputs={}):e.inputs.input!==void 0?(s.input=e.inputs.input,r.inputs=e.inputs.input):(s.input=e.inputs,r.inputs=e.inputs),this.runInfoMap.set(e.id,r),await this.send({event:`on_${n}_start`,data:s,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const n=`on_${e.run_type}_end`,r=e.inputs??t.inputs??{},a={output:e.outputs?.output??e.outputs,input:r};r.input&&Object.keys(r).length===1&&(a.input=r.input,t.inputs=r.input),await this.sendEndEvent({event:n,data:a,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=da(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},n)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const n=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){const t=da(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,n){const r=this.runInfoMap.get(n);if(r===void 0)throw new Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:"on_custom_event",run_id:n,name:e,tags:r.tags,metadata:r.metadata,data:t},r)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},Lp=class extends un{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:n,onError:r}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=r}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function pl(e){return e?e.lc_runnable:!1}var D0=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const r=e.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t)),this.includeTags!==void 0&&(n=n||r.some(s=>this.includeTags?.includes(s))),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n=n&&r.every(s=>!this.excludeTags?.includes(s))),n}};function ho(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const F0=["*","_","`"];function U0(e){let t="";for(const[n,r]of Object.entries(e))t+=` classDef ${n} ${r};
64
- `;return t}function B0(e,t,n){const{firstNode:r,lastNode:s,nodeColors:a,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=n??{};let l=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
65
- graph TD;
66
- `:`graph TD;
67
- `;if(i){const p="default",f={[p]:"{0}({1})"};r!==void 0&&(f[r]="{0}([{1}]):::first"),s!==void 0&&(f[s]="{0}([{1}]):::last");for(const[g,b]of Object.entries(e)){const S=b.name.split(":").pop()??"";let v=F0.some(k=>S.startsWith(k)&&S.endsWith(k))?`<p>${S}</p>`:S;Object.keys(b.metadata??{}).length&&(v+=`<hr/><small><em>${Object.entries(b.metadata??{}).map(([k,O])=>`${k} = ${O}`).join(`
68
- `)}</em></small>`);const T=(f[g]??f[p]).replace("{0}",ho(g)).replace("{1}",v);l+=` ${T}
69
- `}}const u={};for(const p of t){const f=p.source.split(":"),g=p.target.split(":"),b=f.filter((S,w)=>S===g[w]).join(":");u[b]||(u[b]=[]),u[b].push(p)}const d=new Set;function h(p,f){const g=p.length===1&&p[0].source===p[0].target;if(f&&!g){const b=f.split(":").pop();if(d.has(b))throw new Error(`Found duplicate subgraph '${b}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(b),l+=` subgraph ${b}
70
- `}for(const b of p){const{source:S,target:w,data:v,conditional:T}=b;let k="";if(v!==void 0){let O=v;const C=O.split(" ");C.length>c&&(O=Array.from({length:Math.ceil(C.length/c)},(y,N)=>C.slice(N*c,(N+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),k=T?` -. &nbsp;${O}&nbsp; .-> `:` -- &nbsp;${O}&nbsp; --> `}else k=T?" -.-> ":" --> ";l+=` ${ho(S)}${k}${ho(w)};
71
- `}for(const b in u)b.startsWith(`${f}:`)&&b!==f&&h(u[b],b);f&&!g&&(l+=` end
72
- `)}h(u[""]??[],"");for(const p in u)!p.includes(":")&&p!==""&&h(u[p],p);return i&&(l+=U0(a??{})),l}async function z0(e,t){let n=t?.backgroundColor??"white";const r=t?.imageType??"png",s=btoa(e);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));const a=`https://mermaid.ink/img/${s}?bgColor=${n}&type=${r}`,i=await fetch(a);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
73
- `));return await i.blob()}var jp={};U(jp,{Graph:()=>Rs});function H0(e,t){if(e!==void 0&&!br(e))return e;if(pl(t))try{let n=t.getName();return n=n.startsWith("Runnable")?n.slice(8):n,n}catch{return t.getName()}else return t.name??"UnknownSchema"}function V0(e){return pl(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...mt(e.data.schema),title:e.data.name}}}var Rs=class Dp{nodes={};edges=[];constructor(t){this.nodes=t?.nodes??this.nodes,this.edges=t?.edges??this.edges}toJSON(){const t={};return Object.values(this.nodes).forEach((n,r)=>{t[n.id]=br(n.id)?r:n.id}),{nodes:Object.values(this.nodes).map(n=>({id:t[n.id],...V0(n)})),edges:this.edges.map(n=>{const r={source:t[n.source],target:t[n.target]};return typeof n.data<"u"&&(r.data=n.data),typeof n.conditional<"u"&&(r.conditional=n.conditional),r})}}addNode(t,n,r){if(n!==void 0&&this.nodes[n]!==void 0)throw new Error(`Node with id ${n} already exists`);const s=n??ke(),a={id:s,data:t,name:H0(n,t),metadata:r};return this.nodes[s]=a,a}removeNode(t){delete this.nodes[t.id],this.edges=this.edges.filter(n=>n.source!==t.id&&n.target!==t.id)}addEdge(t,n,r,s){if(this.nodes[t.id]===void 0)throw new Error(`Source node ${t.id} not in graph`);if(this.nodes[n.id]===void 0)throw new Error(`Target node ${n.id} not in graph`);const a={source:t.id,target:n.id,data:r,conditional:s};return this.edges.push(a),a}firstNode(){return qu(this)}lastNode(){return Yu(this)}extend(t,n=""){let r=n;Object.values(t.nodes).map(l=>l.id).every(br)&&(r="");const a=l=>r?`${r}:${l}`:l;Object.entries(t.nodes).forEach(([l,u])=>{this.nodes[a(l)]={...u,id:a(l)}});const i=t.edges.map(l=>({...l,source:a(l.source),target:a(l.target)}));this.edges=[...this.edges,...i];const o=t.firstNode(),c=t.lastNode();return[o?{id:a(o.id),data:o.data}:void 0,c?{id:a(c.id),data:c.data}:void 0]}trimFirstNode(){const t=this.firstNode();t&&qu(this,[t.id])&&this.removeNode(t)}trimLastNode(){const t=this.lastNode();t&&Yu(this,[t.id])&&this.removeNode(t)}reid(){const t=Object.fromEntries(Object.values(this.nodes).map(s=>[s.id,s.name])),n=new Map;Object.values(t).forEach(s=>{n.set(s,(n.get(s)||0)+1)});const r=s=>{const a=t[s];return br(s)&&n.get(a)===1?a:s};return new Dp({nodes:Object.fromEntries(Object.entries(this.nodes).map(([s,a])=>[r(s),{...a,id:r(s)}])),edges:this.edges.map(s=>({...s,source:r(s.source),target:r(s.target)}))})}drawMermaid(t){const{withStyles:n,curveStyle:r,nodeColors:s={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:a}=t??{},i=this.reid(),o=i.firstNode(),c=i.lastNode();return B0(i.nodes,i.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:n,curveStyle:r,nodeColors:s,wrapLabelNWords:a})}async drawMermaidPng(t){const n=this.drawMermaid(t);return z0(n,{backgroundColor:t?.backgroundColor})}};function qu(e,t=[]){const n=new Set(e.edges.filter(s=>!t.includes(s.source)).map(s=>s.target)),r=[];for(const s of Object.values(e.nodes))!t.includes(s.id)&&!n.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function Yu(e,t=[]){const n=new Set(e.edges.filter(s=>!t.includes(s.target)).map(s=>s.source)),r=[];for(const s of Object.values(e.nodes))!t.includes(s.id)&&!n.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function G0(e){const t=new TextEncoder,n=new ReadableStream({async start(r){for await(const s of e)r.enqueue(t.encode(`event: data
74
- data: ${JSON.stringify(s)}
75
-
76
- `));r.enqueue(t.encode(`event: end
77
-
78
- `)),r.close()}});return Be.fromReadableStream(n)}function Xu(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}const W0=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function";function rc(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function*Qu(e,t){for(;;){const{value:n,done:r}=Te.runWithConfig(ln(e),t.next.bind(t),!0);if(r)break;yield n}}async function*sc(e,t){const n=t[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await Te.runWithConfig(ln(e),n.next.bind(t),!0);if(s)break;yield r}}function Oe(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}var J=class extends At{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 fl({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Fe({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new Vp({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 Xs({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,Be.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 st(r))?.handleChainStart(this.toJSON(),Oe(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 xn(o,n?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(Oe(i,"output")),i}async _batchWithConfig(e,t,n,r){const s=this._getOptionsList(n??{},t.length),a=await Promise.all(s.map(st)),i=await Promise.all(a.map(async(c,l)=>{const u=await c?.handleChainStart(this.toJSON(),Oe(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 xn(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(Oe(o,"output")))),o}_concatOutputChunks(e,t){return In(e,t)}async*_transformStreamWithConfig(e,t,n){let r,s=!0,a,i=!0;const o=K(n),c=await st(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 kp(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(L0);let f=h.output;p!==void 0&&d!==void 0&&(f=p.tapOutputIterable(d.runId,f));const g=d?.handlers.find(Np);g!==void 0&&d!==void 0&&(f=g.tapOutputIterable(d.runId,f));for await(const b of f)if(yield b,i)if(a===void 0)a=b;else try{a=this._concatOutputChunks(a,b)}catch{a=void 0,i=!1}}catch(h){throw await d?.handleChainError(h,void 0,void 0,void 0,{inputs:Oe(r,"input")}),h}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:Oe(r,"input")})}getGraph(e){const t=new Rs,n=t.addNode({name:`${this.getName()}Input`,schema:Tt()}),r=t.addNode(this),s=t.addNode({name:`${this.getName()}Output`,schema:Tt()});return t.addEdge(n,r),t.addEdge(r,s),t}pipe(e){return new kt({first:this,last:Le(e)})}pick(e){return this.pipe(new Gp(e))}assign(e){return this.pipe(new ml(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 nc({...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 Xt({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"?G0(r):Be.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){const r=new j0({...n,autoClose:!1}),s=K(t),a=s.runId??ke();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 g=await c.stream(e,{...s,signal:p}),b=r.tapOutputIterable(a,g);for await(const S of b)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 nc({...n,autoClose:!1,_schemaFormat:"streaming_events"}),u=new D0({...n}),d=this._streamLog(e,l,a);for await(const p of d){if(r?r=r.concat(p):r=hl.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 S={...r.state},w={run_id:S.id,event:`on_${S.type}_start`,name:c,tags:i,metadata:o,data:{input:e}};u.includeEvent(w,S.type)&&(yield w)}const f=p.ops.filter(S=>S.path.startsWith("/logs/")).map(S=>S.path.split("/")[2]),g=[...new Set(f)];for(const S of g){let w,v={};const T=r.state.logs[S];if(T.end_time===void 0?T.streamed_output.length>0?w="stream":w="start":w="end",w==="start")T.inputs!==void 0&&(v.input=T.inputs);else if(w==="end")T.inputs!==void 0&&(v.input=T.inputs),v.output=T.final_output;else if(w==="stream"){const k=T.streamed_output.length;if(k!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${k} instead. Encountered in: "${T.name}"`);v={chunk:T.streamed_output[0]},T.streamed_output=[]}yield{event:`on_${T.type}_${w}`,name:T.name,run_id:T.id,tags:T.tags,metadata:T.metadata,data:v}}const{state:b}=r;if(b.streamed_output.length>0){const S=b.streamed_output.length;if(S!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${S} instead. Encountered in: "${b.name}"`);const w={chunk:b.streamed_output[0]};b.streamed_output=[];const v={event:`on_${b.type}_stream`,run_id:b.id,tags:i,metadata:o,name:c,data:w};u.includeEvent(v,b.type)&&(yield v)}}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 pl(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new Fe({bound:this,config:{},configFactories:[r=>({callbacks:[new Lp({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return Y0(this,e)}},Fe=class Fp 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=ft(this.config,...t);return ft(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 fl({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 Be.fromAsyncGenerator(a())}static isRunnableBinding(t){return t.bound&&J.isRunnable(t.bound)}withListeners({onStart:t,onEnd:n,onError:r}){return new Fp({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[s=>({callbacks:[new Lp({config:s,onStart:t,onEnd:n,onError:r})]})]})}},J0=class Up 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 Up({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:r})})}},fl=class extends Fe{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 Ha(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 Ha(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)}},kt=class ls 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 st(r))?.handleChainStart(this.toJSON(),Oe(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 xn(d,n?.signal)}if(n?.signal?.aborted)throw Is(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(Oe(o,"output")),o}async batch(t,n,r){const s=this._getOptionsList(n??{},t.length),a=await Promise.all(s.map(st)),i=await Promise.all(a.map(async(c,l)=>{const u=await c?.handleChainStart(this.toJSON(),Oe(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 xn(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(Oe(o,"output")))),o}_concatOutputChunks(t,n){return this.last._concatOutputChunks(t,n)}async*_streamIterator(t,n){const r=await st(n),{runId:s,...a}=n??{},i=await r?.handleChainStart(this.toJSON(),Oe(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(Oe(l,"output"))}getGraph(t){const n=new Rs;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 ls.isRunnableSequence(t)?new ls({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new ls({first:this.first,middle:[...this.middle,this.last],last:Le(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 ls({...s,first:Le(t),middle:n.slice(0,-1).map(Le),last:Le(n[n.length-1])})}},ts=class Bp 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]=Le(r)}static from(t){return new Bp({steps:t})}async invoke(t,n){const r=K(n),a=await(await st(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 xn(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=dl(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 xn(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,Be.fromAsyncGenerator(a)}},K0=class zp extends J{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(t){if(super(t),!ol(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 st(r),a=this.func(ne(r,{callbacks:s}),t);return xn(a,r?.signal)}async*_streamIterator(t,n){const[r]=this._getOptionsList(n??{},1),s=await this.invoke(t,n);if(rc(s)){for await(const a of s)r?.signal?.throwIfAborted(),yield a;return}if(W0(s)){for(;;){r?.signal?.throwIfAborted();const a=s.next();if(a.done)break;yield a.value}return}yield s}static from(t){return new zp({func:t})}};function Z0(e){if(ol(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var ot=class Hp extends J{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(t){if(ol(t.func))return K0.from(t.func);super(t),Z0(t.func),this.func=t.func}static from(t){return new Hp({func:t})}async _invoke(t,n,r){return new Promise((s,a)=>{const i=ne(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??co)-1});Te.runWithConfig(ln(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??co)-1})}else if(rc(o)){let c;for await(const l of sc(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(Xu(o)){let c;for(const l of Qu(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??co)-1}),i=await new Promise((o,c)=>{Te.runWithConfig(ln(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(rc(i))for await(const o of sc(a,i))r?.signal?.throwIfAborted(),yield o;else if(Xu(i))for(const o of Qu(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,Be.fromAsyncGenerator(a)}},q0=class extends ts{},Vp=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 st(n),{runId:s,...a}=n,i=await r?.handleChainStart(this.toJSON(),Oe(e,"input"),s,void 0,void 0,void 0,a?.runName),o=ne(a,{callbacks:i?.getChild()});return await Te.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(Oe(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 st(n),{runId:s,...a}=n,i=await r?.handleChainStart(this.toJSON(),Oe(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=sc(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(Oe(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=>st(o))),a=await Promise.all(s.map(async(o,c)=>{const l=await o?.handleChainStart(this.toJSON(),Oe(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(Oe(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 Le(e){if(typeof e=="function")return new ot({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]=Le(r);return new ts({steps:t})}else throw new Error(`Expected a Runnable, function or object.
79
- Instead got an unsupported type.`)}var ml=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]=dl(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,Be.fromAsyncGenerator(s)}},Gp=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,Be.fromAsyncGenerator(s)}},ac=class extends Fe{name;description;schema;constructor(e){const t=kt.from([ot.from(async n=>{let r;if(fs(n))try{r=await Ei(this.schema,n.args)}catch{throw new ks("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 Y0(e,t){const n=t.name??e.getName(),r=t.description??Hr(t.schema);return ll(t.schema)?new ac({name:n,description:r,schema:Y({input:pe()}).transform(s=>s.input),bound:e}):new ac({name:n,description:r,schema:t.schema,bound:e})}var Wp={};U(Wp,{BasePromptValue:()=>xi,ChatPromptValue:()=>yl,ImagePromptValue:()=>Jp,StringPromptValue:()=>gl});var xi=class extends At{},gl=class extends xi{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 he(this.value)]}},yl=class extends xi{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 rl(this.messages)}toChatMessages(){return this.messages}},Jp=class extends xi{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 he({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},L="0123456789abcdef".split(""),X0=[-2147483648,8388608,32768,128],It=[24,16,8,0],ha=[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],Ie=[];function Ft(e,t){t?(Ie[0]=Ie[16]=Ie[1]=Ie[2]=Ie[3]=Ie[4]=Ie[5]=Ie[6]=Ie[7]=Ie[8]=Ie[9]=Ie[10]=Ie[11]=Ie[12]=Ie[13]=Ie[14]=Ie[15]=0,this.blocks=Ie):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}Ft.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]<<It[a++&3];else for(a=this.start;s<i&&a<64;++s)r=e.charCodeAt(s),r<128?o[a>>>2]|=r<<It[a++&3]:r<2048?(o[a>>>2]|=(192|r>>>6)<<It[a++&3],o[a>>>2]|=(128|r&63)<<It[a++&3]):r<55296||r>=57344?(o[a>>>2]|=(224|r>>>12)<<It[a++&3],o[a>>>2]|=(128|r>>>6&63)<<It[a++&3],o[a>>>2]|=(128|r&63)<<It[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++s)&1023),o[a>>>2]|=(240|r>>>18)<<It[a++&3],o[a>>>2]|=(128|r>>>12&63)<<It[a++&3],o[a>>>2]|=(128|r>>>6&63)<<It[a++&3],o[a>>>2]|=(128|r&63)<<It[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}};Ft.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=X0[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()}};Ft.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,g,b,S,w,v;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(v=t&n,l=0;l<64;l+=4)this.first?(this.is224?(b=300032,p=c[0]-1413257819,o=p-150054599<<0,r=p+24177077<<0):(b=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),b=e&t,h=b^e&n^v,g=s&a^~s&i,p=o+d+g+ha[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),S=r&e,h=S^r&t^b,g=i&o^~i&s,p=a+d+g+ha[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),w=n&r,h=w^n&e^S,g=a&i^~a&o,p=s+d+g+ha[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),v=t&n,h=v^t&r^w,g=a&i^~a&o,p=s+d+g+ha[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};Ft.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};Ft.prototype.toString=Ft.prototype.hex;Ft.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};Ft.prototype.array=Ft.prototype.digest;Ft.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 _l=(...e)=>new Ft(!1,!0).update(e.join("")).hex();var Kp={};U(Kp,{sha256:()=>_l});var Zp={};U(Zp,{BaseCache:()=>Yp,InMemoryCache:()=>Xp,defaultHashKeyEncoder:()=>qp,deserializeStoredGeneration:()=>Q0,serializeGeneration:()=>eS});const qp=(...e)=>_l(e.join("_"));function Q0(e){return e.message!==void 0?{text:e.text,message:sl(e.message)}:{text:e.text}}function eS(e){const t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var Yp=class{keyEncoder=qp;makeDefaultKeyEncoder(t){this.keyEncoder=t}};const tS=new Map;var Xp=class Qp extends Yp{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 Qp(tS)}},ef={};U(ef,{encodingForModel:()=>wl,getEncoding:()=>tf});const pa={},nS=new Xs({});async function tf(e){return e in pa||(pa[e]=nS.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new g_(t)).catch(t=>{throw delete pa[e],t})),await pa[e]}async function wl(e){return tf(m_(e))}var nf={};U(nf,{BaseLangChain:()=>bl,BaseLanguageModel:()=>Pi,calculateMaxTokens:()=>aS,getEmbeddingContextSize:()=>rS,getModelContextSize:()=>vl,getModelNameForTiktoken:()=>Ii,isOpenAITool:()=>sS});const Ii=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,rS=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},vl=e=>{switch(Ii(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function sS(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 aS=async({prompt:e,modelName:t})=>{let n;try{n=(await wl(Ii(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 vl(t)-n},iS=()=>!1;var bl=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??iS(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},Pi=class extends bl{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=Xp.global():this.cache=void 0,this.caller=new Xs(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 wl("modelName"in this?Ii(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 gl(e):Array.isArray(e)?new yl(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 Sl(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function Tl(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 El(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Qn(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 Cl(e){return El(e)||Tl(e)||Sl(e)}var rf={};U(rf,{BaseToolkit:()=>oS,DynamicStructuredTool:()=>Ni,DynamicTool:()=>kl,StructuredTool:()=>er,Tool:()=>Al,ToolInputParsingException:()=>ks,isLangChainTool:()=>Cl,isRunnableToolLike:()=>Tl,isStructuredTool:()=>Sl,isStructuredToolParams:()=>El,tool:()=>Ol});var er=class extends bl{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(ft(this.defaultConfig,t));return fs(e)?(n=e.args,r={...r,toolCall:e}):n=e,this.call(n,r)}async call(e,t,n){const r=fs(e)?e.args:e;let s;if(Qn(this.schema))try{s=await Ei(this.schema,r)}catch(p){let f="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(f=`${f}
80
- Details: ${p.message}`),p instanceof Error&&p.constructor.name==="ZodError"&&(f=`${f}
81
-
82
- ${Jc(p)}`),new ks(f,JSON.stringify(e))}else{const p=y_(r,this.schema);if(!p.valid){let f="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(f=`${f}
83
- Details: ${p.errors.map(g=>`${g.keywordLocation}: ${g.error}`).join(`
84
- `)}`),new ks(f,JSON.stringify(e))}s=r}const a=qs(t),o=await Ke.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.
85
- Result: ${JSON.stringify(c)}`);else l=c;let d;fs(e)&&(d=e.id),!d&&xw(a)&&(d=a.toolCall.id);const h=cS({content:l,artifact:u,toolCallId:d,name:this.name,metadata:this.metadata});return await o?.handleToolEnd(h),h}},Al=class extends er{schema=Y({input:pe().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)}},kl=class extends Al{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=qs(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)}},Ni=class extends er{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=qs(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)}},oS=class{getTools(){return this.tools}};function Ol(e,t){const n=ll(t.schema),r=gs(t.schema);if(!t.schema||n||r)return new kl({...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()});Te.runWithConfig(ln(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 Ni({...t,description:a,schema:s,func:async(i,o,c)=>new Promise((l,u)=>{let d;const h=()=>{c?.signal&&d&&c.signal.removeEventListener("abort",d)};c?.signal&&(d=()=>{h(),u(Is(c.signal))},c.signal.addEventListener("abort",d));const p=ne(c,{callbacks:o?.getChild()});Te.runWithConfig(ln(p),async()=>{try{const f=await e(i,p);if(c?.signal?.aborted){h();return}h(),l(f)}catch(f){h(),u(f)}})})})}function cS(e){const{content:t,artifact:n,toolCallId:r,metadata:s}=e;return r&&!Xc(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:lS(t),artifact:n,tool_call_id:r,name:e.name,metadata:s}):t}function lS(e){try{return JSON.stringify(e,null,2)??""}catch{return`${e}`}}var sf=typeof globalThis=="object"&&globalThis&&globalThis.Object===Object&&globalThis,uS=typeof self=="object"&&self&&self.Object===Object&&self,dn=sf||uS||Function("return this")(),Jr=dn.Symbol,af=Object.prototype,dS=af.hasOwnProperty,hS=af.toString,is=Jr?Jr.toStringTag:void 0;function pS(e){var t=dS.call(e,is),n=e[is];try{e[is]=void 0;var r=!0}catch{}var s=hS.call(e);return r&&(t?e[is]=n:delete e[is]),s}var fS=Object.prototype,mS=fS.toString;function gS(e){return mS.call(e)}var yS="[object Null]",_S="[object Undefined]",ed=Jr?Jr.toStringTag:void 0;function Qs(e){return e==null?e===void 0?_S:yS:ed&&ed in Object(e)?pS(e):gS(e)}function $s(e){return e!=null&&typeof e=="object"}var Xa=Array.isArray;function of(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var wS="[object AsyncFunction]",vS="[object Function]",bS="[object GeneratorFunction]",SS="[object Proxy]";function cf(e){if(!of(e))return!1;var t=Qs(e);return t==vS||t==bS||t==wS||t==SS}var po=dn["__core-js_shared__"],td=(function(){var e=/[^.]+$/.exec(po&&po.keys&&po.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function TS(e){return!!td&&td in e}var ES=Function.prototype,CS=ES.toString;function tr(e){if(e!=null){try{return CS.call(e)}catch{}try{return e+""}catch{}}return""}var AS=/[\\^$.*+?()[\]{}|]/g,kS=/^\[object .+?Constructor\]$/,OS=Function.prototype,xS=Object.prototype,IS=OS.toString,PS=xS.hasOwnProperty,NS=RegExp("^"+IS.call(PS).replace(AS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function MS(e){if(!of(e)||TS(e))return!1;var t=cf(e)?NS:kS;return t.test(tr(e))}function RS(e,t){return e?.[t]}function ns(e,t){var n=RS(e,t);return MS(n)?n:void 0}var ic=ns(dn,"WeakMap"),$S=9007199254740991,LS=/^(?:0|[1-9]\d*)$/;function jS(e,t){var n=typeof e;return t=t??$S,!!t&&(n=="number"||n!="symbol"&&LS.test(e))&&e>-1&&e%1==0&&e<t}function lf(e,t){return e===t||e!==e&&t!==t}var DS=9007199254740991;function uf(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=DS}function FS(e){return e!=null&&uf(e.length)&&!cf(e)}var US=Object.prototype;function BS(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||US;return e===n}function zS(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}var HS="[object Arguments]";function nd(e){return $s(e)&&Qs(e)==HS}var df=Object.prototype,VS=df.hasOwnProperty,GS=df.propertyIsEnumerable,WS=nd((function(){return arguments})())?nd:function(e){return $s(e)&&VS.call(e,"callee")&&!GS.call(e,"callee")};function JS(){return!1}var hf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,rd=hf&&typeof module=="object"&&module&&!module.nodeType&&module,KS=rd&&rd.exports===hf,sd=KS?dn.Buffer:void 0,ZS=sd?sd.isBuffer:void 0,oc=ZS||JS,qS="[object Arguments]",YS="[object Array]",XS="[object Boolean]",QS="[object Date]",eT="[object Error]",tT="[object Function]",nT="[object Map]",rT="[object Number]",sT="[object Object]",aT="[object RegExp]",iT="[object Set]",oT="[object String]",cT="[object WeakMap]",lT="[object ArrayBuffer]",uT="[object DataView]",dT="[object Float32Array]",hT="[object Float64Array]",pT="[object Int8Array]",fT="[object Int16Array]",mT="[object Int32Array]",gT="[object Uint8Array]",yT="[object Uint8ClampedArray]",_T="[object Uint16Array]",wT="[object Uint32Array]",ue={};ue[dT]=ue[hT]=ue[pT]=ue[fT]=ue[mT]=ue[gT]=ue[yT]=ue[_T]=ue[wT]=!0;ue[qS]=ue[YS]=ue[lT]=ue[XS]=ue[uT]=ue[QS]=ue[eT]=ue[tT]=ue[nT]=ue[rT]=ue[sT]=ue[aT]=ue[iT]=ue[oT]=ue[cT]=!1;function vT(e){return $s(e)&&uf(e.length)&&!!ue[Qs(e)]}function bT(e){return function(t){return e(t)}}var pf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ys=pf&&typeof module=="object"&&module&&!module.nodeType&&module,ST=ys&&ys.exports===pf,fo=ST&&sf.process,ad=(function(){try{var e=ys&&ys.require&&ys.require("util").types;return e||fo&&fo.binding&&fo.binding("util")}catch{}})(),id=ad&&ad.isTypedArray,ff=id?bT(id):vT,TT=Object.prototype,ET=TT.hasOwnProperty;function CT(e,t){var n=Xa(e),r=!n&&WS(e),s=!n&&!r&&oc(e),a=!n&&!r&&!s&&ff(e),i=n||r||s||a,o=i?zS(e.length,String):[],c=o.length;for(var l in e)ET.call(e,l)&&!(i&&(l=="length"||s&&(l=="offset"||l=="parent")||a&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||jS(l,c)))&&o.push(l);return o}function AT(e,t){return function(n){return e(t(n))}}var kT=AT(Object.keys,Object),OT=Object.prototype,xT=OT.hasOwnProperty;function IT(e){if(!BS(e))return kT(e);var t=[];for(var n in Object(e))xT.call(e,n)&&n!="constructor"&&t.push(n);return t}function PT(e){return FS(e)?CT(e):IT(e)}var Ls=ns(Object,"create");function NT(){this.__data__=Ls?Ls(null):{},this.size=0}function MT(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var RT="__lodash_hash_undefined__",$T=Object.prototype,LT=$T.hasOwnProperty;function jT(e){var t=this.__data__;if(Ls){var n=t[e];return n===RT?void 0:n}return LT.call(t,e)?t[e]:void 0}var DT=Object.prototype,FT=DT.hasOwnProperty;function UT(e){var t=this.__data__;return Ls?t[e]!==void 0:FT.call(t,e)}var BT="__lodash_hash_undefined__";function zT(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=Ls&&t===void 0?BT:t,this}function Kn(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])}}Kn.prototype.clear=NT;Kn.prototype.delete=MT;Kn.prototype.get=jT;Kn.prototype.has=UT;Kn.prototype.set=zT;function HT(){this.__data__=[],this.size=0}function Mi(e,t){for(var n=e.length;n--;)if(lf(e[n][0],t))return n;return-1}var VT=Array.prototype,GT=VT.splice;function WT(e){var t=this.__data__,n=Mi(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():GT.call(t,n,1),--this.size,!0}function JT(e){var t=this.__data__,n=Mi(t,e);return n<0?void 0:t[n][1]}function KT(e){return Mi(this.__data__,e)>-1}function ZT(e,t){var n=this.__data__,r=Mi(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}function hn(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])}}hn.prototype.clear=HT;hn.prototype.delete=WT;hn.prototype.get=JT;hn.prototype.has=KT;hn.prototype.set=ZT;var js=ns(dn,"Map");function qT(){this.size=0,this.__data__={hash:new Kn,map:new(js||hn),string:new Kn}}function YT(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Ri(e,t){var n=e.__data__;return YT(t)?n[typeof t=="string"?"string":"hash"]:n.map}function XT(e){var t=Ri(this,e).delete(e);return this.size-=t?1:0,t}function QT(e){return Ri(this,e).get(e)}function eE(e){return Ri(this,e).has(e)}function tE(e,t){var n=Ri(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}function nr(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])}}nr.prototype.clear=qT;nr.prototype.delete=XT;nr.prototype.get=QT;nr.prototype.has=eE;nr.prototype.set=tE;function nE(e,t){for(var n=-1,r=t.length,s=e.length;++n<r;)e[s+n]=t[n];return e}function rE(){this.__data__=new hn,this.size=0}function sE(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}function aE(e){return this.__data__.get(e)}function iE(e){return this.__data__.has(e)}var oE=200;function cE(e,t){var n=this.__data__;if(n instanceof hn){var r=n.__data__;if(!js||r.length<oE-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new nr(r)}return n.set(e,t),this.size=n.size,this}function Tn(e){var t=this.__data__=new hn(e);this.size=t.size}Tn.prototype.clear=rE;Tn.prototype.delete=sE;Tn.prototype.get=aE;Tn.prototype.has=iE;Tn.prototype.set=cE;function lE(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 uE(){return[]}var dE=Object.prototype,hE=dE.propertyIsEnumerable,od=Object.getOwnPropertySymbols,pE=od?function(e){return e==null?[]:(e=Object(e),lE(od(e),function(t){return hE.call(e,t)}))}:uE;function fE(e,t,n){var r=t(e);return Xa(e)?r:nE(r,n(e))}function cd(e){return fE(e,PT,pE)}var cc=ns(dn,"DataView"),lc=ns(dn,"Promise"),uc=ns(dn,"Set"),ld="[object Map]",mE="[object Object]",ud="[object Promise]",dd="[object Set]",hd="[object WeakMap]",pd="[object DataView]",gE=tr(cc),yE=tr(js),_E=tr(lc),wE=tr(uc),vE=tr(ic),gn=Qs;(cc&&gn(new cc(new ArrayBuffer(1)))!=pd||js&&gn(new js)!=ld||lc&&gn(lc.resolve())!=ud||uc&&gn(new uc)!=dd||ic&&gn(new ic)!=hd)&&(gn=function(e){var t=Qs(e),n=t==mE?e.constructor:void 0,r=n?tr(n):"";if(r)switch(r){case gE:return pd;case yE:return ld;case _E:return ud;case wE:return dd;case vE:return hd}return t});var fd=dn.Uint8Array,bE="__lodash_hash_undefined__";function SE(e){return this.__data__.set(e,bE),this}function TE(e){return this.__data__.has(e)}function Qa(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new nr;++t<n;)this.add(e[t])}Qa.prototype.add=Qa.prototype.push=SE;Qa.prototype.has=TE;function EE(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 CE(e,t){return e.has(t)}var AE=1,kE=2;function mf(e,t,n,r,s,a){var i=n&AE,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&kE?new Qa:void 0;for(a.set(e,t),a.set(t,e);++d<o;){var f=e[d],g=t[d];if(r)var b=i?r(g,f,d,t,e,a):r(f,g,d,e,t,a);if(b!==void 0){if(b)continue;h=!1;break}if(p){if(!EE(t,function(S,w){if(!CE(p,w)&&(f===S||s(f,S,n,r,a)))return p.push(w)})){h=!1;break}}else if(!(f===g||s(f,g,n,r,a))){h=!1;break}}return a.delete(e),a.delete(t),h}function OE(e){var t=-1,n=Array(e.size);return e.forEach(function(r,s){n[++t]=[s,r]}),n}function xE(e){var t=-1,n=Array(e.size);return e.forEach(function(r){n[++t]=r}),n}var IE=1,PE=2,NE="[object Boolean]",ME="[object Date]",RE="[object Error]",$E="[object Map]",LE="[object Number]",jE="[object RegExp]",DE="[object Set]",FE="[object String]",UE="[object Symbol]",BE="[object ArrayBuffer]",zE="[object DataView]",md=Jr?Jr.prototype:void 0,mo=md?md.valueOf:void 0;function HE(e,t,n,r,s,a,i){switch(n){case zE:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case BE:return!(e.byteLength!=t.byteLength||!a(new fd(e),new fd(t)));case NE:case ME:case LE:return lf(+e,+t);case RE:return e.name==t.name&&e.message==t.message;case jE:case FE:return e==t+"";case $E:var o=OE;case DE:var c=r&IE;if(o||(o=xE),e.size!=t.size&&!c)return!1;var l=i.get(e);if(l)return l==t;r|=PE,i.set(e,t);var u=mf(o(e),o(t),r,s,a,i);return i.delete(e),u;case UE:if(mo)return mo.call(e)==mo.call(t)}return!1}var VE=1,GE=Object.prototype,WE=GE.hasOwnProperty;function JE(e,t,n,r,s,a){var i=n&VE,o=cd(e),c=o.length,l=cd(t),u=l.length;if(c!=u&&!i)return!1;for(var d=c;d--;){var h=o[d];if(!(i?h in t:WE.call(t,h)))return!1}var p=a.get(e),f=a.get(t);if(p&&f)return p==t&&f==e;var g=!0;a.set(e,t),a.set(t,e);for(var b=i;++d<c;){h=o[d];var S=e[h],w=t[h];if(r)var v=i?r(w,S,h,t,e,a):r(S,w,h,e,t,a);if(!(v===void 0?S===w||s(S,w,n,r,a):v)){g=!1;break}b||(b=h=="constructor")}if(g&&!b){var T=e.constructor,k=t.constructor;T!=k&&"constructor"in e&&"constructor"in t&&!(typeof T=="function"&&T instanceof T&&typeof k=="function"&&k instanceof k)&&(g=!1)}return a.delete(e),a.delete(t),g}var KE=1,gd="[object Arguments]",yd="[object Array]",fa="[object Object]",ZE=Object.prototype,_d=ZE.hasOwnProperty;function qE(e,t,n,r,s,a){var i=Xa(e),o=Xa(t),c=i?yd:gn(e),l=o?yd:gn(t);c=c==gd?fa:c,l=l==gd?fa:l;var u=c==fa,d=l==fa,h=c==l;if(h&&oc(e)){if(!oc(t))return!1;i=!0,u=!1}if(h&&!u)return a||(a=new Tn),i||ff(e)?mf(e,t,n,r,s,a):HE(e,t,c,n,r,s,a);if(!(n&KE)){var p=u&&_d.call(e,"__wrapped__"),f=d&&_d.call(t,"__wrapped__");if(p||f){var g=p?e.value():e,b=f?t.value():t;return a||(a=new Tn),s(g,b,n,r,a)}}return h?(a||(a=new Tn),JE(e,t,n,r,s,a)):!1}function gf(e,t,n,r,s){return e===t?!0:e==null||t==null||!$s(e)&&!$s(t)?e!==e&&t!==t:qE(e,t,n,r,gf,s)}function YE(e,t){return gf(e,t)}class XE{capture(){}shutdown(){return Promise.resolve()}}const QE=Symbol("Let zodToJsonSchema decide on which parser to use"),eC={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"},tC=e=>({...eC,...e}),nC=e=>{const t=tC(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 yf(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function ae(e,t,n,r,s){e[t]=n,yf(e,t,r,s)}const _f=(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 ct(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?_f(t,e.currentPath):t.join("/")}}function rC(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==M.ZodAny&&(n.items=te(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 sC(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 aC(){return{type:"boolean"}}function wf(e,t){return te(e.type._def,t)}const iC=(e,t)=>te(e.innerType._def,t);function vf(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,a)=>vf(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 oC(e,t)}}const oC=(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 cC(e,t){return{...te(e.innerType._def,t),default:e.defaultValue()}}function lC(e,t){return t.effectStrategy==="input"?te(e.schema._def,t):ct(t)}function uC(e){return{type:"string",enum:Array.from(e.values)}}const dC=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function hC(e,t){const n=[te(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),te(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(dC(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 pC(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 go;const Pt={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:()=>(go===void 0&&(go=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),go),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 bf(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":Nt(n,"email",r.message,t);break;case"format:idn-email":Nt(n,"idn-email",r.message,t);break;case"pattern:zod":Ge(n,Pt.email,r.message,t);break}break;case"url":Nt(n,"uri",r.message,t);break;case"uuid":Nt(n,"uuid",r.message,t);break;case"regex":Ge(n,r.regex,r.message,t);break;case"cuid":Ge(n,Pt.cuid,r.message,t);break;case"cuid2":Ge(n,Pt.cuid2,r.message,t);break;case"startsWith":Ge(n,RegExp(`^${yo(r.value,t)}`),r.message,t);break;case"endsWith":Ge(n,RegExp(`${yo(r.value,t)}$`),r.message,t);break;case"datetime":Nt(n,"date-time",r.message,t);break;case"date":Nt(n,"date",r.message,t);break;case"time":Nt(n,"time",r.message,t);break;case"duration":Nt(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":{Ge(n,RegExp(yo(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&Nt(n,"ipv4",r.message,t),r.version!=="v4"&&Nt(n,"ipv6",r.message,t);break}case"base64url":Ge(n,Pt.base64url,r.message,t);break;case"jwt":Ge(n,Pt.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&Ge(n,Pt.ipv4Cidr,r.message,t),r.version!=="v4"&&Ge(n,Pt.ipv6Cidr,r.message,t);break}case"emoji":Ge(n,Pt.emoji(),r.message,t);break;case"ulid":{Ge(n,Pt.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Nt(n,"binary",r.message,t);break}case"contentEncoding:base64":{ae(n,"contentEncoding","base64",r.message,t);break}case"pattern:zod":{Ge(n,Pt.base64,r.message,t);break}}break}case"nanoid":Ge(n,Pt.nanoid,r.message,t)}return n}function yo(e,t){return t.patternStrategy==="escape"?mC(e):e}const fC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function mC(e){let t="";for(let n=0;n<e.length;n++)fC.has(e[n])||(t+="\\"),t+=e[n];return t}function Nt(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 Ge(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:wd(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ae(e,"pattern",wd(t,r),n,r)}function wd(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
86
- ]))`;continue}else if(r[c]==="$"){s+=`($|(?=[\r
87
- ]))`;continue}}if(n.s&&r[c]==="."){s+=i?`${r[c]}\r
88
- `:`[${r[c]}\r
89
- ]`;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 Sf(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===M.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,s)=>({...r,[s]:te(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??ct(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:te(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===M.ZodString&&e.keyType._def.checks?.length){const{type:r,...s}=bf(e.keyType._def,t);return{...n,propertyNames:s}}else{if(e.keyType?._def.typeName===M.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===M.ZodBranded&&e.keyType._def.type._def.typeName===M.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...s}=wf(e.keyType._def,t);return{...n,propertyNames:s}}}return n}function gC(e,t){if(t.mapStrategy==="record")return Sf(e,t);const n=te(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ct(t),r=te(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ct(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function yC(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 _C(e){return e.target==="openAi"?void 0:{not:ct({...e,currentPath:[...e.currentPath,"not"]})}}function wC(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const ei={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function vC(e,t){if(t.target==="openApi3")return vd(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in ei&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,a)=>{const i=ei[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":if(a._def.value===null)return[...s,"null"];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 vd(e,t)}const vd=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,s)=>te(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 bC(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:ei[e.innerType._def.typeName],nullable:!0}:{type:[ei[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const r=te(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=te(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function SC(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",yf(n,"type",r.message,t);break;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 TC(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=CC(c);l&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const u=te(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=EC(e,t);return i!==void 0&&(r.additionalProperties=i),r}function EC(e,t){if(e.catchall._def.typeName!=="ZodNever")return te(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 CC(e){try{return e.isOptional()}catch{return!0}}const AC=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return te(e.innerType._def,t);const n=te(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:ct(t)},n]}:ct(t)},kC=(e,t)=>{if(t.pipeStrategy==="input")return te(e.in._def,t);if(t.pipeStrategy==="output")return te(e.out._def,t);const n=te(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=te(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}};function OC(e,t){return te(e.type._def,t)}function xC(e,t){const r={type:"array",uniqueItems:!0,items:te(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ae(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ae(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function IC(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>te(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:te(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>te(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function PC(e){return{not:ct(e)}}function NC(e){return ct(e)}const MC=(e,t)=>te(e.innerType._def,t),RC=(e,t,n)=>{switch(t){case M.ZodString:return bf(e,n);case M.ZodNumber:return SC(e,n);case M.ZodObject:return TC(e,n);case M.ZodBigInt:return sC(e,n);case M.ZodBoolean:return aC();case M.ZodDate:return vf(e,n);case M.ZodUndefined:return PC(n);case M.ZodNull:return wC(n);case M.ZodArray:return rC(e,n);case M.ZodUnion:case M.ZodDiscriminatedUnion:return vC(e,n);case M.ZodIntersection:return hC(e,n);case M.ZodTuple:return IC(e,n);case M.ZodRecord:return Sf(e,n);case M.ZodLiteral:return pC(e,n);case M.ZodEnum:return uC(e);case M.ZodNativeEnum:return yC(e);case M.ZodNullable:return bC(e,n);case M.ZodOptional:return AC(e,n);case M.ZodMap:return gC(e,n);case M.ZodSet:return xC(e,n);case M.ZodLazy:return()=>e.getter()._def;case M.ZodPromise:return OC(e,n);case M.ZodNaN:case M.ZodNever:return _C(n);case M.ZodEffects:return lC(e,n);case M.ZodAny:return ct(n);case M.ZodUnknown:return NC(n);case M.ZodDefault:return cC(e,n);case M.ZodBranded:return wf(e,n);case M.ZodReadonly:return MC(e,n);case M.ZodCatch:return iC(e,n);case M.ZodPipeline:return kC(e,n);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(r=>{})()}};function te(e,t,n=!1){const r=t.seen.get(e);if(t.override){const o=t.override?.(e,t,r,n);if(o!==QE)return o}if(r&&!n){const o=$C(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=RC(e,e.typeName,t),i=typeof a=="function"?te(a(),t):a;if(i&&LC(e,t,i),t.postProcess){const o=t.postProcess(i,e,t);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const $C=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:_f(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`),ct(t)):t.$refStrategy==="seen"?ct(t):void 0}},LC=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),ba=(e,t)=>{const n=nC(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((o,[c,l])=>({...o,[c]:te(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??ct(n)}),{}):void 0;const s=typeof t=="string"?t:t?.name,a=te(e._def,n,!1)??ct(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 jC=Object.defineProperty,Tf=(e,t)=>{for(var n in t)jC(e,n,{get:t[n],enumerable:!0})};const ti=(e,t)=>{const n=[...new Set(t?.map(s=>{if(typeof s=="string")return s;const a=new s({});if(!("getType"in a)||typeof a.getType!="function")throw new Error("Invalid type provided.");return a.getType()}))],r=e.getType();return n.some(s=>s===r)};function Ef(e,t){return Array.isArray(e)?bd(e,t):ot.from(n=>bd(n,e))}function bd(e,t={}){const{includeNames:n,excludeNames:r,includeTypes:s,excludeTypes:a,includeIds:i,excludeIds:o}=t,c=[];for(const l of e)if(!(r&&l.name&&r.includes(l.name))){{if(a&&ti(l,a))continue;if(o&&l.id&&o.includes(l.id))continue}s||i||n?(n&&l.name&&n.some(u=>u===l.name)||s&&ti(l,s)||i&&l.id&&i.some(u=>u===l.id))&&c.push(l):c.push(l)}return c}function DC(e){return Array.isArray(e)?Sd(e):ot.from(Sd)}function Sd(e){if(!e.length)return[];const t=[];for(const n of e){const r=n,s=t.pop();if(!s)t.push(r);else if(r.getType()==="tool"||r.getType()!==s.getType())t.push(s,r);else{const a=Ga(s),i=Ga(r),o=a.concat(i);typeof a.content=="string"&&typeof i.content=="string"&&(o.content=`${a.content}
90
- ${i.content}`),t.push(UC(o))}}return t}function xl(e,t){if(Array.isArray(e)){const n=e;if(!t)throw new Error("Options parameter is required when providing messages.");return Td(n,t)}else{const n=e;return ot.from(r=>Td(r,n)).withConfig({runName:"trim_messages"})}}async function Td(e,t){const{maxTokens:n,tokenCounter:r,strategy:s="last",allowPartial:a=!1,endOn:i,startOn:o,includeSystem:c=!1,textSplitter:l}=t;if(o&&s==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&s==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let u;"getNumTokens"in r?u=async h=>(await Promise.all(h.map(f=>r.getNumTokens(f.content)))).reduce((f,g)=>f+g,0):u=async h=>r(h);let d=Af;if(l&&("splitText"in l?d=l.splitText:d=async h=>l(h)),s==="first")return Cf(e,{maxTokens:n,tokenCounter:u,textSplitter:d,partialStrategy:a?"first":void 0,endOn:i});if(s==="last")return FC(e,{maxTokens:n,tokenCounter:u,textSplitter:d,allowPartial:a,includeSystem:c,startOn:o,endOn:i});throw new Error(`Unrecognized strategy: '${s}'. Must be one of 'first' or 'last'.`)}async function Cf(e,t){const{maxTokens:n,tokenCounter:r,textSplitter:s,partialStrategy:a,endOn:i}=t;let o=[...e],c=0;for(let l=0;l<o.length;l+=1){const u=l>0?o.slice(0,-l):o;if(await r(u)<=n){c=o.length-l;break}}if(c<o.length&&a){let l=!1;if(Array.isArray(o[c].content)){const u=o[c];if(typeof u.content=="string")throw new Error("Expected content to be an array.");const d=u.content.length,h=a==="last"?[...u.content].reverse():u.content;for(let p=1;p<=d;p+=1){const f=a==="first"?h.slice(0,p):h.slice(-p),g=Object.fromEntries(Object.entries(u).filter(([w])=>w!=="type"&&!w.startsWith("lc_"))),b=Il(u.getType(),{...g,content:f}),S=[...o.slice(0,c),b];if(await r(S)<=n)o=S,c+=1,l=!0;else break}l&&a==="last"&&(u.content=[...h].reverse())}if(!l){const u=o[c];let d;if(Array.isArray(u.content)&&u.content.some(h=>typeof h=="string"||h.type==="text")?d=u.content.find(p=>p.type==="text"&&p.text)?.text:typeof u.content=="string"&&(d=u.content),d){const h=await s(d),p=h.length;a==="last"&&h.reverse();for(let f=0;f<p-1;f+=1)if(h.pop(),u.content=h.join(""),await r([...o.slice(0,c),u])<=n){a==="last"&&(u.content=[...h].reverse().join("")),o=[...o.slice(0,c),u],c+=1;break}}}}if(i){const l=Array.isArray(i)?i:[i];for(;c>0&&!ti(o[c-1],l);)c-=1}return o.slice(0,c)}async function FC(e,t){const{allowPartial:n=!1,includeSystem:r=!1,endOn:s,startOn:a,...i}=t;let o=e.map(u=>{const d=Object.fromEntries(Object.entries(u).filter(([h])=>h!=="type"&&!h.startsWith("lc_")));return Il(u.getType(),d,As(u))});if(s){const u=Array.isArray(s)?s:[s];for(;o.length>0&&!ti(o[o.length-1],u);)o=o.slice(0,-1)}const c=r&&o[0]?.getType()==="system";let l=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return l=await Cf(l,{...i,partialStrategy:n?"last":void 0,endOn:a}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}const Ed={human:{message:he,messageChunk:Zs},ai:{message:D,messageChunk:yt},system:{message:Se,messageChunk:Jn},developer:{message:Se,messageChunk:Jn},tool:{message:X,messageChunk:Ks},function:{message:vi,messageChunk:bi},generic:{message:Xn,messageChunk:wi},remove:{message:Sn,messageChunk:Sn}};function Il(e,t,n){let r,s;switch(e){case"human":n?r=new Zs(t):s=new he(t);break;case"ai":if(n){let a={...t};"tool_calls"in a&&(a={...a,tool_call_chunks:a.tool_calls?.map(i=>({...i,type:"tool_call_chunk",index:void 0,args:JSON.stringify(i.args)}))}),r=new yt(a)}else s=new D(t);break;case"system":n?r=new Jn(t):s=new Se(t);break;case"developer":n?r=new Jn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):s=new Se({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in t)n?r=new Ks(t):s=new X(t);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(n)r=new bi(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");s=new vi(t)}break;case"generic":if("role"in t)n?r=new wi(t):s=new Xn(t);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${e}`)}if(n&&r)return r;if(s)return s;throw new Error(`Unrecognized message type ${e}`)}function UC(e){const t=e.getType();let n;const r=Object.fromEntries(Object.entries(e).filter(([s])=>!["type","tool_call_chunks"].includes(s)&&!s.startsWith("lc_")));if(t in Ed&&(n=Il(t,r)),!n)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(Ed)}`);return n}function Af(e){const t=e.split(`
91
- `);return Promise.resolve([...t.slice(0,-1).map(n=>`${n}
92
- `),t[t.length-1]])}const BC=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],zC=["image","video","audio","text-plain","file"],HC=["text","reasoning",...BC,...zC];var kf={};U(kf,{AIMessage:()=>D,AIMessageChunk:()=>yt,BaseMessage:()=>rt,BaseMessageChunk:()=>Nn,ChatMessage:()=>Xn,ChatMessageChunk:()=>wi,FunctionMessage:()=>vi,FunctionMessageChunk:()=>bi,HumanMessage:()=>he,HumanMessageChunk:()=>Zs,KNOWN_BLOCK_TYPES:()=>HC,RemoveMessage:()=>Sn,SystemMessage:()=>Se,SystemMessageChunk:()=>Jn,ToolMessage:()=>X,ToolMessageChunk:()=>Ks,_isMessageFieldWithRole:()=>Sh,_mergeDicts:()=>Ue,_mergeLists:()=>Js,_mergeObj:()=>bh,_mergeStatus:()=>vh,coerceMessageLikeToMessage:()=>Gt,convertToChunk:()=>Ga,convertToOpenAIImageBlock:()=>gh,convertToProviderContentBlock:()=>dw,defaultTextSplitter:()=>Af,defaultToolCallParser:()=>Qc,filterMessages:()=>Ef,getBufferString:()=>rl,iife:()=>Ww,isAIMessage:()=>nl,isAIMessageChunk:()=>zo,isBase64ContentBlock:()=>Zc,isBaseMessage:()=>Pe,isBaseMessageChunk:()=>As,isChatMessage:()=>Dw,isChatMessageChunk:()=>Fw,isDataContentBlock:()=>On,isDirectToolOutput:()=>Xc,isFunctionMessage:()=>Uw,isFunctionMessageChunk:()=>Bw,isHumanMessage:()=>zw,isHumanMessageChunk:()=>Hw,isIDContentBlock:()=>mh,isMessage:()=>wh,isOpenAIToolCallArray:()=>Ow,isPlainTextContentBlock:()=>lw,isSystemMessage:()=>Vw,isSystemMessageChunk:()=>Gw,isToolMessage:()=>el,isToolMessageChunk:()=>Eh,isURLContentBlock:()=>Kc,mapChatMessagesToStoredMessages:()=>Yw,mapStoredMessageToChatMessage:()=>sl,mapStoredMessagesToChatMessages:()=>qw,mergeContent:()=>Yn,mergeMessageRuns:()=>DC,mergeResponseMetadata:()=>Ah,mergeUsageMetadata:()=>Oh,parseBase64DataUrl:()=>Uo,parseMimeType:()=>uw,trimMessages:()=>xl});var Ds=class extends J{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){const n=K(t);return this.func&&await this.func(e,n),this._callWithConfig(r=>Promise.resolve(r),e,n)}async*transform(e,t){const n=K(t);let r,s=!0;for await(const a of this._transformStreamWithConfig(e,i=>i,n))if(yield a,s)if(r===void 0)r=a;else try{r=In(r,a)}catch{r=void 0,s=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new ml(new ts({steps:e}))}};const VC=e=>e();function _o(e){const t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var Of={};U(Of,{BaseChatModel:()=>rr,SimpleChatModel:()=>GC});function wo(e){const t=[];for(const n of e){let r=n;if(Array.isArray(n.content))for(let s=0;s<n.content.length;s++){const a=n.content[s];(Kc(a)||Zc(a))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,s),gh(a),...n.content.slice(s+1)]}))}t.push(r)}return t}var rr=class Ln extends Pi{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(t){super(t),this.outputVersion=VC(()=>{const n=t.outputVersion??rn("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}_separateRunnableConfigFromCallOptionsCompat(t){const[n,r]=super._separateRunnableConfigFromCallOptions(t);return r.signal=n.signal,[n,r]}async invoke(t,n){const r=Ln._convertInputToPromptValue(t);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(t,n,r){throw new Error("Not implemented.")}async*_streamIterator(t,n){if(this._streamResponseChunks===Ln.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,n);else{const s=Ln._convertInputToPromptValue(t).toChatMessages(),[a,i]=this._separateRunnableConfigFromCallOptionsCompat(n),o={...a.metadata,...this.getLsParams(i)},c=await Ke.configure(a.callbacks,this.callbacks,a.tags,this.tags,o,this.metadata,{verbose:this.verbose}),l={options:i,invocation_params:this?.invocationParams(i),batch_size:1},u=i.outputVersion??this.outputVersion,d=await c?.handleChatModelStart(this.toJSON(),[wo(s)],a.runId,void 0,l,void 0,void 0,a.runName);let h,p;try{for await(const f of this._streamResponseChunks(s,i,d?.[0])){if(f.message.id==null){const g=d?.at(0)?.runId;g!=null&&f.message._updateId(`run-${g}`)}f.message.response_metadata={...f.generationInfo,...f.message.response_metadata},u==="v1"?yield _o(f.message):yield f.message,h?h=h.concat(f):h=f,zo(f.message)&&f.message.usage_metadata!==void 0&&(p={tokenUsage:{promptTokens:f.message.usage_metadata.input_tokens,completionTokens:f.message.usage_metadata.output_tokens,totalTokens:f.message.usage_metadata.total_tokens}})}}catch(f){throw await Promise.all((d??[]).map(g=>g?.handleLLMError(f))),f}await Promise.all((d??[]).map(f=>f?.handleLLMEnd({generations:[[h]],llmOutput:p})))}}getLsParams(t){const n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:t.stop,ls_provider:n}}async _generateUncached(t,n,r,s){const a=t.map(h=>h.map(Gt));let i;if(s!==void 0&&s.length===a.length)i=s;else{const h={...r.metadata,...this.getLsParams(n)},p=await Ke.configure(r.callbacks,this.callbacks,r.tags,this.tags,h,this.metadata,{verbose:this.verbose}),f={options:n,invocation_params:this?.invocationParams(n),batch_size:1};i=await p?.handleChatModelStart(this.toJSON(),a.map(wo),r.runId,void 0,f,void 0,void 0,r.runName)}const o=n.outputVersion??this.outputVersion,c=[],l=[];if(!!i?.[0].handlers.find(al)&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==Ln.prototype._streamResponseChunks)try{const h=await this._streamResponseChunks(a[0],n,i?.[0]);let p,f;for await(const g of h){if(g.message.id==null){const b=i?.at(0)?.runId;b!=null&&g.message._updateId(`run-${b}`)}p===void 0?p=g:p=In(p,g),zo(g.message)&&g.message.usage_metadata!==void 0&&(f={tokenUsage:{promptTokens:g.message.usage_metadata.input_tokens,completionTokens:g.message.usage_metadata.output_tokens,totalTokens:g.message.usage_metadata.total_tokens}})}if(p===void 0)throw new Error("Received empty response from chat model call.");c.push([p]),await i?.[0].handleLLMEnd({generations:c,llmOutput:f})}catch(h){throw await i?.[0].handleLLMError(h),h}else{const h=await Promise.allSettled(a.map(async(p,f)=>{const g=await this._generate(p,{...n,promptIndex:f},i?.[f]);if(o==="v1")for(const b of g.generations)b.message=_o(b.message);return g}));await Promise.all(h.map(async(p,f)=>{if(p.status==="fulfilled"){const g=p.value;for(const b of g.generations){if(b.message.id==null){const S=i?.at(0)?.runId;S!=null&&b.message._updateId(`run-${S}`)}b.message.response_metadata={...b.generationInfo,...b.message.response_metadata}}return g.generations.length===1&&(g.generations[0].message.response_metadata={...g.llmOutput,...g.generations[0].message.response_metadata}),c[f]=g.generations,l[f]=g.llmOutput,i?.[f]?.handleLLMEnd({generations:[g.generations],llmOutput:g.llmOutput})}else return await i?.[f]?.handleLLMError(p.reason),Promise.reject(p.reason)}))}const d={generations:c,llmOutput:l.length?this._combineLLMOutput?.(...l):void 0};return Object.defineProperty(d,Ms,{value:i?{runIds:i?.map(h=>h.runId)}:void 0,configurable:!0}),d}async _generateCached({messages:t,cache:n,llmStringKey:r,parsedOptions:s,handledOptions:a}){const i=t.map(S=>S.map(Gt)),o={...a.metadata,...this.getLsParams(s)},c=await Ke.configure(a.callbacks,this.callbacks,a.tags,this.tags,o,this.metadata,{verbose:this.verbose}),l={options:s,invocation_params:this?.invocationParams(s),batch_size:1},u=await c?.handleChatModelStart(this.toJSON(),i.map(wo),a.runId,void 0,l,void 0,void 0,a.runName),d=[],p=(await Promise.allSettled(i.map(async(S,w)=>{const v=Ln._convertInputToPromptValue(S).toString(),T=await n.lookup(v,r);return T==null&&d.push(w),T}))).map((S,w)=>({result:S,runManager:u?.[w]})).filter(({result:S})=>S.status==="fulfilled"&&S.value!=null||S.status==="rejected"),f=s.outputVersion??this.outputVersion,g=[];await Promise.all(p.map(async({result:S,runManager:w},v)=>{if(S.status==="fulfilled"){const T=S.value;return g[v]=T.map(k=>("message"in k&&Pe(k.message)&&nl(k.message)&&(k.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},f==="v1"&&(k.message=_o(k.message))),k.generationInfo={...k.generationInfo,tokenUsage:{}},k)),T.length&&await w?.handleLLMNewToken(T[0].text),w?.handleLLMEnd({generations:[T]},void 0,void 0,void 0,{cached:!0})}else return await w?.handleLLMError(S.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(S.reason)}));const b={generations:g,missingPromptIndices:d,startedRunManagers:u};return Object.defineProperty(b,Ms,{value:u?{runIds:u?.map(S=>S.runId)}:void 0,configurable:!0}),b}async generate(t,n,r){let s;Array.isArray(n)?s={stop:n}:s=n;const a=t.map(f=>f.map(Gt)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(s);if(i.callbacks=i.callbacks??r,!this.cache)return this._generateUncached(a,o,i);const{cache:c}=this,l=this._getSerializedCacheKeyParametersForCall(o),{generations:u,missingPromptIndices:d,startedRunManagers:h}=await this._generateCached({messages:a,cache:c,llmStringKey:l,parsedOptions:o,handledOptions:i});let p={};if(d.length>0){const f=await this._generateUncached(d.map(g=>a[g]),o,i,h!==void 0?d.map(g=>h?.[g]):void 0);await Promise.all(f.generations.map(async(g,b)=>{const S=d[b];u[S]=g;const w=Ln._convertInputToPromptValue(a[S]).toString();return c.update(w,l,g)})),p=f.llmOutput??{}}return{generations:u,llmOutput:p}}invocationParams(t){return{}}_modelType(){return"base_chat_model"}async generatePrompt(t,n,r){const s=t.map(a=>a.toChatMessages());return this.generate(s,n,r)}withStructuredOutput(t,n){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(n?.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=t,s=n?.name,a=Hr(r)??"A function available to call.",i=n?.method,o=n?.includeRaw;if(i==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=s??"extract",l;Qn(r)?l=[{type:"function",function:{name:c,description:a,parameters:mt(r)}}]:("name"in r&&(c=r.name),l=[{type:"function",function:{name:c,description:a,parameters:r}}]);const u=this.bindTools(l),d=ot.from(g=>{if(!yt.isInstance(g))throw new Error("Input is not an AIMessageChunk.");if(!g.tool_calls||g.tool_calls.length===0)throw new Error("No tool calls found in the response.");const b=g.tool_calls.find(S=>S.name===c);if(!b)throw new Error(`No tool call found with name ${c}.`);return b.args});if(!o)return u.pipe(d).withConfig({runName:"StructuredOutput"});const h=Ds.assign({parsed:(g,b)=>d.invoke(g.raw,b)}),p=Ds.assign({parsed:()=>null}),f=h.withFallbacks({fallbacks:[p]});return kt.from([{raw:u},f]).withConfig({runName:"StructuredOutputRunnable"})}},GC=class extends rr{async _generate(e,t,n){const r=await this._call(e,t,n),s=new D(r);if(typeof s.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:s.content,message:s}]}}},WC=class extends J{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){const{key:n,input:r}=e,s=this.runnables[n];if(s===void 0)throw new Error(`No runnable associated with key "${n}".`);return s.invoke(r,K(t))}async batch(e,t,n){const r=e.map(d=>d.key),s=e.map(d=>d.input);if(r.find(d=>this.runnables[d]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const i=r.map(d=>this.runnables[d]),o=this._getOptionsList(t??{},e.length),c=o[0]?.maxConcurrency??n?.maxConcurrency,l=c&&c>0?c:e.length,u=[];for(let d=0;d<s.length;d+=l){const h=s.slice(d,d+l).map((f,g)=>i[g].invoke(f,o[g])),p=await Promise.all(h);u.push(p)}return u.flat()}async stream(e,t){const{key:n,input:r}=e,s=this.runnables[n];if(s===void 0)throw new Error(`No runnable associated with key "${n}".`);return s.stream(r,t)}},JC=class extends J{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");const n=e.slice(0,-1).map(([s,a])=>[Le(s),Le(a)]),r=Le(e[e.length-1]);return new this({branches:n,default:r})}async _invoke(e,t,n){let r;for(let s=0;s<this.branches.length;s+=1){const[a,i]=this.branches[s];if(await a.invoke(e,ne(t,{callbacks:n?.getChild(`condition:${s+1}`)}))){r=await i.invoke(e,ne(t,{callbacks:n?.getChild(`branch:${s+1}`)}));break}}return r||(r=await this.default.invoke(e,ne(t,{callbacks:n?.getChild("branch:default")}))),r}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){const r=await(await st(t))?.handleChainStart(this.toJSON(),Oe(e,"input"),t?.runId,void 0,void 0,void 0,t?.runName);let s,a=!0,i;try{for(let o=0;o<this.branches.length;o+=1){const[c,l]=this.branches[o];if(await c.invoke(e,ne(t,{callbacks:r?.getChild(`condition:${o+1}`)}))){i=await l.stream(e,ne(t,{callbacks:r?.getChild(`branch:${o+1}`)}));for await(const d of i)if(yield d,a)if(s===void 0)s=d;else try{s=In(s,d)}catch{s=void 0,a=!1}break}}if(i===void 0){i=await this.default.stream(e,ne(t,{callbacks:r?.getChild("branch:default")}));for await(const o of i)if(yield o,a)if(s===void 0)s=o;else try{s=In(s,o)}catch{s=void 0,a=!1}}}catch(o){throw await r?.handleChainError(o),o}await r?.handleChainEnd(s??{})}},KC=class extends Fe{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=ot.from((a,i)=>this._enterHistory(a,i??{})).withConfig({runName:"loadHistory"});const n=e.historyMessagesKey??e.inputMessagesKey;n&&(t=Ds.assign({[n]:t}).withConfig({runName:"insertHistory"}));const r=t.pipe(e.runnable.withListeners({onEnd:(a,i)=>this._exitHistory(a,i??{})})).withConfig({runName:"RunnableWithMessageHistory"}),s=e.config??{};super({...e,config:s,bound:r}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e=="object"&&!Array.isArray(e)&&!Pe(e)){let n;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="input",Array.isArray(e[n])&&Array.isArray(e[n][0])?t=e[n][0]:t=e[n]}else t=e;if(typeof t=="string")return[new he(t)];if(Array.isArray(t))return t;if(Pe(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
93
- Got ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!Pe(e)&&typeof e!="string"){let n;this.outputMessagesKey!==void 0?n=this.outputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="output",e.generations!==void 0?t=e.generations[0][0].message:t=e[n]}else t=e;if(typeof t=="string")return[new D(t)];if(Array.isArray(t))return t;if(Pe(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){const r=await(t?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(e)):r}async _exitHistory(e,t){const n=t.configurable?.messageHistory;let r;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?r=e.inputs[0]:r=e.inputs;let s=this._getInputMessages(r);if(this.historyMessagesKey===void 0){const o=await n.getMessages();s=s.slice(o.length)}const a=e.outputs;if(!a)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const i=this._getOutputMessages(a);await n.addMessages([...s,...i])}async _mergeConfig(...e){const t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){const r={[this.inputMessagesKey??"input"]:"foo"},s={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
94
- eg. chain.invoke(${JSON.stringify(r)}, ${JSON.stringify(s)})`)}const{sessionId:n}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(n),t}},xf={};U(xf,{RouterRunnable:()=>WC,Runnable:()=>J,RunnableAssign:()=>ml,RunnableBinding:()=>Fe,RunnableBranch:()=>JC,RunnableEach:()=>J0,RunnableLambda:()=>ot,RunnableMap:()=>ts,RunnableParallel:()=>q0,RunnablePassthrough:()=>Ds,RunnablePick:()=>Gp,RunnableRetry:()=>fl,RunnableSequence:()=>kt,RunnableToolLike:()=>ac,RunnableWithFallbacks:()=>Vp,RunnableWithMessageHistory:()=>KC,_coerceToRunnable:()=>Le,ensureConfig:()=>K,getCallbackManagerForConfig:()=>st,mergeConfigs:()=>ft,patchConfig:()=>ne,pickRunnableConfigKeys:()=>ln});var ZC={};Tf(ZC,{ConfigurableModel:()=>dc,MODEL_PROVIDER_CONFIG:()=>$i,_inferModelProvider:()=>Nf,getChatModelByClassName:()=>Pf,initChatModel:()=>rs});const $i={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},fireworks:{package:"@langchain/community/chat_models/fireworks",className:"ChatFireworks",hasCircularDependency:!0},together:{package:"@langchain/community/chat_models/togetherai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/community/chat_models/perplexity",className:"ChatPerplexity",hasCircularDependency:!0}},If=Object.keys($i);async function Pf(e){const t=Object.entries($i).find(([,r])=>r.className===e);if(!t)return;const[,n]=t;try{return(await import(n.package))[n.className]}catch(r){const s=r;if("code"in s&&s.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in s){const a=s.message.split("Error: Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${a}. Please install with \`npm install ${a}\` or \`pnpm install ${a}\``)}throw r}}async function qC(e,t,n={}){const r=t||Nf(e);if(!r)throw new Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);const s=$i[r];if(!s){const c=If.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
95
-
96
- Supported model providers are: ${c}`)}const{modelProvider:a,...i}=n,o=await Pf(s.className);return new o({model:e,...i})}function Nf(e){return e.startsWith("gpt-3")||e.startsWith("gpt-4")||e.startsWith("gpt-5")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?"openai":e.startsWith("claude")?"anthropic":e.startsWith("command")?"cohere":e.startsWith("accounts/fireworks")?"fireworks":e.startsWith("gemini")?"google-vertexai":e.startsWith("amazon.")?"bedrock":e.startsWith("mistral")?"mistralai":e.startsWith("sonar")||e.startsWith("pplx")?"perplexity":void 0}var dc=class Sa extends rr{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};constructor(t){super(t),this._defaultConfig=t.defaultConfig??{},t.configurableFields==="any"?this._configurableFields="any":this._configurableFields=t.configurableFields??["model","modelProvider"],t.configPrefix?this._configPrefix=t.configPrefix.endsWith("_")?t.configPrefix:`${t.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=t.queuedMethodOperations??this._queuedMethodOperations}async _model(t){const n={...this._defaultConfig,...this._modelParams(t)};let r=await qC(n.model,n.modelProvider,n);const s=Object.entries(this._queuedMethodOperations);if(s.length>0)for(const[a,i]of s)a in r&&typeof r[a]=="function"&&(r=await r[a](...i));return r}async _generate(t,n,r){return(await this._model(n))._generate(t,n??{},r)}bindTools(t,n){const r={...this._queuedMethodOperations};return r.bindTools=[t,n],new Sa({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(t,...n)=>{const r={...this._queuedMethodOperations};return r.withStructuredOutput=[t,...n],new Sa({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})};_modelParams(t){const n=t?.configurable??{};let r={};for(const[s,a]of Object.entries(n))if(s.startsWith(this._configPrefix)){const i=this._removePrefix(s,this._configPrefix);r[i]=a}return this._configurableFields!=="any"&&(r=Object.fromEntries(Object.entries(r).filter(([s])=>this._configurableFields.includes(s)))),r}_removePrefix(t,n){return t.startsWith(n)?t.slice(n.length):t}withConfig(t){const n={...t||{}},r=this._modelParams(n),s=Object.fromEntries(Object.entries(n).filter(([i])=>i!=="configurable"));s.configurable=Object.fromEntries(Object.entries(n.configurable||{}).filter(([i])=>this._configPrefix&&!Object.keys(r).includes(this._removePrefix(i,this._configPrefix))));const a=new Sa({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new Fe({config:n,bound:a})}async invoke(t,n){const r=await this._model(n),s=K(n);return r.invoke(t,s)}async stream(t,n){const r=await this._model(n),s=new Mn({generator:await r.stream(t,n),config:n});return await s.setup,Be.fromAsyncGenerator(s)}async batch(t,n,r){return super.batch(t,n,r)}async*transform(t,n){const r=await this._model(n),s=K(n);yield*r.transform(t,s)}async*streamLog(t,n,r){const s=await this._model(n),a=K(n);yield*s.streamLog(t,a,{...r,_schemaFormat:"original",includeNames:r?.includeNames,includeTypes:r?.includeTypes,includeTags:r?.includeTags,excludeNames:r?.excludeNames,excludeTypes:r?.excludeTypes,excludeTags:r?.excludeTags})}streamEvents(t,n,r){const s=this;async function*a(){const i=await s._model(n),o=K(n),c=i.streamEvents(t,o,r);for await(const l of c)yield l}return Be.fromAsyncGenerator(a())}};async function rs(e,t){let{configurableFields:n,configPrefix:r,modelProvider:s,...a}={configPrefix:"",...t??{}};if(s===void 0&&e?.includes(":")){const[c,...l]=e.split(":"),u=l.length===0?[c]:[c,l.join(":")];If.includes(u[0])&&([s,e]=u)}let i=Array.isArray(n)?[...n]:n;!e&&i===void 0&&(i=["model","modelProvider"]),r&&i===void 0&&console.warn(`{ configPrefix: ${r} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);const o={...a};return i===void 0?new dc({defaultConfig:{...o,model:e,modelProvider:s},configPrefix:r}):(e&&(o.model=e),s&&(o.modelProvider=s),new dc({defaultConfig:o,configPrefix:r,configurableFields:i}))}var hc=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},pc=class extends Error{toolNames;constructor(e){super(`The model has called multiple tools: ${e.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=e}},Mf=class extends Error{toolName;errors;constructor(e,t){super(`Failed to parse structured output for tool '${e}':${t.map(n=>`
97
- - ${n}`).join("")}.`),this.toolName=e,this.errors=t}},Pl=class extends Error{toolCall;toolError;constructor(e,t){const n=e instanceof Error?e:new Error(String(e)),r=JSON.stringify(t.args);super(`Error invoking tool '${t.name}' with kwargs ${r} with error: ${n.stack}
98
- Please fix the error and try again.`),this.toolCall=t,this.toolError=n}};function Nl(e){return"invoke"in e&&typeof e.invoke=="function"&&"_streamResponseChunks"in e}function ni(e){return typeof e=="object"&&e!=null&&"_queuedMethodOperations"in e&&"_model"in e&&typeof e._model=="function"}var Rf={};U(Rf,{extendInteropZodObject:()=>gp,getInteropZodDefaultGetter:()=>ki,getInteropZodObjectShape:()=>Ps,getSchemaDescription:()=>Hr,interopParse:()=>sn,interopParseAsync:()=>Ei,interopSafeParse:()=>mp,interopSafeParseAsync:()=>cl,interopZodObjectMakeFieldsOptional:()=>yp,interopZodObjectPartial:()=>Ai,interopZodObjectPassthrough:()=>Zo,interopZodObjectStrict:()=>Ka,interopZodTransformInputSchema:()=>fr,isInteropZodLiteral:()=>Db,isInteropZodObject:()=>et,isInteropZodSchema:()=>Qn,isShapelessZodSchema:()=>Fb,isSimpleStringZodSchema:()=>ll,isZodArrayV4:()=>Ci,isZodLiteralV3:()=>pp,isZodLiteralV4:()=>fp,isZodObjectV3:()=>ul,isZodObjectV4:()=>Wt,isZodSchema:()=>jb,isZodSchemaV3:()=>Ee,isZodSchemaV4:()=>ge});let YC=0;var yn=class fc{constructor(t,n,r){this.schema=t,this.tool=n,this.options=r}get name(){return this.tool.function.name}static fromSchema(t,n){function r(o){return o??`extract-${++YC}`}if(Qn(t)){const o=mt(t),c={type:"function",function:{name:r(),strict:!1,description:o.description??"Tool for extracting structured output from the model's response.",parameters:o}};return new fc(o,c,n)}let s;typeof t.name=="string"&&typeof t.parameters=="object"&&t.parameters!=null?s=t:s={name:r(t.title),description:t.description??"",parameters:t.schema||t};const a=mt(t),i={type:"function",function:s};return new fc(a,i,n)}parse(t){const r=new Wc(this.schema).validate(t);if(!r.valid)throw new Mf(this.name,r.errors.map(s=>s.error));return t}},Un=class $f{_schemaType;constructor(t){this.schema=t}static fromSchema(t){const n=mt(t);return new $f(n)}parse(t){if(!(typeof t.content!="string"||t.content===""))try{const n=JSON.parse(t.content);return new Wc(this.schema).validate(n).valid?n:void 0}catch{}}};function Lf(e,t,n){if(!e)return[];if(typeof e=="object"&&e!==null&&"__responseFormatUndefined"in e)return[];if(Array.isArray(e)){if(e.every(s=>s instanceof yn||s instanceof Un))return e;if(e.every(s=>et(s)))return e.map(s=>yn.fromSchema(s,t));if(e.every(s=>typeof s=="object"&&s!==null&&!et(s)))return e.map(s=>yn.fromSchema(s,t));throw new Error(`Invalid response format: list contains mixed types.
99
- All items must be either InteropZodObject or plain JSON schema objects.`)}if(e instanceof yn||e instanceof Un)return[e];const r=jf(n);if(et(e))return r?[Un.fromSchema(e)]:[yn.fromSchema(e,t)];if(typeof e=="object"&&e!==null&&"properties"in e)return r?[Un.fromSchema(e)]:[yn.fromSchema(e,t)];throw new Error(`Invalid response format: ${String(e)}`)}function XC(e,t){return Lf(e,t)}function QC(e){return Un.fromSchema(e)}const eA=["ChatOpenAI","ChatXAI"],Cd=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function jf(e){if(!e)return!1;if(typeof e=="string"){const n=e.split(":").pop();return Cd.some(r=>n.includes(r))}if(ni(e))return jf(e._defaultConfig.model);if(!Nl(e))return!1;const t=e.getName();return!!(t==="FakeToolCallingChatModel"||eA.includes(t)&&("model"in e&&Cd.some(n=>typeof e.model=="string"&&e.model.includes(n))||t==="FakeToolCallingModel"&&"structuredResponse"in e))}function Ml(e){let t=0;for(const n of e){let r;typeof n.content=="string"?r=n.content:Array.isArray(n.content)?r=n.content.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join(""):r="",t+=r.length}return Math.ceil(t/4)}function vn(e){if(!(!e||typeof e=="function"))return e.canJumpTo}function Li(e){return typeof e=="function"?e:e.hook}function tA(e){return new Promise(t=>setTimeout(t,e))}function wt(e){return{name:e.name,stateSchema:e.stateSchema,contextSchema:e.contextSchema,wrapToolCall:e.wrapToolCall,wrapModelCall:e.wrapModelCall,beforeAgent:e.beforeAgent,beforeModel:e.beforeModel,afterModel:e.afterModel,afterAgent:e.afterAgent,tools:e.tools??[]}}function Df(e){return A_({clockseq:e})}function gr(e,t){const n=t.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return Es(e,new Uint8Array(n))}const nA="__error__",Ta="__scheduled__",rA="__interrupt__",sA="__resume__";var Ad="[...]",aA="[Circular]",ri=[],yr=[];function iA(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function oA(e,t,n,r){typeof r>"u"&&(r=iA()),mc(e,"",0,[],void 0,0,r);var s;try{yr.length===0?s=JSON.stringify(e,t,n):s=JSON.stringify(e,cA(t),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;ri.length!==0;){var a=ri.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return s}function vo(e,t,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:e}),ri.push([r,n,t,s])):yr.push([t,n,e]):(r[n]=e,ri.push([r,n,t]))}function mc(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){vo(aA,e,t,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){vo(Ad,e,t,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){vo(Ad,e,t,s);return}if(r.push(e),Array.isArray(e))for(o=0;o<e.length;o++)mc(e[o],o,o,r,e,a,i);else{var c=Object.keys(e);for(o=0;o<c.length;o++){var l=c[o];mc(e[l],l,o,r,e,a,i)}}r.pop()}}function cA(e){return e=typeof e<"u"?e:function(t,n){return n},function(t,n){if(yr.length>0)for(var r=0;r<yr.length;r++){var s=yr[r];if(s[1]===t&&s[0]===n){n=s[2],yr.splice(r,1);break}}return e.call(this,t,n)}}const lA=[];var uA={},Ff={};U(Ff,{BaseChatMessageHistory:()=>Uf,BaseListChatMessageHistory:()=>Rl,InMemoryChatMessageHistory:()=>dA});var Uf=class extends At{async addMessages(e){for(const t of e)await this.addMessage(t)}},Rl=class extends At{addUserMessage(e){return this.addMessage(new he(e))}addAIMessage(e){return this.addMessage(new D(e))}async addMessages(e){for(const t of e)await this.addMessage(t)}clear(){throw new Error("Not implemented.")}},dA=class extends Rl{lc_namespace=["langchain","stores","message","in_memory"];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},Bf={};U(Bf,{Embeddings:()=>$l});var $l=class{caller;constructor(e){this.caller=new Xs(e??{})}},hA={},zf={};U(zf,{BaseMemory:()=>pA,getInputValue:()=>fA,getOutputValue:()=>mA,getPromptInputKey:()=>gA});var pA=class{};const Hf=(e,t)=>{if(t!==void 0)return e[t];const n=Object.keys(e);if(n.length===1)return e[n[0]]},fA=(e,t)=>{const n=Hf(e,t);if(!n){const r=Object.keys(e);throw new Error(`input values have ${r.length} keys, you must specify an input key or pass only 1 key as input`)}return n},mA=(e,t)=>{const n=Hf(e,t);if(!n&&n!==""){const r=Object.keys(e);throw new Error(`output values have ${r.length} keys, you must specify an output key or pass only 1 key as output`)}return n};function gA(e,t){const n=Object.keys(e).filter(r=>!t.includes(r)&&r!=="stop");if(n.length!==1)throw new Error(`One input key expected, but got ${n.length}`);return n[0]}var Vf={};U(Vf,{BaseStore:()=>Gf,InMemoryStore:()=>Wf});var Gf=class extends At{},Wf=class extends Gf{lc_namespace=["langchain","storage"];store={};async mget(e){return e.map(t=>this.store[t])}async mset(e){for(const[t,n]of e)this.store[t]=n}async mdelete(e){for(const t of e)delete this.store[t]}async*yieldKeys(e){const t=Object.keys(this.store);for(const n of t)(e===void 0||n.startsWith(e))&&(yield n)}},Jf={};U(Jf,{BaseRetriever:()=>Ll});var Ll=class extends J{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){const n=K(qs(t)),s=await(await Ke.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{const a=await this._getRelevantDocuments(e,s);return await s?.handleRetrieverEnd(a),a}catch(a){throw await s?.handleRetrieverError(a),a}}},Kf={};U(Kf,{SaveableVectorStore:()=>yA,VectorStore:()=>jl,VectorStoreRetriever:()=>Ea});var Ea=class extends Ll{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}vectorStore;k=4;searchType="similarity";searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},jl=class extends At{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)).map(a=>a[0])}async similaritySearchWithScore(e,t=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)}static fromTexts(e,t,n,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,n,r,s,a){if(typeof e=="number")return new Ea({vectorStore:this,k:e,filter:t,tags:[...r??[],this._vectorstoreType()],metadata:s,verbose:a,callbacks:n});{const i={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType==="mmr"?new Ea({...i,searchKwargs:e.searchKwargs}):new Ea({...i})}}},yA=class extends jl{static load(e,t){throw new Error("Not implemented")}},Zf={};U(Zf,{BaseDocumentLoader:()=>qf});var qf=class{},Yf={};U(Yf,{LangSmithLoader:()=>_A});var _A=class extends qf{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=e.client??new zr(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split("."):[],this.formatContent=e.formatContent??wA,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){const e=[];for await(const t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=t.inputs;for(const a of this.contentKey)n=n[a];const r=this.formatContent(n),s=t;["created_at","modified_at"].forEach(a=>{a in s&&typeof s[a]=="object"&&(s[a]=s[a].toString())}),e.push({pageContent:r,metadata:s})}return e}};function wA(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var an=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent!==void 0?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}},Xf=class extends J{lc_namespace=["langchain_core","documents","transformers"];invoke(e,t){return this.transformDocuments(e)}},vA=class extends Xf{async transformDocuments(e){const t=[];for(const n of e){const r=await this._transformDocument(n);t.push(r)}return t}},Qf={};U(Qf,{BaseDocumentTransformer:()=>Xf,Document:()=>an,MappingDocumentTransformer:()=>vA});var Dl=class extends At{lc_namespace=["langchain_core","example_selectors","base"]},em=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},bA=class extends em{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(const[t,n]of this.conditionals)if(t(e))return n;return this.defaultPrompt}};function SA(e){return e._modelType()==="base_llm"}function TA(e){return e._modelType()==="base_chat_model"}function kd(e){return e.split(/\n| /).length}var EA=class tm extends Dl{examples=[];examplePrompt;getTextLength=kd;maxLength=2048;exampleTextLengths=[];constructor(t){super(t),this.examplePrompt=t.examplePrompt,this.maxLength=t.maxLength??2048,this.getTextLength=t.getTextLength??kd}async addExample(t){this.examples.push(t);const n=await this.examplePrompt.format(t);this.exampleTextLengths.push(this.getTextLength(n))}async calculateExampleTextLengths(t,n){if(t.length>0)return t;const{examples:r,examplePrompt:s}=n;return(await Promise.all(r.map(i=>s.format(i)))).map(i=>this.getTextLength(i))}async selectExamples(t){const n=Object.values(t).join(" ");let r=this.maxLength-this.getTextLength(n),s=0;const a=[];for(;r>0&&s<this.examples.length;){const i=r-this.exampleTextLengths[s];if(i<0)break;a.push(this.examples[s]),r=i,s+=1}return a}static async fromExamples(t,n){const r=new tm(n);return await Promise.all(t.map(s=>r.addExample(s))),r}};function bo(e){return Object.keys(e).sort().map(t=>e[t])}var CA=class nm extends Dl{vectorStoreRetriever;exampleKeys;inputKeys;constructor(t){if(super(t),this.exampleKeys=t.exampleKeys,this.inputKeys=t.inputKeys,t.vectorStore!==void 0)this.vectorStoreRetriever=t.vectorStore.asRetriever({k:t.k??4,filter:t.filter});else if(t.vectorStoreRetriever)this.vectorStoreRetriever=t.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(t){const n=this.inputKeys??Object.keys(t),r=bo(n.reduce((s,a)=>({...s,[a]:t[a]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new an({pageContent:r,metadata:t})])}async selectExamples(t){const n=this.inputKeys??Object.keys(t),r=bo(n.reduce((i,o)=>({...i,[o]:t[o]}),{})).join(" "),a=(await this.vectorStoreRetriever.invoke(r)).map(i=>i.metadata);return this.exampleKeys?a.map(i=>this.exampleKeys.reduce((o,c)=>({...o,[c]:i[c]}),{})):a}static async fromExamples(t,n,r,s={}){const a=s.inputKeys??null,i=t.map(c=>bo(a?a.reduce((l,u)=>({...l,[u]:c[u]}),{}):c).join(" ")),o=await r.fromTexts(i,t,n,s);return new nm({vectorStore:o,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},rm={};U(rm,{BaseExampleSelector:()=>Dl,BasePromptSelector:()=>em,ConditionalPromptSelector:()=>bA,LengthBasedExampleSelector:()=>EA,SemanticSimilarityExampleSelector:()=>CA,isChatModel:()=>TA,isLLM:()=>SA});const gc="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var AA=class extends At{lc_namespace=["langchain","recordmanagers"]},sm=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=_l;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){const e=["hash_","content_hash","metadata_hash"];for(const n of e)if(n in this.metadata)throw new Error(`Metadata cannot contain key ${n} as it is reserved for internal use. Restricted keys: [${e.join(", ")}]`);const t=this._hashStringToUUID(this.pageContent);try{const n=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=n}catch(n){throw new Error(`Failed to hash metadata: ${n}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||(this.uid=this.hash_)}toDocument(){return new an({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){const n=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return n.calculateHashes(),n}_hashStringToUUID(e){const t=this.keyEncoder(e);return Es(t,gc)}_hashNestedDictToUUID(e){const t=JSON.stringify(e,Object.keys(e).sort()),n=this.keyEncoder(t);return Es(n,gc)}};function am(e,t){const n=[];let r=[];return t.forEach(s=>{r.push(s),r.length>=e&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function im(e){const t=new Set,n=[];for(const r of e){if(!r.hash_)throw new Error("Hashed document does not have a hash");t.has(r.hash_)||(t.add(r.hash_),n.push(r))}return n}function om(e){if(e===null)return t=>null;if(typeof e=="string")return t=>t.metadata[e];if(typeof e=="function")return e;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}const cm=e=>"load"in e&&typeof e.load=="function"&&"loadAndSplit"in e&&typeof e.loadAndSplit=="function";async function kA(e){const{docsSource:t,recordManager:n,vectorStore:r,options:s}=e,{batchSize:a=100,cleanup:i,sourceIdKey:o,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=s??{};if(i==="incremental"&&!o)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");const u=cm(t)?await t.load():t,d=om(o??null),h=await n.getTime();let p=0,f=0,g=0,b=0;const S=am(a??100,u);for(const w of S){const v=im(w.map(I=>sm.fromDocument(I))),T=v.map(I=>d(I));i==="incremental"&&v.forEach((I,R)=>{if(T[R]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const k=await n.exists(v.map(I=>I.uid)),O=[],C=[],y=[],N=new Set;if(v.forEach((I,R)=>{if(k[R])if(l)N.add(I.uid);else{y.push(I.uid);return}O.push(I.uid),C.push(I.toDocument())}),y.length>0&&(await n.update(y,{timeAtLeast:h}),b+=y.length),C.length>0&&(await r.addDocuments(C,{ids:O}),p+=C.length-N.size,g+=N.size),await n.update(v.map(I=>I.uid),{timeAtLeast:h,groupIds:T}),i==="incremental"){T.forEach(R=>{if(!R)throw new Error("Source id cannot be null")});const I=await n.listKeys({before:h,groupIds:T});I.length>0&&(await r.delete({ids:I}),await n.deleteKeys(I),f+=I.length)}}if(i==="full"){let w=await n.listKeys({before:h,limit:c});for(;w.length>0;)await r.delete({ids:w}),await n.deleteKeys(w),f+=w.length,w=await n.listKeys({before:h,limit:c})}return{numAdded:p,numDeleted:f,numUpdated:g,numSkipped:b}}var lm={};U(lm,{RecordManager:()=>AA,UUIDV5_NAMESPACE:()=>gc,_HashedDocument:()=>sm,_batch:()=>am,_deduplicateInOrder:()=>im,_getSourceIdAssigner:()=>om,_isBaseDocumentLoader:()=>cm,index:()=>kA});var um={};U(um,{BaseLLM:()=>dm,LLM:()=>Fl});var dm=class us extends Pi{lc_namespace=["langchain","llms",this._llmType()];async invoke(t,n){const r=us._convertInputToPromptValue(t);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].text}async*_streamResponseChunks(t,n,r){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(t){const[n,r]=super._separateRunnableConfigFromCallOptions(t);return r.signal=n.signal,[n,r]}async*_streamIterator(t,n){if(this._streamResponseChunks===us.prototype._streamResponseChunks)yield this.invoke(t,n);else{const r=us._convertInputToPromptValue(t),[s,a]=this._separateRunnableConfigFromCallOptionsCompat(n),i=await Ke.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),o={options:a,invocation_params:this?.invocationParams(a),batch_size:1},c=await i?.handleLLMStart(this.toJSON(),[r.toString()],s.runId,void 0,o,void 0,void 0,s.runName);let l=new Gr({text:""});try{for await(const u of this._streamResponseChunks(r.toString(),a,c?.[0]))l?l=l.concat(u):l=u,typeof u.text=="string"&&(yield u.text)}catch(u){throw await Promise.all((c??[]).map(d=>d?.handleLLMError(u))),u}await Promise.all((c??[]).map(u=>u?.handleLLMEnd({generations:[[l]]})))}}async generatePrompt(t,n,r){const s=t.map(a=>a.toString());return this.generate(s,n,r)}invocationParams(t){return{}}_flattenLLMResult(t){const n=[];for(let r=0;r<t.generations.length;r+=1){const s=t.generations[r];if(r===0)n.push({generations:[s],llmOutput:t.llmOutput});else{const a=t.llmOutput?{...t.llmOutput,tokenUsage:{}}:void 0;n.push({generations:[s],llmOutput:a})}}return n}async _generateUncached(t,n,r,s){let a;if(s!==void 0&&s.length===t.length)a=s;else{const l=await Ke.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),u={options:n,invocation_params:this?.invocationParams(n),batch_size:t.length};a=await l?.handleLLMStart(this.toJSON(),t,r.runId,void 0,u,void 0,void 0,r?.runName)}const i=!!a?.[0].handlers.find(al);let o;if(i&&t.length===1&&this._streamResponseChunks!==us.prototype._streamResponseChunks)try{const l=await this._streamResponseChunks(t[0],n,a?.[0]);let u;for await(const d of l)u===void 0?u=d:u=In(u,d);if(u===void 0)throw new Error("Received empty response from chat model call.");o={generations:[[u]],llmOutput:{}},await a?.[0].handleLLMEnd(o)}catch(l){throw await a?.[0].handleLLMError(l),l}else{try{o=await this._generate(t,n,a?.[0])}catch(u){throw await Promise.all((a??[]).map(d=>d?.handleLLMError(u))),u}const l=this._flattenLLMResult(o);await Promise.all((a??[]).map((u,d)=>u?.handleLLMEnd(l[d])))}const c=a?.map(l=>l.runId)||void 0;return Object.defineProperty(o,Ms,{value:c?{runIds:c}:void 0,configurable:!0}),o}async _generateCached({prompts:t,cache:n,llmStringKey:r,parsedOptions:s,handledOptions:a,runId:i}){const o=await Ke.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),c={options:s,invocation_params:this?.invocationParams(s),batch_size:t.length},l=await o?.handleLLMStart(this.toJSON(),t,i,void 0,c,void 0,void 0,a?.runName),u=[],h=(await Promise.allSettled(t.map(async(g,b)=>{const S=await n.lookup(g,r);return S==null&&u.push(b),S}))).map((g,b)=>({result:g,runManager:l?.[b]})).filter(({result:g})=>g.status==="fulfilled"&&g.value!=null||g.status==="rejected"),p=[];await Promise.all(h.map(async({result:g,runManager:b},S)=>{if(g.status==="fulfilled"){const w=g.value;return p[S]=w.map(v=>(v.generationInfo={...v.generationInfo,tokenUsage:{}},v)),w.length&&await b?.handleLLMNewToken(w[0].text),b?.handleLLMEnd({generations:[w]},void 0,void 0,void 0,{cached:!0})}else return await b?.handleLLMError(g.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(g.reason)}));const f={generations:p,missingPromptIndices:u,startedRunManagers:l};return Object.defineProperty(f,Ms,{value:l?{runIds:l?.map(g=>g.runId)}:void 0,configurable:!0}),f}async generate(t,n,r){if(!Array.isArray(t))throw new Error("Argument 'prompts' is expected to be a string[]");let s;Array.isArray(n)?s={stop:n}:s=n;const[a,i]=this._separateRunnableConfigFromCallOptionsCompat(s);if(a.callbacks=a.callbacks??r,!this.cache)return this._generateUncached(t,i,a);const{cache:o}=this,c=this._getSerializedCacheKeyParametersForCall(i),{generations:l,missingPromptIndices:u,startedRunManagers:d}=await this._generateCached({prompts:t,cache:o,llmStringKey:c,parsedOptions:i,handledOptions:a,runId:a.runId});let h={};if(u.length>0){const p=await this._generateUncached(u.map(f=>t[f]),i,a,d!==void 0?u.map(f=>d?.[f]):void 0);await Promise.all(p.generations.map(async(f,g)=>{const b=u[g];return l[b]=f,o.update(t[b],c,f)})),h=p.llmOutput??{}}return{generations:l,llmOutput:h}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},Fl=class extends dm{async _generate(e,t,n){return{generations:await Promise.all(e.map((s,a)=>this._call(s,{...t,promptIndex:a},n).then(i=>[{text:i}])))}}},hm={};U(hm,{applyPatch:()=>Vr,compare:()=>Oi});var ji=class extends J{parseResultWithPrompt(e,t,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r?.callbacks),e,{...t,runType:"parser"})}},ea=class extends ji{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,n){return this.parse(e,n)}_type(){throw new Error("_type not implemented")}},on=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,n,r=!1){if(super(e),this.llmOutput=t,this.observation=n,this.sendToLLM=r,r&&(n===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");Si(this,"OUTPUT_PARSING_FAILURE")}},ta=class extends ea{async*_transform(e){for await(const t of e)typeof t=="string"?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}},na=class extends ta{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,n;for await(const r of e){if(typeof r!="string"&&typeof r.content!="string")throw new Error("Cannot handle non-string output.");let s;if(As(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");s=new Wr({message:r,text:r.content})}else if(Pe(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");s=new Wr({message:Ga(r),text:r.content})}else s=new Gr({text:r});n===void 0?n=s:n=n.concat(s);const a=await this.parsePartialResult([n]);a!=null&&!ch(a,t)&&(this.diff?yield this._diff(t,a):yield a,t=a)}}getFormatInstructions(){return""}},OA=class extends ta{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}},ra=class extends ta{re;async*_transform(e){let t="";for await(const n of e)if(typeof n=="string"?t+=n:t+=n.content,this.re){const r=[...t.matchAll(this.re)];if(r.length>1){let s=0;for(const a of r.slice(0,-1))yield[a[1]],s+=(a.index??0)+a[0].length;t=t.slice(s)}}else{const r=await this.parse(t);if(r.length>1){for(const s of r.slice(0,-1))yield[s];t=r[r.length-1]}}for(const n of await this.parse(t))yield[n]}},xA=class extends ra{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(t=>t.trim())}catch{throw new on(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},IA=class extends ra{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:t}){super(...arguments),this.length=e,this.separator=t||","}async parse(e){try{const t=e.trim().split(this.separator).map(n=>n.trim());if(this.length!==void 0&&t.length!==this.length)throw new on(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===on.prototype?t:new on(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},PA=class extends ra{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
100
-
101
- 1. foo
102
-
103
- 2. bar
104
-
105
- 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},NA=class extends ra{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
106
-
107
- 1. foo
108
-
109
- 2. bar
110
-
111
- 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},MA=class extends ta{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((t,n)=>t+this._messageContentToString(n),"")}},pm=class extends ea{static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),this.schema=e}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=Y(Object.fromEntries(Object.entries(e).map(([n,r])=>[n,pe().describe(r)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
112
-
113
- "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
114
-
115
- For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
116
- would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
117
- Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
118
-
119
- Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
120
-
121
- Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
122
- \`\`\`json
123
- ${JSON.stringify(mt(this.schema))}
124
- \`\`\`
125
- `}async parse(e){try{const t=e.trim(),r=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(s,a)=>`"${a.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await Ei(this.schema,JSON.parse(r))}catch(t){throw new on(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}},fm=class extends pm{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(e){const t=e?.interpolationDepth??1;if(t<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
126
- \`\`\`json
127
- ${this._schemaToInstruction(mt(this.schema)).replaceAll("{","{".repeat(t)).replaceAll("}","}".repeat(t))}
128
- \`\`\``}_schemaToInstruction(e,t=2){const n=e;if("type"in n){let r=!1,s;if(Array.isArray(n.type)){const o=n.type.findIndex(c=>c==="null");o!==-1&&(r=!0,n.type.splice(o,1)),s=n.type.join(" | ")}else s=n.type;if(n.type==="object"&&n.properties){const o=n.description?` // ${n.description}`:"";return`{
129
- ${Object.entries(n.properties).map(([l,u])=>{const d=n.required?.includes(l)?"":" (optional)";return`${" ".repeat(t)}"${l}": ${this._schemaToInstruction(u,t+2)}${d}`}).join(`
130
- `)}
131
- ${" ".repeat(t-2)}}${o}`}if(n.type==="array"&&n.items){const o=n.description?` // ${n.description}`:"";return`array[
132
- ${" ".repeat(t)}${this._schemaToInstruction(n.items,t+2)}
133
- ${" ".repeat(t-2)}] ${o}`}const a=r?" (nullable)":"",i=n.description?` // ${n.description}`:"";return`${s}${i}${a}`}if("anyOf"in n)return n.anyOf.map(r=>this._schemaToInstruction(r,t)).join(`
134
- ${" ".repeat(t-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=Y(Object.fromEntries(Object.entries(e).map(([n,r])=>[n,pe().describe(r)])));return new this(t)}},RA=class extends ea{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new fm(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(n){throw new on(`Failed to parse. Text: "${e}". Error: ${n}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},$A=class extends na{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?Oi(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Bo(e[0].text)}async parse(e){return Bo(e,JSON.parse)}getFormatInstructions(){return""}};const LA=function(){const e={};e.parser=function(_,m){return new n(_,m)},e.SAXParser=n,e.SAXStream=l,e.createStream=c,e.MAX_BUFFER_LENGTH=64*1024;const t=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];e.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function n(_,m){if(!(this instanceof n))return new n(_,m);var x=this;s(x),x.q=x.c="",x.bufferCheckPosition=e.MAX_BUFFER_LENGTH,x.opt=m||{},x.opt.lowercase=x.opt.lowercase||x.opt.lowercasetags,x.looseCase=x.opt.lowercase?"toLowerCase":"toUpperCase",x.tags=[],x.closed=x.closedRoot=x.sawRoot=!1,x.tag=x.error=null,x.strict=!!_,x.noscript=!!(_||x.opt.noscript),x.state=y.BEGIN,x.strictEntities=x.opt.strictEntities,x.ENTITIES=x.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),x.attribList=[],x.opt.xmlns&&(x.ns=Object.create(f)),x.trackPosition=x.opt.position!==!1,x.trackPosition&&(x.position=x.line=x.column=0),I(x,"onready")}Object.create||(Object.create=function(_){function m(){}m.prototype=_;var x=new m;return x}),Object.keys||(Object.keys=function(_){var m=[];for(var x in _)_.hasOwnProperty(x)&&m.push(x);return m});function r(_){for(var m=Math.max(e.MAX_BUFFER_LENGTH,10),x=0,A=0,re=t.length;A<re;A++){var Ce=_[t[A]].length;if(Ce>m)switch(t[A]){case"textNode":z(_);break;case"cdata":R(_,"oncdata",_.cdata),_.cdata="";break;case"script":R(_,"onscript",_.script),_.script="";break;default:fe(_,"Max buffer length exceeded: "+t[A])}x=Math.max(x,Ce)}var Ae=e.MAX_BUFFER_LENGTH-x;_.bufferCheckPosition=Ae+_.position}function s(_){for(var m=0,x=t.length;m<x;m++)_[t[m]]=""}function a(_){z(_),_.cdata!==""&&(R(_,"oncdata",_.cdata),_.cdata=""),_.script!==""&&(R(_,"onscript",_.script),_.script="")}n.prototype={end:function(){or(this)},write:my,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){a(this)}};var i=ReadableStream;i||(i=function(){});var o=e.EVENTS.filter(function(_){return _!=="error"&&_!=="end"});function c(_,m){return new l(_,m)}function l(_,m){if(!(this instanceof l))return new l(_,m);i.apply(this),this._parser=new n(_,m),this.writable=!0,this.readable=!0;var x=this;this._parser.onend=function(){x.emit("end")},this._parser.onerror=function(A){x.emit("error",A),x._parser.error=null},this._decoder=null,o.forEach(function(A){Object.defineProperty(x,"on"+A,{get:function(){return x._parser["on"+A]},set:function(re){if(!re)return x.removeAllListeners(A),x._parser["on"+A]=re,re;x.on(A,re)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(i.prototype,{constructor:{value:l}}),l.prototype.write=function(_){return this._parser.write(_.toString()),this.emit("data",_),!0},l.prototype.end=function(_){return _&&_.length&&this.write(_),this._parser.end(),!0},l.prototype.on=function(_,m){var x=this;return!x._parser["on"+_]&&o.indexOf(_)!==-1&&(x._parser["on"+_]=function(){var A=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);A.splice(0,0,_),x.emit.apply(x,A)}),i.prototype.on.call(x,_,m)};var u="[CDATA[",d="DOCTYPE",h="http://www.w3.org/XML/1998/namespace",p="http://www.w3.org/2000/xmlns/",f={xml:h,xmlns:p},g=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,b=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,S=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,w=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function v(_){return _===" "||_===`
135
- `||_==="\r"||_===" "}function T(_){return _==='"'||_==="'"}function k(_){return _===">"||v(_)}function O(_,m){return _.test(m)}function C(_,m){return!O(_,m)}var y=0;e.STATE={BEGIN:y++,BEGIN_WHITESPACE:y++,TEXT:y++,TEXT_ENTITY:y++,OPEN_WAKA:y++,SGML_DECL:y++,SGML_DECL_QUOTED:y++,DOCTYPE:y++,DOCTYPE_QUOTED:y++,DOCTYPE_DTD:y++,DOCTYPE_DTD_QUOTED:y++,COMMENT_STARTING:y++,COMMENT:y++,COMMENT_ENDING:y++,COMMENT_ENDED:y++,CDATA:y++,CDATA_ENDING:y++,CDATA_ENDING_2:y++,PROC_INST:y++,PROC_INST_BODY:y++,PROC_INST_ENDING:y++,OPEN_TAG:y++,OPEN_TAG_SLASH:y++,ATTRIB:y++,ATTRIB_NAME:y++,ATTRIB_NAME_SAW_WHITE:y++,ATTRIB_VALUE:y++,ATTRIB_VALUE_QUOTED:y++,ATTRIB_VALUE_CLOSED:y++,ATTRIB_VALUE_UNQUOTED:y++,ATTRIB_VALUE_ENTITY_Q:y++,ATTRIB_VALUE_ENTITY_U:y++,CLOSE_TAG:y++,CLOSE_TAG_SAW_WHITE:y++,SCRIPT:y++,SCRIPT_ENDING:y++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach(function(_){var m=e.ENTITIES[_],x=typeof m=="number"?String.fromCharCode(m):m;e.ENTITIES[_]=x});for(var N in e.STATE)e.STATE[e.STATE[N]]=N;y=e.STATE;function I(_,m,x){_[m]&&_[m](x)}function R(_,m,x){_.textNode&&z(_),I(_,m,x)}function z(_){_.textNode=ce(_.opt,_.textNode),_.textNode&&I(_,"ontext",_.textNode),_.textNode=""}function ce(_,m){return _.trim&&(m=m.trim()),_.normalize&&(m=m.replace(/\s+/g," ")),m}function fe(_,m){return z(_),_.trackPosition&&(m+=`
136
- Line: `+_.line+`
137
- Column: `+_.column+`
138
- Char: `+_.c),m=new Error(m),_.error=m,I(_,"onerror",m),_}function or(_){return _.sawRoot&&!_.closedRoot&&q(_,"Unclosed root tag"),_.state!==y.BEGIN&&_.state!==y.BEGIN_WHITESPACE&&_.state!==y.TEXT&&fe(_,"Unexpected end"),z(_),_.c="",_.closed=!0,I(_,"onend"),n.call(_,_.strict,_.opt),_}function q(_,m){if(typeof _!="object"||!(_ instanceof n))throw new Error("bad call to strictFail");_.strict&&fe(_,m)}function zi(_){_.strict||(_.tagName=_.tagName[_.looseCase]());var m=_.tags[_.tags.length-1]||_,x=_.tag={name:_.tagName,attributes:{}};_.opt.xmlns&&(x.ns=m.ns),_.attribList.length=0,R(_,"onopentagstart",x)}function as(_,m){var x=_.indexOf(":"),A=x<0?["",_]:_.split(":"),re=A[0],Ce=A[1];return m&&_==="xmlns"&&(re="xmlns",Ce=""),{prefix:re,local:Ce}}function Hi(_){if(_.strict||(_.attribName=_.attribName[_.looseCase]()),_.attribList.indexOf(_.attribName)!==-1||_.tag.attributes.hasOwnProperty(_.attribName)){_.attribName=_.attribValue="";return}if(_.opt.xmlns){var m=as(_.attribName,!0),x=m.prefix,A=m.local;if(x==="xmlns")if(A==="xml"&&_.attribValue!==h)q(_,"xml: prefix must be bound to "+h+`
139
- Actual: `+_.attribValue);else if(A==="xmlns"&&_.attribValue!==p)q(_,"xmlns: prefix must be bound to "+p+`
140
- Actual: `+_.attribValue);else{var re=_.tag,Ce=_.tags[_.tags.length-1]||_;re.ns===Ce.ns&&(re.ns=Object.create(Ce.ns)),re.ns[A]=_.attribValue}_.attribList.push([_.attribName,_.attribValue])}else _.tag.attributes[_.attribName]=_.attribValue,R(_,"onattribute",{name:_.attribName,value:_.attribValue});_.attribName=_.attribValue=""}function Rn(_,m){if(_.opt.xmlns){var x=_.tag,A=as(_.tagName);x.prefix=A.prefix,x.local=A.local,x.uri=x.ns[A.prefix]||"",x.prefix&&!x.uri&&(q(_,"Unbound namespace prefix: "+JSON.stringify(_.tagName)),x.uri=A.prefix);var re=_.tags[_.tags.length-1]||_;x.ns&&re.ns!==x.ns&&Object.keys(x.ns).forEach(function(uu){R(_,"onopennamespace",{prefix:uu,uri:x.ns[uu]})});for(var Ce=0,Ae=_.attribList.length;Ce<Ae;Ce++){var qe=_.attribList[Ce],vt=qe[0],cr=qe[1],Me=as(vt,!0),Zt=Me.prefix,gy=Me.local,lu=Zt===""?"":x.ns[Zt]||"",Gi={name:vt,value:cr,prefix:Zt,local:gy,uri:lu};Zt&&Zt!=="xmlns"&&!lu&&(q(_,"Unbound namespace prefix: "+JSON.stringify(Zt)),Gi.uri=Zt),_.tag.attributes[vt]=Gi,R(_,"onattribute",Gi)}_.attribList.length=0}_.tag.isSelfClosing=!!m,_.sawRoot=!0,_.tags.push(_.tag),R(_,"onopentag",_.tag),m||(!_.noscript&&_.tagName.toLowerCase()==="script"?_.state=y.SCRIPT:_.state=y.TEXT,_.tag=null,_.tagName=""),_.attribName=_.attribValue="",_.attribList.length=0}function Vi(_){if(!_.tagName){q(_,"Weird empty close tag."),_.textNode+="</>",_.state=y.TEXT;return}if(_.script){if(_.tagName!=="script"){_.script+="</"+_.tagName+">",_.tagName="",_.state=y.SCRIPT;return}R(_,"onscript",_.script),_.script=""}var m=_.tags.length,x=_.tagName;_.strict||(x=x[_.looseCase]());for(var A=x;m--;){var re=_.tags[m];if(re.name!==A)q(_,"Unexpected close tag");else break}if(m<0){q(_,"Unmatched closing tag: "+_.tagName),_.textNode+="</"+_.tagName+">",_.state=y.TEXT;return}_.tagName=x;for(var Ce=_.tags.length;Ce-- >m;){var Ae=_.tag=_.tags.pop();_.tagName=_.tag.name,R(_,"onclosetag",_.tagName);var qe={};for(var vt in Ae.ns)qe[vt]=Ae.ns[vt];var cr=_.tags[_.tags.length-1]||_;_.opt.xmlns&&Ae.ns!==cr.ns&&Object.keys(Ae.ns).forEach(function(Me){var Zt=Ae.ns[Me];R(_,"onclosenamespace",{prefix:Me,uri:Zt})})}m===0&&(_.closedRoot=!0),_.tagName=_.attribValue=_.attribName="",_.attribList.length=0,_.state=y.TEXT}function iu(_){var m=_.entity,x=m.toLowerCase(),A,re="";return _.ENTITIES[m]?_.ENTITIES[m]:_.ENTITIES[x]?_.ENTITIES[x]:(m=x,m.charAt(0)==="#"&&(m.charAt(1)==="x"?(m=m.slice(2),A=parseInt(m,16),re=A.toString(16)):(m=m.slice(1),A=parseInt(m,10),re=A.toString(10))),m=m.replace(/^0+/,""),isNaN(A)||re.toLowerCase()!==m?(q(_,"Invalid character entity"),"&"+_.entity+";"):String.fromCodePoint(A))}function ou(_,m){m==="<"?(_.state=y.OPEN_WAKA,_.startTagPosition=_.position):v(m)||(q(_,"Non-whitespace before first tag."),_.textNode=m,_.state=y.TEXT)}function cu(_,m){var x="";return m<_.length&&(x=_.charAt(m)),x}function my(_){var m=this;if(this.error)throw this.error;if(m.closed)return fe(m,"Cannot write after close. Assign an onready handler.");if(_===null)return or(m);typeof _=="object"&&(_=_.toString());for(var x=0,A="";A=cu(_,x++),m.c=A,!!A;)switch(m.trackPosition&&(m.position++,A===`
141
- `?(m.line++,m.column=0):m.column++),m.state){case y.BEGIN:if(m.state=y.BEGIN_WHITESPACE,A==="\uFEFF")continue;ou(m,A);continue;case y.BEGIN_WHITESPACE:ou(m,A);continue;case y.TEXT:if(m.sawRoot&&!m.closedRoot){for(var re=x-1;A&&A!=="<"&&A!=="&";)A=cu(_,x++),A&&m.trackPosition&&(m.position++,A===`
142
- `?(m.line++,m.column=0):m.column++);m.textNode+=_.substring(re,x-1)}A==="<"&&!(m.sawRoot&&m.closedRoot&&!m.strict)?(m.state=y.OPEN_WAKA,m.startTagPosition=m.position):(!v(A)&&(!m.sawRoot||m.closedRoot)&&q(m,"Text data outside of root node."),A==="&"?m.state=y.TEXT_ENTITY:m.textNode+=A);continue;case y.SCRIPT:A==="<"?m.state=y.SCRIPT_ENDING:m.script+=A;continue;case y.SCRIPT_ENDING:A==="/"?m.state=y.CLOSE_TAG:(m.script+="<"+A,m.state=y.SCRIPT);continue;case y.OPEN_WAKA:if(A==="!")m.state=y.SGML_DECL,m.sgmlDecl="";else if(!v(A))if(O(g,A))m.state=y.OPEN_TAG,m.tagName=A;else if(A==="/")m.state=y.CLOSE_TAG,m.tagName="";else if(A==="?")m.state=y.PROC_INST,m.procInstName=m.procInstBody="";else{if(q(m,"Unencoded <"),m.startTagPosition+1<m.position){var Ce=m.position-m.startTagPosition;A=new Array(Ce).join(" ")+A}m.textNode+="<"+A,m.state=y.TEXT}continue;case y.SGML_DECL:(m.sgmlDecl+A).toUpperCase()===u?(R(m,"onopencdata"),m.state=y.CDATA,m.sgmlDecl="",m.cdata=""):m.sgmlDecl+A==="--"?(m.state=y.COMMENT,m.comment="",m.sgmlDecl=""):(m.sgmlDecl+A).toUpperCase()===d?(m.state=y.DOCTYPE,(m.doctype||m.sawRoot)&&q(m,"Inappropriately located doctype declaration"),m.doctype="",m.sgmlDecl=""):A===">"?(R(m,"onsgmldeclaration",m.sgmlDecl),m.sgmlDecl="",m.state=y.TEXT):(T(A)&&(m.state=y.SGML_DECL_QUOTED),m.sgmlDecl+=A);continue;case y.SGML_DECL_QUOTED:A===m.q&&(m.state=y.SGML_DECL,m.q=""),m.sgmlDecl+=A;continue;case y.DOCTYPE:A===">"?(m.state=y.TEXT,R(m,"ondoctype",m.doctype),m.doctype=!0):(m.doctype+=A,A==="["?m.state=y.DOCTYPE_DTD:T(A)&&(m.state=y.DOCTYPE_QUOTED,m.q=A));continue;case y.DOCTYPE_QUOTED:m.doctype+=A,A===m.q&&(m.q="",m.state=y.DOCTYPE);continue;case y.DOCTYPE_DTD:m.doctype+=A,A==="]"?m.state=y.DOCTYPE:T(A)&&(m.state=y.DOCTYPE_DTD_QUOTED,m.q=A);continue;case y.DOCTYPE_DTD_QUOTED:m.doctype+=A,A===m.q&&(m.state=y.DOCTYPE_DTD,m.q="");continue;case y.COMMENT:A==="-"?m.state=y.COMMENT_ENDING:m.comment+=A;continue;case y.COMMENT_ENDING:A==="-"?(m.state=y.COMMENT_ENDED,m.comment=ce(m.opt,m.comment),m.comment&&R(m,"oncomment",m.comment),m.comment=""):(m.comment+="-"+A,m.state=y.COMMENT);continue;case y.COMMENT_ENDED:A!==">"?(q(m,"Malformed comment"),m.comment+="--"+A,m.state=y.COMMENT):m.state=y.TEXT;continue;case y.CDATA:A==="]"?m.state=y.CDATA_ENDING:m.cdata+=A;continue;case y.CDATA_ENDING:A==="]"?m.state=y.CDATA_ENDING_2:(m.cdata+="]"+A,m.state=y.CDATA);continue;case y.CDATA_ENDING_2:A===">"?(m.cdata&&R(m,"oncdata",m.cdata),R(m,"onclosecdata"),m.cdata="",m.state=y.TEXT):A==="]"?m.cdata+="]":(m.cdata+="]]"+A,m.state=y.CDATA);continue;case y.PROC_INST:A==="?"?m.state=y.PROC_INST_ENDING:v(A)?m.state=y.PROC_INST_BODY:m.procInstName+=A;continue;case y.PROC_INST_BODY:if(!m.procInstBody&&v(A))continue;A==="?"?m.state=y.PROC_INST_ENDING:m.procInstBody+=A;continue;case y.PROC_INST_ENDING:A===">"?(R(m,"onprocessinginstruction",{name:m.procInstName,body:m.procInstBody}),m.procInstName=m.procInstBody="",m.state=y.TEXT):(m.procInstBody+="?"+A,m.state=y.PROC_INST_BODY);continue;case y.OPEN_TAG:O(b,A)?m.tagName+=A:(zi(m),A===">"?Rn(m):A==="/"?m.state=y.OPEN_TAG_SLASH:(v(A)||q(m,"Invalid character in tag name"),m.state=y.ATTRIB));continue;case y.OPEN_TAG_SLASH:A===">"?(Rn(m,!0),Vi(m)):(q(m,"Forward-slash in opening tag not followed by >"),m.state=y.ATTRIB);continue;case y.ATTRIB:if(v(A))continue;A===">"?Rn(m):A==="/"?m.state=y.OPEN_TAG_SLASH:O(g,A)?(m.attribName=A,m.attribValue="",m.state=y.ATTRIB_NAME):q(m,"Invalid attribute name");continue;case y.ATTRIB_NAME:A==="="?m.state=y.ATTRIB_VALUE:A===">"?(q(m,"Attribute without value"),m.attribValue=m.attribName,Hi(m),Rn(m)):v(A)?m.state=y.ATTRIB_NAME_SAW_WHITE:O(b,A)?m.attribName+=A:q(m,"Invalid attribute name");continue;case y.ATTRIB_NAME_SAW_WHITE:if(A==="=")m.state=y.ATTRIB_VALUE;else{if(v(A))continue;q(m,"Attribute without value"),m.tag.attributes[m.attribName]="",m.attribValue="",R(m,"onattribute",{name:m.attribName,value:""}),m.attribName="",A===">"?Rn(m):O(g,A)?(m.attribName=A,m.state=y.ATTRIB_NAME):(q(m,"Invalid attribute name"),m.state=y.ATTRIB)}continue;case y.ATTRIB_VALUE:if(v(A))continue;T(A)?(m.q=A,m.state=y.ATTRIB_VALUE_QUOTED):(q(m,"Unquoted attribute value"),m.state=y.ATTRIB_VALUE_UNQUOTED,m.attribValue=A);continue;case y.ATTRIB_VALUE_QUOTED:if(A!==m.q){A==="&"?m.state=y.ATTRIB_VALUE_ENTITY_Q:m.attribValue+=A;continue}Hi(m),m.q="",m.state=y.ATTRIB_VALUE_CLOSED;continue;case y.ATTRIB_VALUE_CLOSED:v(A)?m.state=y.ATTRIB:A===">"?Rn(m):A==="/"?m.state=y.OPEN_TAG_SLASH:O(g,A)?(q(m,"No whitespace between attributes"),m.attribName=A,m.attribValue="",m.state=y.ATTRIB_NAME):q(m,"Invalid attribute name");continue;case y.ATTRIB_VALUE_UNQUOTED:if(!k(A)){A==="&"?m.state=y.ATTRIB_VALUE_ENTITY_U:m.attribValue+=A;continue}Hi(m),A===">"?Rn(m):m.state=y.ATTRIB;continue;case y.CLOSE_TAG:if(m.tagName)A===">"?Vi(m):O(b,A)?m.tagName+=A:m.script?(m.script+="</"+m.tagName,m.tagName="",m.state=y.SCRIPT):(v(A)||q(m,"Invalid tagname in closing tag"),m.state=y.CLOSE_TAG_SAW_WHITE);else{if(v(A))continue;C(g,A)?m.script?(m.script+="</"+A,m.state=y.SCRIPT):q(m,"Invalid tagname in closing tag."):m.tagName=A}continue;case y.CLOSE_TAG_SAW_WHITE:if(v(A))continue;A===">"?Vi(m):q(m,"Invalid characters in closing tag");continue;case y.TEXT_ENTITY:case y.ATTRIB_VALUE_ENTITY_Q:case y.ATTRIB_VALUE_ENTITY_U:var Ae,qe;switch(m.state){case y.TEXT_ENTITY:Ae=y.TEXT,qe="textNode";break;case y.ATTRIB_VALUE_ENTITY_Q:Ae=y.ATTRIB_VALUE_QUOTED,qe="attribValue";break;case y.ATTRIB_VALUE_ENTITY_U:Ae=y.ATTRIB_VALUE_UNQUOTED,qe="attribValue";break}if(A===";")if(m.opt.unparsedEntities){var vt=iu(m);m.entity="",m.state=Ae,m.write(vt)}else m[qe]+=iu(m),m.entity="",m.state=Ae;else O(m.entity.length?w:S,A)?m.entity+=A:(q(m,"Invalid character in entity name"),m[qe]+="&"+m.entity+A,m.entity="",m.state=Ae);continue;default:throw new Error(m,"Unknown state: "+m.state)}return m.position>=m.bufferCheckPosition&&r(m),m}return String.fromCodePoint||(function(){var _=String.fromCharCode,m=Math.floor,x=function(){var A=16384,re=[],Ce,Ae,qe=-1,vt=arguments.length;if(!vt)return"";for(var cr="";++qe<vt;){var Me=Number(arguments[qe]);if(!isFinite(Me)||Me<0||Me>1114111||m(Me)!==Me)throw RangeError("Invalid code point: "+Me);Me<=65535?re.push(Me):(Me-=65536,Ce=(Me>>10)+55296,Ae=Me%1024+56320,re.push(Ce,Ae)),(qe+1===vt||re.length>A)&&(cr+=_.apply(null,re),re.length=0)}return cr};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:x,configurable:!0,writable:!0}):String.fromCodePoint=x})(),e},jA=LA(),yc=`The output should be formatted as a XML file.
143
- 1. Output should conform to the tags below.
144
- 2. If tags are not given, make them on your own.
145
- 3. Remember to always open and close all the tags.
146
-
147
- As an example, for the tags ["foo", "bar", "baz"]:
148
- 1. String "<foo>
149
- <bar>
150
- <baz></baz>
151
- </bar>
152
- </foo>" is a well-formatted instance of the schema.
153
- 2. String "<foo>
154
- <bar>
155
- </foo>" is a badly-formatted instance.
156
- 3. String "<foo>
157
- <tag>
158
- </tag>
159
- </foo>" is a badly-formatted instance.
160
-
161
- Here are the output tags:
162
- \`\`\`
163
- {tags}
164
- \`\`\``;var DA=class extends na{tags;constructor(e){super(e),this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(e,t){if(t)return e?Oi(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return _c(e[0].text)}async parse(e){return _c(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?yc.replace("{tags}",this.tags?.join(", ")??""):yc}};const FA=e=>e.split(`
165
- `).map(t=>t.replace(/^\s+/,"")).join(`
166
- `).trim(),mm=e=>{if(Object.keys(e).length===0)return{};const t={};return e.children.length>0?(t[e.name]=e.children.map(mm),t):(t[e.name]=e.text??void 0,t)};function _c(e){const t=FA(e),n=jA.parser(!0);let r={};const s=[];n.onopentag=o=>{const c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};s.length>0?s[s.length-1].children.push(c):r=c,o.isSelfClosing||s.push(c)},n.onclosetag=()=>{if(s.length>0){const o=s.pop();s.length===0&&o&&(r=o)}},n.ontext=o=>{if(s.length>0){const c=s[s.length-1];c.text+=o}},n.onattribute=o=>{if(s.length>0){const c=s[s.length-1];c.attributes[o.name]=o.value}};const a=/```(xml)?(.*)```/s.exec(t),i=a?a[2]:t;return n.write(i).close(),r&&r.name==="?xml"&&(r=r.children[0]),mm(r)}var gm={};U(gm,{AsymmetricStructuredOutputParser:()=>RA,BaseCumulativeTransformOutputParser:()=>na,BaseLLMOutputParser:()=>ji,BaseOutputParser:()=>ea,BaseTransformOutputParser:()=>ta,BytesOutputParser:()=>OA,CommaSeparatedListOutputParser:()=>xA,CustomListOutputParser:()=>IA,JsonMarkdownStructuredOutputParser:()=>fm,JsonOutputParser:()=>$A,ListOutputParser:()=>ra,MarkdownListOutputParser:()=>NA,NumberedListOutputParser:()=>PA,OutputParserException:()=>on,StringOutputParser:()=>MA,StructuredOutputParser:()=>pm,XMLOutputParser:()=>DA,XML_FORMAT_INSTRUCTIONS:()=>yc,parseJsonMarkdown:()=>Bo,parsePartialJson:()=>Br,parseXMLMarkdown:()=>_c});function ym(e,t){if(e.function===void 0)return;let n;if(t?.partial)try{n=Br(e.function.arguments??"{}")}catch{return}else try{n=JSON.parse(e.function.arguments)}catch(s){throw new on([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${s.message}`].join(`
167
- `))}const r={name:e.function.name,args:n,type:"tool_call"};return t?.returnId&&(r.id=e.id),r}function UA(e){if(e.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}}function BA(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}var _m=class extends na{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(e){super(e),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){const n=e[0].message;let r;if(nl(n)&&n.tool_calls?.length?r=n.tool_calls.map(a=>{const{id:i,...o}=a;return this.returnId?{id:i,...o}:o}):n.additional_kwargs.tool_calls!==void 0&&(r=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(i=>ym(i,{returnId:this.returnId,partial:t}))),!r)return[];const s=[];for(const a of r)if(a!==void 0){const i={type:a.name,args:a.args,id:a.id};s.push(i)}return s}},zA=class extends _m{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;const t=await cl(this.zodSchema,e);if(t.success)return t.data;throw new on(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const n=(await super.parsePartialResult(e)).filter(s=>s.type===this.keyName);let r=n;if(n.length)return this.returnId||(r=n.map(s=>s.args)),this.returnSingle?r[0]:r}async parseResult(e){const n=(await super.parsePartialResult(e,!1)).filter(a=>a.type===this.keyName);let r=n;return n.length?(this.returnId||(r=n.map(a=>a.args)),this.returnSingle?this._validateResult(r[0]):await Promise.all(r.map(a=>this._validateResult(a)))):void 0}},wm={};U(wm,{JsonOutputKeyToolsParser:()=>zA,JsonOutputToolsParser:()=>_m,convertLangChainToolCallToOpenAI:()=>UA,makeInvalidToolCall:()=>BA,parseToolCall:()=>ym});var vm=class extends ji{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if("message"in e[0]){const n=e[0].message.additional_kwargs.function_call;if(!n)throw new Error(`No function_call in message ${JSON.stringify(e)}`);if(!n.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?n.arguments:JSON.stringify(n)}else throw new Error(`No message in generations ${JSON.stringify(e)}`)}},bm=class extends na{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new vm(e)}_diff(e,t){return t?Oi(e??{},t):void 0}async parsePartialResult(e){const t=e[0];if(!t.message)return;const{message:n}=t,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?Br(r.arguments):{...r,arguments:Br(r.arguments)}}async parseResult(e){const t=await this.outputParser.parseResult(e);if(!t)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){const t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return""}},HA=class extends ji{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new bm;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},Sm={};U(Sm,{JsonKeyOutputFunctionsParser:()=>HA,JsonOutputFunctionsParser:()=>bm,OutputFunctionsParser:()=>vm});var sa=class extends J{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);const{inputVariables:t}=e;if(t.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){const t=this.partialVariables??{},n={};for(const[s,a]of Object.entries(t))typeof a=="string"?n[s]=a:n[s]=await a();return{...n,...e}}async invoke(e,t){const n={...this.metadata,...t?.metadata},r=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),e,{...t,tags:r,metadata:n,runType:"prompt"})}},Fs=class extends sa{async formatPromptValue(e){const t=await this.format(e);return new gl(t)}};var VA=Object.prototype.toString,ss=Array.isArray||function(t){return VA.call(t)==="[object Array]"};function Ul(e){return typeof e=="function"}function GA(e){return ss(e)?"array":typeof e}function So(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Od(e,t){return e!=null&&typeof e=="object"&&t in e}function WA(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var JA=RegExp.prototype.test;function KA(e,t){return JA.call(e,t)}var ZA=/\S/;function qA(e){return!KA(ZA,e)}var YA={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function XA(e){return String(e).replace(/[&<>"'`=\/]/g,function(n){return YA[n]})}var QA=/\s*/,ek=/\s+/,xd=/\s*=/,tk=/\s*\}/,nk=/#|\^|\/|>|\{|&|=|!/;function rk(e,t){if(!e)return[];var n=!1,r=[],s=[],a=[],i=!1,o=!1,c="",l=0;function u(){if(i&&!o)for(;a.length;)delete s[a.pop()];else a=[];i=!1,o=!1}var d,h,p;function f(y){if(typeof y=="string"&&(y=y.split(ek,2)),!ss(y)||y.length!==2)throw new Error("Invalid tags: "+y);d=new RegExp(So(y[0])+"\\s*"),h=new RegExp("\\s*"+So(y[1])),p=new RegExp("\\s*"+So("}"+y[1]))}f(t||lt.tags);for(var g=new aa(e),b,S,w,v,T,k;!g.eos();){if(b=g.pos,w=g.scanUntil(d),w)for(var O=0,C=w.length;O<C;++O)v=w.charAt(O),qA(v)?(a.push(s.length),c+=v):(o=!0,n=!0,c+=" "),s.push(["text",v,b,b+1]),b+=1,v===`
168
- `&&(u(),c="",l=0,n=!1);if(!g.scan(d))break;if(i=!0,S=g.scan(nk)||"name",g.scan(QA),S==="="?(w=g.scanUntil(xd),g.scan(xd),g.scanUntil(h)):S==="{"?(w=g.scanUntil(p),g.scan(tk),g.scanUntil(h),S="&"):w=g.scanUntil(h),!g.scan(h))throw new Error("Unclosed tag at "+g.pos);if(S==">"?T=[S,w,b,g.pos,c,l,n]:T=[S,w,b,g.pos],l++,s.push(T),S==="#"||S==="^")r.push(T);else if(S==="/"){if(k=r.pop(),!k)throw new Error('Unopened section "'+w+'" at '+b);if(k[1]!==w)throw new Error('Unclosed section "'+k[1]+'" at '+b)}else S==="name"||S==="{"||S==="&"?o=!0:S==="="&&f(w)}if(u(),k=r.pop(),k)throw new Error('Unclosed section "'+k[1]+'" at '+g.pos);return ak(sk(s))}function sk(e){for(var t=[],n,r,s=0,a=e.length;s<a;++s)n=e[s],n&&(n[0]==="text"&&r&&r[0]==="text"?(r[1]+=n[1],r[3]=n[3]):(t.push(n),r=n));return t}function ak(e){for(var t=[],n=t,r=[],s,a,i=0,o=e.length;i<o;++i)switch(s=e[i],s[0]){case"#":case"^":n.push(s),r.push(s),n=s[4]=[];break;case"/":a=r.pop(),a[5]=s[2],n=r.length>0?r[r.length-1][4]:t;break;default:n.push(s)}return t}function aa(e){this.string=e,this.tail=e,this.pos=0}aa.prototype.eos=function(){return this.tail===""};aa.prototype.scan=function(t){var n=this.tail.match(t);if(!n||n.index!==0)return"";var r=n[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};aa.prototype.scanUntil=function(t){var n=this.tail.search(t),r;switch(n){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=r.length,r};function Kr(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Kr.prototype.push=function(t){return new Kr(t,this)};Kr.prototype.lookup=function(t){var n=this.cache,r;if(n.hasOwnProperty(t))r=n[t];else{for(var s=this,a,i,o,c=!1;s;){if(t.indexOf(".")>0)for(a=s.view,i=t.split("."),o=0;a!=null&&o<i.length;)o===i.length-1&&(c=Od(a,i[o])||WA(a,i[o])),a=a[i[o++]];else a=s.view[t],c=Od(s.view,t);if(c){r=a;break}s=s.parent}n[t]=r}return Ul(r)&&(r=r.call(this.view)),r};function Ze(){this.templateCache={_cache:{},set:function(t,n){this._cache[t]=n},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}Ze.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Ze.prototype.parse=function(t,n){var r=this.templateCache,s=t+":"+(n||lt.tags).join(":"),a=typeof r<"u",i=a?r.get(s):void 0;return i==null&&(i=rk(t,n),a&&r.set(s,i)),i};Ze.prototype.render=function(t,n,r,s){var a=this.getConfigTags(s),i=this.parse(t,a),o=n instanceof Kr?n:new Kr(n,void 0);return this.renderTokens(i,o,r,t,s)};Ze.prototype.renderTokens=function(t,n,r,s,a){for(var i="",o,c,l,u=0,d=t.length;u<d;++u)l=void 0,o=t[u],c=o[0],c==="#"?l=this.renderSection(o,n,r,s,a):c==="^"?l=this.renderInverted(o,n,r,s,a):c===">"?l=this.renderPartial(o,n,r,a):c==="&"?l=this.unescapedValue(o,n):c==="name"?l=this.escapedValue(o,n,a):c==="text"&&(l=this.rawValue(o)),l!==void 0&&(i+=l);return i};Ze.prototype.renderSection=function(t,n,r,s,a){var i=this,o="",c=n.lookup(t[1]);function l(h){return i.render(h,n,r,a)}if(c){if(ss(c))for(var u=0,d=c.length;u<d;++u)o+=this.renderTokens(t[4],n.push(c[u]),r,s,a);else if(typeof c=="object"||typeof c=="string"||typeof c=="number")o+=this.renderTokens(t[4],n.push(c),r,s,a);else if(Ul(c)){if(typeof s!="string")throw new Error("Cannot use higher-order sections without the original template");c=c.call(n.view,s.slice(t[3],t[5]),l),c!=null&&(o+=c)}else o+=this.renderTokens(t[4],n,r,s,a);return o}};Ze.prototype.renderInverted=function(t,n,r,s,a){var i=n.lookup(t[1]);if(!i||ss(i)&&i.length===0)return this.renderTokens(t[4],n,r,s,a)};Ze.prototype.indentPartial=function(t,n,r){for(var s=n.replace(/[^ \t]/g,""),a=t.split(`
169
- `),i=0;i<a.length;i++)a[i].length&&(i>0||!r)&&(a[i]=s+a[i]);return a.join(`
170
- `)};Ze.prototype.renderPartial=function(t,n,r,s){if(r){var a=this.getConfigTags(s),i=Ul(r)?r(t[1]):r[t[1]];if(i!=null){var o=t[6],c=t[5],l=t[4],u=i;c==0&&l&&(u=this.indentPartial(i,l,o));var d=this.parse(u,a);return this.renderTokens(d,n,r,u,s)}}};Ze.prototype.unescapedValue=function(t,n){var r=n.lookup(t[1]);if(r!=null)return r};Ze.prototype.escapedValue=function(t,n,r){var s=this.getConfigEscape(r)||lt.escape,a=n.lookup(t[1]);if(a!=null)return typeof a=="number"&&s===lt.escape?String(a):s(a)};Ze.prototype.rawValue=function(t){return t[1]};Ze.prototype.getConfigTags=function(t){return ss(t)?t:t&&typeof t=="object"?t.tags:void 0};Ze.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!ss(t))return t.escape};var lt={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){Us.templateCache=e},get templateCache(){return Us.templateCache}},Us=new Ze;lt.clearCache=function(){return Us.clearCache()};lt.parse=function(t,n){return Us.parse(t,n)};lt.render=function(t,n,r,s){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+GA(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Us.render(t,n,r,s)};lt.escape=XA;lt.Scanner=aa;lt.Context=Kr;lt.Writer=Ze;function Tm(){lt.escape=e=>e}const Bs=e=>{const t=e.split(""),n=[],r=(a,i)=>{for(let o=i;o<t.length;o+=1)if(a.includes(t[o]))return o;return-1};let s=0;for(;s<t.length;)if(t[s]==="{"&&s+1<t.length&&t[s+1]==="{")n.push({type:"literal",text:"{"}),s+=2;else if(t[s]==="}"&&s+1<t.length&&t[s+1]==="}")n.push({type:"literal",text:"}"}),s+=2;else if(t[s]==="{"){const a=r("}",s);if(a<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:t.slice(s+1,a).join("")}),s=a+1}else{if(t[s]==="}")throw new Error("Single '}' in template.");{const a=r("{}",s),i=(a<0?t.slice(s):t.slice(s,a)).join("");n.push({type:"literal",text:i}),s=a<0?t.length:a}}return n},Em=(e,t=[])=>{const n=[];for(const r of e)if(r[0]==="name"){const s=r[1].includes(".")?r[1].split(".")[0]:r[1];n.push({type:"variable",name:s})}else if(["#","&","^",">"].includes(r[0])){if(n.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){const s=[...t,r[1]],a=Em(r[4],s);n.push(...a)}}else n.push({type:"literal",text:r[1]});return n},si=e=>{Tm();const t=lt.parse(e);return Em(t)},Cm=(e,t)=>Bs(e).reduce((n,r)=>{if(r.type==="variable"){if(r.name in t){const s=typeof t[r.name]=="string"?t[r.name]:JSON.stringify(t[r.name]);return n+s}throw new Error(`(f-string) Missing value for input ${r.name}`)}return n+r.text},""),Am=(e,t)=>(Tm(),lt.render(e,t)),ai={"f-string":Cm,mustache:Am},km={"f-string":Bs,mustache:si},Dt=(e,t,n)=>{try{return ai[t](e,n)}catch(r){throw Si(r,"INVALID_PROMPT_INPUT")}},ii=(e,t)=>km[t](e),ia=(e,t,n)=>{if(!(t in ai)){const r=Object.keys(ai);throw new Error(`Invalid template format. Got \`${t}\`;
171
- should be one of ${r}`)}try{const r=n.reduce((s,a)=>(s[a]="foo",s),{});Array.isArray(e)?e.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")Dt(s.text,t,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")Dt(s.image_url,t,r);else if(typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"){const a=s.image_url.url;Dt(a,t,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):Dt(e,t,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var En=class ds extends Fs{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(t){if(super(t),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),ia(this.template,this.templateFormat,n)}}_getPromptType(){return"prompt"}async format(t){const n=await this.mergePartialAndUserVariables(t);return Dt(this.template,this.templateFormat,n)}static fromExamples(t,n,r,s=`
172
-
173
- `,a=""){const i=[a,...t,n].join(s);return new ds({inputVariables:r,template:i})}static fromTemplate(t,n){const{templateFormat:r="f-string",...s}=n??{},a=new Set;return ii(t,r).forEach(i=>{i.type==="variable"&&a.add(i.name)}),new ds({inputVariables:[...a],templateFormat:r,template:t,...s})}async partial(t){const n=this.inputVariables.filter(a=>!(a in t)),r={...this.partialVariables??{},...t},s={...this,inputVariables:n,partialVariables:r};return new ds(s)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(t){if(!t.template)throw new Error("Prompt template must have a template");return new ds({inputVariables:t.input_variables,template:t.template,templateFormat:t.template_format})}},Ca=class Om extends sa{static lc_name(){return"ImagePromptTemplate"}lc_namespace=["langchain_core","prompts","image"];template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(t){if(super(t),this.template=t.template,this.templateFormat=t.templateFormat??this.templateFormat,this.validateTemplate=t.validateTemplate??this.validateTemplate,this.additionalContentFields=t.additionalContentFields,this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),ia([{type:"image_url",image_url:this.template}],this.templateFormat,n)}}_getPromptType(){return"prompt"}async partial(t){const n=this.inputVariables.filter(a=>!(a in t)),r={...this.partialVariables??{},...t},s={...this,inputVariables:n,partialVariables:r};return new Om(s)}async format(t){const n={};for(const[i,o]of Object.entries(this.template))typeof o=="string"?n[i]=Dt(o,this.templateFormat,t):n[i]=o;const r=t.url||n.url,s=t.detail||n.detail;if(!r)throw new Error("Must provide either an image URL.");if(typeof r!="string")throw new Error("url must be a string.");const a={url:r};return s&&(a.detail=s),a}async formatPromptValue(t){const n=await this.format(t);return new Jp(n)}},wc=class extends J{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(e){const t=e.templateFormat??"f-string",n=vc(e.template,t);super({inputVariables:n,...e}),this.template=e.template,this.templateFormat=t,this.inputVariables=n}async format(e){return bc(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}};function vc(e,t){const n=[];for(const r of Object.values(e))if(typeof r=="string")ii(r,t).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?ii(s,t).forEach(a=>{a.type==="variable"&&n.push(a.name)}):typeof s=="object"&&n.push(...vc(s,t));else typeof r=="object"&&r!==null&&n.push(...vc(r,t));return Array.from(new Set(n))}function bc(e,t,n){const r={};for(const[s,a]of Object.entries(e))if(typeof a=="string")r[s]=Dt(a,n,t);else if(Array.isArray(a)){const i=[];for(const o of a)typeof o=="string"?i.push(Dt(o,n,t)):typeof o=="object"&&i.push(bc(o,t,n));r[s]=i}else typeof a=="object"&&a!==null?r[s]=bc(a,t,n):r[s]=a;return r}var Di=class extends J{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(e,t){return this._callWithConfig(n=>this.formatMessages(n),e,{...t,runType:"prompt"})}},Sc=class extends Di{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(e){typeof e=="string"&&(e={variableName:e}),super(e),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){const t=e[this.variableName];if(this.optional&&!t)return[];if(!t){const r=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw r.name="InputFormatError",r}let n;try{Array.isArray(t)?n=t.map(Gt):n=[Gt(t)]}catch(r){const s=typeof t=="string"?t:JSON.stringify(t,null,2),a=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${s}`,`Additional message: ${r.message}`].join(`
174
-
175
- `));throw a.name="InputFormatError",a.lc_error_code=r.lc_error_code,a}return n}},xm=class extends Di{prompt;constructor(e){"prompt"in e||(e={prompt:e}),super(e),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},Bl=class extends sa{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){const t=await this.formatMessages(e);return new yl(t)}},Im=class extends xm{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(e,t){"prompt"in e||(e={prompt:e,role:t}),super(e),this.role=e.role}async format(e){return new Xn(await this.prompt.format(e),this.role)}static fromTemplate(e,t,n){return new this(En.fromTemplate(e,{templateFormat:n?.templateFormat}),t)}};function ik(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.keys(e).length===1&&"text"in e&&typeof e.text=="string"}function ok(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:"image_url"in e&&(typeof e.image_url=="string"||typeof e.image_url=="object"&&e.image_url!==null&&"url"in e.image_url&&typeof e.image_url.url=="string")}var zl=class extends Di{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}chatMessageClass;constructor(e,t){if("prompt"in e||(e={prompt:e}),super(e),this.prompt=e.prompt,Array.isArray(this.prompt)){let n=[];this.prompt.forEach(r=>{"inputVariables"in r&&(n=n.concat(r.inputVariables))}),this.inputVariables=n}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){const t=this.constructor;if(t._messageClass()){const n=t._messageClass();return new n({content:e})}else if(t.chatMessageClass){const n=t.chatMessageClass();return new n({content:e,role:this.getRoleFromMessageClass(n.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,t){if(typeof e=="string")return new this(En.fromTemplate(e,t));const n=[];for(const r of e)if(typeof r=="string")n.push(En.fromTemplate(r,t));else if(r!==null)if(ik(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const a={...t,additionalContentFields:r};n.push(En.fromTemplate(s,a))}else if(ok(r)){let s=r.image_url??"",a,i=[];if(typeof s=="string"){let o;t?.templateFormat==="mustache"?o=si(s):o=Bs(s);const c=o.flatMap(l=>l.type==="variable"?[l.name]:[]);if((c?.length??0)>0){if(c.length>1)throw new Error(`Only one format variable allowed per image template.
176
- Got: ${c}
177
- From: ${s}`);i=[c[0]]}else i=[];s={url:s},a=new Ca({template:s,inputVariables:i,templateFormat:t?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let o;t?.templateFormat==="mustache"?o=si(s.url):o=Bs(s.url),i=o.flatMap(c=>c.type==="variable"?[c.name]:[])}else i=[];a=new Ca({template:s,inputVariables:i,templateFormat:t?.templateFormat,additionalContentFields:r})}else throw new Error("Invalid image template");n.push(a)}else typeof r=="object"&&n.push(new wc({template:r,templateFormat:t?.templateFormat}));return new this({prompt:n,additionalOptions:t})}async format(e){if(this.prompt instanceof Fs){const t=await this.prompt.format(e);return this.createMessage(t)}else{const t=[];for(const n of this.prompt){let r={};if(!("inputVariables"in n))throw new Error(`Prompt ${n} does not have inputVariables defined.`);for(const s of n.inputVariables)r||(r={[s]:e[s]}),r={...r,[s]:e[s]};if(n instanceof Fs){const s=await n.format(r);let a;"additionalContentFields"in n&&(a=n.additionalContentFields),s!==""&&t.push({...a,type:"text",text:s})}else if(n instanceof Ca){const s=await n.format(r);let a;"additionalContentFields"in n&&(a=n.additionalContentFields),t.push({...a,type:"image_url",image_url:s})}else if(n instanceof wc){const s=await n.format(r);let a;"additionalContentFields"in n&&(a=n.additionalContentFields),t.push({...a,...s})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}},Hl=class extends zl{static _messageClass(){return he}static lc_name(){return"HumanMessagePromptTemplate"}},Pm=class extends zl{static _messageClass(){return D}static lc_name(){return"AIMessagePromptTemplate"}},Nm=class extends zl{static _messageClass(){return Se}static lc_name(){return"SystemMessagePromptTemplate"}};function ck(e){return typeof e.formatMessages=="function"}function lk(e,t){if(ck(e)||Pe(e))return e;if(Array.isArray(e)&&e[0]==="placeholder"){const s=e[1];if(t?.templateFormat==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}"){const a=s.slice(2,-2);return new Sc({variableName:a,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const a=s.slice(1,-1);return new Sc({variableName:a,optional:!0})}throw new Error(`Invalid placeholder template for format ${t?.templateFormat??'"f-string"'}: "${e[1]}". Expected a variable name surrounded by ${t?.templateFormat==="mustache"?"double":"single"} curly braces.`)}const n=Gt(e);let r;if(typeof n.content=="string"?r=n.content:r=n.content.map(s=>"text"in s?{...s,text:s.text}:"image_url"in s?{...s,image_url:s.image_url}:s),n._getType()==="human")return Hl.fromTemplate(r,t);if(n._getType()==="ai")return Pm.fromTemplate(r,t);if(n._getType()==="system")return Nm.fromTemplate(r,t);if(Xn.isInstance(n))return Im.fromTemplate(n.content,n.role,t);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function uk(e){return e.constructor.lc_name()==="MessagesPlaceholder"}var Vl=class Aa extends Bl{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(t){if(super(t),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){const n=new Set;for(const o of this.promptMessages)if(!(o instanceof rt))for(const c of o.inputVariables)n.add(c);const r=this.inputVariables,s=new Set(this.partialVariables?r.concat(Object.keys(this.partialVariables)):r),a=new Set([...s].filter(o=>!n.has(o)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are not used in any of the prompt messages.`);const i=new Set([...n].filter(o=>!s.has(o)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(t,n){if(typeof t.content=="string")return t;const r=await Promise.all(t.content.map(async s=>{if(s.type!=="image_url")return s;let a="";typeof s.image_url=="string"?a=s.image_url:typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(a=s.image_url.url);const o=await En.fromTemplate(a,{templateFormat:this.templateFormat}).format(n);return typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url?s.image_url.url=o:s.image_url=o,s}));return t.content=r,t}async formatMessages(t){const n=await this.mergePartialAndUserVariables(t);let r=[];for(const s of this.promptMessages)if(s instanceof rt)r.push(await this._parseImagePrompts(s,n));else{let a;this.templateFormat==="mustache"?a={...n}:a=s.inputVariables.reduce((o,c)=>{if(!(c in n)&&!(uk(s)&&s.optional))throw Si(new Error(`Missing value for input variable \`${c.toString()}\``),"INVALID_PROMPT_INPUT");return o[c]=n[c],o},{});const i=await s.formatMessages(a);r=r.concat(i)}return r}async partial(t){const n=this.inputVariables.filter(a=>!(a in t)),r={...this.partialVariables??{},...t},s={...this,inputVariables:n,partialVariables:r};return new Aa(s)}static fromTemplate(t,n){const r=En.fromTemplate(t,n),s=new Hl({prompt:r});return this.fromMessages([s])}static fromMessages(t,n){const r=t.reduce((i,o)=>i.concat(o instanceof Aa?o.promptMessages:[lk(o,n)]),[]),s=t.reduce((i,o)=>o instanceof Aa?Object.assign(i,o.partialVariables):i,Object.create(null)),a=new Set;for(const i of r)if(!(i instanceof rt))for(const o of i.inputVariables)o in s||a.add(o);return new this({...n,inputVariables:[...a],promptMessages:r,partialVariables:s,templateFormat:n?.templateFormat})}},dk=class Tc extends Fs{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
178
-
179
- `;prefix="";templateFormat="f-string";validateTemplate=!0;constructor(t){if(super(t),Object.assign(this,t),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),ia(this.prefix+this.suffix,this.templateFormat,n)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(t){const n=this.inputVariables.filter(a=>!(a in t)),r={...this.partialVariables??{},...t},s={...this,inputVariables:n,partialVariables:r};return new Tc(s)}async format(t){const n=await this.mergePartialAndUserVariables(t),r=await this.getExamples(n),s=await Promise.all(r.map(i=>this.examplePrompt.format(i))),a=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return Dt(a,this.templateFormat,n)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(t){const{example_prompt:n}=t;if(!n)throw new Error("Missing example prompt");const r=await En.deserialize(n);let s;if(Array.isArray(t.examples))s=t.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new Tc({inputVariables:t.input_variables,examplePrompt:r,examples:s,exampleSeparator:t.example_separator,prefix:t.prefix,suffix:t.suffix,templateFormat:t.template_format})}},hk=class Mm extends Bl{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
180
-
181
- `;prefix="";templateFormat="f-string";validateTemplate=!0;_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(t){if(super(t),this.examples=t.examples,this.examplePrompt=t.examplePrompt,this.exampleSeparator=t.exampleSeparator??`
182
-
183
- `,this.exampleSelector=t.exampleSelector,this.prefix=t.prefix??"",this.suffix=t.suffix??"",this.templateFormat=t.templateFormat??"f-string",this.validateTemplate=t.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),ia(this.prefix+this.suffix,this.templateFormat,n)}}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(t){const n=await this.mergePartialAndUserVariables(t);let r=await this.getExamples(n);r=r.map(a=>{const i={};return this.examplePrompt.inputVariables.forEach(o=>{i[o]=a[o]}),i});const s=[];for(const a of r){const i=await this.examplePrompt.formatMessages(a);s.push(...i)}return s}async format(t){const n=await this.mergePartialAndUserVariables(t),r=await this.getExamples(n),a=(await Promise.all(r.map(o=>this.examplePrompt.formatMessages(o)))).flat().map(o=>o.content),i=[this.prefix,...a,this.suffix].join(this.exampleSeparator);return Dt(i,this.templateFormat,n)}async partial(t){const n=this.inputVariables.filter(a=>!(a in t)),r={...this.partialVariables??{},...t},s={...this,inputVariables:n,partialVariables:r};return new Mm(s)}},pk=class ka extends sa{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(t){super({...t,inputVariables:[]}),this.pipelinePrompts=t.pipelinePrompts,this.finalPrompt=t.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){const t=this.pipelinePrompts.map(r=>r.name),n=this.pipelinePrompts.map(r=>r.prompt.inputVariables.filter(s=>!t.includes(s))).flat();return[...new Set(n)]}static extractRequiredInputValues(t,n){return n.reduce((r,s)=>(r[s]=t[s],r),{})}async formatPipelinePrompts(t){const n=await this.mergePartialAndUserVariables(t);for(const{name:r,prompt:s}of this.pipelinePrompts){const a=ka.extractRequiredInputValues(n,s.inputVariables);s instanceof Vl?n[r]=await s.formatMessages(a):n[r]=await s.format(a)}return ka.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(t){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(t))}async format(t){return this.finalPrompt.format(await this.formatPipelinePrompts(t))}async partial(t){const n={...this};return n.inputVariables=this.inputVariables.filter(r=>!(r in t)),n.partialVariables={...this.partialVariables??{},...t},new ka(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function Id(e){return typeof e=="object"&&e!=null&&"withStructuredOutput"in e&&typeof e.withStructuredOutput=="function"}function fk(e){return typeof e=="object"&&e!=null&&"lc_id"in e&&Array.isArray(e.lc_id)&&e.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var mk=class Rm extends Vl{schema;method;lc_namespace=["langchain_core","prompts","structured"];get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(t){super(t),this.schema=t.schema,this.method=t.method}pipe(t){if(Id(t))return super.pipe(t.withStructuredOutput(this.schema));if(fk(t)&&Id(t.bound))return super.pipe(new Fe({bound:t.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:t.kwargs??{},config:t.config,configFactories:t.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(t,n,r){return Rm.fromMessages(t,{schema:n,method:r})}},$m={};U($m,{AIMessagePromptTemplate:()=>Pm,BaseChatPromptTemplate:()=>Bl,BaseMessagePromptTemplate:()=>Di,BaseMessageStringPromptTemplate:()=>xm,BasePromptTemplate:()=>sa,BaseStringPromptTemplate:()=>Fs,ChatMessagePromptTemplate:()=>Im,ChatPromptTemplate:()=>Vl,DEFAULT_FORMATTER_MAPPING:()=>ai,DEFAULT_PARSER_MAPPING:()=>km,DictPromptTemplate:()=>wc,FewShotChatMessagePromptTemplate:()=>hk,FewShotPromptTemplate:()=>dk,HumanMessagePromptTemplate:()=>Hl,ImagePromptTemplate:()=>Ca,MessagesPlaceholder:()=>Sc,PipelinePromptTemplate:()=>pk,PromptTemplate:()=>En,StructuredPrompt:()=>mk,SystemMessagePromptTemplate:()=>Nm,checkValidTemplate:()=>ia,interpolateFString:()=>Cm,interpolateMustache:()=>Am,parseFString:()=>Bs,parseMustache:()=>si,parseTemplate:()=>ii,renderTemplate:()=>Dt});var Lm={};U(Lm,{BaseDocumentCompressor:()=>gk});var gk=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}};const bn={and:"and",or:"or",not:"not"},Z={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var jm=class{},Gl=class{accept(e){if(this.exprName==="Operation")return e.visitOperation(this);if(this.exprName==="Comparison")return e.visitComparison(this);if(this.exprName==="StructuredQuery")return e.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},Wl=class extends Gl{},yk=class extends Wl{exprName="Comparison";constructor(e,t,n){super(),this.comparator=e,this.attribute=t,this.value=n}},_k=class extends Wl{exprName="Operation";constructor(e,t){super(),this.operator=e,this.args=t}},wk=class extends Gl{exprName="StructuredQuery";constructor(e,t){super(),this.query=e,this.filter=t}};function Dm(e){return e&&typeof e=="object"&&!Array.isArray(e)}function $t(e){return e?typeof e=="string"&&e.length>0||typeof e=="function"?!1:Dm(e)&&Object.keys(e).length===0:!0}function Fm(e){if(typeof e=="number")return e%1===0;if(typeof e=="string"){const t=parseInt(e,10);return!Number.isNaN(t)&&t%1===0&&t.toString()===e}return!1}function Um(e){if(typeof e=="number")return e%1!==0;if(typeof e=="string"){const t=parseFloat(e);return!Number.isNaN(t)&&t%1!==0&&t.toString()===e}return!1}function Bm(e){return typeof e=="string"&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function zm(e){return typeof e=="boolean"}function Jl(e){let t;if(Bm(e))t=e;else if(Fm(e))t=parseInt(e,10);else if(Um(e))t=parseFloat(e);else if(zm(e))t=!!e;else throw new Error("Unsupported value type");return t}var Kl=class extends jm{},vk=class extends Kl{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[bn.and,bn.or],this.allowedComparators=e?.allowedComparators??[Z.eq,Z.ne,Z.gt,Z.gte,Z.lt,Z.lte]}formatFunction(e){if(e in Z){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw new Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(e in bn){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw new Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${e}`}visitOperation(e){const t=e.args?.map(n=>n.accept(this));return{[this.formatFunction(e.operator)]:t}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:Jl(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,n="and",r=!1){if(!($t(e)&&$t(t))){if($t(e)||n==="replace")return $t(t)?void 0:t;if($t(t))return r?e:n==="and"?void 0:e;if(n==="and")return{$and:[e,t]};if(n==="or")return{$or:[e,t]};throw new Error("Unknown merge type")}}},bk=class extends Kl{allowedOperators=[bn.and,bn.or];allowedComparators=[Z.eq,Z.ne,Z.gt,Z.gte,Z.lt,Z.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(e){switch(e){case"string":return[Z.eq,Z.ne,Z.gt,Z.gte,Z.lt,Z.lte];case"number":return[Z.eq,Z.ne,Z.gt,Z.gte,Z.lt,Z.lte];case"boolean":return[Z.eq,Z.ne];default:throw new Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case Z.eq:return(t,n)=>t===n;case Z.ne:return(t,n)=>t!==n;case Z.gt:return(t,n)=>t>n;case Z.gte:return(t,n)=>t>=n;case Z.lt:return(t,n)=>t<n;case Z.lte:return(t,n)=>t<=n;default:throw new Error("Unknown comparator")}}getOperatorFunction(e){switch(e){case bn.and:return(t,n)=>t&&n;case bn.or:return(t,n)=>t||n;default:throw new Error("Unknown operator")}}visitOperation(e){const{operator:t,args:n}=e;if(this.allowedOperators.includes(t)){const r=this.getOperatorFunction(t);return s=>n?n.reduce((a,i)=>{const o=i.accept(this);if(typeof o=="function")return r(a,o(s));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(e){const{comparator:t,attribute:n,value:r}=e,s=[Z.ne];if(this.allowedComparators.includes(t)){if(!this.getAllowedComparatorsForType(typeof r).includes(t))throw new Error(`'${t}' comparator not allowed to be used with ${typeof r}`);const a=this.getComparatorFunction(t);return i=>{const o=i.metadata[n];return o===void 0?!!s.includes(t):a(o,Jl(r))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(e){if(!e.filter)return{};const t=e.filter?.accept(this);if(typeof t!="function")throw new Error("Structured query filter is not a function");return{filter:t}}mergeFilters(e,t,n="and"){if(!($t(e)&&$t(t))){if($t(e)||n==="replace")return $t(t)?void 0:t;if($t(t))return n==="and"?void 0:e;if(n==="and")return r=>e(r)&&t(r);if(n==="or")return r=>e(r)||t(r);throw new Error("Unknown merge type")}}},Hm={};U(Hm,{BaseTranslator:()=>Kl,BasicTranslator:()=>vk,Comparators:()=>Z,Comparison:()=>yk,Expression:()=>Gl,FilterDirective:()=>Wl,FunctionalTranslator:()=>bk,Operation:()=>_k,Operators:()=>bn,StructuredQuery:()=>wk,Visitor:()=>jm,castValue:()=>Jl,isBoolean:()=>zm,isFilterEmpty:()=>$t,isFloat:()=>Um,isInt:()=>Fm,isObject:()=>Dm,isString:()=>Bm});var Vm={};U(Vm,{RunCollectorCallbackHandler:()=>Sk});var Sk=class extends un{name="run_collector";exampleId;tracedRuns;constructor({exampleId:e}={}){super({_awaitHandler:!0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){const t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}},Tk={},Gm={};U(Gm,{chunkArray:()=>Ek});const Ek=(e,t)=>e.reduce((n,r,s)=>{const a=Math.floor(s/t),i=n[a]||[];return n[a]=i.concat([r]),n},[]);var Wm={};U(Wm,{EventStreamContentType:()=>Ck,convertEventStreamToIterableReadableDataStream:()=>kk,getBytes:()=>Jm,getLines:()=>Km,getMessages:()=>Zm});const Ck="text/event-stream";async function Jm(e,t){if(e instanceof ReadableStream){const n=e.getReader();for(;;){const r=await n.read();if(r.done){t(new Uint8Array,!0);break}t(r.value)}}else try{for await(const n of e)t(new Uint8Array(n));t(new Uint8Array,!0)}catch(n){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${n.message}`].join(`
184
- `))}}var _r=(function(e){return e[e.NewLine=10]="NewLine",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.Colon=58]="Colon",e})(_r||{});function Km(e){let t,n,r,s=!1;return function(i,o){if(o){e(i,0,!0);return}t===void 0?(t=i,n=0,r=-1):t=Ak(t,i);const c=t.length;let l=0;for(;n<c;){s&&(t[n]===_r.NewLine&&(l=++n),s=!1);let u=-1;for(;n<c&&u===-1;++n)switch(t[n]){case _r.Colon:r===-1&&(r=n-l);break;case _r.CarriageReturn:s=!0;case _r.NewLine:u=n;break}if(u===-1)break;e(t.subarray(l,u),r),l=n,r=-1}l===c?t=void 0:l!==0&&(t=t.subarray(l),n-=l)}}function Zm(e,t,n){let r=To();const s=new TextDecoder;return function(i,o,c){if(c){Ok(r)||(e?.(r),r=To());return}if(i.length===0)e?.(r),r=To();else if(o>0){const l=s.decode(i.subarray(0,o)),u=o+(i[o+1]===_r.Space?2:1),d=s.decode(i.subarray(u));switch(l){case"data":r.data=r.data?r.data+`
185
- `+d:d;break;case"event":r.event=d;break;case"id":t?.(r.id=d);break;case"retry":{const h=parseInt(d,10);Number.isNaN(h)||n?.(r.retry=h);break}}}}}function Ak(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function To(){return{data:"",event:"",id:"",retry:void 0}}function kk(e,t){const n=new ReadableStream({async start(r){const s=Zm(i=>{if(i.event==="error")throw new Error(i.data??"Unspecified event streaming error.");i.event==="metadata"?t?.(i):i.data&&r.enqueue(i.data)});await Jm(e,Km((i,o,c)=>{s(i,o,c),c&&r.close()}))}});return Be.fromReadableStream(n)}function Ok(e){return e.data===""&&e.event===""&&e.id===""&&e.retry===void 0}var xk={},qm={};U(qm,{convertToOpenAIFunction:()=>Ym,convertToOpenAITool:()=>Ik,isLangChainTool:()=>Cl,isRunnableToolLike:()=>Tl,isStructuredTool:()=>Sl,isStructuredToolParams:()=>El});function Ym(e,t){const n=typeof t=="number"?void 0:t;return{name:e.name,description:e.description,parameters:mt(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function Ik(e,t){const n=typeof t=="number"?void 0:t;let r;return Cl(e)?r={type:"function",function:Ym(e)}:r=e,n?.strict!==void 0&&(r.function.strict=n.strict),r}function Xm(e,t){let n=0,r=0,s=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],s+=t[a]*t[a];return n/(Math.sqrt(r)*Math.sqrt(s))}function Pk(e,t){let n=0;for(let r=0;r<e.length;r++)n+=e[r]*t[r];return n}function Nk(e,t){let n=0;for(let r=0;r<e.length;r++)n+=(e[r]-t[r])*(e[r]-t[r]);return n}function Mk(e,t){return Math.sqrt(Nk(e,t))}var Qm={};U(Qm,{cosineSimilarity:()=>Ec,euclideanDistance:()=>Lk,innerProduct:()=>$k,matrixFunc:()=>Fi,maximalMarginalRelevance:()=>jk,normalize:()=>Rk});function Fi(e,t,n){if(e.length===0||e[0].length===0||t.length===0||t[0].length===0)return[[]];if(e[0].length!==t[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[e.length,e[0].length]} and Y has shape ${[t.length,t[0].length]}.`);return e.map(r=>t.map(s=>n(r,s)).map(s=>Number.isNaN(s)?0:s))}function Rk(e,t=!1){const n=Dk(e);return e.map(r=>r.map(s=>t?1-s/n:s/n))}function Ec(e,t){return Fi(e,t,Xm)}function $k(e,t){return Fi(e,t,Pk)}function Lk(e,t){return Fi(e,t,Mk)}function jk(e,t,n=.5,r=4){if(Math.min(r,t.length)<=0)return[];const s=Array.isArray(e[0])?e:[e],a=Ec(s,t)[0],i=eg(a).maxIndex,o=[t[i]],c=[i];for(;c.length<Math.min(r,t.length);){let l=-1/0,u=-1;const d=Ec(t,o);a.forEach((h,p)=>{if(c.includes(p))return;const f=Math.max(...d[p]),g=n*h-(1-n)*f;g>l&&(l=g,u=p)}),o.push(t[u]),c.push(u)}return c}function eg(e){if(e.length===0)return{maxIndex:-1,maxValue:NaN};let t=e[0],n=0;for(let r=1;r<e.length;r+=1)e[r]>t&&(n=r,t=e[r]);return{maxIndex:n,maxValue:t}}function Dk(e){return e.reduce((t,n)=>Math.max(t,eg(n).maxValue),0)}var Fk=class extends rr{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(e,t,n){if(t?.stop?.length)return{generations:[{message:new D(t.stop[0]),text:t.stop[0]}]};const r=e.map(s=>typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2)).join(`
186
- `);return await n?.handleLLMNewToken(r),{generations:[{message:new D(r),text:r}],llmOutput:{}}}},Uk=class tg extends rr{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:t=50,responses:n=[],chunks:r=[],toolStyle:s="openai",thrownErrorString:a,...i}){super(i),this.sleep=t,this.responses=n,this.chunks=r,this.toolStyle=s,this.thrownErrorString=a}_llmType(){return"fake"}bindTools(t){const n=[...this.tools,...t],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:mt(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:mt(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:mt(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:mt(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,a=new tg({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=n,a.withConfig({tools:s})}async _generate(t,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const s=this.responses?.[0]?.content??t[0].content??"";return{generations:[{text:"",message:new D({content:s,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(t,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const i of this.chunks){const o=new Wr({message:new yt({content:i.content,tool_calls:i.tool_calls,additional_kwargs:i.additional_kwargs??{}}),text:i.content?.toString()??""});yield o,await r?.handleLLMNewToken(i.content,void 0,void 0,void 0,void 0,{chunk:o})}return}const s=this.responses?.[0]??new D(typeof t[0].content=="string"?t[0].content:""),a=typeof s.content=="string"?s.content:"";for(const i of a){await new Promise(c=>setTimeout(c,this.sleep));const o=new Wr({message:new yt({content:i}),text:i});yield o,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:o})}}},Bk=class extends rr{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;constructor(e){super(e);const{responses:t,sleep:n,emitCustomEvent:r}=e;this.responses=t,this.sleep=n,this.emitCustomEvent=r??this.emitCustomEvent}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(e,t,n){if(await this._sleepIfRequested(),t?.thrownErrorString)throw new Error(t.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0}),t?.stop?.length)return{generations:[this._formatGeneration(t.stop[0])]};{const r=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(r)],llmOutput:{}}}}_formatGeneration(e){return{message:new D(e),text:e}}async*_streamResponseChunks(e,t,n){const r=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0});for await(const s of r){if(await this._sleepIfRequested(),t?.thrownErrorString)throw new Error(t.thrownErrorString);yield this._createResponseChunk(s),n?.handleLLMNewToken(s)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e){return new Wr({message:new yt({content:e}),text:e})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}withStructuredOutput(e,t){return ot.from(async n=>{const r=await this.invoke(n);if(r.tool_calls?.[0]?.args)return r.tool_calls[0].args;if(typeof r.content=="string")return JSON.parse(r.content);throw new Error("No structured output found")})}},zk=class extends $l{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(t=>this.embedQuery(t)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,"");const n=t.length%this.vectorSize,r=n===0?0:this.vectorSize-n,s=t.length+r;t=t.padEnd(s," ");const a=t.length/this.vectorSize,i=[];for(let c=0;c<t.length;c+=a)i.push(t.slice(c,c+a));return i.map(c=>{let l=0;for(let d=0;d<c.length;d+=1)l+=c===" "?0:c.charCodeAt(d);return l%26/26})}},Hk=class extends $l{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},Vk=class extends Fl{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,t,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.response??e;return await n?.handleLLMNewToken(r),r}},Gk=class extends Fl{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.responses?.[0];this.responses=this.responses?.slice(1);for(const s of r??e)await new Promise(a=>setTimeout(a,this.sleep)),yield{text:s,generationInfo:{}},await n?.handleLLMNewToken(s)}},Wk=class extends Uf{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new he(e))}async addAIMessage(e){this.messages.push(new D(e))}async clear(){this.messages=[]}},Jk=class extends Rl{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},Kk=class extends un{name="fake_tracer";runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},Zk=class extends ea{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(e){return e.split(",").map(t=>t.trim())}},qk=class extends Ll{lc_namespace=["test","fake"];output=[new an({pageContent:"foo"}),new an({pageContent:"bar"})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},Yk=class extends J{lc_namespace=["tests","fake"];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},Xk=class extends er{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}},Qk=class extends un{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},eO=class ng extends jl{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(t,{similarity:n,...r}={}){super(t,r),this.similarity=n??Xm}async addDocuments(t){const n=t.map(({pageContent:r})=>r);return this.addVectors(await this.embeddings.embedDocuments(n),t)}async addVectors(t,n){const r=t.map((s,a)=>({content:n[a].pageContent,embedding:s,metadata:n[a].metadata}));this.memoryVectors=this.memoryVectors.concat(r)}async similaritySearchVectorWithScore(t,n,r){const s=c=>{if(!r)return!0;const l=new an({metadata:c.metadata,pageContent:c.content});return r(l)},a=this.memoryVectors.filter(s);return a.map((c,l)=>({similarity:this.similarity(t,c.embedding),index:l})).sort((c,l)=>c.similarity>l.similarity?-1:0).slice(0,n).map(c=>[new an({metadata:a[c.index].metadata,pageContent:a[c.index].content}),c.similarity])}static async fromTexts(t,n,r,s){const a=[];for(let i=0;i<t.length;i+=1){const o=Array.isArray(n)?n[i]:n,c=new an({pageContent:t[i],metadata:o});a.push(c)}return ng.fromDocuments(a,r,s)}static async fromDocuments(t,n,r){const s=new this(n,r);return await s.addDocuments(t),s}static async fromExistingIndex(t,n){return new this(t,n)}},rg={};U(rg,{FakeChatMessageHistory:()=>Wk,FakeChatModel:()=>Fk,FakeEmbeddings:()=>Hk,FakeLLM:()=>Vk,FakeListChatMessageHistory:()=>Jk,FakeListChatModel:()=>Bk,FakeRetriever:()=>qk,FakeRunnable:()=>Yk,FakeSplitIntoListParser:()=>Zk,FakeStreamingChatModel:()=>Uk,FakeStreamingLLM:()=>Gk,FakeTool:()=>Xk,FakeTracer:()=>Kk,FakeVectorStore:()=>eO,SingleRunExtractor:()=>Qk,SyntheticEmbeddings:()=>zk});var sg={};U(sg,{agents:()=>uA,caches:()=>Zp,callbacks__base:()=>jh,callbacks__manager:()=>ip,callbacks__promises:()=>sp,chat_history:()=>Ff,document_loaders__base:()=>Zf,document_loaders__langsmith:()=>Yf,documents:()=>Qf,embeddings:()=>Bf,example_selectors:()=>rm,index:()=>hA,indexing:()=>lm,language_models__base:()=>nf,language_models__chat_models:()=>Of,language_models__llms:()=>um,load__serializable:()=>ph,memory:()=>zf,messages:()=>kf,messages__tool:()=>Th,output_parsers:()=>gm,output_parsers__openai_functions:()=>Sm,output_parsers__openai_tools:()=>wm,outputs:()=>Mp,prompt_values:()=>Wp,prompts:()=>$m,retrievers:()=>Jf,retrievers__document_compressors:()=>Lm,runnables:()=>xf,runnables__graph:()=>jp,singletons:()=>hp,stores:()=>Vf,structured_query:()=>Hm,tools:()=>rf,tracers__base:()=>Xh,tracers__console:()=>Qh,tracers__log_stream:()=>Pp,tracers__run_collector:()=>Vm,tracers__tracer_langchain:()=>tp,types__stream:()=>Tk,utils__async_caller:()=>Cp,utils__chunk_array:()=>Gm,utils__env:()=>Ih,utils__event_source_parse:()=>Wm,utils__format:()=>xk,utils__function_calling:()=>qm,utils__hash:()=>Kp,utils__json_patch:()=>hm,utils__json_schema:()=>Ep,utils__math:()=>Qm,utils__stream:()=>Ap,utils__testing:()=>rg,utils__tiktoken:()=>ef,utils__types:()=>Rf,vectorstores:()=>Kf});function tO(e){const t={};for(let n=e;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(t,Reflect.get(n.prototype,"lc_aliases"));return Object.entries(t).reduce((n,[r,s])=>(n[s]=r,n),{})}async function Oa(e){const{optionalImportsMap:t={},optionalImportEntrypoints:n=[],importMap:r={},secretsMap:s={},path:a=["$"]}=this,i=a.join(".");if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&"lc"in e&&"type"in e&&"id"in e&&e.lc===1&&e.type==="secret"){const o=e,[c]=o.id;if(c in s)return s[c];{const l=rn(c);if(l)return l;throw new Error(`Missing key "${c}" for ${i} in load(secretsMap={})`)}}else if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&"lc"in e&&"type"in e&&"id"in e&&e.lc===1&&e.type==="not_implemented"){const c=JSON.stringify(e);throw new Error(`Trying to load an object that doesn't implement serialization: ${i} -> ${c}`)}else if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&"lc"in e&&"type"in e&&"id"in e&&"kwargs"in e&&e.lc===1){const o=e,c=JSON.stringify(o),[l,...u]=o.id.slice().reverse(),d=u.reverse(),h={langchain_core:sg,langchain:r};let p=null;const f=[d.join("/")];d[0]==="langchain_community"&&f.push(["langchain",...d.slice(1)].join("/"));const g=f.find(w=>w in t);if(lA.concat(n).includes(d.join("/"))||g)if(g!==void 0)p=await t[g];else throw new Error(`Missing key "${d.join("/")}" for ${i} in load(optionalImportsMap={})`);else{let w;if(d[0]==="langchain"||d[0]==="langchain_core")w=h[d[0]],d.shift();else throw new Error(`Invalid namespace: ${i} -> ${c}`);if(d.length===0)throw new Error(`Invalid namespace: ${i} -> ${c}`);let v;do{if(v=d.join("__"),v in w)break;d.pop()}while(d.length>0);v in w&&(p=w[v])}if(typeof p!="object"||p===null)throw new Error(`Invalid namespace: ${i} -> ${c}`);const b=p[l]??Object.values(p).find(w=>typeof w=="function"&&_i(w)===l);if(typeof b!="function")throw new Error(`Invalid identifer: ${i} -> ${c}`);const S=await Oa.call({...this,path:[...a,"kwargs"]},o.kwargs);if(o.type==="constructor"){const w=new b(hh(S,ow,tO(b)));return Object.defineProperty(w.constructor,"name",{value:l}),w}else throw new Error(`Invalid type: ${i} -> ${c}`)}else if(typeof e=="object"&&e!==null)return Array.isArray(e)?Promise.all(e.map((o,c)=>Oa.call({...this,path:[...a,`${c}`]},o))):Object.fromEntries(await Promise.all(Object.entries(e).map(async([o,c])=>[o,await Oa.call({...this,path:[...a,o]},c)])));return e}async function nO(e,t){const n=JSON.parse(e);return Oa.call({...t},n)}function rO(e){return e!==null&&e.lc===1&&e.type==="constructor"&&Array.isArray(e.id)}async function Cc(e){if(e&&typeof e=="object"){if(Array.isArray(e))return await Promise.all(e.map(n=>Cc(n)));{const t={};for(const[n,r]of Object.entries(e))t[n]=await Cc(r);if(t.lc===2&&t.type==="undefined")return;if(t.lc===2&&t.type==="constructor"&&Array.isArray(t.id))try{const n=t.id[t.id.length-1];let r;switch(n){case"Set":r=Set;break;case"Map":r=Map;break;case"RegExp":r=RegExp;break;case"Error":r=Error;break;default:return t}return t.method?r[t.method](...t.args||[]):new r(...t.args||[])}catch{return t}else if(rO(t))return nO(JSON.stringify(t));return t}}return e}function Eo(e,t,n,r){return{lc:2,type:"constructor",id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function sO(e){return e===void 0?{lc:2,type:"undefined"}:e instanceof Set||e instanceof Map?Eo(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?Eo(RegExp,void 0,[e.source,e.flags]):e instanceof Error?Eo(e.constructor,void 0,[e.message]):e?.lg_name==="Send"?{node:e.node,args:e.args}:e}var aO=class{_dumps(e){return new TextEncoder().encode(oA(e,(n,r)=>sO(r)))}async dumpsTyped(e){return e instanceof Uint8Array?["bytes",e]:["json",this._dumps(e)]}async _loads(e){const t=JSON.parse(e);return Cc(t)}async loadsTyped(e,t){if(e==="bytes")return typeof t=="string"?new TextEncoder().encode(t):t;if(e==="json")return this._loads(typeof t=="string"?t:new TextDecoder().decode(t));throw new Error(`Unknown serialization type: ${e}`)}};function ag(e){if(typeof e!="object"||e===null)return e;const t=Array.isArray(e)?[]:{};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=ag(e[n]));return t}function ig(){return{v:4,id:Df(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function oi(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values},channel_versions:{...e.channel_versions},versions_seen:ag(e.versions_seen)}}function og(e,t){return typeof e=="number"&&typeof t=="number"?Math.sign(e-t):String(e).localeCompare(String(t))}function iO(...e){return e.reduce((t,n,r)=>r===0?n:og(t,n)>=0?t:n)}const oO={[nA]:-1,[Ta]:-2,[rA]:-3,[sA]:-4};var os=class extends Error{constructor(e){super(e),this.name="InvalidNamespaceError"}};function cO(e){if(e.length===0)throw new os("Namespace cannot be empty.");for(const t of e){if(typeof t!="string")throw new os(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes("."))throw new os(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t==="")throw new os(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]==="langgraph")throw new os(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var lO=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){const{filter:n,limit:r=10,offset:s=0,query:a}=t;return(await this.batch([{namespacePrefix:e,filter:n,limit:r,offset:s,query:a}]))[0]}async put(e,t,n,r){cO(e),await this.batch([{namespace:e,key:t,value:n,index:r}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){const{prefix:t,suffix:n,maxDepth:r,limit:s=100,offset:a=0}=e,i=[];return t&&i.push({matchType:"prefix",path:t}),n&&i.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:i.length?i:void 0,maxDepth:r,limit:s,offset:a}]))[0]}start(){}stop(){}};const uO=e=>"lg_name"in e&&e.lg_name==="AsyncBatchedStore"?e.store:e;var dO=class extends lO{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=uO(e)}get isRunning(){return this.running}async batch(e){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){const{filter:n,limit:r=10,offset:s=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:r,offset:s,query:a})}async put(e,t,n){return this.enqueueOperation({namespace:e,key:t,value:n})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,n)=>{const r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:e,resolve:t,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(t=>{setTimeout(t,0)}),this.queue.size===0)continue;const e=new Map(this.queue);this.queue.clear();try{const t=Array.from(e.values()).map(({operation:r})=>r),n=await this.store.batch(t);e.forEach(({resolve:r},s)=>{const a=Array.from(e.keys()).indexOf(s);r(n[a])})}catch(t){e.forEach(({reject:n})=>{n(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},hO=class{serde=new aO;constructor(e){this.serde=e||this.serde}},pO=class cg extends rr{toolCalls;toolStyle;indexRef;structuredResponse;tools=[];constructor({toolCalls:t=[],toolStyle:n="openai",index:r=0,structuredResponse:s,indexRef:a,...i}={}){super(i),this.toolCalls=t,this.toolStyle=n,this.indexRef=a??{current:r},this.structuredResponse=s}get index(){return this.indexRef.current}set index(t){this.indexRef.current=t}_llmType(){return"fake-tool-calling"}_combineLLMOutput(){return[]}bindTools(t){const n=new cg({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...t],n}withStructuredOutput(t){return new ot({func:async()=>this.structuredResponse})}async _generate(t,n,r){let a=t[t.length-1].content;t.length>1&&(a=t.map(d=>d.content).filter(Boolean).join("-")),(t.length===1||t.length===2&&t.every(he.isInstance))&&this.index!==0&&(this.index=0);const o=this.toolCalls[this.index]||[],c=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);const l=new D({content:a,id:c,tool_calls:o.length>0?o.map(u=>({...u,type:"tool_call"})):void 0});return{generations:[{text:a,message:l}],llmOutput:{}}}};class fO{constructor(){this.store=void 0}getStore(){return this.store}run(t,n,...r){this.store=t;try{return n(...r)}finally{this.store=void 0}}exit(t,...n){const r=this.store;this.store=void 0;try{return t(...n)}finally{this.store=r}}enterWith(t){this.store=t}disable(){this.store=void 0}}function mO(){Te.initializeGlobalInstance(new fO)}var sr=class extends Error{lc_error_code;constructor(e,t){let n=e??"";t?.lc_error_code&&(n=`${n}
187
-
188
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/
189
- `),super(n),this.lc_error_code=t?.lc_error_code}},lg=class extends sr{get is_bubble_up(){return!0}},gO=class extends sr{constructor(e,t){super(e,t),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},xa=class extends sr{constructor(e,t){super(e,t),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},Sr=class extends lg{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}},ug=class extends Sr{constructor(e,t){super([{value:e}],t),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},dg=class extends lg{command;constructor(e){super(),this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}};function yO(e){return e!==void 0&&e.name===dg.unminifiable_name}function Ia(e){return e!==void 0&&e.is_bubble_up===!0}function Bn(e){return e!==void 0&&[Sr.unminifiable_name,ug.unminifiable_name].includes(e.name)}var Pd=class extends sr{constructor(e,t){super(e,t),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},je=class extends sr{constructor(e,t){super(e,t),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},de=class extends sr{constructor(e,t){super(e,t),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},_O=class extends sr{constructor(e,t){super(e,t),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function hg(e){return e!=null&&e.lg_is_channel===!0}var ar=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===je.unminifiable_name)return!1;throw e}}};const Ac=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function Zl(e){if(e[Ac]===!0)return e;const t={};for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const r=e[n];hg(r)&&(t[n]=r)}return Object.assign(t,{[Ac]:!0}),t}function ci(e,t){const n=Zl(e),r={};for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const a=t.channel_values[s];r[s]=n[s].fromCheckpoint(a)}return Object.assign(r,{[Ac]:!0}),r}function Fn(e,t,n,r){let s;if(t===void 0)s=e.channel_values;else{s={};for(const a in t)if(Object.prototype.hasOwnProperty.call(t,a))try{s[a]=t[a].checkpoint()}catch(i){if(i.name!==je.unminifiable_name)throw i}}return{v:4,id:r?.id??Df(n),ts:new Date().toISOString(),channel_values:s,channel_versions:e.channel_versions,versions_seen:e.versions_seen}}var kc=class pg extends ar{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(t,n){super(),this.operator=t,this.initialValueFactory=n,this.value=n?.()}fromCheckpoint(t){const n=new pg(this.operator,this.initialValueFactory);return typeof t<"u"&&(n.value=t),n}update(t){let n=t;if(!n.length)return!1;this.value===void 0&&([this.value]=n,n=n.slice(1));for(const r of n)this.value!==void 0&&(this.value=this.operator(this.value,r));return!0}get(){if(this.value===void 0)throw new je;return this.value}checkpoint(){if(this.value===void 0)throw new je;return this.value}isAvailable(){return this.value!==void 0}},ql=class fg extends ar{lc_graph_name="LastValue";value=[];fromCheckpoint(t){const n=new fg;return typeof t<"u"&&(n.value=[t]),n}update(t){if(t.length===0)return!1;if(t.length!==1)throw new de("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new je;return this.value[0]}checkpoint(){if(this.value.length===0)throw new je;return this.value[0]}isAvailable(){return this.value.length!==0}},wO=class mg extends ar{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(t){const n=new mg;if(typeof t<"u"){const[r,s]=t;n.value=[r],n.finished=s}return n}update(t){return t.length===0?!1:(this.finished=!1,this.value=[t[t.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new je;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},vO=class{lc_graph_name="AnnotationRoot";spec;constructor(e){this.spec=e}};const Oc=function(e){return e?xc(e):new ql};Oc.Root=e=>new vO(e);function xc(e){return typeof e=="object"&&e&&"reducer"in e&&e.reducer?new kc(e.reducer,e.default):typeof e=="object"&&e&&"value"in e&&e.value?new kc(e.value,e.default):new ql}const ie="__start__",B="__end__",Qt="__input__",bO="__copy__",tt="__error__",Co="__pregel_ns_writes",Cn="__pregel_send",Yl="__pregel_call",Gn="__pregel_read",_e="__pregel_checkpointer",_n="__pregel_resuming",_s="__pregel_task_id",li="__pregel_stream",SO="__pregel_resume_value",Pa="__pregel_resume_map",An="__pregel_scratchpad",Na="__pregel_previous",gg="__pregel_durability",Ic="checkpoint_id",zt="checkpoint_ns",TO="__pregel_node_finished",St="checkpoint_map",Nd="__pregel_abort_signals",Q="__interrupt__",at="__resume__",Xl="__no_writes__",Zr="__return__",Ao="__previous__",ve="langsmith:hidden",EO="langsmith:nostream",Md="__self__",Et="__pregel_tasks",pt="__pregel_push",Ma="__pregel_pull",Ct="00000000-0000-0000-0000-000000000000",CO=[ve,Qt,Q,at,tt,Xl,Cn,Gn,_e,gg,li,_n,_s,Yl,SO,An,Na,St,zt,Ic],xe="|",cn=":",Rd=Symbol.for("langgraph.command");var AO=class{[Rd];constructor(e){this[Rd]=e}};function Pc(e){const t=e;return t!=null&&typeof t.node=="string"&&t.args!==void 0}var We=class{lg_name="Send";node;args;constructor(e,t){this.node=e,this.args=zs(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function _t(e){return e instanceof We}function yg(e){return!e||typeof e!="object"||!(Q in e)?!1:Array.isArray(e[Q])}var be=class extends AO{lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(e){super(e),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?zs(e.goto):[zs(e.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let e;return typeof this.goto=="string"?e=this.goto:_t(this.goto)?e=this.goto.toJSON():e=this.goto?.map(t=>typeof t=="string"?t:t.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}};function Ne(e){return typeof e!="object"||e==null?!1:"lg_name"in e&&e.lg_name==="Command"}function zs(e,t=new Map){if(e!=null&&typeof e=="object"){if(t.has(e))return t.get(e);let n;if(Array.isArray(e))n=[],t.set(e,n),e.forEach((r,s)=>{n[s]=zs(r,t)});else if(Ne(e)&&!(e instanceof be))n=new be(e),t.set(e,n);else if(Pc(e)&&!(e instanceof We))n=new We(e.node,e.args),t.set(e,n);else if(Ne(e)||_t(e))n=e,t.set(e,n);else if("lc_serializable"in e&&e.lc_serializable)n=e,t.set(e,n);else{n={},t.set(e,n);for(const[r,s]of Object.entries(e))n[r]=zs(s,t)}return n}return e}const kO=["tags","metadata","callbacks","configurable"],OO=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],xO=25;function _g(...e){const t={tags:[],metadata:{},callbacks:void 0,recursionLimit:xO,configurable:{}},n=Te.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(kO.includes(r)){let a;Array.isArray(s)?a=[...s]:typeof s=="object"?r==="callbacks"&&"copy"in s&&typeof s.copy=="function"?a=s.copy():a={...s}:a=s,t[r]=a}else t[r]=s}for(const r of e)if(r!==void 0)for(const[s,a]of Object.entries(r))a!==void 0&&OO.includes(s)&&(t[s]=a);for(const[r,s]of Object.entries(t.configurable))t.metadata=t.metadata??{},!r.startsWith("__")&&(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&!(r in t.metadata)&&(t.metadata[r]=s);return t}function IO(){return Te.getRunnableConfig()}function ko(e){return e.split(xe).filter(t=>!t.match(/^\d+$/)).map(t=>t.split(cn)[0]).join(xe)}function PO(e){const t=e.split(xe);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(xe)}const P=e=>BigInt(e),oe=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),wg=P("0x9E3779B1"),vg=P("0x85EBCA77"),NO=P("0xC2B2AE3D"),Pn=P("0x9E3779B185EBCA87"),Zn=P("0xC2B2AE3D27D4EB4F"),bg=P("0x165667B19E3779F9"),Ql=P("0x85EBCA77C2B2AE63"),MO=P("0x27D4EB2F165667C5"),RO=P("0x165667919E3779F9"),$O=P("0x9FB21C651E98DF25"),LO=e=>{const t=e.length;if(t%2!==0)throw new Error("String should have an even number of characters");const n=t/2,r=new Uint8Array(n);let s=0,a=0;for(;a<n;){const i=e.slice(s,s+=2);r[a]=Number.parseInt(i,16),a+=1}return oe(r)},Bt=LO("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Tr=(P(1)<<P(128))-P(1),W=(P(1)<<P(64))-P(1),ui=(P(1)<<P(32))-P(1),en=64,Sg=en/8,jO=8,ma=4;function qr(e){if(!e)throw new Error("Assert failed")}function DO(e){const t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function FO(e){let t=e;return t=(t&P(65535))<<P(16)|(t&P(4294901760))>>P(16),t=(t&P(16711935))<<P(8)|(t&P(4278255360))>>P(8),t}function UO(e,t){return(e&ui)*(t&ui)&W}function BO(e,t){return(e<<t|e>>P(32)-t)&ui}function Tg(e,t,n){for(let r=0;r<Sg;r+=1){const s=t.getBigUint64(r*8,!0),a=s^n.getBigUint64(r*8,!0);e[r^1]+=s,e[r]+=UO(a,a>>P(32))}return e}function $d(e,t,n,r){for(let s=0;s<r;s+=1)Tg(e,oe(t,s*en),oe(n,s*8));return e}function zO(e,t){for(let n=0;n<Sg;n+=1){const r=t.getBigUint64(n*8,!0);let s=e[n];s=Nc(s,P(47)),s^=r,s*=wg,e[n]=s&W}return e}function ga(e,t){return Eg(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(jO,!0))}function Ld(e,t,n){let r=n;return r+=ga(e.slice(0),oe(t,0*ma)),r+=ga(e.slice(2),oe(t,4*ma)),r+=ga(e.slice(4),oe(t,8*ma)),r+=ga(e.slice(6),oe(t,12*ma)),Ht(r&W)}function HO(e,t,n,r,s){let a=e;const i=Math.floor((n.byteLength-en)/8),o=en*i,c=Math.floor((t.byteLength-1)/o);for(let l=0;l<c;l+=1)a=$d(a,oe(t,l*o),n,i),a=s(a,oe(n,n.byteLength-en));{const l=Math.floor((t.byteLength-1-o*c)/en);a=$d(a,oe(t,c*o),n,l),a=r(a,oe(t,t.byteLength-en),oe(n,n.byteLength-en-7))}return a}function VO(e,t){let n=new BigUint64Array([NO,Pn,Zn,bg,Ql,vg,MO,wg]);qr(e.byteLength>128),n=HO(n,e,t,Tg,zO),qr(n.length*8===64);{const r=Ld(n,oe(t,11),P(e.byteLength)*Pn&W);return Ld(n,oe(t,t.byteLength-en-11),~(P(e.byteLength)*Zn)&W)<<P(64)|r}}function Eg(e,t){const n=e*t&Tr;return n&W^n>>P(64)}function jd(e,t,n){return Eg((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&W,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&W)}function Ra(e,t,n,r,s){let a=e&W,i=e>>P(64)&W;return a+=jd(t,r,s),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=W,i+=jd(n,oe(r,16),s),i^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),i&=W,i<<P(64)|a}function Ht(e){let t=e;return t^=t>>P(37),t*=RO,t&=W,t^=t>>P(32),t}function di(e){let t=e;return t^=t>>P(33),t*=Zn,t&=W,t^=t>>P(29),t*=bg,t&=W,t^=t>>P(32),t}function GO(e,t,n){const r=e.byteLength;qr(r>0&&r<=3);const s=P(e.getUint8(r-1))|P(r<<8)|P(e.getUint8(0)<<16)|P(e.getUint8(r>>1)<<24),a=(P(t.getUint32(0,!0))^P(t.getUint32(4,!0)))+n,i=(s^a)&W,o=(P(t.getUint32(8,!0))^P(t.getUint32(12,!0)))-n,c=(BO(FO(s),P(13))^o)&W;return(di(c)&W)<<P(64)|di(i)}function Nc(e,t){return e^e>>t}function WO(e,t,n){const r=e.byteLength;qr(r>=4&&r<=8);{const s=e.getUint32(0,!0),a=e.getUint32(r-4,!0),i=P(s)|P(a)<<P(32),o=(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+n&W;let l=(i^o)*(Pn+(P(r)<<P(2)))&Tr;return l+=(l&W)<<P(65),l&=Tr,l^=l>>P(67),Nc(Nc(l&W,P(35))*$O&W,P(28))|Ht(l>>P(64))<<P(64)}}function JO(e,t,n){const r=e.byteLength;qr(r>=9&&r<=16);{const s=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+n&W,a=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-n&W,i=e.getBigUint64(0,!0);let o=e.getBigUint64(r-8,!0),c=(i^o^s)*Pn;const l=(c&W)+(P(r-1)<<P(54));c=c&(Tr^W)|l,o^=a,c+=o+(o&ui)*(vg-P(1))<<P(64),c&=Tr,c^=DO(c>>P(64));let u=(c&W)*Zn;return u+=(c>>P(64))*Zn<<P(64),u&=Tr,Ht(u&W)|Ht(u>>P(64))<<P(64)}}function KO(e,t){const n=e.byteLength;return qr(n<=16),n>8?JO(e,Bt,t):n>=4?WO(e,Bt,t):n>0?GO(e,Bt,t):di(t^Bt.getBigUint64(64,!0)^Bt.getBigUint64(72,!0))|di(t^Bt.getBigUint64(80,!0)^Bt.getBigUint64(88,!0))<<P(64)}function Mc(e){return~e+P(1)&W}function ZO(e,t,n){let r=P(e.byteLength)*Pn&W,s=P(e.byteLength-1)/P(32);for(;s>=0;){const o=Number(s);r=Ra(r,oe(e,16*o),oe(e,e.byteLength-16*(o+1)),oe(t,32*o),n),s-=P(1)}let a=r+(r>>P(64))&W;a=Ht(a);let i=(r&W)*Pn+(r>>P(64))*Ql+(P(e.byteLength)-n&W)*Zn;return i&=W,i=Mc(Ht(i)),a|i<<P(64)}function qO(e,t,n){let r=P(e.byteLength)*Pn&W;for(let i=32;i<160;i+=32)r=Ra(r,oe(e,i-32),oe(e,i-16),oe(t,i-32),n);r=Ht(r&W)|Ht(r>>P(64))<<P(64);for(let i=160;i<=e.byteLength;i+=32)r=Ra(r,oe(e,i-32),oe(e,i-16),oe(t,3+i-160),n);r=Ra(r,oe(e,e.byteLength-16),oe(e,e.byteLength-32),oe(t,103),Mc(n));let s=r+(r>>P(64))&W;s=Ht(s);let a=(r&W)*Pn+(r>>P(64))*Ql+(P(e.byteLength)-n&W)*Zn;return a&=W,a=Mc(Ht(a)),s|a<<P(64)}function jn(e,t=P(0)){const n=new TextEncoder,r=oe(typeof e=="string"?n.encode(e):e),s=r.byteLength,a=i=>i.toString(16).padStart(32,"0");return s<=16?a(KO(r,t)):s<=128?a(ZO(r,Bt,t)):s<=240?a(qO(r,Bt,t)):a(VO(r,Bt))}function Cg(e){return/^[0-9a-f]{32}$/.test(e)}function Ag(e){const t=Te.getRunnableConfig();if(!t)throw new Error("Called interrupt() outside the context of a graph.");const n=t.configurable;if(!n)throw new Error("No configurable found in config");if(!n[_e])throw new xa("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=n[An];s.interruptCounter+=1;const a=s.interruptCounter;if(s.resume.length>0&&a<s.resume.length)return n[Cn]?.([[at,s.resume]]),s.resume[a];if(s.nullResume!==void 0){if(s.resume.length!==a)throw new Error(`Resume length mismatch: ${s.resume.length} !== ${a}`);const c=s.consumeNullResume();return s.resume.push(c),n[Cn]?.([[at,s.resume]]),c}const i=n[zt]?.split(xe),o=i?jn(i.join(xe)):void 0;throw new Sr([{id:o,value:e}])}var ir=class extends J{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.trace=t.trace??this.trace,this.recurse=t.recurse??this.recurse}async _tracedInvoke(t,n,r){return new Promise((s,a)=>{const i=ne(n,{callbacks:r?.getChild()});Te.runWithConfig(i,async()=>{try{const o=await this.func(t,i);s(o)}catch(o){a(o)}})})}async invoke(t,n){let r;const s=_g(n),a=ft(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,t,a):r=await Te.runWithConfig(a,async()=>this.func(t,a)),J.isRunnable(r)&&this.recurse?await Te.runWithConfig(a,async()=>r.invoke(t,a)):r}};function*mn(e,t){if(t===void 0)yield*e;else for(const n of e)yield[t,n]}async function wn(e){const t=[];for await(const n of await e)t.push(n);return t}function hs(e){const t=[];for(const n of e)t.push(n);return t}function ur(e,t){return e?"configurable"in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function YO(e){return typeof e=="object"&&e?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const Wn={[Symbol.for("LG_PASSTHROUGH")]:!0};function ya(e){return typeof e=="object"&&e?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const Oo=Symbol("IS_WRITER");var Je=class Rc extends ir{writes;constructor(t,n){const r=`ChannelWrite<${t.map(s=>_t(s)?s.node:"channel"in s?s.channel:"...").join(",")}>`;super({writes:t,name:r,tags:n,func:async(s,a)=>this._write(s,a??{})}),this.writes=t}async _write(t,n){const r=this.writes.map(s=>xo(s)&&ya(s.value)?{mapper:s.mapper,value:t}:$a(s)&&ya(s.value)?{channel:s.channel,value:t,skipNone:s.skipNone,mapper:s.mapper}:s);return await Rc.doWrite(n,r),t}static async doWrite(t,n){for(const a of n){if($a(a)){if(a.channel===Et)throw new de("Cannot write to the reserved channel TASKS");if(ya(a.value))throw new de("PASSTHROUGH value must be replaced")}if(xo(a)&&ya(a.value))throw new de("PASSTHROUGH value must be replaced")}const r=[];for(const a of n)if(_t(a))r.push([Et,a]);else if(xo(a)){const i=await a.mapper.invoke(a.value,t);i!=null&&i.length>0&&r.push(...i)}else if($a(a)){const i=a.mapper!==void 0?await a.mapper.invoke(a.value,t):a.value;if(YO(i)||a.skipNone&&i===void 0)continue;r.push([a.channel,i])}else throw new Error(`Invalid write entry: ${JSON.stringify(a)}`);const s=t.configurable?.[Cn];s(r)}static isWriter(t){return t instanceof Rc||Oo in t&&!!t[Oo]}static registerWriter(t){return Object.defineProperty(t,Oo,{value:!0})}};function $a(e){return e!==void 0&&typeof e.channel=="string"}function xo(e){return e!==void 0&&!$a(e)&&J.isRunnable(e.mapper)}var XO=class kg extends ir{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(t,n,r=!1){super({func:(s,a)=>kg.doRead(a,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(",")}>`:`ChannelRead<${t}>`}static doRead(t,n,r,s){const a=t.configurable?.[Gn];if(!a)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return s?s(a(n,r)):a(n,r)}};const dr=new Ds;var Hs=class ps extends Fe{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=dr;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(t){const{channels:n,triggers:r,mapper:s,writers:a,bound:i,kwargs:o,metadata:c,retryPolicy:l,cachePolicy:u,tags:d,subgraphs:h,ends:p}=t,f=[...t.config?.tags?t.config.tags:[],...d??[]];super({...t,bound:t.bound??dr,config:{...t.config?t.config:{},tags:f}}),this.channels=n,this.triggers=r,this.mapper=s,this.writers=a??this.writers,this.bound=i??this.bound,this.kwargs=o??this.kwargs,this.metadata=c??this.metadata,this.tags=f,this.retryPolicy=l,this.cachePolicy=u,this.subgraphs=h,this.ends=p}getWriters(){const t=[...this.writers];for(;t.length>1&&t[t.length-1]instanceof Je&&t[t.length-2]instanceof Je;){const n=t.slice(-2),r=n[0].writes.concat(n[1].writes);t[t.length-2]=new Je(r,n[0].config?.tags),t.pop()}return t}getNode(){const t=this.getWriters();if(!(this.bound===dr&&t.length===0))return this.bound===dr&&t.length===1?t[0]:this.bound===dr?new kt({first:t[0],middle:t.slice(1,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):t.length>0?new kt({first:this.bound,middle:t.slice(0,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw new Error("channels must be a list");if(typeof this.channels!="object")throw new Error("all channels must be named when using .join()");return new ps({channels:{...this.channels,...Object.fromEntries(t.map(n=>[n,n]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(t){return Je.isWriter(t)?new ps({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===dr?new ps({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Le(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new ps({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function QO(e){return"steps"in e&&Array.isArray(e.steps)}function eu(e){return"lg_is_pregel"in e&&e.lg_is_pregel===!0}function Og(e){const t=[e];for(const n of t){if(eu(n))return n;QO(n)&&t.push(...n.steps)}}function Er(e,t,n=!0,r=!1){try{return e[t].get()}catch(s){if(s.name===je.unminifiable_name){if(r)return s;if(n)return null}throw s}}function qn(e,t,n=!0){if(Array.isArray(t)){const r={};for(const s of t)try{r[s]=Er(e,s,!n)}catch(a){if(a.name===je.unminifiable_name)continue}return r}else return Er(e,t)}function*ex(e,t){if(e.graph===be.PARENT)throw new de("There is no parent graph.");if(e.goto){let n;Array.isArray(e.goto)?n=e.goto:n=[e.goto];for(const r of n)if(_t(r))yield[Ct,Et,r];else if(typeof r=="string")yield[Ct,`branch:to:${r}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof r}`)}if(e.resume)if(typeof e.resume=="object"&&Object.keys(e.resume).length&&Object.keys(e.resume).every(Cg))for(const[n,r]of Object.entries(e.resume)){const s=t.filter(a=>a[0]===n&&a[1]===at).map(a=>a[2]).slice(0,1)??[];s.push(r),yield[n,at,s]}else yield[Ct,at,e.resume];if(e.update){if(typeof e.update!="object"||!e.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(e.update))for(const[n,r]of e.update)yield[Ct,n,r];else for(const[n,r]of Object.entries(e.update))yield[Ct,n,r]}}function*xg(e,t){if(t!=null)if(Array.isArray(e)&&typeof t=="object"&&!Array.isArray(t))for(const n in t)e.includes(n)&&(yield[n,t[n]]);else{if(Array.isArray(e))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[e,t]}}function*Io(e,t,n){Array.isArray(e)?(t===!0||t.find(([r,s])=>e.includes(r)))&&(yield qn(n,e)):(t===!0||t.some(([r,s])=>r===e))&&(yield Er(n,e))}function*tx(e,t,n){const r=t.filter(([o,c])=>(o.config===void 0||!o.config.tags?.includes(ve))&&c[0][0]!==tt&&c[0][0]!==Q);if(!r.length)return;let s;r.some(([o])=>o.writes.some(([c,l])=>c===Zr))?s=r.flatMap(([o])=>o.writes.filter(([c,l])=>c===Zr).map(([c,l])=>[o.name,l])):Array.isArray(e)?s=r.flatMap(([o])=>{const{writes:c}=o,l={};for(const[u]of c)e.includes(u)&&(l[u]=(l[u]||0)+1);return Object.values(l).some(u=>u>1)?c.filter(([u])=>e.includes(u)).map(([u,d])=>[o.name,{[u]:d}]):[[o.name,Object.fromEntries(c.filter(([u])=>e.includes(u)))]]}):s=r.flatMap(([o])=>o.writes.filter(([c,l])=>c===e).map(([c,l])=>[o.name,l]));const a={};for(const[o,c]of s)o in a||(a[o]=[]),a[o].push(c);const i={};for(const o in a)if(a[o].length===1){const[c]=a[o];i[o]=c}else i[o]=a[o];n&&(i.__metadata__={cached:n}),yield i}function tu(e){const t=typeof e[ie];if(t==="number")return 0;if(t==="string")return"";for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const r=typeof e[n];if(r==="number")return 0;if(r==="string")return"";break}}function La(e,t){if(Object.keys(e).length>0){const n=tu(t);return Object.fromEntries(Object.entries(t).filter(([r,s])=>s>(e[r]??n)))}else return t}function nx(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}function Rt(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function $n(e,t){const n=t?.parents??{};return Object.keys(n).length>0?Rt(e,{[St]:{...n,[e.configurable?.checkpoint_ns??""]:e.configurable?.checkpoint_id}}):e}function hi(...e){const t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};const n=new AbortController,r=()=>{const a=t.find(i=>i.aborted)?.reason;n.abort(a),t.forEach(i=>i.removeEventListener("abort",r))};t.forEach(a=>a.addEventListener("abort",r,{once:!0}));const s=t.find(a=>a.aborted);return s&&n.abort(s.reason),{signal:n.signal,dispose:()=>{t.forEach(a=>a.removeEventListener("abort",r))}}}const rx=(e,t)=>{if(!(!e&&!t))return e?t?Array.isArray(e)&&Array.isArray(t)?[...e,...t]:Array.isArray(e)?[...e,t]:Array.isArray(t)?[e,...t]:[e,t]:e:t};var sx=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:e,name:t,input:n,retry:r,cache:s,callbacks:a}){this.func=e,this.name=t,this.input=n,this.retry=r,this.cache=s,this.callbacks=a}};function ax(e){return typeof e=="object"&&e!==null&&"__lg_type"in e&&e.__lg_type==="call"}function ix(e,t){const n=new ir({func:r=>t(...r),name:e,trace:!1,recurse:!1});return new kt({name:e,first:n,last:new Je([{channel:Zr,value:Wn}],[ve])})}const ox=e=>e!==void 0?e+1:1;function cx(e,t){if(t==null)return!1;for(const n of e)if(t[n])return!0;return!1}function lx(e){let t;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t==null?t=e[n]:t=iO(t,e[n]));return t}function _a(e,t,n){const r=tu(e.channel_versions),s=e.versions_seen[Q]??{};let a=!1;if((e.channel_versions[ie]??r)>(s[ie]??r))a=!0;else for(const o in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,o)&&e.channel_versions[o]>(s[o]??r)){a=!0;break}const i=n.some(o=>t==="*"?!o.config?.tags?.includes(ve):t.includes(o.name));return a&&i}function ja(e,t,n,r,s=!1){let a=new Set;if(Array.isArray(r))a=new Set(r.filter(o=>n.writes.some(([c,l])=>c===o)));else{for(const[o]of n.writes)if(o===r){a=new Set([o]);break}a=a||new Set}let i;if(s&&a.size>0){const o=Object.fromEntries(Object.entries(t).filter(([u,d])=>a.has(u))),c=Fn(e,o,-1),l=ci(o,c);ht(oi(c),l,[n],void 0,void 0),i=qn({...t,...l},r)}else i=qn(t,r);return i}function Po(e,t,n){for(const[r,s]of n)if([pt,Et].includes(r)&&s!=null){if(!_t(s))throw new de(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in t))throw new de(`Invalid node name "${s.node}" in Send packet`)}e(n)}const ux=new Set([Xl,pt,at,Q,Zr,tt]);function ht(e,t,n,r,s){n.sort((h,p)=>{const f=h.path?.slice(0,3)||[],g=p.path?.slice(0,3)||[];for(let b=0;b<Math.min(f.length,g.length);b+=1){if(f[b]<g[b])return-1;if(f[b]>g[b])return 1}return f.length-g.length});const a=n.some(h=>h.triggers.length>0),i=Zl(t);for(const h of n){e.versions_seen[h.name]??={};for(const p of h.triggers)p in e.channel_versions&&(e.versions_seen[h.name][p]=e.channel_versions[p])}let o=lx(e.channel_versions);const c=new Set(n.flatMap(h=>h.triggers).filter(h=>!CO.includes(h)));let l=!1;for(const h of c)h in i&&i[h].consume()&&r!==void 0&&(e.channel_versions[h]=r(o),l=!0);const u={};for(const h of n)for(const[p,f]of h.writes)ux.has(p)||p in i&&(u[p]??=[],u[p].push(f));o!=null&&r!=null&&(o=l?r(o):o);const d=new Set;for(const[h,p]of Object.entries(u))if(h in i){const f=i[h];let g;try{g=f.update(p)}catch(b){if(b.name===de.unminifiable_name){const S=new de(`Invalid update for channel "${h}" with values ${JSON.stringify(p)}: ${b.message}`);throw S.lc_error_code=b.lc_error_code,S}else throw b}g&&r!==void 0&&(e.channel_versions[h]=r(o),f.isAvailable()&&d.add(h))}if(a)for(const h in i){if(!Object.prototype.hasOwnProperty.call(i,h))continue;const p=i[h];p.isAvailable()&&!d.has(h)&&p.update([])&&r!==void 0&&(e.channel_versions[h]=r(o),p.isAvailable()&&d.add(h))}if(a&&!cx(d,s))for(const h in i){if(!Object.prototype.hasOwnProperty.call(i,h))continue;const p=i[h];p.finish()&&r!==void 0&&(e.channel_versions[h]=r(o),p.isAvailable()&&d.add(h))}return d}function*dx(e,t,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){const s=new Set;for(const a of n.updatedChannels){const i=n.triggerToNodes[a];for(const o of i??[])s.add(o)}yield*[...s].sort();return}if(!(()=>{for(const s in e.channel_versions)if(e.channel_versions[s]!==null)return!1;return!0})())for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(yield s)}function wr(e,t,n,r,s,a,i){const o={},c=r[Et];if(c?.isAvailable()){const l=c.get().length;for(let u=0;u<l;u+=1){const d=$c([pt,u],e,t,n,r,s,a,i);d!==void 0&&(o[d.id]=d)}}for(const l of dx(e,n,i)){const u=$c([Ma,l],e,t,n,r,s,a,i);u!==void 0&&(o[u.id]=u)}return o}function $c(e,t,n,r,s,a,i,o){const{step:c,checkpointer:l,manager:u}=o,d=a.configurable??{},h=d.checkpoint_ns??"";if(e[0]===pt&&ax(e[e.length-1])){const p=e[e.length-1],f=ix(p.name,p.func),g=[pt],b=h===""?p.name:`${h}${xe}${p.name}`,S=gr(JSON.stringify([b,c.toString(),p.name,pt,e[1],e[2]]),t.id),w=`${b}${cn}${S}`,v=[...e.slice(0,3),!0],T={langgraph_step:c,langgraph_node:p.name,langgraph_triggers:g,langgraph_path:v,langgraph_checkpoint_ns:w};if(i){const k=[];return{name:p.name,input:p.input,proc:f,writes:k,config:ne(ft(a,{metadata:T,store:o.store??a.store}),{runName:p.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[_s]:S,[Cn]:C=>Po(y=>k.push(...y),r,C),[Gn]:(C,y=!1)=>ja(t,s,{name:p.name,writes:k,triggers:g,path:v},C,y),[_e]:l??d[_e],[St]:{...d[St],[h]:t.id},[An]:No({pendingWrites:n??[],taskId:S,currentTaskInput:p.input,resumeMap:a.configurable?.[Pa],namespaceHash:jn(w)}),[Na]:t.channel_values[Ao],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:g,retry_policy:p.retry,cache_key:p.cache?{key:jn((p.cache.keyFunc??JSON.stringify)([p.input])),ns:[Co,p.name??"__dynamic__"],ttl:p.cache.ttl}:void 0,id:S,path:v,writers:[]}}else return{id:S,name:p.name,interrupts:[],path:v}}else if(e[0]===pt){const p=typeof e[1]=="number"?e[1]:parseInt(e[1],10);if(!s[Et]?.isAvailable())return;const f=s[Et].get();if(p<0||p>=f.length)return;const g=Pc(f[p])&&!_t(f[p])?new We(f[p].node,f[p].args):f[p];if(!Pc(g)){console.warn(`Ignoring invalid packet ${JSON.stringify(g)} in pending sends.`);return}if(!(g.node in r)){console.warn(`Ignoring unknown node name ${g.node} in pending sends.`);return}const b=[pt],S=h===""?g.node:`${h}${xe}${g.node}`,w=gr(JSON.stringify([S,c.toString(),g.node,pt,p.toString()]),t.id),v=`${S}${cn}${w}`;let T={langgraph_step:c,langgraph_node:g.node,langgraph_triggers:b,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:v};if(i){const k=r[g.node],O=k.getNode();if(O!==void 0){k.metadata!==void 0&&(T={...T,...k.metadata});const C=[];return{name:g.node,input:g.args,proc:O,subgraphs:k.subgraphs,writes:C,config:ne(ft(a,{metadata:T,tags:k.tags,store:o.store??a.store}),{runName:g.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[_s]:w,[Cn]:y=>Po(N=>C.push(...N),r,y),[Gn]:(y,N=!1)=>ja(t,s,{name:g.node,writes:C,triggers:b,path:e},y,N),[_e]:l??d[_e],[St]:{...d[St],[h]:t.id},[An]:No({pendingWrites:n??[],taskId:w,currentTaskInput:g.args,resumeMap:a.configurable?.[Pa],namespaceHash:jn(v)}),[Na]:t.channel_values[Ao],checkpoint_id:void 0,checkpoint_ns:v}}),triggers:b,retry_policy:k.retryPolicy,cache_key:k.cachePolicy?{key:jn((k.cachePolicy.keyFunc??JSON.stringify)([g.args])),ns:[Co,k.name??"__dynamic__",g.node],ttl:k.cachePolicy.ttl}:void 0,id:w,path:e,writers:k.getWriters()}}}else return{id:w,name:g.node,interrupts:[],path:e}}else if(e[0]===Ma){const p=e[1].toString(),f=r[p];if(f===void 0)return;if(n?.length){const w=h===""?p:`${h}${xe}${p}`,v=gr(JSON.stringify([w,c.toString(),p,Ma,p]),t.id);if(n.some(k=>k[0]===v&&k[1]!==tt))return}const g=tu(t.channel_versions);if(g===void 0)return;const b=t.versions_seen[p]??{},S=f.triggers.find(w=>s[w].isAvailable()?(t.channel_versions[w]??g)>(b[w]??g):!1);if(S!==void 0){const w=hx(f,s,i);if(w===void 0)return;const v=h===""?p:`${h}${xe}${p}`,T=gr(JSON.stringify([v,c.toString(),p,Ma,[S]]),t.id),k=`${v}${cn}${T}`;let O={langgraph_step:c,langgraph_node:p,langgraph_triggers:[S],langgraph_path:e,langgraph_checkpoint_ns:k};if(i){const C=f.getNode();if(C!==void 0){f.metadata!==void 0&&(O={...O,...f.metadata});const y=[];return{name:p,input:w,proc:C,subgraphs:f.subgraphs,writes:y,config:ne(ft(a,{metadata:O,tags:f.tags,store:o.store??a.store}),{runName:p,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[_s]:T,[Cn]:N=>Po(I=>{y.push(...I)},r,N),[Gn]:(N,I=!1)=>ja(t,s,{name:p,writes:y,triggers:[S],path:e},N,I),[_e]:l??d[_e],[St]:{...d[St],[h]:t.id},[An]:No({pendingWrites:n??[],taskId:T,currentTaskInput:w,resumeMap:a.configurable?.[Pa],namespaceHash:jn(k)}),[Na]:t.channel_values[Ao],checkpoint_id:void 0,checkpoint_ns:k}}),triggers:[S],retry_policy:f.retryPolicy,cache_key:f.cachePolicy?{key:jn((f.cachePolicy.keyFunc??JSON.stringify)([w])),ns:[Co,f.name??"__dynamic__",p],ttl:f.cachePolicy.ttl}:void 0,id:T,path:e,writers:f.getWriters()}}}else return{id:T,name:p,interrupts:[],path:e}}}}function hx(e,t,n){let r;if(typeof e.channels=="object"&&!Array.isArray(e.channels)){r={};for(const[s,a]of Object.entries(e.channels))if(e.triggers.includes(a))try{r[s]=Er(t,a,!1)}catch(i){if(i.name===je.unminifiable_name)return;throw i}else if(a in t)try{r[s]=Er(t,a,!1)}catch(i){if(i.name===je.unminifiable_name)continue;throw i}}else if(Array.isArray(e.channels)){let s=!1;for(const a of e.channels)try{r=Er(t,a,!1),s=!0;break}catch(i){if(i.name===je.unminifiable_name)continue;throw i}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return n&&e.mapper!==void 0&&(r=e.mapper(r)),r}function No({pendingWrites:e,taskId:t,currentTaskInput:n,resumeMap:r,namespaceHash:s}){const a=e.find(([c,l])=>c===Ct&&l===at)?.[2],o={callCounter:0,interruptCounter:-1,resume:(()=>{const c=e.filter(([l,u])=>l===t&&u===at).flatMap(([l,u,d])=>d);if(r!=null&&s in r){const l=r[s];c.push(l)}return c})(),nullResume:a,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(o.nullResume)return delete o.nullResume,e.splice(e.findIndex(([c,l])=>c===Ct&&l===at),1),a}};return o}const Vs={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},Gs=(e,t)=>`${e.start}${t}${e.end}`;function*Dd(e){for(const{id:t,name:n,input:r,config:s,triggers:a,writes:i}of e){if(s?.tags?.includes(ve))continue;const o=i.filter(([c,l])=>c===t&&l===Q).map(([,c])=>c);yield{id:t,name:n,input:r,triggers:a,interrupts:o}}}function px(e){return typeof e!="object"||e===null?!1:"$writes"in e&&Array.isArray(e.$writes)}function Ig(e){const t={};for(const[n,r]of e){const s=String(n);if(s in t){const a=px(t[s])?t[s].$writes:[t[s]];a.push(r),t[s]={$writes:a}}else t[s]=r}return t}function*fx(e,t){for(const[{id:n,name:r,config:s},a]of e)s?.tags?.includes(ve)||(yield{id:n,name:r,result:Ig(a.filter(([i])=>Array.isArray(t)?t.includes(i):i===t)),interrupts:a.filter(i=>i[0]===Q).map(i=>i[1])})}function*mx(e,t,n,r,s,a,i,o){function c(d){const h={};return d.callbacks!=null&&(h.callbacks=d.callbacks),d.configurable!=null&&(h.configurable=d.configurable),d.maxConcurrency!=null&&(h.max_concurrency=d.maxConcurrency),d.metadata!=null&&(h.metadata=d.metadata),d.recursionLimit!=null&&(h.recursion_limit=d.recursionLimit),d.runId!=null&&(h.run_id=d.runId),d.runName!=null&&(h.run_name=d.runName),d.tags!=null&&(h.tags=d.tags),h}const l=e.configurable?.checkpoint_ns,u={};for(const d of s){if(!(d.subgraphs?.length?d.subgraphs:[d.proc]).find(Og))continue;let p=`${d.name}:${d.id}`;l&&(p=`${l}|${p}`),u[d.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:p}}}yield{config:c(e),values:qn(t,n),metadata:r,next:s.map(d=>d.name),tasks:Pg(s,a,u,o),parentConfig:i?c(i):void 0}}function Pg(e,t,n,r){return e.map(s=>{const a=t.find(([l,u])=>l===s.id&&u===tt)?.[2],i=t.filter(([l,u])=>l===s.id&&u===Q).map(([,,l])=>l),o=(()=>{if(a||i.length||!t.length)return;const l=t.findIndex(([u,d])=>u===s.id&&d===Zr);if(l>=0)return t[l][2];if(typeof r=="string")return t.find(([u,d])=>u===s.id&&d===r)?.[2];if(Array.isArray(r)){const u=t.filter(([d,h])=>d===s.id&&r.includes(h)).map(([,d,h])=>[d,h]);return u.length?Ig(u):void 0}})();if(a)return{id:s.id,name:s.name,path:s.path,error:a,interrupts:i,result:o};const c=n?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:i,...c!==void 0?{state:c}:{},result:o}})}function gx(e,t,n){console.log([`${Gs(Vs.blue,`[${e}:checkpoint]`)}`,`\x1B[1m State at the end of step ${e}:\x1B[0m
190
- `,JSON.stringify(qn(t,n),null,2)].join(""))}function Ng(e,t){const n=t.length;console.log([`${Gs(Vs.blue,`[${e}:tasks]`)}`,`\x1B[1m Starting step ${e} with ${n} task${n===1?"":"s"}:\x1B[0m
191
- `,t.map(r=>`- ${Gs(Vs.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
192
- `)].join(""))}function yx(e,t,n){const r={};for(const[s,a]of t)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(a));console.log([`${Gs(Vs.blue,`[${e}:writes]`)}`,`\x1B[1m Finished step ${e} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
193
- `,Object.entries(r).map(([s,a])=>`- ${Gs(Vs.yellow,s)} -> ${a.map(i=>JSON.stringify(i)).join(", ")}`).join(`
194
- `)].join(""))}var Fd=class extends Be{_abortController;_innerReader;constructor(e,t){const n=e.getReader(),r=t??new AbortController;super({start(s){return a();function a(){return n.read().then(({done:i,value:o})=>{if(i){s.close();return}return s.enqueue(o),a()})}}}),this._abortController=r,this._innerReader=n}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},Mg=class extends Be{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(e){let t;const n=new Promise(r=>{t=r});super({start:r=>{t(r)}}),n.then(r=>{this.controller=r}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this.passthroughFn?.(e),this.controller.enqueue(e)}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){this.controller.error(e)}};function _x(e){return JSON.stringify(e,function(t,n){const r=this[t];if(r!=null&&typeof r=="object"&&"toDict"in r&&typeof r.toDict=="function"){const{type:s,data:a}=r.toDict();return{...a,type:s}}return n})}function wx(e){return e instanceof Error?{error:e.name,message:e.message}:{error:"Error",message:JSON.stringify(e)}}function nu(e){return typeof e!="object"||e==null?!1:"configurable"in e&&typeof e.configurable=="object"&&e.configurable!=null}function Mo(e){return!nu(e)||!e.configurable.thread_id?null:{thread_id:e.configurable.thread_id,checkpoint_ns:e.configurable.checkpoint_ns||"",checkpoint_id:e.configurable.checkpoint_id||null,checkpoint_map:e.configurable.checkpoint_map||null}}function Ud(e){if(nu(e)){const t=Object.fromEntries(Object.entries(e.configurable).filter(([r])=>!r.startsWith("__"))),n={...e,configurable:t};return delete n.callbacks,n}return e}function Bd(e){const t={...e,checkpoint:Mo(e.config),parent_checkpoint:Mo(e.parentConfig),config:Ud(e.config),parent_config:Ud(e.parentConfig),tasks:e.tasks.map(n=>{if(nu(n.state)){const r=Mo(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete t.parentConfig,t}function vx(e){const t=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(t.encode(`event: ${s.event}
195
- data: ${_x(s.data)}
196
-
197
- `))};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:Bd(u.payload)})}i==="checkpoints"&&(c=Bd(o));const l=a?.length?`${i}|${a.join("|")}`:i;r({event:l,data:c})}}catch(s){r({event:"error",data:wx(s)})}n.close()}})}const wa=Symbol.for("INPUT_DONE"),Ro=Symbol.for("INPUT_RESUMING"),bx=25;function Sx(...e){return new Mg({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 Tx=class extends hO{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}},Ex=class Rg{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?.[_n]!==void 0&&this.config.configurable?.[_n],s=this.input===null||this.input===void 0,a=Ne(this.input)&&this.input.resume!=null,i=this.input===Ro,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=ox,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 Tx(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?.[li]!==void 0&&(r=Sx(r,n.configurable[li]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,a=n.configurable?.[An];n.configurable&&a&&(a.subgraphCounter>0&&(n=Rt(n,{[zt]:[n.configurable[zt],a.subgraphCounter.toString()].join(xe)})),a.subgraphCounter+=1);const i=Gn in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=Rt(n,{checkpoint_ns:"",checkpoint_id:void 0}));let o=n;n.configurable?.[St]!==void 0&&n.configurable?.[St]?.[n.configurable?.checkpoint_ns]&&(o=Rt(n,{checkpoint_id:n.configurable[St][n.configurable?.checkpoint_ns]}));const c=n.configurable?.checkpoint_ns?.split(xe)??[],l=await t.checkpointer?.getTuple(o)??{config:n,checkpoint:ig(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};o={...n,...l.config,configurable:{checkpoint_ns:"",...n.configurable,...l.config.configurable}};const u=l.parentConfig,d=oi(l.checkpoint),h={...l.metadata},p=l.pendingWrites??[],f=ci(t.channelSpecs,d),g=(h.step??0)+1,b=g+(n.recursionLimit??bx)+1,S={...d.channel_versions},w=t.store?new dO(t.store):void 0;return w&&await w.start(),new Rg({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:g,stop:b,checkpointPreviousVersions:S,checkpointPendingWrites:p,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:r,store:w,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 oO)&&(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=Rt(this.checkpointConfig,{[zt]:this.config.configurable?.checkpoint_ns??"",[Ic]: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]===Q||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]===Q){if(s.path?.[0]===pt&&s.path?.at(-1)===!0)return;const a=n.filter(i=>i[0]===Q).flatMap(i=>i[1]);this._emit([["updates",{[Q]:a}],["values",{[Q]:a}]])}else n[0][0]!==tt&&this._emit(hs(mn(tx(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(hs(mn(fx([[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(![wa,Ro].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=ht(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const i=await wn(mn(Io(this.outputKeys,a,this.channels),"values"));if(this._emit(i),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),_a(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new Sr;this.config.configurable?.[_n]!==void 0&&delete this.config.configurable?.[_n]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const r=wr(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 wn(mn(mx(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===Q||i===at)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(_a(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new Sr;const s=await wn(mn(Dd(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(cn)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(t);return(n||t===void 0)&&(this.output=qn(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=ht(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(hs(mn(Io(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),Bn(t)&&!t.interrupts.length&&this._emit([["updates",{[Q]:[]}],["values",{[Q]:[]}]])),n}async acceptPush(t,n,r){if(this.interruptAfter?.length>0&&_a(this.checkpoint,this.interruptAfter,[t])){this.toInterrupt.push(t);return}const s=$c([pt,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&&_a(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(hs(mn(Dd([s]),"tasks"))),this.debug&&Ng(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?.[An];if(r&&r.nullResume!==void 0&&this.putWrites(Ct,[[at,r.nullResume]]),Ne(this.input)){const i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(Cg)&&(this.config.configurable??={},this.config.configurable[Pa]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const o={};for(const[c,l,u]of ex(this.input,this.checkpointPendingWrites))o[c]??=[],o[c].push([l,u]);if(Object.keys(o).length===0)throw new Pd("Received empty Command input");for(const[c,l]of Object.entries(o))this.putWrites(c,l)}const s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===Ct).map(i=>i.slice(1));s.length>0&&ht(this.checkpoint,this.channels,[{name:Qt,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const a=Ne(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[Q]={...this.checkpoint.versions_seen[Q],[o]:c}}const i=await wn(mn(Io(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=Ro;else if(a)await this._putCheckpoint({source:"input"}),this.input=wa;else{const i=await wn(xg(t,this.input));if(i.length>0){const o=wr(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=ht(this.checkpoint,this.channels,Object.values(o).concat([{name:Qt,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=wa}else if(_n in(this.config.configurable??{}))this.input=wa;else throw new Pd(`Received no input writes for ${JSON.stringify(t,null,2)}`)}this.isNested||(this.config=Rt(this.config,{[_n]: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=Rt(this.checkpointConfig,{[zt]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},o=La(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:oi(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?.[St]??{}}),this.checkpoint=Fn(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=Rt(this.checkpointConfig,{[zt]:this.config.configurable?.checkpoint_ns??"",[Ic]: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===Q||r===at)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 Cx(e){return Pe(e?.message)}var Ax=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&&(el(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(EO)&&!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&&(Cx(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new yt({content:e}),n))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){const n=e.generations?.[0]?.[0];Pe(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((Pe(c)||As(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(const l of c)(Pe(l)||As(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(Pe(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(const r of e)Pe(r)&&this._emit(n,r,t,!0);else if(e!=null&&typeof e=="object"){for(const r of Object.values(e))if(Pe(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(const s of r)Pe(s)&&this._emit(n,s,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};const kx=500,Ox=2,xx=128e3,Ix=3,Px=[400,401,402,403,404,405,406,407,409],Nx=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&&Px.includes(+t)||e?.error?.code==="insufficient_quota")};async function $g(e,t,n,r){const s=e.retry_policy??t;let a=s!==void 0?s.initialInterval??kx:0,i=0,o,c,{config:l}=e;for(n&&(l=Rt(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,yO(o)){const f=l?.configurable?.checkpoint_ns,g=o.command;if(g.graph===f){for(const b of e.writers)await b.invoke(g,l);o=void 0;break}else if(g.graph===be.PARENT){const b=PO(f);o.command=new be({...o.command,graph:b})}}if(Ia(o)||s===void 0||(i+=1,i>=(s.maxAttempts??Ix))||!(s.retryOn??Nx)(o))break;a=Math.min(s.maxInterval??xx,a*(s.backoffFactor??Ox));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=Rt(l,{[_n]:!0})}}return{task:e,result:c,error:o,signalAborted:r?.aborted}}const Lc=Symbol.for("promiseAdded");function Mx(){const e={next:()=>{},wait:Promise.resolve(Lc)};function t(n){e.next=()=>{e.wait=new Promise(t),n(Lc)}}return e.wait=new Promise(t),e}var Rx=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:g,signalAborted:b}of p)this._commit(f,g),Bn(g)||Ia(g)&&!Bn(i)?i=g:g&&(a.size===0||!b)&&(o.abort(),a.add(g));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)||Ia(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:n}){const r=this.loop.config.configurable?.[Nd]??{},s=r.externalAbortSignal??n,a=t??r.timeoutAbortSignal,{signal:i,dispose:o}=hi(s,a,e),c={externalAbortSignal:s,timeoutAbortSignal:a,composedAbortSignal:i};return this.loop.config=Rt(this.loop.config,{[Nd]:c}),{signals:c,disposeCombinedSignal:o}}async*_executeTasksWithRetry(e,t){const{retryPolicy:n,maxConcurrency:r,signals:s}=t??{},a=Mx(),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=hi(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]=$g(p,n,{[Yl]:Lg?.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!==Lc&&(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=>[Q,s]),r=e.writes.filter(s=>s[0]===at);r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else Ia(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([Xl,null]),this.loop.putWrites(e.id,e.writes)}};async function Lg(e,t,n,r,s,a={}){const i=t.config?.configurable?.[An];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 sx({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===Zr),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=$g(l,a.retry,{[Yl]:Lg.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 qt=class extends Error{constructor(e){super(e),this.name="GraphValidationError"}};function $x({nodes:e,channels:t,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:a,interruptBeforeNodes:i}){if(!t)throw new qt("Channels not provided");const o=new Set,c=new Set;for(const[l,u]of Object.entries(e)){if(l===Q)throw new qt(`"Node name ${Q} is reserved"`);if(u.constructor===Hs)u.triggers.forEach(d=>o.add(d));else throw new qt(`Invalid node type ${typeof u}, expected PregelNode`)}for(const l of o)if(!(l in t))throw new qt(`Subscribed channel '${String(l)}' not in channels`);if(Array.isArray(n)){if(n.every(l=>!o.has(l)))throw new qt(`None of the input channels ${n} are subscribed to by any node`)}else if(!o.has(n))throw new qt(`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 qt(`Output channel '${String(l)}' not in channels`);if(a&&a!=="*"){for(const l of a)if(!(l in e))throw new qt(`Node ${String(l)} not in nodes`)}if(i&&i!=="*"){for(const l of i)if(!(l in e))throw new qt(`Node ${String(l)} not in nodes`)}}function zd(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 Lx=class jg extends ar{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 jg({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 je;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},jx=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 Hs({channels:s,triggers:a,tags:r})}static writeTo(e,t){const n=[];for(const r of e)n.push({channel:r,value:Wn,skipNone:!1});for(const[r,s]of Object.entries(t??{}))J.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:Wn,skipNone:!0,mapper:Le(s)}):n.push({channel:r,value:s,skipNone:!1});return new Je(n)}},Dx=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)}},Fx=class extends Dx{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,Et in this.channels&&"lc_graph_name"in this.channels[Et]&&this.channels[Et].lc_graph_name!=="Topic")throw new Error(`Channel '${Et}' is reserved and cannot be used in the graph.`);this.channels[Et]=new Lx({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=ft(this.config,e);return new this.constructor({...this,config:t})}validate(){$x({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=Og(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}${xe}${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=ci(this.channels,t.checkpoint);if(t.pendingWrites?.length){const d=t.pendingWrites.filter(([h,p])=>h===Ct).map(([h,p,f])=>[String(p),f]);d.length>0&&ht(t.checkpoint,s,[{name:Qt,writes:d,triggers:[]}],void 0,this.triggerToNodes)}const a=Object.values(wr(t.checkpoint,t.pendingWrites,this.nodes,s,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),i=await wn(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)}${cn}${d.id}`;if(o&&(p=`${o}${xe}${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}},g=h[1];c[d.id]=await g.getState(f,{subgraphs:!0})}}if(r&&t.pendingWrites?.length){const d=Object.fromEntries(a.map(p=>[p.id,p]));for(const[p,f,g]of t.pendingWrites)[tt,Q,Ta].includes(f)||p in d&&d[p].writes.push([String(f),g]);const h=a.filter(p=>p.writes.length>0);h.length>0&&ht(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:qn(s,this.streamChannelsAsIs),next:u,tasks:Pg(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 xa("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=e.configurable?.checkpoint_ns??"";if(r!==""&&e.configurable?.[_e]===void 0){const o=ko(r);for await(const[c,l]of this.getSubgraphsAsync(o,!0))if(c===o)return await l.getState(ur(e,{[_e]:n}),{subgraphs:t?.subgraphs});throw new Error(`Subgraph with namespace "${o}" not found.`)}const s=ft(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 xa("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=e.configurable?.checkpoint_ns??"";if(r!==""&&e.configurable?.[_e]===void 0){const a=ko(r);for await(const[i,o]of this.getSubgraphsAsync(a,!0))if(i===a){yield*o.getStateHistory(ur(e,{[_e]:n}),t);return}throw new Error(`Subgraph with namespace "${a}" not found.`)}const s=ft(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 xa("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=ko(r);for await(const[,o]of this.getSubgraphsAsync(i,!0))return await o.bulkUpdateState(ur(e,{[_e]:n}),t);throw new Error(`Subgraph "${i}" not found`)}const s=async(i,o)=>{const c=this.config?ft(this.config,i):i,l=await n.getTuple(c),u=l!==void 0?oi(l.checkpoint):ig(),d={...l?.checkpoint.channel_versions},h=l?.metadata?.step??-1;let p=ur(c,{checkpoint_ns:c.configurable?.checkpoint_ns??""}),f=c.metadata??{};l?.config.configurable&&(p=ur(c,l.config.configurable),f={...l.metadata,...f});const{values:g,asNode:b}=o[0];if(g==null&&b===void 0){if(o.length>1)throw new de("Cannot create empty checkpoint with multiple updates");const C=await n.put(p,Fn(u,void 0,h),{source:"update",step:h+1,parents:l?.metadata?.parents??{}},{});return $n(C,l?l.metadata:void 0)}const S=ci(this.channels,u);if(g===null&&b===B){if(o.length>1)throw new de("Cannot apply multiple updates when clearing state");if(l){const y=wr(u,l.pendingWrites||[],this.nodes,S,l.config,!0,{step:(l.metadata?.step??-1)+1,checkpointer:n,store:this.store}),N=(l.pendingWrites||[]).filter(I=>I[0]===Ct).map(I=>I.slice(1));N.length>0&&ht(u,S,[{name:Qt,writes:N,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[I,R,z]of l.pendingWrites||[])[tt,Q,Ta].includes(R)||I in y&&y[I].writes.push([R,z]);ht(u,S,Object.values(y),n.getNextVersion.bind(n),this.triggerToNodes)}const C=await n.put(p,Fn(u,S,h),{...f,source:"update",step:h+1,parents:l?.metadata?.parents??{}},La(d,u.channel_versions));return $n(C,l?l.metadata:void 0)}if(b===bO){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 C=I=>!Array.isArray(I)||I.length===0?!1:I.every(R=>Array.isArray(R)&&R.length===2),y=Fn(u,void 0,h),N=await n.put(l.parentConfig??ur(l.config,{checkpoint_id:void 0}),y,{source:"fork",step:h+1,parents:l.metadata?.parents??{}},{});if(C(g)){const I=wr(y,l.pendingWrites,this.nodes,S,N,!1,{step:h+2}),R=Object.values(I).reduce((ce,{name:fe,id:or})=>(ce[fe]??=[],ce[fe].push({id:or}),ce),{}),z=g.reduce((ce,fe)=>{const[or,q]=fe;ce[q]??=[];const zi=ce[q].length,as=R[q]?.[zi]?.id;return ce[q].push({values:or,asNode:q,taskId:as}),ce},{});return s($n(N,l.metadata),Object.values(z).flat())}return $n(N,l.metadata)}if(b===Qt){if(o.length>1)throw new de("Cannot apply multiple updates when updating as input");const C=await wn(xg(this.inputChannels,g));if(C.length===0)throw new de(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);ht(u,S,[{name:Qt,writes:C,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const y=l?.metadata?.step!=null?l.metadata.step+1:-1,N=await n.put(p,Fn(u,S,y),{source:"input",step:y,parents:l?.metadata?.parents??{}},La(d,u.channel_versions));return await n.putWrites(N,C,gr(Qt,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 C=wr(u,l.pendingWrites,this.nodes,S,l.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(l.metadata?.step??-1)+1}),y=(l.pendingWrites??[]).filter(I=>I[0]===Ct).map(I=>I.slice(1));y.length>0&&ht(l.checkpoint,S,[{name:Qt,writes:y,triggers:[]}],void 0,this.triggerToNodes);for(const[I,R,z]of l.pendingWrites)[tt,Q,Ta].includes(R)||C[I]===void 0||C[I].writes.push([R,z]);const N=Object.values(C).filter(I=>I.writes.length>0);N.length>0&&ht(u,S,N,void 0,this.triggerToNodes)}const w=Object.values(u.versions_seen).map(C=>Object.values(C)).flat().find(C=>!!C),v=[];if(o.length===1){let{values:C,asNode:y,taskId:N}=o[0];if(y===void 0&&Object.keys(this.nodes).length===1)[y]=Object.keys(this.nodes);else if(y===void 0&&w===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(y=this.inputChannels);else if(y===void 0){const I=Object.entries(u.versions_seen).map(([R,z])=>Object.values(z).map(ce=>[ce,R])).flat().filter(([R,z])=>z!==Q).sort(([R],[z])=>og(R,z));I&&(I.length===1?y=I[0][1]:I[I.length-1][0]!==I[I.length-2][0]&&(y=I[I.length-1][1]))}if(y===void 0)throw new de('Ambiguous update, specify "asNode"');v.push({values:C,asNode:y,taskId:N})}else for(const{asNode:C,values:y,taskId:N}of o){if(C==null)throw new de('"asNode" is required when applying multiple updates');v.push({values:y,asNode:C,taskId:N})}const T=[];for(const{asNode:C,values:y,taskId:N}of v){if(this.nodes[C]===void 0)throw new de(`Node "${C.toString()}" does not exist`);const I=this.nodes[C].getWriters();if(!I.length)throw new de(`No writers found for node "${C.toString()}"`);T.push({name:C,input:y,proc:I.length>1?kt.from(I,{omitSequenceTags:!0}):I[0],writes:[],triggers:[Q],id:N??gr(Q,u.id),writers:[]})}for(const C of T)await C.proc.invoke(C.input,ne({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[Cn]:y=>C.writes.push(...y),[Gn]:(y,N=!1)=>ja(u,S,C,y,N)}}));for(const C of T){const y=C.writes.filter(N=>N[0]!==pt);l!==void 0&&y.length>0&&await n.putWrites(p,y,C.id)}ht(u,S,T,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const k=La(d,u.channel_versions),O=await n.put(p,Fn(u,S,h+1),{source:"update",step:h+1,parents:l?.metadata?.parents??{}},k);for(const C of T){const y=C.writes.filter(N=>N[0]===pt);y.length>0&&await n.putWrites(O,y,C.id)}return $n(O,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:zd(u,this.channels);let d=r;d===void 0?d=this.inputChannels:zd(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?.[_s]!==void 0?f=["values"]:f=this.streamMode,c=!0);let g;if(this.checkpointer===!1)g=void 0;else if(e!==void 0&&e.configurable?.[_e]!==void 0)g=e.configurable[_e];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");g=this.checkpointer}const b=e.store??this.store,S=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 w=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),v=e.durability??w??e?.configurable?.[gg]??"async";return[l,f,d,u,o,h,p,g,b,c,S,v]}async stream(e,t){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...t,signal:hi(t?.signal,n.signal).signal},s=await super.stream(e,r);return new Fd(t?.encoding==="text/event-stream"?vx(s):s,n)}streamEvents(e,t,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...t,callbacks:rx(this.config?.callbacks,t?.callbacks),signal:hi(t?.signal,r.signal).signal};return new Fd(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=_g(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,g,b,S,w]=this._defaults(o);typeof d.context<"u"?d.context=await this._validateContext(d.context):d.configurable=await this._validateContext(d.configurable);const v=new Mg({modes:new Set(l)});if(this.checkpointer===!0){d.configurable??={};const R=d.configurable[zt]??"";d.configurable[zt]=R.split(xe).map(z=>z.split(cn)[0]).join(xe)}if(l.includes("messages")){const R=new Ax(ce=>v.push(ce)),{callbacks:z}=d;if(z===void 0)d.callbacks=[R];else if(Array.isArray(z))d.callbacks=z.concat(R);else{const ce=z.copy();ce.addHandler(R,!0),d.callbacks=ce}}d.writer??=R=>{if(!l.includes("custom"))return;const z=IO()?.configurable?.[zt]?.split(xe).slice(0,-1);v.push([z??[],"custom",R])},d.interrupt??=this.userInterrupt??Ag;const k=await(await st(d))?.handleChainStart(this.toJSON(),nx(e,"input"),i,void 0,void 0,void 0,d?.runName??this.getName()),O=Zl(this.channels);let C,y;const I=(async()=>{try{C=await Ex.initialize({input:a,config:d,checkpointer:f,nodes:this.nodes,channelSpecs:O,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:g,cache:S,stream:v,interruptAfter:p,interruptBefore:h,manager:k,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:w});const R=new Rx({loop:C,nodeFinished:d.configurable?.[TO]});t?.subgraphs&&(C.config.configurable={...C.config.configurable,[li]:C.stream}),await this._runLoop({loop:C,runner:R,debug:c,config:d}),w==="sync"&&await Promise.all(C?.checkpointerPromises??[])}catch(R){y=R}finally{try{C&&(await C.store?.stop(),await C.cache?.stop()),await Promise.all(C?.checkpointerPromises??[])}catch(R){y=y??R}y?v.error(y):v.close()}})();try{for await(const R of v){if(R===void 0)throw new Error("Data structure error.");const[z,ce,fe]=R;if(l.includes(ce)){if(n==="text/event-stream"){r?yield[z,ce,fe]:yield[null,ce,fe];continue}r&&!b?yield[z,ce,fe]:b?r?yield[z,fe]:yield fe:yield[ce,fe]}}}catch(R){throw await k?.handleChainError(y),R}finally{await I}await k?.handleChainEnd(C?.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"?yg(c)?i.push(c[Q]):o=c:s.push(c);if(n==="values"){if(i.length>0){const c=i.flat(1);if(o==null)return{[Q]:c};if(typeof o=="object")return{...o,[Q]: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&&gx(t.checkpointMetadata.step,t.channels,this.streamChannelsList),r&&Ng(t.step,Object.values(t.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,o)=>{r&&yx(i,o,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(t.status==="out_of_steps")throw new gO([`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([])}},Yr=class Dg extends ar{lc_graph_name="EphemeralValue";guard;value=[];constructor(t=!0){super(),this.guard=t}fromCheckpoint(t){const n=new Dg(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 je;return this.value[0]}checkpoint(){if(this.value.length===0)throw new je;return this.value[0]}isAvailable(){return this.value.length!==0}},Fg=class{path;ends;constructor(e){J.isRunnable(e.path)?this.path=e.path:this.path=Le(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 ir({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,e,t)}catch(s){throw s.name===ug.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
198
- 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=>_t(o)?o:this.ends[o]):a=s,a.some(o=>!o))throw new Error("Branch condition returned unknown or null destination");if(a.filter(_t).some(o=>o.node===B))throw new de("Cannot send a packet to the END node");return await n(a,t)??e}},Ux=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[xe,cn])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=Le(s);this.nodes[r]={runnable:i,metadata:a?.metadata,subgraphs:eu(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=Le(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 Fg(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 Ug({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[ie]:new Yr,[B]:new Yr},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 _O([`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(`
199
- `),{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}},Ug=class extends Fx{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new Yr,this.nodes[e]=new Hs({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new Je([{channel:e,value:Wn}],[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:Wn}],[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]=jx.subscribeTo(ie,{tags:[ve]})),this.nodes[e].pipe(n.run(s=>{const a=s.map(i=>_t(i)?i:{channel:i===B?B:`branch:${e}:${t}:${i}`,value:Wn});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 Yr,this.nodes[s].triggers.push(a),this.nodes[s].channels.push(a)}}async getGraphAsync(e){const t=e?.xray,n=new Rs,r={[ie]:n.addNode({schema:ca()},ie)},s={};let a={};t&&(a=Object.fromEntries((await wn(this.getSubgraphsAsync())).filter(c=>Hd(c[1]))));function i(c,l,u,d=!1){if(l===B&&s[B]===void 0&&(s[B]=n.addNode({schema:ca()},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=De(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 S=function(v){return v?v.lc_runnable:!1},w=function(v,T){if(v!==void 0&&!br(v))return v;if(S(T))try{let k=T.getName();return k=k.startsWith("Runnable")?k.slice(8):k,k}catch{return T.getName()}else return T.name??"UnknownSchema"};const[g,b]=n.extend(f,u);if(g===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);b!==void 0&&(r[u]={name:w(b.id,b.data),...b}),s[u]={name:w(g.id,g.data),...g}}else{const g=n.addNode(d,u,h);r[u]=g,s[u]=g}}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(De(c),De(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=>[De(d),De(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(De(c),De(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(De(c),De(u),void 0,!0);return n}getGraph(e){const t=e?.xray,n=new Rs,r={[ie]:n.addNode({schema:ca()},ie)},s={};let a={};t&&(a=Object.fromEntries(hs(this.getSubgraphs()).filter(c=>Hd(c[1]))));function i(c,l,u,d=!1){return l===B&&s[B]===void 0&&(s[B]=n.addNode({schema:ca()},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=De(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 S=function(v){return v?v.lc_runnable:!1},w=function(v,T){if(v!==void 0&&!br(v))return v;if(S(T))try{let k=T.getName();return k=k.startsWith("Runnable")?k.slice(8):k,k}catch{return T.getName()}else return T.name??"UnknownSchema"};const[g,b]=n.extend(f,u);if(g===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);b!==void 0&&(r[u]={name:w(b.id,b.data),...b}),s[u]={name:w(g.id,g.data),...g}}else{const g=n.addNode(d,u,h);r[u]=g,s[u]=g}}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(De(c),De(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=>[De(d),De(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(De(c),De(f),p,!0)}}return n}};function Hd(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function De(e){return e==="subgraph"?`"${e}"`:e}const zn=(e,t)=>e.size===t.size&&[...e].every(n=>t.has(n));var Bx=class Bg extends ar{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){const n=new Bg(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 je}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)}},zx=class zg extends ar{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 zg(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 je}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 Hx="lg:";var Vx=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=Ps(e);for(const[r,s]of Object.entries(n)){const a=this.get(s);a?.reducer?t[r]=new kc(a.reducer.fn,a.default):t[r]=new ql}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(Ps(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=Hr(l)??Hr(o),d=JSON.stringify({...c.jsonSchemaExtra,description:u});l=l.describe(`${Hx}${d}`)}return[i,l]});s=gp(e,Object.fromEntries(a)),Ee(s)&&(s._def.unknownKeys="strip")}return t.asPartial&&(s=Ai(s)),r.set(e,s),this._extensionCache.set(n,r),s}};const Xr=new Vx;function Qr(e,t){if(t.reducer&&!t.default){const n=ki(e);n!=null&&(t.default=n)}if(t.reducer){const n=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return Xr.extend(n,()=>t),n}else return Xr.extend(e,()=>t),e}const tn="__root__",jc=Symbol.for("langgraph.state.partial");var Gx=class extends Ux{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=Xr;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){if(super(),Xx(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??jc,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=jc,this._outputDefinition=r,this._outputRuntimeDefinition=e}else if(Yx(e))this._schemaDefinition=e.input.spec,this._inputDefinition=e.input.spec,this._outputDefinition=e.output.spec;else if(qx(e))this._schemaDefinition=e.stateSchema.spec,this._inputDefinition=e.input?.spec??this._schemaDefinition,this._outputDefinition=e.output?.spec??this._schemaDefinition;else if(Kx(e)||Vd(e)){const r=Vd(e)?e.spec:e;this._schemaDefinition=r}else if(Zx(e)){const r=Wx(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[xe,cn])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 ir({func:s,name:r,trace:!1}):o=Le(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:eu(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]===tn?tn:o,l=Object.keys(this.channels),u=l.length===1&&l[0]===tn?tn:l,d=this._interrupt,h=new Jx({builder:this,checkpointer:e,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[ie]:new Yr},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,Md,Gd(),{withReader:!1});for(const[p]of Object.entries(this.nodes))h.attachBranch(p,Md,Gd(),{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[g,b]of Object.entries(f))h.attachBranch(p,g,b);return h.validate()}};function Wx(e){const t={};for(const[n,r]of Object.entries(e))t[n]=xc(r);return t}var Jx=class extends Ug{description;_metaRegistry=Xr;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(Ne(o))return o.graph===be.PARENT?null:o._updateAsTuples();if(Array.isArray(o)&&o.length>0&&o.some(c=>Ne(c))){const c=[];for(const l of o)if(Ne(l)){if(l.graph===be.PARENT)continue;c.push(...l._updateAsTuples())}else c.push([tn,l]);return c}else if(o!=null)return[[tn,o]];return null}const s=e;function a(o){if(o){if(Ne(o))return o.graph===be.PARENT?null:o._updateAsTuples().filter(([c])=>n.includes(c));if(Array.isArray(o)&&o.length>0&&o.some(Ne)){const c=[];for(const l of o)if(Ne(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:Wn,mapper:new ir({func:n.length&&n[0]===tn?r:a,trace:!1,recurse:!1})}];if(e===ie)this.nodes[e]=new Hs({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&&tn in c,u=`branch:to:${e}`;this.channels[u]=t?.defer?new wO:new Yr(!1),this.nodes[e]=new Hs({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 zx(new Set(e)):new Bx(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=>_t(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=>XO.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===jc)return Ai(s(r))})();if(Ne(e)){const n=e;return e.update&&t!=null&&(n.update=sn(t,e.update)),n}return t!=null?sn(t,e):e}isInterrupted(e){return yg(e)}async _validateContext(e){const t=this.builder._configRuntimeSchema;return et(t)&&sn(t,e),e}};function Kx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||hg(t))}function Vd(e){return typeof e=="object"&&e!==null&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"}function Zx(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function qx(e){return typeof e=="object"&&e!==null&&e.stateSchema!==void 0}function Yx(e){return typeof e=="object"&&e!==null&&e.stateSchema===void 0&&e.input!==void 0&&e.output!==void 0}function Xx(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 Qx(e){if(_t(e))return[e];const t=[];Ne(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(Ne));const n=[];for(const r of t){if(r.graph===be.PARENT)throw new dg(r);_t(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Gd(){const e=new ir({func:Qx,tags:[ve],trace:!1,recurse:!1,name:"<control_branch>"});return new Fg({path:e})}const Hg="__remove_all__";function Vg(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=ke(),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=ke(),d.lc_kwargs.id=d.id),d.getType()==="remove"&&d.id===Hg&&(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))}Oc.Root({messages:Oc({reducer:Vg,default:()=>[]})});const pi={reducer:{fn:Vg},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};Y({messages:Qr(nt(),pi)});mO();const Dc=Symbol.for("langgraph-zod");Dc in globalThis||(globalThis[Dc]=new WeakSet);function Wd(e){const t=globalThis[Dc];t.has(e)||(Object.defineProperty(e,"langgraph",{get(){const n=this;return{metadata(r){return Qr(n,{jsonSchemaExtra:r})},reducer(r,s){const a=ki(n);return Qr(n,{default:a,reducer:{schema:s,fn:r}})}}}}),t.add(e))}try{Wd(hu.prototype),Wd(hu.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 eI=class extends __{constructor(e){super(),this.parent=e,this._map=this.parent._map}add(e,...t){const n=t[0];if(n&&!n?.default){const r=ki(e);r!=null&&(n.default=r)}return super.add(e,...t)}};new eI(Xr);function tI(e=!0,t,n=[]){const r={messages:Qr(nt(),pi),jumpTo:gt([vr("model_request"),vr("tools"),vr("end"),vy()]).optional()},s=o=>{const{shape:c}=o;for(const[l,u]of Object.entries(c))l.startsWith("_")||l in r||(r[l]=u)};t&&"shape"in t&&s(t);for(const o of n)o.stateSchema&&s(o.stateSchema);e&&(r.structuredResponse=Tt().optional());const a=Y(r);return Xr.getChannelsForSchema(a)}Y({llmInputMessages:Qr(nt(),{reducer:{fn:(e,t)=>pi.reducer.fn([],t)},default:()=>[]}),messages:Qr(nt(),pi)});const Jd="prompt",$o=/<name>(.*?)<\/name>/s,Lo=/<content>(.*?)<\/content>/s;function nI(e){if(!D.isInstance(e)||yt.isInstance(e)||!e.name)return e;const{name:t}=e;if(typeof e.content=="string")return new D({...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 D({...e.lc_kwargs,content:n,name:void 0})}function rI(e){if(!D.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($o),a=r.text.match(Lo);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($o),a=r.text.match(Lo);return!s||!a?r:(n=s[1],{...r,text:a[1]})}return r});else{const r=e.content,s=r.match($o),a=r.match(Lo);if(!s||!a)return e;n=s[1],t=a[1]}return new D({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function ye(e){return J.isRunnable(e)}function Kd(e){return Nl(e)?"bindTools"in e&&typeof e.bindTools=="function":!1}const jo=(e,t,n={})=>{if(Kd(e))return e.bindTools(t,n);if(Fe.isRunnableBinding(e)&&Kd(e.bound)){const r=e.bound.bindTools(t,n);return Fe.isRunnableBinding(r)?new Fe({bound:r.bound,config:{...e.config,...r.config},kwargs:{...e.kwargs,...r.kwargs},configFactories:r.configFactories??e.configFactories}):new Fe({bound:r,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};function Gg(e){if(typeof e=="function")return;let t=e;if(kt.isRunnableSequence(t)&&(t=t.steps.find(n=>Fe.isRunnableBinding(n))||t),!ni(t)){if(Fe.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 hc}if("tools"in t&&t.tools!==void 0&&Array.isArray(t.tools)&&t.tools.length>0)throw new hc}}function Fc(e){return!!(D.isInstance(e)&&e.tool_calls&&e.tool_calls.length>0)}function sI(e){let t;if(e==null)t=ot.from(n=>n.messages).withConfig({runName:Jd});else if(typeof e=="string"){const n=new Se(e);t=ot.from(r=>[n,...r.messages??[]]).withConfig({runName:Jd})}else throw new Error(`Got unexpected type for 'prompt': ${typeof e}`);return t}async function aI(e,t,n={}){const r=jo(e,t,n);if(r)return r;if(ni(e)){const s=jo(await e._model(),t,n);if(s)return s}if(kt.isRunnableSequence(e)){const s=e.steps.findIndex(a=>Fe.isRunnableBinding(a)||Nl(a)||ni(a));if(s>=0){const a=jo(e.steps[s],t,n);if(a){const i=e.steps.slice();return i.splice(s,1,a),kt.from(i)}}}throw new Error(`llm ${e} must define bindTools method.`)}function iI(e){if(e.length===0)return;if(e.length===1)return e[0];function t(r,s){return async(a,i)=>r(a,async()=>s(a,async()=>i(a)))}let n=e[e.length-1];for(let r=e.length-2;r>=0;r--)n=t(e[r],n);return n}function oI(e){const t=e.filter(n=>n.wrapToolCall);if(t.length!==0)return iI(t.map(n=>{const r=n.wrapToolCall;return async(a,i)=>{try{const o=await r({...a,state:{messages:a.state.messages,...n.stateSchema?sn(n.stateSchema,{...a.state}):{}}},i);if(!X.isInstance(o)&&!Ne(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 cI(e,t){const n={};for(const r of e){if(!r.stateSchema)continue;const s=yp(r.stateSchema,o=>o.startsWith("_")),a=await cl(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(`
200
- `);throw new Error(`Middleware "${r.name}" has required state fields that must be initialized:
201
- ${i}
202
-
203
- To fix this, either:
204
- 1. Provide default values in your middleware's state schema using .default():
205
- stateSchema: z.object({
206
- myField: z.string().default("default value")
207
- })
208
-
209
- 2. Or make the fields optional using .optional():
210
- stateSchema: z.object({
211
- myField: z.string().optional()
212
- })
213
-
214
- 3. Or ensure you pass these values when invoking the agent:
215
- agent.invoke({
216
- messages: [...],
217
- ${a.error.issues[0]?.path.join(".")}: "value"
218
- })`)}return n}function lI(e){const t={messages:nt(()=>[]),structuredResponse:Tt().optional()};if(!e)return Y(t);const{shape:n}=e,r={...t};for(const[s,a]of Object.entries(n))s.startsWith("_")?r[s]=a.optional():r[s]=a;return Y(r)}function Yt(e){if(e){if(["model_request","tools",B].includes(e))return e;if(e==="model")return"model_request";if(e==="tools")return"tools";if(e==="end")return B;throw new Error(`Invalid jump target: ${e}, must be "model", "tools" or "end".`)}}function Wg(...e){return AbortSignal.any(e.filter(t=>t!=null&&typeof t=="object"&&"aborted"in t&&typeof t.aborted=="boolean"))}var ru=class extends J{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.recurse=e.recurse??this.recurse}getState(){return this.#e}setState(e){this.#e={...this.#e,...e}}async invoke(e,t){const n=ft(this.config,t),r=await Te.runWithConfig(n,async()=>this.func(e,n));return J.isRunnable(r)&&this.recurse?await Te.runWithConfig(n,async()=>r.invoke(e,n)):(this.#e=r,r)}};function uI(e,t){let n,r;if(t==="inline")n=nI,r=rI;else throw new Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function s(a){return a.map(n)}return kt.from([ot.from(s),e,ot.from(r)])}var dI=class extends ru{#e;constructor(e){super({name:e.name??"model",func:(t,n)=>this.#s(t,n)}),this.#e=e}#n(e){if(!this.#e.responseFormat)return;const t=Lf(this.#e.responseFormat,void 0,e);return t.every(r=>r instanceof Un)?{type:"native",strategy:t[0]}:{type:"tool",tools:t.filter(r=>r instanceof yn).reduce((r,s)=>(r[s.name]=s,r),{})}}async#s(e,t){const n=e.messages.at(-1);if(n&&X.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return{messages:[]};const r=await this.#a(e,t);return"structuredResponse"in r?{messages:[...e.messages,...r.messages||[]],structuredResponse:r.structuredResponse}:r instanceof be?r:(r.name=this.name,r.lc_kwargs.name=this.name,this.#r(e,r)?{messages:[new D({content:"Sorry, need more steps to process this request.",name:this.name,id:r.id})]}:{messages:[r]})}#t(){if(typeof this.#e.model=="string")return rs(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#a(e,t,n={}){const r=await this.#t(),s=t,a=async l=>{Gg(l.model);const u=this.#n(l.model),d=await this.#u(l.model,l,u);let h=this.#l(e);h={...h,messages:l.messages};const p=Wg(this.#e.signal,t.signal),f={...t,signal:p},g=await d.invoke(h,f);if(u?.type==="native"){const v=u.strategy.parse(g);return v?{structuredResponse:v,messages:[g]}:g}if(!u||!g.tool_calls)return g;const b=g.tool_calls.filter(v=>v.name in u.tools);if(b.length===0)return g;if(b.length>1)return this.#o(g,b,u);const w=u.tools[b[0].name]?.options?.toolMessageContent;return this.#c(g,b[0],u,w??n.lastMessage)},i=this.#e.wrapModelCallHookMiddleware??[];let o=a;for(let l=i.length-1;l>=0;l--){const[u,d]=i[l];if(u.wrapModelCall){const h=o,p=u,f=d;o=async g=>{const b=p.contextSchema?sn(p.contextSchema,s?.context||{}):s?.context,S=Object.freeze({context:b,writer:s.writer,interrupt:s.interrupt,signal:s.signal}),w={...g,state:{...u.stateSchema?sn(Ai(u.stateSchema),e):{},...f(),messages:e.messages},runtime:S},v=async T=>{const k=T.tools??[],O=k.filter(y=>ye(y)&&!this.#e.toolClasses.some(N=>N.name===y.name));if(O.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${p.name}": ${O.map(y=>y.name).join(", ")}. This is not supported.`);const C=k.filter(y=>ye(y)&&this.#e.toolClasses.every(N=>N!==y));if(C.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${p.name}": ${C.map(y=>y.name).join(", ")}. This is not supported.`);return h(T)};if(!p.wrapModelCall)return v(w);try{const T=await p.wrapModelCall(w,v);if(!D.isInstance(T))throw new Error(`Invalid response from "wrapModelCall" in middleware "${p.name}": expected AIMessage, got ${typeof T}`);return T}catch(T){throw T instanceof Error&&!T.message.includes(`middleware "${p.name}"`)&&(T.message=`Error in middleware "${p.name}": ${T.message}`),T}}}}const c={model:r,systemPrompt:this.#e.systemPrompt,messages:e.messages,tools:this.#e.toolClasses,state:e,runtime:Object.freeze({context:s?.context,writer:s.writer,interrupt:s.interrupt,signal:s.signal})};return o(c)}#o(e,t,n){const r=new pc(t.map(s=>s.name));return this.#i(r,e,t[0],n)}#c(e,t,n,r){const s=n.tools[t.name];try{const a=s.parse(t.args);return{structuredResponse:a,messages:[e,new X({tool_call_id:t.id??"",content:JSON.stringify(a),name:t.name}),new D(r??`Returning structured response: ${JSON.stringify(a)}`)]}}catch(a){return this.#i(a,e,t,n)}}async#i(e,t,n,r){const s=Object.values(r.tools).at(0)?.options?.handleError,a=n.id;if(!a)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(typeof s=="boolean"&&s||Array.isArray(s)&&s.some(i=>i instanceof pc))return new be({update:{messages:[t,new X({content:e.message,tool_call_id:a})]},goto:"model"});if(typeof s=="string")return new be({update:{messages:[t,new X({content:s,tool_call_id:a})]},goto:"model"});if(typeof s=="function"){const i=await s(e);if(typeof i!="string")throw new Error("Error handler must return a string.");return new be({update:{messages:[t,new X({content:i,tool_call_id:a})]},goto:"model"})}throw e}#r(e,t){const n=D.isInstance(t)&&t.tool_calls?.every(s=>this.#e.shouldReturnDirect.has(s.name)),r="remainingSteps"in e?e.remainingSteps:void 0;return!!(r&&(r<1&&n||r<2&&Fc(e.messages.at(-1))))}#l(e){const{messages:t,llmInputMessages:n,...r}=e;return n&&n.length>0?{messages:n,...r}:{messages:t,...r}}async#u(e,t,n){const r={},s=Object.values(n&&"tools"in n?n.tools:{}),a=[...t?.tools??this.#e.toolClasses,...s.map(l=>l.tool)],i=t?.toolChoice||(s.length>0?"any":void 0);if(n?.type==="native"){const l={name:n.strategy.schema?.name??"extract",description:Hr(n.strategy.schema),schema:n.strategy.schema,strict:!0};Object.assign(r,{response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:n.strategy.schema},strict:!0})}const o=await aI(e,a,{...r,...t?.modelSettings??{},tool_choice:i});return sI(t?.systemPrompt??this.#e.systemPrompt).pipe(this.#e.includeAgentName==="inline"?uI(o,this.#e.includeAgentName):o)}getState(){const e=super.getState(),t=e&&!(e instanceof be)?e:{};return{messages:[],...t}}};const Jg=e=>Array.isArray(e)&&e.every(rt.isInstance),hI=e=>typeof e=="object"&&e!=null&&"messages"in e&&Jg(e.messages),pI=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e;function fI(e,t){return e instanceof Pl?new X({content:e.message,tool_call_id:t.id,name:t.name}):new X({content:`${e}
219
- Please fix your mistakes.`,tool_call_id:t.id,name:t.name})}var mI=class extends ru{tools;trace=!1;signal;handleToolErrors=fI;wrapToolCall;constructor(e,t){const{name:n,tags:r,handleToolErrors:s,signal:a,wrapToolCall:i}=t??{};super({name:n,tags:r,func:(o,c)=>this.run(o,c)}),this.options=t,this.tools=e,this.handleToolErrors=s??this.handleToolErrors,this.signal=a,this.wrapToolCall=i}#e(e,t,n){if(Bn(e)||this.signal?.aborted||n&&this.handleToolErrors!==!0||!this.handleToolErrors)throw e;if(typeof this.handleToolErrors=="function"){const r=this.handleToolErrors(e,t);if(r&&X.isInstance(r))return r;throw e}else if(this.handleToolErrors)return new X({name:t.name,content:`${e}
220
- Please fix your mistakes.`,tool_call_id:t.id});throw e}async runTool(e,t,n){const r=async c=>{const{toolCall:l}=c,u=this.tools.find(d=>d.name===l.name);if(u===void 0)throw new Error(`Tool "${l.name}" not found.`);try{const d=await u.invoke({...l,type:"tool_call"},{...t,config:t,toolCallId:l.id,state:t.configurable?.__pregel_scratchpad?.currentTaskInput,signal:Wg(this.signal,t.signal)});return X.isInstance(d)||Ne(d)?d:new X({name:u.name,content:typeof d=="string"?d:JSON.stringify(d),tool_call_id:l.id})}catch(d){throw d instanceof ks?new Pl(d,l):d}},s=t,a={context:s?.context,writer:s?.writer,interrupt:s?.interrupt,signal:s?.signal},i=this.tools.find(c=>c.name===e.name);if(!i)throw new Error(`Tool "${e.name}" not found.`);const o={toolCall:e,tool:i,state:n,runtime:a};if(this.wrapToolCall)try{return await this.wrapToolCall(o,r)}catch(c){return this.#e(c,e,!0)}try{return await r(o)}catch(c){return this.#e(c,e,!1)}}async run(e,t){let n;if(pI(e)){const{lg_tool_call:a,jumpTo:i,...o}=e;n=[await this.runTool(e.lg_tool_call,t,o)]}else{let a;if(Jg(e))a=e;else if(hI(e))a=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const i=new Set(a.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id));let o;for(let c=a.length-1;c>=0;c-=1){const l=a[c];if(D.isInstance(l)){o=l;break}}if(!D.isInstance(o))throw new Error("ToolNode only accepts AIMessages as input.");n=await Promise.all(o.tool_calls?.filter(c=>c.id==null||!i.has(c.id)).map(c=>this.runTool(c,t,e))??[])}if(!n.some(Ne))return Array.isArray(e)?n:{messages:n};const r=[];let s=null;for(const a of n)Ne(a)?a.graph===be.PARENT&&Array.isArray(a.goto)&&a.goto.every(i=>gI(i))?s?s.goto.push(...a.goto):s=new be({graph:be.PARENT,goto:a.goto}):r.push(a):r.push(Array.isArray(e)?[a]:{messages:[a]});return s&&r.push(s),r}};function gI(e){return e instanceof We}var yI=class{},_I=class{},Ui=class extends ru{#e;constructor(e,t){super(e),this.#e=t}async invokeMiddleware(e,t){let n={};if(this.middleware.contextSchema){const c=this.middleware.contextSchema?.shape;if(c){const l={},u=t?.context||{};for(const d of Object.keys(c))d in u&&(l[d]=u[d]);n=sn(this.middleware.contextSchema,l)}}const r={...this.#e.getState(),...e,messages:e.messages},s={context:n,writer:t?.writer,interrupt:t?.interrupt,signal:t?.signal},a=await this.runHook(r,Object.freeze(Object.assign(new _I,{...s,context:Object.freeze(Object.assign(new yI,n))})));if(!a)return{...r,jumpTo:void 0};let i,o;if(this.name?.startsWith("BeforeAgentNode_")?(i=vn(this.middleware.beforeAgent),o="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=vn(this.middleware.beforeModel),o="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=vn(this.middleware.afterAgent),o="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=vn(this.middleware.afterModel),o="afterModel.canJumpTo"),typeof a.jumpTo=="string"&&!i?.includes(a.jumpTo)){const c=i&&i.length>0?`must be one of: ${i?.join(", ")}.`:o?`no ${o} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${a.jumpTo}, ${c}.`)}if(typeof a=="object"&&"type"in a){if(a.type==="terminate"){if(a.error)throw a.error;return{...r,...a.result||{},jumpTo:a.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(a)}`)}return{...r,...a,jumpTo:a.jumpTo}}get nodeOptions(){return{input:lI(this.middleware.stateSchema)}}},wI=class extends Ui{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(e,t){super({name:`BeforeAgentNode_${e.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},t),this.middleware=e}runHook(e,t){return Li(this.middleware.beforeAgent)(e,t)}},vI=class extends Ui{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(e,t){super({name:`BeforeModelNode_${e.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},t),this.middleware=e}runHook(e,t){return Li(this.middleware.beforeModel)(e,t)}},bI=class extends Ui{lc_namespace=["langchain","agents","afterModelNodes"];constructor(e,t){super({name:`AfterModelNode_${e.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},t),this.middleware=e}runHook(e,t){return Li(this.middleware.afterModel)(e,t)}},SI=class extends Ui{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(e,t){super({name:`AfterAgentNode_${e.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},t),this.middleware=e}runHook(e,t){return Li(this.middleware.afterAgent)(e,t)}},TI=class{#e=new Map;addNode(e,t){this.#e.set(e.name,[...this.#e.get(e.name)??[],t])}getState(e){const n=(this.#e.get(e)??[]).reduce((r,s)=>({...r,...s.getState()??{}}),{});return delete n.jumpTo,n}},EI=class{#e;#n="v2";#s;#t=new TI;constructor(e){if(this.options=e,this.#n=e.version??this.#n,!e.model)throw new Error("`model` option is required to create an agent.");typeof e.model!="string"&&Gg(e.model);const t=this.options.middleware?.filter(w=>w.tools).flatMap(w=>w.tools)??[],n=[...e.tools??[],...t],r=new Set(n.filter(ye).filter(w=>"returnDirect"in w&&w.returnDirect).map(w=>w.name)),s=tI(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),i=new Gx(s,this.options.contextSchema),o=[],c=[],l=[],u=[],d=[];this.#s=new dI({model:this.options.model,systemPrompt:this.options.systemPrompt,includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:n,shouldReturnDirect:r,signal:this.options.signal,wrapModelCallHookMiddleware:d});const h=new Set,p=this.options.middleware??[];for(let w=0;w<p.length;w++){let v,T,k,O;const C=p[w];if(h.has(C.name))throw new Error(`Middleware ${C.name} is defined multiple times`);if(h.add(C.name),C.beforeAgent){v=new wI(C,{getState:()=>this.#t.getState(C.name)}),this.#t.addNode(C,v);const y=`${C.name}.before_agent`;o.push({index:w,name:y,allowed:vn(C.beforeAgent)}),i.addNode(y,v,v.nodeOptions)}if(C.beforeModel){T=new vI(C,{getState:()=>this.#t.getState(C.name)}),this.#t.addNode(C,T);const y=`${C.name}.before_model`;c.push({index:w,name:y,allowed:vn(C.beforeModel)}),i.addNode(y,T,T.nodeOptions)}if(C.afterModel){k=new bI(C,{getState:()=>this.#t.getState(C.name)}),this.#t.addNode(C,k);const y=`${C.name}.after_model`;l.push({index:w,name:y,allowed:vn(C.afterModel)}),i.addNode(y,k,k.nodeOptions)}if(C.afterAgent){O=new SI(C,{getState:()=>this.#t.getState(C.name)}),this.#t.addNode(C,O);const y=`${C.name}.after_agent`;u.push({index:w,name:y,allowed:vn(C.afterAgent)}),i.addNode(y,O,O.nodeOptions)}C.wrapModelCall&&d.push([C,()=>this.#t.getState(C.name)])}if(i.addNode("model_request",this.#s),n.filter(ye).length>0){const w=new mI(n.filter(ye),{signal:this.options.signal,wrapToolCall:oI(p)});i.addNode("tools",w)}let f;o.length>0?f=o[0].name:c.length>0?f=c[0].name:f="model_request";const g=c.length>0?c[0].name:"model_request",b=u.length>0?u[u.length-1].name:B;i.addEdge(ie,f);for(let w=0;w<o.length;w++){const v=o[w],T=v.name,O=w===o.length-1?g:o[w+1].name;if(v.allowed&&v.allowed.length>0){const C=n.filter(ye).length>0,y=v.allowed.map(I=>Yt(I)).filter(I=>I!=="tools"||C),N=Array.from(new Set([O,...y.map(I=>I===B?b:I)]));i.addConditionalEdges(T,this.#l(n.filter(ye),O,b),N)}else i.addEdge(T,O)}for(let w=0;w<c.length;w++){const v=c[w],T=v.name,O=w===c.length-1?"model_request":c[w+1].name;if(v.allowed&&v.allowed.length>0){const C=n.filter(ye).length>0,y=v.allowed.map(I=>Yt(I)).filter(I=>I!=="tools"||C),N=Array.from(new Set([O,...y]));i.addConditionalEdges(T,this.#u(n.filter(ye),O),N)}else i.addEdge(T,O)}const S=l.at(-1);if(l.length>0&&S)i.addEdge("model_request",S.name);else{const v=this.#a(n.filter(ye)).map(T=>T===B?b:T);v.length===1?i.addEdge("model_request",v[0]):i.addConditionalEdges("model_request",this.#c(b),v)}for(let w=l.length-1;w>0;w--){const v=l[w],T=v.name,k=l[w-1].name;if(v.allowed&&v.allowed.length>0){const O=n.filter(ye).length>0,C=v.allowed.map(N=>Yt(N)).filter(N=>N!=="tools"||O),y=Array.from(new Set([k,...C]));i.addConditionalEdges(T,this.#r(n.filter(ye),v.allowed,k),y)}else i.addEdge(T,k)}if(l.length>0){const w=l[0],v=w.name,T=this.#a(n.filter(ye),!0).filter(C=>C!=="tools"||n.filter(ye).length>0),k=!!(w.allowed&&w.allowed.length>0),O=T.map(C=>C===B?b:C);i.addConditionalEdges(v,this.#i(n.filter(ye),k,b),O)}for(let w=u.length-1;w>0;w--){const v=u[w],T=v.name,k=u[w-1].name;if(v.allowed&&v.allowed.length>0){const O=n.filter(ye).length>0,C=v.allowed.map(N=>Yt(N)).filter(N=>N!=="tools"||O),y=Array.from(new Set([k,...C]));i.addConditionalEdges(T,this.#r(n.filter(ye),v.allowed,k),y)}else i.addEdge(T,k)}if(u.length>0){const w=u[0],v=w.name;if(w.allowed&&w.allowed.length>0){const T=n.filter(ye).length>0,k=w.allowed.map(C=>Yt(C)).filter(C=>C!=="tools"||T),O=Array.from(new Set([B,...k]));i.addConditionalEdges(v,this.#r(n.filter(ye),w.allowed,B),O)}else i.addEdge(v,B)}if(n.filter(ye).length>0){const w=g;r.size>0?i.addConditionalEdges("tools",this.#o(r,b),[w,b]):i.addEdge("tools",w)}this.#e=i.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#a(e,t=!1){const n=[];return e.length>0&&n.push("tools"),t&&n.push("model_request"),n.push(B),n}#o(e,t){return n=>{const r=n.messages,s=r[r.length-1];return X.isInstance(s)&&s.name&&e.has(s.name)?this.options.responseFormat?"model_request":t:"model_request"}}#c(e=B){return t=>{const r=t.messages.at(-1);if(!D.isInstance(r)||!r.tool_calls||r.tool_calls.length===0||r.tool_calls.every(i=>i.name.startsWith("extract-")))return e;if(this.#n==="v1")return"tools";const a=r.tool_calls.filter(i=>!i.name.startsWith("extract-"));return a.length===0?e:a.map(i=>new We("tools",{...t,lg_tool_call:i}))}}#i(e,t,n){const r=!!this.options.responseFormat;return s=>{const a=s.messages,i=a.at(-1);if(D.isInstance(i)&&(!i.tool_calls||i.tool_calls.length===0))return n;if(t&&s.jumpTo)return s.jumpTo===B?n:s.jumpTo==="tools"?e.length===0?n:new We("tools",{...s,jumpTo:void 0}):new We("model_request",{...s,jumpTo:void 0});const o=a.filter(X.isInstance),c=a.filter(D.isInstance).at(-1),l=c?.tool_calls?.filter(p=>!o.some(f=>f.tool_call_id===p.id));if(l&&l.length>0)return l.map(p=>new We("tools",{...s,lg_tool_call:p}));const u=c?.tool_calls?.some(p=>p.name.startsWith("extract-"));if(l&&l.length===0&&!u&&r)return"model_request";if(!D.isInstance(i)||!i.tool_calls||i.tool_calls.length===0)return n;const d=i.tool_calls.every(p=>p.name.startsWith("extract-")),h=i.tool_calls.some(p=>!p.name.startsWith("extract-"));return d||!h?n:"tools"}}#r(e,t,n){const r=new Set(t.map(s=>Yt(s)));return s=>{if(s.jumpTo){const a=Yt(s.jumpTo);if(a===B&&r.has(B))return B;if(a==="tools"&&r.has("tools"))return e.length===0?B:new We("tools",{...s,jumpTo:void 0});if(a==="model_request"&&r.has("model_request"))return new We("model_request",{...s,jumpTo:void 0})}return n}}#l(e,t,n){return r=>{if(!r.jumpTo)return t;const s=Yt(r.jumpTo);return s===B?n:s==="tools"?e.length===0?n:new We("tools",{...r,jumpTo:void 0}):new We("model_request",{...r,jumpTo:void 0})}}#u(e,t){return n=>{if(!n.jumpTo)return t;const r=Yt(n.jumpTo);return r===B?B:r==="tools"?e.length===0?B:new We("tools",{...n,jumpTo:void 0}):new We("model_request",{...n,jumpTo:void 0})}}async#d(e,t){if(!this.options.middleware||this.options.middleware.length===0||e instanceof be||!e)return e;const n=await cI(this.options.middleware,e),s={...(await this.#e.getState(t).catch(()=>({values:{}}))).values,...e};if(!s)return s;for(const[a,i]of Object.entries(n))a in s||(s[a]=i);return s}async invoke(e,t){const n=await this.#d(e,t);return this.#e.invoke(n,t)}async stream(e,t){const n=await this.#d(e,t);return this.#e.stream(n,t)}async drawMermaidPng(e){const r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(e)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(e){return(await this.#e.getGraphAsync()).drawMermaid(e)}streamEvents(e,t,n){return this.#e.streamEvents(e,{...t,version:t?.version??"v2"},n)}getGraphAsync(e){return this.#e.getGraphAsync(e)}getState(e,t){return this.#e.getState(e,t)}getStateHistory(e,t){return this.#e.getStateHistory(e,t)}getSubgraphs(e,t){return this.#e.getSubgraphs(e,t)}getSubgraphAsync(e,t){return this.#e.getSubgraphsAsync(e,t)}updateState(e,t,n){return this.#e.updateState(e,t,n)}};function Kg(e){return new EI(e)}const Da=`<role>
221
- Context Extraction Assistant
222
- </role>
223
-
224
- <primary_objective>
225
- Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
226
- </primary_objective>
227
-
228
- <objective_information>
229
- You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
230
- This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
231
- </objective_information>
232
-
233
- <instructions>
234
- The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
235
- You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
236
- </instructions>
237
-
238
- The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
239
-
240
- With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
241
- Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
242
-
243
- <messages>
244
- Messages to summarize:
245
- {messages}
246
- </messages>`,fi=20,CI=4e3,Zd=5,AI=Ua().args(Jt(nt())).returns(gt([le(),sh(le())])),mi=Y({fraction:le().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:le().positive("Tokens must be greater than 0").optional(),messages:le().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(e=>[e.fraction,e.tokens,e.messages].filter(n=>n!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),Zg=Y({fraction:le().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:le().positive("Tokens must be greater than 0").optional(),messages:le().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(e=>[e.fraction,e.tokens,e.messages].filter(n=>n!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),qd=Y({model:nt(),trigger:gt([mi,Jt(mi)]).optional(),keep:Zg.optional(),tokenCounter:AI.optional(),summaryPrompt:pe().default(Da),trimTokensToSummarize:le().optional(),summaryPrefix:pe().optional(),maxTokensBeforeSummary:le().optional(),messagesToKeep:le().optional()});function su(e){try{const t=e;if(t.profile&&typeof t.profile.max_input_tokens=="number")return t.profile.max_input_tokens}catch{}try{const t=e,n=t.model||t.modelName;if(typeof n=="string")return vl(n)}catch{}}function kI(e){const{data:t,error:n}=mp(qd,e);if(n)throw new Error(`Invalid summarization middleware options: ${Jc(n)}`);return wt({name:"SummarizationMiddleware",contextSchema:qd.extend({model:nt().optional()}),beforeModel:async(r,s)=>{let a=t.trigger,i=t.keep;t.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),a===void 0&&(a={tokens:t.maxTokensBeforeSummary})),t.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!i||i&&"messages"in i&&i.messages===fi)&&(i={messages:t.messagesToKeep}));const o=s.context.trigger!==void 0?s.context.trigger:a,c=s.context.keep!==void 0?s.context.keep:i??{messages:fi},l=Zg.parse(c);let u=[];o===void 0?u=[]:Array.isArray(o)?u=o.map(N=>mi.parse(N)):u=[mi.parse(o)];const d=u.some(N=>"fraction"in N)||"fraction"in l,h=typeof t.model=="string"?await rs(t.model):t.model;if(d&&!su(h))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const p=s.context.summaryPrompt===Da?t.summaryPrompt??Da:s.context.summaryPrompt??t.summaryPrompt??Da,f=s.context.trimTokensToSummarize!==void 0?s.context.trimTokensToSummarize:t.trimTokensToSummarize??CI;OI(r.messages);const g=s.context.tokenCounter!==void 0?s.context.tokenCounter:t.tokenCounter??Ml,b=await g(r.messages);if(!await PI(r.messages,b,u,h))return;const{systemPrompt:w,conversationMessages:v}=xI(r.messages),T=await NI(v,l,g,h);if(T<=0)return;const{messagesToSummarize:k,preservedMessages:O}=II(w,v,T),C=await LI(k,h,p,g,f),y=new he({content:`Here is a summary of the conversation to date:
247
-
248
- ${C}`,id:ke()});return{messages:[new Sn({id:Hg}),y,...O]}}})}function OI(e){for(const t of e)t.id||(t.id=ke())}function xI(e){return e.length>0&&Se.isInstance(e[0])?{systemPrompt:e[0],conversationMessages:e.slice(1)}:{conversationMessages:e}}function II(e,t,n){const r=t.slice(0,n),s=t.slice(n);return e&&r.unshift(e),{messagesToSummarize:r,preservedMessages:s}}async function PI(e,t,n,r){if(n.length===0)return!1;for(const s of n){let a=!0,i=!1;if(s.messages!==void 0&&(i=!0,e.length<s.messages&&(a=!1)),s.tokens!==void 0&&(i=!0,t<s.tokens&&(a=!1)),s.fraction!==void 0){i=!0;const o=su(r);if(typeof o=="number"){const c=Math.floor(o*s.fraction);t<c&&(a=!1)}else a=!1}if(i&&a)return!0}return!1}async function NI(e,t,n,r){if("tokens"in t||"fraction"in t){const s=await MI(e,t,n,r);return typeof s=="number"?s:Yd(e,fi)}return Yd(e,t.messages??fi)}async function MI(e,t,n,r){if(e.length===0)return 0;let s;if("fraction"in t&&t.fraction!==void 0){const u=su(r);if(typeof u!="number")return;s=Math.floor(u*t.fraction)}else if("tokens"in t&&t.tokens!==void 0)s=Math.floor(t.tokens);else return;if(s<=0&&(s=1),await n(e)<=s)return 0;let i=0,o=e.length,c=e.length;const l=Math.floor(Math.log2(e.length))+1;for(let u=0;u<l&&!(i>=o);u++){const d=Math.floor((i+o)/2);await n(e.slice(d))<=s?(c=d,o=d):i=d+1}if(c===e.length&&(c=i),c>=e.length){if(e.length===1)return 0;c=e.length-1}for(let u=c;u>=0;u--)if(qg(e,u))return u;return 0}function Yd(e,t){if(e.length<=t)return 0;const n=e.length-t;for(let r=n;r>=0;r--)if(qg(e,r))return r;return 0}function qg(e,t){if(t>=e.length)return!0;if(t<e.length&&D.isInstance(e[t])&&Fc(e[t]))return!1;const n=Math.max(0,t-Zd),r=Math.min(e.length,t+Zd);for(let s=n;s<r;s++){if(!Fc(e[s]))continue;const a=RI(e[s]);if($I(e,s,t,a))return!1}return!0}function RI(e){const t=new Set;if(e.tool_calls)for(const n of e.tool_calls){const r=typeof n=="object"&&"id"in n?n.id:null;r&&t.add(r)}return t}function $I(e,t,n,r){for(let s=t+1;s<e.length;s++){const a=e[s];if(X.isInstance(a)&&r.has(a.tool_call_id)){const i=t<n,o=s<n;if(i!==o)return!0}}return!1}async function LI(e,t,n,r,s){if(!e.length)return"No previous conversation history.";const a=await jI(e,r,s);if(!a.length)return"Previous conversation was too long to summarize.";try{const i=n.replace("{messages}",JSON.stringify(a,null,2)),c=(await t.invoke(i)).content;return typeof c=="string"?c.trim():Array.isArray(c)?c.map(u=>typeof u=="string"?u:typeof u=="object"&&u!==null&&"text"in u?u.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(i){return`Error generating summary: ${i}`}}async function jI(e,t,n){if(n===void 0)return e;try{return await xl(e,{maxTokens:n,tokenCounter:async r=>t(r),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return e.slice(-15)}}const DI=Ua().args(nt(),nt(),nt()).returns(gt([pe(),sh(pe())])),Yg=["approve","edit","reject"],FI=Ur(Yg),UI=Y({allowedDecisions:Jt(FI),description:gt([pe(),DI]).optional(),argsSchema:Ss(Tt()).optional()}),Xd=Y({interruptOn:Ss(gt([bs(),UI])).optional(),descriptionPrefix:pe().default("Tool execution requires approval")});function BI(e){const t=async(r,s,a,i)=>{const o=r.name,c=r.args,l=s.description;let u;typeof l=="function"?u=await l(r,a,i):l!==void 0?u=l:u=`${e.descriptionPrefix??"Tool execution requires approval"}
249
-
250
- Tool: ${o}
251
- Args: ${JSON.stringify(c,null,2)}`;const d={name:o,args:c,description:u},h={actionName:o,allowedDecisions:s.allowedDecisions};return s.argsSchema&&(h.argsSchema=s.argsSchema),{actionRequest:d,reviewConfig:h}},n=(r,s,a)=>{const i=a.allowedDecisions;if(r.type==="approve"&&i.includes("approve"))return{revisedToolCall:s,toolMessage:null};if(r.type==="edit"&&i.includes("edit")){const c=r.editedAction;if(!c||typeof c.name!="string")throw new Error(`Invalid edited action for tool "${s.name}": name must be a string`);if(!c.args||typeof c.args!="object")throw new Error(`Invalid edited action for tool "${s.name}": args must be an object`);return{revisedToolCall:{type:"tool_call",name:c.name,args:c.args,id:s.id},toolMessage:null}}if(r.type==="reject"&&i.includes("reject")){if(r.message!==void 0&&typeof r.message!="string")throw new Error(`Tool call response for "${s.name}" must be a string, got ${typeof r.message}`);const c=r.message??`User rejected the tool call for \`${s.name}\` with id ${s.id}`,l=new X({content:c,name:s.name,tool_call_id:s.id,status:"error"});return{revisedToolCall:s,toolMessage:l}}const o=`Unexpected human decision: ${JSON.stringify(r)}. Decision type '${r.type}' is not allowed for tool '${s.name}'. Expected one of ${JSON.stringify(i)} based on the tool's configuration.`;throw new Error(o)};return wt({name:"HumanInTheLoopMiddleware",contextSchema:Xd,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const a=sn(Xd,{...e,...s.context||{}});if(!a)return;const{messages:i}=r;if(!i.length)return;const o=[...i].reverse().find(T=>D.isInstance(T));if(!o||!o.tool_calls?.length||!a.interruptOn)return;const c={};for(const[T,k]of Object.entries(a.interruptOn))typeof k=="boolean"?k===!0&&(c[T]={allowedDecisions:[...Yg]}):k.allowedDecisions&&(c[T]=k);const l=[],u=[];for(const T of o.tool_calls)T.name in c?l.push(T):u.push(T);if(!l.length)return;const d=[],h=[];for(const T of l){const k=c[T.name],{actionRequest:O,reviewConfig:C}=await t(T,k,r,s);d.push(O),h.push(C)}const g=(await Ag({actionRequests:d,reviewConfigs:h})).decisions;if(!g||!Array.isArray(g))throw new Error("Invalid HITLResponse: decisions must be a non-empty array");if(g.length!==l.length)throw new Error(`Number of human decisions (${g.length}) does not match number of hanging tool calls (${l.length}).`);const b=[...u],S=[],w=g.some(T=>T.type==="reject");for(let T=0;T<g.length;T++){const k=g[T],O=l[T],C=c[O.name],{revisedToolCall:y,toolMessage:N}=n(k,O,C);y&&(!w||k.type==="reject")&&b.push(y),N&&S.push(N)}D.isInstance(o)&&(o.tool_calls=b);const v=w?"model":void 0;return{messages:[o,...S],jumpTo:v}}}})}const zI=!0,HI="5m",VI=3,GI="warn",WI=Y({enableCaching:bs().optional(),ttl:Ur(["5m","1h"]).optional(),minMessagesToCache:le().optional(),unsupportedModelBehavior:Ur(["ignore","warn","raise"]).optional()});var Qd=class extends Error{constructor(e){super(e),this.name="PromptCachingMiddlewareError"}};function JI(e){return wt({name:"PromptCachingMiddleware",contextSchema:WI,wrapModelCall:(t,n)=>{const r=t.runtime.context.enableCaching??e?.enableCaching??zI,s=t.runtime.context.ttl??e?.ttl??HI,a=t.runtime.context.minMessagesToCache??e?.minMessagesToCache??VI,i=t.runtime.context.unsupportedModelBehavior??e?.unsupportedModelBehavior??GI;if(!r||!t.model)return n(t);if(!(t.model.getName()==="ChatAnthropic"||t.model.getName()==="ConfigurableModel"&&t.model._defaultConfig?.modelProvider==="anthropic")){const d=t.model.getName(),p=`Unsupported model '${t.model.getName()==="ConfigurableModel"?`${d} (${t.model._defaultConfig?.modelProvider})`:d}'. Prompt caching requires an Anthropic model`;if(i==="raise")throw new Qd(`${p} (e.g., 'anthropic:claude-4-0-sonnet').`);return i==="warn"&&console.warn(`PromptCachingMiddleware: Skipping caching for ${d}. Consider switching to an Anthropic model for caching benefits.`),n(t)}if(t.state.messages.length+(t.systemPrompt?1:0)<a)return n(t);const l=t.messages.at(-1);if(!l)return n(t);const u=Object.getPrototypeOf(l).constructor;if(Array.isArray(l.content)){const d=new u({...l,content:[...l.content.slice(0,-1),{...l.content.at(-1),cache_control:{type:"ephemeral",ttl:s}}]});return n({...t,messages:[...t.messages.slice(0,-1),d]})}else if(typeof l.content=="string"){const d=new u({...l,content:[{type:"text",text:l.content,cache_control:{type:"ephemeral",ttl:s}}]});return n({...t,messages:[...t.messages.slice(0,-1),d]})}throw new Qd("Last message content is not a string or array")}})}function KI(e){return wt({name:"DynamicSystemPromptMiddleware",wrapModelCall:async(t,n)=>{const r=await e(t.state,t.runtime);if(typeof r!="string")throw new Error("dynamicSystemPromptMiddleware function must return a string");return n({...t,systemPrompt:r})}})}const ZI="Your goal is to select the most relevant tools for answering the user's query.";function qI(e){if(!e||e.length===0)throw new Error("Invalid usage: tools must be non-empty");const t=e.map(r=>vr(r.name)),n=gt(t);return Y({tools:Jt(n).describe("Tools to use. Place the most relevant tools first.")})}const YI=Y({model:pe().or(Ba(Pi)).optional(),systemPrompt:pe().optional(),maxTools:le().optional(),alwaysInclude:Jt(pe()).optional()});function XI(e){return wt({name:"LLMToolSelector",contextSchema:YI,async wrapModelCall(t,n){const r=await QI(t,e,t.runtime);if(!r)return n(t);const s=qI(r.availableTools),i=await(await r.model.withStructuredOutput?.(s))?.invoke([{role:"system",content:r.systemMessage},r.lastUserMessage]);if(!i||typeof i!="object"||!("tools"in i))throw new Error(`Expected object response with tools array, got ${typeof i}`);return n(eP(i,r.availableTools,r.validToolNames,t,e))}})}async function QI(e,t,n){const r=n.context.model??t.model,s=n.context.maxTools??t.maxTools,a=n.context.alwaysInclude??t.alwaysInclude??[],i=n.context.systemPrompt??t.systemPrompt??ZI;if(!e.tools||e.tools.length===0)return;const o=e.tools.filter(p=>typeof p=="object"&&"name"in p&&"description"in p&&typeof p.name=="string");if(a.length>0){const p=new Set(o.map(g=>g.name)),f=a.filter(g=>!p.has(g));if(f.length>0)throw new Error(`Tools in alwaysInclude not found in request: ${f.join(", ")}. Available tools: ${Array.from(p).sort().join(", ")}`)}const c=o.filter(p=>!a.includes(p.name));if(c.length===0)return;let l=i;s!==void 0&&(l+=`
252
- IMPORTANT: List the tool names in order of relevance, with the most relevant first. If you exceed the maximum number of tools, only the first ${s} will be used.`);let u;for(const p of e.messages)he.isInstance(p)&&(u=p);if(!u)throw new Error("No user message found in request messages");const d=r?typeof r=="string"?await rs(r):r:e.model,h=c.map(p=>p.name);return{availableTools:c,systemMessage:l,lastUserMessage:u,model:d,validToolNames:h}}function eP(e,t,n,r,s){const a=s.maxTools,i=s.alwaysInclude??[],o=[],c=[];for(const h of e.tools){if(!n.includes(h)){c.push(h);continue}!o.includes(h)&&(a===void 0||o.length<a)&&o.push(h)}if(c.length>0)throw new Error(`Model selected invalid tools: ${c.join(", ")}`);const l=t.filter(h=>o.includes(h.name)),u=(r.tools??[]).filter(h=>typeof h=="object"&&"name"in h&&typeof h.name=="string"&&i.includes(h.name));l.push(...u);const d=(r.tools??[]).filter(h=>!(typeof h=="object"&&"name"in h&&"description"in h&&typeof h.name=="string"));return{...r,tools:[...l,...d]}}const tP=Y({rules:Ss(pe(),Ba(RegExp).describe("Regular expression pattern to match PII")).optional()});function nP(){return Math.random().toString(36).substring(2,11)}function Do(e,t,n){let r=e;for(const[s,a]of Object.entries(t)){const i=s.toUpperCase().replace(/[^a-zA-Z0-9_-]/g,"");r=r.replace(a,o=>{const c=nP();return n[c]=o,`[REDACTED_${i}_${c}]`})}return r}async function rP(e,t){if(he.isInstance(e)||X.isInstance(e)||Se.isInstance(e)){const n=e.content,r=await Do(n,t.rules,t.redactionMap);if(r!==n){const s=Object.getPrototypeOf(e).constructor;return new s({...e,content:r})}return e}if(D.isInstance(e)){const n=typeof e.content=="string"?e.content:JSON.stringify(e.content),r=JSON.stringify(e.tool_calls),s=await Do(n,t.rules,t.redactionMap),a=await Do(r,t.rules,t.redactionMap);return s!==n||a!==r?new D({...e,content:typeof e.content=="string"?s:JSON.parse(s),tool_calls:JSON.parse(a)}):e}throw new Error(`Unsupported message type: ${e.type}`)}function ws(e,t){let n=e;const r=/\[REDACTED_[A-Z_]+_(\w+)\]/g;return n=n.replace(r,(s,a)=>t[a]?t[a]:s),n}function eh(e,t){if(he.isInstance(e)||X.isInstance(e)||Se.isInstance(e)){const n=e.content,r=ws(n,t);if(r!==n){const s=Object.getPrototypeOf(e).constructor;return{message:new s({...e,content:r}),changed:!0}}return{message:e,changed:!1}}if(D.isInstance(e)){const n=typeof e.content=="string"?e.content:JSON.stringify(e.content),r=JSON.stringify(e.tool_calls),s=ws(n,t),a=ws(r,t);return s!==n||a!==r?{message:new D({...e,content:typeof e.content=="string"?s:JSON.parse(s),tool_calls:JSON.parse(a)}),changed:!0}:{message:e,changed:!1}}throw new Error(`Unsupported message type: ${e.type}`)}function sP(e={}){const t={};return wt({name:"PIIRedactionMiddleware",contextSchema:tP,wrapModelCall:async(n,r)=>{const s=n.runtime.context.rules??e.rules??{};if(Object.keys(s).length===0)return r(n);const a=await Promise.all(n.state.messages.map(i=>rP(i,{rules:s,redactionMap:t})));return r({...n,messages:a})},afterModel:async n=>{if(Object.keys(t).length===0)return;const r=n.messages.at(-1);if(!D.isInstance(r))return;const s=n.messages.at(-2),{message:a,changed:i}=eh(r,t);if(!i)return;let o;if(D.isInstance(r)&&r?.tool_calls?.length===0&&typeof r.content=="string"&&r.content.startsWith("{")&&r.content.endsWith("}"))try{o=JSON.parse(ws(r.content,t))}catch{}if(D.isInstance(s)&&s?.tool_calls?.length!==0&&s?.tool_calls?.some(l=>l.name.startsWith("extract-"))){const{message:l,changed:u}=eh(s,t),d=s.tool_calls?.find(p=>p.name.startsWith("extract-"))?.args,h=d?JSON.parse(ws(JSON.stringify(d),t)):void 0;if(i||u)return{...n,...h?{structuredResponse:h}:{},messages:[new Sn({id:s.id}),new Sn({id:r.id}),l,a]}}return{...n,...o?{structuredResponse:o}:{},messages:[new Sn({id:r.id}),a]}}})}const aP="[cleared]";var Xg=class{triggerTokens;clearAtLeast;keep;clearToolInputs;excludeTools;placeholder;constructor(e={}){this.triggerTokens=e.triggerTokens??1e5,this.clearAtLeast=e.clearAtLeast??0,this.keep=e.keep??3,this.clearToolInputs=e.clearToolInputs??!1,this.excludeTools=new Set(e.excludeTools??[]),this.placeholder=e.placeholder??aP}async apply(e){const{tokens:t,messages:n,countTokens:r}=e;if(t<=this.triggerTokens)return t;const s=[];for(let o=0;o<n.length;o++){const c=n[o];X.isInstance(c)&&s.push({idx:o,msg:c})}const a=this.keep>=s.length?[]:this.keep>0?s.slice(0,-this.keep):s;let i=0;for(const{idx:o,msg:c}of a){if(this.clearAtLeast>0&&i>=this.clearAtLeast)break;if(c.response_metadata?.context_editing?.cleared)continue;const u=this.#e(n.slice(0,o),c.tool_call_id);if(!u)continue;const d=u.tool_calls?.find(f=>f.id===c.tool_call_id);if(!d)continue;const h=c.name||d.name;if(this.excludeTools.has(h))continue;if(n[o]=new X({tool_call_id:c.tool_call_id,content:this.placeholder,name:c.name,artifact:void 0,response_metadata:{...c.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const f=n.indexOf(u);f>=0&&(n[f]=this.#n(u,c.tool_call_id))}const p=await r(n);i=Math.max(0,t-p)}return t-i}#e(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(D.isInstance(r)&&r.tool_calls?.some(a=>a.id===t))return r}return null}#n(e,t){const n=e.tool_calls?.map(i=>i.id===t?{...i,args:{}}:i),r={...e.response_metadata},s={...r.context_editing},a=new Set(s.cleared_tool_inputs);return a.add(t),s.cleared_tool_inputs=Array.from(a).sort(),r.context_editing=s,new D({content:e.content,tool_calls:n,response_metadata:r,id:e.id,name:e.name,additional_kwargs:e.additional_kwargs})}};function iP(e={}){const t=e.edits??[new Xg],n=e.tokenCountMethod??"approx";return wt({name:"ContextEditingMiddleware",wrapModelCall:async(r,s)=>{if(!r.messages||r.messages.length===0)return s(r);const a=r.systemPrompt?[new Se(r.systemPrompt)]:[],i=n==="approx"?Ml:async c=>{const l=[...a,...c];if("getNumTokensFromMessages"in r.model)return r.model.getNumTokensFromMessages(l).then(({totalCount:u})=>u);throw new Error(`Model "${r.model.getName()}" does not support token counting`)};let o=await i(r.messages);for(const c of t)o=await c.apply({tokens:o,messages:r.messages,countTokens:i});return s(r)}})}function oP(e){return e?`Tool call limit exceeded. Do not call '${e}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const cP=["continue","error","end"],Qg="continue";function ey(e,t,n,r,s){const a=s?`'${s}' tool`:"Tool",i=[];n!==void 0&&e>n&&i.push(`thread limit exceeded (${e}/${n} calls)`),r!==void 0&&t>r&&i.push(`run limit exceeded (${t}/${r} calls)`);const o=i.join(" and ");return`${a} call limit reached: ${o}.`}const ty=Ur(cP).default(Qg);var ny=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(e,t,n,r,s=void 0){const a=ey(e,t,n,r,s);super(a),this.name="ToolCallLimitExceededError",this.threadCount=e,this.runCount=t,this.threadLimit=n,this.runLimit=r,this.toolName=s}};Y({toolName:pe().optional(),threadLimit:le().optional(),runLimit:le().optional(),exitBehavior:ty});const lP=Y({threadToolCallCount:Ss(pe(),le()).default({}),runToolCallCount:Ss(pe(),le()).default({})}),uP="__all__";function dP(e){if(e.threadLimit===void 0&&e.runLimit===void 0)throw new Error("At least one limit must be specified (threadLimit or runLimit)");const t=e.exitBehavior??Qg,n=ty.safeParse(t);if(!n.success)throw new Error(Jc(n.error).slice(2));if(e.threadLimit!==void 0&&e.runLimit!==void 0&&e.runLimit>e.threadLimit)throw new Error(`runLimit (${e.runLimit}) cannot exceed threadLimit (${e.threadLimit}). The run limit should be less than or equal to the thread limit.`);const r=e.toolName?`ToolCallLimitMiddleware[${e.toolName}]`:"ToolCallLimitMiddleware";return wt({name:r,stateSchema:lP,afterModel:{canJumpTo:["end"],hook:s=>{const a=[...s.messages].reverse().find(D.isInstance);if(!a||!a.tool_calls)return;const i=(T,k)=>e.threadLimit!==void 0&&T+1>e.threadLimit||e.runLimit!==void 0&&k+1>e.runLimit,o=T=>e.toolName===void 0||T.name===e.toolName,c=(T,k,O)=>{const C=[],y=[];let N=k,I=O;for(const R of T)o(R)&&(i(N,I)?y.push(R):(C.push(R),N+=1,I+=1));return{allowed:C,blocked:y,finalThreadCount:N,finalRunCount:I+y.length}},l=e.toolName??uP,u={...s.threadToolCallCount??{}},d={...s.runToolCallCount??{}},h=u[l]??0,p=d[l]??0,{allowed:f,blocked:g,finalThreadCount:b,finalRunCount:S}=c(a.tool_calls,h,p);if(u[l]=b,d[l]=S,g.length===0)return f.length>0?{threadToolCallCount:u,runToolCallCount:d}:void 0;if(t==="error"){const T=b+g.length;throw new ny(T,S,e.threadLimit,e.runLimit,e.toolName)}const w=oP(e.toolName),v=g.map(T=>new X({content:w,tool_call_id:T.id,name:T.name,status:"error"}));if(t==="end"){let T=[];if(e.toolName!==void 0?T=a.tool_calls.filter(C=>C.name!==e.toolName):new Set(a.tool_calls.map(y=>y.name).filter(Boolean)).size>1&&(T=f.length>0?f:a.tool_calls),T.length>0){const C=Array.from(new Set(T.map(y=>y.name).filter(Boolean))).join(", ");throw new Error(`Cannot end execution with other tool calls pending. Found calls to: ${C}. Use 'continue' or 'error' behavior instead.`)}const k=b+g.length,O=ey(k,S,e.threadLimit,e.runLimit,e.toolName);return v.push(new D(O)),{threadToolCallCount:u,runToolCallCount:d,jumpTo:"end",messages:v}}return{threadToolCallCount:u,runToolCallCount:d,messages:v}}},afterAgent:()=>({runToolCallCount:{}})})}const hP=`Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
253
- It also helps the user understand the progress of the task and overall progress of their requests.
254
- Only use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the taks directly.
255
-
256
- ## When to Use This Tool
257
- Use this tool in these scenarios:
258
-
259
- 1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
260
- 2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
261
- 3. User explicitly requests todo list - When the user directly asks you to use the todo list
262
- 4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
263
- 5. The plan may need future revisions or updates based on results from the first few steps. Keeping track of this in a list is helpful.
264
-
265
- ## How to Use This Tool
266
- 1. When you start working on a task - Mark it as in_progress BEFORE beginning work.
267
- 2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation.
268
- 3. You can also update future tasks, such as deleting them if they are no longer necessary, or adding new tasks that are necessary. Don't change previously completed tasks.
269
- 4. You can make several updates to the todo list at once. For example, when you complete a task, you can mark the next task you need to start as in_progress.
270
-
271
- ## When NOT to Use This Tool
272
- It is important to skip using this tool when:
273
- 1. There is only a single, straightforward task
274
- 2. The task is trivial and tracking it provides no benefit
275
- 3. The task can be completed in less than 3 trivial steps
276
- 4. The task is purely conversational or informational
277
-
278
- ## Examples of When to Use the Todo List
279
-
280
- <example>
281
- User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
282
- Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
283
- *Creates todo list with the following items:*
284
- 1. Create dark mode toggle component in Settings page
285
- 2. Add dark mode state management (context/store)
286
- 3. Implement CSS-in-JS styles for dark theme
287
- 4. Update existing components to support theme switching
288
- 5. Run tests and build process, addressing any failures or errors that occur
289
- *Begins working on the first task*
290
-
291
- <reasoning>
292
- The assistant used the todo list because:
293
- 1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes
294
- 2. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
295
- 3. Both of the user's requests are complex and require multiple steps to complete.
296
- </reasoning>
297
- </example>
298
-
299
- <example>
300
- User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases.
301
- Assistant: I'll help you plan a comprehensive marketing campaign for your product launch. Let me create a todo list to organize all the components.
302
- *Creates todo list with the following items:*
303
- 1. Define target audience and key messaging
304
- 2. Create social media content calendar and posting schedule
305
- 3. Design email marketing sequence and automation flows
306
- 4. Draft press release and identify media contacts
307
- 5. Set up tracking and analytics for campaign performance
308
- 6. Create visual assets and brand materials
309
- 7. Coordinate launch timeline and deliverables
310
- *Begins working on the first task*
311
-
312
- <reasoning>
313
- The assistant used the todo list because:
314
- 1. Marketing campaign planning involves multiple distinct channels and activities
315
- 2. Each component requires careful coordination and planning
316
- 3. The systematic approach ensures all aspects of the launch are covered
317
- </reasoning>
318
- </example>
319
-
320
- <example>
321
- User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
322
- Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
323
- *Uses search tools to locate all instances of getCwd in the codebase*
324
- Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
325
- *Creates todo list with specific items for each file that needs updating*
326
-
327
- <reasoning>
328
- The assistant used the todo list because:
329
- 1. The assistant searched to understand the scope of the task
330
- 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps (>3)
331
- 3. The todo list helps ensure every instance is tracked and updated systematically
332
- 4. This approach prevents missing any occurrences and maintains consistency.
333
- </reasoning>
334
- </example>
335
-
336
- <example>
337
- User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow.
338
- Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization.
339
- *Creates todo list with items like: 1) Sort and declutter desk items, 2) Set up physical filing system for documents, 3) Organize digital files and folders, 4) Create daily workflow and productivity systems, 5) Establish maintenance routines*
340
- Let's start with decluttering your desk space to create a clean foundation for the other organizational systems.
341
-
342
- <reasoning>
343
- The assistant used the todo list because:
344
- 1. The user provided multiple distinct organizational tasks
345
- 2. Each area requires different approaches and careful planning
346
- 3. Home organization benefits from systematic, step-by-step completion
347
- 4. Progress tracking ensures all areas are addressed thoroughly
348
- </reasoning>
349
- </example>
350
-
351
- ## Examples of When NOT to Use the Todo List
352
-
353
- <example>
354
- User: How do I print 'Hello World' in Python?
355
- Assistant: In Python, you can print "Hello World" with this simple code:
356
-
357
- \`\`\`python
358
- print("Hello World")
359
- \`\`\`
360
-
361
- This will output the text "Hello World" to the console when executed.</assistant>
362
-
363
- <reasoning>
364
- The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
365
- </reasoning>
366
- </example>
367
-
368
- <example>
369
- User: What's the best way to water houseplants?
370
- Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines:
371
-
372
- - Check soil moisture by inserting your finger about 1-2 inches into the soil
373
- - Water thoroughly when the top inch feels dry, allowing water to drain from the bottom
374
- - Use room temperature water and water in the morning when possible
375
- - Avoid overwatering, which is more harmful than underwatering for most plants
376
-
377
- Different plants have different needs, so it's important to research your specific varieties for optimal care.
378
-
379
- <reasoning>
380
- The assistant did not use the todo list because this is an informational request with no actual tasks to complete. The user is simply asking for advice and explanation, not for the assistant to perform multiple steps or activities.
381
- </reasoning>
382
- </example>
383
-
384
- <example>
385
- User: Can you add a comment to the calculateTotal function to explain what it does?
386
- Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
387
- * Uses the Edit tool to add a comment to the calculateTotal function *
388
-
389
- <reasoning>
390
- The assistant did not use the todo list because this is a single, straightforward task confined to one location. Adding a comment doesn't require tracking multiple steps or systematic organization.
391
- </reasoning>
392
- </example>
393
-
394
- <example>
395
- User: What time is it in Tokyo right now?
396
- Assistant: I'll check the current time in Tokyo for you.
397
-
398
- *Searches for current time in Tokyo*
399
-
400
- The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9.
401
-
402
- <reasoning>
403
- The assistant did not use the todo list because this is a single information lookup with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward request.
404
- </reasoning>
405
- </example>
406
-
407
- <example>
408
- User: I need to write a function that checks if a number is prime and then test it out.
409
- Assistant: I'll help you write a function that checks if a number is prime and then test it out.
410
- *Writes function that checks if a number is prime*
411
- *Tests the function*
412
-
413
- <reasoning>
414
- Even though this is a multi-step task, it is very straightforward and can be completed in two trivial steps (which is less than 3 steps!). Using the todo list here is overkill and wastes time and tokens.
415
- </reasoning>
416
- </example>
417
-
418
- <example>
419
- User: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
420
- Assistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
421
- *Orders a pizza from Dominos*
422
- *Orders a burger from McDonald's*
423
- *Orders a salad from Subway*
424
-
425
- <reasoning>
426
- Even though this is a multi-step task, assuming the assistant has the ability to order from these restaurants, it is very straightforward and can be completed in three trivial tool calls.
427
- Using the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact.
428
- </reasoning>
429
- </example>
430
-
431
-
432
- ## Task States and Management
433
-
434
- 1. **Task States**: Use these states to track progress:
435
- - pending: Task not yet started
436
- - in_progress: Currently working on (you can have multiple tasks in_progress at a time if they are not related to each other and can be run in parallel)
437
- - completed: Task finished successfully
438
-
439
- 2. **Task Management**:
440
- - Update task status in real-time as you work
441
- - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
442
- - Complete current tasks before starting new ones
443
- - Remove tasks that are no longer relevant from the list entirely
444
- - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.
445
- - IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress to show the user that you are working on something.
446
-
447
- 3. **Task Completion Requirements**:
448
- - ONLY mark a task as completed when you have FULLY accomplished it
449
- - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
450
- - When blocked, create a new task describing what needs to be resolved
451
- - Never mark a task as completed if:
452
- - There are unresolved issues or errors
453
- - Work is partial or incomplete
454
- - You encountered blockers that prevent completion
455
- - You couldn't find necessary resources or dependencies
456
- - Quality standards haven't been met
457
-
458
- 4. **Task Breakdown**:
459
- - Create specific, actionable items
460
- - Break complex tasks into smaller, manageable steps
461
- - Use clear, descriptive task names
462
-
463
- Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully
464
- Remember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.`,ry=`## \`write_todos\`
465
-
466
- You have access to the \`write_todos\` tool to help you manage and plan complex objectives.
467
- Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.
468
- This tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.
469
-
470
- It is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.
471
- For simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.
472
- Writing todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.
473
-
474
- ## Important To-Do List Usage Notes to Remember
475
- - The \`write_todos\` tool should never be called multiple times in parallel.
476
- - Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`,pP=Ur(["pending","in_progress","completed"]).describe("Status of the todo"),sy=Y({content:pe().describe("Content of the todo item"),status:pP}),fP=Y({todos:Jt(sy).default([])});function mP(e){const t=Ol(({todos:n},r)=>new be({update:{todos:n,messages:[new X({content:`Updated todo list to ${JSON.stringify(n)}`,tool_call_id:r.toolCall?.id})]}}),{name:"write_todos",description:e?.toolDescription??hP,schema:Y({todos:Jt(sy).describe("List of todo items to update")})});return wt({name:"todoListMiddleware",stateSchema:fP,tools:[t],wrapModelCall:(n,r)=>r({...n,systemPrompt:(n.systemPrompt?`${n.systemPrompt}
477
-
478
- `:"")+(e?.systemPrompt??ry)})})}const gP="end",yP=Y({threadLimit:le().optional(),runLimit:le().optional(),exitBehavior:Ur(["throw","end"]).optional()}),_P=Y({threadModelCallCount:le().default(0),runModelCallCount:le().default(0)});var th=class extends Error{constructor({threadLimit:e,runLimit:t,threadCount:n,runCount:r}){const s=[];typeof e=="number"&&typeof n=="number"&&s.push(`thread level call limit reached with ${n} model calls`),typeof t=="number"&&typeof r=="number"&&s.push(`run level call limit reached with ${r} model calls`),super(`Model call limits exceeded${s.length>0?`: ${s.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function ay(e){return wt({name:"ModelCallLimitMiddleware",contextSchema:yP,stateSchema:_P,beforeModel:{canJumpTo:["end"],hook:(t,n)=>{const r=n.context.exitBehavior??e?.exitBehavior??gP,s=n.context.threadLimit??e?.threadLimit,a=n.context.runLimit??e?.runLimit,i=t.threadModelCallCount,o=t.runModelCallCount;if(typeof s=="number"&&s<=i){const c=new th({threadLimit:s,threadCount:i});if(r==="end")return{jumpTo:"end",messages:[new D(c.message)]};throw c}if(typeof a=="number"&&a<=o){const c=new th({runLimit:a,runCount:o});if(r==="end")return{jumpTo:"end",messages:[new D(c.message)]};throw c}return t}},afterModel:t=>({runModelCallCount:t.runModelCallCount+1,threadModelCallCount:t.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function wP(...e){return wt({name:"modelFallbackMiddleware",wrapModelCall:async(t,n)=>{try{return await n(t)}catch(r){for(let s=0;s<e.length;s++)try{const a=e[s],i=typeof a=="string"?await rs(a):a;return await n({...t,model:i})}catch(a){if(s===e.length-1)throw a}throw r}}})}function vP(e,t){const{backoffFactor:n,initialDelayMs:r,maxDelayMs:s,jitter:a}=e;let i;if(n===0?i=r:i=r*n**t,i=Math.min(i,s),a&&i>0){const o=i*.25;i=i+(Math.random()*2-1)*o,i=Math.max(0,i)}return i}const nh=Y({maxRetries:le().min(0).default(2),tools:Jt(gt([nt(),nt(),pe()])).optional(),retryOn:gt([Ua().args(Ba(Error)).returns(bs()),Jt(nt())]).default(()=>()=>!0),onFailure:gt([vr("raise"),vr("return_message"),Ua().args(Ba(Error)).returns(pe())]).default("return_message"),backoffFactor:le().min(0).default(2),initialDelayMs:le().min(0).default(1e3),maxDelayMs:le().min(0).default(6e4),jitter:bs().default(!0)});function bP(e={}){const{maxRetries:t,tools:n,retryOn:r,onFailure:s,backoffFactor:a,initialDelayMs:i,maxDelayMs:o,jitter:c}=nh.parse(e),l=[];for(const g of n??[])if(typeof g=="string")l.push(g);else if("name"in g&&typeof g.name=="string")l.push(g.name);else throw new TypeError("Expected a tool name string or tool instance to be passed to toolRetryMiddleware");const u=g=>l.length===0?!0:l.includes(g),d=g=>typeof r=="function"?r(g):r.some(b=>g.constructor===b),h={backoffFactor:a,initialDelayMs:i,maxDelayMs:o,jitter:c},p=(g,b,S)=>{const w=b.constructor.name;return`Tool '${g}' failed after ${S} ${S===1?"attempt":"attempts"} with ${w}`},f=(g,b,S,w)=>{if(s==="raise")throw S;let v;return typeof s=="function"?v=s(S):v=p(g,S,w),new X({content:v,tool_call_id:b,name:g,status:"error"})};return wt({name:"toolRetryMiddleware",contextSchema:nh,wrapToolCall:async(g,b)=>{const S=g.tool.name;if(!u(S))return b(g);const w=g.toolCall.id??"";for(let v=0;v<=t;v++)try{return await b(g)}catch(T){const k=v+1,O=T&&typeof T=="object"&&"message"in T?T:new Error(String(T));if(!d(O))return f(S,w,O,k);if(v<t){const C=vP(h,v);C>0&&await tA(C)}else return f(S,w,O,k)}throw new Error("Unexpected: retry loop completed without returning")}})}var SP={};Tf(SP,{AIMessage:()=>D,AIMessageChunk:()=>yt,BaseMessage:()=>rt,BaseMessageChunk:()=>Nn,ClearToolUsesEdit:()=>Xg,Document:()=>an,DynamicStructuredTool:()=>Ni,DynamicTool:()=>kl,FakeToolCallingModel:()=>pO,HumanMessage:()=>he,HumanMessageChunk:()=>Zs,InMemoryStore:()=>Wf,MultipleStructuredOutputsError:()=>pc,MultipleToolsBoundError:()=>hc,ProviderStrategy:()=>Un,StructuredOutputParsingError:()=>Mf,StructuredTool:()=>er,SystemMessage:()=>Se,SystemMessageChunk:()=>Jn,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>ry,Tool:()=>Al,ToolCallLimitExceededError:()=>ny,ToolInvocationError:()=>Pl,ToolMessage:()=>X,ToolMessageChunk:()=>Ks,ToolStrategy:()=>yn,anthropicPromptCachingMiddleware:()=>JI,contextEditingMiddleware:()=>iP,countTokensApproximately:()=>Ml,createAgent:()=>Kg,createMiddleware:()=>wt,dynamicSystemPromptMiddleware:()=>KI,filterMessages:()=>Ef,humanInTheLoopMiddleware:()=>BI,initChatModel:()=>rs,llmToolSelectorMiddleware:()=>XI,modelCallLimitMiddleware:()=>ay,modelFallbackMiddleware:()=>wP,piiRedactionMiddleware:()=>sP,providerStrategy:()=>QC,summarizationMiddleware:()=>kI,todoListMiddleware:()=>mP,tool:()=>Ol,toolCallLimitMiddleware:()=>dP,toolRetryMiddleware:()=>bP,toolStrategy:()=>XC,trimMessages:()=>xl});var gi={},Cr,iy=(Cr=class{disallowedTools;connectorToolMap=new Map;constructor(t){this.disallowedTools=t??[]}static async createTools(t,n){const r=new this(n);(!t.activeSessions||Object.keys(t.activeSessions).length===0)&&(E.info("No active sessions found, creating new ones..."),await t.createAllSessions());const s=t.getAllActiveSessions(),a=Object.values(s).map(i=>i.connector);return r.createToolsFromConnectors(a)}async loadToolsForConnector(t){if(this.connectorToolMap.has(t)){const s=this.connectorToolMap.get(t);return E.debug(`Returning ${s.length} existing tools for connector`),s}const n=[];if(!await this.ensureConnectorInitialized(t))return[];for(const s of t.tools){const a=this.convertTool(s,t);a&&n.push(a)}return this.connectorToolMap.set(t,n),E.debug(`Loaded ${n.length} new tools for connector: ${n.map(s=>s?.name??String(s)).join(", ")}`),n}async createToolsFromConnectors(t){const n=[];for(const r of t){const s=await this.loadToolsForConnector(r);n.push(...s)}return E.debug(`Available tools: ${n.length}`),n}checkConnectorInitialized(t){return!!(t.tools&&t.tools.length)}async ensureConnectorInitialized(t){if(!this.checkConnectorInitialized(t)){E.debug("Connector doesn't have tools, initializing it");try{return await t.initialize(),!0}catch(n){return E.error(`Error initializing connector: ${n}`),!1}}return!0}},G(Cr,"BaseAdapter"),Cr);function oy(e){try{return sw.convert(e)}catch(t){return E.warn(`Failed to convert JSON schema to Zod: ${t}`),Tt()}}G(oy,"schemaToZod");var Ar,Dn=(Ar=class extends iy{constructor(t=[]){super(t)}convertTool(t,n){if(this.disallowedTools.includes(t.name))return null;const r=t.inputSchema?oy(t.inputSchema):Y({}).optional();return new Ni({name:t.name??"NO NAME",description:t.description??"",schema:r,func:G(async a=>{E.debug(`MCP tool "${t.name}" received input: ${JSON.stringify(a)}`);try{const i=await n.callTool(t.name,a);return JSON.stringify(i)}catch(i){return E.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}},G(Ar,"LangChainAdapter"),Ar),kr,Bi=(kr=class extends er{name="mcp_server_tool";description="Base tool for MCP server operations.";schema;_manager;constructor(t){super(),this._manager=t}async _call(t,n,r){throw new Error("Method not implemented.")}get manager(){return this._manager}},G(kr,"MCPServerTool"),kr),TP=Y({}),Or,EP=(Or=class extends Bi{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=TP;constructor(t){super(t)}async _call(){return this.manager.activeServer?`Currently active MCP server: ${this.manager.activeServer}`:"No MCP server is currently active. Use connect_to_mcp_server to connect to a server."}},G(Or,"AcquireActiveMCPServerTool"),Or),xr,CP=(xr=class extends er{name="add_mcp_server_from_config";description="Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";schema=Y({serverName:pe().describe("The name for the new MCP server."),serverConfig:Tt().describe('The configuration object for the server. This should not include the top-level "mcpServers" key.')});manager;constructor(t){super(),this.manager=t}async _call({serverName:t,serverConfig:n}){try{this.manager.client.addServer(t,n);let r=`Server '${t}' added to the client.`;E.debug(`Connecting to new server '${t}' and discovering tools.`);const a=(await this.manager.client.createSession(t)).connector,i=await this.manager.adapter.createToolsFromConnectors([a]);this.manager.serverTools[t]=i,this.manager.initializedServers[t]=!0,this.manager.activeServer=t;const o=i.length;return r+=` Session created and connected. '${t}' is now the active server with ${o} tools available.`,r+=`
479
-
480
- ${i.map(c=>c.name).join(`
481
- `)}`,E.info(r),r}catch(r){return E.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),AP=Y({serverName:pe().describe("The name of the MCP server.")}),Ir,kP=(Ir=class extends Bi{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=AP;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(E.debug(`Using existing session for server '${t}'`),r||(E.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 E.error(`Error connecting to server '${t}': ${String(r)}`),`Failed to connect to server '${t}': ${String(r)}`}}},G(Ir,"ConnectMCPServerTool"),Ir),OP=Y({}),Pr,xP=(Pr=class extends Bi{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=OP;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
482
- `)}catch(i){E.error(`Unexpected error listing tools for server '${r}': ${String(i)}`)}}return n.join(`
483
- `)}},G(Pr,"ListMCPServersTool"),Pr),IP=Y({}),Nr,PP=(Nr=class extends Bi{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=IP;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,NP=(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,E.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){E.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?"✅":"❌"}));E.info(`Server Manager State: [${t}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&E.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),E.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(E.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),E.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){E.error(`Failed to create tools from connector for server '${n}': ${c}`);continue}const i=this.serverTools[n];!i||!YE(i,a)?(this.serverTools[n]=a,this.initializedServers[n]=!0,E.debug(`Prefetched ${a.length} tools for server '${n}'.`)):E.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){E.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){E.level==="debug"&&this.logState("Providing tools to agent");const t=this.overrideManagementTools??[new CP(this),new xP(this),new kP(this),new EP(this),new PP(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return E.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...t,...n]}return t}},G(Mr,"ServerManager"),Mr),Rr,Uc=(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 Ts(async()=>{const{langfuseHandler:s,langfuseInitPromise:a}=await Promise.resolve().then(()=>rh);return{langfuseHandler:s,langfuseInitPromise:a}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await Ts(async()=>{const{initializeLangfuse:a}=await Promise.resolve().then(()=>rh);return{initializeLangfuse:a}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),E.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"),E.debug("ObservabilityManager: Langfuse handler available"))}catch{E.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(E.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?E.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):E.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(E.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),E.debug(`ObservabilityManager: Added custom callback: ${t.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],E.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();E.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();E.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,MP=($r=class{},G($r,"BaseTelemetryEvent"),$r),Lr,RP=(Lr=class extends MP{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 Fa(){try{if(typeof __dirname>"u"||typeof Fo>"u")return"unknown";const e=Va(__dirname,"../../package.json");return JSON.parse((void 0)(e,"utf-8")).version||"unknown"}catch{return"unknown"}}G(Fa,"getPackageVersion");function cy(e){return e._llm_type||e.constructor.name.toLowerCase()}G(cy,"getModelProvider");function ly(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(ly,"getModelName");function uy(e){return[cy(e),ly(e)]}G(uy,"extractModelInfo");function vs(){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 Fo<"u"&&typeof Fo<"u"&&!1)}catch{return!1}}G(vs,"isNodeJSEnvironment");var jr,$P=(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){E.debug(`Failed to send Scarf event: ${n}`)}}},G(jr,"ScarfEventLogger"),jr);function Bc(){if(!vs())return"/tmp/mcp_use_cache";const e=gi.XDG_CACHE_HOME;if(e&&w_(e))return e;const t=(void 0)();return Va(t,".cache")}G(Bc,"getCacheHome");var Lt,zc=(Lt=class{USER_ID_PATH=Va(Bc(),"mcp_use_3","telemetry_user_id");VERSION_DOWNLOAD_PATH=Va(Bc(),"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=vs(),n=typeof process<"u"&&gi?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()==="false"||!1;if(this._source=typeof process<"u"&&gi?.MCP_USE_TELEMETRY_SOURCE||"typescript",n)this._posthogClient=null,this._scarfClient=null,E.debug("Telemetry disabled via environment variable");else if(!t)this._posthogClient=null,this._scarfClient=null,E.debug("Telemetry disabled - non-Node.js environment detected (e.g., Cloudflare Workers)");else{E.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.");try{this._posthogClient=new XE(this.PROJECT_API_KEY,{host:this.HOST,disableGeoip:!1})}catch(r){E.warn(`Failed to initialize PostHog telemetry: ${r}`),this._posthogClient=null}try{this._scarfClient=new $P(this.SCARF_GATEWAY_URL,3e3)}catch(r){E.warn(`Failed to initialize Scarf telemetry: ${r}`),this._scarfClient=null}}}static getInstance(){return Lt.instance||(Lt.instance=new Lt),Lt.instance}setSource(t){this._source=t,E.debug(`Telemetry source set to: ${t}`)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!vs())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{if(!(void 0)(this.USER_ID_PATH)){E.debug(`Creating user ID path: ${this.USER_ID_PATH}`),(void 0)(mu(this.USER_ID_PATH),{recursive:!0});const n=by();(void 0)(this.USER_ID_PATH,n),this._currUserId=n,E.debug(`User ID path created: ${this.USER_ID_PATH}`)}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(n=>E.debug(`Failed to track package download: ${n}`))}catch(t){E.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=Fa(),n.language="typescript",n.source=this._source,this._posthogClient.capture({distinctId:this.userId,event:t.name,properties:n})}catch(n){E.debug(`Failed to track PostHog event ${t.name}: ${n}`)}if(this._scarfClient)try{const n={};n.mcp_use_version=Fa(),n.user_id=this.userId,n.event=t.name,n.language="typescript",n.source=this._source,await this._scarfClient.logEvent(n)}catch(n){E.debug(`Failed to track Scarf event ${t.name}: ${n}`)}}}async trackPackageDownload(t){if(this._scarfClient&&vs())try{const n=Fa();let r=!1,s=!1;if((void 0)(this.VERSION_DOWNLOAD_PATH)||(r=!0,s=!0,(void 0)(mu(this.VERSION_DOWNLOAD_PATH),{recursive:!0}),(void 0)(this.VERSION_DOWNLOAD_PATH,n)),r){E.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){E.debug(`Failed to track Scarf package_download event: ${n}`)}}async trackAgentExecution(t){const n=new RP(t);await this.capture(n)}flush(){if(this._posthogClient)try{this._posthogClient.flush(),E.debug("PostHog client telemetry queue flushed")}catch(t){E.debug(`Failed to flush PostHog client: ${t}`)}this._scarfClient&&E.debug("Scarf telemetry events sent immediately (no flush needed)")}shutdown(){if(this._posthogClient)try{this._posthogClient.shutdown(),E.debug("PostHog client shutdown successfully")}catch(t){E.debug(`Error shutting down PostHog client: ${t}`)}this._scarfClient&&E.debug("Scarf telemetry client shutdown (no action needed)")}},G(Lt,"Telemetry"),du(Lt,"instance",null),Lt);function LP(e){zc.getInstance().setSource(e)}G(LP,"setTelemetrySource");var jP="/api/v1/chats",DP="/api/v1/chats/{chat_id}/execute",Dr,dy=(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??gi.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 ba(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){E.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}${jP}`;E.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 E.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&&E.warn("External history is not yet supported for remote execution");try{E.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),E.info("🔧 Using structured output with schema"));const c={"Content-Type":"application/json","x-api-key":this.apiKey},l=`${this.baseUrl}${DP.replace("{chat_id}",i)}`;E.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?(E.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?(E.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?(E.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?(E.error(`❌ Validation error: ${h}`),new Error(`Request validation failed: ${h}. Please check your query parameters and output schema format.`)):p===500?(E.error(`❌ Server error: ${h}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(E.error(`❌ Remote execution failed with status ${p}: ${h}`),new Error(`Remote agent execution failed: ${p} - ${h}`))}const d=await u.json();if(E.info(`🔧 Response: ${JSON.stringify(d)}`),E.info("✅ Remote execution completed successfully"),typeof d=="object"&&d!==null){if(d.status==="error"||d.error!==null){const h=d.error??String(d);throw E.error(`❌ Remote agent execution failed: ${h}`),new Error(`Remote agent execution failed: ${h}`)}if(String(d).includes("failed to initialize"))throw E.error(`❌ Agent initialization failed: ${d}`),new Error(`Agent initialization failed on remote server. This usually indicates:
484
- • Invalid agent configuration (LLM model, system prompt)
485
- • Missing or invalid MCP server configurations
486
- • Network connectivity issues with MCP servers
487
- • Missing environment variables or credentials
488
- Raw error: ${d}`)}return a?this.parseStructuredResponse(d,a):typeof d=="object"&&d!==null&&"result"in d?d.result:typeof d=="string"?d:String(d)}catch(i){throw i instanceof Error?i.name==="AbortError"?(E.error(`❌ Remote execution timed out: ${i}`),new Error("Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.")):(E.error(`❌ Remote execution error: ${i}`),new Error(`Remote agent execution failed: ${i.message}`)):(E.error(`❌ Remote execution error: ${i}`),new Error(`Remote agent execution failed: ${String(i)}`))}}async*stream(t,n,r,s,a){return await this.run(t,n,r,s,a)}async close(){E.info("🔌 Remote agent client closed")}},G(Dr,"RemoteAgent"),Dr);function hy(e,t){const n=new Set(t??[]),r=[];for(const s of e){if(n.has(s.name))continue;const a=s.description.replace(/\{/g,"{{").replace(/\}/g,"}}");r.push(`- ${s.name}: ${a}`)}return r}G(hy,"generateToolDescriptions");function py(e,t,n){const r=t.join(`
489
- `);let s;return e.includes("{tool_descriptions}")?s=e.replace("{tool_descriptions}",r):(console.warn("`{tool_descriptions}` placeholder not found; appending at end."),s=`${e}
490
-
491
- Available tools:
492
- ${r}`),n&&(s+=`
493
-
494
- ${n}`),s}G(py,"buildSystemPromptContent");function fy(e,t,n,r,s,a,i){if(a)return new Se({content:a});const o=r?n:t,c=hy(e,s),l=py(o,c,i);return new Se({content:l})}G(fy,"createSystemMessage");var FP=`You are a helpful AI assistant.
495
- You have access to the following tools:
496
-
497
- {tool_descriptions}
498
-
499
- Use the following format:
500
-
501
- Question: the input question you must answer
502
- Thought: you should always think about what to do
503
- Action: the action to take, should be one of the available tools
504
- Action Input: the input to the action
505
- Observation: the result of the action
506
- ... (this Thought/Action/Action Input/Observation can repeat N times)
507
- Thought: I now know the final answer
508
- Final Answer: the final answer to the original input question`,UP=`You are a helpful assistant designed to interact with MCP
509
- (Model Context Protocol) servers. You can manage connections to different servers and use the tools
510
- provided by the currently active server.
511
-
512
- Important: The available tools change depending on which server is active.
513
- If a request requires tools not listed below (e.g., file operations, web browsing,
514
- image manipulation), you MUST first connect to the appropriate server using
515
- 'connect_to_mcp_server'.
516
- Use 'list_mcp_servers' to find the relevant server if you are unsure.
517
- Only after successfully connecting and seeing the new tools listed in
518
- the response should you attempt to use those server-specific tools.
519
- Before attempting a task that requires specific tools, you should
520
- ensure you are connected to the correct server and aware of its
521
- available tools. If unsure, use 'list_mcp_servers' to see options
522
- or 'get_active_mcp_server' to check the current connection.
523
-
524
- When you connect to a server using 'connect_to_mcp_server',
525
- you will be informed about the new tools that become available.
526
- You can then use these server-specific tools in subsequent steps.
527
-
528
- Here are the tools *currently* available to you (this list includes server management tools and will
529
- change when you connect to a server):
530
- {tool_descriptions}
531
- `,Fr,BP=(Fr=class{llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;constructor(t){if(t.agentId){this.isRemote=!0,this.remoteAgent=new dy({agentId:t.agentId,apiKey:t.apiKey,baseUrl:t.baseUrl}),this.maxSteps=t.maxSteps??5,this.memoryEnabled=t.memoryEnabled??!0,this.autoInitialize=t.autoInitialize??!1,this.verbose=t.verbose??!1,this.observe=t.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new Dn,this.telemetry=zc.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Uc({customCallbacks:t.callbacks,agentId:t.agentId}),this.callbacks=[];return}if(!t.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(this.llm=t.llm,this.client=t.client,this.connectors=t.connectors??[],this.maxSteps=t.maxSteps??5,this.autoInitialize=t.autoInitialize??!1,this.memoryEnabled=t.memoryEnabled??!0,this.systemPrompt=t.systemPrompt??null,this.systemPromptTemplateOverride=t.systemPromptTemplate??null,this.additionalInstructions=t.additionalInstructions??null,this.disallowedTools=t.disallowedTools??[],this.additionalTools=t.additionalTools??[],this.toolsUsedNames=t.toolsUsedNames??[],this.useServerManager=t.useServerManager??!1,this.verbose=t.verbose??!1,this.observe=t.observe??!0,!this.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=t.adapter??new Dn(this.disallowedTools),this.serverManager=t.serverManagerFactory?.(this.client)??new NP(this.client,this.adapter)}else this.adapter=t.adapter??new Dn(this.disallowedTools);if(this.telemetry=zc.getInstance(),this.llm){const[n,r]=uy(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Uc({customCallbacks:t.callbacks,verbose:this.verbose,observe:this.observe,agentId:t.agentId,metadataProvider:G(()=>this.getMetadata(),"metadataProvider"),tagsProvider:G(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:G(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:G(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:G(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}E.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const t=await this.observabilityManager.getHandlerNames();if(t.length>0&&E.info(`📊 Observability enabled with: ${t.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),E.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),E.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(E.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),E.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),E.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await Dn.createTools(this.client),E.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{E.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const r of this.connectors)r.isClientConnected||await r.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),E.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}E.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),E.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),E.info("✨ Agent initialization complete")}async createSystemMessageFromTools(t){const n=this.systemPromptTemplateOverride??FP;this.systemMessage=fy(t,n,UP,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof Se))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const t=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(a=>a.name);E.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[ay({runLimit:this.maxSteps})],s=Kg({model:this.llm,tools:this._tools,systemPrompt:t,middleware:r});return E.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(t){this.memoryEnabled&&this.conversationHistory.push(t)}getSystemMessage(){return this.systemMessage}setSystemMessage(t){this.systemMessage=new Se(t),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof Se)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),E.debug("Agent recreated with new system message"))}setDisallowedTools(t){this.disallowedTools=t,this.adapter=new Dn(this.disallowedTools),this._initialized&&E.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(t){const n=this.sanitizeMetadata(t);this.metadata={...this.metadata,...n},E.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(t){const n=this.sanitizeTags(t);this.tags=[...new Set([...this.tags,...n])],E.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(t){const n={};for(const[r,s]of Object.entries(t)){if(typeof r!="string"||r.length===0){E.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const a=r.replace(/[^\w-]/g,"_");if(s==null)n[a]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[a]=s;else if(Array.isArray(s)){const i=s.filter(o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean");i.length>0&&(n[a]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(E.warn(`Metadata value for key '${a}' is too large. Truncating.`),n[a]=`${i.substring(0,1e3)}...`):n[a]=s}catch(i){E.warn(`Failed to serialize metadata value for key '${a}': ${i}. Skipping.`)}else E.warn(`Unsupported metadata value type for key '${a}': ${typeof s}. Skipping.`)}return n}sanitizeTags(t){return t.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const t={};try{if(this.client){const n=this.client.getServerNames();t.mcp_servers_count=n.length,t.mcp_server_names=n;const r={};for(const s of n)try{const a=this.client.getServerConfig(s);if(a){let i="unknown";a.command?i="command":a.url?i="http":a.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!a.args,has_env:!!a.env,has_headers:!!a.headers,url:a.url||null,command:a.command||null}}}catch(a){E.warn(`Failed to get config for server '${s}': ${a}`),r[s]={type:"error",error:"config_unavailable"}}t.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(t.mcp_servers_count=this.connectors.length,t.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),t.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){E.warn(`Failed to collect MCP server info: ${n}`),t.error="collection_failed"}return t}_normalizeOutput(t){try{if(typeof t=="string")return t;if(t&&typeof t=="object"&&"content"in t)return this._normalizeOutput(t.content);if(Array.isArray(t)){const n=[];for(const r of t)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const a=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(a))}}return n.join("")}return String(t)}catch{return String(t)}}_isAIMessageLike(t){if(t instanceof D)return!0;if(typeof t!="object"||t===null)return!1;const n=t;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(t){return typeof t=="object"&&t!==null&&"tool_calls"in t&&Array.isArray(t.tool_calls)?t.tool_calls.length>0:!1}_isHumanMessageLike(t){if(t instanceof he)return!0;if(typeof t!="object"||t===null)return!1;const n=t;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(t){if(t instanceof X)return!0;if(typeof t!="object"||t===null)return!1;const n=t;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(t){if(t instanceof D||t&&typeof t=="object"&&"content"in t)return t.content}async _consumeAndReturn(t){for(;;){const{done:n,value:r}=await t.next();if(n)return r}}async run(t,n,r,s,a){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(t,n,r,s,a);const i=this.stream(t,n,r,s,a);return this._consumeAndReturn(i)}async*stream(t,n,r=!0,s,a){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(t,n,r,s,a);let i=!1;const o=Date.now();let c=!1,l=null,u=0;try{if(r&&!this._initialized?(await this.initialize(),i=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),i=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const S=this.serverManager.tools,w=new Set(S.map(T=>T.name)),v=new Set(this._tools.map(T=>T.name));(w.size!==v.size||[...w].some(T=>!v.has(T)))&&(E.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...w].join(", ")}`),this._tools=S,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const d=s??this.conversationHistory,h=[];for(const S of d)(this._isHumanMessageLike(S)||this._isAIMessageLike(S))&&h.push(S);const p=t.length>50?`${t.slice(0,50).replace(/\n/g," ")}...`:t.replace(/\n/g," ");E.info(`💬 Received query: '${p}'`),E.info("🏁 Starting agent execution");const f=3;let g=0;const b=[...h,new he(t)];for(;g<=f;){const S={messages:b};let w=!1;const v=await this._agentExecutor.stream(S,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const T of v){for(const[k,O]of Object.entries(T))if(E.debug(`📦 Node '${k}' output: ${JSON.stringify(O)}`),O&&typeof O=="object"&&"messages"in O){let C=O.messages;Array.isArray(C)||(C=[C]);for(const y of C)b.includes(y)||b.push(y);for(const y of C){if("tool_calls"in y&&Array.isArray(y.tool_calls)&&y.tool_calls.length>0)for(const N of y.tool_calls){const I=N.name||"unknown",R=N.args||{};this.toolsUsedNames.push(I),u++;let z=JSON.stringify(R);z.length>100&&(z=`${z.slice(0,97)}...`),E.info(`🔧 Tool call: ${I} with input: ${z}`),yield{action:{tool:I,toolInput:R,log:`Calling tool ${I}`},observation:""}}if(this._isToolMessageLike(y)){const N=y.content;let I=String(N);if(I.length>100&&(I=`${I.slice(0,97)}...`),I=I.replace(/\n/g," "),E.info(`📄 Tool result: ${I}`),this.useServerManager&&this.serverManager){const R=this.serverManager.tools,z=new Set(R.map(fe=>fe.name)),ce=new Set(this._tools.map(fe=>fe.name));if(z.size!==ce.size||[...z].some(fe=>!ce.has(fe))){E.info(`🔄 Tools changed during execution. New tools: ${[...z].join(", ")}`),this._tools=R,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),w=!0,g++,E.info(`🔃 Restarting execution with updated tools (restart ${g}/${f})`);break}}}this._isAIMessageLike(y)&&!this._messageHasToolCalls(y)&&(l=this._normalizeOutput(this._getMessageContent(y)),E.info("✅ Agent finished with output"))}if(w)break}if(w)break}if(!w)break;if(g>f){E.warn(`⚠️ Max restarts (${f}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled&&(this.addToHistory(new he(t)),l&&this.addToHistory(new D(l))),a&&l)try{E.info("🔧 Attempting structured output...");const S=await this._attemptStructuredOutput(l,this.llm,a);return this.memoryEnabled&&this.addToHistory(new D(`Structured result: ${JSON.stringify(S)}`)),E.info("✅ Structured output successful"),c=!0,S}catch(S){throw E.error(`❌ Structured output failed: ${S}`),new Error(`Failed to generate structured output: ${S instanceof Error?S.message:String(S)}`)}return E.info(`🎉 Agent execution complete in ${((Date.now()-o)/1e3).toFixed(2)} seconds`),c=!0,l||"No output generated"}catch(d){throw E.error(`❌ Error running query: ${d}`),i&&r&&(E.info("🧹 Cleaning up resources after error"),await this.close()),d}finally{const d=Date.now()-o;let h=0;this.client?h=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(h=this.connectors.length);const p=this.memoryEnabled?this.conversationHistory.length:0,f=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:t,success:c,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:h,serverIdentifiers:this.connectors.map(g=>g.publicIdentifier),totalToolsAvailable:f.length,toolsAvailableNames:f.map(g=>g.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:l||"",executionTimeMs:d,errorType:c?null:"execution_error",conversationHistoryLength:p}),r&&!this.client&&i&&(E.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(E.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}E.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)E.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const t of this.connectors)E.info("🔄 Disconnecting connector"),await t.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new Dn)}finally{this._initialized=!1,E.info("👋 Agent closed successfully")}}async*prettyStreamEvents(t,n,r=!0,s,a){const{prettyStreamEvents:i}=await Ts(async()=>{const{prettyStreamEvents:c}=await import("./display-LIYVTGEU-D2dm8q2H.js");return{prettyStreamEvents:c}},__vite__mapDeps([0,1,2])),o="";for await(const c of i(this.streamEvents(t,n,r,s,a)))yield;return o}async*streamEvents(t,n,r=!0,s,a){let i=!1;const o=Date.now();let c=!1,l=0,u=0,d="";a&&(t=this._enhanceQueryWithSchema(t,a));try{r&&!this._initialized?(await this.initialize(),i=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),i=!0);const h=this._agentExecutor;if(!h)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const p=typeof t=="string"&&t.length>50?`${t.slice(0,50).replace(/\n/g," ")}...`:typeof t=="string"?t.replace(/\n/g," "):String(t);E.info(`💬 Received query for streamEvents: '${p}'`),this.memoryEnabled&&(E.info(`🔄 Adding user message to history: ${p}`),this.addToHistory(new he({content:t})));const f=s??this.conversationHistory,g=[];for(const w of f)this._isHumanMessageLike(w)||this._isAIMessageLike(w)||this._isToolMessageLike(w)?g.push(w):E.info(`⚠️ Skipped message of type: ${w.constructor?.name||typeof w}`);const b=[...g,new he(t)];E.info("callbacks",this.callbacks);const S=h.streamEvents({messages:b},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const w of S)if(l++,!(!w||typeof w!="object")){if(w.event==="on_chat_model_stream"&&w.data?.chunk?.content&&(u+=w.data.chunk.content.length),w.event==="on_chat_model_stream"&&w.data?.chunk){const v=w.data.chunk;if(v.content){d||(d="");const T=this._normalizeOutput(v.content);d+=T,E.debug(`📝 Accumulated response length: ${d.length}`)}}if(yield w,w.event==="on_chain_end"&&w.data?.output&&!d){const v=w.data.output;Array.isArray(v)&&v.length>0&&v[0]?.text?d=v[0].text:typeof v=="string"?d=v:v&&typeof v=="object"&&"output"in v&&(d=v.output)}}if(a&&d){E.info("🔧 Attempting structured output conversion...");try{let w=!1,v=null,T=null;this._attemptStructuredOutput(d,this.llm,a).then(O=>(w=!0,v=O,O)).catch(O=>{throw w=!0,T=O,O});let k=0;for(;!w;)await new Promise(O=>setTimeout(O,2e3)),w||(k++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${k*2}s)`,elapsed:k*2}});if(T)throw T;v&&(yield{event:"on_structured_output",data:{output:v}},this.memoryEnabled&&this.addToHistory(new D(`Structured result: ${JSON.stringify(v)}`)),E.info("✅ Structured output successful"))}catch(w){E.warn(`⚠️ Structured output failed: ${w}`),yield{event:"on_structured_output_error",data:{error:w instanceof Error?w.message:String(w)}}}}else this.memoryEnabled&&d&&this.addToHistory(new D(d));console.log(`
532
-
533
- `),E.info(`🎉 StreamEvents complete - ${l} events emitted`),c=!0}catch(h){throw E.error(`❌ Error during streamEvents: ${h}`),i&&r&&(E.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),h}finally{const h=Date.now()-o;let p=0;this.client?p=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(p=this.connectors.length);const f=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:t,success:c,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:p,serverIdentifiers:this.connectors.map(g=>g.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(g=>g.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,response:`[STREAMED RESPONSE - ${u} chars]`,executionTimeMs:h,errorType:c?null:"streaming_error",conversationHistoryLength:f}),r&&!this.client&&i&&(E.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(t,n,r){E.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),E.info(`🔄 Raw result: ${JSON.stringify(t,null,2)}`);let s=null,a="";if(E.debug(`🔄 Structured output requested, schema: ${JSON.stringify(ba(r),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")s=n.withStructuredOutput(r);else if(n)s=n;else throw new Error("LLM is required for structured output");const i=ba(r),{$schema:o,additionalProperties:c,...l}=i;a=JSON.stringify(l,null,2),E.info(`🔄 Schema description: ${a}`);let u="";typeof t=="string"?u=t:t&&typeof t=="object"&&(u=JSON.stringify(t)),E.info("rawResult",t),u||(u=JSON.stringify(t));const d=3;let h="";for(let p=1;p<=d;p++){E.info(`🔄 Structured output attempt ${p}/${d}`);let f=`
534
- Please format the following information according to the EXACT schema specified below.
535
- You must use the exact field names and types as shown in the schema.
536
-
537
- Required schema format:
538
- ${a}
539
-
540
- Content to extract from:
541
- ${u}
542
-
543
- IMPORTANT:
544
- - Use ONLY the field names specified in the schema
545
- - Match the data types exactly (string, number, boolean, array, etc.)
546
- - Include ALL required fields
547
- - Return valid JSON that matches the schema structure exactly
548
- - For missing data: use null for nullable fields, omit optional fields entirely
549
- - Do NOT use empty strings ("") or zero (0) as placeholders for missing data
550
- `;p>1&&(f+=`
551
-
552
- PREVIOUS ATTEMPT FAILED with error: ${h}
553
- Please fix the issues mentioned above and ensure the output matches the schema exactly.
554
- `);try{E.info(`🔄 Structured output attempt ${p} - using streaming approach`);const g=u.length>300?`${u.slice(0,300)}...`:u;E.info(`🔄 Content being formatted (${u.length} chars): ${g}`),E.info(`🔄 Full format prompt (${f.length} chars):
555
- ${f}`);const b=await s.stream(f);let S=null,w=0;for await(const T of b){if(w++,E.info(`Chunk ${w}: ${JSON.stringify(T,null,2)}`),typeof T=="string")try{S=JSON.parse(T)}catch{E.warn(`🔄 Failed to parse string chunk as JSON: ${T}`)}else if(T&&typeof T=="object")S=T;else try{S=JSON.parse(String(T))}catch{E.warn(`🔄 Failed to parse chunk as JSON: ${T}`)}w%10===0&&E.info(`🔄 Structured output streaming: ${w} chunks`)}if(E.info(`🔄 Structured result attempt ${p}: ${JSON.stringify(S,null,2)}`),!S)throw new Error("No structured result received from stream");const v=this._validateStructuredResult(S,r);return E.info(`✅ Structured output successful on attempt ${p}`),v}catch(g){if(h=g instanceof Error?g.message:String(g),E.warn(`⚠️ Structured output attempt ${p} failed: ${h}`),p===d)throw E.error(`❌ All ${d} structured output attempts failed`),new Error(`Failed to generate valid structured output after ${d} attempts. Last error: ${h}`);continue}}throw new Error("Unexpected error in structured output generation")}_validateStructuredResult(t,n){try{const r=n.parse(t),s=n;if(s._def&&s._def.shape)for(const[a,i]of Object.entries(s._def.shape)){const o=i,c=o.isOptional?.()??o._def?.typeName==="ZodOptional",l=o.isNullable?.()??o._def?.typeName==="ZodNullable";if(!c&&!l){const u=r[a];if(u==null||typeof u=="string"&&!u.trim()||Array.isArray(u)&&u.length===0)throw new Error(`Required field '${a}' is missing or empty`)}}return r}catch(r){throw E.debug(`Validation details: ${r}`),r}}_enhanceQueryWithSchema(t,n){try{const r=ba(n),{$schema:s,additionalProperties:a,...i}=r,o=JSON.stringify(i,null,2);return`
556
- ${t}
557
-
558
- IMPORTANT: Your response must include sufficient information to populate the following structured output:
559
-
560
- ${o}
561
-
562
- Make sure you gather ALL the required information during your task execution.
563
- If any required information is missing, continue working to find it.
564
- `}catch(r){return E.warn(`Could not extract schema details: ${r}`),t}}},G(Fr,"MCPAgent"),Fr),Re={},zP=Re.MCP_USE_LANGFUSE?.toLowerCase()==="false",Ws={handler:null,client:null,initPromise:null};async function au(e,t,n,r){try{const s=await Ts(()=>import("./index-6zrNEwtM.js"),__vite__mapDeps([3,4,1,2,5,6,7,8])).catch(()=>null);if(!s){E.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,g,b){super(h),this.agentId=p,this.metadata=f,this.metadataProvider=g,this.tagsProvider=b,this.verbose=h?.verbose??!1}async handleChainStart(h,p,f,g,b,S,w,v){E.debug("Langfuse: Chain start intercepted");const T=this.getCustomTags(),k=this.getMetadata(),O=[...b||[],...T],C={...S||{},...k};return this.verbose&&(E.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(O)}`),E.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(C)}`)),super.handleChainStart(h,p,f,g,O,C,w,v)}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=Re.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 E.debug("Langfuse: LLM start intercepted"),this.verbose&&E.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return E.debug("Langfuse: Tool start intercepted"),this.verbose&&E.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return E.debug("Langfuse: Retriever start intercepted"),this.verbose&&E.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return E.debug("Langfuse: Agent action intercepted"),this.verbose&&E.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return E.debug("Langfuse: Agent end intercepted"),this.verbose&&E.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:Re.LANGFUSE_PUBLIC_KEY,secretKey:Re.LANGFUSE_SECRET_KEY,baseUrl:Re.LANGFUSE_HOST||Re.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Re.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Re.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Re.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Re.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Re.LANGFUSE_ENABLED!=="false",traceName:o.trace_name||Re.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};E.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Ws.handler=new i(l,e,t,n,r),E.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await Ts(()=>import("./index-DmIKR5St.js"),__vite__mapDeps([4,1,2,5,6,7,8])).catch(()=>null);if(d){const{Langfuse:h}=d;Ws.client=new h({publicKey:Re.LANGFUSE_PUBLIC_KEY,secretKey:Re.LANGFUSE_SECRET_KEY,baseUrl:Re.LANGFUSE_HOST||"https://cloud.langfuse.com"}),E.debug("Langfuse client initialized")}}catch(d){E.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){E.debug(`Langfuse initialization error: ${s}`)}}G(au,"initializeLangfuse");zP?E.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Re.LANGFUSE_PUBLIC_KEY||!Re.LANGFUSE_SECRET_KEY?E.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Ws.initPromise=au();var HP=G(()=>Ws.handler,"langfuseHandler"),VP=G(()=>Ws.initPromise,"langfuseInitPromise");const nN=Object.freeze(Object.defineProperty({__proto__:null,BaseAdapter:iy,BaseConnector:Sy,BrowserOAuthClientProvider:Ty,HttpConnector:Ey,LangChainAdapter:Dn,Logger:Cy,MCPAgent:BP,MCPClient:Ay,MCPSession:ky,ObservabilityManager:Uc,RemoteAgent:dy,WebSocketConnector:Oy,createReadableStreamFromGenerator:uh,logger:E,onMcpAuthorization:xy,streamEventsToAISDK:lh,streamEventsToAISDKWithTools:dh},Symbol.toStringTag,{value:"Module"})),rh=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:au,langfuseHandler:HP,langfuseInitPromise:VP},Symbol.toStringTag,{value:"Module"}));export{D as A,es as B,Xn as C,vi as F,he as H,Se as S,X as T,rt as a,yt as b,nN as c,lt as m};