@mcp-use/inspector 0.4.13 → 0.5.0-canary.1

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 (35) hide show
  1. package/dist/cli.js +1 -5
  2. package/dist/client/assets/{chunk-VL2OQCWN-C61KfPSl.js → chunk-VL2OQCWN-MBqdQwvw.js} +1 -1
  3. package/dist/client/assets/{embeddings-BIo-kwlO.js → embeddings-B5Be4aCe.js} +1 -1
  4. package/dist/client/assets/index-B_wEtYs8.js +40 -0
  5. package/dist/client/assets/index-Bn0J9w6n.js +1438 -0
  6. package/dist/client/assets/{index-dXj4eNzX.js → index-BrE2Q7Md.js} +1 -1
  7. package/dist/client/assets/index-Bx3FWJNp.css +1 -0
  8. package/dist/client/assets/{index-jQGzGE29.js → index-CiA4rdQm.js} +9 -13
  9. package/dist/client/assets/index-CjCfkF26.js +2 -0
  10. package/dist/client/assets/{index-D1RB_-JK.js → index-DyE3WIut.js} +1 -1
  11. package/dist/client/assets/{index-Cva-hqGs.js → index-poirZU-_.js} +1 -1
  12. package/dist/client/assets/langfuse-C4HKZ3NL-DD548jIo.js +562 -0
  13. package/dist/client/assets/{winston-B9dQmIAy.js → winston-vzZ2qSTo.js} +29 -34
  14. package/dist/client/index.html +3 -3
  15. package/dist/server/{chunk-TIYOH5C4.js → chunk-37X7HLUV.js} +1 -5
  16. package/dist/server/{chunk-ZFMPIRVB.js → chunk-5OMSQNKB.js} +1 -1
  17. package/dist/server/{chunk-YGCKPAWJ.js → chunk-UZO6G7KA.js} +3 -3
  18. package/dist/server/{chunk-76XNP4ZB.js → chunk-VOQ3DLXM.js} +1 -5
  19. package/dist/server/{chunk-222XA5JA.js → chunk-WYBXXYSP.js} +1 -1
  20. package/dist/server/cli.js +4 -4
  21. package/dist/server/index.js +5 -5
  22. package/dist/server/middleware.js +5 -5
  23. package/dist/server/server.js +4 -4
  24. package/dist/server/shared-routes.js +2 -2
  25. package/dist/server/shared-static.js +2 -2
  26. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  27. package/dist/server/shared-utils-browser.js +1 -1
  28. package/dist/server/shared-utils.d.ts.map +1 -1
  29. package/dist/server/shared-utils.js +1 -1
  30. package/package.json +2 -2
  31. package/dist/client/assets/index-BLLgp4UX.js +0 -1734
  32. package/dist/client/assets/index-BrUPorMz.css +0 -1
  33. package/dist/client/assets/index-g0U2Uz9F.js +0 -40
  34. package/dist/client/assets/index-gQstsvsJ.js +0 -212
  35. package/dist/client/assets/langfuse-C4HKZ3NL-ComM_afA.js +0 -570
@@ -1,570 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Cva-hqGs.js","assets/index-dXj4eNzX.js","assets/index-BLLgp4UX.js","assets/index-BrUPorMz.css","assets/chunk-VL2OQCWN-C61KfPSl.js","assets/index-DRz5BQNA.js","assets/__vite-browser-external-DFygW7-s.js","assets/path-C9FudP8b.js"])))=>i.map(i=>d[i]);
2
- var hy=Object.defineProperty;var py=(e,t,n)=>t in e?hy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var su=(e,t,n)=>py(e,typeof t!="symbol"?t+"":t,n);import{_ as G,c as ji,u as en,a as ht,d as Rc,n as St,s as Oe,e as Pn,o as te,f as fy,Z as R,h as Ht,i as au,l as Io,j as my,k as Yd,p as Xd,m as Fr,r as $c,q as Qd,t as T,v as gy,w as $a,B as yy,x as _y,H as wy,L as vy,y as by,M as Sy,W as Ty,z as Ey}from"./index-BLLgp4UX.js";import{u as Cy,w as Lc,x as Ay,y as Be,z as ky,A as Oy,B as xy,C as Iy,D as Py,E as Ny,F as My,G as Ry,H as $y,I as Ly,d as An,J as jy,g as Re,K as Dy,L as eh,M as Uy,N as Fy,O as La,h as jc,Q as By,R as zy,S as Hy,U as Vy,W as Gy,X as Wy,Y as Jy,Z as Ky,a0 as Zy,a1 as qy,a2 as Yy,a3 as iu,a4 as Xy,a5 as Qy,a6 as e_,a7 as t_,s as n_,v as Ce,P as tn,p as ja,a as ws,b as th,c as nh,i as Dc,j as r_,f as s_,_ as a_,$ as i_,e as o_,k as c_,t as ou,l as rh,V as Uc,m as l_,n as br,o as u_,T as d_,q as h_,r as p_,a8 as f_}from"./chunk-VL2OQCWN-C61KfPSl.js";import{o as Po}from"./__vite-browser-external-DFygW7-s.js";import{j as Da,d as cu,i as m_}from"./path-C9FudP8b.js";var Di,ra,Ui=0,Fi=0;function g_(e,t,n){var r=0,s=t||new Array(16);e=e||{};var a=e.node,i=e.clockseq;if(e._v6||(a||(a=Di),i==null&&(i=ra)),a==null||i==null){var o=e.random||(e.rng||Cy)();a==null&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],!Di&&!e._v6&&(a[0]|=1,Di=a)),i==null&&(i=(o[6]<<8|o[7])&16383,ra===void 0&&!e._v6&&(ra=i))}var c=e.msecs!==void 0?e.msecs:Date.now(),l=e.nsecs!==void 0?e.nsecs:Fi+1,u=c-Ui+(l-Fi)/1e4;if(u<0&&e.clockseq===void 0&&(i=i+1&16383),(u<0||c>Ui)&&e.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ui=c,Fi=l,ra=i,c+=122192928e5;var d=((c&268435455)*1e4+l)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=d&255;var h=c/4294967296*1e4&268435455;s[r++]=h>>>8&255,s[r++]=h&255,s[r++]=h>>>24&15|16,s[r++]=h>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var p=0;p<6;++p)s[r+p]=a[p];return t||Lc(s)}function y_(e){var t=typeof e=="string"?Ay(e):e,n=__(t);return typeof e=="string"?Lc(n):n}function __(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function lu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function uu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?lu(Object(n),!0).forEach(function(r){w_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lu(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function w_(e,t,n){return(t=v_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function v_(e){var t=b_(e,"string");return typeof t=="symbol"?t:t+""}function b_(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function S_(e={},t,n=0){var r=g_(uu(uu({},e),{},{_v6:!0}),new Uint8Array(16));return r=y_(r),Lc(r)}const T_=(e,t)=>{ky.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>xy(e,n)},flatten:{value:n=>Oy(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},li=Be("ZodError",T_,{Parent:Error}),E_=Iy(li),C_=Ny(li),A_=Py(li),k_=My(li),ct=Be("ZodType",(e,t)=>(Ly.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>An(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>E_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>A_(e,n,r),e.parseAsync=async(n,r)=>C_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>k_(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(X_(n,r)),e.superRefine=n=>e.check(Q_(n)),e.overwrite=n=>e.check(jy(n)),e.optional=()=>du(e),e.nullable=()=>hu(e),e.nullish=()=>du(hu(e)),e.nonoptional=n=>V_(e,n),e.array=()=>I_(e),e.or=n=>N_([e,n]),e.and=n=>R_(e,n),e.transform=n=>pu(e,L_(n)),e.default=n=>F_(e,n),e.prefault=n=>z_(e,n),e.catch=n=>W_(e,n),e.pipe=n=>pu(e,n),e.readonly=()=>Z_(e),e.describe=n=>{const r=e.clone();return Re.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return Re.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Re.get(e);const r=e.clone();return Re.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),O_=Be("ZodAny",(e,t)=>{$y.init(e,t),ct.init(e,t)});function sa(){return Ry(O_)}const x_=Be("ZodArray",(e,t)=>{Yy.init(e,t),ct.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(iu(n,r)),e.nonempty=n=>e.check(iu(1,n)),e.max=(n,r)=>e.check(Xy(n,r)),e.length=(n,r)=>e.check(Qy(n,r)),e.unwrap=()=>e.element});function I_(e,t){return Uy(x_,e,t)}const P_=Be("ZodUnion",(e,t)=>{Hy.init(e,t),ct.init(e,t),e.options=t.options});function N_(e,t){return new P_({type:"union",options:e,...eh(t)})}const M_=Be("ZodIntersection",(e,t)=>{Vy.init(e,t),ct.init(e,t)});function R_(e,t){return new M_({type:"intersection",left:e,right:t})}const $_=Be("ZodTransform",(e,t)=>{Wy.init(e,t),ct.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(La(a,n.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),n.issues.push(La(i))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function L_(e){return new $_({type:"transform",transform:e})}const j_=Be("ZodOptional",(e,t)=>{jc.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function du(e){return new j_({type:"optional",innerType:e})}const D_=Be("ZodNullable",(e,t)=>{By.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function hu(e){return new D_({type:"nullable",innerType:e})}const U_=Be("ZodDefault",(e,t)=>{Jy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F_(e,t){return new U_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const B_=Be("ZodPrefault",(e,t)=>{Ky.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function z_(e,t){return new B_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const H_=Be("ZodNonOptional",(e,t)=>{zy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType});function V_(e,t){return new H_({type:"nonoptional",innerType:e,...eh(t)})}const G_=Be("ZodCatch",(e,t)=>{Zy.init(e,t),ct.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function W_(e,t){return new G_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const J_=Be("ZodPipe",(e,t)=>{Gy.init(e,t),ct.init(e,t),e.in=t.in,e.out=t.out});function pu(e,t){return new J_({type:"pipe",in:e,out:t})}const K_=Be("ZodReadonly",(e,t)=>{qy.init(e,t),ct.init(e,t)});function Z_(e){return new K_({type:"readonly",innerType:e})}const q_=Be("ZodCustom",(e,t)=>{e_.init(e,t),ct.init(e,t)});function Y_(e){const t=new Fy({check:"custom"});return t._zod.check=e,t}function X_(e,t={}){return Dy(q_,e,t)}function Q_(e){const t=Y_(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(La(r,n.value,t._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),n.issues.push(La(s))}},e(n.value,n)));return t}async function*sh(e){for await(const t of e)if(t.event==="on_chat_model_stream"&&t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}G(sh,"streamEventsToAISDK");function ah(e){return new ReadableStream({async start(t){try{for await(const n of e)t.enqueue(n);t.close()}catch(n){t.error(n)}}})}G(ah,"createReadableStreamFromGenerator");async function*ih(e){for await(const t of e)switch(t.event){case"on_chat_model_stream":if(t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
3
- 🔧 Using tool: ${t.name}
4
- `;break;case"on_tool_end":yield`
5
- ✅ Tool completed: ${t.name}
6
- `;break}}G(ih,"streamEventsToAISDKWithTools");class ew{static convert(t){return this.parseSchema(t)}static matchesCondition(t,n){if(!n.properties)return!0;if(typeof t!="object"||t===null||Array.isArray(t))return!1;const r=t;for(const[s,a]of Object.entries(n.properties)){if(!(s in r)){if("const"in a)return!1;continue}const i=r[s];if("const"in a&&i!==a.const||"minimum"in a&&typeof i=="number"&&i<a.minimum||"maximum"in a&&typeof i=="number"&&i>a.maximum)return!1}return!0}static validateConditionalSchema(t,n,r){this.validateRequiredProperties(t,n,r),this.validatePropertyPatterns(t,n,r),this.validateNestedConditions(t,n,r)}static validateRequiredProperties(t,n,r){if(n.required){if(typeof t!="object"||t===null){for(const s of n.required)r.addIssue({code:ji.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in t||r.addIssue({code:ji.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(t,n,r){if(!n.properties||typeof t!="object"||t===null||Array.isArray(t))return;const s=t;for(const[a,i]of Object.entries(n.properties)){if(!(a in s))continue;const o=s[a];i.pattern&&typeof o=="string"&&(new RegExp(i.pattern).test(o)||r.addIssue({code:ji.custom,message:`String '${o}' does not match pattern '${i.pattern}'`,path:[a]}))}}static validateNestedConditions(t,n,r){if(!n.if||!n.then)return;this.matchesCondition(t,n.if)?this.validateConditionalSchema(t,n.then,r):n.else&&this.validateConditionalSchema(t,n.else,r)}static parseSchema(t){return Array.isArray(t.type)?this.handleTypeArray(t):t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.if&&t.then?this.parseObject(t):t.properties&&(!t.type||t.type==="object")?this.parseObject(t):this.handleSingleType(t)}static handleTypeArray(t){if(!Array.isArray(t.type))throw new Error("Expected schema.type to be an array");return t.type.includes("null")?this.handleNullableType(t):this.createUnionFromTypes(t.type,t)}static handleNullableType(t){if(!Array.isArray(t.type))throw new Error("Expected schema.type to be an array");const n={...t};return n.type=t.type.filter(s=>s!=="null"),n.type.length===1?this.handleSingleType({...t,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(t,n){const r=t.map(s=>{const a={...n,type:s};return this.parseSchema(a)});return en(r)}static handleSingleType(t){if(t.type===void 0)return t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.properties?this.parseObject(t):ht();switch(t.type){case"string":return this.parseString(t);case"number":case"integer":return this.parseNumberSchema(t);case"boolean":return Rc();case"array":return this.parseArray(t);case"object":return this.parseObject(t);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(t){let n=St(),r=n;return r=this.applyNumberBounds(n,t),r=this.applyNumberMultipleOf(n,t),r=this.applyNumberEnum(n,t),r=this.applyIntegerConstraint(n,t),r}static applyNumberBounds(t,n){let r=t;return n.minimum!==void 0&&(r=n.exclusiveMinimum?r.gt(n.minimum):r.gte(n.minimum)),n.maximum!==void 0&&(r=n.exclusiveMaximum?r.lt(n.maximum):r.lte(n.maximum)),r}static applyNumberMultipleOf(t,n){return n.multipleOf===void 0?t:t.refine(r=>r%n.multipleOf===0,{message:`Number must be a multiple of ${n.multipleOf}`})}static applyNumberEnum(t,n){if(!n.enum)return t;const r=n.enum.filter(s=>typeof s=="number");return r.length===0?t:t.refine(s=>r.includes(s),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(t,n){return n.type!=="integer"?t:t.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(t){let n=Oe(),r=n;return t.format?this.applyStringFormat(n,t):(r=this.applyStringPattern(n,t),r=this.applyStringLength(n,t),r=this.applyStringEnum(n,t),r)}static applyStringFormat(t,n){if(!n.format)return t;switch(n.format){case"email":return t.email();case"date-time":return t.datetime();case"uri":return t.url();case"uuid":return t.uuid();case"date":return t.date();default:return t}}static applyStringPattern(t,n){if(!n.pattern)return t;const r=new RegExp(n.pattern);return t.regex(r,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(t,n){let r=t;return n.minLength!==void 0&&(t=t.min(n.minLength)),n.maxLength!==void 0&&(t=t.max(n.maxLength)),r}static applyStringEnum(t,n){return n.enum?t.refine(r=>n.enum?.includes(r),{message:`Value must be one of: ${n.enum?.join(", ")}`}):t}static parseArray(t){if(Array.isArray(t.items)){const a=t.items.map(i=>this.parseSchema(i));return en(a)}const n=t.items?this.parseSchema(t.items):ht();let r=Pn(n),s=r;return s=this.applyArrayConstraints(r,t),s}static applyArrayConstraints(t,n){return n.minItems!==void 0&&(t=t.min(n.minItems)),n.maxItems!==void 0&&(t=t.max(n.maxItems)),n.uniqueItems?t.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):t}static parseObject(t){if(t.if&&t.then)return this.parseConditional(t);const n={};return this.processObjectProperties(t,n),this.processAdditionalProperties(t,te(n))}static processObjectProperties(t,n){const r=new Set(t.required||[]);if(t.properties)for(const[s,a]of Object.entries(t.properties)){const i=this.parseSchema(a);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(t,n){if(t.additionalProperties===!0)return n.passthrough();if(t.additionalProperties&&typeof t.additionalProperties=="object"){const r=this.parseSchema(t.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(t){const n=this.createBaseObjectSchema(t),r=t.if,s=t.then,a=t.else;return n.superRefine((i,o)=>{const c=this.applyDefaultValues(i,t);this.matchesCondition(c,r)?this.validateConditionalSchema(c,s,o):a&&this.validateConditionalSchema(c,a,o)})}static createBaseObjectSchema(t){const n={},r=new Set(t.required||[]);for(const[a,i]of Object.entries(t.properties||{})){const o=this.parseSchema(i);n[a]=r.has(a)?o:o.optional()}const s=te(n);return this.processAdditionalProperties(t,s)}static applyDefaultValues(t,n){if(typeof t!="object"||t===null||Array.isArray(t))return t;const s={...t};if(!n.properties)return s;for(const[a,i]of Object.entries(n.properties))!(a in s)&&"default"in i&&(s[a]=i.default);return s}static parseCombinator(t){if(t.oneOf)return this.parseOneOf(t.oneOf);if(t.anyOf)return this.parseAnyOf(t.anyOf);if(t.allOf)return this.parseAllOf(t.allOf);throw new Error("Unsupported schema type")}static parseOneOf(t){return this.createUnionFromSchemas(t)}static parseAnyOf(t){return this.createUnionFromSchemas(t)}static createUnionFromSchemas(t){if(t.length===0)return ht();if(t.length===1)return this.parseSchema(t[0]);const n=[];for(const r of t)r.type==="null"?n.push(fy()):n.push(this.parseSchema(r));return n.length>=2?en(n):n.length===1?n[0]:ht()}static parseAllOf(t){if(t.length===0)return ht();if(t.length===1)return this.parseSchema(t[0]);const n=t.reduce((r,s)=>this.mergeSchemas(r,s));return this.parseSchema(n)}static mergeSchemas(t,n){const r={...t,...n};if(t.properties&&n.properties){const s={...t.properties,...n.properties};r.properties=s}if(t.required&&n.required){const s=[...new Set([...t.required,...n.required])];r.required=s}return r}}var tw=Object.defineProperty,F=(e,t)=>{for(var n in t)tw(e,n,{get:t[n],enumerable:!0})};function nw(e,t){return t?.[e]||n_(e)}function rw(e,t){return t?.[e]||t_(e)}function oh(e,t,n){const r={};for(const s in e)Object.hasOwn(e,s)&&(r[t(s,n)]=e[s]);return r}var ch={};F(ch,{Serializable:()=>Tt,get_lc_unique_name:()=>ui});function fu(e){return Array.isArray(e)?[...e]:{...e}}function sw(e,t){const n=fu(e);for(const[r,s]of Object.entries(t)){const[a,...i]=r.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=fu(o[c]),o=o[c]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return n}function ui(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var Tt=class lh{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ui(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([r])=>this.lc_serializable_keys?.includes(r))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof lh||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},r=Object.keys(this.lc_kwargs).reduce((s,a)=>(s[a]=a in this?this[a]:this.lc_kwargs[a],s),{});for(let s=Object.getPrototypeOf(this);s;s=Object.getPrototypeOf(s))Object.assign(t,Reflect.get(s,"lc_aliases",this)),Object.assign(n,Reflect.get(s,"lc_secrets",this)),Object.assign(r,Reflect.get(s,"lc_attributes",this));return Object.keys(n).forEach(s=>{let a=this,i=r;const[o,...c]=s.split(".").reverse();for(const l of c.reverse()){if(!(l in a)||a[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof a[l]=="object"&&a[l]!=null?i[l]={}:Array.isArray(a[l])&&(i[l]=[])),a=a[l],i=i[l]}o in a&&a[o]!==void 0&&(i[o]=i[o]||a[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:oh(Object.keys(n).length?sw(r,n):r,nw,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function kn(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function Fc(e){return kn(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function Bc(e){return kn(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function aw(e){return kn(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function uh(e){return kn(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function dh(e){if(kn(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function iw(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),r=t[1].trim();if(n===""||r==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const s={};for(const a of e.split(";").slice(1)){const i=a.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);s[o]=c}return{type:n,subtype:r,parameters:s}}function No({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(n){r=n[1].toLowerCase();const s=t?Uint8Array.from(atob(n[2]),a=>a.charCodeAt(0)):n[2];return{mime_type:r,data:s}}}function ow(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function U(e,t){return H(e)&&e.type===t}function H(e){return typeof e=="object"&&e!==null}function Vt(e){return Array.isArray(e)}function $(e){return typeof e=="string"}function Pt(e){return typeof e=="number"}function zc(e){return e instanceof Uint8Array}function mu(e){try{return JSON.parse(e)}catch{return}}const vs=e=>e();function cw(e){if(e.type==="char_location"&&$(e.document_title)&&Pt(e.start_char_index)&&Pt(e.end_char_index)&&$(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="page_location"&&$(e.document_title)&&Pt(e.start_page_number)&&Pt(e.end_page_number)&&$(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="content_block_location"&&$(e.document_title)&&Pt(e.start_block_index)&&Pt(e.end_block_index)&&$(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:r,citedText:s}}if(e.type==="web_search_result_location"&&$(e.url)&&$(e.title)&&$(e.encrypted_index)&&$(e.cited_text)){const{url:t,title:n,encrypted_index:r,cited_text:s,...a}=e;return{...a,type:"citation",source:"url",url:t,title:n,startIndex:Number(r),endIndex:Number(r),citedText:s}}if(e.type==="search_result_location"&&$(e.source)&&$(e.title)&&Pt(e.start_block_index)&&Pt(e.end_block_index)&&$(e.cited_text)){const{source:t,title:n,start_block_index:r,end_block_index:s,cited_text:a,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:r,endIndex:s,citedText:a}}}function hh(e){if(U(e,"document")&&H(e.source)&&"type"in e.source){if(e.source.type==="base64"&&$(e.source.media_type)&&$(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&$(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&$(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&$(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(U(e,"image")&&H(e.source)&&"type"in e.source){if(e.source.type==="base64"&&$(e.source.media_type)&&$(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&$(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&$(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function lw(e){function*t(){for(const n of e){const r=hh(n);r?yield r:yield n}}return Array.from(t())}function gu(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n){if(U(r,"text")&&$(r.text)){const{text:s,citations:a,...i}=r;if(Vt(a)&&a.length){const o=a.reduce((c,l)=>{const u=cw(l);return u?[...c,u]:c},[]);yield{...i,type:"text",text:s,annotations:o};continue}else{yield{...i,type:"text",text:s};continue}}else if(U(r,"thinking")&&$(r.thinking)){const{thinking:s,signature:a,...i}=r;yield{...i,type:"reasoning",reasoning:s,signature:a};continue}else if(U(r,"redacted_thinking")){yield{type:"non_standard",value:r};continue}else if(U(r,"tool_use")&&$(r.name)&&$(r.id)){yield{type:"tool_call",id:r.id,name:r.name,args:r.input};continue}else if(U(r,"input_json_delta")){if(dw(e)&&e.tool_call_chunks?.length){const s=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:s.id,name:s.name,args:s.args,index:s.index};continue}}else if(U(r,"server_tool_use")&&$(r.name)&&$(r.id)){const{name:s,id:a}=r;if(s==="web_search"){const i=vs(()=>{if(typeof r.input=="string")return r.input;if(H(r.input)&&$(r.input.query))return r.input.query;if($(r.partial_json)){const o=mu(r.partial_json);if(o?.query)return o.query}return""});yield{id:a,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(r.name==="code_execution"){const i=vs(()=>{if(typeof r.input=="string")return r.input;if(H(r.input)&&$(r.input.code))return r.input.code;if($(r.partial_json)){const o=mu(r.partial_json);if(o?.code)return o.code}return""});yield{id:a,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(U(r,"web_search_tool_result")&&$(r.tool_use_id)&&Vt(r.content)){const{content:s,tool_use_id:a}=r,i=s.reduce((o,c)=>U(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:a,status:"success",output:{urls:i}};continue}else if(U(r,"code_execution_tool_result")&&$(r.tool_use_id)&&H(r.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(U(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}else if(U(r,"mcp_tool_result")&&$(r.tool_use_id)&&H(r.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(U(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}else if(U(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}else if(U(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}else{const s=hh(r);if(s){yield s;continue}}yield{type:"non_standard",value:r}}}return Array.from(t())}const uw={translateContent:gu,translateContentChunk:gu};function dw(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function hw(e){return Fc(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:Bc(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:uh(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function pw(e){return e.map(hw)}function fw(e){return!!(U(e,"image_url")&&H(e.image_url)||U(e,"input_audio")&&H(e.input_audio)||U(e,"file")&&H(e.file))}function mw(e){if(U(e,"image_url")&&H(e.image_url)&&$(e.image_url.url)){const t=No({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(U(e,"input_audio")&&H(e.input_audio)&&$(e.input_audio.data)&&$(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(U(e,"file")&&H(e.file)&&$(e.file.data)){const t=No({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if($(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function gw(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...Hc(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function yw(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...Hc(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function Hc(e){const t=[];for(const n of e)fw(n)?t.push(mw(n)):t.push(n);return t}function _w(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:r,end_index:s}=e;return{type:"citation",url:t,title:n,startIndex:r,endIndex:s}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:r}=e;return{type:"citation",title:n,startIndex:r,endIndex:r,fileId:t}}return e}function ph(e){function*t(){H(e.additional_kwargs?.reasoning)&&Vt(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((s,a)=>H(a)&&$(a.text)?`${s}${a.text}`:s,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n)if(U(r,"text")){const{text:s,annotations:a,...i}=r;Array.isArray(a)?yield{...i,type:"text",text:String(s),annotations:a.map(_w)}:yield{...i,type:"text",text:String(s)}}for(const r of e.tool_calls??[])yield{type:"tool_call",id:r.id,name:r.name,args:r.args};if(H(e.additional_kwargs)&&Vt(e.additional_kwargs.tool_outputs))for(const r of e.additional_kwargs.tool_outputs){if(U(r,"web_search_call")){yield{id:r.id,type:"server_tool_call",name:"web_search",args:{query:r.query}};continue}else if(U(r,"file_search_call")){yield{id:r.id,type:"server_tool_call",name:"file_search",args:{query:r.query}};continue}else if(U(r,"computer_call")){yield{type:"non_standard",value:r};continue}else if(U(r,"code_interpreter_call")){if($(r.code)&&(yield{id:r.id,type:"server_tool_call",name:"code_interpreter",args:{code:r.code}}),Vt(r.outputs)){const s=vs(()=>{if(r.status!=="in_progress"){if(r.status==="completed")return 0;if(r.status==="incomplete")return 127;if(r.status!=="interpreting"&&r.status==="failed")return 1}});for(const a of r.outputs)if(U(a,"logs")){yield{type:"server_tool_call_result",toolCallId:r.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:s??0,stderr:[0,void 0].includes(s)?void 0:String(a.logs),stdout:[0,void 0].includes(s)?String(a.logs):void 0}};continue}}continue}else if(U(r,"mcp_call")){yield{id:r.id,type:"server_tool_call",name:"mcp_call",args:r.input};continue}else if(U(r,"mcp_list_tools")){yield{id:r.id,type:"server_tool_call",name:"mcp_list_tools",args:r.input};continue}else if(U(r,"mcp_approval_request")){yield{type:"non_standard",value:r};continue}else if(U(r,"image_generation_call")){yield{type:"non_standard",value:r};continue}H(r)&&(yield{type:"non_standard",value:r})}}return Array.from(t())}function ww(e){function*t(){yield*ph(e);for(const n of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(t())}const vw={translateContent:e=>typeof e.content=="string"?gw(e):ph(e),translateContentChunk:e=>typeof e.content=="string"?yw(e):ww(e)};function fh(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function bw(e,t="pretty"){return t==="pretty"?Sw(e):JSON.stringify(e)}function Sw(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),s="=".repeat(r),a=n.length%2===0?s:`${s}=`;if(t.push(`${s}${n}${a}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
7
- `)}const Bi=Symbol.for("langchain.message");function Xn(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.some(n=>kn(n))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?zs(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(n=>kn(n))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function mh(e,t){return e==="error"||t==="error"?"error":"success"}function Tw(e,t){function n(r,s){if(typeof r!="object"||r===null||r===void 0)return r;if(s>=t)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(i=>n(i,s+1));const a={};for(const i of Object.keys(r))a[i]=n(r[i],s+1);return a}return JSON.stringify(n(e,0),null,2)}var tt=class extends Tt{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Bi]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){const t=typeof e=="string"||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):t.content!==void 0?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){const e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[pw,Hc,lw].reduce((r,s)=>s(r),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&Bi in e&&e[Bi]===!0&&fh(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=Tw(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return bw(this,e)}};function Ew(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}function Ue(e={},t={}){const n={...e};for(const[r,s]of Object.entries(t))if(n[r]==null)n[r]=s;else{if(s==null)continue;if(typeof n[r]!=typeof s||Array.isArray(n[r])!==Array.isArray(s))throw new Error(`field[${r}] already exists in the message chunk, but with a different type.`);if(typeof n[r]=="string"){if(r==="type")continue;["id","name","output_version","model_provider"].includes(r)?n[r]=s:n[r]+=s}else if(typeof n[r]=="object"&&!Array.isArray(n[r]))n[r]=Ue(n[r],s);else if(Array.isArray(n[r]))n[r]=zs(n[r],s);else{if(n[r]===s)continue;console.warn(`field[${r}] already exists in this message chunk and value has unsupported type.`)}}return n}function zs(e,t){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)return e||t;{const n=[...e];for(const r of t)if(typeof r=="object"&&r!==null&&"index"in r&&typeof r.index=="number"){const s=n.findIndex(a=>{const i=typeof a=="object",o="index"in a&&a.index===r.index,c="id"in a&&"id"in r&&a?.id===r?.id,l=!("id"in a)||!a?.id||!("id"in r)||!r?.id;return i&&o&&(c||l)});s!==-1&&typeof n[s]=="object"&&n[s]!==null?n[s]=Ue(n[s],r):n.push(r)}else{if(typeof r=="object"&&r!==null&&"text"in r&&r.text==="")continue;n.push(r)}return n}}}function gh(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(!e||!t)return e||t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.
8
- 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 zs(e,t);if(typeof e=="object"&&typeof t=="object")return Ue(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.
10
- Left ${e}
11
- Right ${t}`)}var Nn=class extends tt{static isInstance(e){return super.isInstance(e)&&"concat"in e&&typeof e.concat=="function"}};function yh(e){return typeof e.role=="string"}function Ie(e){return typeof e?._getType=="function"}function bs(e){return Ie(e)&&typeof e.concat=="function"}var _h={};F(_h,{ToolMessage:()=>X,ToolMessageChunk:()=>Hs,defaultToolCallParser:()=>Gc,isDirectToolOutput:()=>Vc,isToolMessage:()=>Wc,isToolMessageChunk:()=>wh});function Vc(e){return e!=null&&typeof e=="object"&&"lc_direct_tool_output"in e&&e.lc_direct_tool_output===!0}var X=class extends tt{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}}},Hs=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:Xn(this.content,e.content),additional_kwargs:Ue(this.additional_kwargs,e.additional_kwargs),response_metadata:Ue(this.response_metadata,e.response_metadata),artifact:gh(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:mh(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function Gc(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 Wc(e){return typeof e=="object"&&e!==null&&"getType"in e&&typeof e.getType=="function"&&e.getType()==="tool"}function wh(e){return e._getType()==="tool"}function ps(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="tool_call")}function Cw(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 Ss=class extends Error{output;constructor(e,t){super(e),this.output=t}};function Mo(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 Jc(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 Aw(e){if(H(e.document)&&H(e.document.source)){const t=H(e.document)&&$(e.document.format)?e.document.format:"",n=Jc(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(zc(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 kw(e){if(U(e,"image")&&H(e.image)){const t=H(e.image)&&$(e.image.format)?e.image.format:"",n=Jc(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(zc(e.image.source.bytes))return{type:"image",mimeType:n,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}function Ow(e){if(U(e,"video")&&H(e.video)){const t=H(e.video)&&$(e.video.format)?e.video.format:"",n=Jc(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(zc(e.video.source.bytes))return{type:"video",mimeType:n,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}function yu(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n){if(U(r,"cache_point")){yield{type:"non_standard",value:r};continue}else if(U(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=vs(()=>{if(H(o.location)){const u=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(H(u))return{source:Pt(u.documentIndex)?u.documentIndex.toString():void 0,startIndex:Pt(u.start)?u.start:void 0,endIndex:Pt(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(U(r,"document")&&H(r.document)){yield Aw(r);continue}else if(U(r,"guard_content")){yield{type:"non_standard",value:r};continue}else if(U(r,"image")&&H(r.image)){yield kw(r);continue}else if(U(r,"reasoning_content")&&$(r.reasoningText)){yield{type:"reasoning",reasoning:r.reasoningText};continue}else if(U(r,"text")&&$(r.text)){yield{type:"text",text:r.text};continue}else if(U(r,"tool_result")){yield{type:"non_standard",value:r};continue}else{if(U(r,"tool_call"))continue;if(U(r,"video")&&H(r.video)){yield Ow(r);continue}}yield{type:"non_standard",value:r}}}return Array.from(t())}const xw={translateContent:yu,translateContentChunk:yu};function _u(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n){if(U(r,"text")&&$(r.text)){yield{type:"text",text:r.text};continue}else if(U(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(U(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(U(r,"functionResponse")){yield{type:"non_standard",value:r};continue}else if(U(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(U(r,"executableCode")){yield{type:"non_standard",value:r};continue}else if(U(r,"codeExecutionResult")){yield{type:"non_standard",value:r};continue}yield{type:"non_standard",value:r}}}return Array.from(t())}const Iw={translateContent:_u,translateContentChunk:_u};function wu(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const r of n){if(U(r,"reasoning")&&$(r.reasoning)){const s=vs(()=>{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(U(r,"text")&&$(r.text)){yield{type:"text",text:r.text};continue}else if(U(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(U(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 Pw={translateContent:wu,translateContentChunk:wu};globalThis.lc_block_translators_registry??=new Map([["anthropic",uw],["bedrock-converse",xw],["google-genai",Iw],["google-vertexai",Pw],["openai",vw]]);function vh(e){return globalThis.lc_block_translators_registry.get(e)}function bh(e,t){return Ue(e??{},t??{})}function Sh(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 Nw(e,t){const n={...Sh(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 Mw(e,t){const n={...Sh(e,t)};return(e?.reasoning!==void 0||t?.reasoning!==void 0)&&(n.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),n}function Th(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:Nw(e?.input_token_details,t?.input_token_details),output_token_details:Mw(e?.output_token_details,t?.output_token_details)}}var D=class extends tt{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]=Gc(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=vh(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 Kc(e){return e._getType()==="ai"}function Ro(e){return e._getType()==="ai"}var mt=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=vh(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:Xn(this.content,e.content),additional_kwargs:Ue(this.additional_kwargs,e.additional_kwargs),response_metadata:bh(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=zs(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=Th(this.usage_metadata,e.usage_metadata));const n=this.constructor;return new n(t)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}},Qn=class Eh extends tt{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return Eh}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}}},di=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:Xn(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 Rw(e){return e._getType()==="generic"}function $w(e){return e._getType()==="generic"}var hi=class extends tt{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},pi=class extends Nn{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){const t=this.constructor;return new t({content:Xn(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 Lw(e){return e._getType()==="function"}function jw(e){return e._getType()==="function"}var de=class extends tt{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},Vs=class extends Nn{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){const t=this.constructor;return new t({content:Xn(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 Dw(e){return e.getType()==="human"}function Uw(e){return e.getType()==="human"}var fe=class extends tt{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="system"}},Kn=class extends Nn{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){const t=this.constructor;return new t({content:Xn(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 Fw(e){return e._getType()==="system"}function Bw(e){return e._getType()==="system"}function fi(e,t){return e.lc_error_code=t,e.message=`${e.message}
17
-
18
- Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/
19
- `,e}var vn=class extends tt{type="remove";id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}};const zw=e=>e();function Hw(e){return ps(e)?e:typeof e.id=="string"&&e.type==="function"&&typeof e.function=="object"&&e.function!==null&&"arguments"in e.function&&typeof e.function.arguments=="string"&&"name"in e.function&&typeof e.function.name=="string"?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function Vw(e){return typeof e=="object"&&e!=null&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs=="object"}function zi(e){let t,n;if(Vw(e)){const r=e.id.at(-1);r==="HumanMessage"||r==="HumanMessageChunk"?t="user":r==="AIMessage"||r==="AIMessageChunk"?t="assistant":r==="SystemMessage"||r==="SystemMessageChunk"?t="system":r==="FunctionMessage"||r==="FunctionMessageChunk"?t="function":r==="ToolMessage"||r==="ToolMessageChunk"?t="tool":t="unknown",n=e.kwargs}else{const{type:r,...s}=e;t=r,n=s}if(t==="human"||t==="user")return new de(n);if(t==="ai"||t==="assistant"){const{tool_calls:r,...s}=n;if(!Array.isArray(r))return new D(n);const a=r.map(Hw);return new D({...s,tool_calls:a})}else{if(t==="system")return new fe(n);if(t==="developer")return new fe({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if(t==="tool"&&"tool_call_id"in n)return new X({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});if(t==="remove"&&"id"in n&&typeof n.id=="string")return new vn({...n,id:n.id});throw fi(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
20
-
21
- Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Gt(e){if(typeof e=="string")return new de(e);if(Ie(e))return e;if(Array.isArray(e)){const[t,n]=e;return zi({type:t,content:n})}else if(yh(e)){const{role:t,...n}=e;return zi({...n,type:t})}else return zi(e)}function Zc(e,t="Human",n="AI"){const r=[];for(const s of e){let a;if(s._getType()==="human")a=t;else if(s._getType()==="ai")a=n;else if(s._getType()==="system")a="System";else if(s._getType()==="tool")a="Tool";else if(s._getType()==="generic")a=s.role;else throw new Error(`Got unsupported message type: ${s._getType()}`);const i=s.name?`${s.name}, `:"",o=typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2);r.push(`${a}: ${i}${o}`)}return r.join(`
22
- `)}function Gw(e){if(e.data!==void 0)return e;{const t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function qc(e){const t=Gw(e);switch(t.type){case"human":return new de(t.data);case"ai":return new D(t.data);case"system":return new fe(t.data);case"function":if(t.data.name===void 0)throw new Error("Name must be defined for function messages");return new hi(t.data);case"tool":if(t.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new X(t.data);case"generic":if(t.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Qn(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function Ww(e){return e.map(qc)}function Jw(e){return e.map(t=>t.toDict())}function Ua(e){const t=e._getType();if(t==="human")return new Vs({...e});if(t==="ai"){let n={...e};return"tool_calls"in n&&(n={...n,tool_call_chunks:n.tool_calls?.map(r=>({...r,type:"tool_call_chunk",index:void 0,args:JSON.stringify(r.args)}))}),new mt({...n})}else{if(t==="system")return new Kn({...e});if(t==="function")return new pi({...e});if(Qn.isInstance(e))return new di({...e});throw new Error("Unknown message type.")}}var Kw={},Ch={};F(Ch,{getEnv:()=>Ih,getEnvironmentVariable:()=>nn,getRuntimeEnvironment:()=>Ph,isBrowser:()=>Ah,isDeno:()=>mi,isJsDom:()=>Oh,isNode:()=>xh,isWebWorker:()=>kh});const Ah=()=>typeof window<"u"&&typeof window.document<"u",kh=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Oh=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),mi=()=>typeof Deno<"u",xh=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!mi(),Ih=()=>{let e;return Ah()?e="browser":xh()?e="node":kh()?e="webworker":Oh()?e="jsdom":mi()?e="deno":e="other",e};let Hi;function Ph(){return Hi===void 0&&(Hi={library:"langchain-js",runtime:Ih()}),Hi}function nn(e){try{return typeof process<"u"?Kw?.[e]:mi()?Deno?.env.get(e):void 0}catch{return}}var Nh={};F(Nh,{BaseCallbackHandler:()=>es,callbackHandlerPrefersStreaming:()=>Yc,isBaseCallbackHandler:()=>Mh});var Zw=class{};function Yc(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var es=class extends Zw{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ui(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=nn("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Tt.prototype.toJSON.call(this)}toJSONNotImplemented(){return Tt.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends es{name=Ce();constructor(){super(),Object.assign(this,e)}}return new t}};const Mh=e=>{const t=e;return t!==void 0&&typeof t.copy=="function"&&typeof t.name=="string"&&typeof t.awaitHandlers=="boolean"},qw="gen_ai.operation.name",Yw="gen_ai.system",vu="gen_ai.request.model",Xw="gen_ai.response.model",bu="gen_ai.usage.input_tokens",Su="gen_ai.usage.output_tokens",Tu="gen_ai.usage.total_tokens",Qw="gen_ai.request.max_tokens",ev="gen_ai.request.temperature",tv="gen_ai.request.top_p",nv="gen_ai.request.frequency_penalty",rv="gen_ai.request.presence_penalty",sv="gen_ai.response.finish_reasons",av="gen_ai.prompt",iv="gen_ai.completion",ov="gen_ai.request.extra_query",cv="gen_ai.request.extra_body",lv="gen_ai.serialized.name",uv="gen_ai.serialized.signature",dv="gen_ai.serialized.doc",hv="gen_ai.response.id",pv="gen_ai.response.service_tier",fv="gen_ai.response.system_fingerprint",mv="gen_ai.usage.input_token_details",gv="gen_ai.usage.output_token_details",yv="langsmith.trace.session_id",_v="langsmith.trace.session_name",wv="langsmith.span.kind",vv="langsmith.trace.name",bv="langsmith.metadata",Eu="langsmith.span.tags",Sv="langsmith.request.streaming",Tv="langsmith.request.headers",Ev=(...e)=>fetch(...e),Rh=Symbol.for("ls:fetch_implementation"),Cv=()=>{const e=globalThis[Rh];return e?typeof e=="function"&&"Headers"in e&&"Request"in e&&"Response"in e:!1},Av=e=>async(...t)=>{if(e||Xe("DEBUG")==="true"){const[r,s]=t;console.log(`→ ${s?.method||"GET"} ${r}`)}const n=await(globalThis[Rh]??Ev)(...t);return(e||Xe("DEBUG")==="true")&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},$h=()=>Xe("PROJECT")??Jt("LANGCHAIN_SESSION")??"default",Lh="0.3.75";var $o={};let Dt;const kv=()=>typeof window<"u"&&typeof window.document<"u",Ov=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",xv=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),jh=()=>typeof Deno<"u",Iv=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!jh(),Dh=()=>Dt||(typeof Bun<"u"?Dt="bun":kv()?Dt="browser":Iv()?Dt="node":Ov()?Dt="webworker":xv()?Dt="jsdom":jh()?Dt="deno":Dt="other",Dt);let Vi;function Uh(){if(Vi===void 0){const e=Dh(),t=Nv();Vi={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:Lh,...t}}return Vi}function Fh(){const e=Pv(),t={},n=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[r,s]of Object.entries(e))typeof s=="string"&&!n.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?t.revision_id=s:t[r]=s);return t}function Pv(){const e={};try{if(typeof process<"u"&&$o)for(const[t,n]of Object.entries($o))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&n!=null&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&typeof n=="string"?e[t]=n.slice(0,2)+"*".repeat(n.length-4)+n.slice(-2):e[t]=n)}catch{}return e}function Jt(e){try{return typeof process<"u"?$o?.[e]:void 0}catch{return}}function Xe(e){return Jt(`LANGSMITH_${e}`)||Jt(`LANGCHAIN_${e}`)}let Gi;function Nv(){if(Gi!==void 0)return Gi;const e=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],t={};for(const n of e){const r=Jt(n);r!==void 0&&(t[n]=r)}return Gi=t,t}function Bh(){return Jt("OTEL_ENABLED")==="true"||Xe("OTEL_ENABLED")==="true"}class Mv{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(t,...n){!this.hasWarned&&Bh()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let r;if(n.length===1&&typeof n[0]=="function"?r=n[0]:n.length===2&&typeof n[1]=="function"?r=n[1]:n.length===3&&typeof n[2]=="function"&&(r=n[2]),typeof r=="function")return r()}}class Rv{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Mv})}getTracer(t,n){return this.mockTracer}getActiveSpan(){}setSpan(t,n){return t}getSpan(t){}setSpanContext(t,n){return t}getTracerProvider(){}setGlobalTracerProvider(t){return!1}}class $v{active(){return{}}with(t,n){return n()}}const Wi=Symbol.for("ls:otel_trace"),Ji=Symbol.for("ls:otel_context"),Cu=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Lv=new Rv,jv=new $v;class Dv{getTraceInstance(){return globalThis[Wi]??Lv}getContextInstance(){return globalThis[Ji]??jv}initializeGlobalInstances(t){globalThis[Wi]===void 0&&(globalThis[Wi]=t.trace),globalThis[Ji]===void 0&&(globalThis[Ji]=t.context)}setDefaultOTLPTracerComponents(t){globalThis[Cu]=t}getDefaultOTLPTracerComponents(){return globalThis[Cu]??void 0}}const Xc=new Dv;function zh(){return Xc.getTraceInstance()}function Uv(){return Xc.getContextInstance()}function Fv(){return Xc.getDefaultOTLPTracerComponents()}const Bv={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function zv(e){return Bv[e]||e}class Hv{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(t,n){for(const r of t)try{if(!r.run)continue;if(r.operation==="post"){const s=this.createSpanForRun(r,r.run,n.get(r.id));s&&!r.run.end_time&&this.spans.set(r.id,s)}else this.updateSpanForRun(r,r.run)}catch(s){console.error(`Error processing operation ${r.id}:`,s)}}createSpanForRun(t,n,r){const s=r&&zh().getSpan(r);if(s)try{return this.finishSpanSetup(s,n,t)}catch(a){console.error(`Failed to create span for run ${t.id}:`,a);return}}finishSpanSetup(t,n,r){return this.setSpanAttributes(t,n,r),n.error?(t.setStatus({code:2}),t.recordException(new Error(n.error))):t.setStatus({code:1}),n.end_time&&t.end(new Date(n.end_time)),t}updateSpanForRun(t,n){try{const r=this.spans.get(t.id);if(!r){console.debug(`No span found for run ${t.id} during update`);return}this.setSpanAttributes(r,n,t),n.error?(r.setStatus({code:2}),r.recordException(new Error(n.error))):r.setStatus({code:1});const s=n.end_time;s&&(r.end(new Date(s)),this.spans.delete(t.id))}catch(r){console.error(`Failed to update span for run ${t.id}:`,r)}}extractModelName(t){if(t.extra?.metadata){const n=t.extra.metadata;if(n.ls_model_name)return n.ls_model_name;if(n.invocation_params){const r=n.invocation_params;if(r.model)return r.model;if(r.model_name)return r.model_name}}}setSpanAttributes(t,n,r){if("run_type"in n&&n.run_type){t.setAttribute(wv,n.run_type);const o=zv(n.run_type||"chain");t.setAttribute(qw,o)}"name"in n&&n.name&&t.setAttribute(vv,n.name),"session_id"in n&&n.session_id&&t.setAttribute(yv,n.session_id),"session_name"in n&&n.session_name&&t.setAttribute(_v,n.session_name),this.setGenAiSystem(t,n);const s=this.extractModelName(n);s&&t.setAttribute(vu,s),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&t.setAttribute(bu,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&t.setAttribute(Su,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&t.setAttribute(Tu,n.total_tokens),this.setInvocationParameters(t,n);const a=n.extra?.metadata||{};for(const[o,c]of Object.entries(a))c!=null&&t.setAttribute(`${bv}.${o}`,String(c));const i=n.tags;if(i&&Array.isArray(i)?t.setAttribute(Eu,i.join(", ")):i&&t.setAttribute(Eu,String(i)),"serialized"in n&&typeof n.serialized=="object"){const o=n.serialized;o.name&&t.setAttribute(lv,String(o.name)),o.signature&&t.setAttribute(uv,String(o.signature)),o.doc&&t.setAttribute(dv,String(o.doc))}this.setIOAttributes(t,r)}setGenAiSystem(t,n){let r="langchain";const s=this.extractModelName(n);if(s){const a=s.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?r="anthropic":a.includes("bedrock")?r="aws.bedrock":a.includes("azure")&&a.includes("openai")?r="az.ai.openai":a.includes("azure")&&a.includes("inference")?r="az.ai.inference":a.includes("cohere")?r="cohere":a.includes("deepseek")?r="deepseek":a.includes("gemini")?r="gemini":a.includes("groq")?r="groq":a.includes("watson")||a.includes("ibm")?r="ibm.watsonx.ai":a.includes("mistral")?r="mistral_ai":a.includes("gpt")||a.includes("openai")?r="openai":a.includes("perplexity")||a.includes("sonar")?r="perplexity":a.includes("vertex")?r="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(r="xai")}t.setAttribute(Yw,r)}setInvocationParameters(t,n){if(!n.extra?.metadata?.invocation_params)return;const r=n.extra.metadata.invocation_params;r.max_tokens!==void 0&&t.setAttribute(Qw,r.max_tokens),r.temperature!==void 0&&t.setAttribute(ev,r.temperature),r.top_p!==void 0&&t.setAttribute(tv,r.top_p),r.frequency_penalty!==void 0&&t.setAttribute(nv,r.frequency_penalty),r.presence_penalty!==void 0&&t.setAttribute(rv,r.presence_penalty)}setIOAttributes(t,n){if(n.run.inputs)try{const r=n.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&t.setAttribute(vu,r.model),r.stream!==void 0&&t.setAttribute(Sv,r.stream),r.extra_headers&&t.setAttribute(Tv,JSON.stringify(r.extra_headers)),r.extra_query&&t.setAttribute(ov,JSON.stringify(r.extra_query)),r.extra_body&&t.setAttribute(cv,JSON.stringify(r.extra_body))),t.setAttribute(av,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${n.id}`,r)}if(n.run.outputs)try{const r=n.run.outputs,s=this.getUnifiedRunTokens(r);if(s&&(t.setAttribute(bu,s[0]),t.setAttribute(Su,s[1]),t.setAttribute(Tu,s[0]+s[1])),r&&typeof r=="object"){if(r.model&&t.setAttribute(Xw,String(r.model)),r.id&&t.setAttribute(hv,r.id),r.choices&&Array.isArray(r.choices)){const a=r.choices.map(i=>i.finish_reason).filter(i=>i).map(String);a.length>0&&t.setAttribute(sv,a.join(", "))}if(r.service_tier&&t.setAttribute(pv,r.service_tier),r.system_fingerprint&&t.setAttribute(fv,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const a=r.usage_metadata;a.input_token_details&&t.setAttribute(mv,JSON.stringify(a.input_token_details)),a.output_token_details&&t.setAttribute(gv,JSON.stringify(a.output_token_details))}}t.setAttribute(iv,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${n.id}`,r)}}getUnifiedRunTokens(t){if(!t)return null;let n=this.extractUnifiedRunTokens(t.usage_metadata);if(n)return n;const r=Object.keys(t);for(const i of r){const o=t[i];if(!(!o||typeof o!="object")&&(n=this.extractUnifiedRunTokens(o.usage_metadata),n||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(n=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),n)))return n}const s=t.generations||[];if(!Array.isArray(s))return null;const a=Array.isArray(s[0])?s.flat():s;for(const i of a)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(n=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),n))return n;return null}extractUnifiedRunTokens(t){return!t||typeof t!="object"||typeof t.input_tokens!="number"||typeof t.output_tokens!="number"?null:[t.input_tokens,t.output_tokens]}}const Vv=[429,500,502,503,504];let Au=class{constructor(t){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,"default"in tn?this.queue=new tn.default({concurrency:this.maxConcurrency}):this.queue=new tn({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...n){const r=this.onFailedResponseHook;return this.queue.add(()=>ja(()=>t(...n).catch(s=>{throw s instanceof Error?s:new Error(s)}),{async onFailedAttempt(s){if(s.message.startsWith("Cancel")||s.message.startsWith("TimeoutError")||s.name==="TimeoutError"||s.message.startsWith("AbortError")||s?.code==="ECONNABORTED")throw s;const a=s?.response;if(r&&await r(a))return;const i=a?.status??s?.status;if(i&&!Vv.includes(+i))throw s},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,n,...r){return t.signal?Promise.race([this.call(n,...r),new Promise((s,a)=>{t.signal?.addEventListener("abort",()=>{a(new Error("AbortError"))})})]):this.call(n,...r)}};function ku(e){return typeof e?._getType=="function"}function Ou(e){const t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}const Gv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function V(e,t){if(!Gv.test(e)){const n=t!==void 0?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`;throw new Error(n)}return e}const xu={};function Lo(e){xu[e]||(console.warn(e),xu[e]=!0)}function dn(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);const[t,n]=e.split(":"),r=n||"latest";if(t.includes("/")){const[s,a]=t.split("/",2);if(!s||!a)throw new Error(`Invalid identifier format: ${e}`);return[s,a,r]}else{if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,r]}}class Wv extends Error{constructor(t){super(t),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function 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 Wv(s);const a=new Error(s);throw a.status=e.status,a}const Hh="ERR_CONFLICTING_ENDPOINTS";class Jv extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:Hh}),this.name="ConflictingEndpointsError"}}function Kv(e){return typeof e=="object"&&e!==null&&e.code===Hh}var Iu="[...]",Zv={result:"[Circular]"},Fa=[],fr=[];const qv=new TextEncoder;function Yv(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function aa(e){return qv.encode(e)}function Vh(e){if(e&&typeof e=="object"&&e!==null){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if(typeof e=="bigint")return e.toString();return e}function Xv(e){return function(t,n){return Vh(n)}}function lt(e,t,n,r,s){try{const a=JSON.stringify(e,Xv(n),r);return aa(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`
23
- Context: ${t}`:""}`),aa("[Unserializable]");Xe("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=Yv()),jo(e,"",0,[],void 0,0,s);let i;try{fr.length===0?i=JSON.stringify(e,n,r):i=JSON.stringify(e,Qv(n),r)}catch{return aa("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Fa.length!==0;){const o=Fa.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return aa(i)}}function Ki(e,t,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:e}),Fa.push([r,n,t,s])):fr.push([t,n,e]):(r[n]=e,Fa.push([r,n,t]))}function jo(e,t,n,r,s,a,i){a+=1;var o;if(typeof e=="object"&&e!==null){for(o=0;o<r.length;o++)if(r[o]===e){Ki(Zv,e,t,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){Ki(Iu,e,t,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){Ki(Iu,e,t,s);return}if(r.push(e),Array.isArray(e))for(o=0;o<e.length;o++)jo(e[o],o,o,r,e,a,i);else{e=Vh(e);var c=Object.keys(e);for(o=0;o<c.length;o++){var l=c[o];jo(e[l],l,o,r,e,a,i)}}r.pop()}}function Qv(e){return e=typeof e<"u"?e:function(t,n){return n},function(t,n){if(fr.length>0)for(var r=0;r<fr.length;r++){var s=fr[r];if(s[1]===t&&s[0]===n){n=s[2],fr.splice(r,1);break}}return e.call(this,t,n)}}function Pu(e,t){const n=Uh(),r=t??Fh(),s=e.extra??{},a=s.metadata;return e.extra={...s,runtime:{...n,...s?.runtime},metadata:{...r,...r.revision_id||"revision_id"in e&&e.revision_id?{revision_id:("revision_id"in e?e.revision_id:void 0)??r.revision_id}:{},...a}},e}const eb=e=>{const t=e?.toString()??Xe("TRACING_SAMPLING_RATE");if(t===void 0)return;const n=parseFloat(t);if(n<0||n>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},tb=e=>{const n=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};async function nb(e){const t=[];for await(const n of e)t.push(n);return t}function ia(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const rb=async e=>{if(e?.status===429){const t=parseInt(e.headers.get("retry-after")??"10",10)*1e3;if(t>0)return await new Promise(n=>setTimeout(n,t)),!0}return!1};function Nu(e){return typeof e=="number"?Number(e.toFixed(4)):e}class sb{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(t){let n;const r=new Promise(a=>{n=a}),s=lt(t.item,`Serializing run with id: ${t.item.id}`).length;return this.items.push({action:t.action,payload:t.item,otelContext:t.otelContext,apiKey:t.apiKey,apiUrl:t.apiUrl,itemPromiseResolve:n,itemPromise:r,size:s}),this.sizeBytes+=s,r}pop({upToSizeBytes:t,upToSize:n}){if(t<1)throw new Error("Number of bytes to pop off may not be less than 1.");const r=[];let s=0;for(;s+(this.peek()?.size??0)<t&&this.items.length>0&&r.length<n;){const a=this.items.shift();a&&(r.push(a),s+=a.size,this.sizeBytes-=a.size)}if(r.length===0&&this.items.length>0){const a=this.items.shift();r.push(a),s+=a.size,this.sizeBytes-=a.size}return[r.map(a=>({action:a.action,item:a.payload,otelContext:a.otelContext,apiKey:a.apiKey,apiUrl:a.apiUrl})),()=>r.forEach(a=>a.itemPromiseResolve())]}}const ab=24*1024*1024,ib=1e4,ob=100,Mu="https://api.smith.langchain.com";class zr{get _fetch(){return this.fetchImplementation||Av(this.debug)}constructor(t={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new sb}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Jt("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Jt("LANGSMITH_DEBUG")==="true"});const n=zr.getDefaultClientConfig();if(this.tracingSampleRate=eb(t.tracingSamplingRate),this.apiUrl=ia(t.apiUrl??n.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=ia(t.apiKey??n.apiKey),this.webUrl=ia(t.webUrl??n.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=ia(t.workspaceId??Xe("WORKSPACE_ID")),this.timeout_ms=t.timeout_ms??9e4,this.caller=new Au({...t.callerOptions??{},maxRetries:4,debug:t.debug??this.debug}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=t.debug??this.debug,this.fetchImplementation=t.fetchImplementation,this.batchIngestCaller=new Au({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...t.callerOptions??{},onFailedResponseHook:rb,debug:t.debug??this.debug}),this.hideInputs=t.hideInputs??t.anonymizer??n.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??n.hideOutputs,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.batchSizeLimit=t.batchSizeLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode,Bh()&&(this.langSmithToOTELTranslator=new Hv),this.cachedLSEnvVarsForMetadata=Fh()}static getDefaultClientConfig(){const t=Xe("API_KEY"),n=Xe("ENDPOINT")??Mu,r=Xe("HIDE_INPUTS")==="true",s=Xe("HIDE_OUTPUTS")==="true";return{apiUrl:n,apiKey:t,webUrl:void 0,hideInputs:r,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:tb(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const t={"User-Agent":`langsmith-js/${Lh}`};return this.apiKey&&(t["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(t["x-tenant-id"]=this.workspaceId),t}_getPlatformEndpointPath(t){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${t}`:`/platform/${t}`}async processInputs(t){return this.hideInputs===!1?t:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(t):t}async processOutputs(t){return this.hideOutputs===!1?t:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(t):t}async prepareRunCreateOrUpdateInputs(t){const n={...t};return n.inputs!==void 0&&(n.inputs=await this.processInputs(n.inputs)),n.outputs!==void 0&&(n.outputs=await this.processOutputs(n.outputs)),n}async _getResponse(t,n){const r=n?.toString()??"",s=`${this.apiUrl}${t}?${r}`;return await this.caller.call(async()=>{const i=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await 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??ab}async _getBatchSizeLimit(){const t=await this._ensureServerInfo();return this.batchSizeLimit??t.batch_ingest_config?.size_limit??ob}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:n}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[s,a]=this.autoBatchQueue.pop({upToSizeBytes:t,upToSize:n});if(!s.length){a();break}const i=s.reduce((l,u)=>{const d=u.apiUrl??this.apiUrl,h=u.apiKey??this.apiKey,f=u.apiKey===this.apiKey&&u.apiUrl===this.apiUrl?"default":`${d}|${h}`;return l[f]||(l[f]=[]),l[f].push(u),l},{}),o=[];for(const[l,u]of Object.entries(i)){const d=this._processBatch(u,{apiUrl:l==="default"?void 0:l.split("|")[0],apiKey:l==="default"?void 0:l.split("|")[1]});o.push(d)}const c=Promise.all(o).finally(a);r.push(c)}return Promise.all(r)}async _processBatch(t,n){if(t.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(t);else{const r={runCreates:t.filter(a=>a.action==="create").map(a=>a.item),runUpdates:t.filter(a=>a.action==="update").map(a=>a.item)},s=await this._ensureServerInfo();if(s?.batch_ingest_config?.use_multipart_endpoint){const a=s?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(r,{...n,useGzip:a})}else await this.batchIngestRuns(r,n)}}catch(r){console.error("Error exporting batch:",r)}}_sendBatchToOTELTranslator(t){if(this.langSmithToOTELTranslator!==void 0){const n=new Map,r=[];for(const s of t)s.item.id&&s.otelContext&&(n.set(s.item.id,s.otelContext),s.action==="create"?r.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):r.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(r,n)}}async processRunOperation(t){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,t.item=Pu(t.item,this.cachedLSEnvVarsForMetadata);const n=this.autoBatchQueue.push(t);if(this.manualFlushMode)return n;const r=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>s)&&this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s})},this.autoBatchAggregationDelayMs)),n}async _getServerInfo(){const n=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(ib),...this.fetchOptions});return await 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=zh(),n=Uv();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=Pu(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=lt(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(lt(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:y,events:S,extra:b,error:v,serialized:w,attachments:E,...A}=p,I={inputs:f,outputs:y,events:S,extra:b,error:v,serialized:w},k=lt(A,`Serializing for multipart ingestion of run with id: ${A.id}`);u.push({name:`${d}.${A.id}`,payload:new Blob([k],{type:`application/json; length=${k.length}`})});for(const[g,N]of Object.entries(I)){if(N===void 0)continue;const x=lt(N,`Serializing ${g} for multipart ingestion of run with id: ${A.id}`);u.push({name:`${d}.${A.id}.${g}`,payload:new Blob([x],{type:`application/json; length=${x.length}`})})}if(A.id!==void 0){const g=s[A.id];if(g){delete s[A.id];for(const[N,x]of Object.entries(g)){let M,z;if(Array.isArray(x)?[M,z]=x:(M=x.mimeType,z=x.data),N.includes(".")){console.warn(`Skipping attachment '${N}' for run ${A.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}u.push({name:`attachment.${A.id}.${N}`,payload:new Blob([z],{type:`${M}; length=${z.byteLength}`})})}}}l.push(`trace=${A.trace_id},id=${A.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=Cv(),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&&Dh()!=="bun"?(u=!0,l=await c(o)):l=await c(i),(!this.multipartStreamingDisabled||u)&&l.status===422&&(r?.apiUrl??this.apiUrl)!==Mu&&(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=lt(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:Xe("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 nb(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:y,treeFilter:S,limit:b,select:v,order:w}=t;let E=[];if(n&&(E=Array.isArray(n)?n:[n]),r){const g=Array.isArray(r)?r:[r],N=await Promise.all(g.map(x=>this.readProject({projectName:x}).then(M=>M.id)));E.push(...N)}const A=["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"],I={session:E.length?E:null,run_type:u,reference_example:i,query:p,filter:f,trace_filter:y,tree_filter:S,execution_order:c,parent_run:s,start_time:o?o.toISOString():null,error:d,id:h,limit:b,trace:a,select:v||A,is_root:l,order:w};I.select.includes("child_run_ids")&&Lo("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let k=0;for await(const g of this._getCursorPaginatedList("/runs/query",I))if(b){if(k>=b)break;if(g.length+k>b){yield*g.slice(0,b-k);break}k+=g.length,yield*g}else yield*g}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 y={...d,offset:h},S=Object.fromEntries(Object.entries(y).filter(([I,k])=>k!==void 0)),b=JSON.stringify(S),w=await(await this.caller.call(async()=>{const I=await this._fetch(f,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await j(I,`Failed to fetch ${p}`),I})).json(),{groups:E,total:A}=w;if(E.length===0)break;for(const I of E)yield I;if(h+=E.length,h>=A)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:y,dataSourceType:S}){let b=i||[];a&&(b=[...i||[],...await Promise.all(a.map(k=>this.readProject({projectName:k}).then(g=>g.id)))]);const w=Object.fromEntries(Object.entries({id:t,trace:n,parent_run:r,run_type:s,session:b,reference_example:o,start_time:c,end_time:l,error:u,query:d,filter:h,trace_filter:p,tree_filter:f,is_root:y,data_source_type:S}).filter(([k,g])=>g!==void 0)),E=JSON.stringify(w);return await(await this.caller.call(async()=>{const k=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:E});return await j(k,"get run stats"),k})).json()}async shareRun(t,{shareId:n}={}){const r={run_id:t,share_token:n||Ce()};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(Ru(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;Ru(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]??Ce())}async createExamples(t){if(Array.isArray(t)){if(t.length===0)return[];const v=t;let w=v[0].dataset_id;const E=v[0].dataset_name;if(w===void 0&&E===void 0)throw new Error("Must provide either datasetName or datasetId");if(w!==void 0&&E!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");w===void 0&&(w=(await this.readDataset({datasetName:E})).id);const A=await this._uploadExamplesMultipart(w,v);return await Promise.all(A.example_ids.map(k=>this.readExample(k)))}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 y=n.map((v,w)=>({dataset_id:p,inputs:v,outputs:r?.[w],metadata:s?.[w],split:a?.[w],id:u?.[w],attachments:l?.[w],source_run_id:i?.[w],use_source_run_io:o?.[w],use_source_run_attachments:c?.[w]})),S=await this._uploadExamplesMultipart(p,y);return await Promise.all(S.example_ids.map(v=>this.readExample(v)))}async createLLMExample(t,n,r){return this.createExample({input:t},{output:n},r)}async createChatExample(t,n,r){const s=t.map(i=>ku(i)?Ou(i):i),a=ku(n)?Ou(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 y=i??!0;if(p.append("inline_s3_urls",y.toString()),r!==void 0)for(const b of r)p.append("id",b);if(a!==void 0)for(const b of a)p.append("splits",b);if(o!==void 0){const b=JSON.stringify(o);p.append("metadata",b)}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(b=>p.append("select",b));let S=0;for await(const b of this._getPaginated("/examples",p)){for(const v of b){const{attachment_urls:w,...E}=v,A=E;w&&(A.attachments=Object.entries(w).reduce((I,[k,g])=>(I[k.slice(11)]={presigned_url:g.presigned_url,mime_type:g.mime_type||void 0},I),{})),yield A,S++}if(c!==void 0&&S>=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}){Lo("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 y={id:u??Ce(),run_id:t,key:n,score:Nu(r),value:s,correction:a,comment:i,feedback_source:f,comparative_experiment_id:p,feedbackConfig:d,session_id:h},S=JSON.stringify(y),b=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const v=await this._fetch(b,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:S});return await j(v,"create feedback",!0),v}),y}async updateFeedback(t,{score:n,value:r,correction:s,comment:a}){const i={};n!=null&&(i.score=Nu(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||Ce(),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]=dn(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]=dn(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]=dn(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]=dn(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]=dn(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=lt(c,`Serializing body for example with id: ${o}`),u=new Blob([l],{type:"application/json"});if(r.append(o,u),i.inputs){const d=lt(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=lt(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 y=new Blob([f],{type:`${p}; length=${f.byteLength}`});r.append(`${o}.attachment.${d}`,y)}if(i.attachments_operations){const d=lt(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??Ce()).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=lt(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=lt(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=lt(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]=dn(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]=dn(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]=dn(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 Fv()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function Ru(e){return"dataset_id"in e||"dataset_name"in e}const cb=e=>!!["TRACING_V2","TRACING"].find(n=>Xe(n)==="true"),Zi=Symbol.for("lc:context_variables");function lb(e){return e.replace(/[-:.]/g,"")}function Gh(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:lb(s)+t,microsecondPrecisionDatestring:s}}class Ba{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 Ba(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 We{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}),Wh(t)){Object.assign(this,{...t});return}const n=We.getDefaultConfig(),{metadata:r,...s}=t,a=s.client??We.getSharedClient(),i={...r,...s?.extra?.metadata};if(s.extra={...s.extra,metadata:i},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=fb(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:c}=Gh(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:Ce(),run_type:"chain",project_name:$h(),child_runs:[],api_url:Jt("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Jt("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return We.sharedClient||(We.sharedClient=new zr),We.sharedClient}createChild(t){const n=this.child_execution_order+1,r=new We({...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});Zi in this&&(r[Zi]=this[Zi]);const s=Symbol.for("lc:child_config"),a=t.extra?.[s]??this.extra[s];if(db(a)){const c={...a},l=ub(c.callbacks)?c.callbacks.copy?.():void 0;l&&(Object.assign(l,{_parentRunId:r.id}),l.handlers?.find(Jh)?.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=>ws(`${d}:${t}`,ws.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=hb(s.dotted_order),h=[];for(let f=0;f<d.length-1;f++){const[y,S]=d[f],b=a(S);h.push(y.toISOString().replace(/[-:]/g,"").replace(".","")+b)}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=Uh();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){Lo("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=cb();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 We({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 We({...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=Ba.fromHeader(r.baggage);c.metadata=l.metadata,c.tags=l.tags,c.project_name=l.project_name,c.replicas=l.replicas}return new We(c)}toHeaders(t){const n={"langsmith-trace":this.dotted_order,baggage:new Ba(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(We,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Wh(e){return e!=null&&typeof e.createChild=="function"&&typeof e.postRun=="function"}function Jh(e){return typeof e=="object"&&e!=null&&typeof e.name=="string"&&e.name==="langchain_tracer"}function $u(e){return Array.isArray(e)&&e.some(t=>Jh(t))}function ub(e){return typeof e=="object"&&e!=null&&Array.isArray(e.handlers)}function db(e){return e!=null&&typeof e.callbacks=="object"&&($u(e.callbacks?.handlers)||$u(e.callbacks))}function hb(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 pb(){const e=Jt("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){mb(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(Kv(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 fb(e){return e?e.map(t=>Array.isArray(t)?{projectName:t[0],updates:t[1]}:t):pb()}function mb(e){if(Object.keys(e).length>0&&Xe("ENDPOINT"))throw new Jv}var Kh={};F(Kh,{BaseTracer:()=>cn,isBaseTracer:()=>pr});const gb=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function Do(e,t){if(e)return new We({...e,start_time:e._serialized_start_time??e.start_time,parent_run:Do(t),child_runs:e.child_runs.map(n=>Do(n)).filter(n=>n!==void 0),extra:{...e.extra,runtime:Ph()},tracingEnabled:!1})}function qi(e,t){return e&&!Array.isArray(e)&&typeof e=="object"?e:{[t]:e}}function pr(e){return typeof e._addRunToRunMap=="function"}var cn=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?gb(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}=Gh(new Date(e.start_time).getTime(),e.id,e.execution_order),r={...e},s=this.getRunById(r.parent_run_id);if(r.parent_run_id!==void 0?s&&(this._addChildRun(s,r),s.child_execution_order=Math.max(s.child_execution_order,r.child_execution_order),r.trace_id=s.trace_id,s.dotted_order!==void 0&&(r.dotted_order=[s.dotted_order,t].join("."),r._serialized_start_time=n)):(r.trace_id=r.id,r.dotted_order=t,r._serialized_start_time=n),this.usesRunTreeMap){const a=Do(r,s);a!==void 0&&this.runTreeMap.set(r.id,a)}else this.runMap.set(r.id,r);return r}async _endTrace(e){const t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,n,r,s,a,i,o){const c=this._getExecutionOrder(r),l=Date.now(),u=i?{...s,metadata:i}:s,d={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleLLMStart(e,t,n,r,s,a,i,o){const c=this.getRunById(n)??this._createRunForLLMStart(e,t,n,r,s,a,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,n,r,s,a,i,o){const c=this._getExecutionOrder(r),l=Date.now(),u=i?{...s,metadata:i}:s,d={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleChatModelStart(e,t,n,r,s,a,i,o){const c=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,r,s,a,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,n,r,s){const a=this.getRunById(t);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=e,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(e,t,n,r,s){const a=this.getRunById(t);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(e,t,n,r,s,a,i,o){const c=this._getExecutionOrder(r),l=Date.now(),u={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:i??"chain",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleChainStart(e,t,n,r,s,a,i,o){const c=this.getRunById(n)??this._createRunForChainStart(e,t,n,r,s,a,i,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,n,r,s){const a=this.getRunById(t);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=qi(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),s?.inputs!==void 0&&(a.inputs=qi(s.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,t,n,r,s){const a=this.getRunById(t);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),s?.inputs!==void 0&&(a.inputs=qi(s.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(e,t,n,r,s,a,i){const o=this._getExecutionOrder(r),c=Date.now(),l={id:n,name:i??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,n,r,s,a,i){const o=this.getRunById(n)??this._createRunForToolStart(e,t,n,r,s,a,i);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="chain")return;const r=n;r.actions=r.actions||[],r.actions.push(e),r.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(n)}async handleAgentEnd(e,t){const n=this.getRunById(t);!n||n?.run_type!=="chain"||(n.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(n))}_createRunForRetrieverStart(e,t,n,r,s,a,i){const o=this._getExecutionOrder(r),c=Date.now(),l={id:n,name:i??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,n,r,s,a,i){const o=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,r,s,a,i);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onRetrieverEnd?.(n),await this._endTrace(n),n}async handleRetrieverError(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onRetrieverError?.(n),await this._endTrace(n),n}async handleText(e,t){const n=this.getRunById(t);!n||n?.run_type!=="chain"||(n.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(n))}async handleLLMNewToken(e,t,n,r,s,a){const i=this.getRunById(n);if(!i||i?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return i.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:a?.chunk}}),await this.onLLMNewToken?.(i,e,{chunk:a?.chunk}),i}},Zh={};F(Zh,{ConsoleCallbackHandler:()=>Uo});function ze(e,t){return`${e.open}${t}${e.close}`}function _t(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function Lu(e){return typeof e=="string"?e.trim():e==null?e:_t(e,e.toString())}function hn(e){if(!e.end_time)return"";const t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}const{color:Ye}=th;var Uo=class extends cn{name="console_callback_handler";persistRun(e){return Promise.resolve()}getParents(e){const t=[];let n=e;for(;n.parent_run_id;){const r=this.runMap.get(n.parent_run_id);if(r)t.push(r),n=r;else break}return t}getBreadcrumbs(e){const n=[...this.getParents(e).reverse(),e].map((r,s,a)=>{const i=`${r.execution_order}:${r.run_type}:${r.name}`;return s===a.length-1?ze(th.bold,i):i}).join(" > ");return ze(Ye.grey,n)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Ye.green,"[chain/start]")} [${t}] Entering Chain run with input: ${_t(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Ye.cyan,"[chain/end]")} [${t}] [${hn(e)}] Exiting Chain run with output: ${_t(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Ye.red,"[chain/error]")} [${t}] [${hn(e)}] Chain run errored with error: ${_t(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),n="prompts"in e.inputs?{prompts:e.inputs.prompts.map(r=>r.trim())}:e.inputs;console.log(`${ze(Ye.green,"[llm/start]")} [${t}] Entering LLM run with input: ${_t(n,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Ye.cyan,"[llm/end]")} [${t}] [${hn(e)}] Exiting LLM run with output: ${_t(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Ye.red,"[llm/error]")} [${t}] [${hn(e)}] LLM run errored with error: ${_t(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Ye.green,"[tool/start]")} [${t}] Entering Tool run with input: "${Lu(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Ye.cyan,"[tool/end]")} [${t}] [${hn(e)}] Exiting Tool run with output: "${Lu(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Ye.red,"[tool/error]")} [${t}] [${hn(e)}] Tool run errored with error: ${_t(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Ye.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${_t(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Ye.cyan,"[retriever/end]")} [${t}] [${hn(e)}] Exiting Retriever run with output: ${_t(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${ze(Ye.red,"[retriever/error]")} [${t}] [${hn(e)}] Retriever run errored with error: ${_t(e.error,"[error]")}`)}onAgentAction(e){const t=e,n=this.getBreadcrumbs(e);console.log(`${ze(Ye.blue,"[agent/action]")} [${n}] Agent selected action: ${_t(t.actions[t.actions.length-1],"[action]")}`)}};let Yi;const qh=()=>{if(Yi===void 0){const e=nn("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Yi=new zr(e)}return Yi};let yb=class{getStore(){}run(t,n){return n()}};const Xi=Symbol.for("ls:tracing_async_local_storage"),_b=new yb;let wb=class{getInstance(){return globalThis[Xi]??_b}initializeGlobalInstance(t){globalThis[Xi]===void 0&&(globalThis[Xi]=t)}};const vb=new wb;function bb(e=!1){const t=vb.getInstance().getStore();if(!e&&t===void 0)throw new Error(`Could not get the current run tree.
57
-
58
- Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}function Qc(e){return typeof e=="function"&&"langsmith:traceable"in e}var Yh={};F(Yh,{LangChainTracer:()=>ga});var ga=class Xh extends cn{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(t={}){super(t);const{exampleId:n,projectName:r,client:s,replicas:a}=t;this.projectName=r??$h(),this.replicas=a,this.exampleId=n,this.client=s??qh();const i=Xh.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(t){}async onRunCreate(t){await this.getRunTreeWithTracingConfig(t.id)?.postRun()}async onRunUpdate(t){await this.getRunTreeWithTracingConfig(t.id)?.patchRun()}getRun(t){return this.runTreeMap.get(t)}updateFromRunTree(t){this.runTreeMap.set(t.id,t);let n=t;const r=new Set;for(;n.parent_run&&!(r.has(n.id)||(r.add(n.id),!n.parent_run));)n=n.parent_run;r.clear();const s=[n];for(;s.length>0;){const a=s.shift();!a||r.has(a.id)||(r.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&s.push(...a.child_runs))}this.client=t.client??this.client,this.replicas=t.replicas??this.replicas,this.projectName=t.project_name??this.projectName,this.exampleId=t.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(t){const n=this.runTreeMap.get(t);if(n)return new We({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return bb(!0)}catch{return}}};const Qh=Symbol.for("ls:tracing_async_local_storage"),Hn=Symbol.for("lc:context_variables"),Sb=e=>{globalThis[Qh]=e},Hr=()=>globalThis[Qh];let Vn;function Tb(){const e="default"in tn?tn.default:tn;return new e({autoStart:!0,concurrency:1})}function Eb(){return typeof Vn>"u"&&(Vn=Tb()),Vn}async function we(e,t){if(t===!0){const n=Hr();n!==void 0?await n.run(void 0,async()=>e()):await e()}else Vn=Eb(),Vn.add(async()=>{const n=Hr();n!==void 0?await n.run(void 0,async()=>e()):await e()})}async function Cb(){const e=qh();await Promise.allSettled([typeof Vn<"u"?Vn.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}var ep={};F(ep,{awaitAllCallbacks:()=>Cb,consumeCallback:()=>we});const Ab=e=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(n=>nn(n)==="true");function kb(e,t){const n=Hr();if(n===void 0)throw new Error("Internal error: Global shared async local storage instance has not been initialized.");const r=n.getStore(),s={...r?.[Hn]};s[e]=t;let a={};Wh(r)&&(a=new We(r)),a[Hn]=s,n.enterWith(a)}function el(e){const t=Hr();return t===void 0?void 0:t.getStore()?.[Hn]?.[e]}const Ob=Symbol("lc:configure_hooks"),xb=()=>el(Ob)||[];var tp={};F(tp,{BaseCallbackManager:()=>np,BaseRunManager:()=>Ws,CallbackManager:()=>Ke,CallbackManagerForChainRun:()=>sp,CallbackManagerForLLMRun:()=>Fo,CallbackManagerForRetrieverRun:()=>rp,CallbackManagerForToolRun:()=>ap,ensureHandler:()=>Ts,parseCallbackConfigArg:()=>Gs});function Gs(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}var np=class{setHandler(e){return this.setHandlers([e])}},Ws=class{constructor(e,t,n,r,s,a,i,o){this.runId=e,this.handlers=t,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=s,this.metadata=a,this.inheritableMetadata=i,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>we(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleCustomEvent(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{try{await a.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}},rp=class extends Ws{getChild(e){const t=new 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)))}},Fo=class extends Ws{async handleLLMNewToken(e,t,n,r,s,a){await Promise.all(this.handlers.map(i=>we(async()=>{if(!i.ignoreLLM)try{await i.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMNewToken: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMError(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{if(!a.ignoreLLM)try{await a.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMError: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}async handleLLMEnd(e,t,n,r,s){await Promise.all(this.handlers.map(a=>we(async()=>{if(!a.ignoreLLM)try{await a.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,s)}catch(i){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMEnd: ${i}`),a.raiseError)throw i}},a.awaitHandlers)))}},sp=class extends Ws{getChild(e){const t=new 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)))}},ap=class extends Ws{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 os extends np{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(t,n){super(),this.handlers=n?.handlers??this.handlers,this.inheritableHandlers=n?.inheritableHandlers??this.inheritableHandlers,this.tags=n?.tags??this.tags,this.inheritableTags=n?.inheritableTags??this.inheritableTags,this.metadata=n?.metadata??this.metadata,this.inheritableMetadata=n?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=t}getParentRunId(){return this._parentRunId}async handleLLMStart(t,n,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(l,u)=>{const d=u===0&&r?r:Ce();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return pr(h)&&h._createRunForLLMStart(t,[l],d,this._parentRunId,a,this.tags,this.metadata,c),we(async()=>{try{await h.handleLLMStart?.(t,[l],d,this._parentRunId,a,this.tags,this.metadata,c)}catch(p){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${p}`),h.raiseError)throw p}},h.awaitHandlers)})),new Fo(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,n,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(l,u)=>{const d=u===0&&r?r:Ce();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return pr(h)&&h._createRunForChatModelStart(t,[l],d,this._parentRunId,a,this.tags,this.metadata,c),we(async()=>{try{if(h.handleChatModelStart)await h.handleChatModelStart?.(t,[l],d,this._parentRunId,a,this.tags,this.metadata,c);else if(h.handleLLMStart){const p=Zc(l);await h.handleLLMStart?.(t,[p],d,this._parentRunId,a,this.tags,this.metadata,c)}}catch(p){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${p}`),h.raiseError)throw p}},h.awaitHandlers)})),new Fo(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,n,r=Ce(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return pr(c)&&c._createRunForChainStart(t,n,r,this._parentRunId,this.tags,this.metadata,s,o),we(async()=>{try{await c.handleChainStart?.(t,n,r,this._parentRunId,this.tags,this.metadata,s,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleChainStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new sp(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,n,r=Ce(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return pr(c)&&c._createRunForToolStart(t,n,r,this._parentRunId,this.tags,this.metadata,o),we(async()=>{try{await c.handleToolStart?.(t,n,r,this._parentRunId,this.tags,this.metadata,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new ap(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,n,r=Ce(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return pr(c)&&c._createRunForRetrieverStart(t,n,r,this._parentRunId,this.tags,this.metadata,o),we(async()=>{try{await c.handleRetrieverStart?.(t,n,r,this._parentRunId,this.tags,this.metadata,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new rp(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,n,r,s,a){await Promise.all(this.handlers.map(i=>we(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(t,n,r,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(t,n=!0){this.handlers.push(t),n&&this.inheritableHandlers.push(t)}removeHandler(t){this.handlers=this.handlers.filter(n=>n!==t),this.inheritableHandlers=this.inheritableHandlers.filter(n=>n!==t)}setHandlers(t,n=!0){this.handlers=[],this.inheritableHandlers=[];for(const r of t)this.addHandler(r,n)}addTags(t,n=!0){this.removeTags(t),this.tags.push(...t),n&&this.inheritableTags.push(...t)}removeTags(t){this.tags=this.tags.filter(n=>!t.includes(n)),this.inheritableTags=this.inheritableTags.filter(n=>!t.includes(n))}addMetadata(t,n=!0){this.metadata={...this.metadata,...t},n&&(this.inheritableMetadata={...this.inheritableMetadata,...t})}removeMetadata(t){for(const n of Object.keys(t))delete this.metadata[n],delete this.inheritableMetadata[n]}copy(t=[],n=!0){const r=new os(this._parentRunId);for(const s of this.handlers){const a=this.inheritableHandlers.includes(s);r.addHandler(s,a)}for(const s of this.tags){const a=this.inheritableTags.includes(s);r.addTags([s],a)}for(const s of Object.keys(this.metadata)){const a=Object.keys(this.inheritableMetadata).includes(s);r.addMetadata({[s]:this.metadata[s]},a)}for(const s of t)r.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===s.name)||r.addHandler(s,n);return r}static fromHandlers(t){class n extends es{name=Ce();constructor(){super(),Object.assign(this,t)}}const r=new this;return r.addHandler(new n),r}static configure(t,n,r,s,a,i,o){return this._configureSync(t,n,r,s,a,i,o)}static _configureSync(t,n,r,s,a,i,o){let c;(t||n)&&(Array.isArray(t)||!t?(c=new os,c.setHandlers(t?.map(Ts)??[],!0)):c=t,c=c.copy(Array.isArray(n)?n.map(Ts):n?.handlers,!1));const l=nn("LANGCHAIN_VERBOSE")==="true"||o?.verbose,u=ga.getTraceableRunTree()?.tracingEnabled||Ab(),d=u||(nn("LANGCHAIN_TRACING")??!1);if(l||d){if(c||(c=new os),l&&!c.handlers.some(h=>h.name===Uo.prototype.name)){const h=new Uo;c.addHandler(h,!0)}if(d&&!c.handlers.some(h=>h.name==="langchain_tracer")&&u){const h=new ga;c.addHandler(h,!0)}if(u){const h=ga.getTraceableRunTree();h&&c._parentRunId===void 0&&(c._parentRunId=h.id,c.handlers.find(f=>f.name==="langchain_tracer")?.updateFromRunTree(h))}}for(const{contextVar:h,inheritable:p=!0,handlerClass:f,envVar:y}of xb()){const S=y&&nn(y)==="true"&&f;let b;const v=h!==void 0?el(h):void 0;v&&Mh(v)?b=v:S&&(b=new f({})),b!==void 0&&(c||(c=new os),c.handlers.some(w=>w.name===b.name)||c.addHandler(b,p))}return(r||s)&&c&&(c.addTags(r??[]),c.addTags(s??[],!1)),(a||i)&&c&&(c.addMetadata(a??{}),c.addMetadata(i??{},!1)),c}};function Ts(e){return"name"in e?e:es.fromMethods(e)}var ip=class{getStore(){}run(e,t){return t()}enterWith(e){}};const Ib=new ip,ju=Symbol.for("lc:child_config");var Pb=class{getInstance(){return Hr()??Ib}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[ju]}runWithConfig(e,t,n){const r=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 We({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[ju]:e}),a!==void 0&&a[Hn]!==void 0&&(c===void 0&&(c={}),c[Hn]=a[Hn]),s.run(c,t)}initializeGlobalInstance(e){Hr()===void 0&&Sb(e)}};const me=new Pb;var op={};F(op,{AsyncLocalStorageProviderSingleton:()=>me,MockAsyncLocalStorage:()=>ip,_CONTEXT_VARIABLES_KEY:()=>Hn});const Qi=25;async function nt(e){return Ke._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function pt(...e){const t={};for(const n of e.filter(r=>!!r))for(const r of Object.keys(n))if(r==="metadata")t[r]={...t[r],...n[r]};else if(r==="tags"){const s=t[r]??[];t[r]=[...new Set(s.concat(n[r]??[]))]}else if(r==="configurable")t[r]={...t[r],...n[r]};else if(r==="timeout")t.timeout===void 0?t.timeout=n.timeout:n.timeout!==void 0&&(t.timeout=Math.min(t.timeout,n.timeout));else if(r==="signal")t.signal===void 0?t.signal=n.signal:n.signal!==void 0&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,n.signal]):t.signal=n.signal);else if(r==="callbacks"){const s=t.callbacks,a=n.callbacks;if(Array.isArray(a))if(!s)t.callbacks=a;else if(Array.isArray(s))t.callbacks=s.concat(a);else{const i=s.copy();for(const o of a)i.addHandler(Ts(o),!0);t.callbacks=i}else if(a)if(!s)t.callbacks=a;else if(Array.isArray(s)){const i=a.copy();for(const o of s)i.addHandler(Ts(o),!0);t.callbacks=i}else t.callbacks=new 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 Nb=new Set(["string","number","boolean"]);function K(e){const t=me.getRunnableConfig();let n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:r,runName:s,...a}=t;n=Object.entries(a).reduce((i,[o,c])=>(c!==void 0&&(i[o]=c),i),n)}if(e&&(n=Object.entries(e).reduce((r,[s,a])=>(a!==void 0&&(r[s]=a),r),n)),n?.configurable)for(const r of Object.keys(n.configurable))Nb.has(typeof n.configurable[r])&&!n.metadata?.[r]&&(n.metadata||(n.metadata={}),n.metadata[r]=n.configurable[r]);if(n.timeout!==void 0){if(n.timeout<=0)throw new Error("Timeout must be a positive number");const r=AbortSignal.timeout(n.timeout);n.signal!==void 0?"any"in AbortSignal&&(n.signal=AbortSignal.any([n.signal,r])):n.signal=r,delete n.timeout}return n}function ne(e={},{callbacks:t,maxConcurrency:n,recursionLimit:r,runName:s,configurable:a,runId:i}={}){const o=K(e);return t!==void 0&&(delete o.runName,o.callbacks=t),r!==void 0&&(o.recursionLimit=r),n!==void 0&&(o.maxConcurrency=n),s!==void 0&&(o.runName=s),a!==void 0&&(o.configurable={...o.configurable,...a}),i!==void 0&&delete o.runId,o}function on(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}async function On(e,t){if(t===void 0)return e;let n;return Promise.race([e.catch(r=>{if(!t?.aborted)throw r}),new Promise((r,s)=>{n=()=>{s(Es(t))},t.addEventListener("abort",n),t.aborted&&s(Es(t))})]).finally(()=>t.removeEventListener("abort",n))}function Es(e){return e?.reason instanceof Error?e.reason:typeof e?.reason=="string"?new Error(e.reason):new Error("Aborted")}function ge(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_zod"in t))return!1;const n=t._zod;return typeof n=="object"&&n!==null&&"def"in n}function Se(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_def"in t)||"_zod"in t)return!1;const n=t._def;return typeof n=="object"&&n!=null&&"typeName"in n}function Mb(e){return ge(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Se(e)}function er(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(ge(e)||Se(e))}function cp(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function lp(e){return ge(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function Rb(e){return!!(cp(e)||lp(e))}async function tl(e,t){if(ge(e))try{return{success:!0,data:await nh(e,t)}}catch(n){return{success:!1,error:n}}if(Se(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function gi(e,t){if(ge(e))return await nh(e,t);if(Se(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function $b(e,t){if(ge(e))try{return{success:!0,data:Dc(e,t)}}catch(n){return{success:!1,error:n}}if(Se(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function bn(e,t){if(ge(e))return Dc(e,t);if(Se(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Vr(e){if(ge(e))return Re.get(e)?.description;if(Se(e)||"description"in e&&typeof e.description=="string")return e.description}function Lb(e){if(!er(e))return!1;if(Se(e)){const t=e._def;if(t.typeName==="ZodObject"){const n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(ge(e)){const t=e._zod.def;if(t.type==="object"){const n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function nl(e){return er(e)?Se(e)?e._def.typeName==="ZodString":ge(e)?e._zod.def.type==="string":!1:!1}function rl(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function Wt(e){return ge(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function yi(e){return ge(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function Qe(e){return!!(rl(e)||Wt(e))}function Cs(e){if(Se(e))return e.shape;if(ge(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function up(e,t){if(Se(e))return e.extend(t);if(ge(e))return r_(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function sl(e){if(Se(e))return e.partial();if(ge(e))return s_(jc,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function za(e,t=!1){if(Se(e))return e.strict();if(Wt(e)){const n=e._zod.def.shape;if(t)for(const[a,i]of Object.entries(e._zod.def.shape)){if(Wt(i)){const c=za(i,t);n[a]=c}else if(yi(i)){let c=i._zod.def.element;Wt(c)&&(c=za(c,t)),n[a]=An(i,{...i._zod.def,element:c})}else n[a]=i;const o=Re.get(i);o&&Re.add(n[a],o)}const r=An(e,{...e._zod.def,shape:n,catchall:a_(i_)}),s=Re.get(e);return s&&Re.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Bo(e,t=!1){if(rl(e))return e.passthrough();if(Wt(e)){const n=e._zod.def.shape;if(t)for(const[a,i]of Object.entries(e._zod.def.shape)){if(Wt(i)){const c=Bo(i,t);n[a]=c}else if(yi(i)){let c=i._zod.def.element;Wt(c)&&(c=Bo(c,t)),n[a]=An(i,{...i._zod.def,element:c})}else n[a]=i;const o=Re.get(i);o&&Re.add(n[a],o)}const r=An(e,{...e._zod.def,shape:n,catchall:o_(c_)}),s=Re.get(e);return s&&Re.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function _i(e){if(Se(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(ge(e))try{const t=Dc(e,void 0);return()=>t}catch{return}}function jb(e){return Se(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function Db(e){return ge(e)&&e._zod.def.type==="pipe"}function mr(e,t=!1){if(Se(e))return jb(e)?mr(e._def.schema,t):e;if(ge(e)){let n=e;if(Db(e)&&(n=mr(e._zod.def.in,t)),t){if(Wt(n)){const s=n._zod.def.shape;for(const[a,i]of Object.entries(n._zod.def.shape))s[a]=mr(i,t);n=An(n,{...n._zod.def,shape:s})}else if(yi(n)){const s=mr(n._zod.def.element,t);n=An(n,{...n._zod.def,element:s})}}const r=Re.get(e);return r&&Re.add(n,r),n}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function dp(e,t){if(Se(e)){const n=Cs(e),r={};for(const[s,a]of Object.entries(n))t(s,a)?r[s]=a.optional():r[s]=a;return e.extend(r)}if(ge(e)){const n=Cs(e),r={...e._zod.def.shape};for(const[i,o]of Object.entries(n))t(i,o)&&(r[i]=new jc({type:"optional",innerType:o}));const s=An(e,{...e._zod.def,shape:r}),a=Re.get(e);return a&&Re.add(s,a),s}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}const Ub=Symbol("Let zodToJsonSchema decide on which parser to use"),Fb={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Bb=e=>({...Fb,...e}),zb=e=>{const t=Bb(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},hp=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function st(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?hp(t,e.currentPath):t.join("/")}}function pp(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function se(e,t,n,r,s){e[t]=n,pp(e,t,r,s)}function Hb(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==R.ZodAny&&(n.items=Q(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&se(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&se(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(se(n,"minItems",e.exactLength.value,e.exactLength.message,t),se(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function Vb(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":t.target==="jsonSchema7"?r.inclusive?se(n,"minimum",r.value,r.message,t):se(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),se(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?se(n,"maximum",r.value,r.message,t):se(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),se(n,"maximum",r.value,r.message,t));break;case"multipleOf":se(n,"multipleOf",r.value,r.message,t);break}return n}function Gb(){return{type:"boolean"}}function fp(e,t){return Q(e.type._def,t)}const Wb=(e,t)=>Q(e.innerType._def,t);function mp(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(s=>mp(e,t,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Jb(e,t)}}const Jb=(e,t)=>{const n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(const r of e.checks)switch(r.kind){case"min":se(n,"minimum",r.value,r.message,t);break;case"max":se(n,"maximum",r.value,r.message,t);break}return n};function Kb(e,t){return{...Q(e.innerType._def,t),default:e.defaultValue()}}function Zb(e,t){return t.effectStrategy==="input"?Q(e.schema._def,t):st(t)}function qb(e){return{type:"string",enum:Array.from(e.values)}}const Yb=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function Xb(e,t){const n=[Q(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Q(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a);let r=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(a=>{if(Yb(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function Qb(e,t){const n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}let eo;const At={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(eo===void 0&&(eo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),eo),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function gp(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":se(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":se(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":kt(n,"email",r.message,t);break;case"format:idn-email":kt(n,"idn-email",r.message,t);break;case"pattern:zod":He(n,At.email,r.message,t);break}break;case"url":kt(n,"uri",r.message,t);break;case"uuid":kt(n,"uuid",r.message,t);break;case"regex":He(n,r.regex,r.message,t);break;case"cuid":He(n,At.cuid,r.message,t);break;case"cuid2":He(n,At.cuid2,r.message,t);break;case"startsWith":He(n,RegExp(`^${to(r.value,t)}`),r.message,t);break;case"endsWith":He(n,RegExp(`${to(r.value,t)}$`),r.message,t);break;case"datetime":kt(n,"date-time",r.message,t);break;case"date":kt(n,"date",r.message,t);break;case"time":kt(n,"time",r.message,t);break;case"duration":kt(n,"duration",r.message,t);break;case"length":se(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t),se(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":He(n,RegExp(to(r.value,t)),r.message,t);break;case"ip":r.version!=="v6"&&kt(n,"ipv4",r.message,t),r.version!=="v4"&&kt(n,"ipv6",r.message,t);break;case"base64url":He(n,At.base64url,r.message,t);break;case"jwt":He(n,At.jwt,r.message,t);break;case"cidr":r.version!=="v6"&&He(n,At.ipv4Cidr,r.message,t),r.version!=="v4"&&He(n,At.ipv6Cidr,r.message,t);break;case"emoji":He(n,At.emoji(),r.message,t);break;case"ulid":He(n,At.ulid,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":kt(n,"binary",r.message,t);break;case"contentEncoding:base64":se(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":He(n,At.base64,r.message,t);break}break;case"nanoid":He(n,At.nanoid,r.message,t);break}return n}function to(e,t){return t.patternStrategy==="escape"?t0(e):e}const e0=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function t0(e){let t="";for(let n=0;n<e.length;n++)e0.has(e[n])||(t+="\\"),t+=e[n];return t}function kt(e,t,n,r){e.format||e.anyOf?.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):se(e,"format",t,n,r)}function He(e,t,n,r){e.pattern||e.allOf?.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Du(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):se(e,"pattern",Du(t,r),n,r)}function Du(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,o=!1;for(let c=0;c<r.length;c++){if(a){s+=r[c],a=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){o?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),o=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],o=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){s+=`(^|(?<=[\r
59
- ]))`;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 yp(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===R.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,s)=>({...r,[s]:Q(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??st(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:Q(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===R.ZodString&&e.keyType._def.checks?.length){const{type:r,...s}=gp(e.keyType._def,t);return{...n,propertyNames:s}}else{if(e.keyType?._def.typeName===R.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===R.ZodBranded&&e.keyType._def.type._def.typeName===R.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...s}=fp(e.keyType._def,t);return{...n,propertyNames:s}}}return n}function n0(e,t){if(t.mapStrategy==="record")return yp(e,t);const n=Q(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||st(t),r=Q(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||st(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function r0(e){const t=e.values,r=Object.keys(e.values).filter(a=>typeof t[t[a]]!="number").map(a=>t[a]),s=Array.from(new Set(r.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function s0(e){return e.target==="openAi"?void 0:{not:st({...e,currentPath:[...e.currentPath,"not"]})}}function a0(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ha={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function i0(e,t){if(t.target==="openApi3")return Uu(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Ha&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,a)=>{const i=Ha[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":return a._def.value===null?[...s,"null"]:s;case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===n.length){const s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return Uu(e,t)}const Uu=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,s)=>Q(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function o0(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Ha[e.innerType._def.typeName],nullable:!0}:{type:[Ha[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const r=Q(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=Q(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function c0(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",pp(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?se(n,"minimum",r.value,r.message,t):se(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),se(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?se(n,"maximum",r.value,r.message,t):se(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),se(n,"maximum",r.value,r.message,t));break;case"multipleOf":se(n,"multipleOf",r.value,r.message,t);break}return n}function l0(e,t){const n=t.target==="openAi",r={type:"object",properties:{}},s=[],a=e.shape();for(const o in a){let c=a[o];if(c===void 0||c._def===void 0)continue;let l=d0(c);l&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const u=Q(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});u!==void 0&&(r.properties[o]=u,l||s.push(o))}s.length&&(r.required=s);const i=u0(e,t);return i!==void 0&&(r.additionalProperties=i),r}function u0(e,t){if(e.catchall._def.typeName!=="ZodNever")return Q(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function d0(e){try{return e.isOptional()}catch{return!0}}const h0=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Q(e.innerType._def,t);const n=Q(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:st(t)},n]}:st(t)},p0=(e,t)=>{if(t.pipeStrategy==="input")return Q(e.in._def,t);if(t.pipeStrategy==="output")return Q(e.out._def,t);const n=Q(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=Q(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}};function f0(e,t){return Q(e.type._def,t)}function m0(e,t){const r={type:"array",uniqueItems:!0,items:Q(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&se(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&se(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function g0(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>Q(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Q(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>Q(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function y0(e){return{not:st(e)}}function _0(e){return st(e)}const w0=(e,t)=>Q(e.innerType._def,t),v0=(e,t,n)=>{switch(t){case R.ZodString:return gp(e,n);case R.ZodNumber:return c0(e,n);case R.ZodObject:return l0(e,n);case R.ZodBigInt:return Vb(e,n);case R.ZodBoolean:return Gb();case R.ZodDate:return mp(e,n);case R.ZodUndefined:return y0(n);case R.ZodNull:return a0(n);case R.ZodArray:return Hb(e,n);case R.ZodUnion:case R.ZodDiscriminatedUnion:return i0(e,n);case R.ZodIntersection:return Xb(e,n);case R.ZodTuple:return g0(e,n);case R.ZodRecord:return yp(e,n);case R.ZodLiteral:return Qb(e,n);case R.ZodEnum:return qb(e);case R.ZodNativeEnum:return r0(e);case R.ZodNullable:return o0(e,n);case R.ZodOptional:return h0(e,n);case R.ZodMap:return n0(e,n);case R.ZodSet:return m0(e,n);case R.ZodLazy:return()=>e.getter()._def;case R.ZodPromise:return f0(e,n);case R.ZodNaN:case R.ZodNever:return s0(n);case R.ZodEffects:return Zb(e,n);case R.ZodAny:return st(n);case R.ZodUnknown:return _0(n);case R.ZodDefault:return Kb(e,n);case R.ZodBranded:return fp(e,n);case R.ZodReadonly:return w0(e,n);case R.ZodCatch:return Wb(e,n);case R.ZodPipeline:return p0(e,n);case R.ZodFunction:case R.ZodVoid:case R.ZodSymbol:return;default:return(r=>{})()}};function Q(e,t,n=!1){const r=t.seen.get(e);if(t.override){const o=t.override?.(e,t,r,n);if(o!==Ub)return o}if(r&&!n){const o=b0(r,t);if(o!==void 0)return o}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=v0(e,e.typeName,t),i=typeof a=="function"?Q(a(),t):a;if(i&&S0(e,t,i),t.postProcess){const o=t.postProcess(i,e,t);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const b0=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:hp(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),st(t)):t.$refStrategy==="seen"?st(t):void 0}},S0=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),T0=(e,t)=>{const n=zb(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((o,[c,l])=>({...o,[c]:Q(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??st(n)}),{}):void 0;const s=typeof t=="string"?t:t?.name,a=Q(e._def,n,!1)??st(n);n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const i=s===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:a}};return n.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};var _p={};F(_p,{Validator:()=>Uc,deepCompareStrict:()=>rh,toJsonSchema:()=>ft,validatesOnlyStrings:()=>fs});function ft(e){if(ge(e)){const t=mr(e,!0);if(Wt(t)){const n=za(t,!0);return ou(n)}else return ou(e)}return Se(e)?T0(e):e}function fs(e){if(!e||typeof e!="object"||Object.keys(e).length===0||Array.isArray(e))return!1;if("type"in e)return typeof e.type=="string"?e.type==="string":Array.isArray(e.type)?e.type.every(t=>t==="string"):!1;if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(t=>typeof t=="string");if("const"in e)return typeof e.const=="string";if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(t=>fs(t));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){const t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(n=>fs(n))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){const t=e.$ref,n=l_(e);return n[t]?fs(n[t]):!1}return!1}var wp={};F(wp,{AsyncCaller:()=>Js});const E0=[400,401,402,403,404,405,406,407,409],C0=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e?.code==="ECONNABORTED")throw e;const t=e?.response?.status??e?.status;if(t&&E0.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){const n=new Error(e?.message);throw n.name="InsufficientQuotaError",n}};var Js=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??C0;const t="default"in tn?tn.default:tn;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>ja(()=>e(...t).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((r,s)=>{e.signal?.addEventListener("abort",()=>{s(Es(e.signal))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}},vp={};F(vp,{AsyncGeneratorWithSetup:()=>Mn,IterableReadableStream:()=>Fe,atee:()=>al,concat:()=>xn,pipeGeneratorWithSetup:()=>bp});var Fe=class zo extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){const t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){const n=this.reader.cancel();this.reader.releaseLock(),await n}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){const n=t.getReader();return new zo({start(r){return s();function s(){return n.read().then(({done:a,value:i})=>{if(a){r.close();return}return r.enqueue(i),s()})}},cancel(){n.releaseLock()}})}static fromAsyncGenerator(t){return new zo({async pull(n){const{value:r,done:s}=await t.next();s&&n.close(),n.enqueue(r)},async cancel(n){await t.return(n)}})}};function al(e,t=2){const n=Array.from({length:t},()=>[]);return n.map(async function*(s){for(;;)if(s.length===0){const a=await e.next();for(const i of n)i.push(a)}else{if(s[0].done)return;yield s.shift().value}})}function xn(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e=="string"&&typeof t=="string")return e+t;if(typeof e=="number"&&typeof t=="number")return e+t;if("concat"in e&&typeof e.concat=="function")return e.concat(t);if(typeof e=="object"&&typeof t=="object"){const n={...e};for(const[r,s]of Object.entries(t))r in n&&!Array.isArray(n[r])?n[r]=xn(n[r],s):n[r]=s;return n}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var Mn=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,n)=>{me.runWithConfig(on(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,n):this.firstResult.then(r=>t(void 0),n)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?me.runWithConfig(on(this.config),this.signal?async()=>On(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function bp(e,t,n,r,...s){const a=new Mn({generator:t,startSetup:n,signal:r}),i=await a.setup;return{output:e(a,i,...s),setup:i}}/*!
63
- * https://github.com/Starcounter-Jack/JSON-Patch
64
- * (c) 2017-2022 Joachim Wester
65
- * MIT licensed
66
- */const A0=Object.prototype.hasOwnProperty;function Ho(e,t){return A0.call(e,t)}function Vo(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)Ho(e,n)&&t.push(n);return t}function $t(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function Go(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 ur(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function k0(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Wo(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let n=0,r=e.length;n<r;n++)if(Wo(e[n]))return!0}else if(typeof e=="object"){const n=Vo(e),r=n.length;for(var t=0;t<r;t++)if(Wo(e[n[t]]))return!0}}return!1}function Fu(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(`
67
- `)}var O0=class extends Error{constructor(e,t,n,r,s){super(Fu(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=Fu(e,{name:t,index:n,operation:r,tree:s})}},Sp={};F(Sp,{JsonPatchError:()=>pe,_areEquals:()=>As,applyOperation:()=>Gn,applyPatch:()=>Gr,applyReducer:()=>P0,deepClone:()=>x0,getValueByPointer:()=>Va,validate:()=>Tp,validator:()=>Ga});const pe=O0,x0=$t,gr={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=Va(n,this.path);r&&(r=$t(r));const s=Gn(n,{op:"remove",path:this.from}).removed;return Gn(n,{op:"add",path:this.path,value:s}),{newDocument:n,removed:r}},copy:function(e,t,n){const r=Va(n,this.from);return Gn(n,{op:"add",path:this.path,value:$t(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:As(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}};var I0={add:function(e,t,n){return Go(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:gr.move,copy:gr.copy,test:gr.test,_get:gr._get};function Va(e,t){if(t=="")return e;var n={op:"_get",path:t};return Gn(e,n),n.value}function Gn(e,t,n=!1,r=!0,s=!0,a=0){if(n&&(typeof n=="function"?n(t,0,e,t.path):Ga(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=Va(e,t.from),t.op==="move"&&(i.removed=e),i;if(t.op==="test"){if(i.test=As(e,t.value),i.test===!1)throw new pe("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 pe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,t,e);return i}}else{r||(e=$t(e));const o=(t.path||"").split("/");let c=e,l=1,u=o.length,d,h,p;for(typeof n=="function"?p=n:p=Ga;;){if(h=o[l],h&&h.indexOf("~")!=-1&&(h=k0(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&&!Go(h))throw new pe("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);Go(h)&&(h=~~h)}if(l>=u){if(n&&t.op==="add"&&h>c.length)throw new pe("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=I0[t.op].call(t,c,h,e);if(f.test===!1)throw new pe("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return f}}else if(l>=u){const f=gr[t.op].call(t,c,h,e);if(f.test===!1)throw new pe("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return f}if(c=c[h],n&&l<u&&(!c||typeof c!="object"))throw new pe("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,t,e)}}}function Gr(e,t,n,r=!0,s=!0){if(n&&!Array.isArray(t))throw new pe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(e=$t(e));const a=new Array(t.length);for(let i=0,o=t.length;i<o;i++)a[i]=Gn(e,t[i],n,!0,s,i),e=a[i].newDocument;return a.newDocument=e,a}function P0(e,t,n){const r=Gn(e,t);if(r.test===!1)throw new pe("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return r.newDocument}function Ga(e,t,n,r){if(typeof e!="object"||e===null||Array.isArray(e))throw new pe("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,n);if(gr[e.op]){if(typeof e.path!="string")throw new pe("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,n);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new pe('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 pe("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 pe("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")&&Wo(e.value))throw new pe("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 pe("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 pe("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=Tp([i],n);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new pe("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}}else throw new pe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n)}function Tp(e,t,n){try{if(!Array.isArray(e))throw new pe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)Gr($t(t),$t(e),n||!0);else{n=n||Ga;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(s){if(s instanceof pe)return s;throw s}}function As(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(!As(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],!As(e[i],t[i]))return!1;return!0}return e!==e&&t!==t}function Ep(e,t,n,r,s){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var a=Vo(t),i=Vo(e),o=!1,c=i.length-1;c>=0;c--){var l=i[c],u=e[l];if(Ho(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)?Ep(u,d,n,r+"/"+ur(l),s):u!==d&&(s&&n.push({op:"test",path:r+"/"+ur(l),value:$t(u)}),n.push({op:"replace",path:r+"/"+ur(l),value:$t(d)}))}else Array.isArray(e)===Array.isArray(t)?(s&&n.push({op:"test",path:r+"/"+ur(l),value:$t(u)}),n.push({op:"remove",path:r+"/"+ur(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];!Ho(e,l)&&t[l]!==void 0&&n.push({op:"add",path:r+"/"+ur(l),value:$t(t[l])})}}}function wi(e,t,n=!1){var r=[];return Ep(e,t,r,"",n),r}({...Sp});var Cp={};F(Cp,{LogStreamCallbackHandler:()=>Ko,RunLog:()=>il,RunLogPatch:()=>qt,isLogStreamHandler:()=>Ap});var qt=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),n=Gr({},t);return new il({ops:t,state:n[n.length-1].newDocument})}},il=class Jo extends qt{state;constructor(t){super(t),this.state=t.state}concat(t){const n=this.ops.concat(t.ops),r=Gr(this.state,t.ops);return new Jo({ops:n,state:r[r.length-1].newDocument})}static fromRunLogPatch(t){const n=Gr({},t.ops);return new Jo({ops:t.ops,state:n[n.length-1].newDocument})}};const Ap=e=>e.name==="log_stream_tracer";async function Bu(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 N0(e){return e!==void 0&&e.message!==void 0}var Ko=class extends cn{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=Fe.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 qt({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 qt({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 Bu(e,this._schemaFormat)),await this.writer.write(new qt({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 Bu(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 qt({ops:n});await this.writer.write(r)}finally{if(e.id===this.rootId){const t=new qt({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?N0(n?.chunk)?a=n?.chunk:a=new mt({id:`run-${e.id}`,content:t}):a=t;const i=new qt({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)}},kp={};F(kp,{ChatGenerationChunk:()=>Jr,GenerationChunk:()=>Wr,RUN_KEY:()=>ks});const ks="__run";var Wr=class Op{text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new Op({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},Jr=class xp extends Wr{message;constructor(t){super(t),this.message=t.message}concat(t){return new xp({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function oa({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 M0=e=>e.name==="event_stream_tracer";var R0=class extends cn{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=Fe.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 Wr({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=oa(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 mt({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 Wr({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=oa(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=oa(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=oa(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()})}},Ip=class extends cn{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 ol(e){return e?e.lc_runnable:!1}var $0=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 no(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const L0=["*","_","`"];function j0(e){let t="";for(const[n,r]of Object.entries(e))t+=` classDef ${n} ${r};
68
- `;return t}function D0(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}'}}}%%
69
- graph TD;
70
- `:`graph TD;
71
- `;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[y,S]of Object.entries(e)){const b=S.name.split(":").pop()??"";let w=L0.some(A=>b.startsWith(A)&&b.endsWith(A))?`<p>${b}</p>`:b;Object.keys(S.metadata??{}).length&&(w+=`<hr/><small><em>${Object.entries(S.metadata??{}).map(([A,I])=>`${A} = ${I}`).join(`
72
- `)}</em></small>`);const E=(f[y]??f[p]).replace("{0}",no(y)).replace("{1}",w);l+=` ${E}
73
- `}}const u={};for(const p of t){const f=p.source.split(":"),y=p.target.split(":"),S=f.filter((b,v)=>b===y[v]).join(":");u[S]||(u[S]=[]),u[S].push(p)}const d=new Set;function h(p,f){const y=p.length===1&&p[0].source===p[0].target;if(f&&!y){const S=f.split(":").pop();if(d.has(S))throw new Error(`Found duplicate subgraph '${S}' -- 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(S),l+=` subgraph ${S}
74
- `}for(const S of p){const{source:b,target:v,data:w,conditional:E}=S;let A="";if(w!==void 0){let I=w;const k=I.split(" ");k.length>c&&(I=Array.from({length:Math.ceil(k.length/c)},(g,N)=>k.slice(N*c,(N+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),A=E?` -. &nbsp;${I}&nbsp; .-> `:` -- &nbsp;${I}&nbsp; --> `}else A=E?" -.-> ":" --> ";l+=` ${no(b)}${A}${no(v)};
75
- `}for(const S in u)S.startsWith(`${f}:`)&&S!==f&&h(u[S],S);f&&!y&&(l+=` end
76
- `)}h(u[""]??[],"");for(const p in u)!p.includes(":")&&p!==""&&h(u[p],p);return i&&(l+=j0(a??{})),l}async function U0(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(`
77
- `));return await i.blob()}var Pp={};F(Pp,{Graph:()=>Os});function F0(e,t){if(e!==void 0&&!br(e))return e;if(ol(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 B0(e){return ol(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...ft(e.data.schema),title:e.data.name}}}var Os=class Np{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],...B0(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??Ce(),a={id:s,data:t,name:F0(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 Hu(this)}lastNode(){return Vu(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&&Hu(this,[t.id])&&this.removeNode(t)}trimLastNode(){const t=this.lastNode();t&&Vu(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 Np({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 D0(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 U0(n,{backgroundColor:t?.backgroundColor})}};function Hu(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 Vu(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 z0(e){const t=new TextEncoder,n=new ReadableStream({async start(r){for await(const s of e)r.enqueue(t.encode(`event: data
78
- data: ${JSON.stringify(s)}
79
-
80
- `));r.enqueue(t.encode(`event: end
81
-
82
- `)),r.close()}});return Fe.fromReadableStream(n)}function Gu(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}const H0=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function";function Zo(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function*Wu(e,t){for(;;){const{value:n,done:r}=me.runWithConfig(on(e),t.next.bind(t),!0);if(r)break;yield n}}async function*qo(e,t){const n=t[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await me.runWithConfig(on(e),n.next.bind(t),!0);if(s)break;yield r}}function Ae(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}var J=class extends Tt{lc_runnable=!0;name;getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new cl({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new De({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new Dp({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(K);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const n=Object.fromEntries(Object.entries(e).filter(([r])=>r!=="runId"));return Array.from({length:t},(r,s)=>K(s===0?e:n))}return Array.from({length:t},()=>K(e))}async batch(e,t,n){const r=this._getOptionsList(t??{},e.length),s=r[0]?.maxConcurrency??n?.maxConcurrency,a=new Js({maxConcurrency:s,onFailedAttempt:o=>{throw o}}),i=e.map((o,c)=>a.call(async()=>{try{return await this.invoke(o,r[c])}catch(l){if(n?.returnExceptions)return l;throw l}}));return Promise.all(i)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const n=K(t),r=new Mn({generator:this._streamIterator(e,n),config:n});return await r.setup,Fe.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=K(e):t=K({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){const r=K(n),a=await(await nt(r))?.handleChainStart(this.toJSON(),Ae(t,"input"),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName());delete r.runId;let i;try{const o=e.call(this,t,r,a);i=await On(o,n?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(Ae(i,"output")),i}async _batchWithConfig(e,t,n,r){const s=this._getOptionsList(n??{},t.length),a=await Promise.all(s.map(nt)),i=await Promise.all(a.map(async(c,l)=>{const u=await c?.handleChainStart(this.toJSON(),Ae(t[l],"input"),s[l].runId,s[l].runType,void 0,void 0,s[l].runName??this.getName());return delete s[l].runId,u}));let o;try{const c=e.call(this,t,s,i,r);o=await On(c,s?.[0]?.signal)}catch(c){throw await Promise.all(i.map(l=>l?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(Ae(o,"output")))),o}_concatOutputChunks(e,t){return xn(e,t)}async*_transformStreamWithConfig(e,t,n){let r,s=!0,a,i=!0;const o=K(n),c=await nt(o),l=this;async function*u(){for await(const h of e){if(s)if(r===void 0)r=h;else try{r=l._concatOutputChunks(r,h)}catch{r=void 0,s=!1}yield h}}let d;try{const h=await bp(t.bind(this),u(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),n?.signal,o);delete o.runId,d=h.setup;const p=d?.handlers.find(M0);let f=h.output;p!==void 0&&d!==void 0&&(f=p.tapOutputIterable(d.runId,f));const y=d?.handlers.find(Ap);y!==void 0&&d!==void 0&&(f=y.tapOutputIterable(d.runId,f));for await(const S of f)if(yield S,i)if(a===void 0)a=S;else try{a=this._concatOutputChunks(a,S)}catch{a=void 0,i=!1}}catch(h){throw await d?.handleChainError(h,void 0,void 0,void 0,{inputs:Ae(r,"input")}),h}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:Ae(r,"input")})}getGraph(e){const t=new Os,n=t.addNode({name:`${this.getName()}Input`,schema:ht()}),r=t.addNode(this),s=t.addNode({name:`${this.getName()}Output`,schema:ht()});return t.addEdge(n,r),t.addEdge(r,s),t}pipe(e){return new Et({first:this,last:$e(e)})}pick(e){return this.pipe(new Up(e))}assign(e){return this.pipe(new ll(new ts({steps:e})))}async*transform(e,t){let n;for await(const r of e)n===void 0?n=r:n=this._concatOutputChunks(n,r);yield*this._streamIterator(n,K(t))}async*streamLog(e,t,n){const r=new Ko({...n,autoClose:!1,_schemaFormat:"original"}),s=K(t);yield*this._streamLog(e,r,s)}async*_streamLog(e,t,n){const{callbacks:r}=n;if(r===void 0)n.callbacks=[t];else if(Array.isArray(r))n.callbacks=r.concat([t]);else{const o=r.copy();o.addHandler(t,!0),n.callbacks=o}const s=this.stream(e,n);async function a(){try{const o=await s;for await(const c of o){const l=new qt({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}const i=a();try{for await(const o of t)yield o}finally{await i}}streamEvents(e,t,n){let r;if(t.version==="v1")r=this._streamEventsV1(e,t,n);else if(t.version==="v2")r=this._streamEventsV2(e,t,n);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?z0(r):Fe.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){const r=new R0({...n,autoClose:!1}),s=K(t),a=s.runId??Ce();s.runId=a;const i=s.callbacks;if(i===void 0)s.callbacks=[r];else if(Array.isArray(i))s.callbacks=i.concat(r);else{const p=i.copy();p.addHandler(r,!0),s.callbacks=p}const o=new AbortController,c=this;async function l(){let p,f=null;try{t?.signal?"any"in AbortSignal?p=AbortSignal.any([o.signal,t.signal]):(p=t.signal,f=()=>{o.abort()},t.signal.addEventListener("abort",f,{once:!0})):p=o.signal;const y=await c.stream(e,{...s,signal:p}),S=r.tapOutputIterable(a,y);for await(const b of S)if(o.signal.aborted)break}finally{await r.finish(),p&&f&&p.removeEventListener("abort",f)}}const u=l();let d=!1,h;try{for await(const p of r){if(!d){p.data.input=e,d=!0,h=p.run_id,yield p;continue}p.run_id===h&&p.event.endsWith("_end")&&p.data?.input&&delete p.data.input,yield p}}finally{o.abort(),await u}}async*_streamEventsV1(e,t,n){let r,s=!1;const a=K(t),i=a.tags??[],o=a.metadata??{},c=a.runName??this.getName(),l=new Ko({...n,autoClose:!1,_schemaFormat:"streaming_events"}),u=new $0({...n}),d=this._streamLog(e,l,a);for await(const p of d){if(r?r=r.concat(p):r=il.fromRunLogPatch(p),r.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!s){s=!0;const b={...r.state},v={run_id:b.id,event:`on_${b.type}_start`,name:c,tags:i,metadata:o,data:{input:e}};u.includeEvent(v,b.type)&&(yield v)}const f=p.ops.filter(b=>b.path.startsWith("/logs/")).map(b=>b.path.split("/")[2]),y=[...new Set(f)];for(const b of y){let v,w={};const E=r.state.logs[b];if(E.end_time===void 0?E.streamed_output.length>0?v="stream":v="start":v="end",v==="start")E.inputs!==void 0&&(w.input=E.inputs);else if(v==="end")E.inputs!==void 0&&(w.input=E.inputs),w.output=E.final_output;else if(v==="stream"){const A=E.streamed_output.length;if(A!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${A} instead. Encountered in: "${E.name}"`);w={chunk:E.streamed_output[0]},E.streamed_output=[]}yield{event:`on_${E.type}_${v}`,name:E.name,run_id:E.id,tags:E.tags,metadata:E.metadata,data:w}}const{state:S}=r;if(S.streamed_output.length>0){const b=S.streamed_output.length;if(b!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${b} instead. Encountered in: "${S.name}"`);const v={chunk:S.streamed_output[0]};S.streamed_output=[];const w={event:`on_${S.type}_stream`,run_id:S.id,tags:i,metadata:o,name:c,data:v};u.includeEvent(w,S.type)&&(yield w)}}const h=r?.state;if(h!==void 0){const p={event:`on_${h.type}_end`,name:c,run_id:h.id,tags:i,metadata:o,data:{output:h.final_output}};u.includeEvent(p,h.type)&&(yield p)}}static isRunnable(e){return ol(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new De({bound:this,config:{},configFactories:[r=>({callbacks:[new Ip({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return K0(this,e)}},De=class Mp extends J{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(t){super(t),this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){const n=pt(this.config,...t);return pt(n,...this.configFactories?await Promise.all(this.configFactories.map(async r=>await r(n))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new cl({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t?.stopAfterAttempt,...t})}async invoke(t,n){return this.bound.invoke(t,await this._mergeConfig(n,this.kwargs))}async batch(t,n,r){const s=Array.isArray(n)?await Promise.all(n.map(async a=>this._mergeConfig(K(a),this.kwargs))):await this._mergeConfig(K(n),this.kwargs);return this.bound.batch(t,s,r)}_concatOutputChunks(t,n){return this.bound._concatOutputChunks(t,n)}async*_streamIterator(t,n){yield*this.bound._streamIterator(t,await this._mergeConfig(K(n),this.kwargs))}async stream(t,n){return this.bound.stream(t,await this._mergeConfig(K(n),this.kwargs))}async*transform(t,n){yield*this.bound.transform(t,await this._mergeConfig(K(n),this.kwargs))}streamEvents(t,n,r){const s=this,a=async function*(){yield*s.bound.streamEvents(t,{...await s._mergeConfig(K(n),s.kwargs),version:n.version},r)};return Fe.fromAsyncGenerator(a())}static isRunnableBinding(t){return t.bound&&J.isRunnable(t.bound)}withListeners({onStart:t,onEnd:n,onError:r}){return new Mp({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[s=>({callbacks:[new Ip({config:s,onStart:t,onEnd:n,onError:r})]})]})}},V0=class Rp extends J{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(t){super(t),this.bound=t.bound}async invoke(t,n){return this._callWithConfig(this._invoke.bind(this),t,n)}async _invoke(t,n,r){return this.bound.batch(t,ne(n,{callbacks:r?.getChild()}))}withListeners({onStart:t,onEnd:n,onError:r}){return new Rp({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:r})})}},cl=class extends De{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){const r=e>1?`retry:attempt:${e}`:void 0;return ne(t,{callbacks:n?.getChild(r)})}async _invoke(e,t,n){return ja(r=>super.invoke(e,this._patchConfigForRetry(r,t,n)),{onFailedAttempt:r=>this.onFailedAttempt(r,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,n,r){const s={};try{await ja(async a=>{const i=e.map((d,h)=>h).filter(d=>s[d.toString()]===void 0||s[d.toString()]instanceof Error),o=i.map(d=>e[d]),c=i.map(d=>this._patchConfigForRetry(a,t?.[d],n?.[d])),l=await super.batch(o,c,{...r,returnExceptions:!0});let u;for(let d=0;d<l.length;d+=1){const h=l[d],p=i[d];h instanceof Error&&u===void 0&&(u=h,u.input=o[d]),s[p.toString()]=h}if(u)throw u;return l},{onFailedAttempt:a=>this.onFailedAttempt(a,a.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(a){if(r?.returnExceptions!==!0)throw a}return Object.keys(s).sort((a,i)=>parseInt(a,10)-parseInt(i,10)).map(a=>s[parseInt(a,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},Et=class cs extends J{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(t){super(t),this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,n){const r=K(n),a=await(await nt(r))?.handleChainStart(this.toJSON(),Ae(t,"input"),r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let i=t,o;try{const c=[this.first,...this.middle];for(let l=0;l<c.length;l+=1){const d=c[l].invoke(i,ne(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${l+1}`)}));i=await On(d,n?.signal)}if(n?.signal?.aborted)throw Es(n.signal);o=await this.last.invoke(i,ne(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await a?.handleChainError(c),c}return await a?.handleChainEnd(Ae(o,"output")),o}async batch(t,n,r){const s=this._getOptionsList(n??{},t.length),a=await Promise.all(s.map(nt)),i=await Promise.all(a.map(async(c,l)=>{const u=await c?.handleChainStart(this.toJSON(),Ae(t[l],"input"),s[l].runId,void 0,void 0,void 0,s[l].runName);return delete s[l].runId,u}));let o=t;try{for(let c=0;c<this.steps.length;c+=1){const u=this.steps[c].batch(o,i.map((d,h)=>{const p=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return ne(s[h],{callbacks:p})}),r);o=await On(u,s[0]?.signal)}}catch(c){throw await Promise.all(i.map(l=>l?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(Ae(o,"output")))),o}_concatOutputChunks(t,n){return this.last._concatOutputChunks(t,n)}async*_streamIterator(t,n){const r=await nt(n),{runId:s,...a}=n??{},i=await r?.handleChainStart(this.toJSON(),Ae(t,"input"),s,void 0,void 0,void 0,a?.runName),o=[this.first,...this.middle,this.last];let c=!0,l;async function*u(){yield t}try{let d=o[0].transform(u(),ne(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let h=1;h<o.length;h+=1)d=await o[h].transform(d,ne(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${h+1}`)}));for await(const h of d)if(n?.signal?.throwIfAborted(),yield h,c)if(l===void 0)l=h;else try{l=this._concatOutputChunks(l,h)}catch{l=void 0,c=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(Ae(l,"output"))}getGraph(t){const n=new Os;let r=null;return this.steps.forEach((s,a)=>{const i=s.getGraph(t);a!==0&&i.trimFirstNode(),a!==this.steps.length-1&&i.trimLastNode(),n.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${s} has no first node`);r&&n.addEdge(r,o),r=i.lastNode()}),n}pipe(t){return cs.isRunnableSequence(t)?new cs({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new cs({first:this.first,middle:[...this.middle,this.last],last:$e(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&J.isRunnable(t)}static from([t,...n],r){let s={};return typeof r=="string"?s.name=r:r!==void 0&&(s=r),new cs({...s,first:$e(t),middle:n.slice(0,-1).map($e),last:$e(n[n.length-1])})}},ts=class $p extends J{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(t){super(t),this.steps={};for(const[n,r]of Object.entries(t.steps))this.steps[n]=$e(r)}static from(t){return new $p({steps:t})}async invoke(t,n){const r=K(n),a=await(await nt(r))?.handleChainStart(this.toJSON(),{input:t},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;const i={};try{const o=Object.entries(this.steps).map(async([c,l])=>{i[c]=await l.invoke(t,ne(r,{callbacks:a?.getChild(`map:key:${c}`)}))});await On(Promise.all(o),n?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(i),i}async*_transform(t,n,r){const s={...this.steps},a=al(t,Object.keys(s).length),i=new Map(Object.entries(s).map(([o,c],l)=>{const u=c.transform(a[l],ne(r,{callbacks:n?.getChild(`map:key:${o}`)}));return[o,u.next().then(d=>({key:o,gen:u,result:d}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:c,result:l,gen:u}=await On(o,r?.signal);i.delete(c),l.done||(yield{[c]:l.value},i.set(c,u.next().then(d=>({key:c,gen:u,result:d}))))}}transform(t,n){return this._transformStreamWithConfig(t,this._transform.bind(this),n)}async stream(t,n){async function*r(){yield t}const s=K(n),a=new Mn({generator:this.transform(r(),s),config:s});return await a.setup,Fe.fromAsyncGenerator(a)}},G0=class Lp extends J{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(t){if(super(t),!Qc(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,n){const[r]=this._getOptionsList(n??{},1),s=await nt(r),a=this.func(ne(r,{callbacks:s}),t);return On(a,r?.signal)}async*_streamIterator(t,n){const[r]=this._getOptionsList(n??{},1),s=await this.invoke(t,n);if(Zo(s)){for await(const a of s)r?.signal?.throwIfAborted(),yield a;return}if(H0(s)){for(;;){r?.signal?.throwIfAborted();const a=s.next();if(a.done)break;yield a.value}return}yield s}static from(t){return new Lp({func:t})}};function W0(e){if(Qc(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var at=class jp extends J{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(t){if(Qc(t.func))return G0.from(t.func);super(t),W0(t.func),this.func=t.func}static from(t){return new jp({func:t})}async _invoke(t,n,r){return new Promise((s,a)=>{const i=ne(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??Qi)-1});me.runWithConfig(on(i),async()=>{try{let o=await this.func(t,{...i});if(o&&J.isRunnable(o)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(t,{...i,recursionLimit:(i.recursionLimit??Qi)-1})}else if(Zo(o)){let c;for await(const l of qo(i,o))if(n?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}else if(Gu(o)){let c;for(const l of Wu(i,o))if(n?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}s(o)}catch(o){a(o)}})})}async invoke(t,n){return this._callWithConfig(this._invoke.bind(this),t,n)}async*_transform(t,n,r){let s;for await(const o of t)if(s===void 0)s=o;else try{s=this._concatOutputChunks(s,o)}catch{s=o}const a=ne(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??Qi)-1}),i=await new Promise((o,c)=>{me.runWithConfig(on(a),async()=>{try{const l=await this.func(s,{...a,config:a});o(l)}catch(l){c(l)}})});if(i&&J.isRunnable(i)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await i.stream(s,a);for await(const c of o)yield c}else if(Zo(i))for await(const o of qo(a,i))r?.signal?.throwIfAborted(),yield o;else if(Gu(i))for(const o of Wu(a,i))r?.signal?.throwIfAborted(),yield o;else yield i}transform(t,n){return this._transformStreamWithConfig(t,this._transform.bind(this),n)}async stream(t,n){async function*r(){yield t}const s=K(n),a=new Mn({generator:this.transform(r(),s),config:s});return await a.setup,Fe.fromAsyncGenerator(a)}},J0=class extends ts{},Dp=class extends J{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const n=K(t),r=await nt(n),{runId:s,...a}=n,i=await r?.handleChainStart(this.toJSON(),Ae(e,"input"),s,void 0,void 0,void 0,a?.runName),o=ne(a,{callbacks:i?.getChild()});return await me.runWithConfig(o,async()=>{let l;for(const u of this.runnables()){n?.signal?.throwIfAborted();try{const d=await u.invoke(e,o);return await i?.handleChainEnd(Ae(d,"output")),d}catch(d){l===void 0&&(l=d)}}throw l===void 0?new Error("No error stored at end of fallback."):(await i?.handleChainError(l),l)})}async*_streamIterator(e,t){const n=K(t),r=await nt(n),{runId:s,...a}=n,i=await r?.handleChainStart(this.toJSON(),Ae(e,"input"),s,void 0,void 0,void 0,a?.runName);let o,c;for(const u of this.runnables()){n?.signal?.throwIfAborted();const d=ne(a,{callbacks:i?.getChild()});try{const h=await u.stream(e,d);c=qo(d,h);break}catch(h){o===void 0&&(o=h)}}if(c===void 0){const u=o??new Error("No error stored at end of fallback.");throw await i?.handleChainError(u),u}let l;try{for await(const u of c){yield u;try{l=l===void 0?l:this._concatOutputChunks(l,u)}catch{l=void 0}}}catch(u){throw await i?.handleChainError(u),u}await i?.handleChainEnd(Ae(l,"output"))}async batch(e,t,n){if(n?.returnExceptions)throw new Error("Not implemented.");const r=this._getOptionsList(t??{},e.length),s=await Promise.all(r.map(o=>nt(o))),a=await Promise.all(s.map(async(o,c)=>{const l=await o?.handleChainStart(this.toJSON(),Ae(e[c],"input"),r[c].runId,void 0,void 0,void 0,r[c].runName);return delete r[c].runId,l}));let i;for(const o of this.runnables()){r[0].signal?.throwIfAborted();try{const c=await o.batch(e,a.map((l,u)=>ne(r[u],{callbacks:l?.getChild()})),n);return await Promise.all(a.map((l,u)=>l?.handleChainEnd(Ae(c[u],"output")))),c}catch(c){i===void 0&&(i=c)}}throw i?(await Promise.all(a.map(o=>o?.handleChainError(i))),i):new Error("No error stored at end of fallbacks.")}};function $e(e){if(typeof e=="function")return new at({func:e});if(J.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=$e(r);return new ts({steps:t})}else throw new Error(`Expected a Runnable, function or object.
83
- Instead got an unsupported type.`)}var ll=class extends J{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof ts&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){const n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){const r=this.mapper.getStepsKeys(),[s,a]=al(e),i=this.mapper.transform(a,ne(n,{callbacks:t?.getChild()})),o=i.next();for await(const c of s){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const l=Object.fromEntries(Object.entries(c).filter(([u])=>!r.includes(u)));Object.keys(l).length>0&&(yield l)}yield(await o).value;for await(const c of i)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const r=K(t),s=new Mn({generator:this.transform(n(),r),config:r});return await s.setup,Fe.fromAsyncGenerator(s)}},Up=class extends J{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const t=this.keys.map(n=>[n,e[n]]).filter(n=>n[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const n=await this._pick(t);n!==void 0&&(yield n)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const r=K(t),s=new Mn({generator:this.transform(n(),r),config:r});return await s.setup,Fe.fromAsyncGenerator(s)}},Yo=class extends De{name;description;schema;constructor(e){const t=Et.from([at.from(async n=>{let r;if(ps(n))try{r=await gi(this.schema,n.args)}catch{throw new Ss("Received tool input did not match expected schema",JSON.stringify(n.args))}else r=n;return r}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function K0(e,t){const n=t.name??e.getName(),r=t.description??Vr(t.schema);return nl(t.schema)?new Yo({name:n,description:r,schema:te({input:Oe()}).transform(s=>s.input),bound:e}):new Yo({name:n,description:r,schema:t.schema,bound:e})}var Fp={};F(Fp,{BasePromptValue:()=>vi,ChatPromptValue:()=>dl,ImagePromptValue:()=>Bp,StringPromptValue:()=>ul});var vi=class extends Tt{},ul=class extends vi{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new de(this.value)]}},dl=class extends vi{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return Zc(this.messages)}toChatMessages(){return this.messages}},Bp=class extends vi{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new de({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},L="0123456789abcdef".split(""),Z0=[-2147483648,8388608,32768,128],Ot=[24,16,8,0],ca=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],xe=[];function jt(e,t){t?(xe[0]=xe[16]=xe[1]=xe[2]=xe[3]=xe[4]=xe[5]=xe[6]=xe[7]=xe[8]=xe[9]=xe[10]=xe[11]=xe[12]=xe[13]=xe[14]=xe[15]=0,this.blocks=xe):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}jt.prototype.update=function(e){if(!this.finalized){var t,n=typeof e;if(n!=="string"){if(n==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);t=!0}for(var r,s=0,a,i=e.length,o=this.blocks;s<i;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),t)for(a=this.start;s<i&&a<64;++s)o[a>>>2]|=e[s]<<Ot[a++&3];else for(a=this.start;s<i&&a<64;++s)r=e.charCodeAt(s),r<128?o[a>>>2]|=r<<Ot[a++&3]:r<2048?(o[a>>>2]|=(192|r>>>6)<<Ot[a++&3],o[a>>>2]|=(128|r&63)<<Ot[a++&3]):r<55296||r>=57344?(o[a>>>2]|=(224|r>>>12)<<Ot[a++&3],o[a>>>2]|=(128|r>>>6&63)<<Ot[a++&3],o[a>>>2]|=(128|r&63)<<Ot[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++s)&1023),o[a>>>2]|=(240|r>>>18)<<Ot[a++&3],o[a>>>2]|=(128|r>>>12&63)<<Ot[a++&3],o[a>>>2]|=(128|r>>>6&63)<<Ot[a++&3],o[a>>>2]|=(128|r&63)<<Ot[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=o[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};jt.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=Z0[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};jt.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=this.blocks,l,u,d,h,p,f,y,S,b,v,w;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(w=t&n,l=0;l<64;l+=4)this.first?(this.is224?(S=300032,p=c[0]-1413257819,o=p-150054599<<0,r=p+24177077<<0):(S=704751109,p=c[0]-210244248,o=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),S=e&t,h=S^e&n^w,y=s&a^~s&i,p=o+d+y+ca[l]+c[l],f=u+h,o=r+p<<0,r=p+f<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),b=r&e,h=b^r&t^S,y=i&o^~i&s,p=a+d+y+ca[l+1]+c[l+1],f=u+h,i=n+p<<0,n=p+f<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),v=n&r,h=v^n&e^b,y=a&i^~a&o,p=s+d+y+ca[l+2]+c[l+2],f=u+h,a=t+p<<0,t=p+f<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),w=t&n,h=w^t&r^v,y=a&i^~a&o,p=s+d+y+ca[l+3]+c[l+3],f=u+h,s=e+p<<0,e=p+f<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+s<<0,this.h5=this.h5+a<<0,this.h6=this.h6+i<<0,this.h7=this.h7+o<<0};jt.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=L[e>>>28&15]+L[e>>>24&15]+L[e>>>20&15]+L[e>>>16&15]+L[e>>>12&15]+L[e>>>8&15]+L[e>>>4&15]+L[e&15]+L[t>>>28&15]+L[t>>>24&15]+L[t>>>20&15]+L[t>>>16&15]+L[t>>>12&15]+L[t>>>8&15]+L[t>>>4&15]+L[t&15]+L[n>>>28&15]+L[n>>>24&15]+L[n>>>20&15]+L[n>>>16&15]+L[n>>>12&15]+L[n>>>8&15]+L[n>>>4&15]+L[n&15]+L[r>>>28&15]+L[r>>>24&15]+L[r>>>20&15]+L[r>>>16&15]+L[r>>>12&15]+L[r>>>8&15]+L[r>>>4&15]+L[r&15]+L[s>>>28&15]+L[s>>>24&15]+L[s>>>20&15]+L[s>>>16&15]+L[s>>>12&15]+L[s>>>8&15]+L[s>>>4&15]+L[s&15]+L[a>>>28&15]+L[a>>>24&15]+L[a>>>20&15]+L[a>>>16&15]+L[a>>>12&15]+L[a>>>8&15]+L[a>>>4&15]+L[a&15]+L[i>>>28&15]+L[i>>>24&15]+L[i>>>20&15]+L[i>>>16&15]+L[i>>>12&15]+L[i>>>8&15]+L[i>>>4&15]+L[i&15];return this.is224||(c+=L[o>>>28&15]+L[o>>>24&15]+L[o>>>20&15]+L[o>>>16&15]+L[o>>>12&15]+L[o>>>8&15]+L[o>>>4&15]+L[o&15]),c};jt.prototype.toString=jt.prototype.hex;jt.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,s=this.h4,a=this.h5,i=this.h6,o=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};jt.prototype.array=jt.prototype.digest;jt.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};const hl=(...e)=>new jt(!1,!0).update(e.join("")).hex();var zp={};F(zp,{sha256:()=>hl});var Hp={};F(Hp,{BaseCache:()=>Gp,InMemoryCache:()=>Wp,defaultHashKeyEncoder:()=>Vp,deserializeStoredGeneration:()=>q0,serializeGeneration:()=>Y0});const Vp=(...e)=>hl(e.join("_"));function q0(e){return e.message!==void 0?{text:e.text,message:qc(e.message)}:{text:e.text}}function Y0(e){const t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var Gp=class{keyEncoder=Vp;makeDefaultKeyEncoder(t){this.keyEncoder=t}};const X0=new Map;var Wp=class Jp extends Gp{cache;constructor(t){super(),this.cache=t??new Map}lookup(t,n){return Promise.resolve(this.cache.get(this.keyEncoder(t,n))??null)}async update(t,n,r){this.cache.set(this.keyEncoder(t,n),r)}static global(){return new Jp(X0)}},Kp={};F(Kp,{encodingForModel:()=>pl,getEncoding:()=>Zp});const la={},Q0=new Js({});async function Zp(e){return e in la||(la[e]=Q0.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new d_(t)).catch(t=>{throw delete la[e],t})),await la[e]}async function pl(e){return Zp(u_(e))}var qp={};F(qp,{BaseLangChain:()=>fl,BaseLanguageModel:()=>Si,calculateMaxTokens:()=>nS,getEmbeddingContextSize:()=>eS,getModelContextSize:()=>Yp,getModelNameForTiktoken:()=>bi,isOpenAITool:()=>tS});const bi=e=>e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,eS=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},Yp=e=>{switch(bi(e)){case"gpt-3.5-turbo-16k":return 16384;case"gpt-3.5-turbo":return 4096;case"gpt-4-32k":return 32768;case"gpt-4":return 8192;case"text-davinci-003":return 4097;case"text-curie-001":return 2048;case"text-babbage-001":return 2048;case"text-ada-001":return 2048;case"code-davinci-002":return 8e3;case"code-cushman-001":return 2048;default:return 4097}};function tS(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}const nS=async({prompt:e,modelName:t})=>{let n;try{n=(await pl(bi(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(e.length/4)}return Yp(t)-n},rS=()=>!1;var fl=class extends J{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??rS(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},Si=class extends fl{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...n}){const{cache:r,...s}=n;super({callbacks:e??t,...s}),typeof r=="object"?this.cache=r:r?this.cache=Wp.global():this.cache=void 0,this.caller=new Js(n??{})}_encoding;async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(r=>typeof r=="string"?r:r.type==="text"&&"text"in r?r.text:"").join("");let n=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await pl("modelName"in this?bi(this.modelName):"gpt2")}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}if(this._encoding)try{n=this._encoding.encode(t).length}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}return n}static _convertInputToPromptValue(e){return typeof e=="string"?new ul(e):Array.isArray(e)?new dl(e.map(Gt)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const n={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([a,i])=>i!==void 0).map(([a,i])=>`${a}:${JSON.stringify(i)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}};function ml(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function gl(e){return e!==void 0&&J.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function yl(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(er(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function _l(e){return yl(e)||gl(e)||ml(e)}var Xp={};F(Xp,{BaseToolkit:()=>sS,DynamicStructuredTool:()=>Ti,DynamicTool:()=>vl,StructuredTool:()=>tr,Tool:()=>wl,ToolInputParsingException:()=>Ss,isLangChainTool:()=>_l,isRunnableToolLike:()=>gl,isStructuredTool:()=>ml,isStructuredToolParams:()=>yl,tool:()=>bl});var tr=class extends fl{returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata}async invoke(e,t){let n,r=K(pt(this.defaultConfig,t));return ps(e)?(n=e.args,r={...r,toolCall:e}):n=e,this.call(n,r)}async call(e,t,n){const r=ps(e)?e.args:e;let s;if(er(this.schema))try{s=await gi(this.schema,r)}catch(p){let f="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(f=`${f}
84
- Details: ${p.message}`),p instanceof Error&&p.constructor.name==="ZodError"&&(f=`${f}
85
-
86
- ${h_(p)}`),new Ss(f,JSON.stringify(e))}else{const p=p_(r,this.schema);if(!p.valid){let f="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(f=`${f}
87
- Details: ${p.errors.map(y=>`${y.keywordLocation}: ${y.error}`).join(`
88
- `)}`),new Ss(f,JSON.stringify(e))}s=r}const a=Gs(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.
89
- Result: ${JSON.stringify(c)}`);else l=c;let d;ps(e)&&(d=e.id),!d&&Cw(a)&&(d=a.toolCall.id);const h=aS({content:l,artifact:u,toolCallId:d,name:this.name,metadata:this.metadata});return await o?.handleToolEnd(h),h}},wl=class extends tr{schema=te({input:Oe().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){const n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,t)}},vl=class extends wl{static lc_name(){return"DynamicTool"}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){const n=Gs(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}async _call(e,t,n){return this.func(e,t,n)}},Ti=class extends tr{static lc_name(){return"DynamicStructuredTool"}name;description;func;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,n){const r=Gs(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r,n)}_call(e,t,n){return this.func(e,t,n)}},sS=class{getTools(){return this.tools}};function bl(e,t){const n=nl(t.schema),r=fs(t.schema);if(!t.schema||n||r)return new vl({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(i,o,c)=>new Promise((l,u)=>{const d=ne(c,{callbacks:o?.getChild()});me.runWithConfig(on(d),async()=>{try{l(e(i,d))}catch(h){u(h)}})})});const s=t.schema,a=t.description??t.schema.description??`${t.name} tool`;return new Ti({...t,description:a,schema:s,func:async(i,o,c)=>new Promise((l,u)=>{c?.signal&&c.signal.addEventListener("abort",()=>u(Es(c.signal)));const d=ne(c,{callbacks:o?.getChild()});me.runWithConfig(on(d),async()=>{try{const h=await e(i,d);if(c?.signal?.aborted)return;l(h)}catch(h){u(h)}})})})}function aS(e){const{content:t,artifact:n,toolCallId:r,metadata:s}=e;return r&&!Vc(t)?typeof t=="string"||Array.isArray(t)&&t.every(a=>typeof a=="object")?new X({status:"success",content:t,artifact:n,tool_call_id:r,name:e.name,metadata:s}):new X({status:"success",content:iS(t),artifact:n,tool_call_id:r,name:e.name,metadata:s}):t}function iS(e){try{return JSON.stringify(e,null,2)??""}catch{return`${e}`}}var Qp=typeof globalThis=="object"&&globalThis&&globalThis.Object===Object&&globalThis,oS=typeof self=="object"&&self&&self.Object===Object&&self,ln=Qp||oS||Function("return this")(),Kr=ln.Symbol,ef=Object.prototype,cS=ef.hasOwnProperty,lS=ef.toString,as=Kr?Kr.toStringTag:void 0;function uS(e){var t=cS.call(e,as),n=e[as];try{e[as]=void 0;var r=!0}catch{}var s=lS.call(e);return r&&(t?e[as]=n:delete e[as]),s}var dS=Object.prototype,hS=dS.toString;function pS(e){return hS.call(e)}var fS="[object Null]",mS="[object Undefined]",Ju=Kr?Kr.toStringTag:void 0;function Ks(e){return e==null?e===void 0?mS:fS:Ju&&Ju in Object(e)?uS(e):pS(e)}function xs(e){return e!=null&&typeof e=="object"}var Wa=Array.isArray;function tf(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var gS="[object AsyncFunction]",yS="[object Function]",_S="[object GeneratorFunction]",wS="[object Proxy]";function nf(e){if(!tf(e))return!1;var t=Ks(e);return t==yS||t==_S||t==gS||t==wS}var ro=ln["__core-js_shared__"],Ku=(function(){var e=/[^.]+$/.exec(ro&&ro.keys&&ro.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function vS(e){return!!Ku&&Ku in e}var bS=Function.prototype,SS=bS.toString;function nr(e){if(e!=null){try{return SS.call(e)}catch{}try{return e+""}catch{}}return""}var TS=/[\\^$.*+?()[\]{}|]/g,ES=/^\[object .+?Constructor\]$/,CS=Function.prototype,AS=Object.prototype,kS=CS.toString,OS=AS.hasOwnProperty,xS=RegExp("^"+kS.call(OS).replace(TS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function IS(e){if(!tf(e)||vS(e))return!1;var t=nf(e)?xS:ES;return t.test(nr(e))}function PS(e,t){return e?.[t]}function ns(e,t){var n=PS(e,t);return IS(n)?n:void 0}var Xo=ns(ln,"WeakMap"),NS=9007199254740991,MS=/^(?:0|[1-9]\d*)$/;function RS(e,t){var n=typeof e;return t=t??NS,!!t&&(n=="number"||n!="symbol"&&MS.test(e))&&e>-1&&e%1==0&&e<t}function rf(e,t){return e===t||e!==e&&t!==t}var $S=9007199254740991;function sf(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=$S}function LS(e){return e!=null&&sf(e.length)&&!nf(e)}var jS=Object.prototype;function DS(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||jS;return e===n}function US(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}var FS="[object Arguments]";function Zu(e){return xs(e)&&Ks(e)==FS}var af=Object.prototype,BS=af.hasOwnProperty,zS=af.propertyIsEnumerable,HS=Zu((function(){return arguments})())?Zu:function(e){return xs(e)&&BS.call(e,"callee")&&!zS.call(e,"callee")};function VS(){return!1}var of=typeof exports=="object"&&exports&&!exports.nodeType&&exports,qu=of&&typeof module=="object"&&module&&!module.nodeType&&module,GS=qu&&qu.exports===of,Yu=GS?ln.Buffer:void 0,WS=Yu?Yu.isBuffer:void 0,Qo=WS||VS,JS="[object Arguments]",KS="[object Array]",ZS="[object Boolean]",qS="[object Date]",YS="[object Error]",XS="[object Function]",QS="[object Map]",eT="[object Number]",tT="[object Object]",nT="[object RegExp]",rT="[object Set]",sT="[object String]",aT="[object WeakMap]",iT="[object ArrayBuffer]",oT="[object DataView]",cT="[object Float32Array]",lT="[object Float64Array]",uT="[object Int8Array]",dT="[object Int16Array]",hT="[object Int32Array]",pT="[object Uint8Array]",fT="[object Uint8ClampedArray]",mT="[object Uint16Array]",gT="[object Uint32Array]",le={};le[cT]=le[lT]=le[uT]=le[dT]=le[hT]=le[pT]=le[fT]=le[mT]=le[gT]=!0;le[JS]=le[KS]=le[iT]=le[ZS]=le[oT]=le[qS]=le[YS]=le[XS]=le[QS]=le[eT]=le[tT]=le[nT]=le[rT]=le[sT]=le[aT]=!1;function yT(e){return xs(e)&&sf(e.length)&&!!le[Ks(e)]}function _T(e){return function(t){return e(t)}}var cf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ms=cf&&typeof module=="object"&&module&&!module.nodeType&&module,wT=ms&&ms.exports===cf,so=wT&&Qp.process,Xu=(function(){try{var e=ms&&ms.require&&ms.require("util").types;return e||so&&so.binding&&so.binding("util")}catch{}})(),Qu=Xu&&Xu.isTypedArray,lf=Qu?_T(Qu):yT,vT=Object.prototype,bT=vT.hasOwnProperty;function ST(e,t){var n=Wa(e),r=!n&&HS(e),s=!n&&!r&&Qo(e),a=!n&&!r&&!s&&lf(e),i=n||r||s||a,o=i?US(e.length,String):[],c=o.length;for(var l in e)bT.call(e,l)&&!(i&&(l=="length"||s&&(l=="offset"||l=="parent")||a&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||RS(l,c)))&&o.push(l);return o}function TT(e,t){return function(n){return e(t(n))}}var ET=TT(Object.keys,Object),CT=Object.prototype,AT=CT.hasOwnProperty;function kT(e){if(!DS(e))return ET(e);var t=[];for(var n in Object(e))AT.call(e,n)&&n!="constructor"&&t.push(n);return t}function OT(e){return LS(e)?ST(e):kT(e)}var Is=ns(Object,"create");function xT(){this.__data__=Is?Is(null):{},this.size=0}function IT(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var PT="__lodash_hash_undefined__",NT=Object.prototype,MT=NT.hasOwnProperty;function RT(e){var t=this.__data__;if(Is){var n=t[e];return n===PT?void 0:n}return MT.call(t,e)?t[e]:void 0}var $T=Object.prototype,LT=$T.hasOwnProperty;function jT(e){var t=this.__data__;return Is?t[e]!==void 0:LT.call(t,e)}var DT="__lodash_hash_undefined__";function UT(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=Is&&t===void 0?DT:t,this}function Zn(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Zn.prototype.clear=xT;Zn.prototype.delete=IT;Zn.prototype.get=RT;Zn.prototype.has=jT;Zn.prototype.set=UT;function FT(){this.__data__=[],this.size=0}function Ei(e,t){for(var n=e.length;n--;)if(rf(e[n][0],t))return n;return-1}var BT=Array.prototype,zT=BT.splice;function HT(e){var t=this.__data__,n=Ei(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():zT.call(t,n,1),--this.size,!0}function VT(e){var t=this.__data__,n=Ei(t,e);return n<0?void 0:t[n][1]}function GT(e){return Ei(this.__data__,e)>-1}function WT(e,t){var n=this.__data__,r=Ei(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}function un(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}un.prototype.clear=FT;un.prototype.delete=HT;un.prototype.get=VT;un.prototype.has=GT;un.prototype.set=WT;var Ps=ns(ln,"Map");function JT(){this.size=0,this.__data__={hash:new Zn,map:new(Ps||un),string:new Zn}}function KT(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Ci(e,t){var n=e.__data__;return KT(t)?n[typeof t=="string"?"string":"hash"]:n.map}function ZT(e){var t=Ci(this,e).delete(e);return this.size-=t?1:0,t}function qT(e){return Ci(this,e).get(e)}function YT(e){return Ci(this,e).has(e)}function XT(e,t){var n=Ci(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}function rr(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}rr.prototype.clear=JT;rr.prototype.delete=ZT;rr.prototype.get=qT;rr.prototype.has=YT;rr.prototype.set=XT;function QT(e,t){for(var n=-1,r=t.length,s=e.length;++n<r;)e[s+n]=t[n];return e}function eE(){this.__data__=new un,this.size=0}function tE(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}function nE(e){return this.__data__.get(e)}function rE(e){return this.__data__.has(e)}var sE=200;function aE(e,t){var n=this.__data__;if(n instanceof un){var r=n.__data__;if(!Ps||r.length<sE-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new rr(r)}return n.set(e,t),this.size=n.size,this}function Sn(e){var t=this.__data__=new un(e);this.size=t.size}Sn.prototype.clear=eE;Sn.prototype.delete=tE;Sn.prototype.get=nE;Sn.prototype.has=rE;Sn.prototype.set=aE;function iE(e,t){for(var n=-1,r=e==null?0:e.length,s=0,a=[];++n<r;){var i=e[n];t(i,n,e)&&(a[s++]=i)}return a}function oE(){return[]}var cE=Object.prototype,lE=cE.propertyIsEnumerable,ed=Object.getOwnPropertySymbols,uE=ed?function(e){return e==null?[]:(e=Object(e),iE(ed(e),function(t){return lE.call(e,t)}))}:oE;function dE(e,t,n){var r=t(e);return Wa(e)?r:QT(r,n(e))}function td(e){return dE(e,OT,uE)}var ec=ns(ln,"DataView"),tc=ns(ln,"Promise"),nc=ns(ln,"Set"),nd="[object Map]",hE="[object Object]",rd="[object Promise]",sd="[object Set]",ad="[object WeakMap]",id="[object DataView]",pE=nr(ec),fE=nr(Ps),mE=nr(tc),gE=nr(nc),yE=nr(Xo),fn=Ks;(ec&&fn(new ec(new ArrayBuffer(1)))!=id||Ps&&fn(new Ps)!=nd||tc&&fn(tc.resolve())!=rd||nc&&fn(new nc)!=sd||Xo&&fn(new Xo)!=ad)&&(fn=function(e){var t=Ks(e),n=t==hE?e.constructor:void 0,r=n?nr(n):"";if(r)switch(r){case pE:return id;case fE:return nd;case mE:return rd;case gE:return sd;case yE:return ad}return t});var od=ln.Uint8Array,_E="__lodash_hash_undefined__";function wE(e){return this.__data__.set(e,_E),this}function vE(e){return this.__data__.has(e)}function Ja(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new rr;++t<n;)this.add(e[t])}Ja.prototype.add=Ja.prototype.push=wE;Ja.prototype.has=vE;function bE(e,t){for(var n=-1,r=e==null?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}function SE(e,t){return e.has(t)}var TE=1,EE=2;function uf(e,t,n,r,s,a){var i=n&TE,o=e.length,c=t.length;if(o!=c&&!(i&&c>o))return!1;var l=a.get(e),u=a.get(t);if(l&&u)return l==t&&u==e;var d=-1,h=!0,p=n&EE?new Ja:void 0;for(a.set(e,t),a.set(t,e);++d<o;){var f=e[d],y=t[d];if(r)var S=i?r(y,f,d,t,e,a):r(f,y,d,e,t,a);if(S!==void 0){if(S)continue;h=!1;break}if(p){if(!bE(t,function(b,v){if(!SE(p,v)&&(f===b||s(f,b,n,r,a)))return p.push(v)})){h=!1;break}}else if(!(f===y||s(f,y,n,r,a))){h=!1;break}}return a.delete(e),a.delete(t),h}function CE(e){var t=-1,n=Array(e.size);return e.forEach(function(r,s){n[++t]=[s,r]}),n}function AE(e){var t=-1,n=Array(e.size);return e.forEach(function(r){n[++t]=r}),n}var kE=1,OE=2,xE="[object Boolean]",IE="[object Date]",PE="[object Error]",NE="[object Map]",ME="[object Number]",RE="[object RegExp]",$E="[object Set]",LE="[object String]",jE="[object Symbol]",DE="[object ArrayBuffer]",UE="[object DataView]",cd=Kr?Kr.prototype:void 0,ao=cd?cd.valueOf:void 0;function FE(e,t,n,r,s,a,i){switch(n){case UE:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case DE:return!(e.byteLength!=t.byteLength||!a(new od(e),new od(t)));case xE:case IE:case ME:return rf(+e,+t);case PE:return e.name==t.name&&e.message==t.message;case RE:case LE:return e==t+"";case NE:var o=CE;case $E:var c=r&kE;if(o||(o=AE),e.size!=t.size&&!c)return!1;var l=i.get(e);if(l)return l==t;r|=OE,i.set(e,t);var u=uf(o(e),o(t),r,s,a,i);return i.delete(e),u;case jE:if(ao)return ao.call(e)==ao.call(t)}return!1}var BE=1,zE=Object.prototype,HE=zE.hasOwnProperty;function VE(e,t,n,r,s,a){var i=n&BE,o=td(e),c=o.length,l=td(t),u=l.length;if(c!=u&&!i)return!1;for(var d=c;d--;){var h=o[d];if(!(i?h in t:HE.call(t,h)))return!1}var p=a.get(e),f=a.get(t);if(p&&f)return p==t&&f==e;var y=!0;a.set(e,t),a.set(t,e);for(var S=i;++d<c;){h=o[d];var b=e[h],v=t[h];if(r)var w=i?r(v,b,h,t,e,a):r(b,v,h,e,t,a);if(!(w===void 0?b===v||s(b,v,n,r,a):w)){y=!1;break}S||(S=h=="constructor")}if(y&&!S){var E=e.constructor,A=t.constructor;E!=A&&"constructor"in e&&"constructor"in t&&!(typeof E=="function"&&E instanceof E&&typeof A=="function"&&A instanceof A)&&(y=!1)}return a.delete(e),a.delete(t),y}var GE=1,ld="[object Arguments]",ud="[object Array]",ua="[object Object]",WE=Object.prototype,dd=WE.hasOwnProperty;function JE(e,t,n,r,s,a){var i=Wa(e),o=Wa(t),c=i?ud:fn(e),l=o?ud:fn(t);c=c==ld?ua:c,l=l==ld?ua:l;var u=c==ua,d=l==ua,h=c==l;if(h&&Qo(e)){if(!Qo(t))return!1;i=!0,u=!1}if(h&&!u)return a||(a=new Sn),i||lf(e)?uf(e,t,n,r,s,a):FE(e,t,c,n,r,s,a);if(!(n&GE)){var p=u&&dd.call(e,"__wrapped__"),f=d&&dd.call(t,"__wrapped__");if(p||f){var y=p?e.value():e,S=f?t.value():t;return a||(a=new Sn),s(y,S,n,r,a)}}return h?(a||(a=new Sn),VE(e,t,n,r,s,a)):!1}function df(e,t,n,r,s){return e===t?!0:e==null||t==null||!xs(e)&&!xs(t)?e!==e&&t!==t:JE(e,t,n,r,df,s)}function KE(e,t){return df(e,t)}class ZE{capture(){}shutdown(){return Promise.resolve()}}const qE=Symbol("Let zodToJsonSchema decide on which parser to use"),YE={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},XE=e=>({...YE,...e}),QE=e=>{const t=XE(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}};function hf(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function ae(e,t,n,r,s){e[t]=n,hf(e,t,r,s)}const pf=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function it(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?pf(t,e.currentPath):t.join("/")}}function eC(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==R.ZodAny&&(n.items=ee(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ae(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ae(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ae(n,"minItems",e.exactLength.value,e.exactLength.message,t),ae(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function tC(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":t.target==="jsonSchema7"?r.inclusive?ae(n,"minimum",r.value,r.message,t):ae(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,t):ae(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,t));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,t);break}return n}function nC(){return{type:"boolean"}}function ff(e,t){return ee(e.type._def,t)}const rC=(e,t)=>ee(e.innerType._def,t);function mf(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,a)=>mf(e,t,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return sC(e,t)}}const sC=(e,t)=>{const n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(const r of e.checks)switch(r.kind){case"min":ae(n,"minimum",r.value,r.message,t);break;case"max":ae(n,"maximum",r.value,r.message,t);break}return n};function aC(e,t){return{...ee(e.innerType._def,t),default:e.defaultValue()}}function iC(e,t){return t.effectStrategy==="input"?ee(e.schema._def,t):it(t)}function oC(e){return{type:"string",enum:Array.from(e.values)}}const cC=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function lC(e,t){const n=[ee(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ee(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a);let r=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(a=>{if(cC(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function uC(e,t){const n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}let io;const xt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(io===void 0&&(io=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),io),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function gf(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":ae(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":It(n,"email",r.message,t);break;case"format:idn-email":It(n,"idn-email",r.message,t);break;case"pattern:zod":Ve(n,xt.email,r.message,t);break}break;case"url":It(n,"uri",r.message,t);break;case"uuid":It(n,"uuid",r.message,t);break;case"regex":Ve(n,r.regex,r.message,t);break;case"cuid":Ve(n,xt.cuid,r.message,t);break;case"cuid2":Ve(n,xt.cuid2,r.message,t);break;case"startsWith":Ve(n,RegExp(`^${oo(r.value,t)}`),r.message,t);break;case"endsWith":Ve(n,RegExp(`${oo(r.value,t)}$`),r.message,t);break;case"datetime":It(n,"date-time",r.message,t);break;case"date":It(n,"date",r.message,t);break;case"time":It(n,"time",r.message,t);break;case"duration":It(n,"duration",r.message,t);break;case"length":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t),ae(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":{Ve(n,RegExp(oo(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&It(n,"ipv4",r.message,t),r.version!=="v4"&&It(n,"ipv6",r.message,t);break}case"base64url":Ve(n,xt.base64url,r.message,t);break;case"jwt":Ve(n,xt.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&Ve(n,xt.ipv4Cidr,r.message,t),r.version!=="v4"&&Ve(n,xt.ipv6Cidr,r.message,t);break}case"emoji":Ve(n,xt.emoji(),r.message,t);break;case"ulid":{Ve(n,xt.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{It(n,"binary",r.message,t);break}case"contentEncoding:base64":{ae(n,"contentEncoding","base64",r.message,t);break}case"pattern:zod":{Ve(n,xt.base64,r.message,t);break}}break}case"nanoid":Ve(n,xt.nanoid,r.message,t)}return n}function oo(e,t){return t.patternStrategy==="escape"?hC(e):e}const dC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function hC(e){let t="";for(let n=0;n<e.length;n++)dC.has(e[n])||(t+="\\"),t+=e[n];return t}function It(e,t,n,r){e.format||e.anyOf?.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):ae(e,"format",t,n,r)}function Ve(e,t,n,r){e.pattern||e.allOf?.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:hd(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ae(e,"pattern",hd(t,r),n,r)}function hd(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,o=!1;for(let c=0;c<r.length;c++){if(a){s+=r[c],a=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){o?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),o=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],o=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){s+=`(^|(?<=[\r
90
- ]))`;continue}else if(r[c]==="$"){s+=`($|(?=[\r
91
- ]))`;continue}}if(n.s&&r[c]==="."){s+=i?`${r[c]}\r
92
- `:`[${r[c]}\r
93
- ]`;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 yf(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===R.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,s)=>({...r,[s]: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===R.ZodString&&e.keyType._def.checks?.length){const{type:r,...s}=gf(e.keyType._def,t);return{...n,propertyNames:s}}else{if(e.keyType?._def.typeName===R.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===R.ZodBranded&&e.keyType._def.type._def.typeName===R.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...s}=ff(e.keyType._def,t);return{...n,propertyNames:s}}}return n}function pC(e,t){if(t.mapStrategy==="record")return yf(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 fC(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 mC(e){return e.target==="openAi"?void 0:{not:it({...e,currentPath:[...e.currentPath,"not"]})}}function gC(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ka={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function yC(e,t){if(t.target==="openApi3")return pd(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Ka&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,a)=>{const i=Ka[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 pd(e,t)}const pd=(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 _C(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:Ka[e.innerType._def.typeName],nullable:!0}:{type:[Ka[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 wC(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",hf(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 vC(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=SC(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=bC(e,t);return i!==void 0&&(r.additionalProperties=i),r}function bC(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 SC(e){try{return e.isOptional()}catch{return!0}}const TC=(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)},EC=(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 CC(e,t){return ee(e.type._def,t)}function AC(e,t){const r={type:"array",uniqueItems:!0,items:ee(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 kC(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 OC(e){return{not:it(e)}}function xC(e){return it(e)}const IC=(e,t)=>ee(e.innerType._def,t),PC=(e,t,n)=>{switch(t){case R.ZodString:return gf(e,n);case R.ZodNumber:return wC(e,n);case R.ZodObject:return vC(e,n);case R.ZodBigInt:return tC(e,n);case R.ZodBoolean:return nC();case R.ZodDate:return mf(e,n);case R.ZodUndefined:return OC(n);case R.ZodNull:return gC(n);case R.ZodArray:return eC(e,n);case R.ZodUnion:case R.ZodDiscriminatedUnion:return yC(e,n);case R.ZodIntersection:return lC(e,n);case R.ZodTuple:return kC(e,n);case R.ZodRecord:return yf(e,n);case R.ZodLiteral:return uC(e,n);case R.ZodEnum:return oC(e);case R.ZodNativeEnum:return fC(e);case R.ZodNullable:return _C(e,n);case R.ZodOptional:return TC(e,n);case R.ZodMap:return pC(e,n);case R.ZodSet:return AC(e,n);case R.ZodLazy:return()=>e.getter()._def;case R.ZodPromise:return CC(e,n);case R.ZodNaN:case R.ZodNever:return mC(n);case R.ZodEffects:return iC(e,n);case R.ZodAny:return it(n);case R.ZodUnknown:return xC(n);case R.ZodDefault:return aC(e,n);case R.ZodBranded:return ff(e,n);case R.ZodReadonly:return IC(e,n);case R.ZodCatch:return rC(e,n);case R.ZodPipeline:return EC(e,n);case R.ZodFunction:case R.ZodVoid:case R.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!==qE)return o}if(r&&!n){const o=NC(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=PC(e,e.typeName,t),i=typeof a=="function"?ee(a(),t):a;if(i&&MC(e,t,i),t.postProcess){const o=t.postProcess(i,e,t);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const NC=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:pf(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}},MC=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),ya=(e,t)=>{const n=QE(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 RC=Object.defineProperty,_f=(e,t)=>{for(var n in t)RC(e,n,{get:t[n],enumerable:!0})};const Za=(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 wf(e,t){return Array.isArray(e)?fd(e,t):at.from(n=>fd(n,e))}function fd(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&&Za(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&&Za(l,s)||i&&l.id&&i.some(u=>u===l.id))&&c.push(l):c.push(l)}return c}function $C(e){return Array.isArray(e)?md(e):at.from(md)}function md(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=Ua(s),i=Ua(r),o=a.concat(i);typeof a.content=="string"&&typeof i.content=="string"&&(o.content=`${a.content}
94
- ${i.content}`),t.push(jC(o))}}return t}function Sl(e,t){if(Array.isArray(e)){const n=e;if(!t)throw new Error("Options parameter is required when providing messages.");return gd(n,t)}else{const n=e;return at.from(r=>gd(r,n)).withConfig({runName:"trim_messages"})}}async function gd(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,y)=>f+y,0):u=async h=>r(h);let d=bf;if(l&&("splitText"in l?d=l.splitText:d=async h=>l(h)),s==="first")return vf(e,{maxTokens:n,tokenCounter:u,textSplitter:d,partialStrategy:a?"first":void 0,endOn:i});if(s==="last")return LC(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 vf(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),y=Object.fromEntries(Object.entries(u).filter(([v])=>v!=="type"&&!v.startsWith("lc_"))),S=Tl(u.getType(),{...y,content:f}),b=[...o.slice(0,c),S];if(await r(b)<=n)o=b,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&&!Za(o[c-1],l);)c-=1}return o.slice(0,c)}async function LC(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 Tl(u.getType(),d,bs(u))});if(s){const u=Array.isArray(s)?s:[s];for(;o.length>0&&!Za(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 vf(l,{...i,partialStrategy:n?"last":void 0,endOn:a}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}const yd={human:{message:de,messageChunk:Vs},ai:{message:D,messageChunk:mt},system:{message:fe,messageChunk:Kn},developer:{message:fe,messageChunk:Kn},tool:{message:X,messageChunk:Hs},function:{message:hi,messageChunk:pi},generic:{message:Qn,messageChunk:di},remove:{message:vn,messageChunk:vn}};function Tl(e,t,n){let r,s;switch(e){case"human":n?r=new Vs(t):s=new de(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 mt(a)}else s=new D(t);break;case"system":n?r=new Kn(t):s=new fe(t);break;case"developer":n?r=new Kn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):s=new fe({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in t)n?r=new Hs(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 pi(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");s=new hi(t)}break;case"generic":if("role"in t)n?r=new di(t):s=new Qn(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 jC(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 yd&&(n=Tl(t,r)),!n)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(yd)}`);return n}function bf(e){const t=e.split(`
95
- `);return Promise.resolve([...t.slice(0,-1).map(n=>`${n}
96
- `),t[t.length-1]])}const DC=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],UC=["image","video","audio","text-plain","file"],FC=["text","reasoning",...DC,...UC];var Sf={};F(Sf,{AIMessage:()=>D,AIMessageChunk:()=>mt,BaseMessage:()=>tt,BaseMessageChunk:()=>Nn,ChatMessage:()=>Qn,ChatMessageChunk:()=>di,FunctionMessage:()=>hi,FunctionMessageChunk:()=>pi,HumanMessage:()=>de,HumanMessageChunk:()=>Vs,KNOWN_BLOCK_TYPES:()=>FC,RemoveMessage:()=>vn,SystemMessage:()=>fe,SystemMessageChunk:()=>Kn,ToolMessage:()=>X,ToolMessageChunk:()=>Hs,_isMessageFieldWithRole:()=>yh,_mergeDicts:()=>Ue,_mergeLists:()=>zs,_mergeObj:()=>gh,_mergeStatus:()=>mh,coerceMessageLikeToMessage:()=>Gt,convertToChunk:()=>Ua,convertToOpenAIImageBlock:()=>dh,convertToProviderContentBlock:()=>ow,defaultTextSplitter:()=>bf,defaultToolCallParser:()=>Gc,filterMessages:()=>wf,getBufferString:()=>Zc,iife:()=>zw,isAIMessage:()=>Kc,isAIMessageChunk:()=>Ro,isBase64ContentBlock:()=>Bc,isBaseMessage:()=>Ie,isBaseMessageChunk:()=>bs,isChatMessage:()=>Rw,isChatMessageChunk:()=>$w,isDataContentBlock:()=>kn,isDirectToolOutput:()=>Vc,isFunctionMessage:()=>Lw,isFunctionMessageChunk:()=>jw,isHumanMessage:()=>Dw,isHumanMessageChunk:()=>Uw,isIDContentBlock:()=>uh,isMessage:()=>fh,isOpenAIToolCallArray:()=>Ew,isPlainTextContentBlock:()=>aw,isSystemMessage:()=>Fw,isSystemMessageChunk:()=>Bw,isToolMessage:()=>Wc,isToolMessageChunk:()=>wh,isURLContentBlock:()=>Fc,mapChatMessagesToStoredMessages:()=>Jw,mapStoredMessageToChatMessage:()=>qc,mapStoredMessagesToChatMessages:()=>Ww,mergeContent:()=>Xn,mergeMessageRuns:()=>$C,mergeResponseMetadata:()=>bh,mergeUsageMetadata:()=>Th,parseBase64DataUrl:()=>No,parseMimeType:()=>iw,trimMessages:()=>Sl});var Ns=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=xn(r,a)}catch{r=void 0,s=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new ll(new ts({steps:e}))}};const BC=e=>e();function co(e){const t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var Tf={};F(Tf,{BaseChatModel:()=>sr,SimpleChatModel:()=>zC});function lo(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];(Fc(a)||Bc(a))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,s),dh(a),...n.content.slice(s+1)]}))}t.push(r)}return t}var sr=class Ln extends Si{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(t){super(t),this.outputVersion=BC(()=>{const n=t.outputVersion??nn("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(),[lo(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 y=d?.at(0)?.runId;y!=null&&f.message._updateId(`run-${y}`)}f.message.response_metadata={...f.generationInfo,...f.message.response_metadata},u==="v1"?yield co(f.message):yield f.message,h?h=h.concat(f):h=f,Ro(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(y=>y?.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(lo),r.runId,void 0,f,void 0,void 0,r.runName)}const o=n.outputVersion??this.outputVersion,c=[],l=[];if(!!i?.[0].handlers.find(Yc)&&!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 y of h){if(y.message.id==null){const S=i?.at(0)?.runId;S!=null&&y.message._updateId(`run-${S}`)}p===void 0?p=y:p=xn(p,y),Ro(y.message)&&y.message.usage_metadata!==void 0&&(f={tokenUsage:{promptTokens:y.message.usage_metadata.input_tokens,completionTokens:y.message.usage_metadata.output_tokens,totalTokens:y.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 y=await this._generate(p,{...n,promptIndex:f},i?.[f]);if(o==="v1")for(const S of y.generations)S.message=co(S.message);return y}));await Promise.all(h.map(async(p,f)=>{if(p.status==="fulfilled"){const y=p.value;for(const S of y.generations){if(S.message.id==null){const b=i?.at(0)?.runId;b!=null&&S.message._updateId(`run-${b}`)}S.message.response_metadata={...S.generationInfo,...S.message.response_metadata}}return y.generations.length===1&&(y.generations[0].message.response_metadata={...y.llmOutput,...y.generations[0].message.response_metadata}),c[f]=y.generations,l[f]=y.llmOutput,i?.[f]?.handleLLMEnd({generations:[y.generations],llmOutput:y.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,ks,{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(b=>b.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(lo),a.runId,void 0,l,void 0,void 0,a.runName),d=[],p=(await Promise.allSettled(i.map(async(b,v)=>{const w=Ln._convertInputToPromptValue(b).toString(),E=await n.lookup(w,r);return E==null&&d.push(v),E}))).map((b,v)=>({result:b,runManager:u?.[v]})).filter(({result:b})=>b.status==="fulfilled"&&b.value!=null||b.status==="rejected"),f=s.outputVersion??this.outputVersion,y=[];await Promise.all(p.map(async({result:b,runManager:v},w)=>{if(b.status==="fulfilled"){const E=b.value;return y[w]=E.map(A=>("message"in A&&Ie(A.message)&&Kc(A.message)&&(A.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},f==="v1"&&(A.message=co(A.message))),A.generationInfo={...A.generationInfo,tokenUsage:{}},A)),E.length&&await v?.handleLLMNewToken(E[0].text),v?.handleLLMEnd({generations:[E]},void 0,void 0,void 0,{cached:!0})}else return await v?.handleLLMError(b.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(b.reason)}));const S={generations:y,missingPromptIndices:d,startedRunManagers:u};return Object.defineProperty(S,ks,{value:u?{runIds:u?.map(b=>b.runId)}:void 0,configurable:!0}),S}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(y=>a[y]),o,i,h!==void 0?d.map(y=>h?.[y]):void 0);await Promise.all(f.generations.map(async(y,S)=>{const b=d[S];u[b]=y;const v=Ln._convertInputToPromptValue(a[b]).toString();return c.update(v,l,y)})),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=Vr(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;er(r)?l=[{type:"function",function:{name:c,description:a,parameters:ft(r)}}]:("name"in r&&(c=r.name),l=[{type:"function",function:{name:c,description:a,parameters:r}}]);const u=this.bindTools(l),d=at.from(y=>{if(!mt.isInstance(y))throw new Error("Input is not an AIMessageChunk.");if(!y.tool_calls||y.tool_calls.length===0)throw new Error("No tool calls found in the response.");const S=y.tool_calls.find(b=>b.name===c);if(!S)throw new Error(`No tool call found with name ${c}.`);return S.args});if(!o)return u.pipe(d).withConfig({runName:"StructuredOutput"});const h=Ns.assign({parsed:(y,S)=>d.invoke(y.raw,S)}),p=Ns.assign({parsed:()=>null}),f=h.withFallbacks({fallbacks:[p]});return Et.from([{raw:u},f]).withConfig({runName:"StructuredOutputRunnable"})}},zC=class extends sr{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}]}}},HC=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,y)=>i[y].invoke(f,o[y])),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)}},VC=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])=>[$e(s),$e(a)]),r=$e(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 nt(t))?.handleChainStart(this.toJSON(),Ae(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=xn(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=xn(s,o)}catch{s=void 0,a=!1}}}catch(o){throw await r?.handleChainError(o),o}await r?.handleChainEnd(s??{})}},GC=class extends De{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=at.from((a,i)=>this._enterHistory(a,i??{})).withConfig({runName:"loadHistory"});const n=e.historyMessagesKey??e.inputMessagesKey;n&&(t=Ns.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)&&!Ie(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 de(t)];if(Array.isArray(t))return t;if(Ie(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
97
- Got ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!Ie(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(Ie(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()
98
- eg. chain.invoke(${JSON.stringify(r)}, ${JSON.stringify(s)})`)}const{sessionId:n}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(n),t}},Ef={};F(Ef,{RouterRunnable:()=>HC,Runnable:()=>J,RunnableAssign:()=>ll,RunnableBinding:()=>De,RunnableBranch:()=>VC,RunnableEach:()=>V0,RunnableLambda:()=>at,RunnableMap:()=>ts,RunnableParallel:()=>J0,RunnablePassthrough:()=>Ns,RunnablePick:()=>Up,RunnableRetry:()=>cl,RunnableSequence:()=>Et,RunnableToolLike:()=>Yo,RunnableWithFallbacks:()=>Dp,RunnableWithMessageHistory:()=>GC,_coerceToRunnable:()=>$e,ensureConfig:()=>K,getCallbackManagerForConfig:()=>nt,mergeConfigs:()=>pt,patchConfig:()=>ne,pickRunnableConfigKeys:()=>on});var WC={};_f(WC,{ConfigurableModel:()=>rc,MODEL_PROVIDER_CONFIG:()=>Ai,_inferModelProvider:()=>kf,getChatModelByClassName:()=>Af,initChatModel:()=>Zs});const Ai={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}},Cf=Object.keys(Ai);async function Af(e){const t=Object.entries(Ai).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")){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 JC(e,t,n={}){const r=t||kf(e);if(!r)throw new Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);const s=Ai[r];if(!s){const c=Cf.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
99
-
100
- Supported model providers are: ${c}`)}const{modelProvider:a,...i}=n,o=await Af(s.className);return new o({model:e,...i})}function kf(e){return e.startsWith("gpt-3")||e.startsWith("gpt-4")||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 rc=class _a extends sr{_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 JC(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 _a({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(t,...n)=>{const r={...this._queuedMethodOperations};return r.withStructuredOutput=[t,...n],new _a({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 _a({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new De({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,Fe.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 Fe.fromAsyncGenerator(a())}};async function Zs(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(":")];Cf.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 rc({defaultConfig:{...o,model:e,modelProvider:s},configPrefix:r}):(e&&(o.model=e),s&&(o.modelProvider=s),new rc({defaultConfig:o,configPrefix:r,configurableFields:i}))}var sc=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.")}},ac=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}},Of=class extends Error{toolName;errors;constructor(e,t){super(`Failed to parse structured output for tool '${e}':${t.map(n=>`
101
- - ${n}`).join("")}.`),this.toolName=e,this.errors=t}},El=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}
102
- Please fix the error and try again.`),this.toolCall=t,this.toolError=n}};function Cl(e){return"invoke"in e&&typeof e.invoke=="function"&&"_streamResponseChunks"in e}function qa(e){return typeof e=="object"&&e!=null&&"_queuedMethodOperations"in e&&"_model"in e&&typeof e._model=="function"}var xf={};F(xf,{extendInteropZodObject:()=>up,getInteropZodDefaultGetter:()=>_i,getInteropZodObjectShape:()=>Cs,getSchemaDescription:()=>Vr,interopParse:()=>bn,interopParseAsync:()=>gi,interopSafeParse:()=>$b,interopSafeParseAsync:()=>tl,interopZodObjectMakeFieldsOptional:()=>dp,interopZodObjectPartial:()=>sl,interopZodObjectPassthrough:()=>Bo,interopZodObjectStrict:()=>za,interopZodTransformInputSchema:()=>mr,isInteropZodLiteral:()=>Rb,isInteropZodObject:()=>Qe,isInteropZodSchema:()=>er,isShapelessZodSchema:()=>Lb,isSimpleStringZodSchema:()=>nl,isZodArrayV4:()=>yi,isZodLiteralV3:()=>cp,isZodLiteralV4:()=>lp,isZodObjectV3:()=>rl,isZodObjectV4:()=>Wt,isZodSchema:()=>Mb,isZodSchemaV3:()=>Se,isZodSchemaV4:()=>ge});let KC=0;var mn=class ic{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-${++KC}`}if(er(t)){const o=ft(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 ic(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=ft(t),i={type:"function",function:s};return new ic(a,i,n)}parse(t){const r=new Uc(this.schema).validate(t);if(!r.valid)throw new Of(this.name,r.errors.map(s=>s.error));return t}},Fn=class If{_schemaType;constructor(t){this.schema=t}static fromSchema(t){const n=ft(t);return new If(n)}parse(t){if(!(typeof t.content!="string"||t.content===""))try{const n=JSON.parse(t.content);return new Uc(this.schema).validate(n).valid?n:void 0}catch{}}};function Pf(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 mn||s instanceof Fn))return e;if(e.every(s=>Qe(s)))return e.map(s=>mn.fromSchema(s,t));if(e.every(s=>typeof s=="object"&&s!==null&&!Qe(s)))return e.map(s=>mn.fromSchema(s,t));throw new Error(`Invalid response format: list contains mixed types.
103
- All items must be either InteropZodObject or plain JSON schema objects.`)}if(e instanceof mn||e instanceof Fn)return[e];const r=Al(n);if(Qe(e))return r?[Fn.fromSchema(e)]:[mn.fromSchema(e,t)];if(typeof e=="object"&&e!==null&&"properties"in e)return r?[Fn.fromSchema(e)]:[mn.fromSchema(e,t)];throw new Error(`Invalid response format: ${String(e)}`)}function ZC(e,t){return Pf(e,t)}function qC(e){return Fn.fromSchema(e)}const YC=["ChatOpenAI","ChatXAI"],_d=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function Al(e){if(!e)return!1;if(typeof e=="string"){const n=e.split(":").pop();return _d.some(r=>n.includes(r))}if(qa(e))return Al(e._defaultConfig.model);if(!Cl(e))return!1;const t=e.getName();return!!(t==="FakeToolCallingChatModel"||YC.includes(t)&&("model"in e&&_d.some(n=>typeof e.model=="string"&&e.model.includes(n))||t==="FakeToolCallingModel"&&"structuredResponse"in e))}function kl(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 _n(e){if(!(!e||typeof e=="function"))return e.canJumpTo}function ki(e){return typeof e=="function"?e:e.hook}function Ct(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 Nf(e){return S_({clockseq:e})}function yr(e,t){const n=t.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return ws(e,new Uint8Array(n))}const XC="__error__",wa="__scheduled__",QC="__interrupt__",eA="__resume__";var wd="[...]",tA="[Circular]",Ya=[],_r=[];function nA(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function rA(e,t,n,r){typeof r>"u"&&(r=nA()),oc(e,"",0,[],void 0,0,r);var s;try{_r.length===0?s=JSON.stringify(e,t,n):s=JSON.stringify(e,sA(t),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Ya.length!==0;){var a=Ya.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return s}function uo(e,t,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:e}),Ya.push([r,n,t,s])):_r.push([t,n,e]):(r[n]=e,Ya.push([r,n,t]))}function oc(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){uo(tA,e,t,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){uo(wd,e,t,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){uo(wd,e,t,s);return}if(r.push(e),Array.isArray(e))for(o=0;o<e.length;o++)oc(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];oc(e[l],l,o,r,e,a,i)}}r.pop()}}function sA(e){return e=typeof e<"u"?e:function(t,n){return n},function(t,n){if(_r.length>0)for(var r=0;r<_r.length;r++){var s=_r[r];if(s[1]===t&&s[0]===n){n=s[2],_r.splice(r,1);break}}return e.call(this,t,n)}}const aA=[];var iA={},Mf={};F(Mf,{BaseChatMessageHistory:()=>Rf,BaseListChatMessageHistory:()=>Ol,InMemoryChatMessageHistory:()=>oA});var Rf=class extends Tt{async addMessages(e){for(const t of e)await this.addMessage(t)}},Ol=class extends Tt{addUserMessage(e){return this.addMessage(new de(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.")}},oA=class extends Ol{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=[]}},$f={};F($f,{Embeddings:()=>xl});var xl=class{caller;constructor(e){this.caller=new Js(e??{})}},cA={},Lf={};F(Lf,{BaseMemory:()=>lA,getInputValue:()=>uA,getOutputValue:()=>dA,getPromptInputKey:()=>hA});var lA=class{};const jf=(e,t)=>{if(t!==void 0)return e[t];const n=Object.keys(e);if(n.length===1)return e[n[0]]},uA=(e,t)=>{const n=jf(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},dA=(e,t)=>{const n=jf(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 hA(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 Df={};F(Df,{BaseStore:()=>Uf,InMemoryStore:()=>Ff});var Uf=class extends Tt{},Ff=class extends Uf{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)}},Bf={};F(Bf,{BaseRetriever:()=>Il});var Il=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(Gs(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}}},zf={};F(zf,{SaveableVectorStore:()=>pA,VectorStore:()=>Pl,VectorStoreRetriever:()=>va});var va=class extends Il{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)}},Pl=class extends Tt{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 va({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 va({...i,searchKwargs:e.searchKwargs}):new va({...i})}}},pA=class extends Pl{static load(e,t){throw new Error("Not implemented")}},Hf={};F(Hf,{BaseDocumentLoader:()=>Vf});var Vf=class{},Gf={};F(Gf,{LangSmithLoader:()=>fA});var fA=class extends Vf{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??mA,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 mA(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var rn=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent!==void 0?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}},Wf=class extends J{lc_namespace=["langchain_core","documents","transformers"];invoke(e,t){return this.transformDocuments(e)}},gA=class extends Wf{async transformDocuments(e){const t=[];for(const n of e){const r=await this._transformDocument(n);t.push(r)}return t}},Jf={};F(Jf,{BaseDocumentTransformer:()=>Wf,Document:()=>rn,MappingDocumentTransformer:()=>gA});var Nl=class extends Tt{lc_namespace=["langchain_core","example_selectors","base"]},Kf=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},yA=class extends Kf{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 _A(e){return e._modelType()==="base_llm"}function wA(e){return e._modelType()==="base_chat_model"}function vd(e){return e.split(/\n| /).length}var vA=class Zf extends Nl{examples=[];examplePrompt;getTextLength=vd;maxLength=2048;exampleTextLengths=[];constructor(t){super(t),this.examplePrompt=t.examplePrompt,this.maxLength=t.maxLength??2048,this.getTextLength=t.getTextLength??vd}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 Zf(n);return await Promise.all(t.map(s=>r.addExample(s))),r}};function ho(e){return Object.keys(e).sort().map(t=>e[t])}var bA=class qf extends Nl{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=ho(n.reduce((s,a)=>({...s,[a]:t[a]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new rn({pageContent:r,metadata:t})])}async selectExamples(t){const n=this.inputKeys??Object.keys(t),r=ho(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=>ho(a?a.reduce((l,u)=>({...l,[u]:c[u]}),{}):c).join(" ")),o=await r.fromTexts(i,t,n,s);return new qf({vectorStore:o,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},Yf={};F(Yf,{BaseExampleSelector:()=>Nl,BasePromptSelector:()=>Kf,ConditionalPromptSelector:()=>yA,LengthBasedExampleSelector:()=>vA,SemanticSimilarityExampleSelector:()=>bA,isChatModel:()=>wA,isLLM:()=>_A});var Xf={};F(Xf,{BaseLLM:()=>Qf,LLM:()=>Ml});var Qf=class ls extends Si{lc_namespace=["langchain","llms",this._llmType()];async invoke(t,n){const r=ls._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===ls.prototype._streamResponseChunks)yield this.invoke(t,n);else{const r=ls._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 Wr({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(Yc);let o;if(i&&t.length===1&&this._streamResponseChunks!==ls.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=xn(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,ks,{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(y,S)=>{const b=await n.lookup(y,r);return b==null&&u.push(S),b}))).map((y,S)=>({result:y,runManager:l?.[S]})).filter(({result:y})=>y.status==="fulfilled"&&y.value!=null||y.status==="rejected"),p=[];await Promise.all(h.map(async({result:y,runManager:S},b)=>{if(y.status==="fulfilled"){const v=y.value;return p[b]=v.map(w=>(w.generationInfo={...w.generationInfo,tokenUsage:{}},w)),v.length&&await S?.handleLLMNewToken(v[0].text),S?.handleLLMEnd({generations:[v]},void 0,void 0,void 0,{cached:!0})}else return await S?.handleLLMError(y.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(y.reason)}));const f={generations:p,missingPromptIndices:u,startedRunManagers:l};return Object.defineProperty(f,ks,{value:l?{runIds:l?.map(y=>y.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,y)=>{const S=u[y];return l[S]=f,o.update(t[S],c,f)})),h=p.llmOutput??{}}return{generations:l,llmOutput:h}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},Ml=class extends Qf{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}])))}}};const cc="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var SA=class extends Tt{lc_namespace=["langchain","recordmanagers"]},em=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=hl;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 rn({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 ws(t,cc)}_hashNestedDictToUUID(e){const t=JSON.stringify(e,Object.keys(e).sort()),n=this.keyEncoder(t);return ws(n,cc)}};function tm(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 nm(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 rm(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 sm=e=>"load"in e&&typeof e.load=="function"&&"loadAndSplit"in e&&typeof e.loadAndSplit=="function";async function TA(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=sm(t)?await t.load():t,d=rm(o??null),h=await n.getTime();let p=0,f=0,y=0,S=0;const b=tm(a??100,u);for(const v of b){const w=nm(v.map(x=>em.fromDocument(x))),E=w.map(x=>d(x));i==="incremental"&&w.forEach((x,M)=>{if(E[M]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const A=await n.exists(w.map(x=>x.uid)),I=[],k=[],g=[],N=new Set;if(w.forEach((x,M)=>{if(A[M])if(l)N.add(x.uid);else{g.push(x.uid);return}I.push(x.uid),k.push(x.toDocument())}),g.length>0&&(await n.update(g,{timeAtLeast:h}),S+=g.length),k.length>0&&(await r.addDocuments(k,{ids:I}),p+=k.length-N.size,y+=N.size),await n.update(w.map(x=>x.uid),{timeAtLeast:h,groupIds:E}),i==="incremental"){E.forEach(M=>{if(!M)throw new Error("Source id cannot be null")});const x=await n.listKeys({before:h,groupIds:E});x.length>0&&(await r.delete({ids:x}),await n.deleteKeys(x),f+=x.length)}}if(i==="full"){let v=await n.listKeys({before:h,limit:c});for(;v.length>0;)await r.delete({ids:v}),await n.deleteKeys(v),f+=v.length,v=await n.listKeys({before:h,limit:c})}return{numAdded:p,numDeleted:f,numUpdated:y,numSkipped:S}}var am={};F(am,{RecordManager:()=>SA,UUIDV5_NAMESPACE:()=>cc,_HashedDocument:()=>em,_batch:()=>tm,_deduplicateInOrder:()=>nm,_getSourceIdAssigner:()=>rm,_isBaseDocumentLoader:()=>sm,index:()=>TA});var im={};F(im,{applyPatch:()=>Gr,compare:()=>wi});var Oi=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"})}},qs=class extends Oi{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")}},sn=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");fi(this,"OUTPUT_PARSING_FAILURE")}},Ys=class extends qs{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"})}},Xs=class extends Ys{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(bs(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");s=new Jr({message:r,text:r.content})}else if(Ie(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");s=new Jr({message:Ua(r),text:r.content})}else s=new Wr({text:r});n===void 0?n=s:n=n.concat(s);const a=await this.parsePartialResult([n]);a!=null&&!rh(a,t)&&(this.diff?yield this._diff(t,a):yield a,t=a)}}getFormatInstructions(){return""}},EA=class extends Ys{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""}},Qs=class extends Ys{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]}},CA=class extends Qs{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 sn(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},AA=class extends Qs{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 sn(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===sn.prototype?t:new sn(`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\`)`}},kA=class extends Qs{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:
104
-
105
- 1. foo
106
-
107
- 2. bar
108
-
109
- 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},OA=class extends Qs{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:
110
-
111
- 1. foo
112
-
113
- 2. bar
114
-
115
- 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},xA=class extends Ys{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),"")}},om=class extends qs{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=te(Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Oe().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.
116
-
117
- "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
118
-
119
- For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
120
- 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.
121
- 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.
122
-
123
- 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!
124
-
125
- Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
126
- \`\`\`json
127
- ${JSON.stringify(ft(this.schema))}
128
- \`\`\`
129
- `}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 gi(this.schema,JSON.parse(r))}catch(t){throw new sn(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}},cm=class extends om{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:
130
- \`\`\`json
131
- ${this._schemaToInstruction(ft(this.schema)).replaceAll("{","{".repeat(t)).replaceAll("}","}".repeat(t))}
132
- \`\`\``}_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`{
133
- ${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(`
134
- `)}
135
- ${" ".repeat(t-2)}}${o}`}if(n.type==="array"&&n.items){const o=n.description?` // ${n.description}`:"";return`array[
136
- ${" ".repeat(t)}${this._schemaToInstruction(n.items,t+2)}
137
- ${" ".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(`
138
- ${" ".repeat(t-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=te(Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Oe().describe(r)])));return new this(t)}},IA=class extends qs{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new cm(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(n){throw new sn(`Failed to parse. Text: "${e}". Error: ${n}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},PA=class extends Xs{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?wi(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Mo(e[0].text)}async parse(e){return Mo(e,JSON.parse)}getFormatInstructions(){return""}};const NA=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 O=this;s(O),O.q=O.c="",O.bufferCheckPosition=e.MAX_BUFFER_LENGTH,O.opt=m||{},O.opt.lowercase=O.opt.lowercase||O.opt.lowercasetags,O.looseCase=O.opt.lowercase?"toLowerCase":"toUpperCase",O.tags=[],O.closed=O.closedRoot=O.sawRoot=!1,O.tag=O.error=null,O.strict=!!_,O.noscript=!!(_||O.opt.noscript),O.state=g.BEGIN,O.strictEntities=O.opt.strictEntities,O.ENTITIES=O.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),O.attribList=[],O.opt.xmlns&&(O.ns=Object.create(f)),O.trackPosition=O.opt.position!==!1,O.trackPosition&&(O.position=O.line=O.column=0),x(O,"onready")}Object.create||(Object.create=function(_){function m(){}m.prototype=_;var O=new m;return O}),Object.keys||(Object.keys=function(_){var m=[];for(var O in _)_.hasOwnProperty(O)&&m.push(O);return m});function r(_){for(var m=Math.max(e.MAX_BUFFER_LENGTH,10),O=0,C=0,re=t.length;C<re;C++){var Te=_[t[C]].length;if(Te>m)switch(t[C]){case"textNode":z(_);break;case"cdata":M(_,"oncdata",_.cdata),_.cdata="";break;case"script":M(_,"onscript",_.script),_.script="";break;default:he(_,"Max buffer length exceeded: "+t[C])}O=Math.max(O,Te)}var Ee=e.MAX_BUFFER_LENGTH-O;_.bufferCheckPosition=Ee+_.position}function s(_){for(var m=0,O=t.length;m<O;m++)_[t[m]]=""}function a(_){z(_),_.cdata!==""&&(M(_,"oncdata",_.cdata),_.cdata=""),_.script!==""&&(M(_,"onscript",_.script),_.script="")}n.prototype={end:function(){cr(this)},write:uy,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 O=this;this._parser.onend=function(){O.emit("end")},this._parser.onerror=function(C){O.emit("error",C),O._parser.error=null},this._decoder=null,o.forEach(function(C){Object.defineProperty(O,"on"+C,{get:function(){return O._parser["on"+C]},set:function(re){if(!re)return O.removeAllListeners(C),O._parser["on"+C]=re,re;O.on(C,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 O=this;return!O._parser["on"+_]&&o.indexOf(_)!==-1&&(O._parser["on"+_]=function(){var C=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);C.splice(0,0,_),O.emit.apply(O,C)}),i.prototype.on.call(O,_,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},y=/[:_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]/,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\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,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]/,v=/[#:_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 w(_){return _===" "||_===`
139
- `||_==="\r"||_===" "}function E(_){return _==='"'||_==="'"}function A(_){return _===">"||w(_)}function I(_,m){return _.test(m)}function k(_,m){return!I(_,m)}var g=0;e.STATE={BEGIN:g++,BEGIN_WHITESPACE:g++,TEXT:g++,TEXT_ENTITY:g++,OPEN_WAKA:g++,SGML_DECL:g++,SGML_DECL_QUOTED:g++,DOCTYPE:g++,DOCTYPE_QUOTED:g++,DOCTYPE_DTD:g++,DOCTYPE_DTD_QUOTED:g++,COMMENT_STARTING:g++,COMMENT:g++,COMMENT_ENDING:g++,COMMENT_ENDED:g++,CDATA:g++,CDATA_ENDING:g++,CDATA_ENDING_2:g++,PROC_INST:g++,PROC_INST_BODY:g++,PROC_INST_ENDING:g++,OPEN_TAG:g++,OPEN_TAG_SLASH:g++,ATTRIB:g++,ATTRIB_NAME:g++,ATTRIB_NAME_SAW_WHITE:g++,ATTRIB_VALUE:g++,ATTRIB_VALUE_QUOTED:g++,ATTRIB_VALUE_CLOSED:g++,ATTRIB_VALUE_UNQUOTED:g++,ATTRIB_VALUE_ENTITY_Q:g++,ATTRIB_VALUE_ENTITY_U:g++,CLOSE_TAG:g++,CLOSE_TAG_SAW_WHITE:g++,SCRIPT:g++,SCRIPT_ENDING:g++},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[_],O=typeof m=="number"?String.fromCharCode(m):m;e.ENTITIES[_]=O});for(var N in e.STATE)e.STATE[e.STATE[N]]=N;g=e.STATE;function x(_,m,O){_[m]&&_[m](O)}function M(_,m,O){_.textNode&&z(_),x(_,m,O)}function z(_){_.textNode=ce(_.opt,_.textNode),_.textNode&&x(_,"ontext",_.textNode),_.textNode=""}function ce(_,m){return _.trim&&(m=m.trim()),_.normalize&&(m=m.replace(/\s+/g," ")),m}function he(_,m){return z(_),_.trackPosition&&(m+=`
140
- Line: `+_.line+`
141
- Column: `+_.column+`
142
- Char: `+_.c),m=new Error(m),_.error=m,x(_,"onerror",m),_}function cr(_){return _.sawRoot&&!_.closedRoot&&q(_,"Unclosed root tag"),_.state!==g.BEGIN&&_.state!==g.BEGIN_WHITESPACE&&_.state!==g.TEXT&&he(_,"Unexpected end"),z(_),_.c="",_.closed=!0,x(_,"onend"),n.call(_,_.strict,_.opt),_}function q(_,m){if(typeof _!="object"||!(_ instanceof n))throw new Error("bad call to strictFail");_.strict&&he(_,m)}function Mi(_){_.strict||(_.tagName=_.tagName[_.looseCase]());var m=_.tags[_.tags.length-1]||_,O=_.tag={name:_.tagName,attributes:{}};_.opt.xmlns&&(O.ns=m.ns),_.attribList.length=0,M(_,"onopentagstart",O)}function ss(_,m){var O=_.indexOf(":"),C=O<0?["",_]:_.split(":"),re=C[0],Te=C[1];return m&&_==="xmlns"&&(re="xmlns",Te=""),{prefix:re,local:Te}}function Ri(_){if(_.strict||(_.attribName=_.attribName[_.looseCase]()),_.attribList.indexOf(_.attribName)!==-1||_.tag.attributes.hasOwnProperty(_.attribName)){_.attribName=_.attribValue="";return}if(_.opt.xmlns){var m=ss(_.attribName,!0),O=m.prefix,C=m.local;if(O==="xmlns")if(C==="xml"&&_.attribValue!==h)q(_,"xml: prefix must be bound to "+h+`
143
- Actual: `+_.attribValue);else if(C==="xmlns"&&_.attribValue!==p)q(_,"xmlns: prefix must be bound to "+p+`
144
- Actual: `+_.attribValue);else{var re=_.tag,Te=_.tags[_.tags.length-1]||_;re.ns===Te.ns&&(re.ns=Object.create(Te.ns)),re.ns[C]=_.attribValue}_.attribList.push([_.attribName,_.attribValue])}else _.tag.attributes[_.attribName]=_.attribValue,M(_,"onattribute",{name:_.attribName,value:_.attribValue});_.attribName=_.attribValue=""}function Rn(_,m){if(_.opt.xmlns){var O=_.tag,C=ss(_.tagName);O.prefix=C.prefix,O.local=C.local,O.uri=O.ns[C.prefix]||"",O.prefix&&!O.uri&&(q(_,"Unbound namespace prefix: "+JSON.stringify(_.tagName)),O.uri=C.prefix);var re=_.tags[_.tags.length-1]||_;O.ns&&re.ns!==O.ns&&Object.keys(O.ns).forEach(function(ru){M(_,"onopennamespace",{prefix:ru,uri:O.ns[ru]})});for(var Te=0,Ee=_.attribList.length;Te<Ee;Te++){var qe=_.attribList[Te],yt=qe[0],lr=qe[1],Ne=ss(yt,!0),Kt=Ne.prefix,dy=Ne.local,nu=Kt===""?"":O.ns[Kt]||"",Li={name:yt,value:lr,prefix:Kt,local:dy,uri:nu};Kt&&Kt!=="xmlns"&&!nu&&(q(_,"Unbound namespace prefix: "+JSON.stringify(Kt)),Li.uri=Kt),_.tag.attributes[yt]=Li,M(_,"onattribute",Li)}_.attribList.length=0}_.tag.isSelfClosing=!!m,_.sawRoot=!0,_.tags.push(_.tag),M(_,"onopentag",_.tag),m||(!_.noscript&&_.tagName.toLowerCase()==="script"?_.state=g.SCRIPT:_.state=g.TEXT,_.tag=null,_.tagName=""),_.attribName=_.attribValue="",_.attribList.length=0}function $i(_){if(!_.tagName){q(_,"Weird empty close tag."),_.textNode+="</>",_.state=g.TEXT;return}if(_.script){if(_.tagName!=="script"){_.script+="</"+_.tagName+">",_.tagName="",_.state=g.SCRIPT;return}M(_,"onscript",_.script),_.script=""}var m=_.tags.length,O=_.tagName;_.strict||(O=O[_.looseCase]());for(var C=O;m--;){var re=_.tags[m];if(re.name!==C)q(_,"Unexpected close tag");else break}if(m<0){q(_,"Unmatched closing tag: "+_.tagName),_.textNode+="</"+_.tagName+">",_.state=g.TEXT;return}_.tagName=O;for(var Te=_.tags.length;Te-- >m;){var Ee=_.tag=_.tags.pop();_.tagName=_.tag.name,M(_,"onclosetag",_.tagName);var qe={};for(var yt in Ee.ns)qe[yt]=Ee.ns[yt];var lr=_.tags[_.tags.length-1]||_;_.opt.xmlns&&Ee.ns!==lr.ns&&Object.keys(Ee.ns).forEach(function(Ne){var Kt=Ee.ns[Ne];M(_,"onclosenamespace",{prefix:Ne,uri:Kt})})}m===0&&(_.closedRoot=!0),_.tagName=_.attribValue=_.attribName="",_.attribList.length=0,_.state=g.TEXT}function Ql(_){var m=_.entity,O=m.toLowerCase(),C,re="";return _.ENTITIES[m]?_.ENTITIES[m]:_.ENTITIES[O]?_.ENTITIES[O]:(m=O,m.charAt(0)==="#"&&(m.charAt(1)==="x"?(m=m.slice(2),C=parseInt(m,16),re=C.toString(16)):(m=m.slice(1),C=parseInt(m,10),re=C.toString(10))),m=m.replace(/^0+/,""),isNaN(C)||re.toLowerCase()!==m?(q(_,"Invalid character entity"),"&"+_.entity+";"):String.fromCodePoint(C))}function eu(_,m){m==="<"?(_.state=g.OPEN_WAKA,_.startTagPosition=_.position):w(m)||(q(_,"Non-whitespace before first tag."),_.textNode=m,_.state=g.TEXT)}function tu(_,m){var O="";return m<_.length&&(O=_.charAt(m)),O}function uy(_){var m=this;if(this.error)throw this.error;if(m.closed)return he(m,"Cannot write after close. Assign an onready handler.");if(_===null)return cr(m);typeof _=="object"&&(_=_.toString());for(var O=0,C="";C=tu(_,O++),m.c=C,!!C;)switch(m.trackPosition&&(m.position++,C===`
145
- `?(m.line++,m.column=0):m.column++),m.state){case g.BEGIN:if(m.state=g.BEGIN_WHITESPACE,C==="\uFEFF")continue;eu(m,C);continue;case g.BEGIN_WHITESPACE:eu(m,C);continue;case g.TEXT:if(m.sawRoot&&!m.closedRoot){for(var re=O-1;C&&C!=="<"&&C!=="&";)C=tu(_,O++),C&&m.trackPosition&&(m.position++,C===`
146
- `?(m.line++,m.column=0):m.column++);m.textNode+=_.substring(re,O-1)}C==="<"&&!(m.sawRoot&&m.closedRoot&&!m.strict)?(m.state=g.OPEN_WAKA,m.startTagPosition=m.position):(!w(C)&&(!m.sawRoot||m.closedRoot)&&q(m,"Text data outside of root node."),C==="&"?m.state=g.TEXT_ENTITY:m.textNode+=C);continue;case g.SCRIPT:C==="<"?m.state=g.SCRIPT_ENDING:m.script+=C;continue;case g.SCRIPT_ENDING:C==="/"?m.state=g.CLOSE_TAG:(m.script+="<"+C,m.state=g.SCRIPT);continue;case g.OPEN_WAKA:if(C==="!")m.state=g.SGML_DECL,m.sgmlDecl="";else if(!w(C))if(I(y,C))m.state=g.OPEN_TAG,m.tagName=C;else if(C==="/")m.state=g.CLOSE_TAG,m.tagName="";else if(C==="?")m.state=g.PROC_INST,m.procInstName=m.procInstBody="";else{if(q(m,"Unencoded <"),m.startTagPosition+1<m.position){var Te=m.position-m.startTagPosition;C=new Array(Te).join(" ")+C}m.textNode+="<"+C,m.state=g.TEXT}continue;case g.SGML_DECL:(m.sgmlDecl+C).toUpperCase()===u?(M(m,"onopencdata"),m.state=g.CDATA,m.sgmlDecl="",m.cdata=""):m.sgmlDecl+C==="--"?(m.state=g.COMMENT,m.comment="",m.sgmlDecl=""):(m.sgmlDecl+C).toUpperCase()===d?(m.state=g.DOCTYPE,(m.doctype||m.sawRoot)&&q(m,"Inappropriately located doctype declaration"),m.doctype="",m.sgmlDecl=""):C===">"?(M(m,"onsgmldeclaration",m.sgmlDecl),m.sgmlDecl="",m.state=g.TEXT):(E(C)&&(m.state=g.SGML_DECL_QUOTED),m.sgmlDecl+=C);continue;case g.SGML_DECL_QUOTED:C===m.q&&(m.state=g.SGML_DECL,m.q=""),m.sgmlDecl+=C;continue;case g.DOCTYPE:C===">"?(m.state=g.TEXT,M(m,"ondoctype",m.doctype),m.doctype=!0):(m.doctype+=C,C==="["?m.state=g.DOCTYPE_DTD:E(C)&&(m.state=g.DOCTYPE_QUOTED,m.q=C));continue;case g.DOCTYPE_QUOTED:m.doctype+=C,C===m.q&&(m.q="",m.state=g.DOCTYPE);continue;case g.DOCTYPE_DTD:m.doctype+=C,C==="]"?m.state=g.DOCTYPE:E(C)&&(m.state=g.DOCTYPE_DTD_QUOTED,m.q=C);continue;case g.DOCTYPE_DTD_QUOTED:m.doctype+=C,C===m.q&&(m.state=g.DOCTYPE_DTD,m.q="");continue;case g.COMMENT:C==="-"?m.state=g.COMMENT_ENDING:m.comment+=C;continue;case g.COMMENT_ENDING:C==="-"?(m.state=g.COMMENT_ENDED,m.comment=ce(m.opt,m.comment),m.comment&&M(m,"oncomment",m.comment),m.comment=""):(m.comment+="-"+C,m.state=g.COMMENT);continue;case g.COMMENT_ENDED:C!==">"?(q(m,"Malformed comment"),m.comment+="--"+C,m.state=g.COMMENT):m.state=g.TEXT;continue;case g.CDATA:C==="]"?m.state=g.CDATA_ENDING:m.cdata+=C;continue;case g.CDATA_ENDING:C==="]"?m.state=g.CDATA_ENDING_2:(m.cdata+="]"+C,m.state=g.CDATA);continue;case g.CDATA_ENDING_2:C===">"?(m.cdata&&M(m,"oncdata",m.cdata),M(m,"onclosecdata"),m.cdata="",m.state=g.TEXT):C==="]"?m.cdata+="]":(m.cdata+="]]"+C,m.state=g.CDATA);continue;case g.PROC_INST:C==="?"?m.state=g.PROC_INST_ENDING:w(C)?m.state=g.PROC_INST_BODY:m.procInstName+=C;continue;case g.PROC_INST_BODY:if(!m.procInstBody&&w(C))continue;C==="?"?m.state=g.PROC_INST_ENDING:m.procInstBody+=C;continue;case g.PROC_INST_ENDING:C===">"?(M(m,"onprocessinginstruction",{name:m.procInstName,body:m.procInstBody}),m.procInstName=m.procInstBody="",m.state=g.TEXT):(m.procInstBody+="?"+C,m.state=g.PROC_INST_BODY);continue;case g.OPEN_TAG:I(S,C)?m.tagName+=C:(Mi(m),C===">"?Rn(m):C==="/"?m.state=g.OPEN_TAG_SLASH:(w(C)||q(m,"Invalid character in tag name"),m.state=g.ATTRIB));continue;case g.OPEN_TAG_SLASH:C===">"?(Rn(m,!0),$i(m)):(q(m,"Forward-slash in opening tag not followed by >"),m.state=g.ATTRIB);continue;case g.ATTRIB:if(w(C))continue;C===">"?Rn(m):C==="/"?m.state=g.OPEN_TAG_SLASH:I(y,C)?(m.attribName=C,m.attribValue="",m.state=g.ATTRIB_NAME):q(m,"Invalid attribute name");continue;case g.ATTRIB_NAME:C==="="?m.state=g.ATTRIB_VALUE:C===">"?(q(m,"Attribute without value"),m.attribValue=m.attribName,Ri(m),Rn(m)):w(C)?m.state=g.ATTRIB_NAME_SAW_WHITE:I(S,C)?m.attribName+=C:q(m,"Invalid attribute name");continue;case g.ATTRIB_NAME_SAW_WHITE:if(C==="=")m.state=g.ATTRIB_VALUE;else{if(w(C))continue;q(m,"Attribute without value"),m.tag.attributes[m.attribName]="",m.attribValue="",M(m,"onattribute",{name:m.attribName,value:""}),m.attribName="",C===">"?Rn(m):I(y,C)?(m.attribName=C,m.state=g.ATTRIB_NAME):(q(m,"Invalid attribute name"),m.state=g.ATTRIB)}continue;case g.ATTRIB_VALUE:if(w(C))continue;E(C)?(m.q=C,m.state=g.ATTRIB_VALUE_QUOTED):(q(m,"Unquoted attribute value"),m.state=g.ATTRIB_VALUE_UNQUOTED,m.attribValue=C);continue;case g.ATTRIB_VALUE_QUOTED:if(C!==m.q){C==="&"?m.state=g.ATTRIB_VALUE_ENTITY_Q:m.attribValue+=C;continue}Ri(m),m.q="",m.state=g.ATTRIB_VALUE_CLOSED;continue;case g.ATTRIB_VALUE_CLOSED:w(C)?m.state=g.ATTRIB:C===">"?Rn(m):C==="/"?m.state=g.OPEN_TAG_SLASH:I(y,C)?(q(m,"No whitespace between attributes"),m.attribName=C,m.attribValue="",m.state=g.ATTRIB_NAME):q(m,"Invalid attribute name");continue;case g.ATTRIB_VALUE_UNQUOTED:if(!A(C)){C==="&"?m.state=g.ATTRIB_VALUE_ENTITY_U:m.attribValue+=C;continue}Ri(m),C===">"?Rn(m):m.state=g.ATTRIB;continue;case g.CLOSE_TAG:if(m.tagName)C===">"?$i(m):I(S,C)?m.tagName+=C:m.script?(m.script+="</"+m.tagName,m.tagName="",m.state=g.SCRIPT):(w(C)||q(m,"Invalid tagname in closing tag"),m.state=g.CLOSE_TAG_SAW_WHITE);else{if(w(C))continue;k(y,C)?m.script?(m.script+="</"+C,m.state=g.SCRIPT):q(m,"Invalid tagname in closing tag."):m.tagName=C}continue;case g.CLOSE_TAG_SAW_WHITE:if(w(C))continue;C===">"?$i(m):q(m,"Invalid characters in closing tag");continue;case g.TEXT_ENTITY:case g.ATTRIB_VALUE_ENTITY_Q:case g.ATTRIB_VALUE_ENTITY_U:var Ee,qe;switch(m.state){case g.TEXT_ENTITY:Ee=g.TEXT,qe="textNode";break;case g.ATTRIB_VALUE_ENTITY_Q:Ee=g.ATTRIB_VALUE_QUOTED,qe="attribValue";break;case g.ATTRIB_VALUE_ENTITY_U:Ee=g.ATTRIB_VALUE_UNQUOTED,qe="attribValue";break}if(C===";")if(m.opt.unparsedEntities){var yt=Ql(m);m.entity="",m.state=Ee,m.write(yt)}else m[qe]+=Ql(m),m.entity="",m.state=Ee;else I(m.entity.length?v:b,C)?m.entity+=C:(q(m,"Invalid character in entity name"),m[qe]+="&"+m.entity+C,m.entity="",m.state=Ee);continue;default:throw new Error(m,"Unknown state: "+m.state)}return m.position>=m.bufferCheckPosition&&r(m),m}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */return String.fromCodePoint||(function(){var _=String.fromCharCode,m=Math.floor,O=function(){var C=16384,re=[],Te,Ee,qe=-1,yt=arguments.length;if(!yt)return"";for(var lr="";++qe<yt;){var Ne=Number(arguments[qe]);if(!isFinite(Ne)||Ne<0||Ne>1114111||m(Ne)!==Ne)throw RangeError("Invalid code point: "+Ne);Ne<=65535?re.push(Ne):(Ne-=65536,Te=(Ne>>10)+55296,Ee=Ne%1024+56320,re.push(Te,Ee)),(qe+1===yt||re.length>C)&&(lr+=_.apply(null,re),re.length=0)}return lr};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:O,configurable:!0,writable:!0}):String.fromCodePoint=O})(),e},MA=NA(),lc=`The output should be formatted as a XML file.
147
- 1. Output should conform to the tags below.
148
- 2. If tags are not given, make them on your own.
149
- 3. Remember to always open and close all the tags.
150
-
151
- As an example, for the tags ["foo", "bar", "baz"]:
152
- 1. String "<foo>
153
- <bar>
154
- <baz></baz>
155
- </bar>
156
- </foo>" is a well-formatted instance of the schema.
157
- 2. String "<foo>
158
- <bar>
159
- </foo>" is a badly-formatted instance.
160
- 3. String "<foo>
161
- <tag>
162
- </tag>
163
- </foo>" is a badly-formatted instance.
164
-
165
- Here are the output tags:
166
- \`\`\`
167
- {tags}
168
- \`\`\``;var RA=class extends Xs{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?wi(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return uc(e[0].text)}async parse(e){return uc(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?lc.replace("{tags}",this.tags?.join(", ")??""):lc}};const $A=e=>e.split(`
169
- `).map(t=>t.replace(/^\s+/,"")).join(`
170
- `).trim(),lm=e=>{if(Object.keys(e).length===0)return{};const t={};return e.children.length>0?(t[e.name]=e.children.map(lm),t):(t[e.name]=e.text??void 0,t)};function uc(e){const t=$A(e),n=MA.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]),lm(r)}var um={};F(um,{AsymmetricStructuredOutputParser:()=>IA,BaseCumulativeTransformOutputParser:()=>Xs,BaseLLMOutputParser:()=>Oi,BaseOutputParser:()=>qs,BaseTransformOutputParser:()=>Ys,BytesOutputParser:()=>EA,CommaSeparatedListOutputParser:()=>CA,CustomListOutputParser:()=>AA,JsonMarkdownStructuredOutputParser:()=>cm,JsonOutputParser:()=>PA,ListOutputParser:()=>Qs,MarkdownListOutputParser:()=>OA,NumberedListOutputParser:()=>kA,OutputParserException:()=>sn,StringOutputParser:()=>xA,StructuredOutputParser:()=>om,XMLOutputParser:()=>RA,XML_FORMAT_INSTRUCTIONS:()=>lc,parseJsonMarkdown:()=>Mo,parsePartialJson:()=>Br,parseXMLMarkdown:()=>uc});function dm(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 sn([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${s.message}`].join(`
171
- `))}const r={name:e.function.name,args:n,type:"tool_call"};return t?.returnId&&(r.id=e.id),r}function LA(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 jA(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}var hm=class extends Xs{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(Kc(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=>dm(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}},DA=class extends hm{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 tl(this.zodSchema,e);if(t.success)return t.data;throw new sn(`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}},pm={};F(pm,{JsonOutputKeyToolsParser:()=>DA,JsonOutputToolsParser:()=>hm,convertLangChainToolCallToOpenAI:()=>LA,makeInvalidToolCall:()=>jA,parseToolCall:()=>dm});var fm=class extends Oi{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)}`)}},mm=class extends Xs{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 fm(e)}_diff(e,t){return t?wi(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""}},UA=class extends Oi{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new mm;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]}},gm={};F(gm,{JsonKeyOutputFunctionsParser:()=>UA,JsonOutputFunctionsParser:()=>mm,OutputFunctionsParser:()=>fm});var ea=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"})}},Ms=class extends ea{async formatPromptValue(e){const t=await this.format(e);return new ul(t)}};/*!
172
- * mustache.js - Logic-less {{mustache}} templates with JavaScript
173
- * http://github.com/janl/mustache.js
174
- */var FA=Object.prototype.toString,rs=Array.isArray||function(t){return FA.call(t)==="[object Array]"};function Rl(e){return typeof e=="function"}function BA(e){return rs(e)?"array":typeof e}function po(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function bd(e,t){return e!=null&&typeof e=="object"&&t in e}function zA(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var HA=RegExp.prototype.test;function VA(e,t){return HA.call(e,t)}var GA=/\S/;function WA(e){return!VA(GA,e)}var JA={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function KA(e){return String(e).replace(/[&<>"'`=\/]/g,function(n){return JA[n]})}var ZA=/\s*/,qA=/\s+/,Sd=/\s*=/,YA=/\s*\}/,XA=/#|\^|\/|>|\{|&|=|!/;function QA(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(g){if(typeof g=="string"&&(g=g.split(qA,2)),!rs(g)||g.length!==2)throw new Error("Invalid tags: "+g);d=new RegExp(po(g[0])+"\\s*"),h=new RegExp("\\s*"+po(g[1])),p=new RegExp("\\s*"+po("}"+g[1]))}f(t||ot.tags);for(var y=new ta(e),S,b,v,w,E,A;!y.eos();){if(S=y.pos,v=y.scanUntil(d),v)for(var I=0,k=v.length;I<k;++I)w=v.charAt(I),WA(w)?(a.push(s.length),c+=w):(o=!0,n=!0,c+=" "),s.push(["text",w,S,S+1]),S+=1,w===`
175
- `&&(u(),c="",l=0,n=!1);if(!y.scan(d))break;if(i=!0,b=y.scan(XA)||"name",y.scan(ZA),b==="="?(v=y.scanUntil(Sd),y.scan(Sd),y.scanUntil(h)):b==="{"?(v=y.scanUntil(p),y.scan(YA),y.scanUntil(h),b="&"):v=y.scanUntil(h),!y.scan(h))throw new Error("Unclosed tag at "+y.pos);if(b==">"?E=[b,v,S,y.pos,c,l,n]:E=[b,v,S,y.pos],l++,s.push(E),b==="#"||b==="^")r.push(E);else if(b==="/"){if(A=r.pop(),!A)throw new Error('Unopened section "'+v+'" at '+S);if(A[1]!==v)throw new Error('Unclosed section "'+A[1]+'" at '+S)}else b==="name"||b==="{"||b==="&"?o=!0:b==="="&&f(v)}if(u(),A=r.pop(),A)throw new Error('Unclosed section "'+A[1]+'" at '+y.pos);return tk(ek(s))}function ek(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 tk(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 ta(e){this.string=e,this.tail=e,this.pos=0}ta.prototype.eos=function(){return this.tail===""};ta.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};ta.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 Zr(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Zr.prototype.push=function(t){return new Zr(t,this)};Zr.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=bd(a,i[o])||zA(a,i[o])),a=a[i[o++]];else a=s.view[t],c=bd(s.view,t);if(c){r=a;break}s=s.parent}n[t]=r}return Rl(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||ot.tags).join(":"),a=typeof r<"u",i=a?r.get(s):void 0;return i==null&&(i=QA(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 Zr?n:new Zr(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(rs(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(Rl(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||rs(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(`
176
- `),i=0;i<a.length;i++)a[i].length&&(i>0||!r)&&(a[i]=s+a[i]);return a.join(`
177
- `)};Ze.prototype.renderPartial=function(t,n,r,s){if(r){var a=this.getConfigTags(s),i=Rl(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)||ot.escape,a=n.lookup(t[1]);if(a!=null)return typeof a=="number"&&s===ot.escape?String(a):s(a)};Ze.prototype.rawValue=function(t){return t[1]};Ze.prototype.getConfigTags=function(t){return rs(t)?t:t&&typeof t=="object"?t.tags:void 0};Ze.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!rs(t))return t.escape};var ot={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){Rs.templateCache=e},get templateCache(){return Rs.templateCache}},Rs=new Ze;ot.clearCache=function(){return Rs.clearCache()};ot.parse=function(t,n){return Rs.parse(t,n)};ot.render=function(t,n,r,s){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+BA(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Rs.render(t,n,r,s)};ot.escape=KA;ot.Scanner=ta;ot.Context=Zr;ot.Writer=Ze;function ym(){ot.escape=e=>e}const $s=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},_m=(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=_m(r[4],s);n.push(...a)}}else n.push({type:"literal",text:r[1]});return n},Xa=e=>{ym();const t=ot.parse(e);return _m(t)},wm=(e,t)=>$s(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},""),vm=(e,t)=>(ym(),ot.render(e,t)),Qa={"f-string":wm,mustache:vm},bm={"f-string":$s,mustache:Xa},Lt=(e,t,n)=>{try{return Qa[t](e,n)}catch(r){throw fi(r,"INVALID_PROMPT_INPUT")}},ei=(e,t)=>bm[t](e),na=(e,t,n)=>{if(!(t in Qa)){const r=Object.keys(Qa);throw new Error(`Invalid template format. Got \`${t}\`;
178
- 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")Lt(s.text,t,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")Lt(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;Lt(a,t,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):Lt(e,t,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var Tn=class us extends Ms{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))),na(this.template,this.templateFormat,n)}}_getPromptType(){return"prompt"}async format(t){const n=await this.mergePartialAndUserVariables(t);return Lt(this.template,this.templateFormat,n)}static fromExamples(t,n,r,s=`
179
-
180
- `,a=""){const i=[a,...t,n].join(s);return new us({inputVariables:r,template:i})}static fromTemplate(t,n){const{templateFormat:r="f-string",...s}=n??{},a=new Set;return ei(t,r).forEach(i=>{i.type==="variable"&&a.add(i.name)}),new us({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 us(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 us({inputVariables:t.input_variables,template:t.template,templateFormat:t.template_format})}},ba=class Sm extends ea{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))),na([{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 Sm(s)}async format(t){const n={};for(const[i,o]of Object.entries(this.template))typeof o=="string"?n[i]=Lt(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 Bp(n)}},dc=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=hc(e.template,t);super({inputVariables:n,...e}),this.template=e.template,this.templateFormat=t,this.inputVariables=n}async format(e){return pc(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}};function hc(e,t){const n=[];for(const r of Object.values(e))if(typeof r=="string")ei(r,t).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?ei(s,t).forEach(a=>{a.type==="variable"&&n.push(a.name)}):typeof s=="object"&&n.push(...hc(s,t));else typeof r=="object"&&r!==null&&n.push(...hc(r,t));return Array.from(new Set(n))}function pc(e,t,n){const r={};for(const[s,a]of Object.entries(e))if(typeof a=="string")r[s]=Lt(a,n,t);else if(Array.isArray(a)){const i=[];for(const o of a)typeof o=="string"?i.push(Lt(o,n,t)):typeof o=="object"&&i.push(pc(o,t,n));r[s]=i}else typeof a=="object"&&a!==null?r[s]=pc(a,t,n):r[s]=a;return r}var xi=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"})}},fc=class extends xi{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(`
181
-
182
- `));throw a.name="InputFormatError",a.lc_error_code=r.lc_error_code,a}return n}},Tm=class extends xi{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)]}},$l=class extends ea{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){const t=await this.formatMessages(e);return new dl(t)}},Em=class extends Tm{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 Qn(await this.prompt.format(e),this.role)}static fromTemplate(e,t,n){return new this(Tn.fromTemplate(e,{templateFormat:n?.templateFormat}),t)}};function nk(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.keys(e).length===1&&"text"in e&&typeof e.text=="string"}function rk(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 Ll=class extends xi{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(Tn.fromTemplate(e,t));const n=[];for(const r of e)if(typeof r=="string")n.push(Tn.fromTemplate(r,t));else if(r!==null)if(nk(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const a={...t,additionalContentFields:r};n.push(Tn.fromTemplate(s,a))}else if(rk(r)){let s=r.image_url??"",a,i=[];if(typeof s=="string"){let o;t?.templateFormat==="mustache"?o=Xa(s):o=$s(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.
183
- Got: ${c}
184
- From: ${s}`);i=[c[0]]}else i=[];s={url:s},a=new ba({template:s,inputVariables:i,templateFormat:t?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let o;t?.templateFormat==="mustache"?o=Xa(s.url):o=$s(s.url),i=o.flatMap(c=>c.type==="variable"?[c.name]:[])}else i=[];a=new ba({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 dc({template:r,templateFormat:t?.templateFormat}));return new this({prompt:n,additionalOptions:t})}async format(e){if(this.prompt instanceof Ms){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 Ms){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 ba){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 dc){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)]}},jl=class extends Ll{static _messageClass(){return de}static lc_name(){return"HumanMessagePromptTemplate"}},Cm=class extends Ll{static _messageClass(){return D}static lc_name(){return"AIMessagePromptTemplate"}},Am=class extends Ll{static _messageClass(){return fe}static lc_name(){return"SystemMessagePromptTemplate"}};function sk(e){return typeof e.formatMessages=="function"}function ak(e,t){if(sk(e)||Ie(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 fc({variableName:a,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const a=s.slice(1,-1);return new fc({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 jl.fromTemplate(r,t);if(n._getType()==="ai")return Cm.fromTemplate(r,t);if(n._getType()==="system")return Am.fromTemplate(r,t);if(Qn.isInstance(n))return Em.fromTemplate(n.content,n.role,t);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function ik(e){return e.constructor.lc_name()==="MessagesPlaceholder"}var Dl=class Sa extends $l{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 tt))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 Tn.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 tt)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)&&!(ik(s)&&s.optional))throw fi(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 Sa(s)}static fromTemplate(t,n){const r=Tn.fromTemplate(t,n),s=new jl({prompt:r});return this.fromMessages([s])}static fromMessages(t,n){const r=t.reduce((i,o)=>i.concat(o instanceof Sa?o.promptMessages:[ak(o,n)]),[]),s=t.reduce((i,o)=>o instanceof Sa?Object.assign(i,o.partialVariables):i,Object.create(null)),a=new Set;for(const i of r)if(!(i instanceof tt))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})}},ok=class mc extends Ms{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
185
-
186
- `;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))),na(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 mc(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 Lt(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 Tn.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 mc({inputVariables:t.input_variables,examplePrompt:r,examples:s,exampleSeparator:t.example_separator,prefix:t.prefix,suffix:t.suffix,templateFormat:t.template_format})}},ck=class km extends $l{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
187
-
188
- `;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??`
189
-
190
- `,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))),na(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 Lt(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 km(s)}},lk=class Ta extends ea{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=Ta.extractRequiredInputValues(n,s.inputVariables);s instanceof Dl?n[r]=await s.formatMessages(a):n[r]=await s.format(a)}return Ta.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 Ta(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function Td(e){return typeof e=="object"&&e!=null&&"withStructuredOutput"in e&&typeof e.withStructuredOutput=="function"}function uk(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 dk=class Om extends Dl{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(Td(t))return super.pipe(t.withStructuredOutput(this.schema));if(uk(t)&&Td(t.bound))return super.pipe(new De({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 Om.fromMessages(t,{schema:n,method:r})}},xm={};F(xm,{AIMessagePromptTemplate:()=>Cm,BaseChatPromptTemplate:()=>$l,BaseMessagePromptTemplate:()=>xi,BaseMessageStringPromptTemplate:()=>Tm,BasePromptTemplate:()=>ea,BaseStringPromptTemplate:()=>Ms,ChatMessagePromptTemplate:()=>Em,ChatPromptTemplate:()=>Dl,DEFAULT_FORMATTER_MAPPING:()=>Qa,DEFAULT_PARSER_MAPPING:()=>bm,DictPromptTemplate:()=>dc,FewShotChatMessagePromptTemplate:()=>ck,FewShotPromptTemplate:()=>ok,HumanMessagePromptTemplate:()=>jl,ImagePromptTemplate:()=>ba,MessagesPlaceholder:()=>fc,PipelinePromptTemplate:()=>lk,PromptTemplate:()=>Tn,StructuredPrompt:()=>dk,SystemMessagePromptTemplate:()=>Am,checkValidTemplate:()=>na,interpolateFString:()=>wm,interpolateMustache:()=>vm,parseFString:()=>$s,parseMustache:()=>Xa,parseTemplate:()=>ei,renderTemplate:()=>Lt});var Im={};F(Im,{BaseDocumentCompressor:()=>hk});var hk=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}};const wn={and:"and",or:"or",not:"not"},Z={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var Pm=class{},Ul=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")}},Fl=class extends Ul{},pk=class extends Fl{exprName="Comparison";constructor(e,t,n){super(),this.comparator=e,this.attribute=t,this.value=n}},fk=class extends Fl{exprName="Operation";constructor(e,t){super(),this.operator=e,this.args=t}},mk=class extends Ul{exprName="StructuredQuery";constructor(e,t){super(),this.query=e,this.filter=t}};function Nm(e){return e&&typeof e=="object"&&!Array.isArray(e)}function Mt(e){return e?typeof e=="string"&&e.length>0||typeof e=="function"?!1:Nm(e)&&Object.keys(e).length===0:!0}function Mm(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 Rm(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 $m(e){return typeof e=="string"&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function Lm(e){return typeof e=="boolean"}function Bl(e){let t;if($m(e))t=e;else if(Mm(e))t=parseInt(e,10);else if(Rm(e))t=parseFloat(e);else if(Lm(e))t=!!e;else throw new Error("Unsupported value type");return t}var zl=class extends Pm{},gk=class extends zl{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[wn.and,wn.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 wn){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)]:Bl(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,n="and",r=!1){if(!(Mt(e)&&Mt(t))){if(Mt(e)||n==="replace")return Mt(t)?void 0:t;if(Mt(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")}}},yk=class extends zl{allowedOperators=[wn.and,wn.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 wn.and:return(t,n)=>t&&n;case wn.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,Bl(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(!(Mt(e)&&Mt(t))){if(Mt(e)||n==="replace")return Mt(t)?void 0:t;if(Mt(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")}}},jm={};F(jm,{BaseTranslator:()=>zl,BasicTranslator:()=>gk,Comparators:()=>Z,Comparison:()=>pk,Expression:()=>Ul,FilterDirective:()=>Fl,FunctionalTranslator:()=>yk,Operation:()=>fk,Operators:()=>wn,StructuredQuery:()=>mk,Visitor:()=>Pm,castValue:()=>Bl,isBoolean:()=>Lm,isFilterEmpty:()=>Mt,isFloat:()=>Rm,isInt:()=>Mm,isObject:()=>Nm,isString:()=>$m});var Dm={};F(Dm,{RunCollectorCallbackHandler:()=>_k});var _k=class extends cn{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)}},wk={},Um={};F(Um,{chunkArray:()=>vk});const vk=(e,t)=>e.reduce((n,r,s)=>{const a=Math.floor(s/t),i=n[a]||[];return n[a]=i.concat([r]),n},[]);var Fm={};F(Fm,{EventStreamContentType:()=>bk,convertEventStreamToIterableReadableDataStream:()=>Tk,getBytes:()=>Bm,getLines:()=>zm,getMessages:()=>Hm});const bk="text/event-stream";async function Bm(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(`
191
- `))}}var wr=(function(e){return e[e.NewLine=10]="NewLine",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.Colon=58]="Colon",e})(wr||{});function zm(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=Sk(t,i);const c=t.length;let l=0;for(;n<c;){s&&(t[n]===wr.NewLine&&(l=++n),s=!1);let u=-1;for(;n<c&&u===-1;++n)switch(t[n]){case wr.Colon:r===-1&&(r=n-l);break;case wr.CarriageReturn:s=!0;case wr.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 Hm(e,t,n){let r=fo();const s=new TextDecoder;return function(i,o,c){if(c){Ek(r)||(e?.(r),r=fo());return}if(i.length===0)e?.(r),r=fo();else if(o>0){const l=s.decode(i.subarray(0,o)),u=o+(i[o+1]===wr.Space?2:1),d=s.decode(i.subarray(u));switch(l){case"data":r.data=r.data?r.data+`
192
- `+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 Sk(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function fo(){return{data:"",event:"",id:"",retry:void 0}}function Tk(e,t){const n=new ReadableStream({async start(r){const s=Hm(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 Bm(e,zm((i,o,c)=>{s(i,o,c),c&&r.close()}))}});return Fe.fromReadableStream(n)}function Ek(e){return e.data===""&&e.event===""&&e.id===""&&e.retry===void 0}var Vm={};F(Vm,{convertToOpenAIFunction:()=>Gm,convertToOpenAITool:()=>Ck,isLangChainTool:()=>_l,isRunnableToolLike:()=>gl,isStructuredTool:()=>ml,isStructuredToolParams:()=>yl});function Gm(e,t){const n=typeof t=="number"?void 0:t;return{name:e.name,description:e.description,parameters:ft(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function Ck(e,t){const n=typeof t=="number"?void 0:t;let r;return _l(e)?r={type:"function",function:Gm(e)}:r=e,n?.strict!==void 0&&(r.function.strict=n.strict),r}function Wm(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 Ak(e,t){let n=0;for(let r=0;r<e.length;r++)n+=e[r]*t[r];return n}function kk(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 Ok(e,t){return Math.sqrt(kk(e,t))}var Jm={};F(Jm,{cosineSimilarity:()=>gc,euclideanDistance:()=>Pk,innerProduct:()=>Ik,matrixFunc:()=>Ii,maximalMarginalRelevance:()=>Nk,normalize:()=>xk});function Ii(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 xk(e,t=!1){const n=Mk(e);return e.map(r=>r.map(s=>t?1-s/n:s/n))}function gc(e,t){return Ii(e,t,Wm)}function Ik(e,t){return Ii(e,t,Ak)}function Pk(e,t){return Ii(e,t,Ok)}function Nk(e,t,n=.5,r=4){if(Math.min(r,t.length)<=0)return[];const s=Array.isArray(e[0])?e:[e],a=gc(s,t)[0],i=Km(a).maxIndex,o=[t[i]],c=[i];for(;c.length<Math.min(r,t.length);){let l=-1/0,u=-1;const d=gc(t,o);a.forEach((h,p)=>{if(c.includes(p))return;const f=Math.max(...d[p]),y=n*h-(1-n)*f;y>l&&(l=y,u=p)}),o.push(t[u]),c.push(u)}return c}function Km(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 Mk(e){return e.reduce((t,n)=>Math.max(t,Km(n).maxValue),0)}var Rk=class extends sr{_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(`
193
- `);return await n?.handleLLMNewToken(r),{generations:[{message:new D(r),text:r}],llmOutput:{}}}},$k=class Zm extends sr{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:ft(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:ft(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:ft(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:ft(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,a=new Zm({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 Jr({message:new mt({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 Jr({message:new mt({content:i}),text:i});yield o,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:o})}}},Lk=class extends sr{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 Jr({message:new mt({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 at.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")})}},jk=class extends xl{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})}},Dk=class extends xl{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},Uk=class extends Ml{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}},Fk=class extends Ml{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)}},Bk=class extends Rf{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 de(e))}async addAIMessage(e){this.messages.push(new D(e))}async clear(){this.messages=[]}},zk=class extends Ol{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},Hk=class extends cn{name="fake_tracer";runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},Vk=class extends qs{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(e){return e.split(",").map(t=>t.trim())}},Gk=class extends Il{lc_namespace=["test","fake"];output=[new rn({pageContent:"foo"}),new rn({pageContent:"bar"})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},Wk=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}}},Jk=class extends tr{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)}},Kk=class extends cn{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}},Zk=class qm extends Pl{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(t,{similarity:n,...r}={}){super(t,r),this.similarity=n??Wm}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 rn({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 rn({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 rn({pageContent:t[i],metadata:o});a.push(c)}return qm.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)}},Ym={};F(Ym,{FakeChatMessageHistory:()=>Bk,FakeChatModel:()=>Rk,FakeEmbeddings:()=>Dk,FakeLLM:()=>Uk,FakeListChatMessageHistory:()=>zk,FakeListChatModel:()=>Lk,FakeRetriever:()=>Gk,FakeRunnable:()=>Wk,FakeSplitIntoListParser:()=>Vk,FakeStreamingChatModel:()=>$k,FakeStreamingLLM:()=>Fk,FakeTool:()=>Jk,FakeTracer:()=>Hk,FakeVectorStore:()=>Zk,SingleRunExtractor:()=>Kk,SyntheticEmbeddings:()=>jk});var Xm={};F(Xm,{agents:()=>iA,caches:()=>Hp,callbacks__base:()=>Nh,callbacks__manager:()=>tp,callbacks__promises:()=>ep,chat_history:()=>Mf,document_loaders__base:()=>Hf,document_loaders__langsmith:()=>Gf,documents:()=>Jf,embeddings:()=>$f,example_selectors:()=>Yf,index:()=>cA,indexing:()=>am,language_models__base:()=>qp,language_models__chat_models:()=>Tf,language_models__llms:()=>Xf,load__serializable:()=>ch,memory:()=>Lf,messages:()=>Sf,messages__tool:()=>_h,output_parsers:()=>um,output_parsers__openai_functions:()=>gm,output_parsers__openai_tools:()=>pm,outputs:()=>kp,prompt_values:()=>Fp,prompts:()=>xm,retrievers:()=>Bf,retrievers__document_compressors:()=>Im,runnables:()=>Ef,runnables__graph:()=>Pp,singletons:()=>op,stores:()=>Df,structured_query:()=>jm,tools:()=>Xp,tracers__base:()=>Kh,tracers__console:()=>Zh,tracers__log_stream:()=>Cp,tracers__run_collector:()=>Dm,tracers__tracer_langchain:()=>Yh,types__stream:()=>wk,utils__async_caller:()=>wp,utils__chunk_array:()=>Um,utils__env:()=>Ch,utils__event_source_parse:()=>Fm,utils__function_calling:()=>Vm,utils__hash:()=>zp,utils__json_patch:()=>im,utils__json_schema:()=>_p,utils__math:()=>Jm,utils__stream:()=>vp,utils__testing:()=>Ym,utils__tiktoken:()=>Kp,utils__types:()=>xf,vectorstores:()=>zf});function qk(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 Ea(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=nn(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:Xm,langchain:r};let p=null;const f=[d.join("/")];d[0]==="langchain_community"&&f.push(["langchain",...d.slice(1)].join("/"));const y=f.find(v=>v in t);if(aA.concat(n).includes(d.join("/"))||y)if(y!==void 0)p=await t[y];else throw new Error(`Missing key "${d.join("/")}" for ${i} in load(optionalImportsMap={})`);else{let v;if(d[0]==="langchain"||d[0]==="langchain_core")v=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 w;do{if(w=d.join("__"),w in v)break;d.pop()}while(d.length>0);w in v&&(p=v[w])}if(typeof p!="object"||p===null)throw new Error(`Invalid namespace: ${i} -> ${c}`);const S=p[l]??Object.values(p).find(v=>typeof v=="function"&&ui(v)===l);if(typeof S!="function")throw new Error(`Invalid identifer: ${i} -> ${c}`);const b=await Ea.call({...this,path:[...a,"kwargs"]},o.kwargs);if(o.type==="constructor"){const v=new S(oh(b,rw,qk(S)));return Object.defineProperty(v.constructor,"name",{value:l}),v}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)=>Ea.call({...this,path:[...a,`${c}`]},o))):Object.fromEntries(await Promise.all(Object.entries(e).map(async([o,c])=>[o,await Ea.call({...this,path:[...a,o]},c)])));return e}async function Yk(e,t){const n=JSON.parse(e);return Ea.call({...t},n)}function Xk(e){return e!==null&&e.lc===1&&e.type==="constructor"&&Array.isArray(e.id)}async function yc(e){if(e&&typeof e=="object"){if(Array.isArray(e))return await Promise.all(e.map(n=>yc(n)));{const t={};for(const[n,r]of Object.entries(e))t[n]=await yc(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(Xk(t))return Yk(JSON.stringify(t));return t}}return e}function mo(e,t,n,r){return{lc:2,type:"constructor",id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function Qk(e){return e===void 0?{lc:2,type:"undefined"}:e instanceof Set||e instanceof Map?mo(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?mo(RegExp,void 0,[e.source,e.flags]):e instanceof Error?mo(e.constructor,void 0,[e.message]):e?.lg_name==="Send"?{node:e.node,args:e.args}:e}var eO=class{_dumps(e){return new TextEncoder().encode(rA(e,(n,r)=>Qk(r)))}async dumpsTyped(e){return e instanceof Uint8Array?["bytes",e]:["json",this._dumps(e)]}async _loads(e){const t=JSON.parse(e);return yc(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 Qm(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]=Qm(e[n]));return t}function eg(){return{v:4,id:Nf(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function ti(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values},channel_versions:{...e.channel_versions},versions_seen:Qm(e.versions_seen)}}function tg(e,t){return typeof e=="number"&&typeof t=="number"?Math.sign(e-t):String(e).localeCompare(String(t))}function tO(...e){return e.reduce((t,n,r)=>r===0?n:tg(t,n)>=0?t:n)}const nO={[XC]:-1,[wa]:-2,[QC]:-3,[eA]:-4};var is=class extends Error{constructor(e){super(e),this.name="InvalidNamespaceError"}};function rO(e){if(e.length===0)throw new is("Namespace cannot be empty.");for(const t of e){if(typeof t!="string")throw new is(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes("."))throw new is(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t==="")throw new is(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]==="langgraph")throw new is(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var sO=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){rO(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 aO=e=>"lg_name"in e&&e.lg_name==="AsyncBatchedStore"?e.store:e;var iO=class extends sO{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=aO(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]"}}},oO=class{serde=new eO;constructor(e){this.serde=e||this.serde}},cO=class ng extends sr{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 ng({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...t],n}withStructuredOutput(t){return new at({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(de.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 rg{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 lO(){me.initializeGlobalInstance(new rg)}var ar=class extends Error{lc_error_code;constructor(e,t){let n=e??"";t?.lc_error_code&&(n=`${n}
194
-
195
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/
196
- `),super(n),this.lc_error_code=t?.lc_error_code}},sg=class extends ar{get is_bubble_up(){return!0}},uO=class extends ar{constructor(e,t){super(e,t),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},Ca=class extends ar{constructor(e,t){super(e,t),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},Sr=class extends sg{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}},ag=class extends Sr{constructor(e,t){super([{value:e}],t),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},ig=class extends sg{command;constructor(e){super(),this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}};function dO(e){return e!==void 0&&e.name===ig.unminifiable_name}function Aa(e){return e!==void 0&&e.is_bubble_up===!0}function Bn(e){return e!==void 0&&[Sr.unminifiable_name,ag.unminifiable_name].includes(e.name)}var Ed=class extends ar{constructor(e,t){super(e,t),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},Le=class extends ar{constructor(e,t){super(e,t),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},ue=class extends ar{constructor(e,t){super(e,t),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},hO=class extends ar{constructor(e,t){super(e,t),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function og(e){return e!=null&&e.lg_is_channel===!0}var ir=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===Le.unminifiable_name)return!1;throw e}}};const _c=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function Hl(e){if(e[_c]===!0)return e;const t={};for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const r=e[n];og(r)&&(t[n]=r)}return Object.assign(t,{[_c]:!0}),t}function ni(e,t){const n=Hl(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,{[_c]:!0}),r}function Un(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!==Le.unminifiable_name)throw i}}return{v:4,id:r?.id??Nf(n),ts:new Date().toISOString(),channel_values:s,channel_versions:e.channel_versions,versions_seen:e.versions_seen}}var wc=class cg extends ir{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 cg(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 Le;return this.value}checkpoint(){if(this.value===void 0)throw new Le;return this.value}isAvailable(){return this.value!==void 0}},Vl=class lg extends ir{lc_graph_name="LastValue";value=[];fromCheckpoint(t){const n=new lg;return typeof t<"u"&&(n.value=[t]),n}update(t){if(t.length===0)return!1;if(t.length!==1)throw new ue("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 Le;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Le;return this.value[0]}isAvailable(){return this.value.length!==0}},pO=class ug extends ir{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(t){const n=new ug;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 Le;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}},fO=class{lc_graph_name="AnnotationRoot";spec;constructor(e){this.spec=e}};const vc=function(e){return e?bc(e):new Vl};vc.Root=e=>new fO(e);function bc(e){return typeof e=="object"&&e&&"reducer"in e&&e.reducer?new wc(e.reducer,e.default):typeof e=="object"&&e&&"value"in e&&e.value?new wc(e.value,e.default):new Vl}const ie="__start__",B="__end__",Yt="__input__",mO="__copy__",et="__error__",go="__pregel_ns_writes",En="__pregel_send",Gl="__pregel_call",Wn="__pregel_read",_e="__pregel_checkpointer",gn="__pregel_resuming",gs="__pregel_task_id",ri="__pregel_stream",gO="__pregel_resume_value",ka="__pregel_resume_map",Cn="__pregel_scratchpad",Oa="__pregel_previous",dg="__pregel_durability",Sc="checkpoint_id",Bt="checkpoint_ns",yO="__pregel_node_finished",wt="checkpoint_map",Cd="__pregel_abort_signals",Y="__interrupt__",rt="__resume__",Wl="__no_writes__",qr="__return__",yo="__previous__",ve="langsmith:hidden",_O="langsmith:nostream",Ad="__self__",vt="__pregel_tasks",dt="__pregel_push",xa="__pregel_pull",bt="00000000-0000-0000-0000-000000000000",wO=[ve,Yt,Y,rt,et,Wl,En,Wn,_e,dg,ri,gn,gs,Gl,gO,Cn,Oa,wt,Bt,Sc],ke="|",an=":",kd=Symbol.for("langgraph.command");var vO=class{[kd];constructor(e){this[kd]=e}};function Tc(e){const t=e;return t!=null&&typeof t.node=="string"&&t.args!==void 0}var Ge=class{lg_name="Send";node;args;constructor(e,t){this.node=e,this.args=Ls(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function gt(e){return e instanceof Ge}function hg(e){return!e||typeof e!="object"||!(Y in e)?!1:Array.isArray(e[Y])}var be=class extends vO{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)?Ls(e.goto):[Ls(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:gt(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 Pe(e){return typeof e!="object"||e==null?!1:"lg_name"in e&&e.lg_name==="Command"}function Ls(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]=Ls(r,t)});else if(Pe(e)&&!(e instanceof be))n=new be(e),t.set(e,n);else if(Tc(e)&&!(e instanceof Ge))n=new Ge(e.node,e.args),t.set(e,n);else if(Pe(e)||gt(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]=Ls(s,t)}return n}return e}const bO=["tags","metadata","callbacks","configurable"],SO=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],TO=25;function pg(...e){const t={tags:[],metadata:{},callbacks:void 0,recursionLimit:TO,configurable:{}},n=me.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(bO.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&&SO.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 EO(){return me.getRunnableConfig()}function _o(e){return e.split(ke).filter(t=>!t.match(/^\d+$/)).map(t=>t.split(an)[0]).join(ke)}function CO(e){const t=e.split(ke);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(ke)}const P=e=>BigInt(e),oe=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),fg=P("0x9E3779B1"),mg=P("0x85EBCA77"),AO=P("0xC2B2AE3D"),In=P("0x9E3779B185EBCA87"),qn=P("0xC2B2AE3D27D4EB4F"),gg=P("0x165667B19E3779F9"),Jl=P("0x85EBCA77C2B2AE63"),kO=P("0x27D4EB2F165667C5"),OO=P("0x165667919E3779F9"),xO=P("0x9FB21C651E98DF25"),IO=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)},Ft=IO("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Tr=(P(1)<<P(128))-P(1),W=(P(1)<<P(64))-P(1),si=(P(1)<<P(32))-P(1),Xt=64,yg=Xt/8,PO=8,da=4;function Yr(e){if(!e)throw new Error("Assert failed")}function NO(e){const t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function MO(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 RO(e,t){return(e&si)*(t&si)&W}function $O(e,t){return(e<<t|e>>P(32)-t)&si}function _g(e,t,n){for(let r=0;r<yg;r+=1){const s=t.getBigUint64(r*8,!0),a=s^n.getBigUint64(r*8,!0);e[r^1]+=s,e[r]+=RO(a,a>>P(32))}return e}function Od(e,t,n,r){for(let s=0;s<r;s+=1)_g(e,oe(t,s*Xt),oe(n,s*8));return e}function LO(e,t){for(let n=0;n<yg;n+=1){const r=t.getBigUint64(n*8,!0);let s=e[n];s=Ec(s,P(47)),s^=r,s*=fg,e[n]=s&W}return e}function ha(e,t){return wg(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(PO,!0))}function xd(e,t,n){let r=n;return r+=ha(e.slice(0),oe(t,0*da)),r+=ha(e.slice(2),oe(t,4*da)),r+=ha(e.slice(4),oe(t,8*da)),r+=ha(e.slice(6),oe(t,12*da)),zt(r&W)}function jO(e,t,n,r,s){let a=e;const i=Math.floor((n.byteLength-Xt)/8),o=Xt*i,c=Math.floor((t.byteLength-1)/o);for(let l=0;l<c;l+=1)a=Od(a,oe(t,l*o),n,i),a=s(a,oe(n,n.byteLength-Xt));{const l=Math.floor((t.byteLength-1-o*c)/Xt);a=Od(a,oe(t,c*o),n,l),a=r(a,oe(t,t.byteLength-Xt),oe(n,n.byteLength-Xt-7))}return a}function DO(e,t){let n=new BigUint64Array([AO,In,qn,gg,Jl,mg,kO,fg]);Yr(e.byteLength>128),n=jO(n,e,t,_g,LO),Yr(n.length*8===64);{const r=xd(n,oe(t,11),P(e.byteLength)*In&W);return xd(n,oe(t,t.byteLength-Xt-11),~(P(e.byteLength)*qn)&W)<<P(64)|r}}function wg(e,t){const n=e*t&Tr;return n&W^n>>P(64)}function Id(e,t,n){return wg((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&W,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&W)}function Ia(e,t,n,r,s){let a=e&W,i=e>>P(64)&W;return a+=Id(t,r,s),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=W,i+=Id(n,oe(r,16),s),i^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),i&=W,i<<P(64)|a}function zt(e){let t=e;return t^=t>>P(37),t*=OO,t&=W,t^=t>>P(32),t}function ai(e){let t=e;return t^=t>>P(33),t*=qn,t&=W,t^=t>>P(29),t*=gg,t&=W,t^=t>>P(32),t}function UO(e,t,n){const r=e.byteLength;Yr(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=($O(MO(s),P(13))^o)&W;return(ai(c)&W)<<P(64)|ai(i)}function Ec(e,t){return e^e>>t}function FO(e,t,n){const r=e.byteLength;Yr(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)*(In+(P(r)<<P(2)))&Tr;return l+=(l&W)<<P(65),l&=Tr,l^=l>>P(67),Ec(Ec(l&W,P(35))*xO&W,P(28))|zt(l>>P(64))<<P(64)}}function BO(e,t,n){const r=e.byteLength;Yr(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)*In;const l=(c&W)+(P(r-1)<<P(54));c=c&(Tr^W)|l,o^=a,c+=o+(o&si)*(mg-P(1))<<P(64),c&=Tr,c^=NO(c>>P(64));let u=(c&W)*qn;return u+=(c>>P(64))*qn<<P(64),u&=Tr,zt(u&W)|zt(u>>P(64))<<P(64)}}function zO(e,t){const n=e.byteLength;return Yr(n<=16),n>8?BO(e,Ft,t):n>=4?FO(e,Ft,t):n>0?UO(e,Ft,t):ai(t^Ft.getBigUint64(64,!0)^Ft.getBigUint64(72,!0))|ai(t^Ft.getBigUint64(80,!0)^Ft.getBigUint64(88,!0))<<P(64)}function Cc(e){return~e+P(1)&W}function HO(e,t,n){let r=P(e.byteLength)*In&W,s=P(e.byteLength-1)/P(32);for(;s>=0;){const o=Number(s);r=Ia(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=zt(a);let i=(r&W)*In+(r>>P(64))*Jl+(P(e.byteLength)-n&W)*qn;return i&=W,i=Cc(zt(i)),a|i<<P(64)}function VO(e,t,n){let r=P(e.byteLength)*In&W;for(let i=32;i<160;i+=32)r=Ia(r,oe(e,i-32),oe(e,i-16),oe(t,i-32),n);r=zt(r&W)|zt(r>>P(64))<<P(64);for(let i=160;i<=e.byteLength;i+=32)r=Ia(r,oe(e,i-32),oe(e,i-16),oe(t,3+i-160),n);r=Ia(r,oe(e,e.byteLength-16),oe(e,e.byteLength-32),oe(t,103),Cc(n));let s=r+(r>>P(64))&W;s=zt(s);let a=(r&W)*In+(r>>P(64))*Jl+(P(e.byteLength)-n&W)*qn;return a&=W,a=Cc(zt(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(zO(r,t)):s<=128?a(HO(r,Ft,t)):s<=240?a(VO(r,Ft,t)):a(DO(r,Ft))}function vg(e){return/^[0-9a-f]{32}$/.test(e)}function bg(e){const t=me.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 Ca("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=n[Cn];s.interruptCounter+=1;const a=s.interruptCounter;if(s.resume.length>0&&a<s.resume.length)return n[En]?.([[rt,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[En]?.([[rt,s.resume]]),c}const i=n[Bt]?.split(ke),o=i?jn(i.join(ke)):void 0;throw new Sr([{id:o,value:e}])}var or=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()});me.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=pg(n),a=pt(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,t,a):r=await me.runWithConfig(a,async()=>this.func(t,a)),J.isRunnable(r)&&this.recurse?await me.runWithConfig(a,async()=>r.invoke(t,a)):r}};function*pn(e,t){if(t===void 0)yield*e;else for(const n of e)yield[t,n]}async function yn(e){const t=[];for await(const n of await e)t.push(n);return t}function ds(e){const t=[];for(const n of e)t.push(n);return t}function dr(e,t){return e?"configurable"in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function GO(e){return typeof e=="object"&&e?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const Jn={[Symbol.for("LG_PASSTHROUGH")]:!0};function pa(e){return typeof e=="object"&&e?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const wo=Symbol("IS_WRITER");var Je=class Ac extends or{writes;constructor(t,n){const r=`ChannelWrite<${t.map(s=>gt(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=>vo(s)&&pa(s.value)?{mapper:s.mapper,value:t}:Pa(s)&&pa(s.value)?{channel:s.channel,value:t,skipNone:s.skipNone,mapper:s.mapper}:s);return await Ac.doWrite(n,r),t}static async doWrite(t,n){for(const a of n){if(Pa(a)){if(a.channel===vt)throw new ue("Cannot write to the reserved channel TASKS");if(pa(a.value))throw new ue("PASSTHROUGH value must be replaced")}if(vo(a)&&pa(a.value))throw new ue("PASSTHROUGH value must be replaced")}const r=[];for(const a of n)if(gt(a))r.push([vt,a]);else if(vo(a)){const i=await a.mapper.invoke(a.value,t);i!=null&&i.length>0&&r.push(...i)}else if(Pa(a)){const i=a.mapper!==void 0?await a.mapper.invoke(a.value,t):a.value;if(GO(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?.[En];s(r)}static isWriter(t){return t instanceof Ac||wo in t&&!!t[wo]}static registerWriter(t){return Object.defineProperty(t,wo,{value:!0})}};function Pa(e){return e!==void 0&&typeof e.channel=="string"}function vo(e){return e!==void 0&&!Pa(e)&&J.isRunnable(e.mapper)}var WO=class Sg extends or{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(t,n,r=!1){super({func:(s,a)=>Sg.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?.[Wn];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 hr=new Ns;var js=class hs extends De{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=hr;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??hr,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===hr&&t.length===0))return this.bound===hr&&t.length===1?t[0]:this.bound===hr?new Et({first:t[0],middle:t.slice(1,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):t.length>0?new Et({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 hs({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 hs({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===hr?new hs({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:$e(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new hs({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 JO(e){return"steps"in e&&Array.isArray(e.steps)}function Kl(e){return"lg_is_pregel"in e&&e.lg_is_pregel===!0}function Tg(e){const t=[e];for(const n of t){if(Kl(n))return n;JO(n)&&t.push(...n.steps)}}function Er(e,t,n=!0,r=!1){try{return e[t].get()}catch(s){if(s.name===Le.unminifiable_name){if(r)return s;if(n)return null}throw s}}function Yn(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===Le.unminifiable_name)continue}return r}else return Er(e,t)}function*KO(e,t){if(e.graph===be.PARENT)throw new ue("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(gt(r))yield[bt,vt,r];else if(typeof r=="string")yield[bt,`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(vg))for(const[n,r]of Object.entries(e.resume)){const s=t.filter(a=>a[0]===n&&a[1]===rt).map(a=>a[2]).slice(0,1)??[];s.push(r),yield[n,rt,s]}else yield[bt,rt,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[bt,n,r];else for(const[n,r]of Object.entries(e.update))yield[bt,n,r]}}function*Eg(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*bo(e,t,n){Array.isArray(e)?(t===!0||t.find(([r,s])=>e.includes(r)))&&(yield Yn(n,e)):(t===!0||t.some(([r,s])=>r===e))&&(yield Er(n,e))}function*ZO(e,t,n){const r=t.filter(([o,c])=>(o.config===void 0||!o.config.tags?.includes(ve))&&c[0][0]!==et&&c[0][0]!==Y);if(!r.length)return;let s;r.some(([o])=>o.writes.some(([c,l])=>c===qr))?s=r.flatMap(([o])=>o.writes.filter(([c,l])=>c===qr).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 Zl(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 Na(e,t){if(Object.keys(e).length>0){const n=Zl(t);return Object.fromEntries(Object.entries(t).filter(([r,s])=>s>(e[r]??n)))}else return t}function qO(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}function Nt(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?Nt(e,{[wt]:{...n,[e.configurable?.checkpoint_ns??""]:e.configurable?.checkpoint_id}}):e}function ii(...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 YO=(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 XO=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 QO(e){return typeof e=="object"&&e!==null&&"__lg_type"in e&&e.__lg_type==="call"}function ex(e,t){const n=new or({func:r=>t(...r),name:e,trace:!1,recurse:!1});return new Et({name:e,first:n,last:new Je([{channel:qr,value:Jn}],[ve])})}const tx=e=>e!==void 0?e+1:1;function nx(e,t){if(t==null)return!1;for(const n of e)if(t[n])return!0;return!1}function rx(e){let t;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t==null?t=e[n]:t=tO(t,e[n]));return t}function fa(e,t,n){const r=Zl(e.channel_versions),s=e.versions_seen[Y]??{};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 Ma(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=Un(e,o,-1),l=ni(o,c);ut(ti(c),l,[n],void 0,void 0),i=Yn({...t,...l},r)}else i=Yn(t,r);return i}function So(e,t,n){for(const[r,s]of n)if([dt,vt].includes(r)&&s!=null){if(!gt(s))throw new ue(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in t))throw new ue(`Invalid node name "${s.node}" in Send packet`)}e(n)}const sx=new Set([Wl,dt,rt,Y,qr,et]);function ut(e,t,n,r,s){n.sort((h,p)=>{const f=h.path?.slice(0,3)||[],y=p.path?.slice(0,3)||[];for(let S=0;S<Math.min(f.length,y.length);S+=1){if(f[S]<y[S])return-1;if(f[S]>y[S])return 1}return f.length-y.length});const a=n.some(h=>h.triggers.length>0),i=Hl(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=rx(e.channel_versions);const c=new Set(n.flatMap(h=>h.triggers).filter(h=>!wO.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)sx.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 y;try{y=f.update(p)}catch(S){if(S.name===ue.unminifiable_name){const b=new ue(`Invalid update for channel "${h}" with values ${JSON.stringify(p)}: ${S.message}`);throw b.lc_error_code=S.lc_error_code,b}else throw S}y&&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&&!nx(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*ax(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 vr(e,t,n,r,s,a,i){const o={},c=r[vt];if(c?.isAvailable()){const l=c.get().length;for(let u=0;u<l;u+=1){const d=kc([dt,u],e,t,n,r,s,a,i);d!==void 0&&(o[d.id]=d)}}for(const l of ax(e,n,i)){const u=kc([xa,l],e,t,n,r,s,a,i);u!==void 0&&(o[u.id]=u)}return o}function kc(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]===dt&&QO(e[e.length-1])){const p=e[e.length-1],f=ex(p.name,p.func),y=[dt],S=h===""?p.name:`${h}${ke}${p.name}`,b=yr(JSON.stringify([S,c.toString(),p.name,dt,e[1],e[2]]),t.id),v=`${S}${an}${b}`,w=[...e.slice(0,3),!0],E={langgraph_step:c,langgraph_node:p.name,langgraph_triggers:y,langgraph_path:w,langgraph_checkpoint_ns:v};if(i){const A=[];return{name:p.name,input:p.input,proc:f,writes:A,config:ne(pt(a,{metadata:E,store:o.store??a.store}),{runName:p.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[gs]:b,[En]:k=>So(g=>A.push(...g),r,k),[Wn]:(k,g=!1)=>Ma(t,s,{name:p.name,writes:A,triggers:y,path:w},k,g),[_e]:l??d[_e],[wt]:{...d[wt],[h]:t.id},[Cn]:To({pendingWrites:n??[],taskId:b,currentTaskInput:p.input,resumeMap:a.configurable?.[ka],namespaceHash:jn(v)}),[Oa]:t.channel_values[yo],checkpoint_id:void 0,checkpoint_ns:v}}),triggers:y,retry_policy:p.retry,cache_key:p.cache?{key:jn((p.cache.keyFunc??JSON.stringify)([p.input])),ns:[go,p.name??"__dynamic__"],ttl:p.cache.ttl}:void 0,id:b,path:w,writers:[]}}else return{id:b,name:p.name,interrupts:[],path:w}}else if(e[0]===dt){const p=typeof e[1]=="number"?e[1]:parseInt(e[1],10);if(!s[vt]?.isAvailable())return;const f=s[vt].get();if(p<0||p>=f.length)return;const y=Tc(f[p])&&!gt(f[p])?new Ge(f[p].node,f[p].args):f[p];if(!Tc(y)){console.warn(`Ignoring invalid packet ${JSON.stringify(y)} in pending sends.`);return}if(!(y.node in r)){console.warn(`Ignoring unknown node name ${y.node} in pending sends.`);return}const S=[dt],b=h===""?y.node:`${h}${ke}${y.node}`,v=yr(JSON.stringify([b,c.toString(),y.node,dt,p.toString()]),t.id),w=`${b}${an}${v}`;let E={langgraph_step:c,langgraph_node:y.node,langgraph_triggers:S,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:w};if(i){const A=r[y.node],I=A.getNode();if(I!==void 0){A.metadata!==void 0&&(E={...E,...A.metadata});const k=[];return{name:y.node,input:y.args,proc:I,subgraphs:A.subgraphs,writes:k,config:ne(pt(a,{metadata:E,tags:A.tags,store:o.store??a.store}),{runName:y.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[gs]:v,[En]:g=>So(N=>k.push(...N),r,g),[Wn]:(g,N=!1)=>Ma(t,s,{name:y.node,writes:k,triggers:S,path:e},g,N),[_e]:l??d[_e],[wt]:{...d[wt],[h]:t.id},[Cn]:To({pendingWrites:n??[],taskId:v,currentTaskInput:y.args,resumeMap:a.configurable?.[ka],namespaceHash:jn(w)}),[Oa]:t.channel_values[yo],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:S,retry_policy:A.retryPolicy,cache_key:A.cachePolicy?{key:jn((A.cachePolicy.keyFunc??JSON.stringify)([y.args])),ns:[go,A.name??"__dynamic__",y.node],ttl:A.cachePolicy.ttl}:void 0,id:v,path:e,writers:A.getWriters()}}}else return{id:v,name:y.node,interrupts:[],path:e}}else if(e[0]===xa){const p=e[1].toString(),f=r[p];if(f===void 0)return;if(n?.length){const v=h===""?p:`${h}${ke}${p}`,w=yr(JSON.stringify([v,c.toString(),p,xa,p]),t.id);if(n.some(A=>A[0]===w&&A[1]!==et))return}const y=Zl(t.channel_versions);if(y===void 0)return;const S=t.versions_seen[p]??{},b=f.triggers.find(v=>s[v].isAvailable()?(t.channel_versions[v]??y)>(S[v]??y):!1);if(b!==void 0){const v=ix(f,s,i);if(v===void 0)return;const w=h===""?p:`${h}${ke}${p}`,E=yr(JSON.stringify([w,c.toString(),p,xa,[b]]),t.id),A=`${w}${an}${E}`;let I={langgraph_step:c,langgraph_node:p,langgraph_triggers:[b],langgraph_path:e,langgraph_checkpoint_ns:A};if(i){const k=f.getNode();if(k!==void 0){f.metadata!==void 0&&(I={...I,...f.metadata});const g=[];return{name:p,input:v,proc:k,subgraphs:f.subgraphs,writes:g,config:ne(pt(a,{metadata:I,tags:f.tags,store:o.store??a.store}),{runName:p,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[gs]:E,[En]:N=>So(x=>{g.push(...x)},r,N),[Wn]:(N,x=!1)=>Ma(t,s,{name:p,writes:g,triggers:[b],path:e},N,x),[_e]:l??d[_e],[wt]:{...d[wt],[h]:t.id},[Cn]:To({pendingWrites:n??[],taskId:E,currentTaskInput:v,resumeMap:a.configurable?.[ka],namespaceHash:jn(A)}),[Oa]:t.channel_values[yo],checkpoint_id:void 0,checkpoint_ns:A}}),triggers:[b],retry_policy:f.retryPolicy,cache_key:f.cachePolicy?{key:jn((f.cachePolicy.keyFunc??JSON.stringify)([v])),ns:[go,f.name??"__dynamic__",p],ttl:f.cachePolicy.ttl}:void 0,id:E,path:e,writers:f.getWriters()}}}else return{id:E,name:p,interrupts:[],path:e}}}}function ix(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===Le.unminifiable_name)return;throw i}else if(a in t)try{r[s]=Er(t,a,!1)}catch(i){if(i.name===Le.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===Le.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 To({pendingWrites:e,taskId:t,currentTaskInput:n,resumeMap:r,namespaceHash:s}){const a=e.find(([c,l])=>c===bt&&l===rt)?.[2],o={callCounter:0,interruptCounter:-1,resume:(()=>{const c=e.filter(([l,u])=>l===t&&u===rt).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===bt&&l===rt),1),a}};return o}const Ds={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},Us=(e,t)=>`${e.start}${t}${e.end}`;function*Pd(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===Y).map(([,c])=>c);yield{id:t,name:n,input:r,triggers:a,interrupts:o}}}function ox(e){return typeof e!="object"||e===null?!1:"$writes"in e&&Array.isArray(e.$writes)}function Cg(e){const t={};for(const[n,r]of e){const s=String(n);if(s in t){const a=ox(t[s])?t[s].$writes:[t[s]];a.push(r),t[s]={$writes:a}}else t[s]=r}return t}function*cx(e,t){for(const[{id:n,name:r,config:s},a]of e)s?.tags?.includes(ve)||(yield{id:n,name:r,result:Cg(a.filter(([i])=>Array.isArray(t)?t.includes(i):i===t)),interrupts:a.filter(i=>i[0]===Y).map(i=>i[1])})}function*lx(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(Tg))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:Yn(t,n),metadata:r,next:s.map(d=>d.name),tasks:Ag(s,a,u,o),parentConfig:i?c(i):void 0}}function Ag(e,t,n,r){return e.map(s=>{const a=t.find(([l,u])=>l===s.id&&u===et)?.[2],i=t.filter(([l,u])=>l===s.id&&u===Y).map(([,,l])=>l),o=(()=>{if(a||i.length||!t.length)return;const l=t.findIndex(([u,d])=>u===s.id&&d===qr);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?Cg(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 ux(e,t,n){console.log([`${Us(Ds.blue,`[${e}:checkpoint]`)}`,`\x1B[1m State at the end of step ${e}:\x1B[0m
197
- `,JSON.stringify(Yn(t,n),null,2)].join(""))}function kg(e,t){const n=t.length;console.log([`${Us(Ds.blue,`[${e}:tasks]`)}`,`\x1B[1m Starting step ${e} with ${n} task${n===1?"":"s"}:\x1B[0m
198
- `,t.map(r=>`- ${Us(Ds.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
199
- `)].join(""))}function dx(e,t,n){const r={};for(const[s,a]of t)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(a));console.log([`${Us(Ds.blue,`[${e}:writes]`)}`,`\x1B[1m Finished step ${e} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
200
- `,Object.entries(r).map(([s,a])=>`- ${Us(Ds.yellow,s)} -> ${a.map(i=>JSON.stringify(i)).join(", ")}`).join(`
201
- `)].join(""))}var Nd=class extends Fe{_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}},Og=class extends Fe{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 hx(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 px(e){return e instanceof Error?{error:e.name,message:e.message}:{error:"Error",message:JSON.stringify(e)}}function ql(e){return typeof e!="object"||e==null?!1:"configurable"in e&&typeof e.configurable=="object"&&e.configurable!=null}function Eo(e){return!ql(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 Md(e){if(ql(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 Rd(e){const t={...e,checkpoint:Eo(e.config),parent_checkpoint:Eo(e.parentConfig),config:Md(e.config),parent_config:Md(e.parentConfig),tasks:e.tasks.map(n=>{if(ql(n.state)){const r=Eo(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete t.parentConfig,t}function fx(e){const t=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(t.encode(`event: ${s.event}
202
- data: ${hx(s.data)}
203
-
204
- `))};try{for await(const s of e){const[a,i,o]=s;let c=o;if(i==="debug"){const u=o;u.type==="checkpoint"&&(c={...u,payload:Rd(u.payload)})}i==="checkpoints"&&(c=Rd(o));const l=a?.length?`${i}|${a.join("|")}`:i;r({event:l,data:c})}}catch(s){r({event:"error",data:px(s)})}n.close()}})}const ma=Symbol.for("INPUT_DONE"),Co=Symbol.for("INPUT_RESUMING"),mx=25;function gx(...e){return new Og({passthroughFn:t=>{for(const n of e)n.modes.has(t[1])&&n.push(t)},modes:new Set(e.flatMap(t=>Array.from(t.modes)))})}var yx=class extends oO{cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation("get",e)}async set(e){return this.enqueueOperation("set",e)}async clear(e){return this.enqueueOperation("clear",e)}async stop(){await this.queue}enqueueOperation(e,...t){const n=this.queue.then(()=>this.cache[e](...t));return this.queue=n.then(()=>{},()=>{}),n}},_x=class xg{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status="pending";tasks={};stream;checkpointerPromises=[];isNested;_checkpointerChainedPromise=Promise.resolve();store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let t=!1;if(ie in this.checkpoint.channel_versions)t=!0;else for(const c in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,c)){t=!0;break}const r=this.config.configurable?.[gn]!==void 0&&this.config.configurable?.[gn],s=this.input===null||this.input===void 0,a=Pe(this.input)&&this.input.resume!=null,i=this.input===Co,o=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return t&&(r||s||a||i||o)}constructor(t){this.input=t.input,this.checkpointer=t.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=tx,this.checkpoint=t.checkpoint,this.checkpointMetadata=t.checkpointMetadata,this.checkpointPreviousVersions=t.checkpointPreviousVersions,this.channels=t.channels,this.checkpointPendingWrites=t.checkpointPendingWrites,this.step=t.step,this.stop=t.stop,this.config=t.config,this.checkpointConfig=t.checkpointConfig,this.isNested=t.isNested,this.manager=t.manager,this.outputKeys=t.outputKeys,this.streamKeys=t.streamKeys,this.nodes=t.nodes,this.skipDoneTasks=t.skipDoneTasks,this.store=t.store,this.cache=t.cache?new yx(t.cache):void 0,this.stream=t.stream,this.checkpointNamespace=t.checkpointNamespace,this.prevCheckpointConfig=t.prevCheckpointConfig,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.durability=t.durability,this.debug=t.debug,this.triggerToNodes=t.triggerToNodes}static async initialize(t){let{config:n,stream:r}=t;r!==void 0&&n.configurable?.[ri]!==void 0&&(r=gx(r,n.configurable[ri]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,a=n.configurable?.[Cn];n.configurable&&a&&(a.subgraphCounter>0&&(n=Nt(n,{[Bt]:[n.configurable[Bt],a.subgraphCounter.toString()].join(ke)})),a.subgraphCounter+=1);const i=Wn in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=Nt(n,{checkpoint_ns:"",checkpoint_id:void 0}));let o=n;n.configurable?.[wt]!==void 0&&n.configurable?.[wt]?.[n.configurable?.checkpoint_ns]&&(o=Nt(n,{checkpoint_id:n.configurable[wt][n.configurable?.checkpoint_ns]}));const c=n.configurable?.checkpoint_ns?.split(ke)??[],l=await t.checkpointer?.getTuple(o)??{config:n,checkpoint:eg(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};o={...n,...l.config,configurable:{checkpoint_ns:"",...n.configurable,...l.config.configurable}};const u=l.parentConfig,d=ti(l.checkpoint),h={...l.metadata},p=l.pendingWrites??[],f=ni(t.channelSpecs,d),y=(h.step??0)+1,S=y+(n.recursionLimit??mx)+1,b={...d.channel_versions},v=t.store?new iO(t.store):void 0;return v&&await v.start(),new xg({input:t.input,config:n,checkpointer:t.checkpointer,checkpoint:d,checkpointMetadata:h,checkpointConfig:o,prevCheckpointConfig:u,checkpointNamespace:c,channels:f,isNested:i,manager:t.manager,skipDoneTasks:s,step:y,stop:S,checkpointPreviousVersions:b,checkpointPendingWrites:p,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:r,store:v,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes})}_checkpointerPutAfterPrevious(t){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(t.config,t.checkpoint,t.metadata,t.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(t,n){let r=n;if(r.length===0)return;r.every(([i])=>i in nO)&&(r=Array.from(new Map(r.map(i=>[i[0],i])).values())),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(i=>i[0]!==t);for(const[i,o]of r)this.checkpointPendingWrites.push([t,i,o]);const s=Nt(this.checkpointConfig,{[Bt]:this.config.configurable?.checkpoint_ns??"",[Sc]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(s,r,t)),this.tasks&&this._outputWrites(t,r),!n.length||!this.cache||!this.tasks)return;const a=this.tasks[t];a==null||a.cache_key==null||n[0][0]===et||n[0][0]===Y||this.cache.set([{key:[a.cache_key.ns,a.cache_key.key],value:a.writes,ttl:a.cache_key.ttl}])}_outputWrites(t,n,r=!1){const s=this.tasks[t];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes(ve))return;if(n.length>0)if(n[0][0]===Y){if(s.path?.[0]===dt&&s.path?.at(-1)===!0)return;const a=n.filter(i=>i[0]===Y).flatMap(i=>i[1]);this._emit([["updates",{[Y]:a}],["values",{[Y]:a}]])}else n[0][0]!==et&&this._emit(ds(pn(ZO(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(ds(pn(cx([[s,n]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const t=[],n=([i,o])=>`ns:${i.join(",")}|key:${o}`,r=[],s={};for(const i of Object.values(this.tasks))i.cache_key!=null&&!i.writes.length&&(r.push([i.cache_key.ns,i.cache_key.key]),s[n([i.cache_key.ns,i.cache_key.key])]=i);if(r.length===0)return[];const a=await this.cache.get(r);for(const{key:i,value:o}of a){const c=s[n(i)];c!=null&&(c.writes.push(...o),t.push({task:c,result:o}))}return t}async tick(t){this.store&&!this.store.isRunning&&await this.store?.start();const{inputKeys:n=[]}=t;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![ma,Co].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new Sr;if(Object.values(this.tasks).every(a=>a.writes.length>0)){const a=Object.values(this.tasks).flatMap(o=>o.writes);this.updatedChannels=ut(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const i=await yn(pn(bo(this.outputKeys,a,this.channels),"values"));if(this._emit(i),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),fa(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new Sr;this.config.configurable?.[gn]!==void 0&&delete this.config.configurable?.[gn]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const r=vr(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels});if(this.tasks=r,this.checkpointer&&this._emit(await yn(pn(lx(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[a,i,o]of this.checkpointPendingWrites){if(i===et||i===Y||i===rt)continue;const c=Object.values(this.tasks).find(l=>l.id===a);c&&c.writes.push([i,o])}for(const a of Object.values(this.tasks))a.writes.length>0&&this._outputWrites(a.id,a.writes,!0)}if(Object.values(this.tasks).every(a=>a.writes.length>0))return this.tick({inputKeys:n});if(fa(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new Sr;const s=await yn(pn(Pd(Object.values(this.tasks)),"tasks"));return this._emit(s),!0}async finishAndHandleError(t){this.durability==="exit"&&(!this.isNested||typeof t<"u"||this.checkpointNamespace.every(r=>!r.includes(an)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(t);return(n||t===void 0)&&(this.output=Yn(this.channels,this.outputKeys)),n&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(r=>r.writes.length>0)&&(this.updatedChannels=ut(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(ds(pn(bo(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),Bn(t)&&!t.interrupts.length&&this._emit([["updates",{[Y]:[]}],["values",{[Y]:[]}]])),n}async acceptPush(t,n,r){if(this.interruptAfter?.length>0&&fa(this.checkpoint,this.interruptAfter,[t])){this.toInterrupt.push(t);return}const s=kc([dt,t.path??[],n,t.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,t.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!s)return;if(this.interruptBefore?.length>0&&fa(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(ds(pn(Pd([s]),"tasks"))),this.debug&&kg(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});const a=await this._matchCachedWrites();for(const{task:i}of a)this._outputWrites(i.id,i.writes,!0);return s}_suppressInterrupt(t){return Bn(t)&&!this.isNested}async _first(t){const{configurable:n}=this.config,r=n?.[Cn];if(r&&r.nullResume!==void 0&&this.putWrites(bt,[[rt,r.nullResume]]),Pe(this.input)){const i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(vg)&&(this.config.configurable??={},this.config.configurable[ka]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const o={};for(const[c,l,u]of KO(this.input,this.checkpointPendingWrites))o[c]??=[],o[c].push([l,u]);if(Object.keys(o).length===0)throw new Ed("Received empty Command input");for(const[c,l]of Object.entries(o))this.putWrites(c,l)}const s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===bt).map(i=>i.slice(1));s.length>0&&ut(this.checkpoint,this.channels,[{name:Yt,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const a=Pe(this.input)&&s.length>0;if(this.isResuming||a){for(const o in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,o)&&this.checkpoint.channel_versions[o]!==void 0){const c=this.checkpoint.channel_versions[o];this.checkpoint.versions_seen[Y]={...this.checkpoint.versions_seen[Y],[o]:c}}const i=await yn(pn(bo(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=Co;else if(a)await this._putCheckpoint({source:"input"}),this.input=ma;else{const i=await yn(Eg(t,this.input));if(i.length>0){const o=vr(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=ut(this.checkpoint,this.channels,Object.values(o).concat([{name:Yt,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=ma}else if(gn in(this.config.configurable??{}))this.input=ma;else throw new Ed(`Received no input writes for ${JSON.stringify(t,null,2)}`)}this.isNested||(this.config=Nt(this.config,{[gn]:this.isResuming}))}_emit(t){for(const[n,r]of t)if(this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){const s=n==="checkpoints"?this.step-1:this.step,a=new Date().toISOString(),i=n==="checkpoints"?"checkpoint":typeof r=="object"&&r!=null&&"result"in r?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:s,type:i,timestamp:a,payload:r}])}}_putCheckpoint(t){const n=this.checkpointMetadata===t,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=a=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=Nt(this.checkpointConfig,{[Bt]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},o=Na(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:ti(a),metadata:{...this.checkpointMetadata},newVersions:o}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};n||(this.checkpointMetadata={...t,step:this.step,parents:this.config.configurable?.[wt]??{}}),this.checkpoint=Un(this.checkpoint,r?this.channels:void 0,this.step,n?{id:this.checkpoint.id}:void 0),r&&s(this.checkpoint),n||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;const t=Nt(this.checkpointConfig,{[Bt]:this.config.configurable?.checkpoint_ns??"",[Sc]:this.checkpoint.id}),n={};for(const[r,s,a]of this.checkpointPendingWrites)n[r]??=[],n[r].push([s,a]);for(const[r,s]of Object.entries(n))this.checkpointerPromises.push(this.checkpointer.putWrites(t,s,r))}_matchWrites(t){for(const[n,r,s]of this.checkpointPendingWrites){if(r===et||r===Y||r===rt)continue;const a=Object.values(t).find(i=>i.id===n);a&&a.writes.push([r,s])}for(const n of Object.values(t))n.writes.length>0&&this._outputWrites(n.id,n.writes,!0)}};function wx(e){return Ie(e?.message)}var vx=class extends es{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,n,r=!1){if(r&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let s=t.id;n!=null&&(Wc(t)?s??=`run-${n}-tool-${t.tool_call_id}`:((s==null||s===`run-${n}`)&&(s=this.stableMessageIdMap[n]??s??`run-${n}`),this.stableMessageIdMap[n]??=s)),s!==t.id&&(t.id=s,t.lc_kwargs.id=s),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,n,r,s,a,i,o){i&&(!a||!a.includes(_O)&&!a.includes("nostream"))&&(this.metadatas[n]=[i.langgraph_checkpoint_ns.split("|"),{tags:a,name:o,...i}])}handleLLMNewToken(e,t,n,r,s,a){const i=a?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(wx(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new mt({content:e}),n))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){const n=e.generations?.[0]?.[0];Ie(n?.message)&&this._emit(this.metadatas[t],n?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,n,r,s,a,i,o){if(a!==void 0&&o===a.langgraph_node&&(s===void 0||!s.includes(ve))&&(this.metadatas[n]=[a.langgraph_checkpoint_ns.split("|"),{tags:s,name:o,...a}],typeof t=="object")){for(const c of Object.values(t))if((Ie(c)||bs(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(const l of c)(Ie(l)||bs(l))&&l.id!==void 0&&(this.seen[l.id]=l)}}handleChainEnd(e,t){const n=this.metadatas[t];if(delete this.metadatas[t],n!==void 0){if(Ie(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(const r of e)Ie(r)&&this._emit(n,r,t,!0);else if(e!=null&&typeof e=="object"){for(const r of Object.values(e))if(Ie(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(const s of r)Ie(s)&&this._emit(n,s,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};const bx=500,Sx=2,Tx=128e3,Ex=3,Cx=[400,401,402,403,404,405,406,407,409],Ax=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e.name==="GraphValueError"||e?.code==="ECONNABORTED")return!1;const t=e?.response?.status??e?.status;return!(t&&Cx.includes(+t)||e?.error?.code==="insufficient_quota")};async function Ig(e,t,n,r){const s=e.retry_policy??t;let a=s!==void 0?s.initialInterval??bx:0,i=0,o,c,{config:l}=e;for(n&&(l=Nt(l,n)),l={...l,signal:r};!r?.aborted;){e.writes.splice(0,e.writes.length),o=void 0;try{c=await e.proc.invoke(e.input,l);break}catch(u){if(o=u,o.pregelTaskId=e.id,dO(o)){const f=l?.configurable?.checkpoint_ns,y=o.command;if(y.graph===f){for(const S of e.writers)await S.invoke(y,l);o=void 0;break}else if(y.graph===be.PARENT){const S=CO(f);o.command=new be({...o.command,graph:S})}}if(Aa(o)||s===void 0||(i+=1,i>=(s.maxAttempts??Ex))||!(s.retryOn??Ax)(o))break;a=Math.min(s.maxInterval??Tx,a*(s.backoffFactor??Sx));const h=s.jitter?Math.floor(a+Math.random()*1e3):a;await new Promise(f=>setTimeout(f,h));const p=o.name??o.constructor.unminifiable_name??o.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${a.toFixed(2)}ms (attempt ${i}) after ${p}: ${o}`),l=Nt(l,{[gn]:!0})}}return{task:e,result:c,error:o,signalAborted:r?.aborted}}const Oc=Symbol.for("promiseAdded");function kx(){const e={next:()=>{},wait:Promise.resolve(Oc)};function t(n){e.next=()=>{e.wait=new Promise(t),n(Oc)}}return e.wait=new Promise(t),e}var Ox=class{nodeFinished;loop;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){const{timeout:t,retryPolicy:n,onStepWrite:r,maxConcurrency:s}=e,a=new Set;let i;const o=new AbortController,c=o.signal,l=t?AbortSignal.timeout(t):void 0,u=Object.values(this.loop.tasks).filter(f=>f.writes.length===0),{signals:d,disposeCombinedSignal:h}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:l,signal:e.signal}),p=this._executeTasksWithRetry(u,{signals:d,retryPolicy:n,maxConcurrency:s});for await(const{task:f,error:y,signalAborted:S}of p)this._commit(f,y),Bn(y)||Aa(y)&&!Bn(i)?i=y:y&&(a.size===0||!S)&&(o.abort(),a.add(y));if(h?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(f=>f.writes).flat()),a.size===1)throw Array.from(a)[0];if(a.size>1)throw new AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(Bn(i)||Aa(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:n}){const r=this.loop.config.configurable?.[Cd]??{},s=r.externalAbortSignal??n,a=t??r.timeoutAbortSignal,{signal:i,dispose:o}=ii(s,a,e),c={externalAbortSignal:s,timeoutAbortSignal:a,composedAbortSignal:i};return this.loop.config=Nt(this.loop.config,{[Cd]:c}),{signals:c,disposeCombinedSignal:o}}async*_executeTasksWithRetry(e,t){const{retryPolicy:n,maxConcurrency:r,signals:s}=t??{},a=kx(),i={},o={executingTasksMap:i,barrier:a,retryPolicy:n,scheduleTask:async(h,p,f)=>this.loop.acceptPush(h,p,f)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let c=0,l;const u=ii(s?.externalAbortSignal,s?.timeoutAbortSignal),d=u.signal?new Promise((h,p)=>{l=()=>p(new Error("Abort")),u.signal?.addEventListener("abort",l,{once:!0})}):void 0;for(;(c===0||Object.keys(i).length>0)&&e.length;){for(;Object.values(i).length<(r??e.length)&&c<e.length;c+=1){const p=e[c];i[p.id]=Ig(p,n,{[Gl]:Pg?.bind(o,this,p)},s?.composedAbortSignal).catch(f=>({task:p,error:f,signalAborted:s?.composedAbortSignal?.aborted}))}const h=await Promise.race([...Object.values(i),...d?[d]:[],a.wait]);h!==Oc&&(yield h,l!=null&&(u.signal?.removeEventListener("abort",l),u.dispose?.()),delete i[h.task.id])}}_commit(e,t){if(t!==void 0)if(Bn(t)){if(t.interrupts.length){const n=t.interrupts.map(s=>[Y,s]),r=e.writes.filter(s=>s[0]===rt);r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else Aa(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[et,{message:t.message,name:t.name}]]);else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes(ve))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([Wl,null]),this.loop.putWrites(e.id,e.writes)}};async function Pg(e,t,n,r,s,a={}){const i=t.config?.configurable?.[Cn];if(!i)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);const o=i.callCounter;i.callCounter+=1;const c=new XO({func:n,name:r,input:s,cache:a.cache,retry:a.retry,callbacks:a.callbacks}),l=await this.scheduleTask(t,o,c);if(!l)return;const u=this.executingTasksMap[l.id];if(u!==void 0)return u;if(l.writes.length>0){const d=l.writes.filter(([p])=>p===qr),h=l.writes.filter(([p])=>p===et);if(d.length>0){if(d.length===1)return Promise.resolve(d[0][1]);throw new Error(`BUG: multiple returns found for task ${l.name}__${l.id}`)}if(h.length>0){if(h.length===1){const p=h[0][1],f=p instanceof Error?p:new Error(String(p));return Promise.reject(f)}throw new Error(`BUG: multiple errors found for task ${l.name}__${l.id}`)}return}else{const d=Ig(l,a.retry,{[Gl]:Pg.bind(this,e,l)});return this.executingTasksMap[l.id]=d,this.barrier.next(),d.then(({result:h,error:p})=>p?Promise.reject(p):h)}}var Zt=class extends Error{constructor(e){super(e),this.name="GraphValidationError"}};function xx({nodes:e,channels:t,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:a,interruptBeforeNodes:i}){if(!t)throw new Zt("Channels not provided");const o=new Set,c=new Set;for(const[l,u]of Object.entries(e)){if(l===Y)throw new Zt(`"Node name ${Y} is reserved"`);if(u.constructor===js)u.triggers.forEach(d=>o.add(d));else throw new Zt(`Invalid node type ${typeof u}, expected PregelNode`)}for(const l of o)if(!(l in t))throw new Zt(`Subscribed channel '${String(l)}' not in channels`);if(Array.isArray(n)){if(n.every(l=>!o.has(l)))throw new Zt(`None of the input channels ${n} are subscribed to by any node`)}else if(!o.has(n))throw new Zt(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(l=>c.add(l)):c.add(r),s&&!Array.isArray(s)?c.add(s):Array.isArray(s)&&s.forEach(l=>c.add(l));for(const l of c)if(!(l in t))throw new Zt(`Output channel '${String(l)}' not in channels`);if(a&&a!=="*"){for(const l of a)if(!(l in e))throw new Zt(`Node ${String(l)} not in nodes`)}if(i&&i!=="*"){for(const l of i)if(!(l in e))throw new Zt(`Node ${String(l)} not in nodes`)}}function $d(e,t){if(Array.isArray(e)){for(const n of e)if(!(n in t))throw new Error(`Key ${String(n)} not found in channels`)}else if(!(e in t))throw new Error(`Key ${String(e)} not found in channels`)}var Ix=class Ng extends ir{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(t){super(),this.unique=t?.unique??this.unique,this.accumulate=t?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){const n=new Ng({unique:this.unique,accumulate:this.accumulate});return typeof t<"u"&&(n.seen=new Set(t[0]),n.values=t[1]),n}update(t){let n=!1;this.accumulate||(n=this.values.length>0,this.values=[]);const r=t.flat();if(r.length>0)if(this.unique)for(const s of r)this.seen.has(s)||(n=!0,this.seen.add(s),this.values.push(s));else n=!0,this.values.push(...r);return n}get(){if(this.values.length===0)throw new Le;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},Px=class{static subscribeTo(e,t){const{key:n,tags:r}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&n!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;typeof e=="string"?n?s={[n]:e}:s=[e]:s=Object.fromEntries(e.map(i=>[i,i]));const a=Array.isArray(e)?e:[e];return new js({channels:s,triggers:a,tags:r})}static writeTo(e,t){const n=[];for(const r of e)n.push({channel:r,value:Jn,skipNone:!1});for(const[r,s]of Object.entries(t??{}))J.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:Jn,skipNone:!0,mapper:$e(s)}):n.push({channel:r,value:s,skipNone:!1});return new Je(n)}},Nx=class extends J{lc_namespace=["langgraph","pregel"];invoke(e,t){throw new Error("Not implemented")}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},Mx=class extends Nx{static lc_name(){return"LangGraph"}lc_namespace=["langgraph","pregel"];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=["values"];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,vt in this.channels&&"lc_graph_name"in this.channels[vt]&&this.channels[vt].lc_graph_name!=="Topic")throw new Error(`Channel '${vt}' is reserved and cannot be used in the graph.`);this.channels[vt]=new Ix({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.autoValidate&&this.validate()}withConfig(e){const t=pt(this.config,e);return new this.constructor({...this,config:t})}validate(){xx({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(const[e,t]of Object.entries(this.nodes))for(const n of t.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(e);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(const[n,r]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(n))continue;const s=r.subgraphs?.length?r.subgraphs:[r.bound];for(const a of s){const i=Tg(a);if(i!==void 0){if(n===e){yield[n,i];return}if(e===void 0&&(yield[n,i]),t){let o=e;e!==void 0&&(o=e.slice(n.length+1));for(const[c,l]of i.getSubgraphs(o,t))yield[`${n}${ke}${c}`,l]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};const s=ni(this.channels,t.checkpoint);if(t.pendingWrites?.length){const d=t.pendingWrites.filter(([h,p])=>h===bt).map(([h,p,f])=>[String(p),f]);d.length>0&&ut(t.checkpoint,s,[{name:Yt,writes:d,triggers:[]}],void 0,this.triggerToNodes)}const a=Object.values(vr(t.checkpoint,t.pendingWrites,this.nodes,s,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),i=await yn(this.getSubgraphsAsync()),o=t.config.configurable?.checkpoint_ns??"",c={};for(const d of a){const h=i.find(([f])=>f===d.name);if(!h)continue;let p=`${String(d.name)}${an}${d.id}`;if(o&&(p=`${o}${ke}${p}`),n===void 0){const f={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:p}};c[d.id]=f}else{const f={configurable:{[_e]:n,thread_id:t.config.configurable?.thread_id,checkpoint_ns:p}},y=h[1];c[d.id]=await y.getState(f,{subgraphs:!0})}}if(r&&t.pendingWrites?.length){const d=Object.fromEntries(a.map(p=>[p.id,p]));for(const[p,f,y]of t.pendingWrites)[et,Y,wa].includes(f)||p in d&&d[p].writes.push([String(f),y]);const h=a.filter(p=>p.writes.length>0);h.length>0&&ut(t.checkpoint,s,h,void 0,this.triggerToNodes)}let l=t?.metadata;l&&t?.config?.configurable?.thread_id&&(l={...l,thread_id:t.config.configurable.thread_id});const u=a.filter(d=>d.writes.length===0).map(d=>d.name);return{values:Yn(s,this.streamChannelsAsIs),next:u,tasks:Ag(a,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:$n(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){const n=e.configurable?.[_e]??this.checkpointer;if(!n)throw new Ca("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=e.configurable?.checkpoint_ns??"";if(r!==""&&e.configurable?.[_e]===void 0){const o=_o(r);for await(const[c,l]of this.getSubgraphsAsync(o,!0))if(c===o)return await l.getState(dr(e,{[_e]:n}),{subgraphs:t?.subgraphs});throw new Error(`Subgraph with namespace "${o}" not found.`)}const s=pt(this.config,e),a=await n.getTuple(e);return await this._prepareStateSnapshot({config:s,saved:a,subgraphCheckpointer:t?.subgraphs?n:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){const n=e.configurable?.[_e]??this.checkpointer;if(!n)throw new Ca("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=e.configurable?.checkpoint_ns??"";if(r!==""&&e.configurable?.[_e]===void 0){const a=_o(r);for await(const[i,o]of this.getSubgraphsAsync(a,!0))if(i===a){yield*o.getStateHistory(dr(e,{[_e]:n}),t);return}throw new Error(`Subgraph with namespace "${a}" not found.`)}const s=pt(this.config,e,{configurable:{checkpoint_ns:r}});for await(const a of n.list(s,t))yield this._prepareStateSnapshot({config:a.config,saved:a})}async bulkUpdateState(e,t){const n=e.configurable?.[_e]??this.checkpointer;if(!n)throw new Ca("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(t.length===0)throw new Error("No supersteps provided");if(t.some(i=>i.updates.length===0))throw new Error("No updates provided");const r=e.configurable?.checkpoint_ns??"";if(r!==""&&e.configurable?.[_e]===void 0){const i=_o(r);for await(const[,o]of this.getSubgraphsAsync(i,!0))return await o.bulkUpdateState(dr(e,{[_e]:n}),t);throw new Error(`Subgraph "${i}" not found`)}const s=async(i,o)=>{const c=this.config?pt(this.config,i):i,l=await n.getTuple(c),u=l!==void 0?ti(l.checkpoint):eg(),d={...l?.checkpoint.channel_versions},h=l?.metadata?.step??-1;let p=dr(c,{checkpoint_ns:c.configurable?.checkpoint_ns??""}),f=c.metadata??{};l?.config.configurable&&(p=dr(c,l.config.configurable),f={...l.metadata,...f});const{values:y,asNode:S}=o[0];if(y==null&&S===void 0){if(o.length>1)throw new ue("Cannot create empty checkpoint with multiple updates");const k=await n.put(p,Un(u,void 0,h),{source:"update",step:h+1,parents:l?.metadata?.parents??{}},{});return $n(k,l?l.metadata:void 0)}const b=ni(this.channels,u);if(y===null&&S===B){if(o.length>1)throw new ue("Cannot apply multiple updates when clearing state");if(l){const g=vr(u,l.pendingWrites||[],this.nodes,b,l.config,!0,{step:(l.metadata?.step??-1)+1,checkpointer:n,store:this.store}),N=(l.pendingWrites||[]).filter(x=>x[0]===bt).map(x=>x.slice(1));N.length>0&&ut(u,b,[{name:Yt,writes:N,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[x,M,z]of l.pendingWrites||[])[et,Y,wa].includes(M)||x in g&&g[x].writes.push([M,z]);ut(u,b,Object.values(g),n.getNextVersion.bind(n),this.triggerToNodes)}const k=await n.put(p,Un(u,b,h),{...f,source:"update",step:h+1,parents:l?.metadata?.parents??{}},Na(d,u.channel_versions));return $n(k,l?l.metadata:void 0)}if(S===mO){if(o.length>1)throw new ue("Cannot copy checkpoint with multiple updates");if(l==null)throw new ue("Cannot copy a non-existent checkpoint");const k=x=>!Array.isArray(x)||x.length===0?!1:x.every(M=>Array.isArray(M)&&M.length===2),g=Un(u,void 0,h),N=await n.put(l.parentConfig??dr(l.config,{checkpoint_id:void 0}),g,{source:"fork",step:h+1,parents:l.metadata?.parents??{}},{});if(k(y)){const x=vr(g,l.pendingWrites,this.nodes,b,N,!1,{step:h+2}),M=Object.values(x).reduce((ce,{name:he,id:cr})=>(ce[he]??=[],ce[he].push({id:cr}),ce),{}),z=y.reduce((ce,he)=>{const[cr,q]=he;ce[q]??=[];const Mi=ce[q].length,ss=M[q]?.[Mi]?.id;return ce[q].push({values:cr,asNode:q,taskId:ss}),ce},{});return s($n(N,l.metadata),Object.values(z).flat())}return $n(N,l.metadata)}if(S===Yt){if(o.length>1)throw new ue("Cannot apply multiple updates when updating as input");const k=await yn(Eg(this.inputChannels,y));if(k.length===0)throw new ue(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);ut(u,b,[{name:Yt,writes:k,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const g=l?.metadata?.step!=null?l.metadata.step+1:-1,N=await n.put(p,Un(u,b,g),{source:"input",step:g,parents:l?.metadata?.parents??{}},Na(d,u.channel_versions));return await n.putWrites(N,k,yr(Yt,u.id)),$n(N,l?l.metadata:void 0)}if(c.configurable?.checkpoint_id===void 0&&l?.pendingWrites!==void 0&&l.pendingWrites.length>0){const k=vr(u,l.pendingWrites,this.nodes,b,l.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(l.metadata?.step??-1)+1}),g=(l.pendingWrites??[]).filter(x=>x[0]===bt).map(x=>x.slice(1));g.length>0&&ut(l.checkpoint,b,[{name:Yt,writes:g,triggers:[]}],void 0,this.triggerToNodes);for(const[x,M,z]of l.pendingWrites)[et,Y,wa].includes(M)||k[x]===void 0||k[x].writes.push([M,z]);const N=Object.values(k).filter(x=>x.writes.length>0);N.length>0&&ut(u,b,N,void 0,this.triggerToNodes)}const v=Object.values(u.versions_seen).map(k=>Object.values(k)).flat().find(k=>!!k),w=[];if(o.length===1){let{values:k,asNode:g,taskId:N}=o[0];if(g===void 0&&Object.keys(this.nodes).length===1)[g]=Object.keys(this.nodes);else if(g===void 0&&v===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(g=this.inputChannels);else if(g===void 0){const x=Object.entries(u.versions_seen).map(([M,z])=>Object.values(z).map(ce=>[ce,M])).flat().filter(([M,z])=>z!==Y).sort(([M],[z])=>tg(M,z));x&&(x.length===1?g=x[0][1]:x[x.length-1][0]!==x[x.length-2][0]&&(g=x[x.length-1][1]))}if(g===void 0)throw new ue('Ambiguous update, specify "asNode"');w.push({values:k,asNode:g,taskId:N})}else for(const{asNode:k,values:g,taskId:N}of o){if(k==null)throw new ue('"asNode" is required when applying multiple updates');w.push({values:g,asNode:k,taskId:N})}const E=[];for(const{asNode:k,values:g,taskId:N}of w){if(this.nodes[k]===void 0)throw new ue(`Node "${k.toString()}" does not exist`);const x=this.nodes[k].getWriters();if(!x.length)throw new ue(`No writers found for node "${k.toString()}"`);E.push({name:k,input:g,proc:x.length>1?Et.from(x,{omitSequenceTags:!0}):x[0],writes:[],triggers:[Y],id:N??yr(Y,u.id),writers:[]})}for(const k of E)await k.proc.invoke(k.input,ne({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[En]:g=>k.writes.push(...g),[Wn]:(g,N=!1)=>Ma(u,b,k,g,N)}}));for(const k of E){const g=k.writes.filter(N=>N[0]!==dt);l!==void 0&&g.length>0&&await n.putWrites(p,g,k.id)}ut(u,b,E,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const A=Na(d,u.channel_versions),I=await n.put(p,Un(u,b,h+1),{source:"update",step:h+1,parents:l?.metadata?.parents??{}},A);for(const k of E){const g=k.writes.filter(N=>N[0]===dt);g.length>0&&await n.putWrites(I,g,k.id)}return $n(I,l?l.metadata:void 0)};let a=e;for(const{updates:i}of t)a=await s(a,i);return a}async updateState(e,t,n){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:n}]}])}_defaults(e){const{debug:t,streamMode:n,inputKeys:r,outputKeys:s,interruptAfter:a,interruptBefore:i,...o}=e;let c=!0;const l=t!==void 0?t:this.debug;let u=s;u===void 0?u=this.streamChannelsAsIs:$d(u,this.channels);let d=r;d===void 0?d=this.inputChannels:$d(d,this.channels);const h=i??this.interruptBefore??[],p=a??this.interruptAfter??[];let f;n!==void 0?(f=Array.isArray(n)?n:[n],c=typeof n=="string"):(e.configurable?.[gs]!==void 0?f=["values"]:f=this.streamMode,c=!0);let y;if(this.checkpointer===!1)y=void 0;else if(e!==void 0&&e.configurable?.[_e]!==void 0)y=e.configurable[_e];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");y=this.checkpointer}const S=e.store??this.store,b=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");const v=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),w=e.durability??v??e?.configurable?.[dg]??"async";return[l,f,d,u,o,h,p,y,S,c,b,w]}async stream(e,t){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...t,signal:ii(t?.signal,n.signal).signal},s=await super.stream(e,r);return new Nd(t?.encoding==="text/event-stream"?fx(s):s,n)}streamEvents(e,t,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...t,callbacks:YO(this.config?.callbacks,t?.callbacks),signal:ii(t?.signal,r.signal).signal};return new Nd(super.streamEvents(e,s,n),r)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){const n="version"in(t??{})?void 0:t?.encoding??void 0,r=t?.subgraphs,s=pg(this.config,t);if(s.recursionLimit===void 0||s.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&s.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const a=await this._validateInput(e),{runId:i,...o}=s,[c,l,,u,d,h,p,f,y,S,b,v]=this._defaults(o);typeof d.context<"u"?d.context=await this._validateContext(d.context):d.configurable=await this._validateContext(d.configurable);const w=new Og({modes:new Set(l)});if(this.checkpointer===!0){d.configurable??={};const M=d.configurable[Bt]??"";d.configurable[Bt]=M.split(ke).map(z=>z.split(an)[0]).join(ke)}if(l.includes("messages")){const M=new vx(ce=>w.push(ce)),{callbacks:z}=d;if(z===void 0)d.callbacks=[M];else if(Array.isArray(z))d.callbacks=z.concat(M);else{const ce=z.copy();ce.addHandler(M,!0),d.callbacks=ce}}d.writer??=M=>{if(!l.includes("custom"))return;const z=EO()?.configurable?.[Bt]?.split(ke).slice(0,-1);w.push([z??[],"custom",M])},d.interrupt??=this.userInterrupt??bg;const A=await(await nt(d))?.handleChainStart(this.toJSON(),qO(e,"input"),i,void 0,void 0,void 0,d?.runName??this.getName()),I=Hl(this.channels);let k,g;const x=(async()=>{try{k=await _x.initialize({input:a,config:d,checkpointer:f,nodes:this.nodes,channelSpecs:I,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:y,cache:b,stream:w,interruptAfter:p,interruptBefore:h,manager:A,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:v});const M=new Ox({loop:k,nodeFinished:d.configurable?.[yO]});t?.subgraphs&&(k.config.configurable={...k.config.configurable,[ri]:k.stream}),await this._runLoop({loop:k,runner:M,debug:c,config:d}),v==="sync"&&await Promise.all(k?.checkpointerPromises??[])}catch(M){g=M}finally{try{k&&(await k.store?.stop(),await k.cache?.stop()),await Promise.all(k?.checkpointerPromises??[])}catch(M){g=g??M}g?w.error(g):w.close()}})();try{for await(const M of w){if(M===void 0)throw new Error("Data structure error.");const[z,ce,he]=M;if(l.includes(ce)){if(n==="text/event-stream"){r?yield[z,ce,he]:yield[null,ce,he];continue}r&&!S?yield[z,ce,he]:S?r?yield[z,he]:yield he:yield[ce,he]}}}catch(M){throw await A?.handleChainError(g),M}finally{await x}await A?.handleChainEnd(k?.output??{},i,void 0,void 0,void 0)}async invoke(e,t){const n=t?.streamMode??"values",r={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},s=[],a=await this.stream(e,r),i=[];let o;for await(const c of a)n==="values"?hg(c)?i.push(c[Y]):o=c:s.push(c);if(n==="values"){if(i.length>0){const c=i.flat(1);if(o==null)return{[Y]:c};if(typeof o=="object")return{...o,[Y]:c}}return o}return s}async _runLoop(e){const{loop:t,runner:n,debug:r,config:s}=e;let a;try{for(;await t.tick({inputKeys:this.inputChannels});){for(const{task:i}of await t._matchCachedWrites())t._outputWrites(i.id,i.writes,!0);r&&ux(t.checkpointMetadata.step,t.channels,this.streamChannelsList),r&&kg(t.step,Object.values(t.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,o)=>{r&&dx(i,o,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(t.status==="out_of_steps")throw new uO([`Recursion limit of ${s.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(i){if(a=i,!await t.finishAndHandleError(a))throw i}finally{a===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}},Xr=class Mg extends ir{lc_graph_name="EphemeralValue";guard;value=[];constructor(t=!0){super(),this.guard=t}fromCheckpoint(t){const n=new Mg(this.guard);return typeof t<"u"&&(n.value=[t]),n}update(t){if(t.length===0){const n=this.value.length>0;return this.value=[],n}if(t.length!==1&&this.guard)throw new ue("EphemeralValue can only receive one value per step.");return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new Le;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Le;return this.value[0]}isAvailable(){return this.value.length!==0}},Rg=class{path;ends;constructor(e){J.isRunnable(e.path)?this.path=e.path:this.path=$e(e.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((t,n)=>(t[n]=n,t),{}):e.pathMap}run(e,t){return Je.registerWriter(new or({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,e,t)}catch(s){throw s.name===ag.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
205
- NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(e,t,n,r){let s=await this.path.invoke(r?r(t):e,t);Array.isArray(s)||(s=[s]);let a;if(this.ends?a=s.map(o=>gt(o)?o:this.ends[o]):a=s,a.some(o=>!o))throw new Error("Branch condition returned unknown or null destination");if(a.filter(gt).some(o=>o.node===B))throw new ue("Cannot send a packet to the END node");return await n(a,t)??e}},Rx=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(r){return r.length>=1&&typeof r[0]!="string"}const n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,a]of n){for(const o of[ke,an])if(r.includes(o))throw new Error(`"${o}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===B)throw new Error(`Node \`${r}\` is reserved.`);const i=$e(s);this.nodes[r]={runnable:i,metadata:a?.metadata,subgraphs:Kl(i)?[i]:a?.subgraphs,ends:a?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),e===B)throw new Error("END cannot be a start node");if(t===ie)throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([n])=>n===e)&&!("channels"in this))throw new Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,n){const r=typeof e=="object"?e:{source:e,path:t,pathMap:n};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!J.isRunnable(r.path)){const a=Array.isArray(r.pathMap)?r.pathMap.join(","):Object.keys(r.pathMap??{}).join(",");r.path=$e(r.path).withConfig({runName:`Branch<${r.source}${a!==""?`,${a}`:""}>`.slice(0,63)})}const s=r.path.getName()==="RunnableLambda"?"condition":r.path.getName();if(this.branches[r.source]&&this.branches[r.source][s])throw new Error(`Condition \`${s}\` already present for node \`${e}\``);return this.branches[r.source]??={},this.branches[r.source][s]=new Rg(r),this}setEntryPoint(e){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(ie,e)}setFinishPoint(e){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(e,B)}compile({checkpointer:e,interruptBefore:t,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]]);const s=new $g({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[ie]:new Xr,[B]:new Xr},inputChannels:ie,outputChannels:B,streamChannels:[],streamMode:"values",name:r});for(const[a,i]of Object.entries(this.nodes))s.attachNode(a,i);for(const[a,i]of this.edges)s.attachEdge(a,i);for(const[a,i]of Object.entries(this.branches))for(const[o,c]of Object.entries(i))s.attachBranch(a,o,c);return s.validate()}validate(e){const t=new Set([...this.allEdges].map(([r,s])=>r));for(const[r]of Object.entries(this.branches))t.add(r);for(const r of t)if(r!==ie&&!(r in this.nodes))throw new Error(`Found edge starting at unknown node \`${r}\``);const n=new Set([...this.allEdges].map(([r,s])=>s));for(const[r,s]of Object.entries(this.branches))for(const a of Object.values(s))if(a.ends!=null)for(const i of Object.values(a.ends))n.add(i);else{n.add(B);for(const i of Object.keys(this.nodes))i!==r&&n.add(i)}for(const r of Object.values(this.nodes))for(const s of r.ends??[])n.add(s);for(const r of Object.keys(this.nodes))if(!n.has(r))throw new hO([`Node \`${r}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join(`
206
- `),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!==B&&!(r in this.nodes))throw new Error(`Found edge ending at unknown node \`${r}\``);if(e){for(const r of e)if(!(r in this.nodes))throw new Error(`Interrupt node \`${r}\` is not present`)}this.compiled=!0}},$g=class extends Mx{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new Xr,this.nodes[e]=new js({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new Je([{channel:e,value:Jn}],[ve])),this.streamChannels.push(e)}attachEdge(e,t){if(t===B){if(e===ie)throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new Je([{channel:B,value:Jn}],[ve]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e===ie&&!this.nodes[ie]&&(this.nodes[ie]=Px.subscribeTo(ie,{tags:[ve]})),this.nodes[e].pipe(n.run(s=>{const a=s.map(i=>gt(i)?i:{channel:i===B?B:`branch:${e}:${t}:${i}`,value:Jn});return new Je(a,[ve])}));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const s of r)if(s!==B){const a=`branch:${e}:${t}:${s}`;this.channels[a]=new Xr,this.nodes[s].triggers.push(a),this.nodes[s].channels.push(a)}}async getGraphAsync(e){const t=e?.xray,n=new Os,r={[ie]:n.addNode({schema:sa()},ie)},s={};let a={};t&&(a=Object.fromEntries((await yn(this.getSubgraphsAsync())).filter(c=>Ld(c[1]))));function i(c,l,u,d=!1){if(l===B&&s[B]===void 0&&(s[B]=n.addNode({schema:sa()},B)),r[c]!==void 0){if(s[l]===void 0)throw new Error(`End node ${l} not found!`);return n.addEdge(r[c],s[l],u!==l?u:void 0,d)}}for(const[c,l]of Object.entries(this.builder.nodes)){const u=je(c),d=l.runnable,h=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?h.__interrupt="before,after":this.interruptBefore?.includes(c)?h.__interrupt="before":this.interruptAfter?.includes(c)&&(h.__interrupt="after"),t){const p=typeof t=="number"?t-1:t,f=a[c]!==void 0?await a[c].getGraphAsync({...e,xray:p}):d.getGraph(e);if(f.trimFirstNode(),f.trimLastNode(),Object.keys(f.nodes).length>1){let b=function(w){return w?w.lc_runnable:!1},v=function(w,E){if(w!==void 0&&!br(w))return w;if(b(E))try{let A=E.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return E.getName()}else return E.name??"UnknownSchema"};const[y,S]=n.extend(f,u);if(y===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:v(S.id,S.data),...S}),s[u]={name:v(y.id,y.data),...y}}else{const y=n.addNode(d,u,h);r[u]=y,s[u]=y}}else{const p=n.addNode(d,u,h);r[u]=p,s[u]=p}}const o=[...this.builder.allEdges].sort(([c],[l])=>c<l?-1:l>c?1:0);for(const[c,l]of o)i(je(c),je(l));for(const[c,l]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[je(d),je(d)])),[B]:B};for(const d of Object.values(l)){let h;d.ends!==void 0?h=d.ends:h=u;for(const[p,f]of Object.entries(h))i(je(c),je(f),p,!0)}}for(const[c,l]of Object.entries(this.builder.nodes))if(l.ends!==void 0)for(const u of l.ends)i(je(c),je(u),void 0,!0);return n}getGraph(e){const t=e?.xray,n=new Os,r={[ie]:n.addNode({schema:sa()},ie)},s={};let a={};t&&(a=Object.fromEntries(ds(this.getSubgraphs()).filter(c=>Ld(c[1]))));function i(c,l,u,d=!1){return l===B&&s[B]===void 0&&(s[B]=n.addNode({schema:sa()},B)),n.addEdge(r[c],s[l],u!==l?u:void 0,d)}for(const[c,l]of Object.entries(this.builder.nodes)){const u=je(c),d=l.runnable,h=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?h.__interrupt="before,after":this.interruptBefore?.includes(c)?h.__interrupt="before":this.interruptAfter?.includes(c)&&(h.__interrupt="after"),t){const p=typeof t=="number"?t-1:t,f=a[c]!==void 0?a[c].getGraph({...e,xray:p}):d.getGraph(e);if(f.trimFirstNode(),f.trimLastNode(),Object.keys(f.nodes).length>1){let b=function(w){return w?w.lc_runnable:!1},v=function(w,E){if(w!==void 0&&!br(w))return w;if(b(E))try{let A=E.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return E.getName()}else return E.name??"UnknownSchema"};const[y,S]=n.extend(f,u);if(y===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:v(S.id,S.data),...S}),s[u]={name:v(y.id,y.data),...y}}else{const y=n.addNode(d,u,h);r[u]=y,s[u]=y}}else{const p=n.addNode(d,u,h);r[u]=p,s[u]=p}}const o=[...this.builder.allEdges].sort(([c],[l])=>c<l?-1:l>c?1:0);for(const[c,l]of o)i(je(c),je(l));for(const[c,l]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[je(d),je(d)])),[B]:B};for(const d of Object.values(l)){let h;d.ends!==void 0?h=d.ends:h=u;for(const[p,f]of Object.entries(h))i(je(c),je(f),p,!0)}}return n}};function Ld(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function je(e){return e==="subgraph"?`"${e}"`:e}const zn=(e,t)=>e.size===t.size&&[...e].every(n=>t.has(n));var $x=class Lg extends ir{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){const n=new Lg(this.names);return typeof t<"u"&&(n.seen=new Set(t)),n}update(t){let n=!1;for(const r of t)if(this.names.has(r))this.seen.has(r)||(this.seen.add(r),n=!0);else throw new ue(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!zn(this.names,this.seen))throw new Le}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&zn(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&zn(this.names,this.seen)}},Lx=class jg extends ir{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(t){super(),this.names=t,this.seen=new Set,this.finished=!1}fromCheckpoint(t){const n=new jg(this.names);if(typeof t<"u"){const[r,s]=t;n.seen=new Set(r),n.finished=s}return n}update(t){let n=!1;for(const r of t)if(this.names.has(r)&&!this.seen.has(r))this.seen.add(r),n=!0;else if(!this.names.has(r))throw new ue(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!zn(this.names,this.seen))throw new Le}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&zn(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&zn(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&zn(this.names,this.seen)}};const jx="lg:";var Dx=class{_map=new WeakMap;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){const n=this.get(e);this._map.set(e,t(n))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){const t={},n=Cs(e);for(const[r,s]of Object.entries(n)){const a=this.get(s);a?.reducer?t[r]=new wc(a.reducer.fn,a.default):t[r]=new Vl}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;const n=Object.entries(t).filter(([,a])=>a===!0).sort(([a],[i])=>a.localeCompare(i)).map(([a,i])=>`${a}:${i}`).join("|"),r=this._extensionCache.get(n)??new WeakMap;if(r.has(e))return r.get(e);let s=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){const a=Object.entries(Cs(e)).map(([i,o])=>{const c=this.get(o);let l=t.withReducerSchema?c?.reducer?.schema??o:o;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){const u=Vr(l)??Vr(o),d=JSON.stringify({...c.jsonSchemaExtra,description:u});l=l.describe(`${jx}${d}`)}return[i,l]});s=up(e,Object.fromEntries(a)),Se(s)&&(s._def.unknownKeys="strip")}return t.asPartial&&(s=sl(s)),r.set(e,s),this._extensionCache.set(n,r),s}};const Fs=new Dx;function Qr(e,t){if(t.reducer&&!t.default){const n=_i(e);n!=null&&(t.default=n)}if(t.reducer){const n=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return Fs.extend(n,()=>t),n}else return Fs.extend(e,()=>t),e}const Qt="__root__",xc=Symbol.for("langgraph.state.partial");var Ux=class extends Rx{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=Fs;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){if(super(),Wx(e)){const r=this._metaRegistry.getChannelsForSchema(e.state),s=e.input!=null?this._metaRegistry.getChannelsForSchema(e.input):r,a=e.output!=null?this._metaRegistry.getChannelsForSchema(e.output):r;this._schemaDefinition=r,this._schemaRuntimeDefinition=e.state,this._inputDefinition=s,this._inputRuntimeDefinition=e.input??xc,this._outputDefinition=a,this._outputRuntimeDefinition=e.output??e.state}else if(Qe(e)){const r=this._metaRegistry.getChannelsForSchema(e);this._schemaDefinition=r,this._schemaRuntimeDefinition=e,this._inputDefinition=r,this._inputRuntimeDefinition=xc,this._outputDefinition=r,this._outputRuntimeDefinition=e}else if(Gx(e))this._schemaDefinition=e.input.spec,this._inputDefinition=e.input.spec,this._outputDefinition=e.output.spec;else if(Vx(e))this._schemaDefinition=e.stateSchema.spec,this._inputDefinition=e.input?.spec??this._schemaDefinition,this._outputDefinition=e.output?.spec??this._schemaDefinition;else if(zx(e)||jd(e)){const r=jd(e)?e.spec:e;this._schemaDefinition=r}else if(Hx(e)){const r=Fx(e.channels);this._schemaDefinition=r}else throw new Error("Invalid StateGraph input. Make sure to pass a valid Annotation.Root or Zod schema.");this._inputDefinition??=this._schemaDefinition,this._outputDefinition??=this._schemaDefinition,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition);function n(r){return typeof r=="object"&&r!=null&&!("spec"in r)&&!Qe(r)}n(t)?(Qe(t.context)&&(this._configRuntimeSchema=t.context),this._interrupt=t.interrupt,this._writer=t.writer):Qe(t)&&(this._configRuntimeSchema=t)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(n=>[n,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(const[t,n]of Object.entries(e)){let r;if(typeof n=="function"?r=n():r=n,this.channels[t]!==void 0){if(this.channels[t]!==r&&r.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=r}}}addNode(...e){function t(r){return r.length>=1&&typeof r[0]!="string"}const n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([r,s])=>[r,s]):[[e[0],e[1],e[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,a]of n){if(r in this.channels)throw new Error(`${r} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const u of[ke,an])if(r.includes(u))throw new Error(`"${u}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===B||r===ie)throw new Error(`Node \`${r}\` is reserved.`);let i=this._schemaDefinition;a?.input!==void 0&&(Qe(a.input)?i=this._metaRegistry.getChannelsForSchema(a.input):a.input.spec!==void 0&&(i=a.input.spec)),i!==void 0&&this._addSchema(i);let o;J.isRunnable(s)?o=s:typeof s=="function"?o=new or({func:s,name:r,trace:!1}):o=$e(s);let c=a?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);const l={runnable:o,retryPolicy:a?.retryPolicy,cachePolicy:c,metadata:a?.metadata,input:i??this._schemaDefinition,subgraphs:Kl(o)?[o]:a?.subgraphs,ends:a?.ends,defer:a?.defer};this.nodes[r]=l}return this}addEdge(e,t){if(typeof e=="string")return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(const n of e){if(n===B)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(r=>r===n))throw new Error(`Need to add a node named "${n}" first`)}if(t===B)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(n=>n===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){const t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let n;for(const[r,s,a]of t){if(r in this.nodes)throw new Error(`Node names must be unique: node with the name "${r}" already exists.`);const i=r;this.addNode(i,s,a),n!=null&&this.addEdge(n,i),n=i}return this}compile({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:s,name:a,description:i}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(s)?s:[]]);const o=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=o.length===1&&o[0]===Qt?Qt:o,l=Object.keys(this.channels),u=l.length===1&&l[0]===Qt?Qt:l,d=this._interrupt,h=new Bx({builder:this,checkpointer:e,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[ie]:new Xr},inputChannels:ie,outputChannels:c,streamChannels:u,streamMode:"updates",store:t,cache:n,name:a,description:i,userInterrupt:d});h.attachNode(ie);for(const[p,f]of Object.entries(this.nodes))h.attachNode(p,f);h.attachBranch(ie,Ad,Dd(),{withReader:!1});for(const[p]of Object.entries(this.nodes))h.attachBranch(p,Ad,Dd(),{withReader:!1});for(const[p,f]of this.edges)h.attachEdge(p,f);for(const[p,f]of this.waitingEdges)h.attachEdge(p,f);for(const[p,f]of Object.entries(this.branches))for(const[y,S]of Object.entries(f))h.attachBranch(p,y,S);return h.validate()}};function Fx(e){const t={};for(const[n,r]of Object.entries(e))t[n]=bc(r);return t}var Bx=class extends $g{description;_metaRegistry=Fs;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let n;e===ie?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([o])=>o):n=Object.keys(this.builder.channels);function r(o){if(Pe(o))return o.graph===be.PARENT?null:o._updateAsTuples();if(Array.isArray(o)&&o.length>0&&o.some(c=>Pe(c))){const c=[];for(const l of o)if(Pe(l)){if(l.graph===be.PARENT)continue;c.push(...l._updateAsTuples())}else c.push([Qt,l]);return c}else if(o!=null)return[[Qt,o]];return null}const s=e;function a(o){if(o){if(Pe(o))return o.graph===be.PARENT?null:o._updateAsTuples().filter(([c])=>n.includes(c));if(Array.isArray(o)&&o.length>0&&o.some(Pe)){const c=[];for(const l of o)if(Pe(l)){if(l.graph===be.PARENT)continue;c.push(...l._updateAsTuples().filter(([u])=>n.includes(u)))}else{const u=a(l);u&&c.push(...u??[])}return c}else{if(typeof o=="object"&&!Array.isArray(o))return Object.entries(o).filter(([c])=>n.includes(c));{const c=Array.isArray(o)?"array":typeof o;throw new ue(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${c}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const i=[{value:Jn,mapper:new or({func:n.length&&n[0]===Qt?r:a,trace:!1,recurse:!1})}];if(e===ie)this.nodes[e]=new js({tags:[ve],triggers:[ie],channels:[ie],writers:[new Je(i,[ve])]});else{const o=t?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(o)).map(d=>[d,d])),l=Object.keys(c).length===1&&Qt in c,u=`branch:to:${e}`;this.channels[u]=t?.defer?new pO:new Xr(!1),this.nodes[e]=new js({triggers:[u],channels:l?Object.keys(c):c,writers:[new Je(i,[ve])],mapper:l?void 0:d=>Object.fromEntries(Object.entries(d).filter(([h])=>h in c)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:t?.cachePolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!==B){if(typeof e=="string")this.nodes[e].writers.push(new Je([{channel:`branch:to:${t}`,value:null}],[ve]));else if(Array.isArray(e)){const n=`join:${e.join("+")}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new Lx(new Set(e)):new $x(new Set(e)),this.nodes[t].triggers.push(n);for(const r of e)this.nodes[r].writers.push(new Je([{channel:n,value:r}],[ve]))}}}attachBranch(e,t,n,r={withReader:!0}){const s=async(a,i)=>{const o=a.filter(l=>l!==B);if(!o.length)return;const c=o.map(l=>gt(l)?l:{channel:l===B?l:`branch:to:${l}`,value:e});await Je.doWrite({...i,tags:(i.tags??[]).concat([ve])},c)};this.nodes[e].writers.push(n.run(s,r.withReader?a=>WO.doRead(a,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;const t=(()=>{const n=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition,s=a=>{if(a!=null)return this._metaRegistry.getExtendedChannelSchemas(a,{withReducerSchema:!0})};if(Qe(n))return s(n);if(n===xc)return sl(s(r))})();if(Pe(e)){const n=e;return e.update&&t!=null&&(n.update=bn(t,e.update)),n}return t!=null?bn(t,e):e}isInterrupted(e){return hg(e)}async _validateContext(e){const t=this.builder._configRuntimeSchema;return Qe(t)&&bn(t,e),e}};function zx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||og(t))}function jd(e){return typeof e=="object"&&e!==null&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"}function Hx(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function Vx(e){return typeof e=="object"&&e!==null&&e.stateSchema!==void 0}function Gx(e){return typeof e=="object"&&e!==null&&e.stateSchema===void 0&&e.input!==void 0&&e.output!==void 0}function Wx(e){return!(typeof e!="object"||e==null||!("state"in e)||!Qe(e.state)||"input"in e&&!Qe(e.input)||"output"in e&&!Qe(e.output))}function Jx(e){if(gt(e))return[e];const t=[];Pe(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(Pe));const n=[];for(const r of t){if(r.graph===be.PARENT)throw new ig(r);gt(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Dd(){const e=new or({func:Jx,tags:[ve],trace:!1,recurse:!1,name:"<control_branch>"});return new Rg({path:e})}const Dg="__remove_all__";function Ug(e,t){const n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],s=n.map(Gt),a=r.map(Gt);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=Ce(),u.lc_kwargs.id=u.id);let i;for(let u=0;u<a.length;u+=1){const d=a[u];(d.id===null||d.id===void 0)&&(d.id=Ce(),d.lc_kwargs.id=d.id),d.getType()==="remove"&&d.id===Dg&&(i=u)}if(i!=null)return a.slice(i+1);const o=[...s],c=new Map(o.map((u,d)=>[u.id,d])),l=new Set;for(const u of a){const d=c.get(u.id);if(d!==void 0)u.getType()==="remove"?l.add(u.id):(l.delete(u.id),o[d]=u);else{if(u.getType()==="remove")throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);c.set(u.id,o.length),o.push(u)}}return o.filter(u=>!l.has(u.id))}vc.Root({messages:vc({reducer:Ug,default:()=>[]})});const oi={reducer:{fn:Ug},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};te({messages:Qr(Ht(),oi)});lO();const Ic=Symbol.for("langgraph-zod");Ic in globalThis||(globalThis[Ic]=new WeakSet);function Ud(e){const t=globalThis[Ic];t.has(e)||(Object.defineProperty(e,"langgraph",{get(){const n=this;return{metadata(r){return Qr(n,{jsonSchemaExtra:r})},reducer(r,s){const a=_i(n);return Qr(n,{default:a,reducer:{schema:s,fn:r}})}}}}),t.add(e))}try{Ud(au.prototype),Ud(au.prototype)}catch(e){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:e})}var Kx=class extends f_{constructor(e){super(),this.parent=e,this._map=this.parent._map}add(e,...t){const n=t[0];if(n&&!n?.default){const r=_i(e);r!=null&&(n.default=r)}return super.add(e,...t)}};new Kx(Fs);function Zx(e=!0,t,n=[]){const r={messages:Qr(Ht(),oi),jumpTo:en([Io("model_request"),Io("tools"),my()]).optional()},s=a=>{const{shape:i}=a;for(const[o,c]of Object.entries(i))o.startsWith("_")||o in r||(r[o]=c)};t&&"shape"in t&&s(t);for(const a of n)a.stateSchema&&s(a.stateSchema);return e&&(r.structuredResponse=ht().optional()),te(r)}te({llmInputMessages:Qr(Ht(),{reducer:{fn:(e,t)=>oi.reducer.fn([],t)},default:()=>[]}),messages:Qr(Ht(),oi)});const Fd="prompt",Ao=/<name>(.*?)<\/name>/s,ko=/<content>(.*?)<\/content>/s;function qx(e){if(!D.isInstance(e)||mt.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 Yx(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(Ao),a=r.text.match(ko);return s&&(!a||a[1]==="")?(n=s[1],!1):!0}return!0}).map(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(Ao),a=r.text.match(ko);return!s||!a?r:(n=s[1],{...r,text:a[1]})}return r});else{const r=e.content,s=r.match(Ao),a=r.match(ko);if(!s||!a)return e;n=s[1],t=a[1]}return new D({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function ye(e){return J.isRunnable(e)}function Bd(e){return Cl(e)?"bindTools"in e&&typeof e.bindTools=="function":!1}const Oo=(e,t,n={})=>{if(Bd(e))return e.bindTools(t,n);if(De.isRunnableBinding(e)&&Bd(e.bound)){const r=e.bound.bindTools(t,n);return De.isRunnableBinding(r)?new De({bound:r.bound,config:{...e.config,...r.config},kwargs:{...e.kwargs,...r.kwargs},configFactories:r.configFactories??e.configFactories}):new De({bound:r,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};function Fg(e){if(typeof e=="function")return;let t=e;if(Et.isRunnableSequence(t)&&(t=t.steps.find(n=>De.isRunnableBinding(n))||t),!qa(t)){if(De.isRunnableBinding(t)){const n=t.kwargs!=null&&typeof t.kwargs=="object"&&"tools"in t.kwargs&&Array.isArray(t.kwargs.tools)&&t.kwargs.tools.length>0,r=t.config!=null&&typeof t.config=="object"&&"tools"in t.config&&Array.isArray(t.config.tools)&&t.config.tools.length>0;if(n||r)throw new sc}if("tools"in t&&t.tools!==void 0&&Array.isArray(t.tools)&&t.tools.length>0)throw new sc}}function Bg(e){return!!(D.isInstance(e)&&e.tool_calls&&e.tool_calls.length>0)}function Xx(e){let t;if(e==null)t=at.from(n=>n.messages).withConfig({runName:Fd});else if(typeof e=="string"){const n=new fe(e);t=at.from(r=>[n,...r.messages??[]]).withConfig({runName:Fd})}else throw new Error(`Got unexpected type for 'prompt': ${typeof e}`);return t}async function Qx(e,t,n={}){const r=Oo(e,t,n);if(r)return r;if(qa(e)){const s=Oo(await e._model(),t,n);if(s)return s}if(Et.isRunnableSequence(e)){const s=e.steps.findIndex(a=>De.isRunnableBinding(a)||Cl(a)||qa(a));if(s>=0){const a=Oo(e.steps[s],t,n);if(a){const i=e.steps.slice();return i.splice(s,1,a),Et.from(i)}}}throw new Error(`llm ${e} must define bindTools method.`)}function eI(e){if(e.length===0)return;if(e.length===1)return e[0];function t(r,s){return async(a,i)=>r(a,async c=>s(c,async l=>i(l)))}let n=e[e.length-1];for(let r=e.length-2;r>=0;r--)n=t(e[r],n);return n}function tI(e){const t=e.filter(n=>n.wrapToolCall);if(t.length!==0)return eI(t.map(n=>{const r=n.wrapToolCall;return async(a,i)=>{try{const o=await r(a,i);if(!X.isInstance(o)&&!Pe(o))throw new Error(`Invalid response from "wrapToolCall" in middleware "${n.name}": expected ToolMessage or Command, got ${typeof o}`);return o}catch(o){throw o instanceof Error&&!o.message.includes(`middleware "${n.name}"`)&&(o.message=`Error in middleware "${n.name}": ${o.message}`),o}}}))}async function nI(e,t){const n={};for(const r of e)if(r.stateSchema){const s=dp(r.stateSchema,o=>o.startsWith("_")),a=await tl(s,t);if(a.success){Object.assign(n,a.data);continue}const i=a.error.issues.filter(o=>o.code==="invalid_type"&&o.message==="Required").map(o=>` - ${o.path.join(".")}: ${o.message}`).join(`
207
- `);throw new Error(`Middleware "${r.name}" has required state fields that must be initialized:
208
- ${i}
209
-
210
- To fix this, either:
211
- 1. Provide default values in your middleware's state schema using .default():
212
- stateSchema: z.object({
213
- myField: z.string().default("default value")
214
- })
215
-
216
- 2. Or make the fields optional using .optional():
217
- stateSchema: z.object({
218
- myField: z.string().optional()
219
- })
220
-
221
- 3. Or ensure you pass these values when invoking the agent:
222
- agent.invoke({
223
- messages: [...],
224
- ${a.error.issues[0]?.path.join(".")}: "value"
225
- })`)}return n}function rI(e){const t={messages:Ht(()=>[]),structuredResponse:ht().optional()};if(!e)return te(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 te(r)}function Ut(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 zg(...e){return AbortSignal.any(e.filter(t=>t!=null&&typeof t=="object"&&"aborted"in t&&typeof t.aborted=="boolean"))}var Yl=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=pt(this.config,t),r=await me.runWithConfig(n,async()=>this.func(e,n));return J.isRunnable(r)&&this.recurse?await me.runWithConfig(n,async()=>r.invoke(e,n)):(this.#e=r,r)}};function sI(e,t){let n,r;if(t==="inline")n=qx,r=Yx;else throw new Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function s(a){return a.map(n)}return Et.from([at.from(s),e,at.from(r)])}var zd=class extends Yl{#e;#n={runModelCallCount:0};constructor(e){super({name:e.name??"model",func:(t,n)=>this.#s(t,n)}),this.#e=e}#t(e){if(!this.#e.responseFormat)return;const t=Pf(this.#e.responseFormat,void 0,e);return t.every(r=>r instanceof Fn)?{type:"native",strategy:t[0]}:{type:"tool",tools:t.filter(r=>r instanceof mn).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:[],_privateState:this.getState()._privateState};const r=this.getState()._privateState,s=await this.#c(e,t);this.#n.runModelCallCount++;const a={...r,threadLevelCallCount:r.threadLevelCallCount+1};return"structuredResponse"in s?{messages:[...e.messages,...s.messages||[]],structuredResponse:s.structuredResponse,_privateState:a}:s instanceof be?s:(s.name=this.name,s.lc_kwargs.name=this.name,this.#u(e,s)?{messages:[new D({content:"Sorry, need more steps to process this request.",name:this.name,id:s.id})],_privateState:a}:{messages:[s],_privateState:a})}#o(){if(typeof this.#e.model=="string")return Zs(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#c(e,t,n={}){const r=await this.#o(),s=t,a=async l=>{Fg(l.model);const u=this.#t(l.model),d=await this.#d(l.model,l,u);let h=this.#i(e);h={...h,messages:l.messages};const p=zg(this.#e.signal,t.signal),f={...t,signal:p},y=await d.invoke(h,f);if(u?.type==="native"){const w=u.strategy.parse(y);return w?{structuredResponse:w,messages:[y]}:y}if(!u||!y.tool_calls)return y;const S=y.tool_calls.filter(w=>w.name in u.tools);if(S.length===0)return y;if(S.length>1)return this.#l(y,S,u);const v=u.tools[S[0].name]?.options?.toolMessageContent;return this.#r(y,S[0],u,v??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 y=>{const S=p.contextSchema?bn(p.contextSchema,s?.context||{}):s?.context,b=this.getState()._privateState,v=Object.freeze({...b,context:S,writer:s.writer,interrupt:s.interrupt,signal:s.signal}),w={...y,state:{...f(),messages:e.messages},runtime:v},E=async A=>{const I=A.tools??[],k=I.filter(N=>ye(N)&&!this.#e.toolClasses.some(x=>x.name===N.name));if(k.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${p.name}": ${k.map(N=>N.name).join(", ")}. This is not supported.`);const g=I.filter(N=>ye(N)&&this.#e.toolClasses.every(x=>x!==N));if(g.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${p.name}": ${g.map(N=>N.name).join(", ")}. This is not supported.`);return h(A)};if(!p.wrapModelCall)return E(w);try{const A=await p.wrapModelCall(w,E);if(!D.isInstance(A))throw new Error(`Invalid response from "wrapModelCall" in middleware "${p.name}": expected AIMessage, got ${typeof A}`);return A}catch(A){throw A instanceof Error&&!A.message.includes(`middleware "${p.name}"`)&&(A.message=`Error in middleware "${p.name}": ${A.message}`),A}}}}const c={model:r,systemPrompt:this.#e.systemPrompt,messages:e.messages,tools:this.#e.toolClasses,state:{messages:e.messages},runtime:Object.freeze({...this.getState()._privateState,context:s?.context,writer:s.writer,interrupt:s.interrupt,signal:s.signal})};return o(c)}#l(e,t,n){const r=new ac(t.map(s=>s.name));return this.#a(r,e,t[0],n)}#r(e,t,n,r){const s=n.tools[t.name];try{const a=s.parse(t.args);return{structuredResponse:a,messages:[e,new D(r??`Returning structured response: ${JSON.stringify(a)}`)]}}catch(a){return this.#a(a,e,t,n)}}async#a(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 ac))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}#u(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&&Bg(e.messages.at(-1))))}#i(e){const{messages:t,llmInputMessages:n,...r}=e;return n&&n.length>0?{messages:n,...r}:{messages:t,...r}}async#d(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"){if(!Al(e))throw new Error("Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.");const l={name:n.strategy.schema?.name??"extract",description:Vr(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 Qx(e,a,{...r,...t?.modelSettings??{},tool_choice:i});return Xx(t?.systemPrompt??this.#e.systemPrompt).pipe(this.#e.includeAgentName==="inline"?sI(o,this.#e.includeAgentName):o)}static get nodeOptions(){return{input:te({messages:Pn(Ht()),_privateState:te({threadLevelCallCount:St()})})}}getState(){const e=super.getState(),t=e&&!(e instanceof be)?e:{_privateState:{threadLevelCallCount:0,runModelCallCount:0}};return{messages:[],...t,_privateState:{threadLevelCallCount:0,...t._privateState??{},...this.#n}}}};const Hg=e=>Array.isArray(e)&&e.every(tt.isInstance),aI=e=>typeof e=="object"&&e!=null&&"messages"in e&&Hg(e.messages),iI=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e;function oI(e,t){return e instanceof El?new X({content:e.message,tool_call_id:t.id,name:t.name}):new X({content:`${e}
226
- Please fix your mistakes.`,tool_call_id:t.id,name:t.name})}var cI=class extends Yl{tools;trace=!1;signal;handleToolErrors=oI;wrapToolCall;getPrivateState;constructor(e,t){const{name:n,tags:r,handleToolErrors:s,wrapToolCall:a,getPrivateState: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.wrapToolCall=a,this.getPrivateState=i,this.signal=t?.signal}#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}
227
- Please fix your mistakes.`,tool_call_id:t.id});throw e}async runTool(e,t,n){const r=async l=>{const{toolCall:u}=l,d=this.tools.find(h=>h.name===u.name);if(d===void 0)throw new Error(`Tool "${u.name}" not found.`);try{const h=await d.invoke({...u,type:"tool_call"},{...t,signal:zg(this.signal,t.signal)});return X.isInstance(h)||Pe(h)?h:new X({name:d.name,content:typeof h=="string"?h:JSON.stringify(h),tool_call_id:u.id})}catch(h){throw h instanceof Ss?new El(h,u):h}},s=t,a=this.getPrivateState?.()||{threadLevelCallCount:0,runModelCallCount:0},i={context:s?.context,writer:s?.writer,interrupt:s?.interrupt,signal:s?.signal,threadLevelCallCount:a.threadLevelCallCount,runModelCallCount:a.runModelCallCount},o=this.tools.find(l=>l.name===e.name);if(!o)throw new Error(`Tool "${e.name}" not found.`);const c={toolCall:e,tool:o,state:n||{},runtime:i};if(this.wrapToolCall&&n)try{return await this.wrapToolCall(c,r)}catch(l){return this.#e(l,e,!0)}try{return await r(c)}catch(l){return this.#e(l,e,!1)}}async run(e,t){let n;if(iI(e))n=[await this.runTool(e.lg_tool_call,t,e)];else{let a;if(Hg(e))a=e;else if(aI(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(Pe))return Array.isArray(e)?n:{messages:n};const r=[];let s=null;for(const a of n)Pe(a)?a.graph===be.PARENT&&Array.isArray(a.goto)&&a.goto.every(i=>lI(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 lI(e){return e instanceof Ge}var uI=class{},dI=class{},Pi=class extends Yl{#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=bn(this.middleware.contextSchema,l)}}const r={context:n,writer:t?.writer,interrupt:t?.interrupt,signal:t?.signal,...this.#e.getPrivateState()},s=await this.runHook(e,Object.freeze(Object.assign(new dI,{...r,context:Object.freeze(Object.assign(new uI,n))})));if(delete s?._privateState,!s)return{...e,jumpTo:void 0};let a,i;if(this.name?.startsWith("BeforeAgentNode_")?(a=_n(this.middleware.beforeAgent),i="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(a=_n(this.middleware.beforeModel),i="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(a=_n(this.middleware.afterAgent),i="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(a=_n(this.middleware.afterModel),i="afterModel.canJumpTo"),typeof s.jumpTo=="string"&&!a?.includes(s.jumpTo)){const c=a&&a.length>0?`must be one of: ${a?.join(", ")}.`:i?`no ${i} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${s.jumpTo}, ${c}.`)}const o=Ut(s.jumpTo);if(typeof s=="object"&&"type"in s){if(s.type==="terminate"){if(s.error)throw s.error;return{...e,...s.result||{},jumpTo:o}}throw new Error(`Invalid control action: ${JSON.stringify(s)}`)}return{...e,...s,jumpTo:o}}get nodeOptions(){return{input:rI(this.middleware.stateSchema)}}},hI=class extends Pi{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 ki(this.middleware.beforeAgent)(e,t)}},pI=class extends Pi{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 ki(this.middleware.beforeModel)(e,t)}},fI=class extends Pi{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 ki(this.middleware.afterModel)(e,t)}},mI=class extends Pi{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 ki(this.middleware.afterAgent)(e,t)}},gI=class{#e;#n="v2";#t;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"&&Fg(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=Zx(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),i=new Ux(s,this.options.contextSchema),o=[],c=[],l=[],u=[],d=[];this.#t=new zd({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 E,A,I,k;const g=p[w];if(h.has(g.name))throw new Error(`Middleware ${g.name} is defined multiple times`);if(h.add(g.name),g.beforeAgent){E=new hI(g,{getPrivateState:()=>this.#t.getState()._privateState});const N=`${g.name}.before_agent`;o.push({index:w,name:N,allowed:_n(g.beforeAgent)}),i.addNode(N,E,E.nodeOptions)}if(g.beforeModel){A=new pI(g,{getPrivateState:()=>this.#t.getState()._privateState});const N=`${g.name}.before_model`;c.push({index:w,name:N,allowed:_n(g.beforeModel)}),i.addNode(N,A,A.nodeOptions)}if(g.afterModel){I=new fI(g,{getPrivateState:()=>this.#t.getState()._privateState});const N=`${g.name}.after_model`;l.push({index:w,name:N,allowed:_n(g.afterModel)}),i.addNode(N,I,I.nodeOptions)}if(g.afterAgent){k=new mI(g,{getPrivateState:()=>this.#t.getState()._privateState});const N=`${g.name}.after_agent`;u.push({index:w,name:N,allowed:_n(g.afterAgent)}),i.addNode(N,k,k.nodeOptions)}g.wrapModelCall&&d.push([g,()=>({...E?.getState(),...A?.getState(),...I?.getState(),...k?.getState()})])}i.addNode("model_request",this.#t,zd.nodeOptions);const f=tI(p);if(n.filter(ye).length>0){const w=new cI(n.filter(ye),{signal:this.options.signal,wrapToolCall:f,getPrivateState:()=>this.#t.getState()._privateState});i.addNode("tools",w)}let y;o.length>0?y=o[0].name:c.length>0?y=c[0].name:y="model_request";const S=c.length>0?c[0].name:"model_request",b=u.length>0?u[u.length-1].name:B;i.addEdge(ie,y);for(let w=0;w<o.length;w++){const E=o[w],A=E.name,k=w===o.length-1?S:o[w+1].name;if(E.allowed&&E.allowed.length>0){const g=n.filter(ye).length>0,N=E.allowed.map(M=>Ut(M)).filter(M=>M!=="tools"||g),x=Array.from(new Set([k,...N.map(M=>M===B?b:M)]));i.addConditionalEdges(A,this.#a(n.filter(ye),k,b),x)}else i.addEdge(A,k)}for(let w=0;w<c.length;w++){const E=c[w],A=E.name,k=w===c.length-1?"model_request":c[w+1].name;if(E.allowed&&E.allowed.length>0){const g=n.filter(ye).length>0,N=E.allowed.map(M=>Ut(M)).filter(M=>M!=="tools"||g),x=Array.from(new Set([k,...N]));i.addConditionalEdges(A,this.#u(n.filter(ye),k),x)}else i.addEdge(A,k)}const v=l.at(-1);if(l.length>0&&v)i.addEdge("model_request",v.name);else{const E=this.#s(n.filter(ye)).map(A=>A===B?b:A);E.length===1?i.addEdge("model_request",E[0]):i.addConditionalEdges("model_request",this.#c(b),E)}for(let w=l.length-1;w>0;w--){const E=l[w],A=E.name,I=l[w-1].name;if(E.allowed&&E.allowed.length>0){const k=n.filter(ye).length>0,g=E.allowed.map(x=>Ut(x)).filter(x=>x!=="tools"||k),N=Array.from(new Set([I,...g]));i.addConditionalEdges(A,this.#r(n.filter(ye),E.allowed,I),N)}else i.addEdge(A,I)}if(l.length>0){const w=l[0],E=w.name,A=this.#s(n.filter(ye),!0).filter(g=>g!=="tools"||n.filter(ye).length>0),I=!!(w.allowed&&w.allowed.length>0),k=A.map(g=>g===B?b:g);i.addConditionalEdges(E,this.#l(n.filter(ye),I,b),k)}for(let w=u.length-1;w>0;w--){const E=u[w],A=E.name,I=u[w-1].name;if(E.allowed&&E.allowed.length>0){const k=n.filter(ye).length>0,g=E.allowed.map(x=>Ut(x)).filter(x=>x!=="tools"||k),N=Array.from(new Set([I,...g]));i.addConditionalEdges(A,this.#r(n.filter(ye),E.allowed,I),N)}else i.addEdge(A,I)}if(u.length>0){const w=u[0],E=w.name;if(w.allowed&&w.allowed.length>0){const A=n.filter(ye).length>0,I=w.allowed.map(g=>Ut(g)).filter(g=>g!=="tools"||A),k=Array.from(new Set([B,...I]));i.addConditionalEdges(E,this.#r(n.filter(ye),w.allowed,B),k)}else i.addEdge(E,B)}if(n.filter(ye).length>0){const w=S;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}#s(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 Ge("tools",{...t,lg_tool_call:i}))}}#l(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 Ge("tools",{...s,jumpTo:void 0}):new Ge("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 Ge("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=>Ut(s)));return s=>{if(s.jumpTo){const a=Ut(s.jumpTo);if(a===B&&r.has(B))return B;if(a==="tools"&&r.has("tools"))return e.length===0?B:new Ge("tools",{...s,jumpTo:void 0});if(a==="model_request"&&r.has("model_request"))return new Ge("model_request",{...s,jumpTo:void 0})}return n}}#a(e,t,n){return r=>{if(!r.jumpTo)return t;const s=Ut(r.jumpTo);return s===B?n:s==="tools"?e.length===0?n:new Ge("tools",{...r,jumpTo:void 0}):new Ge("model_request",{...r,jumpTo:void 0})}}#u(e,t){return n=>{if(!n.jumpTo)return t;const r=Ut(n.jumpTo);return r===B?B:r==="tools"?e.length===0?B:new Ge("tools",{...n,jumpTo:void 0}):new Ge("model_request",{...n,jumpTo:void 0})}}async#i(e){if(!this.options.middleware||this.options.middleware.length===0||e instanceof be||!e)return e;const t=await nI(this.options.middleware,e),n={...e};if(!n)return n;for(const[r,s]of Object.entries(t))r in n||(n[r]=s);return n}async#d(e){if(!e?.configurable?.thread_id)return;const t=await this.#e.getState(e);t.values._privateState&&this.#t.setState({structuredResponse:void 0,_privateState:t.values._privateState})}async invoke(e,t){const n=await this.#i(e);return await this.#d(t),this.#e.invoke(n,t)}async stream(e,t){const n=await this.#i(e);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 Vg(e){return new gI(e)}const Gg=`<role>
228
- Context Extraction Assistant
229
- </role>
230
-
231
- <primary_objective>
232
- Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
233
- </primary_objective>
234
-
235
- <objective_information>
236
- 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.
237
- 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.
238
- </objective_information>
239
-
240
- <instructions>
241
- 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.
242
- 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.
243
- </instructions>
244
-
245
- 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:
246
-
247
- 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.
248
- Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
249
-
250
- <messages>
251
- Messages to summarize:
252
- {messages}
253
- </messages>`,Wg="## Previous conversation summary:",Jg=20,yI=4e3,Hd=5,Vd=te({model:Ht(),maxTokensBeforeSummary:St().optional(),messagesToKeep:St().default(Jg),tokenCounter:Yd().args(Pn(ht())).returns(en([St(),Xd(St())])).optional(),summaryPrompt:Oe().default(Gg),summaryPrefix:Oe().default(Wg)});function _I(e){return Ct({name:"SummarizationMiddleware",contextSchema:Vd,beforeModel:async(t,n)=>{const r=bn(Vd,e),s={model:r.model,maxTokensBeforeSummary:n.context.maxTokensBeforeSummary!==void 0?n.context.maxTokensBeforeSummary:r.maxTokensBeforeSummary,messagesToKeep:n.context.messagesToKeep===Jg?r.messagesToKeep:n.context.messagesToKeep??r.messagesToKeep,tokenCounter:n.context.tokenCounter!==void 0?n.context.tokenCounter:r.tokenCounter,summaryPrompt:n.context.summaryPrompt===Gg?r.summaryPrompt:n.context.summaryPrompt??r.summaryPrompt,summaryPrefix:n.context.summaryPrefix===Wg?r.summaryPrefix:n.context.summaryPrefix??r.summaryPrefix},{messages:a}=t;wI(a);const i=s.tokenCounter||kl,o=await i(a);if(s.maxTokensBeforeSummary==null||o<s.maxTokensBeforeSummary)return;const{systemPrompt:c,conversationMessages:l}=vI(a),u=TI(l,s.messagesToKeep);if(u<=0)return;const{messagesToSummarize:d,preservedMessages:h}=bI(c,l,u),p=await kI(d,s.model,s.summaryPrompt,i),f=SI(c,p,s.summaryPrefix);return{messages:[new vn({id:Dg}),f,...h]}}})}function wI(e){for(const t of e)t.id||(t.id=Ce())}function vI(e){return e.length>0&&fe.isInstance(e[0])?{systemPrompt:e[0],conversationMessages:e.slice(1)}:{systemPrompt:null,conversationMessages:e}}function bI(e,t,n){const r=t.slice(0,n),s=t.slice(n);return e&&r.unshift(e),{messagesToSummarize:r,preservedMessages:s}}function SI(e,t,n){let r="";if(e){const{content:a}=e;typeof a=="string"&&(r=a.split(n)[0].trim())}const s=r?`${r}
254
- ${n}
255
- ${t}`:`${n}
256
- ${t}`;return new fe({content:s,id:e?.id||Ce()})}function TI(e,t){if(e.length<=t)return 0;const n=e.length-t;for(let r=n;r>=0;r--)if(EI(e,r))return r;return 0}function EI(e,t){if(t>=e.length)return!0;const n=Math.max(0,t-Hd),r=Math.min(e.length,t+Hd);for(let s=n;s<r;s++){if(!Bg(e[s]))continue;const a=CI(e[s]);if(AI(e,s,t,a))return!1}return!0}function CI(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 AI(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 kI(e,t,n,r){if(!e.length)return"No previous conversation history.";const s=await OI(e,r);if(!s.length)return"Previous conversation was too long to summarize.";try{const a=n.replace("{messages}",JSON.stringify(s,null,2)),i=await t.invoke(a),{content:o}=i;return typeof o=="string"?o.trim():"Error generating summary: Invalid response format"}catch(a){return`Error generating summary: ${a}`}}async function OI(e,t){try{return await Sl(e,{maxTokens:yI,tokenCounter:async n=>Promise.resolve(t(n)),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return e.slice(-15)}}const xI=Yd().args(Ht(),Ht(),Ht()).returns(en([Oe(),Xd(Oe())])),Kg=["approve","edit","reject"],II=Fr(Kg),PI=te({allowedDecisions:Pn(II),description:en([Oe(),xI]).optional(),argsSchema:$c(ht()).optional()}),Gd=te({interruptOn:$c(en([Rc(),PI])).optional(),descriptionPrefix:Oe().default("Tool execution requires approval")});function NI(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"}
257
-
258
- Tool: ${o}
259
- 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 Ct({name:"HumanInTheLoopMiddleware",contextSchema:Gd,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const a=bn(Gd,{...e,...s.context||{}});if(!a)return;const{messages:i}=r;if(!i.length)return;const o=[...i].reverse().find(v=>D.isInstance(v));if(!o||!o.tool_calls?.length||!a.interruptOn)return;const c={};for(const[v,w]of Object.entries(a.interruptOn))typeof w=="boolean"?w===!0&&(c[v]={allowedDecisions:[...Kg]}):w.allowedDecisions&&(c[v]=w);const l=[],u=[];for(const v of o.tool_calls)v.name in c?l.push(v):u.push(v);if(!l.length)return;const d=[],h=[];for(const v of l){const w=c[v.name],{actionRequest:E,reviewConfig:A}=await t(v,w,r,s);d.push(E),h.push(A)}const y=(await bg({actionRequests:d,reviewConfigs:h})).decisions;if(!y||!Array.isArray(y))throw new Error("Invalid HITLResponse: decisions must be a non-empty array");if(y.length!==l.length)throw new Error(`Number of human decisions (${y.length}) does not match number of hanging tool calls (${l.length}).`);const S=[...u],b=[];for(let v=0;v<y.length;v++){const w=y[v],E=l[v],A=c[E.name],{revisedToolCall:I,toolMessage:k}=n(w,E,A);I&&S.push(I),k&&b.push(k)}return D.isInstance(o)&&(o.tool_calls=S),{messages:[o,...b]}}}})}const MI=!0,RI="5m",$I=3,LI="warn",jI=te({enableCaching:Rc().optional(),ttl:Fr(["5m","1h"]).optional(),minMessagesToCache:St().optional(),unsupportedModelBehavior:Fr(["ignore","warn","raise"]).optional()});var Wd=class extends Error{constructor(e){super(e),this.name="PromptCachingMiddlewareError"}};function DI(e){return Ct({name:"PromptCachingMiddleware",contextSchema:jI,wrapModelCall:(t,n)=>{const r=t.runtime.context.enableCaching??e?.enableCaching??MI,s=t.runtime.context.ttl??e?.ttl??RI,a=t.runtime.context.minMessagesToCache??e?.minMessagesToCache??$I,i=t.runtime.context.unsupportedModelBehavior??e?.unsupportedModelBehavior??LI;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 Wd(`${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 Wd("Last message content is not a string or array")}})}function UI(e){return Ct({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 FI="Your goal is to select the most relevant tools for answering the user's query.";function BI(e){if(!e||e.length===0)throw new Error("Invalid usage: tools must be non-empty");const t=e.map(r=>Io(r.name)),n=en(t);return te({tools:Pn(n).describe("Tools to use. Place the most relevant tools first.")})}const zI=te({model:Oe().or(Qd(Si)).optional(),systemPrompt:Oe().optional(),maxTools:St().optional(),alwaysInclude:Pn(Oe()).optional()});function HI(e){return Ct({name:"LLMToolSelector",contextSchema:zI,async wrapModelCall(t,n){const r=await VI(t,e,t.runtime);if(!r)return n(t);const s=BI(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(GI(i,r.availableTools,r.validToolNames,t,e))}})}async function VI(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??FI;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(y=>y.name)),f=a.filter(y=>!p.has(y));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+=`
260
- 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)de.isInstance(p)&&(u=p);if(!u)throw new Error("No user message found in request messages");const d=r?typeof r=="string"?await Zs(r):r:e.model,h=c.map(p=>p.name);return{availableTools:c,systemMessage:l,lastUserMessage:u,model:d,validToolNames:h}}function GI(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 WI=te({rules:$c(Oe(),Qd(RegExp).describe("Regular expression pattern to match PII")).optional()});function JI(){return Math.random().toString(36).substring(2,11)}function xo(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=JI();return n[c]=o,`[REDACTED_${i}_${c}]`})}return r}async function KI(e,t){if(de.isInstance(e)||X.isInstance(e)||fe.isInstance(e)){const n=e.content,r=await xo(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 xo(n,t.rules,t.redactionMap),a=await xo(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 ys(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 Jd(e,t){if(de.isInstance(e)||X.isInstance(e)||fe.isInstance(e)){const n=e.content,r=ys(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=ys(n,t),a=ys(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 ZI(e={}){const t={};return Ct({name:"PIIRedactionMiddleware",contextSchema:WI,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=>KI(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}=Jd(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(ys(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}=Jd(s,t),d=s.tool_calls?.find(p=>p.name.startsWith("extract-"))?.args,h=d?JSON.parse(ys(JSON.stringify(d),t)):void 0;if(i||u)return{...n,...h?{structuredResponse:h}:{},messages:[new vn({id:s.id}),new vn({id:r.id}),l,a]}}return{...n,...o?{structuredResponse:o}:{},messages:[new vn({id:r.id}),a]}}})}const qI="[cleared]";var Zg=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??qI}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 YI(e={}){const t=e.edits??[new Zg],n=e.tokenCountMethod??"approx";return Ct({name:"ContextEditingMiddleware",wrapModelCall:async(r,s)=>{if(!r.messages||r.messages.length===0)return s(r);const a=r.systemPrompt?[new fe(r.systemPrompt)]:[],i=n==="approx"?kl: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 Kd(e,t){let n=0;for(const r of e)D.isInstance(r)&&r.tool_calls&&(t===void 0?n+=r.tool_calls.length:n+=r.tool_calls.filter(s=>s.name===t).length);return n}function XI(e){let t=-1;for(let n=e.length-1;n>=0;n--)if(de.isInstance(e[n])){t=n;break}return t===-1?e:e.slice(t+1)}function qg(e,t,n,r,s){const a=s?`'${s}' tool call`:"Tool call",i=[];return n!==void 0&&e>=n&&i.push(`thread limit reached (${e}/${n})`),r!==void 0&&t>=r&&i.push(`run limit reached (${t}/${r})`),`${a} limit${i.length>1?"s":""}: ${i.join(", ")}. Stopping to prevent further tool calls.`}var Yg=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(e,t,n,r,s=void 0){const a=qg(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}};te({toolName:Oe().optional(),threadLimit:St().optional(),runLimit:St().optional(),exitBehavior:Fr(["end","error"]).default("end")});function QI(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??"end";if(t!=="end"&&t!=="error")throw new Error(`Invalid exit behavior: ${t}. Must be 'end' or 'error'`);const n=e.toolName?`ToolCallLimitMiddleware[${e.toolName}]`:"ToolCallLimitMiddleware";return Ct({name:n,beforeModel:{canJumpTo:["end"],hook:r=>{const s=r.messages,a=Kd(s,e.toolName),i=XI(s),o=Kd(i,e.toolName),c=e.threadLimit!==void 0&&a>=e.threadLimit,l=e.runLimit!==void 0&&o>=e.runLimit;if(!c&&!l)return;if(t==="error")throw new Yg(a,o,e.threadLimit,e.runLimit,e.toolName);const u=qg(a,o,e.threadLimit,e.runLimit,e.toolName);return{jumpTo:"end",messages:[new D(u)]}}}})}const eP=`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.
261
- It also helps the user understand the progress of the task and overall progress of their requests.
262
- 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.
263
-
264
- ## When to Use This Tool
265
- Use this tool in these scenarios:
266
-
267
- 1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
268
- 2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
269
- 3. User explicitly requests todo list - When the user directly asks you to use the todo list
270
- 4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
271
- 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.
272
-
273
- ## How to Use This Tool
274
- 1. When you start working on a task - Mark it as in_progress BEFORE beginning work.
275
- 2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation.
276
- 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.
277
- 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.
278
-
279
- ## When NOT to Use This Tool
280
- It is important to skip using this tool when:
281
- 1. There is only a single, straightforward task
282
- 2. The task is trivial and tracking it provides no benefit
283
- 3. The task can be completed in less than 3 trivial steps
284
- 4. The task is purely conversational or informational
285
-
286
- ## Examples of When to Use the Todo List
287
-
288
- <example>
289
- 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!
290
- Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
291
- *Creates todo list with the following items:*
292
- 1. Create dark mode toggle component in Settings page
293
- 2. Add dark mode state management (context/store)
294
- 3. Implement CSS-in-JS styles for dark theme
295
- 4. Update existing components to support theme switching
296
- 5. Run tests and build process, addressing any failures or errors that occur
297
- *Begins working on the first task*
298
-
299
- <reasoning>
300
- The assistant used the todo list because:
301
- 1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes
302
- 2. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
303
- 3. Both of the user's requests are complex and require multiple steps to complete.
304
- </reasoning>
305
- </example>
306
-
307
- <example>
308
- User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases.
309
- 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.
310
- *Creates todo list with the following items:*
311
- 1. Define target audience and key messaging
312
- 2. Create social media content calendar and posting schedule
313
- 3. Design email marketing sequence and automation flows
314
- 4. Draft press release and identify media contacts
315
- 5. Set up tracking and analytics for campaign performance
316
- 6. Create visual assets and brand materials
317
- 7. Coordinate launch timeline and deliverables
318
- *Begins working on the first task*
319
-
320
- <reasoning>
321
- The assistant used the todo list because:
322
- 1. Marketing campaign planning involves multiple distinct channels and activities
323
- 2. Each component requires careful coordination and planning
324
- 3. The systematic approach ensures all aspects of the launch are covered
325
- </reasoning>
326
- </example>
327
-
328
- <example>
329
- User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
330
- Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
331
- *Uses search tools to locate all instances of getCwd in the codebase*
332
- Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
333
- *Creates todo list with specific items for each file that needs updating*
334
-
335
- <reasoning>
336
- The assistant used the todo list because:
337
- 1. The assistant searched to understand the scope of the task
338
- 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps (>3)
339
- 3. The todo list helps ensure every instance is tracked and updated systematically
340
- 4. This approach prevents missing any occurrences and maintains consistency.
341
- </reasoning>
342
- </example>
343
-
344
- <example>
345
- User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow.
346
- Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization.
347
- *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*
348
- Let's start with decluttering your desk space to create a clean foundation for the other organizational systems.
349
-
350
- <reasoning>
351
- The assistant used the todo list because:
352
- 1. The user provided multiple distinct organizational tasks
353
- 2. Each area requires different approaches and careful planning
354
- 3. Home organization benefits from systematic, step-by-step completion
355
- 4. Progress tracking ensures all areas are addressed thoroughly
356
- </reasoning>
357
- </example>
358
-
359
- ## Examples of When NOT to Use the Todo List
360
-
361
- <example>
362
- User: How do I print 'Hello World' in Python?
363
- Assistant: In Python, you can print "Hello World" with this simple code:
364
-
365
- \`\`\`python
366
- print("Hello World")
367
- \`\`\`
368
-
369
- This will output the text "Hello World" to the console when executed.</assistant>
370
-
371
- <reasoning>
372
- 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.
373
- </reasoning>
374
- </example>
375
-
376
- <example>
377
- User: What's the best way to water houseplants?
378
- Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines:
379
-
380
- - Check soil moisture by inserting your finger about 1-2 inches into the soil
381
- - Water thoroughly when the top inch feels dry, allowing water to drain from the bottom
382
- - Use room temperature water and water in the morning when possible
383
- - Avoid overwatering, which is more harmful than underwatering for most plants
384
-
385
- Different plants have different needs, so it's important to research your specific varieties for optimal care.
386
-
387
- <reasoning>
388
- 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.
389
- </reasoning>
390
- </example>
391
-
392
- <example>
393
- User: Can you add a comment to the calculateTotal function to explain what it does?
394
- Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
395
- * Uses the Edit tool to add a comment to the calculateTotal function *
396
-
397
- <reasoning>
398
- 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.
399
- </reasoning>
400
- </example>
401
-
402
- <example>
403
- User: What time is it in Tokyo right now?
404
- Assistant: I'll check the current time in Tokyo for you.
405
-
406
- *Searches for current time in Tokyo*
407
-
408
- The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9.
409
-
410
- <reasoning>
411
- 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.
412
- </reasoning>
413
- </example>
414
-
415
- <example>
416
- User: I need to write a function that checks if a number is prime and then test it out.
417
- Assistant: I'll help you write a function that checks if a number is prime and then test it out.
418
- *Writes function that checks if a number is prime*
419
- *Tests the function*
420
-
421
- <reasoning>
422
- 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.
423
- </reasoning>
424
- </example>
425
-
426
- <example>
427
- User: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
428
- Assistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
429
- *Orders a pizza from Dominos*
430
- *Orders a burger from McDonald's*
431
- *Orders a salad from Subway*
432
-
433
- <reasoning>
434
- 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.
435
- Using the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact.
436
- </reasoning>
437
- </example>
438
-
439
-
440
- ## Task States and Management
441
-
442
- 1. **Task States**: Use these states to track progress:
443
- - pending: Task not yet started
444
- - 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)
445
- - completed: Task finished successfully
446
-
447
- 2. **Task Management**:
448
- - Update task status in real-time as you work
449
- - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
450
- - Complete current tasks before starting new ones
451
- - Remove tasks that are no longer relevant from the list entirely
452
- - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.
453
- - 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.
454
-
455
- 3. **Task Completion Requirements**:
456
- - ONLY mark a task as completed when you have FULLY accomplished it
457
- - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
458
- - When blocked, create a new task describing what needs to be resolved
459
- - Never mark a task as completed if:
460
- - There are unresolved issues or errors
461
- - Work is partial or incomplete
462
- - You encountered blockers that prevent completion
463
- - You couldn't find necessary resources or dependencies
464
- - Quality standards haven't been met
465
-
466
- 4. **Task Breakdown**:
467
- - Create specific, actionable items
468
- - Break complex tasks into smaller, manageable steps
469
- - Use clear, descriptive task names
470
-
471
- Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully
472
- 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.`,Xg=`## \`write_todos\`
473
-
474
- You have access to the \`write_todos\` tool to help you manage and plan complex objectives.
475
- Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.
476
- This tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.
477
-
478
- 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.
479
- For simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.
480
- 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.
481
-
482
- ## Important To-Do List Usage Notes to Remember
483
- - The \`write_todos\` tool should never be called multiple times in parallel.
484
- - 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.`,tP=Fr(["pending","in_progress","completed"]).describe("Status of the todo"),Qg=te({content:Oe().describe("Content of the todo item"),status:tP}),nP=te({todos:Pn(Qg).default([])});function rP(e){const t=bl(({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??eP,schema:te({todos:Pn(Qg).describe("List of todo items to update")})});return Ct({name:"todoListMiddleware",stateSchema:nP,tools:[t],wrapModelCall:(n,r)=>r({...n,systemPrompt:(n.systemPrompt?`${n.systemPrompt}
485
-
486
- `:"")+(e?.systemPrompt??Xg)})})}const sP="end",aP=te({threadLimit:St().optional(),runLimit:St().optional(),exitBehavior:Fr(["throw","end"]).optional()});var Zd=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 ey(e){return Ct({name:"ModelCallLimitMiddleware",contextSchema:aP,beforeModel:{canJumpTo:["end"],hook:(t,n)=>{const r=n.context.exitBehavior??e?.exitBehavior??sP,s=n.context.threadLimit??e?.threadLimit,a=n.context.runLimit??e?.runLimit;if(typeof s=="number"&&s<=n.threadLevelCallCount){const i=new Zd({threadLimit:s,threadCount:n.threadLevelCallCount});if(r==="end")return{jumpTo:"end",messages:[new D(i.message)]};throw i}if(typeof a=="number"&&a<=n.runModelCallCount){const i=new Zd({runLimit:a,runCount:n.runModelCallCount});if(r==="end")return{jumpTo:"end",messages:[new D(i.message)]};throw i}return t}}})}function iP(...e){return Ct({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 Zs(a):a;return await n({...t,model:i})}catch(a){if(s===e.length-1)throw a}throw r}}})}me.initializeGlobalInstance(new rg);var oP={};_f(oP,{AIMessage:()=>D,AIMessageChunk:()=>mt,BaseMessage:()=>tt,BaseMessageChunk:()=>Nn,ClearToolUsesEdit:()=>Zg,Document:()=>rn,DynamicStructuredTool:()=>Ti,DynamicTool:()=>vl,FakeToolCallingModel:()=>cO,HumanMessage:()=>de,HumanMessageChunk:()=>Vs,InMemoryStore:()=>Ff,MultipleStructuredOutputsError:()=>ac,MultipleToolsBoundError:()=>sc,ProviderStrategy:()=>Fn,StructuredOutputParsingError:()=>Of,StructuredTool:()=>tr,SystemMessage:()=>fe,SystemMessageChunk:()=>Kn,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>Xg,Tool:()=>wl,ToolCallLimitExceededError:()=>Yg,ToolInvocationError:()=>El,ToolMessage:()=>X,ToolMessageChunk:()=>Hs,ToolStrategy:()=>mn,anthropicPromptCachingMiddleware:()=>DI,contextEditingMiddleware:()=>YI,countTokensApproximately:()=>kl,createAgent:()=>Vg,createMiddleware:()=>Ct,dynamicSystemPromptMiddleware:()=>UI,filterMessages:()=>wf,getContextVariable:()=>el,humanInTheLoopMiddleware:()=>NI,initChatModel:()=>Zs,llmToolSelectorMiddleware:()=>HI,modelCallLimitMiddleware:()=>ey,modelFallbackMiddleware:()=>iP,piiRedactionMiddleware:()=>ZI,providerStrategy:()=>qC,setContextVariable:()=>kb,summarizationMiddleware:()=>_I,todoListMiddleware:()=>rP,tool:()=>bl,toolCallLimitMiddleware:()=>QI,toolStrategy:()=>ZC,trimMessages:()=>Sl});var ci={},Cr,ty=(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)&&(T.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 T.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),T.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 T.debug(`Available tools: ${n.length}`),n}checkConnectorInitialized(t){return!!(t.tools&&t.tools.length)}async ensureConnectorInitialized(t){if(!this.checkConnectorInitialized(t)){T.debug("Connector doesn't have tools, initializing it");try{return await t.initialize(),!0}catch(n){return T.error(`Error initializing connector: ${n}`),!1}}return!0}},G(Cr,"BaseAdapter"),Cr);function ny(e){try{return ew.convert(e)}catch(t){return T.warn(`Failed to convert JSON schema to Zod: ${t}`),ht()}}G(ny,"schemaToZod");var Ar,Dn=(Ar=class extends ty{constructor(t=[]){super(t)}convertTool(t,n){if(this.disallowedTools.includes(t.name))return null;const r=t.inputSchema?ny(t.inputSchema):te({}).optional();return new Ti({name:t.name??"NO NAME",description:t.description??"",schema:r,func:G(async a=>{T.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 T.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}},G(Ar,"LangChainAdapter"),Ar),kr,Ni=(kr=class extends tr{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),cP=te({}),Or,lP=(Or=class extends Ni{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=cP;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,uP=(xr=class extends tr{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=te({serverName:Oe().describe("The name for the new MCP server."),serverConfig:ht().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.`;T.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+=`
487
-
488
- ${i.map(c=>c.name).join(`
489
- `)}`,T.info(r),r}catch(r){return T.error(`Failed to add or connect to server '${t}': ${r.message}`),`Failed to add or connect to server '${t}': ${r.message}`}}},G(xr,"AddMCPServerFromConfigTool"),xr),dP=te({serverName:Oe().describe("The name of the MCP server.")}),Ir,hP=(Ir=class extends Ni{name="connect_to_mcp_server";description="Connect to a specific MCP (Model Context Protocol) server to use its tools. Use this tool to connect to a specific server and use its tools.";schema=dP;constructor(t){super(t)}async _call({serverName:t}){const n=this.manager.client.getServerNames();if(!n.includes(t)){const r=n.length>0?n.join(", "):"none";return`Server '${t}' not found. Available servers: ${r}`}if(this.manager.activeServer===t)return`Already connected to MCP server '${t}'`;try{let r=this.manager.client.getSession(t);if(T.debug(`Using existing session for server '${t}'`),r||(T.debug(`Creating new session for server '${t}'`),r=await this.manager.client.createSession(t)),this.manager.activeServer=t,this.manager.serverTools[t]){const i=r.connector,o=await this.manager.adapter.createToolsFromConnectors([i]);this.manager.serverTools[t]=o,this.manager.initializedServers[t]=!0}const a=(this.manager.serverTools[t]||[]).length;return`Connected to MCP server '${t}'. ${a} tools are now available.`}catch(r){return T.error(`Error connecting to server '${t}': ${String(r)}`),`Failed to connect to server '${t}': ${String(r)}`}}},G(Ir,"ConnectMCPServerTool"),Ir),pP=te({}),Pr,fP=(Pr=class extends Ni{name="list_mcp_servers";description="Lists all available MCP (Model Context Protocol) servers that can be connected to, along with the tools available on each server. Use this tool to discover servers and see what functionalities they offer.";schema=pP;constructor(t){super(t)}async _call(){const t=this.manager.client.getServerNames();if(t.length===0)return"No MCP servers are currently defined.";const n=["Available MCP servers:"];for(const r of t){const a=r===this.manager.activeServer?" (ACTIVE)":"";n.push(`- ${r}${a}`);try{const i=this.manager.serverTools?.[r]??[],o=Array.isArray(i)?i.length:0;n.push(`${o} tools available for this server
490
- `)}catch(i){T.error(`Unexpected error listing tools for server '${r}': ${String(i)}`)}}return n.join(`
491
- `)}},G(Pr,"ListMCPServersTool"),Pr),mP=te({}),Nr,gP=(Nr=class extends Ni{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=mP;constructor(t){super(t)}async _call(){if(!this.manager.activeServer)return"No MCP server is currently active, so there's nothing to disconnect from.";const t=this.manager.activeServer;return this.manager.activeServer=null,`Successfully disconnected from MCP server '${t}'.`}},G(Nr,"ReleaseMCPServerConnectionTool"),Nr),Mr,yP=(Mr=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(t,n,r){this.client=t,this.adapter=n,this.overrideManagementTools=r}setManagementTools(t){this.overrideManagementTools=t,T.info(`Overriding default management tools with a new set of ${t.length} tools.`)}logState(t){const n=this.client.getServerNames(),r=Object.keys(this.client.getAllActiveSessions());if(n.length===0){T.info("Server Manager State: No servers configured.");return}const s=n.map(a=>({"Server Name":a,Connected:r.includes(a)?"✅":"❌",Initialized:this.initializedServers[a]?"✅":"❌","Tool Count":this.serverTools[a]?.length??0,Active:this.activeServer===a?"✅":"❌"}));T.info(`Server Manager State: [${t}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&T.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const t=this.client.getServerNames();for(const n of t)try{let r=null;if(r=this.client.getSession(n),T.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(T.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),T.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let a=[];try{a=await this.adapter.createToolsFromConnectors([s])}catch(c){T.error(`Failed to create tools from connector for server '${n}': ${c}`);continue}const i=this.serverTools[n];!i||!KE(i,a)?(this.serverTools[n]=a,this.initializedServers[n]=!0,T.debug(`Prefetched ${a.length} tools for server '${n}'.`)):T.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){T.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){T.level==="debug"&&this.logState("Providing tools to agent");const t=this.overrideManagementTools??[new uP(this),new fP(this),new hP(this),new lP(this),new gP(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return T.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...t,...n]}return t}},G(Mr,"ServerManager"),Mr),Rr,Pc=(Rr=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(t={}){this.customCallbacks=t.customCallbacks,this.verbose=t.verbose??!1,this.observe=t.observe??!0,this.agentId=t.agentId,this.metadata=t.metadata,this.metadataProvider=t.metadataProvider,this.tagsProvider=t.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:t,langfuseInitPromise:n}=await $a(async()=>{const{langfuseHandler:s,langfuseInitPromise:a}=await Promise.resolve().then(()=>qd);return{langfuseHandler:s,langfuseInitPromise:a}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await $a(async()=>{const{initializeLangfuse:a}=await Promise.resolve().then(()=>qd);return{initializeLangfuse:a}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),T.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const s=n();s&&await s}const r=t();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),T.debug("ObservabilityManager: Langfuse handler available"))}catch{T.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(T.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?T.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):T.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(T.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(t=>t.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const t=await this.getCallbacks(),n=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},s=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&t.length>0,callbackCount:t.length,handlerNames:n,metadata:r,tags:s}}addCallback(t){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(t),T.debug(`ObservabilityManager: Added custom callback: ${t.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],T.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const t=await this.getCallbacks();for(const n of t)"flushAsync"in n&&typeof n.flushAsync=="function"&&await n.flushAsync();T.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const t=await this.getCallbacks();for(const n of t)"shutdownAsync"in n&&typeof n.shutdownAsync=="function"?await n.shutdownAsync():"shutdown"in n&&typeof n.shutdown=="function"&&await n.shutdown();T.debug("ObservabilityManager: All handlers shutdown")}toString(){const t=this.handlerNames;return t.length>0?`ObservabilityManager(handlers=${t.join(", ")})`:"ObservabilityManager(no handlers)"}},G(Rr,"ObservabilityManager"),Rr),$r,_P=($r=class{},G($r,"BaseTelemetryEvent"),$r),Lr,wP=(Lr=class extends _P{constructor(t){super(),this.data=t}get name(){return"mcp_agent_execution"}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}},G(Lr,"MCPAgentExecutionEvent"),Lr);function Ra(){try{if(typeof __dirname>"u"||typeof Po>"u")return"unknown";const e=Da(__dirname,"../../package.json");return JSON.parse((void 0)(e,"utf-8")).version||"unknown"}catch{return"unknown"}}G(Ra,"getPackageVersion");function ry(e){return e._llm_type||e.constructor.name.toLowerCase()}G(ry,"getModelProvider");function sy(e){if("_identifyingParams"in e){const t=e._identifyingParams;if(typeof t=="object"&&t!==null){for(const n of["model","modelName","model_name","modelId","model_id","deploymentName","deployment_name"])if(n in t)return String(t[n])}}return e.model||e.modelName||e.constructor.name}G(sy,"getModelName");function ay(e){return[ry(e),sy(e)]}G(ay,"extractModelInfo");function _s(){try{return typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")||typeof globalThis.EdgeRuntime<"u"||typeof globalThis.Deno<"u"?!1:typeof process<"u"&&!0&&typeof __dirname<"u"&&(typeof Po<"u"&&typeof Po<"u"&&!1)}catch{return!1}}G(_s,"isNodeJSEnvironment");var jr,vP=(jr=class{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,r=setTimeout(()=>n.abort(),this.timeout),s=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(r),!s.ok)throw new Error(`HTTP error! status: ${s.status}`)}catch(n){T.debug(`Failed to send Scarf event: ${n}`)}}},G(jr,"ScarfEventLogger"),jr);function Nc(){if(!_s())return"/tmp/mcp_use_cache";const e=ci.XDG_CACHE_HOME;if(e&&m_(e))return e;const t=(void 0)();return Da(t,".cache")}G(Nc,"getCacheHome");var Rt,Mc=(Rt=class{USER_ID_PATH=Da(Nc(),"mcp_use_3","telemetry_user_id");VERSION_DOWNLOAD_PATH=Da(Nc(),"mcp_use","download_version");PROJECT_API_KEY="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";HOST="https://eu.i.posthog.com";SCARF_GATEWAY_URL="https://mcpuse.gateway.scarf.sh/events-ts";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogClient=null;_scarfClient=null;_source="typescript";constructor(){const t=_s(),n=typeof process<"u"&&ci?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()==="false"||!1;if(this._source=typeof process<"u"&&ci?.MCP_USE_TELEMETRY_SOURCE||"typescript",n)this._posthogClient=null,this._scarfClient=null,T.debug("Telemetry disabled via environment variable");else if(!t)this._posthogClient=null,this._scarfClient=null,T.debug("Telemetry disabled - non-Node.js environment detected (e.g., Cloudflare Workers)");else{T.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.");try{this._posthogClient=new ZE(this.PROJECT_API_KEY,{host:this.HOST,disableGeoip:!1})}catch(r){T.warn(`Failed to initialize PostHog telemetry: ${r}`),this._posthogClient=null}try{this._scarfClient=new vP(this.SCARF_GATEWAY_URL,3e3)}catch(r){T.warn(`Failed to initialize Scarf telemetry: ${r}`),this._scarfClient=null}}}static getInstance(){return Rt.instance||(Rt.instance=new Rt),Rt.instance}setSource(t){this._source=t,T.debug(`Telemetry source set to: ${t}`)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!_s())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{if(!(void 0)(this.USER_ID_PATH)){T.debug(`Creating user ID path: ${this.USER_ID_PATH}`),(void 0)(cu(this.USER_ID_PATH),{recursive:!0});const n=gy();(void 0)(this.USER_ID_PATH,n),this._currUserId=n,T.debug(`User ID path created: ${this.USER_ID_PATH}`)}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(n=>T.debug(`Failed to track package download: ${n}`))}catch(t){T.debug(`Failed to get/create user ID: ${t}`),this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}async capture(t){if(!(!this._posthogClient&&!this._scarfClient)){if(this._posthogClient)try{const n={...t.properties};n.mcp_use_version=Ra(),n.language="typescript",n.source=this._source,this._posthogClient.capture({distinctId:this.userId,event:t.name,properties:n})}catch(n){T.debug(`Failed to track PostHog event ${t.name}: ${n}`)}if(this._scarfClient)try{const n={};n.mcp_use_version=Ra(),n.user_id=this.userId,n.event=t.name,n.language="typescript",n.source=this._source,await this._scarfClient.logEvent(n)}catch(n){T.debug(`Failed to track Scarf event ${t.name}: ${n}`)}}}async trackPackageDownload(t){if(this._scarfClient&&_s())try{const n=Ra();let r=!1,s=!1;if((void 0)(this.VERSION_DOWNLOAD_PATH)||(r=!0,s=!0,(void 0)(cu(this.VERSION_DOWNLOAD_PATH),{recursive:!0}),(void 0)(this.VERSION_DOWNLOAD_PATH,n)),r){T.debug(`Tracking package download event with properties: ${JSON.stringify(t)}`);const a={...t||{}};a.mcp_use_version=n,a.user_id=this.userId,a.event="package_download",a.first_download=s,a.language="typescript",a.source=this._source,await this._scarfClient.logEvent(a)}}catch(n){T.debug(`Failed to track Scarf package_download event: ${n}`)}}async trackAgentExecution(t){const n=new wP(t);await this.capture(n)}flush(){if(this._posthogClient)try{this._posthogClient.flush(),T.debug("PostHog client telemetry queue flushed")}catch(t){T.debug(`Failed to flush PostHog client: ${t}`)}this._scarfClient&&T.debug("Scarf telemetry events sent immediately (no flush needed)")}shutdown(){if(this._posthogClient)try{this._posthogClient.shutdown(),T.debug("PostHog client shutdown successfully")}catch(t){T.debug(`Error shutting down PostHog client: ${t}`)}this._scarfClient&&T.debug("Scarf telemetry client shutdown (no action needed)")}},G(Rt,"Telemetry"),su(Rt,"instance",null),Rt);function bP(e){Mc.getInstance().setSource(e)}G(bP,"setTelemetrySource");var SP="/api/v1/chats",TP="/api/v1/chats/{chat_id}/execute",Dr,iy=(Dr=class{agentId;apiKey;baseUrl;chatId=null;constructor(t){this.agentId=t.agentId,this.baseUrl=t.baseUrl??"https://cloud.mcp-use.com";const n=t.apiKey??ci.MCP_USE_API_KEY;if(!n)throw new Error("API key is required for remote execution. Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. You can get an API key from https://cloud.mcp-use.com");this.apiKey=n}pydanticToJsonSchema(t){return ya(t)}parseStructuredResponse(t,n){let r;if(typeof t=="object"&&t!==null)if("result"in t){const s=t.result;typeof s=="object"&&s!==null&&"result"in s?r=s.result:r=s}else r=t;else if(typeof t=="string")try{r=JSON.parse(t)}catch{r={content:t}}else r=t;try{return n.parse(r)}catch(s){T.warn(`Failed to parse structured output: ${s}`);const a=n._def?.shape();if(a&&"content"in a)return n.parse({content:String(r)});throw s}}async createChatSession(){const t={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},n={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${SP}`;T.info(`📝 Creating chat session for agent ${this.agentId}`);try{const s=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(t)});if(!s.ok){const o=await s.text(),c=s.status;throw c===404?new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`):new Error(`Failed to create chat session: ${c} - ${o}`)}const i=(await s.json()).id;return T.info(`✅ Chat session created: ${i}`),i}catch(s){throw s instanceof Error?new TypeError(`Failed to create chat session: ${s.message}`):new Error(`Failed to create chat session: ${String(s)}`)}}async run(t,n,r,s,a){s!==void 0&&T.warn("External history is not yet supported for remote execution");try{T.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const i=this.chatId,o={query:t,max_steps:n??10};a&&(o.output_schema=this.pydanticToJsonSchema(a),T.info("🔧 Using structured output with schema"));const c={"Content-Type":"application/json","x-api-key":this.apiKey},l=`${this.baseUrl}${TP.replace("{chat_id}",i)}`;T.info(`🚀 Executing agent in chat ${i}`);const u=await fetch(l,{method:"POST",headers:c,body:JSON.stringify(o),signal:AbortSignal.timeout(3e5)});if(!u.ok){const h=await u.text(),p=u.status;throw p===401?(T.error(`❌ Authentication failed: ${h}`),new Error("Authentication failed: Invalid or missing API key. Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.")):p===403?(T.error(`❌ Access forbidden: ${h}`),new Error(`Access denied: You don't have permission to execute agent '${this.agentId}'. Check if the agent exists and you have the necessary permissions.`)):p===404?(T.error(`❌ Agent not found: ${h}`),new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`)):p===422?(T.error(`❌ Validation error: ${h}`),new Error(`Request validation failed: ${h}. Please check your query parameters and output schema format.`)):p===500?(T.error(`❌ Server error: ${h}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(T.error(`❌ Remote execution failed with status ${p}: ${h}`),new Error(`Remote agent execution failed: ${p} - ${h}`))}const d=await u.json();if(T.info(`🔧 Response: ${JSON.stringify(d)}`),T.info("✅ Remote execution completed successfully"),typeof d=="object"&&d!==null){if(d.status==="error"||d.error!==null){const h=d.error??String(d);throw T.error(`❌ Remote agent execution failed: ${h}`),new Error(`Remote agent execution failed: ${h}`)}if(String(d).includes("failed to initialize"))throw T.error(`❌ Agent initialization failed: ${d}`),new Error(`Agent initialization failed on remote server. This usually indicates:
492
- • Invalid agent configuration (LLM model, system prompt)
493
- • Missing or invalid MCP server configurations
494
- • Network connectivity issues with MCP servers
495
- • Missing environment variables or credentials
496
- 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"?(T.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.")):(T.error(`❌ Remote execution error: ${i}`),new Error(`Remote agent execution failed: ${i.message}`)):(T.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(){T.info("🔌 Remote agent client closed")}},G(Dr,"RemoteAgent"),Dr);function oy(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(oy,"generateToolDescriptions");function cy(e,t,n){const r=t.join(`
497
- `);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}
498
-
499
- Available tools:
500
- ${r}`),n&&(s+=`
501
-
502
- ${n}`),s}G(cy,"buildSystemPromptContent");function ly(e,t,n,r,s,a,i){if(a)return new fe({content:a});const o=r?n:t,c=oy(e,s),l=cy(o,c,i);return new fe({content:l})}G(ly,"createSystemMessage");var EP=`You are a helpful AI assistant.
503
- You have access to the following tools:
504
-
505
- {tool_descriptions}
506
-
507
- Use the following format:
508
-
509
- Question: the input question you must answer
510
- Thought: you should always think about what to do
511
- Action: the action to take, should be one of the available tools
512
- Action Input: the input to the action
513
- Observation: the result of the action
514
- ... (this Thought/Action/Action Input/Observation can repeat N times)
515
- Thought: I now know the final answer
516
- Final Answer: the final answer to the original input question`,CP=`You are a helpful assistant designed to interact with MCP
517
- (Model Context Protocol) servers. You can manage connections to different servers and use the tools
518
- provided by the currently active server.
519
-
520
- Important: The available tools change depending on which server is active.
521
- If a request requires tools not listed below (e.g., file operations, web browsing,
522
- image manipulation), you MUST first connect to the appropriate server using
523
- 'connect_to_mcp_server'.
524
- Use 'list_mcp_servers' to find the relevant server if you are unsure.
525
- Only after successfully connecting and seeing the new tools listed in
526
- the response should you attempt to use those server-specific tools.
527
- Before attempting a task that requires specific tools, you should
528
- ensure you are connected to the correct server and aware of its
529
- available tools. If unsure, use 'list_mcp_servers' to see options
530
- or 'get_active_mcp_server' to check the current connection.
531
-
532
- When you connect to a server using 'connect_to_mcp_server',
533
- you will be informed about the new tools that become available.
534
- You can then use these server-specific tools in subsequent steps.
535
-
536
- Here are the tools *currently* available to you (this list includes server management tools and will
537
- change when you connect to a server):
538
- {tool_descriptions}
539
- `,Ur,AP=(Ur=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 iy({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=Mc.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Pc({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 yP(this.client,this.adapter)}else this.adapter=t.adapter??new Dn(this.disallowedTools);if(this.telemetry=Mc.getInstance(),this.llm){const[n,r]=ay(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Pc({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}T.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const t=await this.observabilityManager.getHandlerNames();if(t.length>0&&T.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),T.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client)this.sessions=this.client.getAllActiveSessions(),T.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).length===0&&(T.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),T.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this._tools=await Dn.createTools(this.client),this._tools.push(...this.additionalTools),T.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);else{T.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),T.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}T.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),T.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),T.info("✨ Agent initialization complete")}async createSystemMessageFromTools(t){const n=this.systemPromptTemplateOverride??EP;this.systemMessage=ly(t,n,CP,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof fe))])}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);T.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[ey({runLimit:this.maxSteps})],s=Vg({model:this.llm,tools:this._tools,systemPrompt:t,middleware:r});return T.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 fe(t),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof fe)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),T.debug("Agent recreated with new system message"))}setDisallowedTools(t){this.disallowedTools=t,this.adapter=new Dn(this.disallowedTools),this._initialized&&T.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},T.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])],T.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){T.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?(T.warn(`Metadata value for key '${a}' is too large. Truncating.`),n[a]=`${i.substring(0,1e3)}...`):n[a]=s}catch(i){T.warn(`Failed to serialize metadata value for key '${a}': ${i}. Skipping.`)}else T.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){T.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){T.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)}}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 b=this.serverManager.tools,v=new Set(b.map(E=>E.name)),w=new Set(this._tools.map(E=>E.name));(v.size!==w.size||[...v].some(E=>!w.has(E)))&&(T.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...v].join(", ")}`),this._tools=b,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const d=s??this.conversationHistory,h=[];for(const b of d)(b instanceof de||b instanceof D)&&h.push(b);const p=t.length>50?`${t.slice(0,50).replace(/\n/g," ")}...`:t.replace(/\n/g," ");T.info(`💬 Received query: '${p}'`),T.info("🏁 Starting agent execution");const f=3;let y=0;const S=[...h,new de(t)];for(;y<=f;){const b={messages:S};let v=!1;const w=await this._agentExecutor.stream(b,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const E of w){for(const[A,I]of Object.entries(E))if(T.debug(`📦 Node '${A}' output: ${JSON.stringify(I)}`),I&&typeof I=="object"&&"messages"in I){let k=I.messages;Array.isArray(k)||(k=[k]);for(const g of k)S.includes(g)||S.push(g);for(const g of k){if("tool_calls"in g&&Array.isArray(g.tool_calls)&&g.tool_calls.length>0)for(const N of g.tool_calls){const x=N.name||"unknown",M=N.args||{};this.toolsUsedNames.push(x),u++;let z=JSON.stringify(M);z.length>100&&(z=`${z.slice(0,97)}...`),T.info(`🔧 Tool call: ${x} with input: ${z}`),yield{action:{tool:x,toolInput:M,log:`Calling tool ${x}`},observation:""}}if(g instanceof X||g&&"type"in g&&g.type==="tool"){const N=g.content;let x=String(N);if(x.length>100&&(x=`${x.slice(0,97)}...`),x=x.replace(/\n/g," "),T.info(`📄 Tool result: ${x}`),this.useServerManager&&this.serverManager){const M=this.serverManager.tools,z=new Set(M.map(he=>he.name)),ce=new Set(this._tools.map(he=>he.name));if(z.size!==ce.size||[...z].some(he=>!ce.has(he))){T.info(`🔄 Tools changed during execution. New tools: ${[...z].join(", ")}`),this._tools=M,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),v=!0,y++,T.info(`🔃 Restarting execution with updated tools (restart ${y}/${f})`);break}}}g instanceof D&&!("tool_calls"in g&&Array.isArray(g.tool_calls)&&g.tool_calls.length>0)&&(l=this._normalizeOutput(g.content),T.info("✅ Agent finished with output"))}if(v)break}if(v)break}if(!v)break;if(y>f){T.warn(`⚠️ Max restarts (${f}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled&&(this.addToHistory(new de(t)),l&&this.addToHistory(new D(l))),a&&l)try{T.info("🔧 Attempting structured output...");const b=await this._attemptStructuredOutput(l,this.llm,a);return this.memoryEnabled&&this.addToHistory(new D(`Structured result: ${JSON.stringify(b)}`)),T.info("✅ Structured output successful"),c=!0,b}catch(b){throw T.error(`❌ Structured output failed: ${b}`),new Error(`Failed to generate structured output: ${b instanceof Error?b.message:String(b)}`)}return T.info(`🎉 Agent execution complete in ${((Date.now()-o)/1e3).toFixed(2)} seconds`),c=!0,l||"No output generated"}catch(d){throw T.error(`❌ Error running query: ${d}`),i&&r&&(T.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(y=>y.publicIdentifier),totalToolsAvailable:f.length,toolsAvailableNames:f.map(y=>y.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&&(T.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(T.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}T.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)T.info("🔄 Closing sessions through client"),await this.client.closeAllSessions(),this.sessions={};else for(const t of this.connectors)T.info("🔄 Disconnecting connector"),await t.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new Dn)}finally{this._initialized=!1,T.info("👋 Agent closed successfully")}}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=t.length>50?`${t.slice(0,50).replace(/\n/g," ")}...`:t.replace(/\n/g," ");T.info(`💬 Received query for streamEvents: '${p}'`),this.memoryEnabled&&(T.info(`🔄 Adding user message to history: ${t}`),this.addToHistory(new de(t)));const f=s??this.conversationHistory,y=[];for(const v of f)v instanceof de||v instanceof D||v instanceof X?y.push(v):T.info(`⚠️ Skipped message of type: ${v.constructor.name}`);const S=[...y,new de(t)];T.info("callbacks",this.callbacks);const b=h.streamEvents({messages:S},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const v of b)if(l++,!(!v||typeof v!="object")){if(v.event==="on_chat_model_stream"&&v.data?.chunk?.content&&(u+=v.data.chunk.content.length),v.event==="on_chat_model_stream"&&v.data?.chunk){const w=v.data.chunk;if(w.content){d||(d="");const E=this._normalizeOutput(w.content);d+=E,T.debug(`📝 Accumulated response length: ${d.length}`)}}if(yield v,v.event==="on_chain_end"&&v.data?.output&&!d){const w=v.data.output;Array.isArray(w)&&w.length>0&&w[0]?.text?d=w[0].text:typeof w=="string"?d=w:w&&typeof w=="object"&&"output"in w&&(d=w.output)}}if(a&&d){T.info("🔧 Attempting structured output conversion...");try{let v=!1,w=null,E=null;this._attemptStructuredOutput(d,this.llm,a).then(I=>(v=!0,w=I,I)).catch(I=>{throw v=!0,E=I,I});let A=0;for(;!v;)await new Promise(I=>setTimeout(I,2e3)),v||(A++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${A*2}s)`,elapsed:A*2}});if(E)throw E;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new D(`Structured result: ${JSON.stringify(w)}`)),T.info("✅ Structured output successful"))}catch(v){T.warn(`⚠️ Structured output failed: ${v}`),yield{event:"on_structured_output_error",data:{error:v instanceof Error?v.message:String(v)}}}}else this.memoryEnabled&&d&&this.addToHistory(new D(d));T.info(`🎉 StreamEvents complete - ${l} events emitted`),c=!0}catch(h){throw T.error(`❌ Error during streamEvents: ${h}`),i&&r&&(T.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(y=>y.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(y=>y.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&&(T.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(t,n,r){T.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),T.info(`🔄 Raw result: ${JSON.stringify(t,null,2)}`);let s=null,a="";if(T.debug(`🔄 Structured output requested, schema: ${JSON.stringify(ya(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=ya(r),{$schema:o,additionalProperties:c,...l}=i;a=JSON.stringify(l,null,2),T.info(`🔄 Schema description: ${a}`);let u="";typeof t=="string"?u=t:t&&typeof t=="object"&&(u=JSON.stringify(t)),T.info("rawResult",t),u||(u=JSON.stringify(t));const d=3;let h="";for(let p=1;p<=d;p++){T.info(`🔄 Structured output attempt ${p}/${d}`);let f=`
540
- Please format the following information according to the EXACT schema specified below.
541
- You must use the exact field names and types as shown in the schema.
542
-
543
- Required schema format:
544
- ${a}
545
-
546
- Content to extract from:
547
- ${u}
548
-
549
- IMPORTANT:
550
- - Use ONLY the field names specified in the schema
551
- - Match the data types exactly (string, number, boolean, array, etc.)
552
- - Include ALL required fields
553
- - Return valid JSON that matches the schema structure exactly
554
- - For missing data: use null for nullable fields, omit optional fields entirely
555
- - Do NOT use empty strings ("") or zero (0) as placeholders for missing data
556
- `;p>1&&(f+=`
557
-
558
- PREVIOUS ATTEMPT FAILED with error: ${h}
559
- Please fix the issues mentioned above and ensure the output matches the schema exactly.
560
- `);try{T.info(`🔄 Structured output attempt ${p} - using streaming approach`);const y=u.length>300?`${u.slice(0,300)}...`:u;T.info(`🔄 Content being formatted (${u.length} chars): ${y}`),T.info(`🔄 Full format prompt (${f.length} chars):
561
- ${f}`);const S=await s.stream(f);let b=null,v=0;for await(const E of S){if(v++,T.info(`Chunk ${v}: ${JSON.stringify(E,null,2)}`),typeof E=="string")try{b=JSON.parse(E)}catch{T.warn(`🔄 Failed to parse string chunk as JSON: ${E}`)}else if(E&&typeof E=="object")b=E;else try{b=JSON.parse(String(E))}catch{T.warn(`🔄 Failed to parse chunk as JSON: ${E}`)}v%10===0&&T.info(`🔄 Structured output streaming: ${v} chunks`)}if(T.info(`🔄 Structured result attempt ${p}: ${JSON.stringify(b,null,2)}`),!b)throw new Error("No structured result received from stream");const w=this._validateStructuredResult(b,r);return T.info(`✅ Structured output successful on attempt ${p}`),w}catch(y){if(h=y instanceof Error?y.message:String(y),T.warn(`⚠️ Structured output attempt ${p} failed: ${h}`),p===d)throw T.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 T.debug(`Validation details: ${r}`),r}}_enhanceQueryWithSchema(t,n){try{const r=ya(n),{$schema:s,additionalProperties:a,...i}=r,o=JSON.stringify(i,null,2);return`
562
- ${t}
563
-
564
- IMPORTANT: Your response must include sufficient information to populate the following structured output:
565
-
566
- ${o}
567
-
568
- Make sure you gather ALL the required information during your task execution.
569
- If any required information is missing, continue working to find it.
570
- `}catch(r){return T.warn(`Could not extract schema details: ${r}`),t}}},G(Ur,"MCPAgent"),Ur),Me={},kP=Me.MCP_USE_LANGFUSE?.toLowerCase()==="false",Bs={handler:null,client:null,initPromise:null};async function Xl(e,t,n,r){try{const s=await $a(()=>import("./index-Cva-hqGs.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).catch(()=>null);if(!s){T.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:a}=s,u=class u extends a{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(h,p,f,y,S){super(h),this.agentId=p,this.metadata=f,this.metadataProvider=y,this.tagsProvider=S,this.verbose=h?.verbose??!1}async handleChainStart(h,p,f,y,S,b,v,w){T.debug("Langfuse: Chain start intercepted");const E=this.getCustomTags(),A=this.getMetadata(),I=[...S||[],...E],k={...b||{},...A};return this.verbose&&(T.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(I)}`),T.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(k)}`)),super.handleChainStart(h,p,f,y,I,k,v,w)}getCustomTags(){const h=[],p=this.getEnvironmentTag();if(p&&h.push(`env:${p}`),this.agentId&&h.push(`agent_id:${this.agentId}`),this.tagsProvider){const f=this.tagsProvider();f&&f.length>0&&h.push(...f)}return h}getMetadata(){const h={},p=this.getEnvironmentTag();if(p&&(h.env=p),this.agentId&&(h.agent_id=this.agentId),this.metadata&&Object.assign(h,this.metadata),this.metadataProvider){const f=this.metadataProvider();f&&Object.assign(h,f)}return h}getEnvironmentTag(){const h=Me.MCP_USE_AGENT_ENV;if(!h)return"unknown";const p=h.toLowerCase();return p==="local"||p==="development"?"local":p==="production"||p==="prod"?"production":p==="staging"||p==="stage"?"staging":p==="hosted"||p==="cloud"?"hosted":p.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...h){return T.debug("Langfuse: LLM start intercepted"),this.verbose&&T.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return T.debug("Langfuse: Tool start intercepted"),this.verbose&&T.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return T.debug("Langfuse: Retriever start intercepted"),this.verbose&&T.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return T.debug("Langfuse: Agent action intercepted"),this.verbose&&T.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return T.debug("Langfuse: Agent end intercepted"),this.verbose&&T.debug(`Langfuse: Agent end args: ${JSON.stringify(h)}`),super.handleAgentEnd(...h)}};G(u,"LoggingCallbackHandler");let i=u;const o=t||(n?n():{}),c=r?r():[],l={publicKey:Me.LANGFUSE_PUBLIC_KEY,secretKey:Me.LANGFUSE_SECRET_KEY,baseUrl:Me.LANGFUSE_HOST||Me.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Me.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Me.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Me.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Me.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Me.LANGFUSE_ENABLED!=="false",traceName:o.trace_name||Me.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:o.session_id||void 0,userId:o.user_id||void 0,tags:c.length>0?c:void 0,metadata:o||void 0};T.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Bs.handler=new i(l,e,t,n,r),T.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await $a(()=>import("./index-dXj4eNzX.js"),__vite__mapDeps([1,2,3,4,5,6,7])).catch(()=>null);if(d){const{Langfuse:h}=d;Bs.client=new h({publicKey:Me.LANGFUSE_PUBLIC_KEY,secretKey:Me.LANGFUSE_SECRET_KEY,baseUrl:Me.LANGFUSE_HOST||"https://cloud.langfuse.com"}),T.debug("Langfuse client initialized")}}catch(d){T.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){T.debug(`Langfuse initialization error: ${s}`)}}G(Xl,"initializeLangfuse");kP?T.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Me.LANGFUSE_PUBLIC_KEY||!Me.LANGFUSE_SECRET_KEY?T.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Bs.initPromise=Xl();var OP=G(()=>Bs.handler,"langfuseHandler"),xP=G(()=>Bs.initPromise,"langfuseInitPromise");const BP=Object.freeze(Object.defineProperty({__proto__:null,BaseAdapter:ty,BaseConnector:yy,BrowserOAuthClientProvider:_y,HttpConnector:wy,LangChainAdapter:Dn,Logger:vy,MCPAgent:AP,MCPClient:by,MCPSession:Sy,ObservabilityManager:Pc,RemoteAgent:iy,WebSocketConnector:Ty,createReadableStreamFromGenerator:ah,logger:T,onMcpAuthorization:Ey,streamEventsToAISDK:sh,streamEventsToAISDKWithTools:ih},Symbol.toStringTag,{value:"Module"})),qd=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:Xl,langfuseHandler:OP,langfuseInitPromise:xP},Symbol.toStringTag,{value:"Module"}));export{D as A,es as B,Qn as C,hi as F,de as H,fe as S,X as T,tt as a,mt as b,BP as c,ot as m};