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

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 (41) hide show
  1. package/dist/cli.js +11 -3
  2. package/dist/server/{chunk-R5QBLPYB.js → chunk-7ILBF6EL.js} +1 -1
  3. package/dist/server/{chunk-OSJXVY3O.js → chunk-F2FWROJ2.js} +2 -2
  4. package/dist/server/{chunk-PUX4EJWH.js → chunk-O7EUTZ5E.js} +1 -1
  5. package/dist/server/{chunk-Z5QIR3IS.js → chunk-SFZ4CU6U.js} +10 -2
  6. package/dist/server/{chunk-GDZFYTRE.js → chunk-W5XB3CR5.js} +10 -2
  7. package/dist/server/{chunk-QCDOO2RF.js → chunk-Z2X4KZ3J.js} +3 -3
  8. package/dist/server/cli.js +5 -5
  9. package/dist/server/index.js +6 -6
  10. package/dist/server/middleware.js +6 -6
  11. package/dist/server/server.js +5 -5
  12. package/dist/server/shared-routes.js +3 -3
  13. package/dist/server/shared-static.js +2 -2
  14. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  15. package/dist/server/shared-utils-browser.js +1 -1
  16. package/dist/server/shared-utils.d.ts.map +1 -1
  17. package/dist/server/shared-utils.js +1 -1
  18. package/dist/server/utils.d.ts.map +1 -1
  19. package/dist/server/utils.js +1 -1
  20. package/dist/web/assets/browser-CrZmtltD.js +423 -0
  21. package/dist/web/assets/{client-CBVDiOq1.js → client-CsMGnuwC.js} +6 -6
  22. package/dist/web/assets/{display-A5IEINAP-DUaOR-3m.js → display-A5IEINAP-D8OCMEUd.js} +2 -2
  23. package/dist/web/assets/{embeddings-DBkvyXXr.js → embeddings-By0Dfnxp.js} +1 -1
  24. package/dist/web/assets/{index-nULKD42X.js → index-BvMdqfyu.js} +11 -11
  25. package/dist/web/assets/{index-CpzEQlXL.js → index-BxMZcKR4.js} +14 -14
  26. package/dist/web/assets/{index-1YTmX4QT.js → index-CaVm3fHm.js} +2 -2
  27. package/dist/web/assets/{index-hu1QYxMc.js → index-Cze4GuPX.js} +1 -1
  28. package/dist/web/assets/index-D7mhOTIc.js +80 -0
  29. package/dist/web/assets/{index-CvL4NMn9.js → index-DYa4NhVm.js} +1 -1
  30. package/dist/web/assets/index-DjkfvIWz.js +1783 -0
  31. package/dist/web/assets/index-DlhqMiEp.css +1 -0
  32. package/dist/web/assets/index-DwWeVml5.js +7 -0
  33. package/dist/web/assets/{index-BpbjNRUs.js → index-o8LZS9ZF.js} +6 -6
  34. package/dist/web/assets/{llms-DLjfslEu.js → llms-DCC0HMlB.js} +1 -1
  35. package/dist/web/index.html +3 -3
  36. package/package.json +5 -5
  37. package/dist/web/assets/browser-CJMCg3ZC.js +0 -410
  38. package/dist/web/assets/index-C314DwyM.js +0 -40
  39. package/dist/web/assets/index-CW3Avs3Z.js +0 -80
  40. package/dist/web/assets/index-CqlJu5dO.js +0 -1753
  41. package/dist/web/assets/index-G80eS8Oh.css +0 -1
@@ -0,0 +1,423 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-CsMGnuwC.js","assets/index-DjkfvIWz.js","assets/index-DlhqMiEp.css","assets/display-A5IEINAP-D8OCMEUd.js"])))=>i.map(i=>d[i]);
2
+ import{bV as vo,bW as lc,bX as cc,_ as $,bw as ve,bq as y,bB as kr,bY as ke,bZ as Nr,bH as $r,by as uc,bD as hc,bx as dc,b_ as fc,b$ as pc,c0 as mc,p as Ds,bo as gc,c1 as Rr,c2 as bo,a as Ht,bI as Vn}from"./index-DjkfvIWz.js";import{bj as cy,c3 as uy,bp as hy,bs as dy,c4 as fy,c5 as py,br as my,bp as gy,c6 as yy,c7 as wy,c8 as vy,c8 as by}from"./index-DjkfvIWz.js";import{D as Bn,S as Er,t as yc,a as hi,T as wc,b as vc}from"./index-CaVm3fHm.js";import{h as xn,s as di,g as fi,d as bc,k as _c,l as Sc,I as Cc,C as Tc,m as kc,t as Ec,n as xc,o as Mc,p as Ac,q as Pc,r as Ic,u as Oc,v as Nc,w as $c,x as Rc,y as jc,R as Lc,z as _o,e as Dc}from"./index-o8LZS9ZF.js";import{aT as Fc,aU as Fs,aV as Uc,aw as $e,e as sn,aW as Vc,aX as fn,a4 as ge,y as xe,aY as pi,i as mi,B as I,f as j,aZ as as,g as q,aj as en,ah as ee,S as re,p as Bc,C as zc,a_ as Wc,u as So,aE as gi,a$ as te,al as pn,b0 as cn,F as yi,z as De,b1 as Us,D as ls,E as Gt,ap as lr,b2 as Hc,b3 as Gc,b4 as Kc,b5 as Jc,b6 as qc,b7 as Yc,b8 as Xc,b9 as Zc,ba as Qc,bb as eu,bc as tu,bd as nu,be as ru,bf as su,bg as ou,bh as iu,bi as au,bj as lu,bk as cu,L as uu,bl as hu,bm as du,bn as fu,A as ze,k as un,m as Ve,M as st,at as Kt,bo as pu,H as mu,aF as Co,au as gu,bp as To,bq as ko,af as Vs,ae as cs,ad as us,ag as yu,V as wu,a9 as Bs,ac as et,br as cr,o as B,bs as Se,bt as vu,bu as Ae,bv as Re,bw as bu,U as jr,s as Q,bx as zs,aa as _u,r as Su,ax as Cu,T as Tu,by as Mn,bz as wi,bA as Jt,bB as mn,bC as Ge,bD as ft,bE as V,ab as ku,bF as zn,ai as Eu,bG as vi,bH as An,bI as xu,aP as Mu,aN as Au,aM as Pu,bJ as Iu}from"./index-D7mhOTIc.js";import{E as bi,c as Ou,e as Nu}from"./embeddings-By0Dfnxp.js";import{L as _i,o as $u,l as Ru}from"./llms-DCC0HMlB.js";const ju=t=>{const e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},Lu=()=>{const t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${ju(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${lc(r.values[0])}`:`Invalid option: expected one of ${vo(r.values,"|")}`;case"too_big":{const s=r.inclusive?"<=":"<",o=e(r.origin);return o?`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{const s=r.inclusive?">=":">",o=e(r.origin);return o?`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${o.unit}`:`Too small: expected ${r.origin} to be ${s}${r.minimum.toString()}`}case"invalid_format":{const s=r;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${n[s.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${vo(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function Du(){return{localeError:Lu()}}cc(Du());var Lr,$n,Dr=0,Fr=0;function Fu(t,e,n){var r=0,s=e||new Array(16);t=t||{};var o=t.node,i=t.clockseq;if(t._v6||(o||(o=Lr),i==null&&(i=$n)),o==null||i==null){var a=t.random||(t.rng||Fc)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Lr&&!t._v6&&(o[0]|=1,Lr=o)),i==null&&(i=(a[6]<<8|a[7])&16383,$n===void 0&&!t._v6&&($n=i))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Fr+1,u=l-Dr+(c-Fr)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||l>Dr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Dr=l,Fr=c,$n=i,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=l/4294967296*1e4&268435455;s[r++]=d>>>8&255,s[r++]=d&255,s[r++]=d>>>24&15|16,s[r++]=d>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var f=0;f<6;++f)s[r+f]=o[f];return e||Fs(s)}function Uu(t){var e=typeof t=="string"?Uc(t):t,n=Vu(e);return typeof t=="string"?Fs(n):n}function Vu(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function Eo(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function xo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Eo(Object(n),!0).forEach(function(r){Bu(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Eo(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Bu(t,e,n){return(e=zu(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function zu(t){var e=Wu(t,"string");return typeof e=="symbol"?e:e+""}function Wu(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Hu(t={},e,n=0){var r=Fu(xo(xo({},t),{},{_v6:!0}),new Uint8Array(16));return r=Uu(r),Fs(r)}async function*Gu(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}$(Gu,"streamEventsToAISDK");function Ku(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}$(Ku,"createReadableStreamFromGenerator");async function*Ju(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
3
+ 🔧 Using tool: ${e.name}
4
+ `;break;case"on_tool_end":yield`
5
+ ✅ Tool completed: ${e.name}
6
+ `;break}}$(Ju,"streamEventsToAISDKWithTools");var Ot,qu=(Ot=class{disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,n){const r=new this(n);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(y.info("No active sessions found, creating new ones..."),await e.createAllSessions());const s=e.getAllActiveSessions(),o=Object.values(s).map(i=>i.connector);return r.createToolsFromConnectors(o)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const s=this.connectorToolMap.get(e);return y.debug(`Returning ${s.length} existing tools for connector`),s}const n=[];if(!await this.ensureConnectorInitialized(e))return[];for(const s of e.tools){const o=this.convertTool(s,e);o&&n.push(o)}return this.connectorToolMap.set(e,n),y.debug(`Loaded ${n.length} new tools for connector: ${n.map(s=>s?.name??String(s)).join(", ")}`),n}async createToolsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadToolsForConnector(r);n.push(...s)}return y.debug(`Available tools: ${n.length}`),n}async loadResourcesForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listAllResources())?.resources||[];if(this.convertResource)for(const i of o){const a=this.convertResource(i,e);a&&n.push(a)}y.debug(`Loaded ${n.length} new resources for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){y.warn(`Error loading resources for connector: ${s}`)}return n}async loadPromptsForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(const i of o){const a=this.convertPrompt(i,e);a&&n.push(a)}y.debug(`Loaded ${n.length} new prompts for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){y.warn(`Error loading prompts for connector: ${s}`)}return n}async createResourcesFromConnectors(e){const n=[];for(const r of e){const s=await this.loadResourcesForConnector(r);n.push(...s)}return y.debug(`Available resources: ${n.length}`),n}async createPromptsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadPromptsForConnector(r);n.push(...s)}return y.debug(`Available prompts: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){y.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return y.error(`Error initializing connector: ${n}`),!1}}return!0}},$(Ot,"BaseAdapter"),Ot),Nt,Yu=(Nt=class{static convert(e){return this.parseSchema(e)}static matchesCondition(e,n){if(!n.properties)return!0;if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;for(const[s,o]of Object.entries(n.properties)){if(!(s in r)){if("const"in o)return!1;continue}const i=r[s];if("const"in o&&i!==o.const||"minimum"in o&&typeof i=="number"&&i<o.minimum||"maximum"in o&&typeof i=="number"&&i>o.maximum)return!1}return!0}static validateConditionalSchema(e,n,r){this.validateRequiredProperties(e,n,r),this.validatePropertyPatterns(e,n,r),this.validateNestedConditions(e,n,r)}static validateRequiredProperties(e,n,r){if(n.required){if(typeof e!="object"||e===null){for(const s of n.required)r.addIssue({code:Nr.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:Nr.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(e,n,r){if(!n.properties||typeof e!="object"||e===null||Array.isArray(e))return;const s=e;for(const[o,i]of Object.entries(n.properties)){if(!(o in s))continue;const a=s[o];i.pattern&&typeof a=="string"&&(new RegExp(i.pattern).test(a)||r.addIssue({code:Nr.custom,message:`String '${a}' does not match pattern '${i.pattern}'`,path:[o]}))}}static validateNestedConditions(e,n,r){if(!n.if||!n.then)return;this.matchesCondition(e,n.if)?this.validateConditionalSchema(e,n.then,r):n.else&&this.validateConditionalSchema(e,n.else,r)}static parseSchema(e){return Array.isArray(e.type)?this.handleTypeArray(e):e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.if&&e.then?this.parseObject(e):e.properties&&(!e.type||e.type==="object")?this.parseObject(e):this.handleSingleType(e)}static handleTypeArray(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");return e.type.includes("null")?this.handleNullableType(e):this.createUnionFromTypes(e.type,e)}static handleNullableType(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");const n={...e};return n.type=e.type.filter(s=>s!=="null"),n.type.length===1?this.handleSingleType({...e,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(e,n){const r=e.map(s=>{const o={...n,type:s};return this.parseSchema(o)});return $r(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):ke();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return uc();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=hc();let r=n;return r=this.applyNumberBounds(n,e),r=this.applyNumberMultipleOf(n,e),r=this.applyNumberEnum(n,e),r=this.applyIntegerConstraint(n,e),r}static applyNumberBounds(e,n){let r=e;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(e,n){return n.multipleOf===void 0?e:e.refine(r=>r%n.multipleOf===0,{message:`Number must be a multiple of ${n.multipleOf}`})}static applyNumberEnum(e,n){if(!n.enum)return e;const r=n.enum.filter(s=>typeof s=="number");return r.length===0?e:e.refine(s=>r.includes(s),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(e,n){return n.type!=="integer"?e:e.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(e){const n=kr();let r=n;return e.format?this.applyStringFormat(n,e):(r=this.applyStringPattern(n,e),r=this.applyStringLength(n,e),r=this.applyStringEnum(n,e),r)}static applyStringFormat(e,n){if(!n.format)return e;switch(n.format){case"email":return e.email();case"date-time":return e.datetime();case"uri":return e.url();case"uuid":return e.uuid();case"date":return e.date();default:return e}}static applyStringPattern(e,n){if(!n.pattern)return e;const r=new RegExp(n.pattern);return e.regex(r,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(e,n){const r=e;return n.minLength!==void 0&&(e=e.min(n.minLength)),n.maxLength!==void 0&&(e=e.max(n.maxLength)),r}static applyStringEnum(e,n){return n.enum?e.refine(r=>n.enum?.includes(r),{message:`Value must be one of: ${n.enum?.join(", ")}`}):e}static parseArray(e){if(Array.isArray(e.items)){const o=e.items.map(i=>this.parseSchema(i));return $r(o)}const n=e.items?this.parseSchema(e.items):ke(),r=dc(n);let s=r;return s=this.applyArrayConstraints(r,e),s}static applyArrayConstraints(e,n){return n.minItems!==void 0&&(e=e.min(n.minItems)),n.maxItems!==void 0&&(e=e.max(n.maxItems)),n.uniqueItems?e.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):e}static parseObject(e){if(e.if&&e.then)return this.parseConditional(e);const n={};return this.processObjectProperties(e,n),this.processAdditionalProperties(e,ve(n))}static processObjectProperties(e,n){const r=new Set(e.required||[]);if(e.properties)for(const[s,o]of Object.entries(e.properties)){const i=this.parseSchema(o);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(e,n){if(e.additionalProperties===!0)return n.passthrough();if(e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(e){const n=this.createBaseObjectSchema(e),r=e.if,s=e.then,o=e.else;return n.superRefine((i,a)=>{const l=this.applyDefaultValues(i,e);this.matchesCondition(l,r)?this.validateConditionalSchema(l,s,a):o&&this.validateConditionalSchema(l,o,a)})}static createBaseObjectSchema(e){const n={},r=new Set(e.required||[]);for(const[o,i]of Object.entries(e.properties||{})){const a=this.parseSchema(i);n[o]=r.has(o)?a:a.optional()}const s=ve(n);return this.processAdditionalProperties(e,s)}static applyDefaultValues(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return e;const s={...e};if(!n.properties)return s;for(const[o,i]of Object.entries(n.properties))!(o in s)&&"default"in i&&(s[o]=i.default);return s}static parseCombinator(e){if(e.oneOf)return this.parseOneOf(e.oneOf);if(e.anyOf)return this.parseAnyOf(e.anyOf);if(e.allOf)return this.parseAllOf(e.allOf);throw new Error("Unsupported schema type")}static parseOneOf(e){return this.createUnionFromSchemas(e)}static parseAnyOf(e){return this.createUnionFromSchemas(e)}static createUnionFromSchemas(e){if(e.length===0)return ke();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(fc()):n.push(this.parseSchema(r));return n.length>=2?$r(n):n.length===1?n[0]:ke()}static parseAllOf(e){if(e.length===0)return ke();if(e.length===1)return this.parseSchema(e[0]);const n=e.reduce((r,s)=>this.mergeSchemas(r,s));return this.parseSchema(n)}static mergeSchemas(e,n){const r={...e,...n};if(e.properties&&n.properties){const s={...e.properties,...n.properties};r.properties=s}if(e.required&&n.required){const s=[...new Set([...e.required,...n.required])];r.required=s}return r}},$(Nt,"JSONSchemaToZod"),Nt);function Si(t){try{return Yu.convert(t)}catch(e){return y.warn(`Failed to convert JSON schema to Zod: ${e}`),ke()}}$(Si,"schemaToZod");var $t,St=($t=class extends qu{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?Si(e.inputSchema):ve({}).optional();return new Bn({name:e.name??"NO NAME",description:e.description??"",schema:r,func:$(async o=>{y.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(o)}`);try{const i=await n.callTool(e.name,o);return JSON.stringify(i)}catch(i){return y.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,n){const s=$(a=>a.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),o=e.uri;return new Bn({name:s,description:e.description||`Return the content of the resource located at URI ${o}.`,schema:ve({}).optional(),func:$(async()=>{y.debug(`Resource tool: "${s}" called`);try{const a=await n.readResource(o);return a.contents&&a.contents.length>0?a.contents.map(l=>typeof l=="string"?l:l.text?l.text:l.uri?l.uri:JSON.stringify(l)).join(`
7
+ `):"Resource is empty or unavailable"}catch(a){return y.error(`Error reading resource: ${a.message}`),`Error reading resource: ${String(a)}`}},"func")})}convertPrompt(e,n){let r=ve({}).optional();if(e.arguments&&e.arguments.length>0){const o={};for(const i of e.arguments){const a=kr();i.required!==!1?o[i.name]=a:o[i.name]=a.optional()}r=Object.keys(o).length>0?ve(o):ve({}).optional()}return new Bn({name:e.name,description:e.description||"",schema:r,func:$(async o=>{y.debug(`Prompt tool: "${e.name}" called with args: ${JSON.stringify(o)}`);try{const i=await n.getPrompt(e.name,o);return i.messages&&i.messages.length>0?i.messages.map(a=>typeof a=="string"?a:a.content?typeof a.content=="string"?a.content:JSON.stringify(a.content):JSON.stringify(a)).join(`
8
+ `):"Prompt returned no messages"}catch(i){return y.error(`Error getting prompt: ${i.message}`),`Error getting prompt: ${String(i)}`}},"func")})}},$($t,"LangChainAdapter"),$t),Xu=Object.defineProperty,Ci=(t,e)=>{for(var n in e)Xu(t,n,{get:e[n],enumerable:!0})},Zu={};Ci(Zu,{ConfigurableModel:()=>hs,MODEL_PROVIDER_CONFIG:()=>xr,_inferModelProvider:()=>Ei,getChatModelByClassName:()=>ki,initChatModel:()=>it});const xr={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}},Ti=Object.keys(xr);async function ki(t){const e=Object.entries(xr).find(([,r])=>r.className===t);if(!e)return;const[,n]=e;try{return(await import(n.package))[n.className]}catch(r){const s=r;if("code"in s&&s.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in s&&typeof s.message=="string"){const i=(s.message.startsWith("Error: ")?s.message.slice(7):s.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${i}. Please install with \`npm install ${i}\` or \`pnpm install ${i}\``)}throw r}}async function Qu(t,e,n={}){const r=e||Ei(t);if(!r)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);const s=xr[r];if(!s){const l=Ti.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
9
+
10
+ Supported model providers are: ${l}`)}const{modelProvider:o,...i}=n,a=await ki(s.className);return new a({model:t,...i})}function Ei(t){return t.startsWith("gpt-3")||t.startsWith("gpt-4")||t.startsWith("gpt-5")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?"openai":t.startsWith("claude")?"anthropic":t.startsWith("command")?"cohere":t.startsWith("accounts/fireworks")?"fireworks":t.startsWith("gemini")?"google-vertexai":t.startsWith("amazon.")?"bedrock":t.startsWith("mistral")?"mistralai":t.startsWith("sonar")||t.startsWith("pplx")?"perplexity":void 0}var hs=class Wn extends xn{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields==="any"?this._configurableFields="any":this._configurableFields=e.configurableFields??["model","modelProvider"],e.configPrefix?this._configPrefix=e.configPrefix.endsWith("_")?e.configPrefix:`${e.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations,this._profile=e.profile??void 0}async _getModelInstance(e){const n=JSON.stringify(e??{}),r=this._modelInstanceCache.get(n);if(r)return r;const s={...this._defaultConfig,...this._modelParams(e)};let o=await Qu(s.model,s.modelProvider,s);for(const[i,a]of Object.entries(this._queuedMethodOperations))i in o&&typeof o[i]=="function"&&(o=await o[i](...a));return this._modelInstanceCache.set(n,o),o}async _generate(e,n,r){return(await this._getModelInstance(n))._generate(e,n??{},r)}bindTools(e,n){const r={...this._queuedMethodOperations};return r.bindTools=[e,n],new Wn({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(e,...n)=>{const r={...this._queuedMethodOperations};return r.withStructuredOutput=[e,...n],new Wn({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})};_modelParams(e){const n=e?.configurable??{};let r={};for(const[s,o]of Object.entries(n))if(s.startsWith(this._configPrefix)){const i=this._removePrefix(s,this._configPrefix);r[i]=o}return this._configurableFields!=="any"&&(r=Object.fromEntries(Object.entries(r).filter(([s])=>this._configurableFields.includes(s)))),r}_removePrefix(e,n){return e.startsWith(n)?e.slice(n.length):e}withConfig(e){const n={...e||{}},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 o=new Wn({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new $e({config:n,bound:o})}async invoke(e,n){const r=await this._getModelInstance(n),s=sn(n);return r.invoke(e,s)}async stream(e,n){const r=await this._getModelInstance(n),s=new Vc({generator:await r.stream(e,n),config:n});return await s.setup,fn.fromAsyncGenerator(s)}async batch(e,n,r){return super.batch(e,n,r)}async*transform(e,n){const r=await this._getModelInstance(n),s=sn(n);yield*r.transform(e,s)}async*streamLog(e,n,r){const s=await this._getModelInstance(n),o=sn(n);yield*s.streamLog(e,o,{...r,_schemaFormat:"original",includeNames:r?.includeNames,includeTypes:r?.includeTypes,includeTags:r?.includeTags,excludeNames:r?.excludeNames,excludeTypes:r?.excludeTypes,excludeTags:r?.excludeTags})}streamEvents(e,n,r){const s=this;async function*o(){const i=await s._getModelInstance(n),a=sn(n),l=i.streamEvents(e,a,r);for await(const c of l)yield c}return fn.fromAsyncGenerator(o())}get profile(){if(this._profile)return this._profile;const e=JSON.stringify({});return this._modelInstanceCache.get(e)?.profile??{}}};async function it(t,e){let{configurableFields:n,configPrefix:r,modelProvider:s,profile:o,...i}={configPrefix:"",...e??{}};if(s===void 0&&t?.includes(":")){const[u,...h]=t.split(":"),d=h.length===0?[u]:[u,h.join(":")];Ti.includes(d[0])&&([s,t]=d)}let a=Array.isArray(n)?[...n]:n;!t&&a===void 0&&(a=["model","modelProvider"]),r&&a===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 l={...i};let c;return a===void 0?c=new hs({defaultConfig:{...l,model:t,modelProvider:s},configPrefix:r,profile:o}):(t&&(l.model=t),s&&(l.modelProvider=s),c=new hs({defaultConfig:l,configPrefix:r,configurableFields:a,profile:o})),await c._getModelInstance(),c}var ds=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.")}},fs=class extends Error{toolNames;constructor(t){super(`The model has called multiple tools: ${t.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=t}},xi=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(n=>`
11
+ - ${n}`).join("")}.`),this.toolName=t,this.errors=e}},Ws=class extends Error{toolCall;toolError;constructor(t,e){const n=t instanceof Error?t:new Error(String(t)),r=JSON.stringify(e.args);super(`Error invoking tool '${e.name}' with kwargs ${r} with error: ${n.stack}
12
+ Please fix the error and try again.`),this.toolCall=e,this.toolError=n}};function Hs(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function ur(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_getModelInstance"in t&&typeof t._getModelInstance=="function"}const Mo=!0;let eh=0;var Je=class ps{constructor(e,n,r){this.schema=e,this.tool=n,this.options=r}get name(){return this.tool.function.name}static fromSchema(e,n){function r(a){return a??`extract-${++eh}`}if(mi(e)){const a=xe(e),l={type:"function",function:{name:r(a.title),strict:!1,description:a.description??"Tool for extracting structured output from the model's response.",parameters:a}};return new ps(a,l,n)}let s;typeof e.name=="string"&&typeof e.parameters=="object"&&e.parameters!=null?s=e:s={name:r(e.title),description:e.description??"",parameters:e.schema||e};const o=xe(e),i={type:"function",function:s};return new ps(o,i,n)}parse(e){const r=new pi(this.schema).validate(e);if(!r.valid)throw new xi(this.name,r.errors.map(s=>s.error));return e}},Xe=class Mi{_schemaType;schema;strict;constructor(e,n){if("schema"in e&&typeof e.schema=="object"&&e.schema!==null&&!("type"in e)){const r=e;this.schema=r.schema,this.strict=r.strict??Mo}else this.schema=e,this.strict=n??Mo}static fromSchema(e,n){const r=xe(e);return new Mi(r,n)}parse(e){let n;if(typeof e.content=="string")n=e.content;else if(Array.isArray(e.content)){for(const r of e.content)if(typeof r=="object"&&r!==null&&"type"in r&&r.type==="text"&&"text"in r&&typeof r.text=="string"){n=r.text;break}}if(!(!n||n===""))try{const r=JSON.parse(n);return new pi(this.schema).validate(r).valid?r:void 0}catch{}}};function Ai(t,e,n){if(!t)return[];if(typeof t=="object"&&t!==null&&"__responseFormatUndefined"in t)return[];if(Array.isArray(t)){if(t.every(s=>s instanceof Je||s instanceof Xe))return t;if(t.every(s=>ge(s)))return t.map(s=>Je.fromSchema(s,e));if(t.every(s=>typeof s=="object"&&s!==null&&!ge(s)))return t.map(s=>Je.fromSchema(s,e));throw new Error(`Invalid response format: list contains mixed types.
13
+ All items must be either InteropZodObject or plain JSON schema objects.`)}if(t instanceof Je||t instanceof Xe)return[t];const r=Pi(n);if(ge(t))return r?[Xe.fromSchema(t)]:[Je.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[Xe.fromSchema(t)]:[Je.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function th(t,e){return Ai(t,e)}function nh(t){if(typeof t=="object"&&t!==null&&"schema"in t&&!mi(t)&&!("type"in t)){const{schema:e,strict:n}=t;return Xe.fromSchema(e,n)}return Xe.fromSchema(t)}const rh=["ChatOpenAI","ChatXAI"],Ao=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function Pi(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return Ao.some(r=>n.includes(r))}if(ur(t))return Pi(t._defaultConfig.model);if(!Hs(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||rh.includes(e)&&("model"in t&&Ao.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function Gs(t){let e=0;for(const n of t){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="",I.isInstance(n)&&Array.isArray(n.tool_calls)&&n.tool_calls.length>0&&(r+=JSON.stringify(n.tool_calls)),j.isInstance(n)&&(r+=n.tool_call_id??""),e+=r.length}return Math.ceil(e/4)}function Ze(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Mr(t){return typeof t=="function"?t:t.hook}function Ii(t){return new Promise(e=>setTimeout(e,t))}function Oi(t,e){const{backoffFactor:n,initialDelayMs:r,maxDelayMs:s,jitter:o}=t;let i;if(n===0?i=r:i=r*n**e,i=Math.min(i,s),o&&i>0){const a=i*.25;i=i+(Math.random()*2-1)*a,i=Math.max(0,i)}return i}const Ni=Symbol("AgentMiddleware");function se(t){return{[Ni]:!0,name:t.name,stateSchema:t.stateSchema,contextSchema:t.contextSchema,wrapToolCall:t.wrapToolCall,wrapModelCall:t.wrapModelCall,beforeAgent:t.beforeAgent,beforeModel:t.beforeModel,afterModel:t.afterModel,afterAgent:t.afterAgent,tools:t.tools}}function $i(t){return Hu({clockseq:t})}function kt(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return as(t,new Uint8Array(n))}const sh="__error__",Hn="__scheduled__",oh="__interrupt__",ih="__resume__";var Po="[...]",ah="[Circular]",hr=[],Et=[];function lh(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function ch(t,e,n,r){typeof r>"u"&&(r=lh()),ms(t,"",0,[],void 0,0,r);var s;try{Et.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,uh(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;hr.length!==0;){var o=hr.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return s}function Ur(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),hr.push([r,n,e,s])):Et.push([e,n,t]):(r[n]=t,hr.push([r,n,e]))}function ms(t,e,n,r,s,o,i){o+=1;var a;if(typeof t=="object"&&t!==null){for(a=0;a<r.length;a++)if(r[a]===t){Ur(ah,t,e,s);return}if(typeof i.depthLimit<"u"&&o>i.depthLimit){Ur(Po,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){Ur(Po,t,e,s);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)ms(t[a],a,a,r,t,o,i);else{var l=Object.keys(t);for(a=0;a<l.length;a++){var c=l[a];ms(t[c],c,a,r,t,o,i)}}r.pop()}}function uh(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(Et.length>0)for(var r=0;r<Et.length;r++){var s=Et[r];if(s[1]===e&&s[0]===n){n=s[2],Et.splice(r,1);break}}return t.call(this,e,n)}}const hh=[];var dh={},Ri={};q(Ri,{BaseChatMessageHistory:()=>ji,BaseListChatMessageHistory:()=>Ks,InMemoryChatMessageHistory:()=>fh});var ji=class extends en{async addMessages(t){for(const e of t)await this.addMessage(e)}},Ks=class extends en{addUserMessage(t){return this.addMessage(new ee(t))}addAIMessage(t){return this.addMessage(new I(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},fh=class extends Ks{lc_namespace=["langchain","stores","message","in_memory"];messages=[];constructor(t){super(...arguments),this.messages=t??[]}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async clear(){this.messages=[]}},ph={},Li={};q(Li,{BaseMemory:()=>mh,getInputValue:()=>gh,getOutputValue:()=>yh,getPromptInputKey:()=>wh});var mh=class{};const Di=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},gh=(t,e)=>{const n=Di(t,e);if(!n){const r=Object.keys(t);throw new Error(`input values have ${r.length} keys, you must specify an input key or pass only 1 key as input`)}return n},yh=(t,e)=>{const n=Di(t,e);if(!n&&n!==""){const r=Object.keys(t);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 wh(t,e){const n=Object.keys(t).filter(r=>!e.includes(r)&&r!=="stop");if(n.length!==1)throw new Error(`One input key expected, but got ${n.length}`);return n[0]}var Fi={};q(Fi,{BaseStore:()=>Ui,InMemoryStore:()=>Vi});var Ui=class extends en{},Vi=class extends Ui{lc_namespace=["langchain","storage"];store={};async mget(t){return t.map(e=>this.store[e])}async mset(t){for(const[e,n]of t)this.store[e]=n}async mdelete(t){for(const e of t)delete this.store[e]}async*yieldKeys(t){const e=Object.keys(this.store);for(const n of e)(t===void 0||n.startsWith(t))&&(yield n)}},Bi={};q(Bi,{BaseRetriever:()=>Js});var Js=class extends re{callbacks;tags;metadata;verbose;constructor(t){super(t),this.callbacks=t?.callbacks,this.tags=t?.tags??[],this.metadata=t?.metadata??{},this.verbose=t?.verbose??!1}_getRelevantDocuments(t,e){throw new Error("Not implemented!")}async invoke(t,e){const n=sn(Bc(e)),s=await(await zc.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),t,n.runId,void 0,void 0,void 0,n.runName);try{const o=await this._getRelevantDocuments(t,s);return await s?.handleRetrieverEnd(o),o}catch(o){throw await s?.handleRetrieverError(o),o}}},zi={};q(zi,{SaveableVectorStore:()=>vh,VectorStore:()=>qs,VectorStoreRetriever:()=>Gn});var Gn=class extends Js{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(t){super(t),this.vectorStore=t.vectorStore,this.k=t.k??this.k,this.searchType=t.searchType??this.searchType,this.filter=t.filter,t.searchType==="mmr"&&(this.searchKwargs=t.searchKwargs)}async _getRelevantDocuments(t,e){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(t,{k:this.k,filter:this.filter,...this.searchKwargs},e?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(t,this.k,this.filter,e?.getChild("vectorstore"))}async addDocuments(t,e){return this.vectorStore.addDocuments(t,e)}},qs=class extends en{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(t,e){super(e),this.embeddings=t}async delete(t){throw new Error("Not implemented.")}async similaritySearch(t,e=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)).map(o=>o[0])}async similaritySearchWithScore(t,e=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)}static fromTexts(t,e,n,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(t,e,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(t,e,n,r,s,o){if(typeof t=="number")return new Gn({vectorStore:this,k:t,filter:e,tags:[...r??[],this._vectorstoreType()],metadata:s,verbose:o,callbacks:n});{const i={vectorStore:this,k:t?.k,filter:t?.filter,tags:[...t?.tags??[],this._vectorstoreType()],metadata:t?.metadata,verbose:t?.verbose,callbacks:t?.callbacks,searchType:t?.searchType};return t?.searchType==="mmr"?new Gn({...i,searchKwargs:t.searchKwargs}):new Gn({...i})}}},vh=class extends qs{static load(t,e){throw new Error("Not implemented")}},Wi={};q(Wi,{BaseDocumentLoader:()=>Hi});var Hi=class{},Gi={};q(Gi,{LangSmithLoader:()=>bh});var bh=class extends Hi{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(t){if(super(),t.client&&t.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=t.client??new Wc(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??_h,this.datasetId=t.datasetId,this.datasetName=t.datasetName,this.exampleIds=t.exampleIds,this.asOf=t.asOf,this.splits=t.splits,this.inlineS3Urls=t.inlineS3Urls,this.offset=t.offset,this.limit=t.limit,this.metadata=t.metadata,this.filter=t.filter}async load(){const t=[];for await(const e 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=e.inputs;for(const o of this.contentKey)n=n[o];const r=this.formatContent(n),s=e;["created_at","modified_at"].forEach(o=>{o in s&&typeof s[o]=="object"&&(s[o]=s[o].toString())}),t.push({pageContent:r,metadata:s})}return t}};function _h(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var We=class{pageContent;metadata;id;constructor(t){this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},Ki=class extends re{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},Sh=class extends Ki{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},Ji={};q(Ji,{BaseDocumentTransformer:()=>Ki,Document:()=>We,MappingDocumentTransformer:()=>Sh});var Ys=class extends en{lc_namespace=["langchain_core","example_selectors","base"]},qi=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},Ch=class extends qi{defaultPrompt;conditionals;constructor(t,e=[]){super(),this.defaultPrompt=t,this.conditionals=e}getPrompt(t){for(const[e,n]of this.conditionals)if(e(t))return n;return this.defaultPrompt}};function Th(t){return t._modelType()==="base_llm"}function kh(t){return t._modelType()==="base_chat_model"}function Io(t){return t.split(/\n| /).length}var Eh=class Yi extends Ys{examples=[];examplePrompt;getTextLength=Io;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Io}async addExample(e){this.examples.push(e);const n=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(n))}async calculateExampleTextLengths(e,n){if(e.length>0)return e;const{examples:r,examplePrompt:s}=n;return(await Promise.all(r.map(i=>s.format(i)))).map(i=>this.getTextLength(i))}async selectExamples(e){const n=Object.values(e).join(" ");let r=this.maxLength-this.getTextLength(n),s=0;const o=[];for(;r>0&&s<this.examples.length;){const i=r-this.exampleTextLengths[s];if(i<0)break;o.push(this.examples[s]),r=i,s+=1}return o}static async fromExamples(e,n){const r=new Yi(n);return await Promise.all(e.map(s=>r.addExample(s))),r}};function Vr(t){return Object.keys(t).sort().map(e=>t[e])}var xh=class Xi extends Ys{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(e){const n=this.inputKeys??Object.keys(e),r=Vr(n.reduce((s,o)=>({...s,[o]:e[o]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new We({pageContent:r,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),r=Vr(n.reduce((i,a)=>({...i,[a]:e[a]}),{})).join(" "),o=(await this.vectorStoreRetriever.invoke(r)).map(i=>i.metadata);return this.exampleKeys?o.map(i=>this.exampleKeys.reduce((a,l)=>({...a,[l]:i[l]}),{})):o}static async fromExamples(e,n,r,s={}){const o=s.inputKeys??null,i=e.map(l=>Vr(o?o.reduce((c,u)=>({...c,[u]:l[u]}),{}):l).join(" ")),a=await r.fromTexts(i,e,n,s);return new Xi({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},Zi={};q(Zi,{BaseExampleSelector:()=>Ys,BasePromptSelector:()=>qi,ConditionalPromptSelector:()=>Ch,LengthBasedExampleSelector:()=>Eh,SemanticSimilarityExampleSelector:()=>xh,isChatModel:()=>kh,isLLM:()=>Th});const gs="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var Mh=class extends en{lc_namespace=["langchain","recordmanagers"]},Qi=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=di;constructor(t){this.uid=t.uid,this.pageContent=t.pageContent,this.metadata=t.metadata}makeDefaultKeyEncoder(t){this.keyEncoder=t}calculateHashes(){const t=["hash_","content_hash","metadata_hash"];for(const n of t)if(n in this.metadata)throw new Error(`Metadata cannot contain key ${n} as it is reserved for internal use. Restricted keys: [${t.join(", ")}]`);const e=this._hashStringToUUID(this.pageContent);try{const n=this._hashNestedDictToUUID(this.metadata);this.contentHash=e,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 We({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(t,e){const n=new this({pageContent:t.pageContent,metadata:t.metadata,uid:e||t.uid});return n.calculateHashes(),n}_hashStringToUUID(t){const e=this.keyEncoder(t);return as(e,gs)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return as(n,gs)}};function ea(t,e){const n=[];let r=[];return e.forEach(s=>{r.push(s),r.length>=t&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function ta(t){const e=new Set,n=[];for(const r of t){if(!r.hash_)throw new Error("Hashed document does not have a hash");e.has(r.hash_)||(e.add(r.hash_),n.push(r))}return n}function na(t){if(t===null)return e=>null;if(typeof t=="string")return e=>e.metadata[t];if(typeof t=="function")return t;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof t}`)}const ra=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function Ah(t){const{docsSource:e,recordManager:n,vectorStore:r,options:s}=t,{batchSize:o=100,cleanup:i,sourceIdKey:a,cleanupBatchSize:l=1e3,forceUpdate:c=!1}=s??{};if(i==="incremental"&&!a)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");const u=ra(e)?await e.load():e,h=na(a??null),d=await n.getTime();let f=0,p=0,m=0,S=0;const C=ea(o??100,u);for(const E of C){const b=ta(E.map(T=>Qi.fromDocument(T))),w=b.map(T=>h(T));i==="incremental"&&b.forEach((T,M)=>{if(w[M]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const g=await n.exists(b.map(T=>T.uid)),k=[],_=[],v=[],x=new Set;if(b.forEach((T,M)=>{if(g[M])if(c)x.add(T.uid);else{v.push(T.uid);return}k.push(T.uid),_.push(T.toDocument())}),v.length>0&&(await n.update(v,{timeAtLeast:d}),S+=v.length),_.length>0&&(await r.addDocuments(_,{ids:k}),f+=_.length-x.size,m+=x.size),await n.update(b.map(T=>T.uid),{timeAtLeast:d,groupIds:w}),i==="incremental"){w.forEach(M=>{if(!M)throw new Error("Source id cannot be null")});const T=await n.listKeys({before:d,groupIds:w});T.length>0&&(await r.delete({ids:T}),await n.deleteKeys(T),p+=T.length)}}if(i==="full"){let E=await n.listKeys({before:d,limit:l});for(;E.length>0;)await r.delete({ids:E}),await n.deleteKeys(E),p+=E.length,E=await n.listKeys({before:d,limit:l})}return{numAdded:f,numDeleted:p,numUpdated:m,numSkipped:S}}var sa={};q(sa,{RecordManager:()=>Mh,UUIDV5_NAMESPACE:()=>gs,_HashedDocument:()=>Qi,_batch:()=>ea,_deduplicateInOrder:()=>ta,_getSourceIdAssigner:()=>na,_isBaseDocumentLoader:()=>ra,index:()=>Ah});var Ph={},oa=class extends fi{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(t){super(),this.argsOnly=t?.argsOnly??this.argsOnly}async parseResult(t){if("message"in t[0]){const n=t[0].message.additional_kwargs.function_call;if(!n)throw new Error(`No function_call in message ${JSON.stringify(t)}`);if(!n.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(t)}`);return this.argsOnly?n.arguments:JSON.stringify(n)}else throw new Error(`No message in generations ${JSON.stringify(t)}`)}},ia=class extends bc{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(t){super(t),this.argsOnly=t?.argsOnly??this.argsOnly,this.outputParser=new oa(t)}_diff(t,e){return e?_c(t??{},e):void 0}async parsePartialResult(t){const e=t[0];if(!e.message)return;const{message:n}=e,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?So(r.arguments):{...r,arguments:So(r.arguments)}}async parseResult(t){const e=await this.outputParser.parseResult(t);if(!e)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(t)}`);return this.parse(e)}async parse(t){const e=JSON.parse(t);return this.argsOnly||(e.arguments=JSON.parse(e.arguments)),e}getFormatInstructions(){return""}},Ih=class extends fi{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new ia;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(t){super(t),this.attrName=t.attrName}async parseResult(t){return(await this.outputParser.parseResult(t))[this.attrName]}},aa={};q(aa,{JsonKeyOutputFunctionsParser:()=>Ih,JsonOutputFunctionsParser:()=>ia,OutputFunctionsParser:()=>oa});var Pn=class extends re{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(t){super(t);const{inputVariables:e}=t;if(e.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,t)}async mergePartialAndUserVariables(t){const e=this.partialVariables??{},n={};for(const[s,o]of Object.entries(e))typeof o=="string"?n[s]=o:n[s]=await o();return{...n,...t}}async invoke(t,e){const n={...this.metadata,...e?.metadata},r=[...this.tags??[],...e?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),t,{...e,tags:r,metadata:n,runType:"prompt"})}},gn=class extends Pn{async formatPromptValue(t){const e=await this.format(t);return new Sc(e)}};var Oh=Object.prototype.toString,tn=Array.isArray||function(e){return Oh.call(e)==="[object Array]"};function Xs(t){return typeof t=="function"}function Nh(t){return tn(t)?"array":typeof t}function Br(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Oo(t,e){return t!=null&&typeof t=="object"&&e in t}function $h(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var Rh=RegExp.prototype.test;function jh(t,e){return Rh.call(t,e)}var Lh=/\S/;function Dh(t){return!jh(Lh,t)}var Fh={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Uh(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return Fh[n]})}var Vh=/\s*/,Bh=/\s+/,No=/\s*=/,zh=/\s*\}/,Wh=/#|\^|\/|>|\{|&|=|!/;function Hh(t,e){if(!t)return[];var n=!1,r=[],s=[],o=[],i=!1,a=!1,l="",c=0;function u(){if(i&&!a)for(;o.length;)delete s[o.pop()];else o=[];i=!1,a=!1}var h,d,f;function p(v){if(typeof v=="string"&&(v=v.split(Bh,2)),!tn(v)||v.length!==2)throw new Error("Invalid tags: "+v);h=new RegExp(Br(v[0])+"\\s*"),d=new RegExp("\\s*"+Br(v[1])),f=new RegExp("\\s*"+Br("}"+v[1]))}p(e||fe.tags);for(var m=new In(t),S,C,E,b,w,g;!m.eos();){if(S=m.pos,E=m.scanUntil(h),E)for(var k=0,_=E.length;k<_;++k)b=E.charAt(k),Dh(b)?(o.push(s.length),l+=b):(a=!0,n=!0,l+=" "),s.push(["text",b,S,S+1]),S+=1,b===`
14
+ `&&(u(),l="",c=0,n=!1);if(!m.scan(h))break;if(i=!0,C=m.scan(Wh)||"name",m.scan(Vh),C==="="?(E=m.scanUntil(No),m.scan(No),m.scanUntil(d)):C==="{"?(E=m.scanUntil(f),m.scan(zh),m.scanUntil(d),C="&"):E=m.scanUntil(d),!m.scan(d))throw new Error("Unclosed tag at "+m.pos);if(C==">"?w=[C,E,S,m.pos,l,c,n]:w=[C,E,S,m.pos],c++,s.push(w),C==="#"||C==="^")r.push(w);else if(C==="/"){if(g=r.pop(),!g)throw new Error('Unopened section "'+E+'" at '+S);if(g[1]!==E)throw new Error('Unclosed section "'+g[1]+'" at '+S)}else C==="name"||C==="{"||C==="&"?a=!0:C==="="&&p(E)}if(u(),g=r.pop(),g)throw new Error('Unclosed section "'+g[1]+'" at '+m.pos);return Kh(Gh(s))}function Gh(t){for(var e=[],n,r,s=0,o=t.length;s<o;++s)n=t[s],n&&(n[0]==="text"&&r&&r[0]==="text"?(r[1]+=n[1],r[3]=n[3]):(e.push(n),r=n));return e}function Kh(t){for(var e=[],n=e,r=[],s,o,i=0,a=t.length;i<a;++i)switch(s=t[i],s[0]){case"#":case"^":n.push(s),r.push(s),n=s[4]=[];break;case"/":o=r.pop(),o[5]=s[2],n=r.length>0?r[r.length-1][4]:e;break;default:n.push(s)}return e}function In(t){this.string=t,this.tail=t,this.pos=0}In.prototype.eos=function(){return this.tail===""};In.prototype.scan=function(e){var n=this.tail.match(e);if(!n||n.index!==0)return"";var r=n[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};In.prototype.scanUntil=function(e){var n=this.tail.search(e),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 qt(t,e){this.view=t,this.cache={".":this.view},this.parent=e}qt.prototype.push=function(e){return new qt(e,this)};qt.prototype.lookup=function(e){var n=this.cache,r;if(n.hasOwnProperty(e))r=n[e];else{for(var s=this,o,i,a,l=!1;s;){if(e.indexOf(".")>0)for(o=s.view,i=e.split("."),a=0;o!=null&&a<i.length;)a===i.length-1&&(l=Oo(o,i[a])||$h(o,i[a])),o=o[i[a++]];else o=s.view[e],l=Oo(s.view,e);if(l){r=o;break}s=s.parent}n[e]=r}return Xs(r)&&(r=r.call(this.view)),r};function ue(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}ue.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};ue.prototype.parse=function(e,n){var r=this.templateCache,s=e+":"+(n||fe.tags).join(":"),o=typeof r<"u",i=o?r.get(s):void 0;return i==null&&(i=Hh(e,n),o&&r.set(s,i)),i};ue.prototype.render=function(e,n,r,s){var o=this.getConfigTags(s),i=this.parse(e,o),a=n instanceof qt?n:new qt(n,void 0);return this.renderTokens(i,a,r,e,s)};ue.prototype.renderTokens=function(e,n,r,s,o){for(var i="",a,l,c,u=0,h=e.length;u<h;++u)c=void 0,a=e[u],l=a[0],l==="#"?c=this.renderSection(a,n,r,s,o):l==="^"?c=this.renderInverted(a,n,r,s,o):l===">"?c=this.renderPartial(a,n,r,o):l==="&"?c=this.unescapedValue(a,n):l==="name"?c=this.escapedValue(a,n,o):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(i+=c);return i};ue.prototype.renderSection=function(e,n,r,s,o){var i=this,a="",l=n.lookup(e[1]);function c(d){return i.render(d,n,r,o)}if(l){if(tn(l))for(var u=0,h=l.length;u<h;++u)a+=this.renderTokens(e[4],n.push(l[u]),r,s,o);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(e[4],n.push(l),r,s,o);else if(Xs(l)){if(typeof s!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(n.view,s.slice(e[3],e[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(e[4],n,r,s,o);return a}};ue.prototype.renderInverted=function(e,n,r,s,o){var i=n.lookup(e[1]);if(!i||tn(i)&&i.length===0)return this.renderTokens(e[4],n,r,s,o)};ue.prototype.indentPartial=function(e,n,r){for(var s=n.replace(/[^ \t]/g,""),o=e.split(`
15
+ `),i=0;i<o.length;i++)o[i].length&&(i>0||!r)&&(o[i]=s+o[i]);return o.join(`
16
+ `)};ue.prototype.renderPartial=function(e,n,r,s){if(r){var o=this.getConfigTags(s),i=Xs(r)?r(e[1]):r[e[1]];if(i!=null){var a=e[6],l=e[5],c=e[4],u=i;l==0&&c&&(u=this.indentPartial(i,c,a));var h=this.parse(u,o);return this.renderTokens(h,n,r,u,s)}}};ue.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};ue.prototype.escapedValue=function(e,n,r){var s=this.getConfigEscape(r)||fe.escape,o=n.lookup(e[1]);if(o!=null)return typeof o=="number"&&s===fe.escape?String(o):s(o)};ue.prototype.rawValue=function(e){return e[1]};ue.prototype.getConfigTags=function(e){return tn(e)?e:e&&typeof e=="object"?e.tags:void 0};ue.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!tn(e))return e.escape};var fe={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(t){yn.templateCache=t},get templateCache(){return yn.templateCache}},yn=new ue;fe.clearCache=function(){return yn.clearCache()};fe.parse=function(e,n){return yn.parse(e,n)};fe.render=function(e,n,r,s){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Nh(e)+'" was given as the first argument for mustache#render(template, view, partials)');return yn.render(e,n,r,s)};fe.escape=Uh;fe.Scanner=In;fe.Context=qt;fe.Writer=ue;function la(){fe.escape=t=>t}const wn=t=>{const e=t.split(""),n=[],r=(o,i)=>{for(let a=i;a<e.length;a+=1)if(o.includes(e[a]))return a;return-1};let s=0;for(;s<e.length;)if(e[s]==="{"&&s+1<e.length&&e[s+1]==="{")n.push({type:"literal",text:"{"}),s+=2;else if(e[s]==="}"&&s+1<e.length&&e[s+1]==="}")n.push({type:"literal",text:"}"}),s+=2;else if(e[s]==="{"){const o=r("}",s);if(o<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(s+1,o).join("")}),s=o+1}else{if(e[s]==="}")throw new Error("Single '}' in template.");{const o=r("{}",s),i=(o<0?e.slice(s):e.slice(s,o)).join("");n.push({type:"literal",text:i}),s=o<0?e.length:o}}return n},ca=(t,e=[])=>{const n=[];for(const r of t)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=[...e,r[1]],o=ca(r[4],s);n.push(...o)}}else n.push({type:"literal",text:r[1]});return n},dr=t=>{la();const e=fe.parse(t);return ca(e)},ua=(t,e)=>wn(t).reduce((n,r)=>{if(r.type==="variable"){if(r.name in e){const s=typeof e[r.name]=="string"?e[r.name]:JSON.stringify(e[r.name]);return n+s}throw new Error(`(f-string) Missing value for input ${r.name}`)}return n+r.text},""),ha=(t,e)=>(la(),fe.render(t,e)),fr={"f-string":ua,mustache:ha},da={"f-string":wn,mustache:dr},Me=(t,e,n)=>{try{return fr[e](t,n)}catch(r){throw gi(r,"INVALID_PROMPT_INPUT")}},pr=(t,e)=>da[e](t),On=(t,e,n)=>{if(!(e in fr)){const r=Object.keys(fr);throw new Error(`Invalid template format. Got \`${e}\`;
17
+ should be one of ${r}`)}try{const r=Object.fromEntries(n.map(s=>[s,"foo"]));Array.isArray(t)?t.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")Me(s.text,e,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")Me(s.image_url,e,r);else if(typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"){const o=s.image_url.url;Me(o,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):Me(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var tt=class on extends gn{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),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))),On(this.template,this.templateFormat,n)}}_getPromptType(){return"prompt"}async format(e){const n=await this.mergePartialAndUserVariables(e);return Me(this.template,this.templateFormat,n)}static fromExamples(e,n,r,s=`
18
+
19
+ `,o=""){const i=[o,...e,n].join(s);return new on({inputVariables:r,template:i})}static fromTemplate(e,n){const{templateFormat:r="f-string",...s}=n??{},o=new Set;return pr(e,r).forEach(i=>{i.type==="variable"&&o.add(i.name)}),new on({inputVariables:[...o],templateFormat:r,template:e,...s})}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new on(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(e){if(!e.template)throw new Error("Prompt template must have a template");return new on({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}},Kn=class fa extends Pn{static lc_name(){return"ImagePromptTemplate"}lc_namespace=["langchain_core","prompts","image"];template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),On([{type:"image_url",image_url:this.template}],this.templateFormat,n)}}_getPromptType(){return"prompt"}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new fa(s)}async format(e){const n={};for(const[i,a]of Object.entries(this.template))typeof a=="string"?n[i]=Me(a,this.templateFormat,e):n[i]=a;const r=e.url||n.url,s=e.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 o={url:r};return s&&(o.detail=s),o}async formatPromptValue(e){const n=await this.format(e);return new Cc(n)}},ys=class extends re{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(t){const e=t.templateFormat??"f-string",n=ws(t.template,e);super({inputVariables:n,...t}),this.template=t.template,this.templateFormat=e,this.inputVariables=n}async format(t){return vs(this.template,t,this.templateFormat)}async invoke(t){return await this._callWithConfig(this.format.bind(this),t,{runType:"prompt"})}};function ws(t,e){const n=[];for(const r of Object.values(t))if(typeof r=="string")pr(r,e).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?pr(s,e).forEach(o=>{o.type==="variable"&&n.push(o.name)}):typeof s=="object"&&n.push(...ws(s,e));else typeof r=="object"&&r!==null&&n.push(...ws(r,e));return Array.from(new Set(n))}function vs(t,e,n){const r={};for(const[s,o]of Object.entries(t))if(typeof o=="string")r[s]=Me(o,n,e);else if(Array.isArray(o)){const i=[];for(const a of o)typeof a=="string"?i.push(Me(a,n,e)):typeof a=="object"&&i.push(vs(a,e,n));r[s]=i}else typeof o=="object"&&o!==null?r[s]=vs(o,e,n):r[s]=o;return r}var Ar=class extends re{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(t,e){return this._callWithConfig(n=>this.formatMessages(n),t,{...e,runType:"prompt"})}},bs=class extends Ar{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(t){typeof t=="string"&&(t={variableName:t}),super(t),this.variableName=t.variableName,this.optional=t.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(t){const e=t[this.variableName];if(this.optional&&!e)return[];if(!e){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(e)?n=e.map(pn):n=[pn(e)]}catch(r){const s=typeof e=="string"?e:JSON.stringify(e,null,2),o=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(`
20
+
21
+ `));throw o.name="InputFormatError",o.lc_error_code=r.lc_error_code,o}return n}},pa=class extends Ar{prompt;constructor(t){"prompt"in t||(t={prompt:t}),super(t),this.prompt=t.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(t){return[await this.format(t)]}},Zs=class extends Pn{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){const e=await this.formatMessages(t);return new Tc(e)}},ma=class extends pa{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(t,e){"prompt"in t||(t={prompt:t,role:e}),super(t),this.role=t.role}async format(t){return new yi(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(tt.fromTemplate(t,{templateFormat:n?.templateFormat}),e)}};function Jh(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function qh(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:"image_url"in t&&(typeof t.image_url=="string"||typeof t.image_url=="object"&&t.image_url!==null&&"url"in t.image_url&&typeof t.image_url.url=="string")}var Qs=class extends Ar{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(t,e){if("prompt"in t||(t={prompt:t}),super(t),this.prompt=t.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=e??this.additionalOptions}createMessage(t){const e=this.constructor;if(e._messageClass()){const n=e._messageClass();return new n({content:t})}else if(e.chatMessageClass){const n=e.chatMessageClass();return new n({content:t,role:this.getRoleFromMessageClass(n.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(t){switch(t){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(t,e){if(typeof t=="string")return new this(tt.fromTemplate(t,e));const n=[];for(const r of t)if(typeof r=="string")n.push(tt.fromTemplate(r,e));else if(r!==null)if(Jh(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const o={...e,additionalContentFields:r};n.push(tt.fromTemplate(s,o))}else if(qh(r)){let s=r.image_url??"",o,i=[];if(typeof s=="string"){let a;e?.templateFormat==="mustache"?a=dr(s):a=wn(s);const l=a.flatMap(c=>c.type==="variable"?[c.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Only one format variable allowed per image template.
22
+ Got: ${l}
23
+ From: ${s}`);i=[l[0]]}else i=[];s={url:s},o=new Kn({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let a;e?.templateFormat==="mustache"?a=dr(s.url):a=wn(s.url),i=a.flatMap(l=>l.type==="variable"?[l.name]:[])}else i=[];o=new Kn({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else throw new Error("Invalid image template");n.push(o)}else typeof r=="object"&&n.push(new ys({template:r,templateFormat:e?.templateFormat}));return new this({prompt:n,additionalOptions:e})}async format(t){if(this.prompt instanceof gn){const e=await this.prompt.format(t);return this.createMessage(e)}else{const e=[];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]:t[s]}),r={...r,[s]:t[s]};if(n instanceof gn){const s=await n.format(r);let o;"additionalContentFields"in n&&(o=n.additionalContentFields),s!==""&&e.push({...o,type:"text",text:s})}else if(n instanceof Kn){const s=await n.format(r);let o;"additionalContentFields"in n&&(o=n.additionalContentFields),e.push({...o,type:"image_url",image_url:s})}else if(n instanceof ys){const s=await n.format(r);let o;"additionalContentFields"in n&&(o=n.additionalContentFields),e.push({...o,...s})}}return this.createMessage(e)}}async formatMessages(t){return[await this.format(t)]}},eo=class extends Qs{static _messageClass(){return ee}static lc_name(){return"HumanMessagePromptTemplate"}},ga=class extends Qs{static _messageClass(){return I}static lc_name(){return"AIMessagePromptTemplate"}},ya=class extends Qs{static _messageClass(){return te}static lc_name(){return"SystemMessagePromptTemplate"}};function Yh(t){return typeof t.formatMessages=="function"}function Xh(t,e){if(Yh(t)||De(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){const s=t[1];if(e?.templateFormat==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}"){const o=s.slice(2,-2);return new bs({variableName:o,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const o=s.slice(1,-1);return new bs({variableName:o,optional:!0})}throw new Error(`Invalid placeholder template for format ${e?.templateFormat??'"f-string"'}: "${t[1]}". Expected a variable name surrounded by ${e?.templateFormat==="mustache"?"double":"single"} curly braces.`)}const n=pn(t);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 eo.fromTemplate(r,e);if(n._getType()==="ai")return ga.fromTemplate(r,e);if(n._getType()==="system")return ya.fromTemplate(r,e);if(yi.isInstance(n))return ma.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function Zh(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var to=class Jn extends Zs{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(e){if(super(e),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){const n=new Set;for(const a of this.promptMessages)if(!(a instanceof cn))for(const l of a.inputVariables)n.add(l);const r=this.inputVariables,s=new Set(this.partialVariables?r.concat(Object.keys(this.partialVariables)):r),o=new Set([...s].filter(a=>!n.has(a)));if(o.size>0)throw new Error(`Input variables \`${[...o]}\` are not used in any of the prompt messages.`);const i=new Set([...n].filter(a=>!s.has(a)));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(e,n){if(typeof e.content=="string")return e;const r=await Promise.all(e.content.map(async s=>{if(s.type!=="image_url")return s;let o="";typeof s.image_url=="string"?o=s.image_url:typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(o=s.image_url.url);const a=await tt.fromTemplate(o,{templateFormat:this.templateFormat}).format(n);return typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url?s.image_url.url=a:s.image_url=a,s}));return e.content=r,e}async formatMessages(e){const n=await this.mergePartialAndUserVariables(e);let r=[];for(const s of this.promptMessages)if(s instanceof cn)r.push(await this._parseImagePrompts(s,n));else{let o;this.templateFormat==="mustache"?o={...n}:o=s.inputVariables.reduce((a,l)=>{if(!(l in n)&&!(Zh(s)&&s.optional))throw gi(new Error(`Missing value for input variable \`${l.toString()}\``),"INVALID_PROMPT_INPUT");return a[l]=n[l],a},{});const i=await s.formatMessages(o);r=r.concat(i)}return r}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new Jn(s)}static fromTemplate(e,n){const r=tt.fromTemplate(e,n),s=new eo({prompt:r});return this.fromMessages([s])}static fromMessages(e,n){const r=e.reduce((i,a)=>i.concat(a instanceof Jn?a.promptMessages:[Xh(a,n)]),[]),s=e.reduce((i,a)=>a instanceof Jn?Object.assign(i,a.partialVariables):i,Object.create(null)),o=new Set;for(const i of r)if(!(i instanceof cn))for(const a of i.inputVariables)a in s||o.add(a);return new this({...n,inputVariables:[...o],promptMessages:r,partialVariables:s,templateFormat:n?.templateFormat})}},Qh=class _s extends gn{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
24
+
25
+ `;prefix="";templateFormat="f-string";validateTemplate=!0;constructor(e){if(super(e),Object.assign(this,e),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))),On(this.prefix+this.suffix,this.templateFormat,n)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new _s(s)}async format(e){const n=await this.mergePartialAndUserVariables(e),r=await this.getExamples(n),s=await Promise.all(r.map(i=>this.examplePrompt.format(i))),o=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return Me(o,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(e){const{example_prompt:n}=e;if(!n)throw new Error("Missing example prompt");const r=await tt.deserialize(n);let s;if(Array.isArray(e.examples))s=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new _s({inputVariables:e.input_variables,examplePrompt:r,examples:s,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},ed=class wa extends Zs{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
26
+
27
+ `;prefix="";templateFormat="f-string";validateTemplate=!0;_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(e){if(super(e),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??`
28
+
29
+ `,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??"",this.suffix=e.suffix??"",this.templateFormat=e.templateFormat??"f-string",this.validateTemplate=e.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))),On(this.prefix+this.suffix,this.templateFormat,n)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){const n=await this.mergePartialAndUserVariables(e);let r=await this.getExamples(n);r=r.map(o=>{const i={};return this.examplePrompt.inputVariables.forEach(a=>{i[a]=o[a]}),i});const s=[];for(const o of r){const i=await this.examplePrompt.formatMessages(o);s.push(...i)}return s}async format(e){const n=await this.mergePartialAndUserVariables(e),r=await this.getExamples(n),o=(await Promise.all(r.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content),i=[this.prefix,...o,this.suffix].join(this.exampleSeparator);return Me(i,this.templateFormat,n)}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new wa(s)}},td=class qn extends Pn{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(e){super({...e,inputVariables:[]}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){const e=this.pipelinePrompts.map(r=>r.name),n=this.pipelinePrompts.map(r=>r.prompt.inputVariables.filter(s=>!e.includes(s))).flat();return[...new Set(n)]}static extractRequiredInputValues(e,n){return n.reduce((r,s)=>(r[s]=e[s],r),{})}async formatPipelinePrompts(e){const n=await this.mergePartialAndUserVariables(e);for(const{name:r,prompt:s}of this.pipelinePrompts){const o=qn.extractRequiredInputValues(n,s.inputVariables);s instanceof to?n[r]=await s.formatMessages(o):n[r]=await s.format(o)}return qn.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(e){const n={...this};return n.inputVariables=this.inputVariables.filter(r=>!(r in e)),n.partialVariables={...this.partialVariables??{},...e},new qn(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function $o(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function nd(t){return typeof t=="object"&&t!=null&&"lc_id"in t&&Array.isArray(t.lc_id)&&t.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var rd=class va extends to{schema;method;lc_namespace=["langchain_core","prompts","structured"];get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(e){super(e),this.schema=e.schema,this.method=e.method}pipe(e){if($o(e))return super.pipe(e.withStructuredOutput(this.schema));if(nd(e)&&$o(e.bound))return super.pipe(new $e({bound:e.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:e.kwargs??{},config:e.config,configFactories:e.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(e,n,r){return va.fromMessages(e,{schema:n,method:r})}},ba={};q(ba,{AIMessagePromptTemplate:()=>ga,BaseChatPromptTemplate:()=>Zs,BaseMessagePromptTemplate:()=>Ar,BaseMessageStringPromptTemplate:()=>pa,BasePromptTemplate:()=>Pn,BaseStringPromptTemplate:()=>gn,ChatMessagePromptTemplate:()=>ma,ChatPromptTemplate:()=>to,DEFAULT_FORMATTER_MAPPING:()=>fr,DEFAULT_PARSER_MAPPING:()=>da,DictPromptTemplate:()=>ys,FewShotChatMessagePromptTemplate:()=>ed,FewShotPromptTemplate:()=>Qh,HumanMessagePromptTemplate:()=>eo,ImagePromptTemplate:()=>Kn,MessagesPlaceholder:()=>bs,PipelinePromptTemplate:()=>td,PromptTemplate:()=>tt,StructuredPrompt:()=>rd,SystemMessagePromptTemplate:()=>ya,checkValidTemplate:()=>On,interpolateFString:()=>ua,interpolateMustache:()=>ha,parseFString:()=>wn,parseMustache:()=>dr,parseTemplate:()=>pr,renderTemplate:()=>Me});var _a={};q(_a,{BaseDocumentCompressor:()=>sd});var sd=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}};const Qe={and:"and",or:"or",not:"not"},L={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var Sa=class{},no=class{accept(t){if(this.exprName==="Operation")return t.visitOperation(this);if(this.exprName==="Comparison")return t.visitComparison(this);if(this.exprName==="StructuredQuery")return t.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},ro=class extends no{},od=class extends ro{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},id=class extends ro{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},ad=class extends no{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function Ca(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Ee(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:Ca(t)&&Object.keys(t).length===0:!0}function Ta(t){if(typeof t=="number")return t%1===0;if(typeof t=="string"){const e=parseInt(t,10);return!Number.isNaN(e)&&e%1===0&&e.toString()===t}return!1}function ka(t){if(typeof t=="number")return t%1!==0;if(typeof t=="string"){const e=parseFloat(t);return!Number.isNaN(e)&&e%1!==0&&e.toString()===t}return!1}function Ea(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function xa(t){return typeof t=="boolean"}function so(t){let e;if(Ea(t))e=t;else if(Ta(t))e=parseInt(t,10);else if(ka(t))e=parseFloat(t);else if(xa(t))e=!!t;else throw new Error("Unsupported value type");return e}var oo=class extends Sa{},ld=class extends oo{allowedOperators;allowedComparators;constructor(t){super(),this.allowedOperators=t?.allowedOperators??[Qe.and,Qe.or],this.allowedComparators=t?.allowedComparators??[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte]}formatFunction(t){if(t in L){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(t)===-1)throw new Error(`Comparator ${t} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(t in Qe){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(t)===-1)throw new Error(`Operator ${t} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${t}`}visitOperation(t){const e=t.args?.map(n=>n.accept(this));return{[this.formatFunction(t.operator)]:e}}visitComparison(t){return{[t.attribute]:{[this.formatFunction(t.comparator)]:so(t.value)}}}visitStructuredQuery(t){let e={};return t.filter&&(e={filter:t.filter.accept(this)}),e}mergeFilters(t,e,n="and",r=!1){if(!(Ee(t)&&Ee(e))){if(Ee(t)||n==="replace")return Ee(e)?void 0:e;if(Ee(e))return r?t:n==="and"?void 0:t;if(n==="and")return{$and:[t,e]};if(n==="or")return{$or:[t,e]};throw new Error("Unknown merge type")}}},cd=class extends oo{allowedOperators=[Qe.and,Qe.or];allowedComparators=[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(t){switch(t){case"string":return[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];case"number":return[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];case"boolean":return[L.eq,L.ne];default:throw new Error(`Unsupported data type: ${t}`)}}getComparatorFunction(t){switch(t){case L.eq:return(e,n)=>e===n;case L.ne:return(e,n)=>e!==n;case L.gt:return(e,n)=>e>n;case L.gte:return(e,n)=>e>=n;case L.lt:return(e,n)=>e<n;case L.lte:return(e,n)=>e<=n;default:throw new Error("Unknown comparator")}}getOperatorFunction(t){switch(t){case Qe.and:return(e,n)=>e&&n;case Qe.or:return(e,n)=>e||n;default:throw new Error("Unknown operator")}}visitOperation(t){const{operator:e,args:n}=t;if(this.allowedOperators.includes(e)){const r=this.getOperatorFunction(e);return s=>n?n.reduce((o,i)=>{const a=i.accept(this);if(typeof a=="function")return r(o,a(s));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(t){const{comparator:e,attribute:n,value:r}=t,s=[L.ne];if(this.allowedComparators.includes(e)){if(!this.getAllowedComparatorsForType(typeof r).includes(e))throw new Error(`'${e}' comparator not allowed to be used with ${typeof r}`);const o=this.getComparatorFunction(e);return i=>{const a=i.metadata[n];return a===void 0?!!s.includes(e):o(a,so(r))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(t){if(!t.filter)return{};const e=t.filter?.accept(this);if(typeof e!="function")throw new Error("Structured query filter is not a function");return{filter:e}}mergeFilters(t,e,n="and"){if(!(Ee(t)&&Ee(e))){if(Ee(t)||n==="replace")return Ee(e)?void 0:e;if(Ee(e))return n==="and"?void 0:t;if(n==="and")return r=>t(r)&&e(r);if(n==="or")return r=>t(r)||e(r);throw new Error("Unknown merge type")}}},Ma={};q(Ma,{BaseTranslator:()=>oo,BasicTranslator:()=>ld,Comparators:()=>L,Comparison:()=>od,Expression:()=>no,FilterDirective:()=>ro,FunctionalTranslator:()=>cd,Operation:()=>id,Operators:()=>Qe,StructuredQuery:()=>ad,Visitor:()=>Sa,castValue:()=>so,isBoolean:()=>xa,isFilterEmpty:()=>Ee,isFloat:()=>ka,isInt:()=>Ta,isObject:()=>Ca,isString:()=>Ea});var Aa={};q(Aa,{RunCollectorCallbackHandler:()=>ud});var ud=class extends Us{name="run_collector";exampleId;tracedRuns;constructor({exampleId:t}={}){super({_awaitHandler:!0}),this.exampleId=t,this.tracedRuns=[]}async persistRun(t){const e={...t};e.reference_example_id=this.exampleId,this.tracedRuns.push(e)}},hd={},Pa={};q(Pa,{context:()=>Ia});function Ia(t,...e){const n=t.raw;let r="";for(let s=0;s<n.length;s++){const o=n[s].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(r+=o,s<e.length){const i=dd(e[s],r);r+=typeof i=="string"?i:JSON.stringify(i)}}return r=fd(r),r=r.trim(),r=r.replace(/\\n/g,`
30
+ `),r}function dd(t,e){if(typeof t!="string"||!t.includes(`
31
+ `))return t;const r=e.slice(e.lastIndexOf(`
32
+ `)+1).match(/^(\s+)/);if(r){const s=r[1];return t.replace(/\n/g,`
33
+ ${s}`)}return t}function fd(t){const e=t.split(`
34
+ `);let n=null;for(const r of e){const s=r.match(/^(\s+)\S+/);if(s){const o=s[1].length;n===null?n=o:n=Math.min(n,o)}}return n===null?t:e.map(r=>r[0]===" "||r[0]===" "?r.slice(n):r).join(`
35
+ `)}var Oa={};q(Oa,{EventStreamContentType:()=>pd,convertEventStreamToIterableReadableDataStream:()=>gd,getBytes:()=>Na,getLines:()=>$a,getMessages:()=>Ra});const pd="text/event-stream";async function Na(t,e){if(t instanceof ReadableStream){const n=t.getReader();for(;;){const r=await n.read();if(r.done){e(new Uint8Array,!0);break}e(r.value)}}else try{for await(const n of t)e(new Uint8Array(n));e(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(`
36
+ `))}}var xt=(function(t){return t[t.NewLine=10]="NewLine",t[t.CarriageReturn=13]="CarriageReturn",t[t.Space=32]="Space",t[t.Colon=58]="Colon",t})(xt||{});function $a(t){let e,n,r,s=!1;return function(i,a){if(a){t(i,0,!0);return}e===void 0?(e=i,n=0,r=-1):e=md(e,i);const l=e.length;let c=0;for(;n<l;){s&&(e[n]===xt.NewLine&&(c=++n),s=!1);let u=-1;for(;n<l&&u===-1;++n)switch(e[n]){case xt.Colon:r===-1&&(r=n-c);break;case xt.CarriageReturn:s=!0;case xt.NewLine:u=n;break}if(u===-1)break;t(e.subarray(c,u),r),c=n,r=-1}c===l?e=void 0:c!==0&&(e=e.subarray(c),n-=c)}}function Ra(t,e,n){let r=zr();const s=new TextDecoder;return function(i,a,l){if(l){yd(r)||(t?.(r),r=zr());return}if(i.length===0)t?.(r),r=zr();else if(a>0){const c=s.decode(i.subarray(0,a)),u=a+(i[a+1]===xt.Space?2:1),h=s.decode(i.subarray(u));switch(c){case"data":r.data=r.data?r.data+`
37
+ `+h:h;break;case"event":r.event=h;break;case"id":e?.(r.id=h);break;case"retry":{const d=parseInt(h,10);Number.isNaN(d)||n?.(r.retry=d);break}}}}}function md(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function zr(){return{data:"",event:"",id:"",retry:void 0}}function gd(t,e){const n=new ReadableStream({async start(r){const s=Ra(i=>{if(i.event==="error")throw new Error(i.data??"Unspecified event streaming error.");i.event==="metadata"?e?.(i):i.data&&r.enqueue(i.data)});await Na(t,$a((i,a,l)=>{s(i,a,l),l&&r.close()}))}});return fn.fromReadableStream(n)}function yd(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var wd={};function ja(t,e){let n=0,r=0,s=0;for(let o=0;o<t.length;o++)n+=t[o]*e[o],r+=t[o]*t[o],s+=e[o]*e[o];return n/(Math.sqrt(r)*Math.sqrt(s))}function vd(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function bd(t,e){let n=0;for(let r=0;r<t.length;r++)n+=(t[r]-e[r])*(t[r]-e[r]);return n}function _d(t,e){return Math.sqrt(bd(t,e))}var La={};q(La,{cosineSimilarity:()=>Ss,euclideanDistance:()=>Td,innerProduct:()=>Cd,matrixFunc:()=>Pr,maximalMarginalRelevance:()=>kd,normalize:()=>Sd});function Pr(t,e,n){if(t.length===0||t[0].length===0||e.length===0||e[0].length===0)return[[]];if(t[0].length!==e[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[t.length,t[0].length]} and Y has shape ${[e.length,e[0].length]}.`);return t.map(r=>e.map(s=>n(r,s)).map(s=>Number.isNaN(s)?0:s))}function Sd(t,e=!1){const n=Ed(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function Ss(t,e){return Pr(t,e,ja)}function Cd(t,e){return Pr(t,e,vd)}function Td(t,e){return Pr(t,e,_d)}function kd(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(t[0])?t:[t],o=Ss(s,e)[0],i=Da(o).maxIndex,a=[e[i]],l=[i];for(;l.length<Math.min(r,e.length);){let c=-1/0,u=-1;const h=Ss(e,a);o.forEach((d,f)=>{if(l.includes(f))return;const p=Math.max(...h[f]),m=n*d-(1-n)*p;m>c&&(c=m,u=f)}),a.push(e[u]),l.push(u)}return l}function Da(t){if(t.length===0)return{maxIndex:-1,maxValue:NaN};let e=t[0],n=0;for(let r=1;r<t.length;r+=1)t[r]>e&&(n=r,e=t[r]);return{maxIndex:n,maxValue:e}}function Ed(t){return t.reduce((e,n)=>Math.max(e,Da(n).maxValue),0)}var xd=class extends xn{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,n){if(e?.stop?.length)return{generations:[{message:new I(e.stop[0]),text:e.stop[0]}]};const r=t.map(s=>typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2)).join(`
38
+ `);return await n?.handleLLMNewToken(r),{generations:[{message:new I(r),text:r}],llmOutput:{}}}},Md=class Fa extends xn{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:e=50,responses:n=[],chunks:r=[],toolStyle:s="openai",thrownErrorString:o,...i}){super(i),this.sleep=e,this.responses=n,this.chunks=r,this.toolStyle=s,this.thrownErrorString=o}_llmType(){return"fake"}bindTools(e){const n=[...this.tools,...e],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:xe(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:xe(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:xe(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:xe(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new Fa({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return o.tools=n,o.withConfig({tools:s})}async _generate(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const s=this.responses?.[0]?.content??e[0].content??"";return{generations:[{text:"",message:new I({content:s,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const i of this.chunks){const a=new ls({message:new Gt({content:i.content,tool_calls:i.tool_calls,additional_kwargs:i.additional_kwargs??{}}),text:i.content?.toString()??""});if(n.signal?.aborted)break;yield a,await r?.handleLLMNewToken(i.content,void 0,void 0,void 0,void 0,{chunk:a})}return}const s=this.responses?.[0]??new I(typeof e[0].content=="string"?e[0].content:""),o=typeof s.content=="string"?s.content:"";for(const i of o){await new Promise(l=>setTimeout(l,this.sleep));const a=new ls({message:new Gt({content:i}),text:i});if(n.signal?.aborted)break;yield a,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:a})}}},Ad=class Ua extends xn{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(e){super(e);const{responses:n,sleep:r,emitCustomEvent:s,generationInfo:o}=e;this.responses=n,this.sleep=r,this.emitCustomEvent=s??this.emitCustomEvent,this.generationInfo=o}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(e,n,r){if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);if(this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0}),n?.stop?.length)return{generations:[this._formatGeneration(n.stop[0])]};{const s=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(s)],llmOutput:{}}}}_formatGeneration(e){return{message:new I(e),text:e}}async*_streamResponseChunks(e,n,r){const s=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0});const o=[...s];for(let i=0;i<o.length;i++){const a=o[i],l=i===o.length-1;if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);const c=this._createResponseChunk(a,l?this.generationInfo:void 0);if(n.signal?.aborted)break;yield c,r?.handleLLMNewToken(a)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,n){return new ls({message:new Gt({content:e}),text:e,generationInfo:n})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(e){const n=[...this.tools,...e],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:xe(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:xe(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:xe(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:xe(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new Ua({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return o.tools=n,o.toolStyle=this.toolStyle,o.i=this.i,o.withConfig({tools:s})}withStructuredOutput(e,n){return lr.from(async r=>{const s=await this.invoke(r);if(s.tool_calls?.[0]?.args)return s.tool_calls[0].args;if(typeof s.content=="string")return JSON.parse(s.content);throw new Error("No structured output found")})}},Pd=class extends bi{vectorSize;constructor(t){super(t??{}),this.vectorSize=t?.vectorSize??4}async embedDocuments(t){return Promise.all(t.map(e=>this.embedQuery(e)))}async embedQuery(t){let e=t;e=e.toLowerCase().replaceAll(/[^a-z ]/g,"");const n=e.length%this.vectorSize,r=n===0?0:this.vectorSize-n,s=e.length+r;e=e.padEnd(s," ");const o=e.length/this.vectorSize,i=[];for(let l=0;l<e.length;l+=o)i.push(e.slice(l,l+o));return i.map(l=>{let c=0;for(let h=0;h<l.length;h+=1)c+=l===" "?0:l.charCodeAt(h);return c%26/26})}},Id=class extends bi{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},Od=class extends _i{response;thrownErrorString;constructor(t){super(t),this.response=t.response,this.thrownErrorString=t.thrownErrorString}_llmType(){return"fake"}async _call(t,e,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.response??t;return await n?.handleLLMNewToken(r),r}},Nd=class extends _i{sleep=50;responses;thrownErrorString;constructor(t){super(t),this.sleep=t.sleep??this.sleep,this.responses=t.responses,this.thrownErrorString=t.thrownErrorString}_llmType(){return"fake"}async _call(t){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const e=this.responses?.[0];return this.responses=this.responses?.slice(1),e??t}async*_streamResponseChunks(t,e,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??t)await new Promise(o=>setTimeout(o,this.sleep)),yield{text:s,generationInfo:{}},await n?.handleLLMNewToken(s)}},$d=class extends ji{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async addUserMessage(t){this.messages.push(new ee(t))}async addAIMessage(t){this.messages.push(new I(t))}async clear(){this.messages=[]}},Rd=class extends Ks{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},jd=class extends Us{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},Ld=class extends kc{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},Dd=class extends Js{lc_namespace=["test","fake"];output=[new We({pageContent:"foo"}),new We({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},Fd=class extends re{lc_namespace=["tests","fake"];returnOptions;constructor(t){super(t),this.returnOptions=t.returnOptions}async invoke(t,e){return this.returnOptions?e??{}:{input:t}}},Ud=class extends Er{name;description;schema;constructor(t){super(t),this.name=t.name,this.description=t.description,this.schema=t.schema}async _call(t,e){return JSON.stringify(t)}},Vd=class extends Us{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(t=>{this.runPromiseResolver=t})}async persistRun(t){this.runPromiseResolver(t)}async extract(){return this.runPromise}},Bd=class Va extends qs{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??ja}async addDocuments(e){const n=e.map(({pageContent:r})=>r);return this.addVectors(await this.embeddings.embedDocuments(n),e)}async addVectors(e,n){const r=e.map((s,o)=>({content:n[o].pageContent,embedding:s,metadata:n[o].metadata}));this.memoryVectors=this.memoryVectors.concat(r)}async similaritySearchVectorWithScore(e,n,r){const s=l=>{if(!r)return!0;const c=new We({metadata:l.metadata,pageContent:l.content});return r(c)},o=this.memoryVectors.filter(s);return o.map((l,c)=>({similarity:this.similarity(e,l.embedding),index:c})).sort((l,c)=>l.similarity>c.similarity?-1:0).slice(0,n).map(l=>[new We({metadata:o[l.index].metadata,pageContent:o[l.index].content}),l.similarity])}static async fromTexts(e,n,r,s){const o=[];for(let i=0;i<e.length;i+=1){const a=Array.isArray(n)?n[i]:n,l=new We({pageContent:e[i],metadata:a});o.push(l)}return Va.fromDocuments(o,r,s)}static async fromDocuments(e,n,r){const s=new this(n,r);return await s.addDocuments(e),s}static async fromExistingIndex(e,n){return new this(e,n)}},Ba={};q(Ba,{FakeChatMessageHistory:()=>$d,FakeChatModel:()=>xd,FakeEmbeddings:()=>Id,FakeLLM:()=>Od,FakeListChatMessageHistory:()=>Rd,FakeListChatModel:()=>Ad,FakeRetriever:()=>Dd,FakeRunnable:()=>Fd,FakeSplitIntoListParser:()=>Ld,FakeStreamingChatModel:()=>Md,FakeStreamingLLM:()=>Nd,FakeTool:()=>Ud,FakeTracer:()=>jd,FakeVectorStore:()=>Bd,SingleRunExtractor:()=>Vd,SyntheticEmbeddings:()=>Pd});var za={};q(za,{agents:()=>dh,caches:()=>jc,callbacks__base:()=>au,callbacks__manager:()=>iu,callbacks__promises:()=>ou,chat_history:()=>Ri,document_loaders__base:()=>Wi,document_loaders__langsmith:()=>Gi,documents:()=>Ji,embeddings:()=>Nu,example_selectors:()=>Zi,index:()=>ph,indexing:()=>sa,language_models__base:()=>Rc,language_models__chat_models:()=>$c,language_models__llms:()=>Ru,language_models__profile:()=>Ph,load__serializable:()=>su,memory:()=>Li,messages:()=>ru,messages__tool:()=>nu,output_parsers:()=>Nc,output_parsers__openai_functions:()=>aa,output_parsers__openai_tools:()=>$u,outputs:()=>tu,prompt_values:()=>Oc,prompts:()=>ba,retrievers:()=>Bi,retrievers__document_compressors:()=>_a,runnables:()=>Ic,runnables__graph:()=>eu,singletons:()=>Qc,stores:()=>Fi,structured_query:()=>Ma,tools:()=>yc,tracers__base:()=>Zc,tracers__console:()=>Xc,tracers__log_stream:()=>Yc,tracers__run_collector:()=>Aa,tracers__tracer_langchain:()=>qc,types__stream:()=>hd,utils__async_caller:()=>Jc,utils__chunk_array:()=>Ou,utils__context:()=>Pa,utils__env:()=>Kc,utils__event_source_parse:()=>Oa,utils__format:()=>wd,utils__function_calling:()=>Pc,utils__hash:()=>Ac,utils__json_patch:()=>Mc,utils__json_schema:()=>Gc,utils__math:()=>La,utils__stream:()=>Hc,utils__testing:()=>Ba,utils__tiktoken:()=>xc,utils__types:()=>Ec,vectorstores:()=>zi});const zd=50;function Wd(t){const e={};for(let n=t;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(e,Reflect.get(n.prototype,"lc_aliases"));return Object.entries(e).reduce((n,[r,s])=>(n[s]=r,n),{})}async function Yn(t){const{optionalImportsMap:e,optionalImportEntrypoints:n,importMap:r,secretsMap:s,secretsFromEnv:o,path:i,depth:a,maxDepth:l}=this,c=i.join(".");if(a>l)throw new Error(`Maximum recursion depth (${l}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof t!="object"||t==null)return t;if(Array.isArray(t))return Promise.all(t.map((d,f)=>Yn.call({...this,path:[...i,`${f}`],depth:a+1},d)));const u=t;if(lu(u))return cu(u);if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="secret"){const d=u,[f]=d.id;if(f in s)return s[f];if(o){const p=uu(f);if(p)return p}throw new Error(`Missing secret "${f}" at ${c}`)}if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="not_implemented"){const f=JSON.stringify(u);throw new Error(`Trying to load an object that doesn't implement serialization: ${c} -> ${f}`)}if("lc"in u&&"type"in u&&"id"in u&&"kwargs"in u&&u.lc===1&&u.type==="constructor"){const d=u,f=JSON.stringify(d),[p,...m]=d.id.slice().reverse(),S=m.reverse(),C={langchain_core:za,langchain:r};let E=null;const b=[S.join("/")];S[0]==="langchain_community"&&b.push(["langchain",...S.slice(1)].join("/"));const w=b.find(v=>v in e);if(hh.concat(n).includes(S.join("/"))||w)if(w!==void 0)E=await e[w];else throw new Error(`Missing key "${S.join("/")}" for ${c} in load(optionalImportsMap={})`);else{let v;if(S[0]==="langchain"||S[0]==="langchain_core")v=C[S[0]],S.shift();else throw new Error(`Invalid namespace: ${c} -> ${f}`);if(S.length===0)throw new Error(`Invalid namespace: ${c} -> ${f}`);let x;do{if(x=S.join("__"),x in v)break;S.pop()}while(S.length>0);x in v&&(E=v[x])}if(typeof E!="object"||E===null)throw new Error(`Invalid namespace: ${c} -> ${f}`);const g=E[p]??Object.values(E).find(v=>typeof v=="function"&&hu(v)===p);if(typeof g!="function")throw new Error(`Invalid identifer: ${c} -> ${f}`);const k=await Yn.call({...this,path:[...i,"kwargs"],depth:a+1},d.kwargs),_=new g(du(k,fu,Wd(g)));return Object.defineProperty(_.constructor,"name",{value:p}),_}const h={};for(const[d,f]of Object.entries(u))h[d]=await Yn.call({...this,path:[...i,d],depth:a+1},f);return h}async function Hd(t,e){const n=JSON.parse(t),r={optionalImportsMap:{},optionalImportEntrypoints:[],secretsMap:{},secretsFromEnv:!1,importMap:{},path:["$"],depth:0,maxDepth:zd};return Yn.call(r,n)}function Gd(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function Cs(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>Cs(n)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await Cs(r);if(e.lc===2&&e.type==="undefined")return;if(e.lc===2&&e.type==="constructor"&&Array.isArray(e.id))try{const n=e.id[e.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 e}return e.method?r[e.method](...e.args||[]):new r(...e.args||[])}catch{return e}else if(Gd(e))return Hd(JSON.stringify(e));return e}}return t}function Wr(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function Kd(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?Wr(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?Wr(RegExp,void 0,[t.source,t.flags]):t instanceof Error?Wr(t.constructor,void 0,[t.message]):t?.lg_name==="Send"?{node:t.node,args:t.args}:t}var Jd=class{_dumps(t){return new TextEncoder().encode(ch(t,(n,r)=>Kd(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return Cs(e)}async loadsTyped(t,e){if(t==="bytes")return typeof e=="string"?new TextEncoder().encode(e):e;if(t==="json")return this._loads(typeof e=="string"?e:new TextDecoder().decode(e));throw new Error(`Unknown serialization type: ${t}`)}};function Wa(t){if(typeof t!="object"||t===null)return t;const e=Array.isArray(t)?[]:{};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=Wa(t[n]));return e}function Ha(){return{v:4,id:$i(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function mr(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:Wa(t.versions_seen)}}function Ga(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function qd(...t){return t.reduce((e,n,r)=>r===0?n:Ga(e,n)>=0?e:n)}const Yd={[sh]:-1,[Hn]:-2,[oh]:-3,[ih]:-4};var rn=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function Xd(t){if(t.length===0)throw new rn("Namespace cannot be empty.");for(const e of t){if(typeof e!="string")throw new rn(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new rn(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new rn(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new rn(`Root label for namespace cannot be "langgraph". Got: ${t}`)}var Zd=class{async get(t,e){return(await this.batch([{namespace:t,key:e}]))[0]}async search(t,e={}){const{filter:n,limit:r=10,offset:s=0,query:o}=e;return(await this.batch([{namespacePrefix:t,filter:n,limit:r,offset:s,query:o}]))[0]}async put(t,e,n,r){Xd(t),await this.batch([{namespace:t,key:e,value:n,index:r}])}async delete(t,e){await this.batch([{namespace:t,key:e,value:null}])}async listNamespaces(t={}){const{prefix:e,suffix:n,maxDepth:r,limit:s=100,offset:o=0}=t,i=[];return e&&i.push({matchType:"prefix",path:e}),n&&i.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:i.length?i:void 0,maxDepth:r,limit:s,offset:o}]))[0]}start(){}stop(){}};const Qd=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var ef=class extends Zd{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=Qd(t)}get isRunning(){return this.running}async batch(t){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(t,e){return this.enqueueOperation({namespace:t,key:e})}async search(t,e){const{filter:n,limit:r=10,offset:s=0,query:o}=e||{};return this.enqueueOperation({namespacePrefix:t,filter:n,limit:r,offset:s,query:o})}async put(t,e,n){return this.enqueueOperation({namespace:t,key:e,value:n})}async delete(t,e){return this.enqueueOperation({namespace:t,key:e,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(t){return new Promise((e,n)=>{const r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:t,resolve:e,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(e=>{setTimeout(e,0)}),this.queue.size===0)continue;const t=new Map(this.queue);this.queue.clear();try{const e=Array.from(t.values()).map(({operation:r})=>r),n=await this.store.batch(e);t.forEach(({resolve:r},s)=>{const o=Array.from(t.keys()).indexOf(s);r(n[o])})}catch(e){t.forEach(({reject:n})=>{n(e)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},tf=class{serde=new Jd;constructor(t){this.serde=t||this.serde}},nf=class Ka extends xn{toolCalls;toolStyle;indexRef;structuredResponse;tools=[];constructor({toolCalls:e=[],toolStyle:n="openai",index:r=0,structuredResponse:s,indexRef:o,...i}={}){super(i),this.toolCalls=e,this.toolStyle=n,this.indexRef=o??{current:r},this.structuredResponse=s}get index(){return this.indexRef.current}set index(e){this.indexRef.current=e}_llmType(){return"fake-tool-calling"}_combineLLMOutput(){return[]}bindTools(e){const n=new Ka({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...e],n}withStructuredOutput(e){return new lr({func:async()=>this.structuredResponse})}async _generate(e,n,r){let o=e[e.length-1].content;e.length>1&&(o=e.map(h=>h.content).filter(Boolean).map(h=>typeof h=="string"?h:typeof h=="object"&&"text"in h?h.text:Array.isArray(h)?h.map(d=>typeof d=="string"?d:typeof d=="object"&&"text"in d?d.text:"").join("-"):JSON.stringify(h)).join("-")),(e.length===1||e.length===2&&e.every(ee.isInstance))&&this.index!==0&&(this.index=0);const a=this.toolCalls[this.index]||[],l=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);const c=new I({content:o,id:l,tool_calls:a.length>0?a.map(u=>({...u,type:"tool_call"})):void 0});return{generations:[{text:o,message:c}],llmOutput:{}}}};class rf{constructor(){this.store=void 0}getStore(){return this.store}run(e,n,...r){this.store=e;try{return n(...r)}finally{this.store=void 0}}exit(e,...n){const r=this.store;this.store=void 0;try{return e(...n)}finally{this.store=r}}enterWith(e){this.store=e}disable(){this.store=void 0}}function sf(){ze.initializeGlobalInstance(new rf)}var vt=class extends Error{lc_error_code;constructor(t,e){let n=t??"";e?.lc_error_code&&(n=`${n}
39
+
40
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${e.lc_error_code}/
41
+ `),super(n),this.lc_error_code=e?.lc_error_code}},Ja=class extends vt{get is_bubble_up(){return!0}},of=class extends vt{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},Xn=class extends vt{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},At=class extends Ja{interrupts;constructor(t,e){super(JSON.stringify(t,null,2),e),this.name="GraphInterrupt",this.interrupts=t??[]}static get unminifiable_name(){return"GraphInterrupt"}},qa=class extends At{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},Ya=class extends Ja{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function af(t){return t!==void 0&&t.name===Ya.unminifiable_name}function Zn(t){return t!==void 0&&t.is_bubble_up===!0}function ht(t){return t!==void 0&&[At.unminifiable_name,qa.unminifiable_name].includes(t.name)}var Ro=class extends vt{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},ne=class extends vt{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},z=class extends vt{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},lf=class extends vt{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function Xa(t){return t!=null&&t.lg_is_channel===!0}var bt=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===ne.unminifiable_name)return!1;throw t}}};const Ts=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function io(t){if(t[Ts]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];Xa(r)&&(e[n]=r)}return Object.assign(e,{[Ts]:!0}),e}function gr(t,e){const n=io(t),r={};for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=e.channel_values[s];r[s]=n[s].fromCheckpoint(o)}return Object.assign(r,{[Ts]:!0}),r}function ct(t,e,n,r){let s;if(e===void 0)s=t.channel_values;else{s={};for(const o in e)if(Object.prototype.hasOwnProperty.call(e,o))try{s[o]=e[o].checkpoint()}catch(i){if(i.name!==ne.unminifiable_name)throw i}}return{v:4,id:r?.id??$i(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}var ks=class Za extends bt{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(e,n){super(),this.operator=e,this.initialValueFactory=n,this.value=n?.()}fromCheckpoint(e){const n=new Za(this.operator,this.initialValueFactory);return typeof e<"u"&&(n.value=e),n}update(e){let n=e;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 ne;return this.value}checkpoint(){if(this.value===void 0)throw new ne;return this.value}isAvailable(){return this.value!==void 0}},ao=class Qa extends bt{lc_graph_name="LastValue";value=[];fromCheckpoint(e){const n=new Qa;return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new z("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new ne;return this.value[0]}checkpoint(){if(this.value.length===0)throw new ne;return this.value[0]}isAvailable(){return this.value.length!==0}},cf=class el extends bt{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new el;if(typeof e<"u"){const[r,s]=e;n.value=[r],n.finished=s}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new ne;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}},uf=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}};const Es=function(t){return t?xs(t):new ao};Es.Root=t=>new uf(t);function xs(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new ks(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new ks(t.value,t.default):new ao}const F="__start__",O="__end__",Fe="__input__",hf="__copy__",he="__error__",Hr="__pregel_ns_writes",nt="__pregel_send",lo="__pregel_call",pt="__pregel_read",K="__pregel_checkpointer",qe="__pregel_resuming",hn="__pregel_task_id",yr="__pregel_stream",df="__pregel_resume_value",Qn="__pregel_resume_map",rt="__pregel_scratchpad",er="__pregel_previous",tl="__pregel_durability",Ms="checkpoint_id",Ne="checkpoint_ns",ff="__pregel_node_finished",we="checkpoint_map",jo="__pregel_abort_signals",D="__interrupt__",de="__resume__",co="__no_writes__",Yt="__return__",Gr="__previous__",J="langsmith:hidden",pf="langsmith:nostream",Lo="__self__",be="__pregel_tasks",me="__pregel_push",tr="__pregel_pull",_e="00000000-0000-0000-0000-000000000000",mf=[J,Fe,D,de,he,co,nt,pt,K,tl,yr,qe,hn,lo,df,rt,er,we,Ne,Ms],Y="|",He=":",Do=Symbol.for("langgraph.command");var gf=class{[Do];constructor(t){this[Do]=t}};function As(t){const e=t;return e!=null&&typeof e.node=="string"&&e.args!==void 0}var le=class{lg_name="Send";node;args;constructor(t,e){this.node=t,this.args=vn(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function ye(t){return t instanceof le}function nl(t){return!t||typeof t!="object"||!(D in t)?!1:Array.isArray(t[D])}var G=class extends gf{lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(t){super(t),this.resume=t.resume,this.graph=t.graph,this.update=t.update,t.goto&&(this.goto=Array.isArray(t.goto)?vn(t.goto):[vn(t.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let t;return typeof this.goto=="string"?t=this.goto:ye(this.goto)?t=this.goto.toJSON():t=this.goto?.map(e=>typeof e=="string"?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:t}}};function Z(t){return typeof t!="object"||t==null?!1:"lg_name"in t&&t.lg_name==="Command"}function vn(t,e=new Map){if(t!=null&&typeof t=="object"){if(e.has(t))return e.get(t);let n;if(Array.isArray(t))n=[],e.set(t,n),t.forEach((r,s)=>{n[s]=vn(r,e)});else if(Z(t)&&!(t instanceof G))n=new G(t),e.set(t,n);else if(As(t)&&!(t instanceof le))n=new le(t.node,t.args),e.set(t,n);else if(Z(t)||ye(t))n=t,e.set(t,n);else if("lc_serializable"in t&&t.lc_serializable)n=t,e.set(t,n);else{n={},e.set(t,n);for(const[r,s]of Object.entries(t))n[r]=vn(s,e)}return n}return t}const yf=["tags","metadata","callbacks","configurable"],wf=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],vf=25;function rl(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:vf,configurable:{}},n=ze.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(yf.includes(r)){let o;Array.isArray(s)?o=[...s]:typeof s=="object"?r==="callbacks"&&"copy"in s&&typeof s.copy=="function"?o=s.copy():o={...s}:o=s,e[r]=o}else e[r]=s}for(const r of t)if(r!==void 0)for(const[s,o]of Object.entries(r))o!==void 0&&wf.includes(s)&&(e[s]=o);for(const[r,s]of Object.entries(e.configurable))e.metadata=e.metadata??{},!r.startsWith("__")&&(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&!(r in e.metadata)&&(e.metadata[r]=s);return e}function bf(){return ze.getRunnableConfig()}function Kr(t){return t.split(Y).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(He)[0]).join(Y)}function _f(t){const e=t.split(Y);for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join(Y)}const A=t=>BigInt(t),U=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),sl=A("0x9E3779B1"),ol=A("0x85EBCA77"),Sf=A("0xC2B2AE3D"),ot=A("0x9E3779B185EBCA87"),gt=A("0xC2B2AE3D27D4EB4F"),il=A("0x165667B19E3779F9"),uo=A("0x85EBCA77C2B2AE63"),Cf=A("0x27D4EB2F165667C5"),Tf=A("0x165667919E3779F9"),kf=A("0x9FB21C651E98DF25"),Ef=t=>{const e=t.length;if(e%2!==0)throw new Error("String should have an even number of characters");const n=e/2,r=new Uint8Array(n);let s=0,o=0;for(;o<n;){const i=t.slice(s,s+=2);r[o]=Number.parseInt(i,16),o+=1}return U(r)},Oe=Ef("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Pt=(A(1)<<A(128))-A(1),R=(A(1)<<A(64))-A(1),wr=(A(1)<<A(32))-A(1),Ue=64,al=Ue/8,xf=8,Rn=4;function Xt(t){if(!t)throw new Error("Assert failed")}function Mf(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Af(t){let e=t;return e=(e&A(65535))<<A(16)|(e&A(4294901760))>>A(16),e=(e&A(16711935))<<A(8)|(e&A(4278255360))>>A(8),e}function Pf(t,e){return(t&wr)*(e&wr)&R}function If(t,e){return(t<<e|t>>A(32)-e)&wr}function ll(t,e,n){for(let r=0;r<al;r+=1){const s=e.getBigUint64(r*8,!0),o=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Pf(o,o>>A(32))}return t}function Fo(t,e,n,r){for(let s=0;s<r;s+=1)ll(t,U(e,s*Ue),U(n,s*8));return t}function Of(t,e){for(let n=0;n<al;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=Ps(s,A(47)),s^=r,s*=sl,t[n]=s&R}return t}function jn(t,e){return cl(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(xf,!0))}function Uo(t,e,n){let r=n;return r+=jn(t.slice(0),U(e,0*Rn)),r+=jn(t.slice(2),U(e,4*Rn)),r+=jn(t.slice(4),U(e,8*Rn)),r+=jn(t.slice(6),U(e,12*Rn)),je(r&R)}function Nf(t,e,n,r,s){let o=t;const i=Math.floor((n.byteLength-Ue)/8),a=Ue*i,l=Math.floor((e.byteLength-1)/a);for(let c=0;c<l;c+=1)o=Fo(o,U(e,c*a),n,i),o=s(o,U(n,n.byteLength-Ue));{const c=Math.floor((e.byteLength-1-a*l)/Ue);o=Fo(o,U(e,l*a),n,c),o=r(o,U(e,e.byteLength-Ue),U(n,n.byteLength-Ue-7))}return o}function $f(t,e){let n=new BigUint64Array([Sf,ot,gt,il,uo,ol,Cf,sl]);Xt(t.byteLength>128),n=Nf(n,t,e,ll,Of),Xt(n.length*8===64);{const r=Uo(n,U(e,11),A(t.byteLength)*ot&R);return Uo(n,U(e,e.byteLength-Ue-11),~(A(t.byteLength)*gt)&R)<<A(64)|r}}function cl(t,e){const n=t*e&Pt;return n&R^n>>A(64)}function Vo(t,e,n){return cl((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&R,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&R)}function nr(t,e,n,r,s){let o=t&R,i=t>>A(64)&R;return o+=Vo(e,r,s),o^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),o&=R,i+=Vo(n,U(r,16),s),i^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),i&=R,i<<A(64)|o}function je(t){let e=t;return e^=e>>A(37),e*=Tf,e&=R,e^=e>>A(32),e}function vr(t){let e=t;return e^=e>>A(33),e*=gt,e&=R,e^=e>>A(29),e*=il,e&=R,e^=e>>A(32),e}function Rf(t,e,n){const r=t.byteLength;Xt(r>0&&r<=3);const s=A(t.getUint8(r-1))|A(r<<8)|A(t.getUint8(0)<<16)|A(t.getUint8(r>>1)<<24),o=(A(e.getUint32(0,!0))^A(e.getUint32(4,!0)))+n,i=(s^o)&R,a=(A(e.getUint32(8,!0))^A(e.getUint32(12,!0)))-n,l=(If(Af(s),A(13))^a)&R;return(vr(l)&R)<<A(64)|vr(i)}function Ps(t,e){return t^t>>e}function jf(t,e,n){const r=t.byteLength;Xt(r>=4&&r<=8);{const s=t.getUint32(0,!0),o=t.getUint32(r-4,!0),i=A(s)|A(o)<<A(32),a=(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&R;let c=(i^a)*(ot+(A(r)<<A(2)))&Pt;return c+=(c&R)<<A(65),c&=Pt,c^=c>>A(67),Ps(Ps(c&R,A(35))*kf&R,A(28))|je(c>>A(64))<<A(64)}}function Lf(t,e,n){const r=t.byteLength;Xt(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&R,o=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&R,i=t.getBigUint64(0,!0);let a=t.getBigUint64(r-8,!0),l=(i^a^s)*ot;const c=(l&R)+(A(r-1)<<A(54));l=l&(Pt^R)|c,a^=o,l+=a+(a&wr)*(ol-A(1))<<A(64),l&=Pt,l^=Mf(l>>A(64));let u=(l&R)*gt;return u+=(l>>A(64))*gt<<A(64),u&=Pt,je(u&R)|je(u>>A(64))<<A(64)}}function Df(t,e){const n=t.byteLength;return Xt(n<=16),n>8?Lf(t,Oe,e):n>=4?jf(t,Oe,e):n>0?Rf(t,Oe,e):vr(e^Oe.getBigUint64(64,!0)^Oe.getBigUint64(72,!0))|vr(e^Oe.getBigUint64(80,!0)^Oe.getBigUint64(88,!0))<<A(64)}function Is(t){return~t+A(1)&R}function Ff(t,e,n){let r=A(t.byteLength)*ot&R,s=A(t.byteLength-1)/A(32);for(;s>=0;){const a=Number(s);r=nr(r,U(t,16*a),U(t,t.byteLength-16*(a+1)),U(e,32*a),n),s-=A(1)}let o=r+(r>>A(64))&R;o=je(o);let i=(r&R)*ot+(r>>A(64))*uo+(A(t.byteLength)-n&R)*gt;return i&=R,i=Is(je(i)),o|i<<A(64)}function Uf(t,e,n){let r=A(t.byteLength)*ot&R;for(let i=32;i<160;i+=32)r=nr(r,U(t,i-32),U(t,i-16),U(e,i-32),n);r=je(r&R)|je(r>>A(64))<<A(64);for(let i=160;i<=t.byteLength;i+=32)r=nr(r,U(t,i-32),U(t,i-16),U(e,3+i-160),n);r=nr(r,U(t,t.byteLength-16),U(t,t.byteLength-32),U(e,103),Is(n));let s=r+(r>>A(64))&R;s=je(s);let o=(r&R)*ot+(r>>A(64))*uo+(A(t.byteLength)-n&R)*gt;return o&=R,o=Is(je(o)),s|o<<A(64)}function lt(t,e=A(0)){const n=new TextEncoder,r=U(typeof t=="string"?n.encode(t):t),s=r.byteLength,o=i=>i.toString(16).padStart(32,"0");return s<=16?o(Df(r,e)):s<=128?o(Ff(r,Oe,e)):s<=240?o(Uf(r,Oe,e)):o($f(r,Oe))}function ul(t){return/^[0-9a-f]{32}$/.test(t)}function hl(t){const e=ze.getRunnableConfig();if(!e)throw new Error("Called interrupt() outside the context of a graph.");const n=e.configurable;if(!n)throw new Error("No configurable found in config");if(!n[K])throw new Xn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=n[rt];s.interruptCounter+=1;const o=s.interruptCounter;if(s.resume.length>0&&o<s.resume.length)return n[nt]?.([[de,s.resume]]),s.resume[o];if(s.nullResume!==void 0){if(s.resume.length!==o)throw new Error(`Resume length mismatch: ${s.resume.length} !== ${o}`);const l=s.consumeNullResume();return s.resume.push(l),n[nt]?.([[de,s.resume]]),l}const i=n[Ne]?.split(Y),a=i?lt(i.join(Y)):void 0;throw new At([{id:a,value:t}])}var _t=class extends re{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,n,r){return new Promise((s,o)=>{const i=un(n,{callbacks:r?.getChild()});ze.runWithConfig(i,async()=>{try{const a=await this.func(e,i);s(a)}catch(a){o(a)}})})}async invoke(e,n){let r;const s=rl(n),o=Ve(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,o):r=await ze.runWithConfig(o,async()=>this.func(e,o)),re.isRunnable(r)&&this.recurse?await ze.runWithConfig(o,async()=>r.invoke(e,o)):r}};function*Ke(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function Ye(t){const e=[];for await(const n of await t)e.push(n);return e}function an(t){const e=[];for(const n of t)e.push(n);return e}function Ct(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function Vf(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const mt={[Symbol.for("LG_PASSTHROUGH")]:!0};function Ln(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const Jr=Symbol("IS_WRITER");var ce=class Os extends _t{writes;constructor(e,n){const r=`ChannelWrite<${e.map(s=>ye(s)?s.node:"channel"in s?s.channel:"...").join(",")}>`;super({writes:e,name:r,tags:n,func:async(s,o)=>this._write(s,o??{})}),this.writes=e}async _write(e,n){const r=this.writes.map(s=>qr(s)&&Ln(s.value)?{mapper:s.mapper,value:e}:rr(s)&&Ln(s.value)?{channel:s.channel,value:e,skipNone:s.skipNone,mapper:s.mapper}:s);return await Os.doWrite(n,r),e}static async doWrite(e,n){for(const o of n){if(rr(o)){if(o.channel===be)throw new z("Cannot write to the reserved channel TASKS");if(Ln(o.value))throw new z("PASSTHROUGH value must be replaced")}if(qr(o)&&Ln(o.value))throw new z("PASSTHROUGH value must be replaced")}const r=[];for(const o of n)if(ye(o))r.push([be,o]);else if(qr(o)){const i=await o.mapper.invoke(o.value,e);i!=null&&i.length>0&&r.push(...i)}else if(rr(o)){const i=o.mapper!==void 0?await o.mapper.invoke(o.value,e):o.value;if(Vf(i)||o.skipNone&&i===void 0)continue;r.push([o.channel,i])}else throw new Error(`Invalid write entry: ${JSON.stringify(o)}`);const s=e.configurable?.[nt];s(r)}static isWriter(e){return e instanceof Os||Jr in e&&!!e[Jr]}static registerWriter(e){return Object.defineProperty(e,Jr,{value:!0})}};function rr(t){return t!==void 0&&typeof t.channel=="string"}function qr(t){return t!==void 0&&!rr(t)&&re.isRunnable(t.mapper)}var Bf=class dl extends _t{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,o)=>dl.doRead(o,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=e,this.name=Array.isArray(e)?`ChannelRead<${e.join(",")}>`:`ChannelRead<${e}>`}static doRead(e,n,r,s){const o=e.configurable?.[pt];if(!o)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(o(n,r)):o(n,r)}};const Tt=new Lc;var bn=class ln extends $e{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=Tt;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(e){const{channels:n,triggers:r,mapper:s,writers:o,bound:i,kwargs:a,metadata:l,retryPolicy:c,cachePolicy:u,tags:h,subgraphs:d,ends:f}=e,p=[...e.config?.tags?e.config.tags:[],...h??[]];super({...e,bound:e.bound??Tt,config:{...e.config?e.config:{},tags:p}}),this.channels=n,this.triggers=r,this.mapper=s,this.writers=o??this.writers,this.bound=i??this.bound,this.kwargs=a??this.kwargs,this.metadata=l??this.metadata,this.tags=p,this.retryPolicy=c,this.cachePolicy=u,this.subgraphs=d,this.ends=f}getWriters(){const e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof ce&&e[e.length-2]instanceof ce;){const n=e.slice(-2),r=n[0].writes.concat(n[1].writes);e[e.length-2]=new ce(r,n[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();if(!(this.bound===Tt&&e.length===0))return this.bound===Tt&&e.length===1?e[0]:this.bound===Tt?new st({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new st({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(e){if(!Array.isArray(e))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 ln({channels:{...this.channels,...Object.fromEntries(e.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(e){return ce.isWriter(e)?new ln({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,e],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===Tt?new ln({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Kt(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new ln({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function zf(t){return"steps"in t&&Array.isArray(t.steps)}function ho(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function fl(t){const e=[t];for(const n of e){if(ho(n))return n;zf(n)&&e.push(...n.steps)}}function It(t,e,n=!0,r=!1){try{return t[e].get()}catch(s){if(s.name===ne.unminifiable_name){if(r)return s;if(n)return null}throw s}}function yt(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=It(t,s,!n)}catch(o){if(o.name===ne.unminifiable_name)continue}return r}else return It(t,e)}function*Wf(t,e){if(t.graph===G.PARENT)throw new z("There is no parent graph.");if(t.goto){let n;Array.isArray(t.goto)?n=t.goto:n=[t.goto];for(const r of n)if(ye(r))yield[_e,be,r];else if(typeof r=="string")yield[_e,`branch:to:${r}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof r}`)}if(t.resume)if(typeof t.resume=="object"&&Object.keys(t.resume).length&&Object.keys(t.resume).every(ul))for(const[n,r]of Object.entries(t.resume)){const s=e.filter(o=>o[0]===n&&o[1]===de).map(o=>o[2]).slice(0,1)??[];s.push(r),yield[n,de,s]}else yield[_e,de,t.resume];if(t.update){if(typeof t.update!="object"||!t.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(t.update))for(const[n,r]of t.update)yield[_e,n,r];else for(const[n,r]of Object.entries(t.update))yield[_e,n,r]}}function*pl(t,e){if(e!=null)if(Array.isArray(t)&&typeof e=="object"&&!Array.isArray(e))for(const n in e)t.includes(n)&&(yield[n,e[n]]);else{if(Array.isArray(t))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[t,e]}}function*Yr(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield yt(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield It(n,t))}function*Hf(t,e,n){const r=e.filter(([a,l])=>(a.config===void 0||!a.config.tags?.includes(J))&&l[0][0]!==he&&l[0][0]!==D);if(!r.length)return;let s;r.some(([a])=>a.writes.some(([l,c])=>l===Yt))?s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===Yt).map(([l,c])=>[a.name,c])):Array.isArray(t)?s=r.flatMap(([a])=>{const{writes:l}=a,c={};for(const[u]of l)t.includes(u)&&(c[u]=(c[u]||0)+1);return Object.values(c).some(u=>u>1)?l.filter(([u])=>t.includes(u)).map(([u,h])=>[a.name,{[u]:h}]):[[a.name,Object.fromEntries(l.filter(([u])=>t.includes(u)))]]}):s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===t).map(([l,c])=>[a.name,c]));const o={};for(const[a,l]of s)a in o||(o[a]=[]),o[a].push(l);const i={};for(const a in o)if(o[a].length===1){const[l]=o[a];i[a]=l}else i[a]=o[a];n&&(i.__metadata__={cached:n}),yield i}function fo(t){const e=typeof t[F];if(e==="number")return 0;if(e==="string")return"";for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=typeof t[n];if(r==="number")return 0;if(r==="string")return"";break}}function sr(t,e){if(Object.keys(t).length>0){const n=fo(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function Gf(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Te(t,e){return t===null?{configurable:e}:t?.configurable===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function at(t,e){const n=e?.parents??{};return Object.keys(n).length>0?Te(t,{[we]:{...n,[t.configurable?.checkpoint_ns??""]:t.configurable?.checkpoint_id}}):t}function br(...t){const e=[...new Set(t.filter(Boolean))];if(e.length===0)return{signal:void 0,dispose:void 0};if(e.length===1)return{signal:e[0],dispose:void 0};const n=new AbortController,r=()=>{const o=e.find(i=>i.aborted)?.reason;n.abort(o),e.forEach(i=>i.removeEventListener("abort",r))};e.forEach(o=>o.addEventListener("abort",r,{once:!0}));const s=e.find(o=>o.aborted);return s&&n.abort(s.reason),{signal:n.signal,dispose:()=>{e.forEach(o=>o.removeEventListener("abort",r))}}}const Kf=(t,e)=>{if(!(!t&&!e))return t?e?Array.isArray(t)&&Array.isArray(e)?[...t,...e]:Array.isArray(t)?[...t,e]:Array.isArray(e)?[t,...e]:[t,e]:t:e};var Jf=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:t,name:e,input:n,retry:r,cache:s,callbacks:o}){this.func=t,this.name=e,this.input=n,this.retry=r,this.cache=s,this.callbacks=o}};function qf(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function Yf(t,e){const n=new _t({func:r=>e(...r),name:t,trace:!1,recurse:!1});return new st({name:t,first:n,last:new ce([{channel:Yt,value:mt}],[J])})}const Xf=t=>t!==void 0?t+1:1;function Zf(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function Qf(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=qd(e,t[n]));return e}function Dn(t,e,n){const r=fo(t.channel_versions),s=t.versions_seen[D]??{};let o=!1;if((t.channel_versions[F]??r)>(s[F]??r))o=!0;else for(const a in t.channel_versions)if(Object.prototype.hasOwnProperty.call(t.channel_versions,a)&&t.channel_versions[a]>(s[a]??r)){o=!0;break}const i=n.some(a=>e==="*"?!a.config?.tags?.includes(J):e.includes(a.name));return o&&i}function or(t,e,n,r,s=!1){let o=new Set;if(Array.isArray(r))o=new Set(r.filter(a=>n.writes.some(([l,c])=>l===a)));else{for(const[a]of n.writes)if(a===r){o=new Set([a]);break}o=o||new Set}let i;if(s&&o.size>0){const a=Object.fromEntries(Object.entries(e).filter(([u,h])=>o.has(u))),l=ct(t,a,-1),c=gr(a,l);pe(mr(l),c,[n],void 0,void 0),i=yt({...e,...c},r)}else i=yt(e,r);return i}function Xr(t,e,n){for(const[r,s]of n)if([me,be].includes(r)&&s!=null){if(!ye(s))throw new z(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in e))throw new z(`Invalid node name "${s.node}" in Send packet`)}t(n)}const ep=new Set([co,me,de,D,Yt,he]);function pe(t,e,n,r,s){n.sort((d,f)=>{const p=d.path?.slice(0,3)||[],m=f.path?.slice(0,3)||[];for(let S=0;S<Math.min(p.length,m.length);S+=1){if(p[S]<m[S])return-1;if(p[S]>m[S])return 1}return p.length-m.length});const o=n.some(d=>d.triggers.length>0),i=io(e);for(const d of n){t.versions_seen[d.name]??={};for(const f of d.triggers)f in t.channel_versions&&(t.versions_seen[d.name][f]=t.channel_versions[f])}let a=Qf(t.channel_versions);const l=new Set(n.flatMap(d=>d.triggers).filter(d=>!mf.includes(d)));let c=!1;for(const d of l)d in i&&i[d].consume()&&r!==void 0&&(t.channel_versions[d]=r(a),c=!0);const u={};for(const d of n)for(const[f,p]of d.writes)ep.has(f)||f in i&&(u[f]??=[],u[f].push(p));a!=null&&r!=null&&(a=c?r(a):a);const h=new Set;for(const[d,f]of Object.entries(u))if(d in i){const p=i[d];let m;try{m=p.update(f)}catch(S){if(S.name===z.unminifiable_name){const C=new z(`Invalid update for channel "${d}" with values ${JSON.stringify(f)}: ${S.message}`);throw C.lc_error_code=S.lc_error_code,C}else throw S}m&&r!==void 0&&(t.channel_versions[d]=r(a),p.isAvailable()&&h.add(d))}if(o)for(const d in i){if(!Object.prototype.hasOwnProperty.call(i,d))continue;const f=i[d];f.isAvailable()&&!h.has(d)&&f.update([])&&r!==void 0&&(t.channel_versions[d]=r(a),f.isAvailable()&&h.add(d))}if(o&&!Zf(h,s))for(const d in i){if(!Object.prototype.hasOwnProperty.call(i,d))continue;const f=i[d];f.finish()&&r!==void 0&&(t.channel_versions[d]=r(a),f.isAvailable()&&h.add(d))}return h}function*tp(t,e,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){const s=new Set;for(const o of n.updatedChannels){const i=n.triggerToNodes[o];for(const a of i??[])s.add(a)}yield*[...s].sort();return}if(!(()=>{for(const s in t.channel_versions)if(t.channel_versions[s]!==null)return!1;return!0})())for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(yield s)}function Mt(t,e,n,r,s,o,i){const a={},l=r[be];if(l?.isAvailable()){const c=l.get().length;for(let u=0;u<c;u+=1){const h=Ns([me,u],t,e,n,r,s,o,i);h!==void 0&&(a[h.id]=h)}}for(const c of tp(t,n,i)){const u=Ns([tr,c],t,e,n,r,s,o,i);u!==void 0&&(a[u.id]=u)}return a}function Ns(t,e,n,r,s,o,i,a){const{step:l,checkpointer:c,manager:u}=a,h=o.configurable??{},d=h.checkpoint_ns??"";if(t[0]===me&&qf(t[t.length-1])){const f=t[t.length-1],p=Yf(f.name,f.func),m=[me],S=d===""?f.name:`${d}${Y}${f.name}`,C=kt(JSON.stringify([S,l.toString(),f.name,me,t[1],t[2]]),e.id),E=`${S}${He}${C}`,b=[...t.slice(0,3),!0],w={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:m,langgraph_path:b,langgraph_checkpoint_ns:E};if(i){const g=[];return{name:f.name,input:f.input,proc:p,writes:g,config:un(Ve(o,{metadata:w,store:a.store??o.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[hn]:C,[nt]:_=>Xr(v=>g.push(...v),r,_),[pt]:(_,v=!1)=>or(e,s,{name:f.name,writes:g,triggers:m,path:b},_,v),[K]:c??h[K],[we]:{...h[we],[d]:e.id},[rt]:Zr({pendingWrites:n??[],taskId:C,currentTaskInput:f.input,resumeMap:o.configurable?.[Qn],namespaceHash:lt(E)}),[er]:e.channel_values[Gr],checkpoint_id:void 0,checkpoint_ns:E}}),triggers:m,retry_policy:f.retry,cache_key:f.cache?{key:lt((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[Hr,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:C,path:b,writers:[]}}else return{id:C,name:f.name,interrupts:[],path:b}}else if(t[0]===me){const f=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!s[be]?.isAvailable())return;const p=s[be].get();if(f<0||f>=p.length)return;const m=As(p[f])&&!ye(p[f])?new le(p[f].node,p[f].args):p[f];if(!As(m)){console.warn(`Ignoring invalid packet ${JSON.stringify(m)} in pending sends.`);return}if(!(m.node in r)){console.warn(`Ignoring unknown node name ${m.node} in pending sends.`);return}const S=[me],C=d===""?m.node:`${d}${Y}${m.node}`,E=kt(JSON.stringify([C,l.toString(),m.node,me,f.toString()]),e.id),b=`${C}${He}${E}`;let w={langgraph_step:l,langgraph_node:m.node,langgraph_triggers:S,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:b};if(i){const g=r[m.node],k=g.getNode();if(k!==void 0){g.metadata!==void 0&&(w={...w,...g.metadata});const _=[];return{name:m.node,input:m.args,proc:k,subgraphs:g.subgraphs,writes:_,config:un(Ve(o,{metadata:w,tags:g.tags,store:a.store??o.store}),{runName:m.node,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[hn]:E,[nt]:v=>Xr(x=>_.push(...x),r,v),[pt]:(v,x=!1)=>or(e,s,{name:m.node,writes:_,triggers:S,path:t},v,x),[K]:c??h[K],[we]:{...h[we],[d]:e.id},[rt]:Zr({pendingWrites:n??[],taskId:E,currentTaskInput:m.args,resumeMap:o.configurable?.[Qn],namespaceHash:lt(b)}),[er]:e.channel_values[Gr],checkpoint_id:void 0,checkpoint_ns:b}}),triggers:S,retry_policy:g.retryPolicy,cache_key:g.cachePolicy?{key:lt((g.cachePolicy.keyFunc??JSON.stringify)([m.args])),ns:[Hr,g.name??"__dynamic__",m.node],ttl:g.cachePolicy.ttl}:void 0,id:E,path:t,writers:g.getWriters()}}}else return{id:E,name:m.node,interrupts:[],path:t}}else if(t[0]===tr){const f=t[1].toString(),p=r[f];if(p===void 0)return;if(n?.length){const E=d===""?f:`${d}${Y}${f}`,b=kt(JSON.stringify([E,l.toString(),f,tr,f]),e.id);if(n.some(g=>g[0]===b&&g[1]!==he))return}const m=fo(e.channel_versions);if(m===void 0)return;const S=e.versions_seen[f]??{},C=p.triggers.find(E=>s[E].isAvailable()?(e.channel_versions[E]??m)>(S[E]??m):!1);if(C!==void 0){const E=np(p,s,i);if(E===void 0)return;const b=d===""?f:`${d}${Y}${f}`,w=kt(JSON.stringify([b,l.toString(),f,tr,[C]]),e.id),g=`${b}${He}${w}`;let k={langgraph_step:l,langgraph_node:f,langgraph_triggers:[C],langgraph_path:t,langgraph_checkpoint_ns:g};if(i){const _=p.getNode();if(_!==void 0){p.metadata!==void 0&&(k={...k,...p.metadata});const v=[];return{name:f,input:E,proc:_,subgraphs:p.subgraphs,writes:v,config:un(Ve(o,{metadata:k,tags:p.tags,store:a.store??o.store}),{runName:f,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[hn]:w,[nt]:x=>Xr(T=>{v.push(...T)},r,x),[pt]:(x,T=!1)=>or(e,s,{name:f,writes:v,triggers:[C],path:t},x,T),[K]:c??h[K],[we]:{...h[we],[d]:e.id},[rt]:Zr({pendingWrites:n??[],taskId:w,currentTaskInput:E,resumeMap:o.configurable?.[Qn],namespaceHash:lt(g)}),[er]:e.channel_values[Gr],checkpoint_id:void 0,checkpoint_ns:g}}),triggers:[C],retry_policy:p.retryPolicy,cache_key:p.cachePolicy?{key:lt((p.cachePolicy.keyFunc??JSON.stringify)([E])),ns:[Hr,p.name??"__dynamic__",f],ttl:p.cachePolicy.ttl}:void 0,id:w,path:t,writers:p.getWriters()}}}else return{id:w,name:f,interrupts:[],path:t}}}}function np(t,e,n){let r;if(typeof t.channels=="object"&&!Array.isArray(t.channels)){r={};for(const[s,o]of Object.entries(t.channels))if(t.triggers.includes(o))try{r[s]=It(e,o,!1)}catch(i){if(i.name===ne.unminifiable_name)return;throw i}else if(o in e)try{r[s]=It(e,o,!1)}catch(i){if(i.name===ne.unminifiable_name)continue;throw i}}else if(Array.isArray(t.channels)){let s=!1;for(const o of t.channels)try{r=It(e,o,!1),s=!0;break}catch(i){if(i.name===ne.unminifiable_name)continue;throw i}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);return n&&t.mapper!==void 0&&(r=t.mapper(r)),r}function Zr({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:r,namespaceHash:s}){const o=t.find(([l,c])=>l===_e&&c===de)?.[2],a={callCounter:0,interruptCounter:-1,resume:(()=>{const l=t.filter(([c,u])=>c===e&&u===de).flatMap(([c,u,h])=>h);if(r!=null&&s in r){const c=r[s];l.push(c)}return l})(),nullResume:o,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(a.nullResume)return delete a.nullResume,t.splice(t.findIndex(([l,c])=>l===_e&&c===de),1),o}};return a}const _n={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},Sn=(t,e)=>`${t.start}${e}${t.end}`;function*Bo(t){for(const{id:e,name:n,input:r,config:s,triggers:o,writes:i}of t){if(s?.tags?.includes(J))continue;const a=i.filter(([l,c])=>l===e&&c===D).map(([,l])=>l);yield{id:e,name:n,input:r,triggers:o,interrupts:a}}}function rp(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function ml(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const o=rp(e[s])?e[s].$writes:[e[s]];o.push(r),e[s]={$writes:o}}else e[s]=r}return e}function*sp(t,e){for(const[{id:n,name:r,config:s},o]of t)s?.tags?.includes(J)||(yield{id:n,name:r,result:ml(o.filter(([i])=>Array.isArray(e)?e.includes(i):i===e)),interrupts:o.filter(i=>i[0]===D).map(i=>i[1])})}function*op(t,e,n,r,s,o,i,a){function l(h){const d={};return h.callbacks!=null&&(d.callbacks=h.callbacks),h.configurable!=null&&(d.configurable=h.configurable),h.maxConcurrency!=null&&(d.max_concurrency=h.maxConcurrency),h.metadata!=null&&(d.metadata=h.metadata),h.recursionLimit!=null&&(d.recursion_limit=h.recursionLimit),h.runId!=null&&(d.run_id=h.runId),h.runName!=null&&(d.run_name=h.runName),h.tags!=null&&(d.tags=h.tags),d}const c=t.configurable?.checkpoint_ns,u={};for(const h of s){if(!(h.subgraphs?.length?h.subgraphs:[h.proc]).find(fl))continue;let f=`${h.name}:${h.id}`;c&&(f=`${c}|${f}`),u[h.id]={configurable:{thread_id:t.configurable?.thread_id,checkpoint_ns:f}}}yield{config:l(t),values:yt(e,n),metadata:r,next:s.map(h=>h.name),tasks:gl(s,o,u,a),parentConfig:i?l(i):void 0}}function gl(t,e,n,r){return t.map(s=>{const o=e.find(([c,u])=>c===s.id&&u===he)?.[2],i=e.filter(([c,u])=>c===s.id&&u===D).map(([,,c])=>c),a=(()=>{if(o||i.length||!e.length)return;const c=e.findIndex(([u,h])=>u===s.id&&h===Yt);if(c>=0)return e[c][2];if(typeof r=="string")return e.find(([u,h])=>u===s.id&&h===r)?.[2];if(Array.isArray(r)){const u=e.filter(([h,d])=>h===s.id&&r.includes(d)).map(([,h,d])=>[h,d]);return u.length?ml(u):void 0}})();if(o)return{id:s.id,name:s.name,path:s.path,error:o,interrupts:i,result:a};const l=n?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:i,...l!==void 0?{state:l}:{},result:a}})}function ip(t,e,n){console.log([`${Sn(_n.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
42
+ `,JSON.stringify(yt(e,n),null,2)].join(""))}function yl(t,e){const n=e.length;console.log([`${Sn(_n.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
43
+ `,e.map(r=>`- ${Sn(_n.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
44
+ `)].join(""))}function ap(t,e,n){const r={};for(const[s,o]of e)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(o));console.log([`${Sn(_n.blue,`[${t}:writes]`)}`,`\x1B[1m Finished step ${t} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
45
+ `,Object.entries(r).map(([s,o])=>`- ${Sn(_n.yellow,s)} -> ${o.map(i=>JSON.stringify(i)).join(", ")}`).join(`
46
+ `)].join(""))}var zo=class extends fn{_abortController;_innerReader;constructor(t,e){const n=t.getReader(),r=e??new AbortController;super({start(s){return o();function o(){return n.read().then(({done:i,value:a})=>{if(i){s.close();return}return s.enqueue(a),o()})}}}),this._abortController=r,this._innerReader=n}async cancel(t){this._abortController.abort(t),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},wl=class extends fn{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(t){let e;const n=new Promise(r=>{e=r});super({start:r=>{e(r)}}),n.then(r=>{this.controller=r}),this.passthroughFn=t.passthroughFn,this.modes=t.modes}push(t){this.passthroughFn?.(t),this.controller.enqueue(t)}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(t){this.controller.error(t)}};function lp(t){return JSON.stringify(t,function(e,n){const r=this[e];if(r!=null&&typeof r=="object"&&"toDict"in r&&typeof r.toDict=="function"){const{type:s,data:o}=r.toDict();return{...o,type:s}}return n})}function cp(t){return t instanceof Error?{error:t.name,message:t.message}:{error:"Error",message:JSON.stringify(t)}}function po(t){return typeof t!="object"||t==null?!1:"configurable"in t&&typeof t.configurable=="object"&&t.configurable!=null}function Qr(t){return!po(t)||!t.configurable.thread_id?null:{thread_id:t.configurable.thread_id,checkpoint_ns:t.configurable.checkpoint_ns||"",checkpoint_id:t.configurable.checkpoint_id||null,checkpoint_map:t.configurable.checkpoint_map||null}}function Wo(t){if(po(t)){const e=Object.fromEntries(Object.entries(t.configurable).filter(([r])=>!r.startsWith("__"))),n={...t,configurable:e};return delete n.callbacks,n}return t}function Ho(t){const e={...t,checkpoint:Qr(t.config),parent_checkpoint:Qr(t.parentConfig),config:Wo(t.config),parent_config:Wo(t.parentConfig),tasks:t.tasks.map(n=>{if(po(n.state)){const r=Qr(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete e.parentConfig,e}function up(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
47
+ data: ${lp(s.data)}
48
+
49
+ `))};try{for await(const s of t){const[o,i,a]=s;let l=a;if(i==="debug"){const u=a;u.type==="checkpoint"&&(l={...u,payload:Ho(u.payload)})}i==="checkpoints"&&(l=Ho(a));const c=o?.length?`${i}|${o.join("|")}`:i;r({event:c,data:l})}}catch(s){r({event:"error",data:cp(s)})}n.close()}})}const Fn=Symbol.for("INPUT_DONE"),es=Symbol.for("INPUT_RESUMING"),hp=25;function dp(...t){return new wl({passthroughFn:e=>{for(const n of t)n.modes.has(e[1])&&n.push(e)},modes:new Set(t.flatMap(e=>Array.from(e.modes)))})}var fp=class extends tf{cache;queue=Promise.resolve();constructor(t){super(),this.cache=t}async get(t){return this.enqueueOperation("get",t)}async set(t){return this.enqueueOperation("set",t)}async clear(t){return this.enqueueOperation("clear",t)}async stop(){await this.queue}enqueueOperation(t,...e){const n=this.queue.then(()=>this.cache[t](...e));return this.queue=n.then(()=>{},()=>{}),n}},pp=class vl{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 e=!1;if(F in this.checkpoint.channel_versions)e=!0;else for(const l in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,l)){e=!0;break}const r=this.config.configurable?.[qe]!==void 0&&this.config.configurable?.[qe],s=this.input===null||this.input===void 0,o=Z(this.input)&&this.input.resume!=null,i=this.input===es,a=!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 e&&(r||s||o||i||a)}constructor(e){this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=Xf,this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.manager=e.manager,this.outputKeys=e.outputKeys,this.streamKeys=e.streamKeys,this.nodes=e.nodes,this.skipDoneTasks=e.skipDoneTasks,this.store=e.store,this.cache=e.cache?new fp(e.cache):void 0,this.stream=e.stream,this.checkpointNamespace=e.checkpointNamespace,this.prevCheckpointConfig=e.prevCheckpointConfig,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.durability=e.durability,this.debug=e.debug,this.triggerToNodes=e.triggerToNodes}static async initialize(e){let{config:n,stream:r}=e;r!==void 0&&n.configurable?.[yr]!==void 0&&(r=dp(r,n.configurable[yr]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,o=n.configurable?.[rt];n.configurable&&o&&(o.subgraphCounter>0&&(n=Te(n,{[Ne]:[n.configurable[Ne],o.subgraphCounter.toString()].join(Y)})),o.subgraphCounter+=1);const i=pt in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=Te(n,{checkpoint_ns:"",checkpoint_id:void 0}));let a=n;n.configurable?.[we]!==void 0&&n.configurable?.[we]?.[n.configurable?.checkpoint_ns]&&(a=Te(n,{checkpoint_id:n.configurable[we][n.configurable?.checkpoint_ns]}));const l=n.configurable?.checkpoint_ns?.split(Y)??[],c=await e.checkpointer?.getTuple(a)??{config:n,checkpoint:Ha(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...n,...c.config,configurable:{checkpoint_ns:"",...n.configurable,...c.config.configurable}};const u=c.parentConfig,h=mr(c.checkpoint),d={...c.metadata},f=c.pendingWrites??[],p=gr(e.channelSpecs,h),m=(d.step??0)+1,S=m+(n.recursionLimit??hp)+1,C={...h.channel_versions},E=e.store?new ef(e.store):void 0;return E&&await E.start(),new vl({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:h,checkpointMetadata:d,checkpointConfig:a,prevCheckpointConfig:u,checkpointNamespace:l,channels:p,isNested:i,manager:e.manager,skipDoneTasks:s,step:m,stop:S,checkpointPreviousVersions:C,checkpointPendingWrites:f,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:E,cache:e.cache,interruptAfter:e.interruptAfter,interruptBefore:e.interruptBefore,durability:e.durability,debug:e.debug,triggerToNodes:e.triggerToNodes})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(e,n){let r=n;if(r.length===0)return;r.every(([i])=>i in Yd)&&(r=Array.from(new Map(r.map(i=>[i[0],i])).values())),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(i=>i[0]!==e);for(const[i,a]of r)this.checkpointPendingWrites.push([e,i,a]);const s=Te(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??"",[Ms]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(s,r,e)),this.tasks&&this._outputWrites(e,r),!n.length||!this.cache||!this.tasks)return;const o=this.tasks[e];o==null||o.cache_key==null||n[0][0]===he||n[0][0]===D||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,n,r=!1){const s=this.tasks[e];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes(J))return;if(n.length>0)if(n[0][0]===D){if(s.path?.[0]===me&&s.path?.at(-1)===!0)return;const o=n.filter(i=>i[0]===D).flatMap(i=>i[1]);this._emit([["updates",{[D]:o}],["values",{[D]:o}]])}else n[0][0]!==he&&this._emit(an(Ke(Hf(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(an(Ke(sp([[s,n]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const e=[],n=([i,a])=>`ns:${i.join(",")}|key:${a}`,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 o=await this.cache.get(r);for(const{key:i,value:a}of o){const l=s[n(i)];l!=null&&(l.writes.push(...a),e.push({task:l,result:a}))}return e}async tick(e){this.store&&!this.store.isRunning&&await this.store?.start();const{inputKeys:n=[]}=e;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![Fn,es].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new At;if(Object.values(this.tasks).every(o=>o.writes.length>0)){const o=Object.values(this.tasks).flatMap(a=>a.writes);this.updatedChannels=pe(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const i=await Ye(Ke(Yr(this.outputKeys,o,this.channels),"values"));if(this._emit(i),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),Dn(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new At;this.config.configurable?.[qe]!==void 0&&delete this.config.configurable?.[qe]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const r=Mt(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 Ye(Ke(op(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[o,i,a]of this.checkpointPendingWrites){if(i===he||i===D||i===de)continue;const l=Object.values(this.tasks).find(c=>c.id===o);l&&l.writes.push([i,a])}for(const o of Object.values(this.tasks))o.writes.length>0&&this._outputWrites(o.id,o.writes,!0)}if(Object.values(this.tasks).every(o=>o.writes.length>0))return this.tick({inputKeys:n});if(Dn(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new At;const s=await Ye(Ke(Bo(Object.values(this.tasks)),"tasks"));return this._emit(s),!0}async finishAndHandleError(e){this.durability==="exit"&&(!this.isNested||typeof e<"u"||this.checkpointNamespace.every(r=>!r.includes(He)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=yt(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=pe(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(an(Ke(Yr(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),ht(e)&&!e.interrupts.length&&this._emit([["updates",{[D]:[]}],["values",{[D]:[]}]])),n}async acceptPush(e,n,r){if(this.interruptAfter?.length>0&&Dn(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=Ns([me,e.path??[],n,e.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.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&&Dn(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(an(Ke(Bo([s]),"tasks"))),this.debug&&yl(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});const o=await this._matchCachedWrites();for(const{task:i}of o)this._outputWrites(i.id,i.writes,!0);return s}_suppressInterrupt(e){return ht(e)&&!this.isNested}async _first(e){const{configurable:n}=this.config,r=n?.[rt];if(r&&r.nullResume!==void 0&&this.putWrites(_e,[[de,r.nullResume]]),Z(this.input)){const i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(ul)&&(this.config.configurable??={},this.config.configurable[Qn]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[l,c,u]of Wf(this.input,this.checkpointPendingWrites))a[l]??=[],a[l].push([c,u]);if(Object.keys(a).length===0)throw new Ro("Received empty Command input");for(const[l,c]of Object.entries(a))this.putWrites(l,c)}const s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===_e).map(i=>i.slice(1));s.length>0&&pe(this.checkpoint,this.channels,[{name:Fe,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const o=Z(this.input)&&s.length>0;if(this.isResuming||o){for(const a in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,a)&&this.checkpoint.channel_versions[a]!==void 0){const l=this.checkpoint.channel_versions[a];this.checkpoint.versions_seen[D]={...this.checkpoint.versions_seen[D],[a]:l}}const i=await Ye(Ke(Yr(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=es;else if(o)await this._putCheckpoint({source:"input"}),this.input=Fn;else{const i=await Ye(pl(e,this.input));if(i.length>0){const a=Mt(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=pe(this.checkpoint,this.channels,Object.values(a).concat([{name:Fe,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=Fn}else if(qe in(this.config.configurable??{}))this.input=Fn;else throw new Ro(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=Te(this.config,{[qe]:this.isResuming}))}_emit(e){for(const[n,r]of e)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,o=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:o,payload:r}])}}_putCheckpoint(e){const n=this.checkpointMetadata===e,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=o=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=Te(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},a=sr(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:mr(o),metadata:{...this.checkpointMetadata},newVersions:a}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};n||(this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.[we]??{}}),this.checkpoint=ct(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 e=Te(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??"",[Ms]:this.checkpoint.id}),n={};for(const[r,s,o]of this.checkpointPendingWrites)n[r]??=[],n[r].push([s,o]);for(const[r,s]of Object.entries(n))this.checkpointerPromises.push(this.checkpointer.putWrites(e,s,r))}_matchWrites(e){for(const[n,r,s]of this.checkpointPendingWrites){if(r===he||r===D||r===de)continue;const o=Object.values(e).find(i=>i.id===n);o&&o.writes.push([r,s])}for(const n of Object.values(e))n.writes.length>0&&this._outputWrites(n.id,n.writes,!0)}};function mp(t){return De(t?.message)}var gp=class extends pu{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(t){super(),this.streamFn=t}_emit(t,e,n,r=!1){if(r&&e.id!==void 0&&this.seen[e.id]!==void 0)return;let s=e.id;n!=null&&(mu(e)?s??=`run-${n}-tool-${e.tool_call_id}`:((s==null||s===`run-${n}`)&&(s=this.stableMessageIdMap[n]??s??`run-${n}`),this.stableMessageIdMap[n]??=s)),s!==e.id&&(e.id=s,e.lc_kwargs.id=s),e.id!=null&&(this.seen[e.id]=e),this.streamFn([t[0],"messages",[e,t[1]]])}handleChatModelStart(t,e,n,r,s,o,i,a){i&&(!o||!o.includes(pf)&&!o.includes("nostream"))&&(this.metadatas[n]=[i.langgraph_checkpoint_ns.split("|"),{tags:o,name:a,...i}])}handleLLMNewToken(t,e,n,r,s,o){const i=o?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(mp(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new Gt({content:t}),n))}handleLLMEnd(t,e){if(this.metadatas[e]!==void 0){if(!this.emittedChatModelRunIds[e]){const n=t.generations?.[0]?.[0];De(n?.message)&&this._emit(this.metadatas[e],n?.message,e,!0),delete this.emittedChatModelRunIds[e]}delete this.metadatas[e],delete this.stableMessageIdMap[e]}}handleLLMError(t,e){delete this.metadatas[e]}handleChainStart(t,e,n,r,s,o,i,a){if(o!==void 0&&a===o.langgraph_node&&(s===void 0||!s.includes(J))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...o}],typeof e=="object")){for(const l of Object.values(e))if((De(l)||Co(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(const c of l)(De(c)||Co(c))&&c.id!==void 0&&(this.seen[c.id]=c)}}handleChainEnd(t,e){const n=this.metadatas[e];if(delete this.metadatas[e],n!==void 0){if(De(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const r of t)De(r)&&this._emit(n,r,e,!0);else if(t!=null&&typeof t=="object"){for(const r of Object.values(t))if(De(r))this._emit(n,r,e,!0);else if(Array.isArray(r))for(const s of r)De(s)&&this._emit(n,s,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const yp=500,wp=2,vp=128e3,bp=3,_p=[400,401,402,403,404,405,406,407,409],Sp=t=>{if(t.message.startsWith("Cancel")||t.message.startsWith("AbortError")||t.name==="AbortError"||t.name==="GraphValueError"||t?.code==="ECONNABORTED")return!1;const e=t?.response?.status??t?.status;return!(e&&_p.includes(+e)||t?.error?.code==="insufficient_quota")};async function bl(t,e,n,r){const s=t.retry_policy??e;let o=s!==void 0?s.initialInterval??yp:0,i=0,a,l,{config:c}=t;for(n&&(c=Te(c,n)),c={...c,signal:r};!r?.aborted;){t.writes.splice(0,t.writes.length),a=void 0;try{l=await t.proc.invoke(t.input,c);break}catch(u){if(a=u,a.pregelTaskId=t.id,af(a)){const p=c?.configurable?.checkpoint_ns,m=a.command;if(m.graph===p){for(const S of t.writers)await S.invoke(m,c);a=void 0;break}else if(m.graph===G.PARENT){const S=_f(p);a.command=new G({...a.command,graph:S})}}if(Zn(a)||s===void 0||(i+=1,i>=(s.maxAttempts??bp))||!(s.retryOn??Sp)(a))break;o=Math.min(s.maxInterval??vp,o*(s.backoffFactor??wp));const d=s.jitter?Math.floor(o+Math.random()*1e3):o;await new Promise(p=>setTimeout(p,d));const f=a.name??a.constructor.unminifiable_name??a.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(t.name)}" after ${o.toFixed(2)}ms (attempt ${i}) after ${f}: ${a}`),c=Te(c,{[qe]:!0})}}return{task:t,result:l,error:a,signalAborted:r?.aborted}}const $s=Symbol.for("promiseAdded");function Cp(){const t={next:()=>{},wait:Promise.resolve($s)};function e(n){t.next=()=>{t.wait=new Promise(e),n($s)}}return t.wait=new Promise(e),t}var Tp=class{nodeFinished;loop;constructor({loop:t,nodeFinished:e}){this.loop=t,this.nodeFinished=e}async tick(t={}){const{timeout:e,retryPolicy:n,onStepWrite:r,maxConcurrency:s}=t,o=new Set;let i;const a=new AbortController,l=a.signal,c=e?AbortSignal.timeout(e):void 0,u=Object.values(this.loop.tasks).filter(p=>p.writes.length===0),{signals:h,disposeCombinedSignal:d}=this._initializeAbortSignals({exceptionSignal:l,stepTimeoutSignal:c,signal:t.signal}),f=this._executeTasksWithRetry(u,{signals:h,retryPolicy:n,maxConcurrency:s});for await(const{task:p,error:m,signalAborted:S}of f)this._commit(p,m),ht(m)||Zn(m)&&!ht(i)?i=m:m&&(o.size===0||!S)&&(a.abort(),o.add(m));if(d?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(p=>p.writes).flat()),o.size===1)throw Array.from(o)[0];if(o.size>1)throw new AggregateError(Array.from(o),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(ht(i)||Zn(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[jo]??{},s=r.externalAbortSignal??n,o=e??r.timeoutAbortSignal,{signal:i,dispose:a}=br(s,o,t),l={externalAbortSignal:s,timeoutAbortSignal:o,composedAbortSignal:i};return this.loop.config=Te(this.loop.config,{[jo]:l}),{signals:l,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},o=Cp(),i={},a={executingTasksMap:i,barrier:o,retryPolicy:n,scheduleTask:async(d,f,p)=>this.loop.acceptPush(d,f,p)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let l=0,c;const u=br(s?.externalAbortSignal,s?.timeoutAbortSignal),h=u.signal?new Promise((d,f)=>{c=()=>f(new Error("Abort")),u.signal?.addEventListener("abort",c,{once:!0})}):void 0;for(;(l===0||Object.keys(i).length>0)&&t.length;){for(;Object.values(i).length<(r??t.length)&&l<t.length;l+=1){const f=t[l];i[f.id]=bl(f,n,{[lo]:_l?.bind(a,this,f)},s?.composedAbortSignal).catch(p=>({task:f,error:p,signalAborted:s?.composedAbortSignal?.aborted}))}const d=await Promise.race([...Object.values(i),...h?[h]:[],o.wait]);d!==$s&&(yield d,c!=null&&(u.signal?.removeEventListener("abort",c),u.dispose?.()),delete i[d.task.id])}}_commit(t,e){if(e!==void 0)if(ht(e)){if(e.interrupts.length){const n=e.interrupts.map(s=>[D,s]),r=t.writes.filter(s=>s[0]===de);r.length&&n.push(...r),this.loop.putWrites(t.id,n)}}else Zn(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):this.loop.putWrites(t.id,[[he,{message:e.message,name:e.name}]]);else this.nodeFinished&&(t.config?.tags==null||!t.config.tags.includes(J))&&this.nodeFinished(String(t.name)),t.writes.length===0&&t.writes.push([co,null]),this.loop.putWrites(t.id,t.writes)}};async function _l(t,e,n,r,s,o={}){const i=e.config?.configurable?.[rt];if(!i)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const a=i.callCounter;i.callCounter+=1;const l=new Jf({func:n,name:r,input:s,cache:o.cache,retry:o.retry,callbacks:o.callbacks}),c=await this.scheduleTask(e,a,l);if(!c)return;const u=this.executingTasksMap[c.id];if(u!==void 0)return u;if(c.writes.length>0){const h=c.writes.filter(([f])=>f===Yt),d=c.writes.filter(([f])=>f===he);if(h.length>0){if(h.length===1)return Promise.resolve(h[0][1]);throw new Error(`BUG: multiple returns found for task ${c.name}__${c.id}`)}if(d.length>0){if(d.length===1){const f=d[0][1],p=f instanceof Error?f:new Error(String(f));return Promise.reject(p)}throw new Error(`BUG: multiple errors found for task ${c.name}__${c.id}`)}return}else{const h=bl(c,o.retry,{[lo]:_l.bind(this,t,c)});return this.executingTasksMap[c.id]=h,this.barrier.next(),h.then(({result:d,error:f})=>f?Promise.reject(f):d)}}var Le=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function kp({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:o,interruptBeforeNodes:i}){if(!e)throw new Le("Channels not provided");const a=new Set,l=new Set;for(const[c,u]of Object.entries(t)){if(c===D)throw new Le(`"Node name ${D} is reserved"`);if(u.constructor===bn)u.triggers.forEach(h=>a.add(h));else throw new Le(`Invalid node type ${typeof u}, expected PregelNode`)}for(const c of a)if(!(c in e))throw new Le(`Subscribed channel '${String(c)}' not in channels`);if(Array.isArray(n)){if(n.every(c=>!a.has(c)))throw new Le(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new Le(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(c=>l.add(c)):l.add(r),s&&!Array.isArray(s)?l.add(s):Array.isArray(s)&&s.forEach(c=>l.add(c));for(const c of l)if(!(c in e))throw new Le(`Output channel '${String(c)}' not in channels`);if(o&&o!=="*"){for(const c of o)if(!(c in t))throw new Le(`Node ${String(c)} not in nodes`)}if(i&&i!=="*"){for(const c of i)if(!(c in t))throw new Le(`Node ${String(c)} not in nodes`)}}function Go(t,e){if(Array.isArray(t)){for(const n of t)if(!(n in e))throw new Error(`Key ${String(n)} not found in channels`)}else if(!(t in e))throw new Error(`Key ${String(t)} not found in channels`)}var Ep=class Sl extends bt{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(e){super(),this.unique=e?.unique??this.unique,this.accumulate=e?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(e){const n=new Sl({unique:this.unique,accumulate:this.accumulate});return typeof e<"u"&&(n.seen=new Set(e[0]),n.values=e[1]),n}update(e){let n=!1;this.accumulate||(n=this.values.length>0,this.values=[]);const r=e.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 ne;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},xp=class{static subscribeTo(t,e){const{key:n,tags:r}={key:void 0,tags:void 0,...e??{}};if(Array.isArray(t)&&n!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;typeof t=="string"?n?s={[n]:t}:s=[t]:s=Object.fromEntries(t.map(i=>[i,i]));const o=Array.isArray(t)?t:[t];return new bn({channels:s,triggers:o,tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:mt,skipNone:!1});for(const[r,s]of Object.entries(e??{}))re.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:mt,skipNone:!0,mapper:Kt(s)}):n.push({channel:r,value:s,skipNone:!1});return new ce(n)}},Mp=class extends re{lc_namespace=["langgraph","pregel"];invoke(t,e){throw new Error("Not implemented")}withConfig(t){return super.withConfig(t)}stream(t,e){return super.stream(t,e)}},Ap=class extends Mp{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(t){super(t);let{streamMode:e}=t;if(e!=null&&!Array.isArray(e)&&(e=[e]),this.nodes=t.nodes,this.channels=t.channels,be in this.channels&&"lc_graph_name"in this.channels[be]&&this.channels[be].lc_graph_name!=="Topic")throw new Error(`Channel '${be}' is reserved and cannot be used in the graph.`);this.channels[be]=new Ep({accumulate:!1}),this.autoValidate=t.autoValidate??this.autoValidate,this.streamMode=e??this.streamMode,this.inputChannels=t.inputChannels,this.outputChannels=t.outputChannels,this.streamChannels=t.streamChannels??this.streamChannels,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.stepTimeout=t.stepTimeout??this.stepTimeout,this.debug=t.debug??this.debug,this.checkpointer=t.checkpointer,this.retryPolicy=t.retryPolicy,this.config=t.config,this.store=t.store,this.cache=t.cache,this.name=t.name,this.triggerToNodes=t.triggerToNodes??this.triggerToNodes,this.userInterrupt=t.userInterrupt,this.autoValidate&&this.validate()}withConfig(t){const e=Ve(this.config,t);return new this.constructor({...this,config:e})}validate(){kp({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(const[t,e]of Object.entries(this.nodes))for(const n of e.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(t);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(t){return this.getGraph(t)}*getSubgraphs(t,e){for(const[n,r]of Object.entries(this.nodes)){if(t!==void 0&&!t.startsWith(n))continue;const s=r.subgraphs?.length?r.subgraphs:[r.bound];for(const o of s){const i=fl(o);if(i!==void 0){if(n===t){yield[n,i];return}if(t===void 0&&(yield[n,i]),e){let a=t;t!==void 0&&(a=t.slice(n.length+1));for(const[l,c]of i.getSubgraphs(a,e))yield[`${n}${Y}${l}`,c]}}}}}async*getSubgraphsAsync(t,e){yield*this.getSubgraphs(t,e)}async _prepareStateSnapshot({config:t,saved:e,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(e===void 0)return{values:{},next:[],config:t,tasks:[]};const s=gr(this.channels,e.checkpoint);if(e.pendingWrites?.length){const h=e.pendingWrites.filter(([d,f])=>d===_e).map(([d,f,p])=>[String(f),p]);h.length>0&&pe(e.checkpoint,s,[{name:Fe,writes:h,triggers:[]}],void 0,this.triggerToNodes)}const o=Object.values(Mt(e.checkpoint,e.pendingWrites,this.nodes,s,e.config,!0,{step:(e.metadata?.step??-1)+1,store:this.store})),i=await Ye(this.getSubgraphsAsync()),a=e.config.configurable?.checkpoint_ns??"",l={};for(const h of o){const d=i.find(([p])=>p===h.name);if(!d)continue;let f=`${String(h.name)}${He}${h.id}`;if(a&&(f=`${a}${Y}${f}`),n===void 0){const p={configurable:{thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}};l[h.id]=p}else{const p={configurable:{[K]:n,thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}},m=d[1];l[h.id]=await m.getState(p,{subgraphs:!0})}}if(r&&e.pendingWrites?.length){const h=Object.fromEntries(o.map(f=>[f.id,f]));for(const[f,p,m]of e.pendingWrites)[he,D,Hn].includes(p)||f in h&&h[f].writes.push([String(p),m]);const d=o.filter(f=>f.writes.length>0);d.length>0&&pe(e.checkpoint,s,d,void 0,this.triggerToNodes)}let c=e?.metadata;c&&e?.config?.configurable?.thread_id&&(c={...c,thread_id:e.config.configurable.thread_id});const u=o.filter(h=>h.writes.length===0).map(h=>h.name);return{values:yt(s,this.streamChannelsAsIs),next:u,tasks:gl(o,e?.pendingWrites??[],l,this.streamChannelsAsIs),metadata:c,config:at(e.config,e.metadata),createdAt:e.checkpoint.ts,parentConfig:e.parentConfig}}async getState(t,e){const n=t.configurable?.[K]??this.checkpointer;if(!n)throw new Xn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[K]===void 0){const a=Kr(r);for await(const[l,c]of this.getSubgraphsAsync(a,!0))if(l===a)return await c.getState(Ct(t,{[K]:n}),{subgraphs:e?.subgraphs});throw new Error(`Subgraph with namespace "${a}" not found.`)}const s=Ve(this.config,t),o=await n.getTuple(t);return await this._prepareStateSnapshot({config:s,saved:o,subgraphCheckpointer:e?.subgraphs?n:void 0,applyPendingWrites:!t.configurable?.checkpoint_id})}async*getStateHistory(t,e){const n=t.configurable?.[K]??this.checkpointer;if(!n)throw new Xn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[K]===void 0){const o=Kr(r);for await(const[i,a]of this.getSubgraphsAsync(o,!0))if(i===o){yield*a.getStateHistory(Ct(t,{[K]:n}),e);return}throw new Error(`Subgraph with namespace "${o}" not found.`)}const s=Ve(this.config,t,{configurable:{checkpoint_ns:r}});for await(const o of n.list(s,e))yield this._prepareStateSnapshot({config:o.config,saved:o})}async bulkUpdateState(t,e){const n=t.configurable?.[K]??this.checkpointer;if(!n)throw new Xn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(e.length===0)throw new Error("No supersteps provided");if(e.some(i=>i.updates.length===0))throw new Error("No updates provided");const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[K]===void 0){const i=Kr(r);for await(const[,a]of this.getSubgraphsAsync(i,!0))return await a.bulkUpdateState(Ct(t,{[K]:n}),e);throw new Error(`Subgraph "${i}" not found`)}const s=async(i,a)=>{const l=this.config?Ve(this.config,i):i,c=await n.getTuple(l),u=c!==void 0?mr(c.checkpoint):Ha(),h={...c?.checkpoint.channel_versions},d=c?.metadata?.step??-1;let f=Ct(l,{checkpoint_ns:l.configurable?.checkpoint_ns??""}),p=l.metadata??{};c?.config.configurable&&(f=Ct(l,c.config.configurable),p={...c.metadata,...p});const{values:m,asNode:S}=a[0];if(m==null&&S===void 0){if(a.length>1)throw new z("Cannot create empty checkpoint with multiple updates");const _=await n.put(f,ct(u,void 0,d),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},{});return at(_,c?c.metadata:void 0)}const C=gr(this.channels,u);if(m===null&&S===O){if(a.length>1)throw new z("Cannot apply multiple updates when clearing state");if(c){const v=Mt(u,c.pendingWrites||[],this.nodes,C,c.config,!0,{step:(c.metadata?.step??-1)+1,checkpointer:n,store:this.store}),x=(c.pendingWrites||[]).filter(T=>T[0]===_e).map(T=>T.slice(1));x.length>0&&pe(u,C,[{name:Fe,writes:x,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[T,M,P]of c.pendingWrites||[])[he,D,Hn].includes(M)||T in v&&v[T].writes.push([M,P]);pe(u,C,Object.values(v),n.getNextVersion.bind(n),this.triggerToNodes)}const _=await n.put(f,ct(u,C,d),{...p,source:"update",step:d+1,parents:c?.metadata?.parents??{}},sr(h,u.channel_versions));return at(_,c?c.metadata:void 0)}if(S===hf){if(a.length>1)throw new z("Cannot copy checkpoint with multiple updates");if(c==null)throw new z("Cannot copy a non-existent checkpoint");const _=T=>!Array.isArray(T)||T.length===0?!1:T.every(M=>Array.isArray(M)&&M.length===2),v=ct(u,void 0,d),x=await n.put(c.parentConfig??Ct(c.config,{checkpoint_id:void 0}),v,{source:"fork",step:d+1,parents:c.metadata?.parents??{}},{});if(_(m)){const T=Mt(v,c.pendingWrites,this.nodes,C,x,!1,{step:d+2}),M=Object.values(T).reduce((N,{name:oe,id:ae})=>(N[oe]??=[],N[oe].push({id:ae}),N),{}),P=m.reduce((N,oe)=>{const[ae,Ce]=oe;N[Ce]??=[];const Pe=N[Ce].length,Nn=M[Ce]?.[Pe]?.id;return N[Ce].push({values:ae,asNode:Ce,taskId:Nn}),N},{});return s(at(x,c.metadata),Object.values(P).flat())}return at(x,c.metadata)}if(S===Fe){if(a.length>1)throw new z("Cannot apply multiple updates when updating as input");const _=await Ye(pl(this.inputChannels,m));if(_.length===0)throw new z(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);pe(u,C,[{name:Fe,writes:_,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const v=c?.metadata?.step!=null?c.metadata.step+1:-1,x=await n.put(f,ct(u,C,v),{source:"input",step:v,parents:c?.metadata?.parents??{}},sr(h,u.channel_versions));return await n.putWrites(x,_,kt(Fe,u.id)),at(x,c?c.metadata:void 0)}if(l.configurable?.checkpoint_id===void 0&&c?.pendingWrites!==void 0&&c.pendingWrites.length>0){const _=Mt(u,c.pendingWrites,this.nodes,C,c.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(c.metadata?.step??-1)+1}),v=(c.pendingWrites??[]).filter(T=>T[0]===_e).map(T=>T.slice(1));v.length>0&&pe(c.checkpoint,C,[{name:Fe,writes:v,triggers:[]}],void 0,this.triggerToNodes);for(const[T,M,P]of c.pendingWrites)[he,D,Hn].includes(M)||_[T]===void 0||_[T].writes.push([M,P]);const x=Object.values(_).filter(T=>T.writes.length>0);x.length>0&&pe(u,C,x,void 0,this.triggerToNodes)}const E=Object.values(u.versions_seen).map(_=>Object.values(_)).flat().find(_=>!!_),b=[];if(a.length===1){let{values:_,asNode:v,taskId:x}=a[0];if(v===void 0&&Object.keys(this.nodes).length===1)[v]=Object.keys(this.nodes);else if(v===void 0&&E===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(v=this.inputChannels);else if(v===void 0){const T=Object.entries(u.versions_seen).map(([M,P])=>Object.values(P).map(N=>[N,M])).flat().filter(([M,P])=>P!==D).sort(([M],[P])=>Ga(M,P));T&&(T.length===1?v=T[0][1]:T[T.length-1][0]!==T[T.length-2][0]&&(v=T[T.length-1][1]))}if(v===void 0)throw new z('Ambiguous update, specify "asNode"');b.push({values:_,asNode:v,taskId:x})}else for(const{asNode:_,values:v,taskId:x}of a){if(_==null)throw new z('"asNode" is required when applying multiple updates');b.push({values:v,asNode:_,taskId:x})}const w=[];for(const{asNode:_,values:v,taskId:x}of b){if(this.nodes[_]===void 0)throw new z(`Node "${_.toString()}" does not exist`);const T=this.nodes[_].getWriters();if(!T.length)throw new z(`No writers found for node "${_.toString()}"`);w.push({name:_,input:v,proc:T.length>1?st.from(T,{omitSequenceTags:!0}):T[0],writes:[],triggers:[D],id:x??kt(D,u.id),writers:[]})}for(const _ of w)await _.proc.invoke(_.input,un({...l,store:l?.store??this.store},{runName:l.runName??`${this.getName()}UpdateState`,configurable:{[nt]:v=>_.writes.push(...v),[pt]:(v,x=!1)=>or(u,C,_,v,x)}}));for(const _ of w){const v=_.writes.filter(x=>x[0]!==me);c!==void 0&&v.length>0&&await n.putWrites(f,v,_.id)}pe(u,C,w,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const g=sr(h,u.channel_versions),k=await n.put(f,ct(u,C,d+1),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},g);for(const _ of w){const v=_.writes.filter(x=>x[0]===me);v.length>0&&await n.putWrites(k,v,_.id)}return at(k,c?c.metadata:void 0)};let o=t;for(const{updates:i}of e)o=await s(o,i);return o}async updateState(t,e,n){return this.bulkUpdateState(t,[{updates:[{values:e,asNode:n}]}])}_defaults(t){const{debug:e,streamMode:n,inputKeys:r,outputKeys:s,interruptAfter:o,interruptBefore:i,...a}=t;let l=!0;const c=e!==void 0?e:this.debug;let u=s;u===void 0?u=this.streamChannelsAsIs:Go(u,this.channels);let h=r;h===void 0?h=this.inputChannels:Go(h,this.channels);const d=i??this.interruptBefore??[],f=o??this.interruptAfter??[];let p;n!==void 0?(p=Array.isArray(n)?n:[n],l=typeof n=="string"):(t.configurable?.[hn]!==void 0?p=["values"]:p=this.streamMode,l=!0);let m;if(this.checkpointer===!1)m=void 0;else if(t!==void 0&&t.configurable?.[K]!==void 0)m=t.configurable[K];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");m=this.checkpointer}const S=t.store??this.store,C=t.cache??this.cache;if(t.durability!=null&&t.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");const E=(()=>{if(t.checkpointDuring!=null)return t.checkpointDuring===!1?"exit":"async"})(),b=t.durability??E??t?.configurable?.[tl]??"async";return[c,p,h,u,a,d,f,m,S,l,C,b]}async stream(t,e){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...e,signal:br(e?.signal,n.signal).signal},s=await super.stream(t,r);return new zo(e?.encoding==="text/event-stream"?up(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:Kf(this.config?.callbacks,e?.callbacks),signal:br(e?.signal,r.signal).signal};return new zo(super.streamEvents(t,s,n),r)}async _validateInput(t){return t}async _validateContext(t){return t}async*_streamIterator(t,e){const n="version"in(e??{})?void 0:e?.encoding??void 0,r=e?.subgraphs,s=rl(this.config,e);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 o=await this._validateInput(t),{runId:i,...a}=s,[l,c,,u,h,d,f,p,m,S,C,E]=this._defaults(a);typeof h.context<"u"?h.context=await this._validateContext(h.context):h.configurable=await this._validateContext(h.configurable);const b=new wl({modes:new Set(c)});if(this.checkpointer===!0){h.configurable??={};const M=h.configurable[Ne]??"";h.configurable[Ne]=M.split(Y).map(P=>P.split(He)[0]).join(Y)}if(c.includes("messages")){const M=new gp(N=>b.push(N)),{callbacks:P}=h;if(P===void 0)h.callbacks=[M];else if(Array.isArray(P))h.callbacks=P.concat(M);else{const N=P.copy();N.addHandler(M,!0),h.callbacks=N}}h.writer??=M=>{if(!c.includes("custom"))return;const P=bf()?.configurable?.[Ne]?.split(Y).slice(0,-1);b.push([P??[],"custom",M])},h.interrupt??=this.userInterrupt??hl;const g=await(await gu(h))?.handleChainStart(this.toJSON(),Gf(t,"input"),i,void 0,void 0,void 0,h?.runName??this.getName()),k=io(this.channels);let _,v;const T=(async()=>{try{_=await pp.initialize({input:o,config:h,checkpointer:p,nodes:this.nodes,channelSpecs:k,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:m,cache:C,stream:b,interruptAfter:f,interruptBefore:d,manager:g,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:E});const M=new Tp({loop:_,nodeFinished:h.configurable?.[ff]});e?.subgraphs&&(_.config.configurable={..._.config.configurable,[yr]:_.stream}),await this._runLoop({loop:_,runner:M,debug:l,config:h}),E==="sync"&&await Promise.all(_?.checkpointerPromises??[])}catch(M){v=M}finally{try{_&&(await _.store?.stop(),await _.cache?.stop()),await Promise.all(_?.checkpointerPromises??[])}catch(M){v=v??M}v?b.error(v):b.close()}})();try{for await(const M of b){if(M===void 0)throw new Error("Data structure error.");const[P,N,oe]=M;if(c.includes(N)){if(n==="text/event-stream"){r?yield[P,N,oe]:yield[null,N,oe];continue}r&&!S?yield[P,N,oe]:S?r?yield[P,oe]:yield oe:yield[N,oe]}}}catch(M){throw await g?.handleChainError(v),M}finally{await T}await g?.handleChainEnd(_?.output??{},i,void 0,void 0,void 0)}async invoke(t,e){const n=e?.streamMode??"values",r={...e,outputKeys:e?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},s=[],o=await this.stream(t,r),i=[];let a;for await(const l of o)n==="values"?nl(l)?i.push(l[D]):a=l:s.push(l);if(n==="values"){if(i.length>0){const l=i.flat(1);if(a==null)return{[D]:l};if(typeof a=="object")return{...a,[D]:l}}return a}return s}async _runLoop(t){const{loop:e,runner:n,debug:r,config:s}=t;let o;try{for(;await e.tick({inputKeys:this.inputChannels});){for(const{task:i}of await e._matchCachedWrites())e._outputWrites(i.id,i.writes,!0);r&&ip(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&yl(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,a)=>{r&&ap(i,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new of([`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(o=i,!await e.finishAndHandleError(o))throw i}finally{o===void 0&&await e.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}},Zt=class Cl extends bt{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new Cl(this.guard);return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0){const n=this.value.length>0;return this.value=[],n}if(e.length!==1&&this.guard)throw new z("EphemeralValue can only receive one value per step.");return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new ne;return this.value[0]}checkpoint(){if(this.value.length===0)throw new ne;return this.value[0]}isAvailable(){return this.value.length!==0}},Tl=class{path;ends;constructor(t){re.isRunnable(t.path)?this.path=t.path:this.path=Kt(t.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(t.pathMap)?t.pathMap.reduce((e,n)=>(e[n]=n,e),{}):t.pathMap}run(t,e){return ce.registerWriter(new _t({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,t,e)}catch(s){throw s.name===qa.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
50
+ NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(t,e,n,r){let s=await this.path.invoke(r?r(e):t,e);Array.isArray(s)||(s=[s]);let o;if(this.ends?o=s.map(a=>ye(a)?a:this.ends[a]):o=s,o.some(a=>!a))throw new Error("Branch condition returned unknown or null destination");if(o.filter(ye).some(a=>a.node===O))throw new z("Cannot send a packet to the END node");return await n(o,e)??t}},Pp=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(t){this.compiled&&console.warn(t)}get allEdges(){return this.edges}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,o]of n){for(const a of[Y,He])if(r.includes(a))throw new Error(`"${a}" 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===O)throw new Error(`Node \`${r}\` is reserved.`);const i=Kt(s);this.nodes[r]={runnable:i,metadata:o?.metadata,subgraphs:ho(i)?[i]:o?.subgraphs,ends:o?.ends}}return this}addEdge(t,e){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),t===O)throw new Error("END cannot be a start node");if(e===F)throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([n])=>n===t)&&!("channels"in this))throw new Error(`Already found path for ${t}. For multiple edges, use StateGraph.`);return this.edges.add([t,e]),this}addConditionalEdges(t,e,n){const r=typeof t=="object"?t:{source:t,path:e,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."),!re.isRunnable(r.path)){const o=Array.isArray(r.pathMap)?r.pathMap.join(","):Object.keys(r.pathMap??{}).join(",");r.path=Kt(r.path).withConfig({runName:`Branch<${r.source}${o!==""?`,${o}`:""}>`.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 \`${t}\``);return this.branches[r.source]??={},this.branches[r.source][s]=new Tl(r),this}setEntryPoint(t){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(F,t)}setFinishPoint(t){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(t,O)}compile({checkpointer:t,interruptBefore:e,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(e)?e:[],...Array.isArray(n)?n:[]]);const s=new kl({builder:this,checkpointer:t,interruptAfter:n,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[F]:new Zt,[O]:new Zt},inputChannels:F,outputChannels:O,streamChannels:[],streamMode:"values",name:r});for(const[o,i]of Object.entries(this.nodes))s.attachNode(o,i);for(const[o,i]of this.edges)s.attachEdge(o,i);for(const[o,i]of Object.entries(this.branches))for(const[a,l]of Object.entries(i))s.attachBranch(o,a,l);return s.validate()}validate(t){const e=new Set([...this.allEdges].map(([r,s])=>r));for(const[r]of Object.entries(this.branches))e.add(r);for(const r of e)if(r!==F&&!(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 o of Object.values(s))if(o.ends!=null)for(const i of Object.values(o.ends))n.add(i);else{n.add(O);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 lf([`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(`
51
+ `),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!==O&&!(r in this.nodes))throw new Error(`Found edge ending at unknown node \`${r}\``);if(t){for(const r of t)if(!(r in this.nodes))throw new Error(`Interrupt node \`${r}\` is not present`)}this.compiled=!0}},kl=class extends Ap{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new Zt,this.nodes[t]=new bn({channels:[],triggers:[],metadata:e.metadata,subgraphs:e.subgraphs,ends:e.ends}).pipe(e.runnable).pipe(new ce([{channel:t,value:mt}],[J])),this.streamChannels.push(t)}attachEdge(t,e){if(e===O){if(t===F)throw new Error("Cannot have an edge from START to END");this.nodes[t].writers.push(new ce([{channel:O,value:mt}],[J]))}else this.nodes[e].triggers.push(t),this.nodes[e].channels.push(t)}attachBranch(t,e,n){t===F&&!this.nodes[F]&&(this.nodes[F]=xp.subscribeTo(F,{tags:[J]})),this.nodes[t].pipe(n.run(s=>{const o=s.map(i=>ye(i)?i:{channel:i===O?O:`branch:${t}:${e}:${i}`,value:mt});return new ce(o,[J])}));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const s of r)if(s!==O){const o=`branch:${t}:${e}:${s}`;this.channels[o]=new Zt,this.nodes[s].triggers.push(o),this.nodes[s].channels.push(o)}}async getGraphAsync(t){const e=t?.xray,n=new To,r={[F]:n.addNode({schema:ke()},F)},s={};let o={};e&&(o=Object.fromEntries((await Ye(this.getSubgraphsAsync())).filter(l=>Ko(l[1]))));function i(l,c,u,h=!1){if(c===O&&s[O]===void 0&&(s[O]=n.addNode({schema:ke()},O)),r[l]!==void 0){if(s[c]===void 0)throw new Error(`End node ${c} not found!`);return n.addEdge(r[l],s[c],u!==c?u:void 0,h)}}for(const[l,c]of Object.entries(this.builder.nodes)){const u=ie(l),h=c.runnable,d=c.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?d.__interrupt="before,after":this.interruptBefore?.includes(l)?d.__interrupt="before":this.interruptAfter?.includes(l)&&(d.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,p=o[l]!==void 0?await o[l].getGraphAsync({...t,xray:f}):h.getGraph(t);if(p.trimFirstNode(),p.trimLastNode(),Object.keys(p.nodes).length>1){let C=function(b){return b?b.lc_runnable:!1},E=function(b,w){if(b!==void 0&&!ko(b))return b;if(C(w))try{let g=w.getName();return g=g.startsWith("Runnable")?g.slice(8):g,g}catch{return w.getName()}else return w.name??"UnknownSchema"};const[m,S]=n.extend(p,u);if(m===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:E(S.id,S.data),...S}),s[u]={name:E(m.id,m.data),...m}}else{const m=n.addNode(h,u,d);r[u]=m,s[u]=m}}else{const f=n.addNode(h,u,d);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(ie(l),ie(c));for(const[l,c]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(h=>h!==l).map(h=>[ie(h),ie(h)])),[O]:O};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,p]of Object.entries(d))i(ie(l),ie(p),f,!0)}}for(const[l,c]of Object.entries(this.builder.nodes))if(c.ends!==void 0)for(const u of c.ends)i(ie(l),ie(u),void 0,!0);return n}getGraph(t){const e=t?.xray,n=new To,r={[F]:n.addNode({schema:ke()},F)},s={};let o={};e&&(o=Object.fromEntries(an(this.getSubgraphs()).filter(l=>Ko(l[1]))));function i(l,c,u,h=!1){return c===O&&s[O]===void 0&&(s[O]=n.addNode({schema:ke()},O)),n.addEdge(r[l],s[c],u!==c?u:void 0,h)}for(const[l,c]of Object.entries(this.builder.nodes)){const u=ie(l),h=c.runnable,d=c.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?d.__interrupt="before,after":this.interruptBefore?.includes(l)?d.__interrupt="before":this.interruptAfter?.includes(l)&&(d.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,p=o[l]!==void 0?o[l].getGraph({...t,xray:f}):h.getGraph(t);if(p.trimFirstNode(),p.trimLastNode(),Object.keys(p.nodes).length>1){let C=function(b){return b?b.lc_runnable:!1},E=function(b,w){if(b!==void 0&&!ko(b))return b;if(C(w))try{let g=w.getName();return g=g.startsWith("Runnable")?g.slice(8):g,g}catch{return w.getName()}else return w.name??"UnknownSchema"};const[m,S]=n.extend(p,u);if(m===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:E(S.id,S.data),...S}),s[u]={name:E(m.id,m.data),...m}}else{const m=n.addNode(h,u,d);r[u]=m,s[u]=m}}else{const f=n.addNode(h,u,d);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(ie(l),ie(c));for(const[l,c]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(h=>h!==l).map(h=>[ie(h),ie(h)])),[O]:O};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,p]of Object.entries(d))i(ie(l),ie(p),f,!0)}}return n}};function Ko(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function ie(t){return t==="subgraph"?`"${t}"`:t}const dt=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var Ip=class El extends bt{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new El(this.names);return typeof e<"u"&&(n.seen=new Set(e)),n}update(e){let n=!1;for(const r of e)if(this.names.has(r))this.seen.has(r)||(this.seen.add(r),n=!0);else throw new z(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!dt(this.names,this.seen))throw new ne}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&dt(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&dt(this.names,this.seen)}},Op=class xl extends bt{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(e){super(),this.names=e,this.seen=new Set,this.finished=!1}fromCheckpoint(e){const n=new xl(this.names);if(typeof e<"u"){const[r,s]=e;n.seen=new Set(r),n.finished=s}return n}update(e){let n=!1;for(const r of e)if(this.names.has(r)&&!this.seen.has(r))this.seen.add(r),n=!0;else if(!this.names.has(r))throw new z(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!dt(this.names,this.seen))throw new ne}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&dt(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&dt(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&dt(this.names,this.seen)}};const Np="lg:";var $p=class{_map=new WeakMap;_extensionCache=new Map;get(t){return this._map.get(t)}extend(t,e){const n=this.get(t);this._map.set(t,e(n))}remove(t){return this._map.delete(t),this}has(t){return this._map.has(t)}getChannelsForSchema(t){const e={},n=cs(t);for(const[r,s]of Object.entries(n)){const o=this.get(s);o?.reducer?e[r]=new ks(o.reducer.fn,o.default):e[r]=new ao}return e}getExtendedChannelSchemas(t,e){if(Object.keys(e).length===0)return t;const n=Object.entries(e).filter(([,o])=>o===!0).sort(([o],[i])=>o.localeCompare(i)).map(([o,i])=>`${o}:${i}`).join("|"),r=this._extensionCache.get(n)??new WeakMap;if(r.has(t))return r.get(t);let s=t;if(e.withReducerSchema||e.withJsonSchemaExtrasAsDescription){const o=Object.entries(cs(t)).map(([i,a])=>{const l=this.get(a);let c=e.withReducerSchema?l?.reducer?.schema??a:a;if(e.withJsonSchemaExtrasAsDescription&&l?.jsonSchemaExtra){const u=us(c)??us(a),h=JSON.stringify({...l.jsonSchemaExtra,description:u});c=c.describe(`${Np}${h}`)}return[i,c]});s=yu(t,Object.fromEntries(o)),wu(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=Bs(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const Cn=new $p;function _r(t,e){if(e.reducer&&!e.default){const n=Vs(t);n!=null&&(e.default=n)}if(e.reducer){const n=Object.assign(t,{lg_reducer_schema:e.reducer?.schema??t});return Cn.extend(n,()=>e),n}else return Cn.extend(t,()=>e),t}const Be="__root__",Rs=Symbol.for("langgraph.state.partial");var Rp=class extends Pp{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=Cn;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),Bp(t)){const r=this._metaRegistry.getChannelsForSchema(t.state),s=t.input!=null?this._metaRegistry.getChannelsForSchema(t.input):r,o=t.output!=null?this._metaRegistry.getChannelsForSchema(t.output):r;this._schemaDefinition=r,this._schemaRuntimeDefinition=t.state,this._inputDefinition=s,this._inputRuntimeDefinition=t.input??Rs,this._outputDefinition=o,this._outputRuntimeDefinition=t.output??t.state}else if(ge(t)){const r=this._metaRegistry.getChannelsForSchema(t);this._schemaDefinition=r,this._schemaRuntimeDefinition=t,this._inputDefinition=r,this._inputRuntimeDefinition=Rs,this._outputDefinition=r,this._outputRuntimeDefinition=t}else if(Vp(t))this._schemaDefinition=t.input.spec,this._inputDefinition=t.input.spec,this._outputDefinition=t.output.spec;else if(Up(t))this._schemaDefinition=t.stateSchema.spec,this._inputDefinition=t.input?.spec??this._schemaDefinition,this._outputDefinition=t.output?.spec??this._schemaDefinition;else if(Dp(t)||Jo(t)){const r=Jo(t)?t.spec:t;this._schemaDefinition=r}else if(Fp(t)){const r=jp(t.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)&&!ge(r)}n(e)?(ge(e.context)&&(this._configRuntimeSchema=e.context),this._interrupt=e.interrupt,this._writer=e.writer):ge(e)&&(this._configRuntimeSchema=e)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([t,e])=>t.map(n=>[n,e]))])}_addSchema(t){if(!this._schemaDefinitions.has(t)){this._schemaDefinitions.set(t,t);for(const[e,n]of Object.entries(t)){let r;if(typeof n=="function"?r=n():r=n,this.channels[e]!==void 0){if(this.channels[e]!==r&&r.lc_graph_name!=="LastValue")throw new Error(`Channel "${e}" already exists with a different type.`)}else this.channels[e]=r}}}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]).map(([r,s])=>[r,s]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,o]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[Y,He])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===O||r===F)throw new Error(`Node \`${r}\` is reserved.`);let i=this._schemaDefinition;o?.input!==void 0&&(ge(o.input)?i=this._metaRegistry.getChannelsForSchema(o.input):o.input.spec!==void 0&&(i=o.input.spec)),i!==void 0&&this._addSchema(i);let a;re.isRunnable(s)?a=s:typeof s=="function"?a=new _t({func:s,name:r,trace:!1}):a=Kt(s);let l=o?.cachePolicy;typeof l=="boolean"&&(l=l?{}:void 0);const c={runnable:a,retryPolicy:o?.retryPolicy,cachePolicy:l,metadata:o?.metadata,input:i??this._schemaDefinition,subgraphs:ho(a)?[a]:o?.subgraphs,ends:o?.ends,defer:o?.defer};this.nodes[r]=c}return this}addEdge(t,e){if(typeof t=="string")return super.addEdge(t,e);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 t){if(n===O)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(e===O)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(n=>n===e))throw new Error(`Need to add a node named "${e}" first`);return this.waitingEdges.add([t,e]),this}addSequence(t){const e=Array.isArray(t)?t:Object.entries(t);if(e.length===0)throw new Error("Sequence requires at least one node.");let n;for(const[r,s,o]of e){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,o),n!=null&&this.addEdge(n,i),n=i}return this}compile({checkpointer:t,store:e,cache:n,interruptBefore:r,interruptAfter:s,name:o,description:i}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(s)?s:[]]);const a=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),l=a.length===1&&a[0]===Be?Be:a,c=Object.keys(this.channels),u=c.length===1&&c[0]===Be?Be:c,h=this._interrupt,d=new Lp({builder:this,checkpointer:t,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[F]:new Zt},inputChannels:F,outputChannels:l,streamChannels:u,streamMode:"updates",store:e,cache:n,name:o,description:i,userInterrupt:h});d.attachNode(F);for(const[f,p]of Object.entries(this.nodes))d.attachNode(f,p);d.attachBranch(F,Lo,qo(),{withReader:!1});for(const[f]of Object.entries(this.nodes))d.attachBranch(f,Lo,qo(),{withReader:!1});for(const[f,p]of this.edges)d.attachEdge(f,p);for(const[f,p]of this.waitingEdges)d.attachEdge(f,p);for(const[f,p]of Object.entries(this.branches))for(const[m,S]of Object.entries(p))d.attachBranch(f,m,S);return d.validate()}};function jp(t){const e={};for(const[n,r]of Object.entries(t))e[n]=xs(r);return e}var Lp=class extends kl{description;_metaRegistry=Cn;constructor({description:t,...e}){super(e),this.description=t}attachNode(t,e){let n;t===F?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([a])=>a):n=Object.keys(this.builder.channels);function r(a){if(Z(a))return a.graph===G.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(l=>Z(l))){const l=[];for(const c of a)if(Z(c)){if(c.graph===G.PARENT)continue;l.push(...c._updateAsTuples())}else l.push([Be,c]);return l}else if(a!=null)return[[Be,a]];return null}const s=t;function o(a){if(a){if(Z(a))return a.graph===G.PARENT?null:a._updateAsTuples().filter(([l])=>n.includes(l));if(Array.isArray(a)&&a.length>0&&a.some(Z)){const l=[];for(const c of a)if(Z(c)){if(c.graph===G.PARENT)continue;l.push(...c._updateAsTuples().filter(([u])=>n.includes(u)))}else{const u=o(c);u&&l.push(...u??[])}return l}else{if(typeof a=="object"&&!Array.isArray(a))return Object.entries(a).filter(([l])=>n.includes(l));{const l=Array.isArray(a)?"array":typeof a;throw new z(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${l}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const i=[{value:mt,mapper:new _t({func:n.length&&n[0]===Be?r:o,trace:!1,recurse:!1})}];if(t===F)this.nodes[t]=new bn({tags:[J],triggers:[F],channels:[F],writers:[new ce(i,[J])]});else{const a=e?.input??this.builder._schemaDefinition,l=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(a)).map(h=>[h,h])),c=Object.keys(l).length===1&&Be in l,u=`branch:to:${t}`;this.channels[u]=e?.defer?new cf:new Zt(!1),this.nodes[t]=new bn({triggers:[u],channels:c?Object.keys(l):l,writers:[new ce(i,[J])],mapper:c?void 0:h=>Object.fromEntries(Object.entries(h).filter(([d])=>d in l)),bound:e?.runnable,metadata:e?.metadata,retryPolicy:e?.retryPolicy,cachePolicy:e?.cachePolicy,subgraphs:e?.subgraphs,ends:e?.ends})}}attachEdge(t,e){if(e!==O){if(typeof t=="string")this.nodes[t].writers.push(new ce([{channel:`branch:to:${e}`,value:null}],[J]));else if(Array.isArray(t)){const n=`join:${t.join("+")}:${e}`;this.channels[n]=this.builder.nodes[e].defer?new Op(new Set(t)):new Ip(new Set(t)),this.nodes[e].triggers.push(n);for(const r of t)this.nodes[r].writers.push(new ce([{channel:n,value:r}],[J]))}}}attachBranch(t,e,n,r={withReader:!0}){const s=async(o,i)=>{const a=o.filter(c=>c!==O);if(!a.length)return;const l=a.map(c=>ye(c)?c:{channel:c===O?c:`branch:to:${c}`,value:t});await ce.doWrite({...i,tags:(i.tags??[]).concat([J])},l)};this.nodes[t].writers.push(n.run(s,r.withReader?o=>Bf.doRead(o,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(t){if(t==null)return t;const e=(()=>{const n=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition,s=o=>{if(o!=null)return this._metaRegistry.getExtendedChannelSchemas(o,{withReducerSchema:!0})};if(ge(n))return s(n);if(n===Rs)return Bs(s(r))})();if(Z(t)){const n=t;return t.update&&e!=null&&(n.update=et(e,t.update)),n}return e!=null?et(e,t):t}isInterrupted(t){return nl(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return ge(e)&&et(e,t),t}};function Dp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||Xa(e))}function Jo(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}function Fp(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function Up(t){return typeof t=="object"&&t!==null&&t.stateSchema!==void 0}function Vp(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function Bp(t){return!(typeof t!="object"||t==null||!("state"in t)||!ge(t.state)||"input"in t&&!ge(t.input)||"output"in t&&!ge(t.output))}function zp(t){if(ye(t))return[t];const e=[];Z(t)?e.push(t):Array.isArray(t)&&e.push(...t.filter(Z));const n=[];for(const r of e){if(r.graph===G.PARENT)throw new Ya(r);ye(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function qo(){const t=new _t({func:zp,tags:[J],trace:!1,recurse:!1,name:"<control_branch>"});return new Tl({path:t})}const Ml="__remove_all__";function Al(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(pn),o=r.map(pn);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=cr(),u.lc_kwargs.id=u.id);let i;for(let u=0;u<o.length;u+=1){const h=o[u];(h.id===null||h.id===void 0)&&(h.id=cr(),h.lc_kwargs.id=h.id),h.getType()==="remove"&&h.id===Ml&&(i=u)}if(i!=null)return o.slice(i+1);const a=[...s],l=new Map(a.map((u,h)=>[u.id,h])),c=new Set;for(const u of o){const h=l.get(u.id);if(h!==void 0)u.getType()==="remove"?c.add(u.id):(c.delete(u.id),a[h]=u);else{if(u.getType()==="remove")throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);l.set(u.id,a.length),a.push(u)}}return a.filter(u=>!c.has(u.id))}Es.Root({messages:Es({reducer:Al,default:()=>[]})});const Wp={reducer:{fn:Al},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},Hp=B({messages:_r(Se(),Wp)});sf();const js=Symbol.for("langgraph-zod");js in globalThis||(globalThis[js]=new WeakSet);function Yo(t){const e=globalThis[js];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(r){return _r(n,{jsonSchemaExtra:r})},reducer(r,s){const o=Vs(n);return _r(n,{default:o,reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{Yo(vu.prototype),Yo(pc.prototype)}catch(t){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:t})}var Gp=class extends mc{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){const n=e[0];if(n&&!n?.default){const r=Vs(t);r!=null&&(n.default=r)}return super.add(t,...e)}};new Gp(Cn);function Kp(t=!0,e,n=[]){const r={jumpTo:Ae([Re("model_request"),Re("tools"),Re("end"),bu()]).optional()},s=i=>{const a=jr(i)?cs(i):i.shape;for(const[l,c]of Object.entries(a))l.startsWith("_")||l in r||(r[l]=jr(c)?zs():c)};e&&("shape"in e||jr(e))&&s(e);for(const i of n)i.stateSchema&&s(i.stateSchema);t&&(r.structuredResponse=Q().optional());const o=_r(Se(),{jsonSchemaExtra:{langgraph_type:"messages"}});return{state:Hp.extend(r),input:B({messages:o,...Object.fromEntries(Object.entries(r).filter(([i])=>!["structuredResponse","jumpTo"].includes(i)))}),output:B({messages:o,...Object.fromEntries(Object.entries(r).filter(([i])=>i!=="jumpTo"))})}}const ts=/<name>(.*?)<\/name>/s,ns=/<content>(.*?)<\/content>/s;function Jp(t){if(!I.isInstance(t)||Gt.isInstance(t)||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new I({...t.lc_kwargs,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});const n=[];let r=0;for(const s of t.content)typeof s=="string"?(r+=1,n.push(`<name>${e}</name><content>${s}</content>`)):typeof s=="object"&&"type"in s&&s.type==="text"?(r+=1,n.push({...s,text:`<name>${e}</name><content>${s.text}</content>`})):n.push(s);return r||n.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new I({...t.lc_kwargs,content:n,name:void 0})}function qp(t){if(!I.isInstance(t)||!t.content)return t;let e=[],n;if(Array.isArray(t.content))e=t.content.filter(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(ts),o=r.text.match(ns);return s&&(!o||o[1]==="")?(n=s[1],!1):!0}return!0}).map(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(ts),o=r.text.match(ns);return!s||!o?r:(n=s[1],{...r,text:o[1]})}return r});else{const r=t.content,s=r.match(ts),o=r.match(ns);if(!s||!o)return t;n=s[1],e=o[1]}return new I({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function ut(t){return re.isRunnable(t)}function Xo(t){return Hs(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const rs=(t,e,n={})=>{if(Xo(t))return t.bindTools(e,n);if($e.isRunnableBinding(t)&&Xo(t.bound)){const r=t.bound.bindTools(e,n);return $e.isRunnableBinding(r)?new $e({bound:r.bound,config:{...t.config,...r.config},kwargs:{...t.kwargs,...r.kwargs},configFactories:r.configFactories??t.configFactories}):new $e({bound:r,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function Pl(t){if(typeof t=="function")return;let e=t;if(st.isRunnableSequence(e)&&(e=e.steps.find(n=>$e.isRunnableBinding(n))||e),!ur(e)){if($e.isRunnableBinding(e)){const n=e.kwargs!=null&&typeof e.kwargs=="object"&&"tools"in e.kwargs&&Array.isArray(e.kwargs.tools)&&e.kwargs.tools.length>0,r=e.config!=null&&typeof e.config=="object"&&"tools"in e.config&&Array.isArray(e.config.tools)&&e.config.tools.length>0;if(n||r)throw new ds}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new ds}}function Sr(t){return!!(I.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function Yp(t){if(t==null)return new te("");if(te.isInstance(t))return t;if(typeof t=="string")return new te({content:[{type:"text",text:t}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof t}`)}async function Xp(t,e,n={}){const r=rs(t,e,n);if(r)return r;if(ur(t)){const s=rs(await t._getModelInstance(),e,n);if(s)return s}if(st.isRunnableSequence(t)){const s=t.steps.findIndex(o=>$e.isRunnableBinding(o)||Hs(o)||ur(o));if(s>=0){const o=rs(t.steps[s],e,n);if(o){const i=t.steps.slice();return i.splice(s,1,o),st.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}function Zp(t){if(t.length===0)return;if(t.length===1)return t[0];function e(r,s){return async(o,i)=>r(o,async()=>s(o,async()=>i(o)))}let n=t[t.length-1];for(let r=t.length-2;r>=0;r--)n=e(t[r],n);return n}function Qp(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return Zp(e.map(n=>{const r=n.wrapToolCall;return async(o,i)=>{try{const a=await r({...o,state:{messages:o.state.messages,...n.stateSchema?et(n.stateSchema,{...o.state}):{}}},i);if(!j.isInstance(a)&&!Z(a))throw new Error(`Invalid response from "wrapToolCall" in middleware "${n.name}": expected ToolMessage or Command, got ${typeof a}`);return a}catch(a){throw a instanceof Error&&!a.message.includes(`middleware "${n.name}"`)&&(a.message=`Error in middleware "${n.name}": ${a.message}`),a}}}))}async function em(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;const s=_u(r.stateSchema,a=>a.startsWith("_")),o=await Su(s,e);if(o.success){Object.assign(n,o.data);continue}const i=o.error.issues.filter(a=>a.code==="invalid_type"&&a.message==="Required").map(a=>` - ${a.path.join(".")}: ${a.message}`).join(`
52
+ `);throw new Error(`Middleware "${r.name}" has required state fields that must be initialized:
53
+ ${i}
54
+
55
+ To fix this, either:
56
+ 1. Provide default values in your middleware's state schema using .default():
57
+ stateSchema: z.object({
58
+ myField: z.string().default("default value")
59
+ })
60
+
61
+ 2. Or make the fields optional using .optional():
62
+ stateSchema: z.object({
63
+ myField: z.string().optional()
64
+ })
65
+
66
+ 3. Or ensure you pass these values when invoking the agent:
67
+ agent.invoke({
68
+ messages: [...],
69
+ ${o.error.issues[0]?.path.join(".")}: "value"
70
+ })`)}return n}function tm(t){const e={messages:Se(()=>[]),structuredResponse:zs().optional()};if(!t)return B(e);const{shape:n}=t,r={...e};for(const[s,o]of Object.entries(n))s.startsWith("_")?r[s]=o.optional():r[s]=o;return B(r)}function Ie(t){if(t){if(["model_request","tools",O].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return O;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function Il(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var mo=class extends re{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.recurse=t.recurse??this.recurse}getState(){return this.#e}setState(t){this.#e={...this.#e,...t}}async invoke(t,e){const n=Ve(this.config,e),r=await ze.runWithConfig(n,async()=>this.func(t,n));return re.isRunnable(r)&&this.recurse?await ze.runWithConfig(n,async()=>r.invoke(t,n)):(this.#e=r,r)}};function nm(t,e){let n,r;if(e==="inline")n=Jp,r=qp;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(o){return o.map(n)}return st.from([lr.from(s),t,lr.from(r)])}function rm(t){return I.isInstance(t)||typeof t=="object"&&t!==null&&"structuredResponse"in t&&"messages"in t}const H="model_request";var sm=class extends mo{#e;#r;#t;constructor(t){super({name:t.name??"model",func:(e,n)=>this.#s(e,n)}),this.#e=t,this.#r=t.systemMessage}#n(t){if(!this.#e.responseFormat)return;const e=Ai(this.#e.responseFormat,void 0,t);return e.every(r=>r instanceof Xe)?{type:"native",strategy:e[0]}:{type:"tool",tools:e.filter(r=>r instanceof Je).reduce((r,s)=>(r[s.name]=s,r),{})}}async#s(t,e){const n=t.messages.at(-1);if(n&&j.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return{messages:[]};const r=await this.#c(t,e);return"structuredResponse"in r?{messages:[...t.messages,...r.messages||[]],structuredResponse:r.structuredResponse}:r instanceof G?r:(r.name=this.name,r.lc_kwargs.name=this.name,this.#h(t,r)?{messages:[new I({content:"Sorry, need more steps to process this request.",name:this.name,id:r.id})]}:{messages:[r]})}#l(){if(typeof this.#e.model=="string")return it(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(t,e,n={}){const r=await this.#l(),s=e,o=async c=>{Pl(c.model);const u=this.#n(c.model),h=await this.#a(c.model,c,u),d=[...this.#t.text===""?[]:[this.#t],...c.messages],f=Il(this.#e.signal,e.signal),p=await Cu(h.invoke(d,{...e,signal:f}),f);if(u?.type==="native"){const E=u.strategy.parse(p);return E?{structuredResponse:E,messages:[p]}:p}if(!u||!p.tool_calls)return p;const m=p.tool_calls.filter(E=>E.name in u.tools);if(m.length===0)return p;if(m.length>1)return this.#u(p,m,u);const C=u.tools[m[0].name]?.options?.toolMessageContent;return this.#o(p,m[0],u,C??n.lastMessage)},i=this.#e.wrapModelCallHookMiddleware??[];let a=o;for(let c=i.length-1;c>=0;c--){const[u,h]=i[c];if(u.wrapModelCall){const d=a,f=u,p=h;a=async m=>{const S=f.contextSchema?et(f.contextSchema,s?.context||{}):s?.context,C=Object.freeze({context:S,writer:s.writer,interrupt:s.interrupt,signal:s.signal}),E={...m,state:{...u.stateSchema?et(Bs(u.stateSchema),t):{},...p(),messages:t.messages},runtime:C},b=async w=>{const g=w.tools??[],k=g.filter(M=>ut(M)&&!this.#e.toolClasses.some(P=>P.name===M.name));if(k.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${f.name}": ${k.map(M=>M.name).join(", ")}. This is not supported.`);const _=g.filter(M=>ut(M)&&this.#e.toolClasses.every(P=>P!==M));if(_.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${f.name}": ${_.map(M=>M.name).join(", ")}. This is not supported.`);let v=w;const x=w.systemPrompt!==this.#t.text,T=w.systemMessage!==this.#t;if(x&&T)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");return x&&(this.#t=new te({content:[{type:"text",text:w.systemPrompt}]}),v={...w,systemPrompt:this.#t.text,systemMessage:this.#t}),T&&(this.#t=new te({...w.systemMessage}),v={...w,systemPrompt:this.#t.text,systemMessage:this.#t}),d(v)};if(!f.wrapModelCall)return b(E);try{const w=await f.wrapModelCall(E,b);if(!rm(w))throw new Error(`Invalid response from "wrapModelCall" in middleware "${f.name}": expected AIMessage, got ${typeof w}`);return w}catch(w){throw w instanceof Error&&!w.message.includes(`middleware "${f.name}"`)&&(w.message=`Error in middleware "${f.name}": ${w.message}`),w}}}}this.#t=this.#r;const l={model:r,systemPrompt:this.#t?.text,systemMessage:this.#t,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:s?.context,writer:s.writer,interrupt:s.interrupt,signal:s.signal})};return a(l)}#u(t,e,n){const r=new fs(e.map(s=>s.name));return this.#i(r,t,e[0],n)}#o(t,e,n,r){const s=n.tools[e.name];try{const o=s.parse(e.args);return{structuredResponse:o,messages:[t,new j({tool_call_id:e.id??"",content:JSON.stringify(o),name:e.name}),new I(r??`Returning structured response: ${JSON.stringify(o)}`)]}}catch(o){return this.#i(o,t,e,n)}}async#i(t,e,n,r){const s=Object.values(r.tools).at(0)?.options?.handleError,o=n.id;if(!o)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(s===!1)throw t;if(s===void 0||typeof s=="boolean"&&s||Array.isArray(s)&&s.some(i=>i instanceof fs))return new G({update:{messages:[e,new j({content:t.message,tool_call_id:o})]},goto:H});if(typeof s=="string")return new G({update:{messages:[e,new j({content:s,tool_call_id:o})]},goto:H});if(typeof s=="function"){const i=await s(t);if(typeof i!="string")throw new Error("Error handler must return a string.");return new G({update:{messages:[e,new j({content:i,tool_call_id:o})]},goto:H})}return new G({update:{messages:[e,new j({content:t.message,tool_call_id:o})]},goto:H})}#h(t,e){const n=I.isInstance(e)&&e.tool_calls?.every(s=>this.#e.shouldReturnDirect.has(s.name)),r="remainingSteps"in t?t.remainingSteps:void 0;return!!(r&&(r<1&&n||r<2&&Sr(t.messages.at(-1))))}async#a(t,e,n){const r={},s=Object.values(n&&"tools"in n?n.tools:{}),o=[...e?.tools??this.#e.toolClasses,...s.map(c=>c.tool)],i=e?.toolChoice||(s.length>0?"any":void 0);if(n?.type==="native"){const c=e?.modelSettings?.strict??n?.strategy?.strict??!0,u={name:n.strategy.schema?.name??"extract",description:us(n.strategy.schema),schema:n.strategy.schema,strict:c};Object.assign(r,{response_format:{type:"json_schema",json_schema:u},output_format:{type:"json_schema",schema:n.strategy.schema},headers:{"anthropic-beta":"structured-outputs-2025-11-13"},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:n.strategy.schema},strict:c})}const a=await Xp(t,o,{...r,...e?.modelSettings??{},tool_choice:i});return this.#e.includeAgentName==="inline"?nm(a,this.#e.includeAgentName):a}getState(){const t=super.getState(),e=t&&!(t instanceof G)?t:{};return{messages:[],...e}}};const W="tools",Ol=t=>Array.isArray(t)&&t.every(cn.isInstance),om=t=>typeof t=="object"&&t!=null&&"messages"in t&&Ol(t.messages),im=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function am(t,e){return t instanceof Ws?new j({content:t.message,tool_call_id:e.id,name:e.name}):new j({content:`${t}
71
+ Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var lm=class extends mo{tools;trace=!1;signal;handleToolErrors=am;wrapToolCall;constructor(t,e){const{name:n,tags:r,handleToolErrors:s,signal:o,wrapToolCall:i}=e??{};super({name:n,tags:r,func:(a,l)=>this.run(a,l)}),this.options=e,this.tools=t,this.handleToolErrors=s??this.handleToolErrors,this.signal=o,this.wrapToolCall=i}#e(t,e,n){if(ht(t)||this.signal?.aborted||n&&this.handleToolErrors!==!0||!this.handleToolErrors)throw t;if(typeof this.handleToolErrors=="function"){const r=this.handleToolErrors(t,e);if(r&&j.isInstance(r))return r;throw t}else if(this.handleToolErrors)return new j({name:e.name,content:`${t}
72
+ Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,n){const r=async l=>{const{toolCall:c}=l,u=this.tools.find(h=>h.name===c.name);if(u===void 0)throw new Error(`Tool "${c.name}" not found.`);try{const h=await u.invoke({...c,type:"tool_call"},{...e,config:e,toolCallId:c.id,state:e.configurable?.__pregel_scratchpad?.currentTaskInput,signal:Il(this.signal,e.signal)});return j.isInstance(h)||Z(h)?h:new j({name:u.name,content:typeof h=="string"?h:JSON.stringify(h),tool_call_id:c.id})}catch(h){throw h instanceof Tu?new Ws(h,c):h}},s=e,o={context:s?.context,writer:s?.writer,interrupt:s?.interrupt,signal:s?.signal},i=this.tools.find(l=>l.name===t.name);if(!i)throw new Error(`Tool "${t.name}" not found.`);const a={toolCall:t,tool:i,state:n,runtime:o};if(this.wrapToolCall)try{return await this.wrapToolCall(a,r)}catch(l){return this.#e(l,t,!0)}try{return await r(a)}catch(l){return this.#e(l,t,!1)}}async run(t,e){let n;if(im(t)){const{lg_tool_call:o,jumpTo:i,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let o;if(Ol(t))o=t;else if(om(t))o=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const i=new Set(o.filter(l=>l.getType()==="tool").map(l=>l.tool_call_id));let a;for(let l=o.length-1;l>=0;l-=1){const c=o[l];if(I.isInstance(c)){a=c;break}}if(!I.isInstance(a))throw new Error("ToolNode only accepts AIMessages as input.");n=await Promise.all(a.tool_calls?.filter(l=>l.id==null||!i.has(l.id)).map(l=>this.runTool(l,e,t))??[])}if(!n.some(Z))return Array.isArray(t)?n:{messages:n};const r=[];let s=null;for(const o of n)Z(o)?o.graph===G.PARENT&&Array.isArray(o.goto)&&o.goto.every(i=>cm(i))?s?s.goto.push(...o.goto):s=new G({graph:G.PARENT,goto:o.goto}):r.push(o):r.push(Array.isArray(t)?[o]:{messages:[o]});return s&&r.push(s),r}};function cm(t){return t instanceof le}var um=class{},hm=class{},Ir=class extends mo{#e;constructor(t,e){super(t),this.#e=e}async invokeMiddleware(t,e){let n={};if(this.middleware.contextSchema){const l=this.middleware.contextSchema?.shape;if(l){const c={},u=e?.context||{};for(const h of Object.keys(l))h in u&&(c[h]=u[h]);n=et(this.middleware.contextSchema,c)}}const r={...this.#e.getState(),...t,messages:t.messages},s={context:n,writer:e?.writer,interrupt:e?.interrupt,signal:e?.signal},o=await this.runHook(r,Object.freeze(Object.assign(new hm,{...s,context:Object.freeze(Object.assign(new um,n))})));if(!o)return{...r,jumpTo:void 0};let i,a;if(this.name?.startsWith("BeforeAgentNode_")?(i=Ze(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=Ze(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=Ze(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=Ze(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof o.jumpTo=="string"&&!i?.includes(o.jumpTo)){const l=i&&i.length>0?`must be one of: ${i?.join(", ")}.`:a?`no ${a} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${o.jumpTo}, ${l}.`)}if(typeof o=="object"&&"type"in o){if(o.type==="terminate"){if(o.error)throw o.error;return{...r,...o.result||{},jumpTo:o.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(o)}`)}return{...r,...o,jumpTo:o.jumpTo}}get nodeOptions(){return{input:tm(this.middleware.stateSchema)}}},dm=class extends Ir{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(t,e){super({name:`BeforeAgentNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Mr(this.middleware.beforeAgent)(t,e)}},fm=class extends Ir{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(t,e){super({name:`BeforeModelNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Mr(this.middleware.beforeModel)(t,e)}},pm=class extends Ir{lc_namespace=["langchain","agents","afterModelNodes"];constructor(t,e){super({name:`AfterModelNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Mr(this.middleware.afterModel)(t,e)}},mm=class extends Ir{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(t,e){super({name:`AfterAgentNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Mr(this.middleware.afterAgent)(t,e)}},gm=class{#e=new Map;addNode(t,e){this.#e.set(t.name,[...this.#e.get(t.name)??[],e])}getState(t){const n=(this.#e.get(t)??[]).reduce((r,s)=>({...r,...s.getState()??{}}),{});return delete n.jumpTo,n}},ym=class{#e;#r="v2";#t;#n=new gm;constructor(t){if(this.options=t,this.#r=t.version??this.#r,!t.model)throw new Error("`model` option is required to create an agent.");typeof t.model!="string"&&Pl(t.model);const e=this.options.middleware?.filter(g=>g.tools).flatMap(g=>g.tools)??[],n=[...t.tools??[],...e],r=new Set(n.filter(ut).filter(g=>"returnDirect"in g&&g.returnDirect).map(g=>g.name)),{state:s,input:o,output:i}=Kp(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),l=new Rp({state:s,input:o,output:i},this.options.contextSchema),c=[],u=[],h=[],d=[],f=[];this.#t=new sm({model:this.options.model,systemMessage:Yp(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:f});const p=new Set,m=this.options.middleware??[];for(let g=0;g<m.length;g++){let k,_,v,x;const T=m[g];if(p.has(T.name))throw new Error(`Middleware ${T.name} is defined multiple times`);if(p.add(T.name),T.beforeAgent){k=new dm(T,{getState:()=>this.#n.getState(T.name)}),this.#n.addNode(T,k);const M=`${T.name}.before_agent`;c.push({index:g,name:M,allowed:Ze(T.beforeAgent)}),l.addNode(M,k,k.nodeOptions)}if(T.beforeModel){_=new fm(T,{getState:()=>this.#n.getState(T.name)}),this.#n.addNode(T,_);const M=`${T.name}.before_model`;u.push({index:g,name:M,allowed:Ze(T.beforeModel)}),l.addNode(M,_,_.nodeOptions)}if(T.afterModel){v=new pm(T,{getState:()=>this.#n.getState(T.name)}),this.#n.addNode(T,v);const M=`${T.name}.after_model`;h.push({index:g,name:M,allowed:Ze(T.afterModel)}),l.addNode(M,v,v.nodeOptions)}if(T.afterAgent){x=new mm(T,{getState:()=>this.#n.getState(T.name)}),this.#n.addNode(T,x);const M=`${T.name}.after_agent`;d.push({index:g,name:M,allowed:Ze(T.afterAgent)}),l.addNode(M,x,x.nodeOptions)}T.wrapModelCall&&f.push([T,()=>this.#n.getState(T.name)])}if(l.addNode(H,this.#t),n.filter(ut).length>0){const g=new lm(n.filter(ut),{signal:this.options.signal,wrapToolCall:Qp(m)});l.addNode(W,g)}let S;c.length>0?S=c[0].name:u.length>0?S=u[0].name:S=H;const C=u.length>0?u[0].name:H,E=d.length>0?d[d.length-1].name:O;l.addEdge(F,S);const b=n.filter(ut);for(let g=0;g<c.length;g++){const k=c[g],_=k.name,x=g===c.length-1?C:c[g+1].name;if(k.allowed&&k.allowed.length>0){const T=b.length>0,M=k.allowed.map(N=>Ie(N)).filter(N=>N!==W||T),P=Array.from(new Set([x,...M.map(N=>N===O?E:N)]));l.addConditionalEdges(_,this.#i(b,x,E),P)}else l.addEdge(_,x)}for(let g=0;g<u.length;g++){const k=u[g],_=k.name,x=g===u.length-1?H:u[g+1].name;if(k.allowed&&k.allowed.length>0){const T=b.length>0,M=k.allowed.map(N=>Ie(N)).filter(N=>N!==W||T),P=Array.from(new Set([x,...M]));l.addConditionalEdges(_,this.#h(b,x),P)}else l.addEdge(_,x)}const w=h.at(-1);if(h.length>0&&w)l.addEdge(H,w.name);else{const k=this.#s(b).map(_=>_===O?E:_);k.length===1?l.addEdge(H,k[0]):l.addConditionalEdges(H,this.#c(E),k)}for(let g=h.length-1;g>0;g--){const k=h[g],_=k.name,v=h[g-1].name;if(k.allowed&&k.allowed.length>0){const x=b.length>0,T=k.allowed.map(P=>Ie(P)).filter(P=>P!==W||x),M=Array.from(new Set([v,...T]));l.addConditionalEdges(_,this.#o(b,k.allowed,v),M)}else l.addEdge(_,v)}if(h.length>0){const g=h[0],k=g.name,_=this.#s(b,!0).filter(T=>T!==W||n.filter(ut).length>0),v=!!(g.allowed&&g.allowed.length>0),x=_.map(T=>T===O?E:T);l.addConditionalEdges(k,this.#u(b,v,E),x)}for(let g=d.length-1;g>0;g--){const k=d[g],_=k.name,v=d[g-1].name;if(k.allowed&&k.allowed.length>0){const x=b.length>0,T=k.allowed.map(P=>Ie(P)).filter(P=>P!==W||x),M=Array.from(new Set([v,...T]));l.addConditionalEdges(_,this.#o(b,k.allowed,v),M)}else l.addEdge(_,v)}if(d.length>0){const g=d[0],k=g.name;if(g.allowed&&g.allowed.length>0){const _=b.length>0,v=g.allowed.map(T=>Ie(T)).filter(T=>T!==W||_),x=Array.from(new Set([O,...v]));l.addConditionalEdges(k,this.#o(b,g.allowed,O),x)}else l.addEdge(k,O)}if(b.length>0){const g=C;r.size>0?l.addConditionalEdges(W,this.#l(r,E),[g,E]):l.addEdge(W,g)}this.#e=l.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#s(t,e=!1){const n=[];return t.length>0&&n.push(W),e&&n.push(H),n.push(O),n}#l(t,e){return n=>{const s=n.messages,o=s[s.length-1];return j.isInstance(o)&&o.name&&t.has(o.name)?this.options.responseFormat?H:e:H}}#c(t=O){return e=>{const s=e.messages.at(-1);if(!I.isInstance(s)||!s.tool_calls||s.tool_calls.length===0||s.tool_calls.every(a=>a.name.startsWith("extract-")))return t;if(this.#r==="v1")return W;const i=s.tool_calls.filter(a=>!a.name.startsWith("extract-"));return i.length===0?t:i.map(a=>new le(W,{...e,lg_tool_call:a}))}}#u(t,e,n){const r=!!this.options.responseFormat;return s=>{const o=s,i=o.messages,a=i.at(-1);if(I.isInstance(a)&&(!a.tool_calls||a.tool_calls.length===0))return n;if(e&&o.jumpTo){const p=Ie(o.jumpTo);return p===O?n:p===W?t.length===0?n:new le(W,{...s,jumpTo:void 0}):new le(H,{...s,jumpTo:void 0})}const l=i.filter(j.isInstance),c=i.filter(I.isInstance).at(-1),u=c?.tool_calls?.filter(p=>!l.some(m=>m.tool_call_id===p.id));if(u&&u.length>0)return u.map(p=>new le(W,{...s,lg_tool_call:p}));const h=c?.tool_calls?.some(p=>p.name.startsWith("extract-"));if(u&&u.length===0&&!h&&r)return H;if(!I.isInstance(a)||!a.tool_calls||a.tool_calls.length===0)return n;const d=a.tool_calls.every(p=>p.name.startsWith("extract-")),f=a.tool_calls.some(p=>!p.name.startsWith("extract-"));return d||!f?n:W}}#o(t,e,n){const r=new Set(e.map(s=>Ie(s)));return s=>{const o=s;if(o.jumpTo){const i=Ie(o.jumpTo);if(i===O&&r.has(O))return O;if(i===W&&r.has(W))return t.length===0?O:new le(W,{...s,jumpTo:void 0});if(i===H&&r.has(H))return new le(H,{...s,jumpTo:void 0})}return n}}#i(t,e,n){return r=>{const s=r;if(!s.jumpTo)return e;const o=Ie(s.jumpTo);return o===O?n:o===W?t.length===0?n:new le(W,{...r,jumpTo:void 0}):new le(H,{...r,jumpTo:void 0})}}#h(t,e){return n=>{const r=n;if(!r.jumpTo)return e;const s=Ie(r.jumpTo);return s===O?O:s===W?t.length===0?O:new le(W,{...n,jumpTo:void 0}):new le(H,{...n,jumpTo:void 0})}}async#a(t,e){if(!this.options.middleware||this.options.middleware.length===0||t instanceof G||!t)return t;const n=await em(this.options.middleware,t),s={...(await this.#e.getState(e).catch(()=>({values:{}}))).values,...t};if(!s)return s;for(const[o,i]of Object.entries(n))o in s||(s[o]=i);return s}async invoke(t,e){const n=await this.#a(t,e);return this.#e.invoke(n,e)}async stream(t,e){const n=await this.#a(t,e);return this.#e.stream(n,e)}async drawMermaidPng(t){const r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(t)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(t){return(await this.#e.getGraphAsync()).drawMermaid(t)}streamEvents(t,e,n){return this.#e.streamEvents(t,{...e,version:e?.version??"v2"},n)}getGraphAsync(t){return this.#e.getGraphAsync(t)}getState(t,e){return this.#e.getState(t,e)}getStateHistory(t,e){return this.#e.getStateHistory(t,e)}getSubgraphs(t,e){return this.#e.getSubgraphs(t,e)}getSubgraphAsync(t,e){return this.#e.getSubgraphsAsync(t,e)}updateState(t,e,n){return this.#e.updateState(t,e,n)}get builder(){return this.#e.builder}};function Nl(t){return new ym(t)}const wm=Mn().args(Se(),Se(),Se()).returns(Ae([Q(),wi(Q())])),$l=["approve","edit","reject"],vm=Jt($l),bm=B({allowedDecisions:Ge(vm),description:Ae([Q(),wm]).optional(),argsSchema:mn(zs()).optional()}),Zo=B({interruptOn:mn(Ae([ft(),bm])).optional(),descriptionPrefix:Q().default("Tool execution requires approval")});function _m(t){const e=async(r,s,o,i)=>{const a=r.name,l=r.args,c=s.description;let u;typeof c=="function"?u=await c(r,o,i):c!==void 0?u=c:u=`${t.descriptionPrefix??"Tool execution requires approval"}
73
+
74
+ Tool: ${a}
75
+ Args: ${JSON.stringify(l,null,2)}`;const h={name:a,args:l,description:u},d={actionName:a,allowedDecisions:s.allowedDecisions};return s.argsSchema&&(d.argsSchema=s.argsSchema),{actionRequest:h,reviewConfig:d}},n=(r,s,o)=>{const i=o.allowedDecisions;if(r.type==="approve"&&i.includes("approve"))return{revisedToolCall:s,toolMessage:null};if(r.type==="edit"&&i.includes("edit")){const l=r.editedAction;if(!l||typeof l.name!="string")throw new Error(`Invalid edited action for tool "${s.name}": name must be a string`);if(!l.args||typeof l.args!="object")throw new Error(`Invalid edited action for tool "${s.name}": args must be an object`);return{revisedToolCall:{type:"tool_call",name:l.name,args:l.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 l=r.message??`User rejected the tool call for \`${s.name}\` with id ${s.id}`,c=new j({content:l,name:s.name,tool_call_id:s.id,status:"error"});return{revisedToolCall:s,toolMessage:c}}const a=`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(a)};return se({name:"HumanInTheLoopMiddleware",contextSchema:Zo,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const o=et(Zo,{...t,...s.context||{}});if(!o)return;const{messages:i}=r;if(!i.length)return;const a=[...i].reverse().find(w=>I.isInstance(w));if(!a||!a.tool_calls?.length||!o.interruptOn)return;const l={};for(const[w,g]of Object.entries(o.interruptOn))typeof g=="boolean"?g===!0&&(l[w]={allowedDecisions:[...$l]}):g.allowedDecisions&&(l[w]=g);const c=[],u=[];for(const w of a.tool_calls)w.name in l?c.push(w):u.push(w);if(!c.length)return;const h=[],d=[];for(const w of c){const g=l[w.name],{actionRequest:k,reviewConfig:_}=await e(w,g,r,s);h.push(k),d.push(_)}const m=(await hl({actionRequests:h,reviewConfigs:d})).decisions;if(!m||!Array.isArray(m))throw new Error("Invalid HITLResponse: decisions must be a non-empty array");if(m.length!==c.length)throw new Error(`Number of human decisions (${m.length}) does not match number of hanging tool calls (${c.length}).`);const S=[...u],C=[],E=m.some(w=>w.type==="reject");for(let w=0;w<m.length;w++){const g=m[w],k=c[w],_=l[k.name],{revisedToolCall:v,toolMessage:x}=n(g,k,_);v&&(!E||g.type==="reject")&&S.push(v),x&&C.push(x)}I.isInstance(a)&&(a.tool_calls=S);const b=E?"model":void 0;return{messages:[a,...C],jumpTo:b}}}})}const ir=`<role>
76
+ Context Extraction Assistant
77
+ </role>
78
+
79
+ <primary_objective>
80
+ Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
81
+ </primary_objective>
82
+
83
+ <objective_information>
84
+ 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.
85
+ 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.
86
+ </objective_information>
87
+
88
+ <instructions>
89
+ 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.
90
+ 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.
91
+ </instructions>
92
+
93
+ 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:
94
+
95
+ 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.
96
+ Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
97
+
98
+ <messages>
99
+ Messages to summarize:
100
+ {messages}
101
+ </messages>`,Sm="Here is a summary of the conversation to date:",Cr=20,Cm=4e3,Qo=5,Tm=Mn().args(Ge(Se())).returns(Ae([V(),wi(V())])),Qt=B({fraction:V().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:V().positive("Tokens must be greater than 0").optional(),messages:V().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(n=>n!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),go=B({fraction:V().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:V().min(0,"Tokens must be greater than or equal to 0").optional(),messages:V().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(n=>n!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),ei=B({model:Se(),trigger:Ae([Qt,Ge(Qt)]).optional(),keep:go.optional(),tokenCounter:Tm.optional(),summaryPrompt:Q().default(ir),trimTokensToSummarize:V().optional(),summaryPrefix:Q().optional(),maxTokensBeforeSummary:V().optional(),messagesToKeep:V().optional()});function Tn(t){if("profile"in t&&typeof t.profile=="object"&&t.profile&&"maxInputTokens"in t.profile&&(typeof t.profile.maxInputTokens=="number"||t.profile.maxInputTokens==null))return t.profile.maxInputTokens??void 0;if("model"in t&&typeof t.model=="string")return _o(t.model);if("modelName"in t&&typeof t.modelName=="string")return _o(t.modelName)}function km(t){const{data:e,error:n}=ku(ei,t);if(n)throw new Error(`Invalid summarization middleware options: ${Ds(n)}`);return se({name:"SummarizationMiddleware",contextSchema:ei.extend({model:Se().optional()}),beforeModel:async(r,s)=>{let o=e.trigger,i=e.keep;e.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),o===void 0&&(o={tokens:e.maxTokensBeforeSummary})),e.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!i||i&&"messages"in i&&i.messages===Cr)&&(i={messages:e.messagesToKeep}));const a=s.context?.trigger!==void 0?s.context.trigger:o,l=s.context?.keep!==void 0?s.context.keep:i??{messages:Cr},c=go.parse(l);let u=[];a===void 0?u=[]:Array.isArray(a)?u=a.map(T=>Qt.parse(T)):u=[Qt.parse(a)];const h=u.some(T=>"fraction"in T)||"fraction"in c,d=typeof e.model=="string"?await it(e.model):e.model;if(h&&!Tn(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const f=s.context?.summaryPrompt===ir?e.summaryPrompt??ir:s.context?.summaryPrompt??e.summaryPrompt??ir,p=s.context.summaryPrefix??e.summaryPrefix??Sm,m=s.context?.trimTokensToSummarize!==void 0?s.context.trimTokensToSummarize:e.trimTokensToSummarize??Cm;Em(r.messages);const S=s.context?.tokenCounter!==void 0?s.context.tokenCounter:e.tokenCounter??Gs,C=await S(r.messages);if(!await Am(r.messages,C,u,d))return;const{systemPrompt:b,conversationMessages:w}=xm(r.messages),g=await Pm(w,c,S,d);if(g<=0)return;const{messagesToSummarize:k,preservedMessages:_}=Mm(b,w,g),v=await Nm(k,d,f,S,m),x=new ee({content:`${p}
102
+
103
+ ${v}`,id:cr()});return{messages:[new zn({id:Ml}),x,..._]}}})}function Em(t){for(const e of t)e.id||(e.id=cr())}function xm(t){return t.length>0&&te.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function Mm(t,e,n){const r=e.slice(0,n),s=e.slice(n);return t&&r.unshift(t),{messagesToSummarize:r,preservedMessages:s}}async function Am(t,e,n,r){if(n.length===0)return!1;for(const s of n){let o=!0,i=!1;if(s.messages!==void 0&&(i=!0,t.length<s.messages&&(o=!1)),s.tokens!==void 0&&(i=!0,e<s.tokens&&(o=!1)),s.fraction!==void 0){i=!0;const a=Tn(r);if(typeof a=="number"){const l=Math.floor(a*s.fraction);e<l&&(o=!1)}else o=!1}if(i&&o)return!0}return!1}async function Pm(t,e,n,r){if("tokens"in e||"fraction"in e){const s=await Im(t,e,n,r);return typeof s=="number"?s:ti(t,Cr)}return ti(t,e.messages??Cr)}async function Im(t,e,n,r){if(t.length===0)return 0;let s;if("fraction"in e&&e.fraction!==void 0){const h=Tn(r);if(typeof h!="number")return;s=Math.floor(h*e.fraction)}else if("tokens"in e&&e.tokens!==void 0)s=Math.floor(e.tokens);else return;if(s<=0&&(s=1),await n(t)<=s)return 0;let i=0,a=t.length,l=t.length;const c=Math.floor(Math.log2(t.length))+1;for(let h=0;h<c&&!(i>=a);h++){const d=Math.floor((i+a)/2);await n(t.slice(d))<=s?(l=d,a=d):i=d+1}if(l===t.length&&(l=i),l>=t.length){if(t.length===1)return 0;l=t.length-1}const u=Ll(t,l);if(u<=l)return u;for(let h=l;h>=0;h--)if(Rl(t,h))return h;return 0}function ti(t,e){if(t.length<=e)return 0;const n=t.length-e,r=Ll(t,n);if(r<=n)return r;for(let s=n;s>=0;s--)if(Rl(t,s))return s;return 0}function Rl(t,e){if(e>=t.length)return!0;if(e<t.length&&I.isInstance(t[e])&&Sr(t[e]))return!1;const n=Math.max(0,e-Qo),r=Math.min(t.length,e+Qo);for(let s=n;s<r;s++){if(!Sr(t[s]))continue;const o=jl(t[s]);if(Om(t,s,e,o))return!1}return!0}function jl(t){const e=new Set;if(t.tool_calls)for(const n of t.tool_calls){const r=typeof n=="object"&&"id"in n?n.id:null;r&&e.add(r)}return e}function Ll(t,e){if(e>=t.length||!j.isInstance(t[e]))return e;const n=new Set;let r=e;for(;r<t.length&&j.isInstance(t[r]);){const s=t[r];s.tool_call_id&&n.add(s.tool_call_id),r++}for(let s=e-1;s>=0;s--){const o=t[s];if(I.isInstance(o)&&Sr(o)){const i=jl(o);for(const a of n)if(i.has(a))return s}}return r}function Om(t,e,n,r){for(let s=e+1;s<t.length;s++){const o=t[s];if(j.isInstance(o)&&r.has(o.tool_call_id)){const i=e<n,a=s<n;if(i!==a)return!0}}return!1}async function Nm(t,e,n,r,s){if(!t.length)return"No previous conversation history.";const o=await $m(t,r,s);if(!o.length)return"Previous conversation was too long to summarize.";const i=Eu(o);try{const a=n.replace("{messages}",i),c=(await e.invoke(a,{callbacks:[]})).content;return typeof c=="string"?c.trim():Array.isArray(c)?c.map(h=>typeof h=="string"?h:typeof h=="object"&&h!==null&&"text"in h?h.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(a){return`Error generating summary: ${a}`}}async function $m(t,e,n){if(n===void 0)return t;try{return await vi(t,{maxTokens:n,tokenCounter:async r=>e(r),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-15)}}function Rm(t){return se({name:"DynamicSystemPromptMiddleware",wrapModelCall:async(e,n)=>{const r=await t(e.state,e.runtime);if(!(typeof r=="string"||te.isInstance(r)))throw new Error("dynamicSystemPromptMiddleware function must return a string or SystemMessage");return n({...e,systemMessage:e.systemMessage.concat(r)})}})}const jm="Your goal is to select the most relevant tools for answering the user's query.";function Lm(t){if(!t||t.length===0)throw new Error("Invalid usage: tools must be non-empty");const e=t.map(r=>Re(r.name)),n=Ae(e);return B({tools:Ge(n).describe("Tools to use. Place the most relevant tools first.")})}const Dm=B({model:Q().or(An(Dc)).optional(),systemPrompt:Q().optional(),maxTools:V().optional(),alwaysInclude:Ge(Q()).optional()});function Fm(t){return se({name:"LLMToolSelector",contextSchema:Dm,async wrapModelCall(e,n){const r=await Um(e,t,e.runtime);if(!r)return n(e);const s=Lm(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(Vm(i,r.availableTools,r.validToolNames,e,t))}})}async function Um(t,e,n){const r=n.context.model??e.model,s=n.context.maxTools??e.maxTools,o=n.context.alwaysInclude??e.alwaysInclude??[],i=n.context.systemPrompt??e.systemPrompt??jm;if(!t.tools||t.tools.length===0)return;const a=t.tools.filter(f=>typeof f=="object"&&"name"in f&&"description"in f&&typeof f.name=="string");if(o.length>0){const f=new Set(a.map(m=>m.name)),p=o.filter(m=>!f.has(m));if(p.length>0)throw new Error(`Tools in alwaysInclude not found in request: ${p.join(", ")}. Available tools: ${Array.from(f).sort().join(", ")}`)}const l=a.filter(f=>!o.includes(f.name));if(l.length===0)return;let c=i;s!==void 0&&(c+=`
104
+ 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 f of t.messages)ee.isInstance(f)&&(u=f);if(!u)throw new Error("No user message found in request messages");const h=r?typeof r=="string"?await it(r):r:t.model,d=l.map(f=>f.name);return{availableTools:l,systemMessage:c,lastUserMessage:u,model:h,validToolNames:d}}function Vm(t,e,n,r,s){const o=s.maxTools,i=s.alwaysInclude??[],a=[],l=[];for(const d of t.tools){if(!n.includes(d)){l.push(d);continue}!a.includes(d)&&(o===void 0||a.length<o)&&a.push(d)}if(l.length>0)throw new Error(`Model selected invalid tools: ${l.join(", ")}`);const c=e.filter(d=>a.includes(d.name)),u=(r.tools??[]).filter(d=>typeof d=="object"&&"name"in d&&typeof d.name=="string"&&i.includes(d.name));c.push(...u);const h=(r.tools??[]).filter(d=>!(typeof d=="object"&&"name"in d&&"description"in d&&typeof d.name=="string"));return{...r,tools:[...c,...h]}}var Dl=class extends Error{constructor(t,e){super(`PII detected: ${t} found ${e.length} occurrence(s)`),this.piiType=t,this.matches=e,this.name="PIIDetectionError"}};const Bm=/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,zm=/\b(?:\d{4}[-\s]?){3}\d{4}\b/g,Wm=/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g,Hm=/\b(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})\b/g,Gm=/(?:https?:\/\/|www\.)[^\s<>"{}|\\^`[\]]+/gi;function Km(t){const e=t.replace(/\D/g,"");let n=0,r=!1;for(let s=e.length-1;s>=0;s--){let o=parseInt(e[s],10);r&&(o*=2,o>9&&(o-=9)),n+=o,r=!r}return n%10===0}function wt(t){return{text:t[0],start:t.index??0,end:(t.index??0)+t[0].length}}function Fl(t){const e=[],n=new RegExp(Bm);let r;for(;(r=n.exec(t))!==null;)e.push(wt(r));return e}function Ul(t){const e=[],n=new RegExp(zm);let r;for(;(r=n.exec(t))!==null;){const s=r[0].replace(/\D/g,"");s.length>=13&&s.length<=19&&Km(s)&&e.push(wt(r))}return e}function Vl(t){const e=[],n=new RegExp(Wm);let r;for(;(r=n.exec(t))!==null;){const o=r[0].split(".");o.length===4&&o.every(i=>{const a=parseInt(i,10);return a>=0&&a<=255})&&e.push(wt(r))}return e}function Bl(t){const e=[],n=new RegExp(Hm);let r;for(;(r=n.exec(t))!==null;)e.push(wt(r));return e}function zl(t){const e=[],n=new RegExp(Gm);let r;for(;(r=n.exec(t))!==null;)e.push(wt(r));return e}const ss={email:Fl,credit_card:Ul,ip:Vl,mac_address:Bl,url:zl};function Wl(t){let e;if(t.detector)if(typeof t.detector=="string"){const n=new RegExp(t.detector,"g");e=r=>{const s=[];let o;const i=new RegExp(n);for(;(o=i.exec(r))!==null;)s.push(wt(o));return s}}else t.detector instanceof RegExp?e=n=>{if(!(t.detector instanceof RegExp))throw new Error("Detector is required");const r=[];let s;for(;(s=t.detector.exec(n))!==null;)r.push(wt(s));return r}:e=t.detector;else{const n=t.piiType;if(!ss[n])throw new Error(`Unknown PII type: ${t.piiType}. Must be one of: ${Object.keys(ss).join(", ")}, or provide a custom detector.`);e=ss[n]}return{piiType:t.piiType,strategy:t.strategy,detector:e}}function Jm(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=`[REDACTED_${n.toUpperCase()}]`;r=r.slice(0,o.start)+i+r.slice(o.end)}return r}function qm(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=o.text;let a;if(n==="credit_card")a=`****-****-****-${i.replace(/\D/g,"").slice(-4)}`;else if(n==="email"){const[l,c]=i.split("@");l&&c?a=`${l[0]}***@${c}`:a="***"}else{const l=Math.min(4,i.length);a=`${"*".repeat(Math.max(0,i.length-l))}${i.slice(-l)}`}r=r.slice(0,o.start)+a+r.slice(o.end)}return r}function Ym(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=di(o.text).slice(0,8),a=`<${n}_hash:${i}>`;r=r.slice(0,o.start)+a+r.slice(o.end)}return r}function Hl(t,e,n,r){if(e.length===0)return t;switch(n){case"block":throw new Dl(r,e);case"redact":return Jm(t,e,r);case"mask":return qm(t,e,r);case"hash":return Ym(t,e,r);default:throw new Error(`Unknown strategy: ${n}`)}}const Xm=B({applyToInput:ft().optional(),applyToOutput:ft().optional(),applyToToolResults:ft().optional()});function os(t,e){const n=e.detector(t);return n.length===0?{content:t,matches:[]}:{content:Hl(t,n,e.strategy,e.piiType),matches:n}}function Zm(t,e={}){const{strategy:n="redact",detector:r}=e,s=Wl({piiType:t,strategy:n,detector:r}),o=`PIIMiddleware[${s.piiType}]`;return se({name:o,contextSchema:Xm,beforeModel:async(i,a)=>{const l=a.context.applyToInput??e.applyToInput??!0,c=a.context.applyToToolResults??e.applyToToolResults??!1;if(!l&&!c)return;const u=i.messages;if(!u||u.length===0)return;const h=[...u];let d=!1;if(l){let f=null;for(let p=u.length-1;p>=0;p--)if(ee.isInstance(u[p])){f=p;break}if(f!==null){const p=u[f];if(p&&p.content){const m=String(p.content),{content:S,matches:C}=os(m,s);C.length>0&&(h[f]=new ee({content:S,id:p.id,name:p.name}),d=!0)}}}if(c){let f=null;for(let p=u.length-1;p>=0;p--)if(I.isInstance(u[p])){f=p;break}if(f!==null)for(let p=f+1;p<u.length;p++){const m=u[p];if(j.isInstance(m)){if(!m.content)continue;const S=String(m.content),{content:C,matches:E}=os(S,s);E.length>0&&(h[p]=new j({content:C,id:m.id,name:m.name,tool_call_id:m.tool_call_id}),d=!0)}}}if(d)return{messages:h}},afterModel:async(i,a)=>{if(!(a.context.applyToOutput??e.applyToOutput??!1))return;const c=i.messages;if(!c||c.length===0)return;let u=null,h=null;for(let C=c.length-1;C>=0;C--)if(I.isInstance(c[C])){h=c[C],u=C;break}if(u===null||!h||!h.content)return;const d=String(h.content),{content:f,matches:p}=os(d,s);if(p.length===0)return;const m=new I({content:f,id:h.id,name:h.name,tool_calls:h.tool_calls}),S=[...c];return S[u]=m,{messages:S}}})}const Qm=B({rules:mn(Q(),An(RegExp).describe("Regular expression pattern to match PII")).optional()});function eg(){return Math.random().toString(36).substring(2,11)}function is(t,e,n){let r=t;for(const[s,o]of Object.entries(e)){const i=s.toUpperCase().replace(/[^a-zA-Z0-9_-]/g,"");r=r.replace(o,a=>{const l=eg();return n[l]=a,`[REDACTED_${i}_${l}]`})}return r}async function tg(t,e){if(ee.isInstance(t)||j.isInstance(t)||te.isInstance(t)){const n=t.content,r=await is(n,e.rules,e.redactionMap);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return new s({...t,content:r})}return t}if(I.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=await is(n,e.rules,e.redactionMap),o=await is(r,e.rules,e.redactionMap);return s!==n||o!==r?new I({...t,content:typeof t.content=="string"?s:JSON.parse(s),tool_calls:JSON.parse(o)}):t}throw new Error(`Unsupported message type: ${t.type}`)}function dn(t,e){let n=t;const r=/\[REDACTED_[A-Z_]+_(\w+)\]/g;return n=n.replace(r,(s,o)=>e[o]?e[o]:s),n}function ni(t,e){if(ee.isInstance(t)||j.isInstance(t)||te.isInstance(t)){const n=t.content,r=dn(n,e);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return{message:new s({...t,content:r}),changed:!0}}return{message:t,changed:!1}}if(I.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=dn(n,e),o=dn(r,e);return s!==n||o!==r?{message:new I({...t,content:typeof t.content=="string"?s:JSON.parse(s),tool_calls:JSON.parse(o)}),changed:!0}:{message:t,changed:!1}}throw new Error(`Unsupported message type: ${t.type}`)}function ng(t={}){const e={};return console.warn("DEPRECATED: piiRedactionMiddleware is deprecated. Please use piiMiddleware instead, go to https://docs.langchain.com/oss/javascript/langchain/middleware/built-in#pii-detection for more information."),se({name:"PIIRedactionMiddleware",contextSchema:Qm,wrapModelCall:async(n,r)=>{const s=n.runtime.context.rules??t.rules??{};if(Object.keys(s).length===0)return r(n);const o=await Promise.all(n.state.messages.map(i=>tg(i,{rules:s,redactionMap:e})));return r({...n,messages:o})},afterModel:async n=>{if(Object.keys(e).length===0)return;const r=n.messages.at(-1);if(!I.isInstance(r))return;const s=n.messages.at(-2),{message:o,changed:i}=ni(r,e);if(!i)return;let a;if(I.isInstance(r)&&r?.tool_calls?.length===0&&typeof r.content=="string"&&r.content.startsWith("{")&&r.content.endsWith("}"))try{a=JSON.parse(dn(r.content,e))}catch{}if(I.isInstance(s)&&s?.tool_calls?.length!==0&&s?.tool_calls?.some(c=>c.name.startsWith("extract-"))){const{message:c,changed:u}=ni(s,e),h=s.tool_calls?.find(f=>f.name.startsWith("extract-"))?.args,d=h?JSON.parse(dn(JSON.stringify(h),e)):void 0;if(i||u)return{...n,...d?{structuredResponse:d}:{},messages:[new zn({id:s.id}),new zn({id:r.id}),c,o]}}return{...n,...a?{structuredResponse:a}:{},messages:[new zn({id:r.id}),o]}}})}const rg="[cleared]",sg=1e5,Un=3;var Gl=class{#e;trigger;keep;clearToolInputs;excludeTools;placeholder;model;clearAtLeast;constructor(t={}){let e=t.trigger;t.triggerTokens!==void 0&&(console.warn("triggerTokens is deprecated. Use `trigger: { tokens: value }` instead."),e===void 0&&(e={tokens:t.triggerTokens}));let n=t.keep;if(t.keepMessages!==void 0&&(console.warn("keepMessages is deprecated. Use `keep: { messages: value }` instead."),n===void 0&&(n={messages:t.keepMessages})),e===void 0&&(e={tokens:sg}),n===void 0&&(n={messages:Un}),Array.isArray(e))this.#e=e.map(s=>Qt.parse(s)),this.trigger=this.#e;else{const s=Qt.parse(e);this.#e=[s],this.trigger=s}const r=go.parse(n);this.keep=r,t.clearAtLeast!==void 0&&console.warn("clearAtLeast is deprecated and will be removed in a future version. It conflicts with the `keep` property. Use `keep: { tokens: value }` or `keep: { messages: value }` instead to control retention."),this.clearAtLeast=t.clearAtLeast??0,this.clearToolInputs=t.clearToolInputs??!1,this.excludeTools=new Set(t.excludeTools??[]),this.placeholder=t.placeholder??rg}async apply(t){const{messages:e,model:n,countTokens:r}=t,s=await r(e),o=[];for(let d=0;d<e.length;d++){const f=e[d];if(j.isInstance(f)){const p=this.#n(e.slice(0,d),f.tool_call_id);p&&p.tool_calls?.find(S=>S.id===f.tool_call_id)||o.push(d)}}for(let d=o.length-1;d>=0;d--)e.splice(o[d],1);let i=s;if(o.length>0&&(i=await r(e)),!this.#r(e,i,n))return;const a=[];for(let d=0;d<e.length;d++){const f=e[d];j.isInstance(f)&&a.push({idx:d,msg:f})}if(a.length===0)return;const l=await this.#t(a,r,n),c=l>=a.length?[]:l>0?a.slice(0,-l):a;let u=0;const h=[...c];for(const{idx:d,msg:f}of h){if(f.response_metadata?.context_editing?.cleared)continue;const m=this.#n(e.slice(0,d),f.tool_call_id);if(!m)continue;const S=m.tool_calls?.find(b=>b.id===f.tool_call_id);if(!S)continue;const C=f.name||S.name;if(this.excludeTools.has(C))continue;if(e[d]=new j({tool_call_id:f.tool_call_id,content:this.placeholder,name:f.name,artifact:void 0,response_metadata:{...f.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const b=e.indexOf(m);b>=0&&(e[b]=this.#s(m,f.tool_call_id))}const E=await r(e);u=Math.max(0,i-E)}if(this.clearAtLeast>0&&u<this.clearAtLeast){const d=l>0&&l<a.length?a.slice(-l):[];for(let f=d.length-1;f>=0&&!(u>=this.clearAtLeast);f--){const{idx:p,msg:m}=d[f];if(m.response_metadata?.context_editing?.cleared)continue;const C=this.#n(e.slice(0,p),m.tool_call_id);if(!C)continue;const E=C.tool_calls?.find(g=>g.id===m.tool_call_id);if(!E)continue;const b=m.name||E.name;if(this.excludeTools.has(b))continue;if(e[p]=new j({tool_call_id:m.tool_call_id,content:this.placeholder,name:m.name,artifact:void 0,response_metadata:{...m.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const g=e.indexOf(C);g>=0&&(e[g]=this.#s(C,m.tool_call_id))}const w=await r(e);u=Math.max(0,i-w)}}}#r(t,e,n){for(const r of this.#e){let s=!0,o=!1;if(r.messages!==void 0&&(o=!0,t.length<r.messages&&(s=!1)),r.tokens!==void 0&&(o=!0,e<r.tokens&&(s=!1)),r.fraction!==void 0){if(o=!0,!n)continue;const i=Tn(n);if(typeof i=="number"){const a=Math.floor(i*r.fraction);if(a<=0)continue;e<a&&(s=!1)}else continue}if(o&&s)return!0}return!1}async#t(t,e,n){if("messages"in this.keep&&this.keep.messages!==void 0)return this.keep.messages;if("tokens"in this.keep&&this.keep.tokens!==void 0){const r=this.keep.tokens;let s=0,o=0;for(let i=t.length-1;i>=0;i--){const a=t[i],l=await e([a.msg]);if(s+l<=r)s+=l,o++;else break}return o}if("fraction"in this.keep&&this.keep.fraction!==void 0){if(!n)return Un;const r=Tn(n);if(typeof r=="number"){const s=Math.floor(r*this.keep.fraction);if(s<=0)return Un;let o=0,i=0;for(let a=t.length-1;a>=0;a--){const l=t[a],c=await e([l.msg]);if(o+c<=s)o+=c,i++;else break}return i}}return Un}#n(t,e){for(let n=t.length-1;n>=0;n--){const r=t[n];if(I.isInstance(r)&&r.tool_calls?.some(o=>o.id===e))return r}return null}#s(t,e){const n=t.tool_calls?.map(i=>i.id===e?{...i,args:{}}:i),r={...t.response_metadata},s={...r.context_editing},o=new Set(s.cleared_tool_inputs);return o.add(e),s.cleared_tool_inputs=Array.from(o).sort(),r.context_editing=s,new I({content:t.content,tool_calls:n,response_metadata:r,id:t.id,name:t.name,additional_kwargs:t.additional_kwargs})}};function og(t={}){const e=t.edits??[new Gl],n=t.tokenCountMethod??"approx";return se({name:"ContextEditingMiddleware",wrapModelCall:async(r,s)=>{if(!r.messages||r.messages.length===0)return s(r);const o=r.systemPrompt?[new te(r.systemPrompt)]:[],i=n==="approx"?Gs:async a=>{const l=[...o,...a];if("getNumTokensFromMessages"in r.model)return r.model.getNumTokensFromMessages(l).then(({totalCount:c})=>c);throw new Error(`Model "${r.model.getName()}" does not support token counting`)};for(const a of e)await a.apply({messages:r.messages,model:r.model,countTokens:i});return s(r)}})}function ig(t){return t?`Tool call limit exceeded. Do not call '${t}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const ag=["continue","error","end"],Kl="continue";function Jl(t,e,n,r,s){const o=s?`'${s}' tool`:"Tool",i=[];n!==void 0&&t>n&&i.push(`thread limit exceeded (${t}/${n} calls)`),r!==void 0&&e>r&&i.push(`run limit exceeded (${e}/${r} calls)`);const a=i.join(" and ");return`${o} call limit reached: ${a}.`}const ql=Jt(ag).default(Kl);var Yl=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,r,s=void 0){const o=Jl(t,e,n,r,s);super(o),this.name="ToolCallLimitExceededError",this.threadCount=t,this.runCount=e,this.threadLimit=n,this.runLimit=r,this.toolName=s}};B({toolName:Q().optional(),threadLimit:V().optional(),runLimit:V().optional(),exitBehavior:ql});const lg=B({threadToolCallCount:mn(Q(),V()).default({}),runToolCallCount:mn(Q(),V()).default({})}),cg="__all__";function ug(t){if(t.threadLimit===void 0&&t.runLimit===void 0)throw new Error("At least one limit must be specified (threadLimit or runLimit)");const e=t.exitBehavior??Kl,n=ql.safeParse(e);if(!n.success)throw new Error(Ds(n.error).slice(2));if(t.threadLimit!==void 0&&t.runLimit!==void 0&&t.runLimit>t.threadLimit)throw new Error(`runLimit (${t.runLimit}) cannot exceed threadLimit (${t.threadLimit}). The run limit should be less than or equal to the thread limit.`);const r=t.toolName?`ToolCallLimitMiddleware[${t.toolName}]`:"ToolCallLimitMiddleware";return se({name:r,stateSchema:lg,afterModel:{canJumpTo:["end"],hook:s=>{const o=[...s.messages].reverse().find(I.isInstance);if(!o||!o.tool_calls)return;const i=(w,g)=>t.threadLimit!==void 0&&w+1>t.threadLimit||t.runLimit!==void 0&&g+1>t.runLimit,a=w=>t.toolName===void 0||w.name===t.toolName,l=(w,g,k)=>{const _=[],v=[];let x=g,T=k;for(const M of w)a(M)&&(i(x,T)?v.push(M):(_.push(M),x+=1,T+=1));return{allowed:_,blocked:v,finalThreadCount:x,finalRunCount:T+v.length}},c=t.toolName??cg,u={...s.threadToolCallCount??{}},h={...s.runToolCallCount??{}},d=u[c]??0,f=h[c]??0,{allowed:p,blocked:m,finalThreadCount:S,finalRunCount:C}=l(o.tool_calls,d,f);if(u[c]=S,h[c]=C,m.length===0)return p.length>0?{threadToolCallCount:u,runToolCallCount:h}:void 0;if(e==="error"){const w=S+m.length;throw new Yl(w,C,t.threadLimit,t.runLimit,t.toolName)}const E=ig(t.toolName),b=m.map(w=>new j({content:E,tool_call_id:w.id,name:w.name,status:"error"}));if(e==="end"){let w=[];if(t.toolName!==void 0?w=o.tool_calls.filter(_=>_.name!==t.toolName):new Set(o.tool_calls.map(v=>v.name).filter(Boolean)).size>1&&(w=p.length>0?p:o.tool_calls),w.length>0){const _=Array.from(new Set(w.map(v=>v.name).filter(Boolean))).join(", ");throw new Error(`Cannot end execution with other tool calls pending. Found calls to: ${_}. Use 'continue' or 'error' behavior instead.`)}const g=S+m.length,k=Jl(g,C,t.threadLimit,t.runLimit,t.toolName);return b.push(new I(k)),{threadToolCallCount:u,runToolCallCount:h,jumpTo:"end",messages:b}}return{threadToolCallCount:u,runToolCallCount:h,messages:b}}},afterAgent:()=>({runToolCallCount:{}})})}const hg=`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.
105
+ It also helps the user understand the progress of the task and overall progress of their requests.
106
+ 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.
107
+
108
+ ## When to Use This Tool
109
+ Use this tool in these scenarios:
110
+
111
+ 1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
112
+ 2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
113
+ 3. User explicitly requests todo list - When the user directly asks you to use the todo list
114
+ 4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
115
+ 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.
116
+
117
+ ## How to Use This Tool
118
+ 1. When you start working on a task - Mark it as in_progress BEFORE beginning work.
119
+ 2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation.
120
+ 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.
121
+ 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.
122
+
123
+ ## When NOT to Use This Tool
124
+ It is important to skip using this tool when:
125
+ 1. There is only a single, straightforward task
126
+ 2. The task is trivial and tracking it provides no benefit
127
+ 3. The task can be completed in less than 3 trivial steps
128
+ 4. The task is purely conversational or informational
129
+
130
+ ## Examples of When to Use the Todo List
131
+
132
+ <example>
133
+ 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!
134
+ Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
135
+ *Creates todo list with the following items:*
136
+ 1. Create dark mode toggle component in Settings page
137
+ 2. Add dark mode state management (context/store)
138
+ 3. Implement CSS-in-JS styles for dark theme
139
+ 4. Update existing components to support theme switching
140
+ 5. Run tests and build process, addressing any failures or errors that occur
141
+ *Begins working on the first task*
142
+
143
+ <reasoning>
144
+ The assistant used the todo list because:
145
+ 1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes
146
+ 2. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
147
+ 3. Both of the user's requests are complex and require multiple steps to complete.
148
+ </reasoning>
149
+ </example>
150
+
151
+ <example>
152
+ User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases.
153
+ 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.
154
+ *Creates todo list with the following items:*
155
+ 1. Define target audience and key messaging
156
+ 2. Create social media content calendar and posting schedule
157
+ 3. Design email marketing sequence and automation flows
158
+ 4. Draft press release and identify media contacts
159
+ 5. Set up tracking and analytics for campaign performance
160
+ 6. Create visual assets and brand materials
161
+ 7. Coordinate launch timeline and deliverables
162
+ *Begins working on the first task*
163
+
164
+ <reasoning>
165
+ The assistant used the todo list because:
166
+ 1. Marketing campaign planning involves multiple distinct channels and activities
167
+ 2. Each component requires careful coordination and planning
168
+ 3. The systematic approach ensures all aspects of the launch are covered
169
+ </reasoning>
170
+ </example>
171
+
172
+ <example>
173
+ User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
174
+ Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
175
+ *Uses search tools to locate all instances of getCwd in the codebase*
176
+ Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
177
+ *Creates todo list with specific items for each file that needs updating*
178
+
179
+ <reasoning>
180
+ The assistant used the todo list because:
181
+ 1. The assistant searched to understand the scope of the task
182
+ 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps (>3)
183
+ 3. The todo list helps ensure every instance is tracked and updated systematically
184
+ 4. This approach prevents missing any occurrences and maintains consistency.
185
+ </reasoning>
186
+ </example>
187
+
188
+ <example>
189
+ User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow.
190
+ Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization.
191
+ *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*
192
+ Let's start with decluttering your desk space to create a clean foundation for the other organizational systems.
193
+
194
+ <reasoning>
195
+ The assistant used the todo list because:
196
+ 1. The user provided multiple distinct organizational tasks
197
+ 2. Each area requires different approaches and careful planning
198
+ 3. Home organization benefits from systematic, step-by-step completion
199
+ 4. Progress tracking ensures all areas are addressed thoroughly
200
+ </reasoning>
201
+ </example>
202
+
203
+ ## Examples of When NOT to Use the Todo List
204
+
205
+ <example>
206
+ User: How do I print 'Hello World' in Python?
207
+ Assistant: In Python, you can print "Hello World" with this simple code:
208
+
209
+ \`\`\`python
210
+ print("Hello World")
211
+ \`\`\`
212
+
213
+ This will output the text "Hello World" to the console when executed.</assistant>
214
+
215
+ <reasoning>
216
+ 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.
217
+ </reasoning>
218
+ </example>
219
+
220
+ <example>
221
+ User: What's the best way to water houseplants?
222
+ Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines:
223
+
224
+ - Check soil moisture by inserting your finger about 1-2 inches into the soil
225
+ - Water thoroughly when the top inch feels dry, allowing water to drain from the bottom
226
+ - Use room temperature water and water in the morning when possible
227
+ - Avoid overwatering, which is more harmful than underwatering for most plants
228
+
229
+ Different plants have different needs, so it's important to research your specific varieties for optimal care.
230
+
231
+ <reasoning>
232
+ 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.
233
+ </reasoning>
234
+ </example>
235
+
236
+ <example>
237
+ User: Can you add a comment to the calculateTotal function to explain what it does?
238
+ Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
239
+ * Uses the Edit tool to add a comment to the calculateTotal function *
240
+
241
+ <reasoning>
242
+ 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.
243
+ </reasoning>
244
+ </example>
245
+
246
+ <example>
247
+ User: What time is it in Tokyo right now?
248
+ Assistant: I'll check the current time in Tokyo for you.
249
+
250
+ *Searches for current time in Tokyo*
251
+
252
+ The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9.
253
+
254
+ <reasoning>
255
+ 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.
256
+ </reasoning>
257
+ </example>
258
+
259
+ <example>
260
+ User: I need to write a function that checks if a number is prime and then test it out.
261
+ Assistant: I'll help you write a function that checks if a number is prime and then test it out.
262
+ *Writes function that checks if a number is prime*
263
+ *Tests the function*
264
+
265
+ <reasoning>
266
+ 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.
267
+ </reasoning>
268
+ </example>
269
+
270
+ <example>
271
+ User: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
272
+ Assistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
273
+ *Orders a pizza from Dominos*
274
+ *Orders a burger from McDonald's*
275
+ *Orders a salad from Subway*
276
+
277
+ <reasoning>
278
+ 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.
279
+ Using the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact.
280
+ </reasoning>
281
+ </example>
282
+
283
+
284
+ ## Task States and Management
285
+
286
+ 1. **Task States**: Use these states to track progress:
287
+ - pending: Task not yet started
288
+ - 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)
289
+ - completed: Task finished successfully
290
+
291
+ 2. **Task Management**:
292
+ - Update task status in real-time as you work
293
+ - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
294
+ - Complete current tasks before starting new ones
295
+ - Remove tasks that are no longer relevant from the list entirely
296
+ - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.
297
+ - 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.
298
+
299
+ 3. **Task Completion Requirements**:
300
+ - ONLY mark a task as completed when you have FULLY accomplished it
301
+ - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
302
+ - When blocked, create a new task describing what needs to be resolved
303
+ - Never mark a task as completed if:
304
+ - There are unresolved issues or errors
305
+ - Work is partial or incomplete
306
+ - You encountered blockers that prevent completion
307
+ - You couldn't find necessary resources or dependencies
308
+ - Quality standards haven't been met
309
+
310
+ 4. **Task Breakdown**:
311
+ - Create specific, actionable items
312
+ - Break complex tasks into smaller, manageable steps
313
+ - Use clear, descriptive task names
314
+
315
+ Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully
316
+ 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.`,Xl=`## \`write_todos\`
317
+
318
+ You have access to the \`write_todos\` tool to help you manage and plan complex objectives.
319
+ Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.
320
+ This tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.
321
+
322
+ 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.
323
+ For simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.
324
+ 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.
325
+
326
+ ## Important To-Do List Usage Notes to Remember
327
+ - The \`write_todos\` tool should never be called multiple times in parallel.
328
+ - 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.`,dg=Jt(["pending","in_progress","completed"]).describe("Status of the todo"),Zl=B({content:Q().describe("Content of the todo item"),status:dg}),fg=B({todos:Ge(Zl).default([])});function pg(t){const e=hi(({todos:n},r)=>new G({update:{todos:n,messages:[new j({content:`Updated todo list to ${JSON.stringify(n)}`,tool_call_id:r.toolCall?.id})]}}),{name:"write_todos",description:t?.toolDescription??hg,schema:B({todos:Ge(Zl).describe("List of todo items to update")})});return se({name:"todoListMiddleware",stateSchema:fg,tools:[e],wrapModelCall:(n,r)=>r({...n,systemMessage:n.systemMessage.concat(`
329
+
330
+ ${t?.systemPrompt??Xl}`)}),afterModel:n=>{const r=n.messages;if(!r||r.length===0)return;const s=[...r].reverse().find(i=>I.isInstance(i));if(!s||!s.tool_calls||s.tool_calls.length===0)return;const o=s.tool_calls.filter(i=>i.name===e.name);if(o.length>1)return{messages:o.map(a=>new j({content:"Error: The `write_todos` tool should never be called multiple times in parallel. Please call it only once per model invocation to update the todo list.",tool_call_id:a.id,status:"error"}))}}})}const mg="end",gg=B({threadLimit:V().optional(),runLimit:V().optional(),exitBehavior:Jt(["error","end"]).optional()}),yg=B({threadModelCallCount:V().default(0),runModelCallCount:V().default(0)});var ri=class extends Error{constructor({threadLimit:t,runLimit:e,threadCount:n,runCount:r}){const s=[];typeof t=="number"&&typeof n=="number"&&s.push(`thread level call limit reached with ${n} model calls`),typeof e=="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 Ql(t){return se({name:"ModelCallLimitMiddleware",contextSchema:gg,stateSchema:yg,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{let r=n.context.exitBehavior??t?.exitBehavior??mg;r==="throw"&&(console.warn("The 'throw' exit behavior is deprecated. Please use 'error' instead."),r="error");const s=n.context.threadLimit??t?.threadLimit,o=n.context.runLimit??t?.runLimit,i=e.threadModelCallCount,a=e.runModelCallCount;if(typeof s=="number"&&s<=i){const l=new ri({threadLimit:s,threadCount:i});if(r==="end")return{jumpTo:"end",messages:[new I(l.message)]};throw l}if(typeof o=="number"&&o<=a){const l=new ri({runLimit:o,runCount:a});if(r==="end")return{jumpTo:"end",messages:[new I(l.message)]};throw l}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function wg(...t){return se({name:"modelFallbackMiddleware",wrapModelCall:async(e,n)=>{try{return await n(e)}catch(r){for(let s=0;s<t.length;s++)try{const o=t[s],i=typeof o=="string"?await it(o):o;return await n({...e,model:i})}catch(o){if(s===t.length-1)throw o}throw r}}})}const ec=B({maxRetries:V().min(0).default(2),retryOn:Ae([Mn().args(An(Error)).returns(ft()),Ge(Se())]).default(()=>()=>!0),backoffFactor:V().min(0).default(2),initialDelayMs:V().min(0).default(1e3),maxDelayMs:V().min(0).default(6e4),jitter:ft().default(!0)});var tc=class extends Error{cause;constructor(t){const e=Ds(t).slice(2);super(e),this.name="InvalidRetryConfigError",this.cause=t}};const si=B({onFailure:Ae([Re("error"),Re("continue"),Mn().args(An(Error)).returns(Q())]).default("continue")}).merge(ec);function vg(t={}){const{success:e,error:n,data:r}=si.safeParse(t);if(!e)throw new tc(n);const{maxRetries:s,retryOn:o,onFailure:i,backoffFactor:a,initialDelayMs:l,maxDelayMs:c,jitter:u}=r,h=m=>typeof o=="function"?o(m):o.some(S=>m.constructor===S),d={backoffFactor:a,initialDelayMs:l,maxDelayMs:c,jitter:u},f=(m,S)=>{const C=m.constructor.name;return`Model call failed after ${S} ${S===1?"attempt":"attempts"} with ${C}: ${m.message}`},p=(m,S)=>{if(i==="error")throw m;let C;return typeof i=="function"?C=i(m):C=f(m,S),new I({content:C})};return se({name:"modelRetryMiddleware",contextSchema:si,wrapModelCall:async(m,S)=>{for(let C=0;C<=s;C++)try{return await S(m)}catch(E){const b=C+1,w=E&&typeof E=="object"&&"message"in E?E:new Error(String(E));if(!h(w))return p(w,b);if(C<s){const g=Oi(d,C);g>0&&await Ii(g)}else return p(w,b)}throw new Error("Unexpected: retry loop completed without returning")}})}const oi=B({tools:Ge(Ae([Se(),Se(),Q()])).optional(),onFailure:Ae([Re("error"),Re("continue"),Re("raise"),Re("return_message"),Mn().args(An(Error)).returns(Q())]).default("continue")}).merge(ec);function bg(t={}){const{success:e,error:n,data:r}=oi.safeParse(t);if(!e)throw new tc(n);const{maxRetries:s,tools:o,retryOn:i,onFailure:a,backoffFactor:l,initialDelayMs:c,maxDelayMs:u,jitter:h}=r;let d=a;a==="raise"?(console.warn("⚠️ `onFailure: 'raise'` is deprecated. Use `onFailure: 'error'` instead."),d="error"):a==="return_message"&&(console.warn("⚠️ `onFailure: 'return_message'` is deprecated. Use `onFailure: 'continue'` instead."),d="continue");const f=[];for(const b of o??[])if(typeof b=="string")f.push(b);else if("name"in b&&typeof b.name=="string")f.push(b.name);else throw new TypeError("Expected a tool name string or tool instance to be passed to toolRetryMiddleware");const p=b=>f.length===0?!0:f.includes(b),m=b=>typeof i=="function"?i(b):i.some(w=>b instanceof w),S={backoffFactor:l,initialDelayMs:c,maxDelayMs:u,jitter:h},C=(b,w,g)=>{const k=w.constructor.name;return`Tool '${b}' failed after ${g} ${g===1?"attempt":"attempts"} with ${k}`},E=(b,w,g,k)=>{if(d==="error")throw g;let _;return typeof d=="function"?_=d(g):_=C(b,g,k),new j({content:_,tool_call_id:w,name:b,status:"error"})};return se({name:"toolRetryMiddleware",contextSchema:oi,wrapToolCall:async(b,w)=>{const g=b.tool?.name??b.toolCall.name;if(!p(g))return w(b);const k=b.toolCall.id??"";for(let _=0;_<=s;_++)try{return await w(b)}catch(v){const x=_+1,T=v&&typeof v=="object"&&"message"in v?v:new Error(String(v));if(!m(T))return E(g,k,T,x);if(_<s){const M=Oi(S,_);M>0&&await Ii(M)}else return E(g,k,T,x)}throw new Error("Unexpected: retry loop completed without returning")}})}function _g(t={}){let e;const{tools:n,model:r}=t,s=!n||n.length===0,o=new Set;if(!s&&n)for(const l of n)if(typeof l=="string")o.add(l);else{const c=typeof l.name=="string"?l.name:String(l.name);o.add(c)}let i;const a=async()=>typeof r=="object"?r:typeof r=="string"?(i=i??await it(r,{temperature:1}).catch(l=>(console.error("Error initializing emulator model, using agent model:",l),e)),i):e;return se({name:"ToolEmulatorMiddleware",wrapModelCall:async(l,c)=>(e=l.model,c(l)),wrapToolCall:async(l,c)=>{const u=l.toolCall.name;if(!(s||o.has(u)))return c(l);const d=l.toolCall.args,f=l.tool.description||"No description available",p=typeof d=="string"?d:JSON.stringify(d),m=`You are emulating a tool call for testing purposes.
331
+
332
+ Tool: ${u}
333
+ Description: ${f}
334
+ Arguments: ${p}
335
+
336
+ Generate a realistic response that this tool would return given these arguments.
337
+ Return ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`,C=await(await a()).invoke([new ee(m)]),E=typeof C.content=="string"?C.content:JSON.stringify(C.content);return new j({content:E,tool_call_id:l.toolCall.id??"",name:u})}})}function Sg(t){return!t||typeof t!="object"||t===null||!("client"in t)||!("_getClientOptions"in t)||typeof t._getClientOptions!="function"?!1:(t._getClientOptions(),typeof t.client=="object"&&t.client!==null&&"moderations"in t.client&&typeof t.client.moderations=="object"&&t.client.moderations!==null&&"create"in t.client.moderations&&typeof t.client.moderations.create=="function")}const Cg="I'm sorry, but I can't comply with that request. It was flagged for {categories}.";var Tg=class extends Error{content;stage;result;originalMessage;constructor({content:t,stage:e,result:n,message:r}){super(r),this.name="OpenAIModerationError",this.content=t,this.stage=e,this.result=n,this.originalMessage=r}};function kg(t){const{model:e,moderationModel:n="omni-moderation-latest",checkInput:r=!0,checkOutput:s=!0,checkToolResults:o=!1,exitBehavior:i="end",violationMessage:a}=t;let l;const c=async()=>{if(l)return l;const b=typeof e=="string"?await it(e):e;if(!b.getName().includes("ChatOpenAI"))throw new Error(`Model must be an OpenAI model to use moderation middleware. Got: ${b.getName()}`);if(!Sg(b))throw new Error("Model must support moderation to use moderation middleware.");return l=b,l},u=b=>b.content==null?null:b.text||null,h=(b,w)=>{for(let g=b.length-1;g>=0;g--)if(w.isInstance(b[g]))return g;return null},d=(b,w)=>{const g=[],k=w.categories;for(const[T,M]of Object.entries(k))M&&g.push(T.replace(/_/g," "));const _=g.length>0?g.join(", "):"OpenAI's safety policies",v=a||Cg,x=JSON.stringify(w.category_scores,null,2);try{return v.replace("{categories}",_).replace("{category_scores}",x).replace("{original_content}",b)}catch{return v}};function f(b,w){const g=l?._getClientOptions?.(),k=w?.model??"omni-moderation-latest",_={input:b,model:k};return l.client.moderations.create(_,g)}const p=(b,w,g,k,_)=>{const v=d(k,_);if(i==="error")throw new Tg({content:k,stage:g,result:_,message:v});if(i==="end")return{jumpTo:"end",messages:[new I({content:v})]};if(w==null)return;const x=[...b],T=x[w],M=Object.getPrototypeOf(T).constructor;return x[w]=new M({...T,content:v}),{messages:x}},m=async b=>{const w=h(b,ee);if(w==null)return null;const g=b[w],k=u(g);if(!k)return null;await c();const v=(await f(k,{model:n})).results.find(x=>x.flagged);return v?p(b,w,"input",k,v):null},S=async b=>{const w=h(b,I);if(w==null)return null;const g=[...b];let k=!1;for(let _=w+1;_<g.length;_++){const v=g[_];if(!j.isInstance(v))continue;const x=u(v);if(!x)continue;await c();const M=(await f(x,{model:n})).results.find(N=>N.flagged);if(!M)continue;const P=p(g,_,"tool",x,M);if(P){if("jumpTo"in P)return P;"messages"in P&&(g.splice(0,g.length,...P.messages),k=!0)}}return k?{messages:g}:null},C=async b=>{const w=h(b,I);if(w==null)return null;const g=b[w],k=u(g);if(!k)return null;await c();const v=(await f(k,{model:n})).results.find(x=>x.flagged);return v?p(b,w,"output",k,v):null},E=async b=>{const w=[...b];let g=!1;if(o){const k=await S(w);if(k){if("jumpTo"in k)return k;"messages"in k&&(w.splice(0,w.length,...k.messages),g=!0)}}if(r){const k=await m(w);if(k){if("jumpTo"in k)return k;"messages"in k&&(w.splice(0,w.length,...k.messages),g=!0)}}return g?{messages:w}:null};return se({name:"OpenAIModerationMiddleware",beforeModel:{hook:async b=>{if(!r&&!o)return;const w=b.messages||[];if(w.length!==0)return await E(w)??void 0},canJumpTo:["end"]},afterModel:{hook:async b=>{if(!s)return;const w=b.messages||[];if(w.length!==0)return await C(w)??void 0},canJumpTo:["end"]}})}const Eg=!0,xg="5m",Mg=3,Ag="warn",Pg=B({enableCaching:ft().optional(),ttl:Jt(["5m","1h"]).optional(),minMessagesToCache:V().optional(),unsupportedModelBehavior:Jt(["ignore","warn","raise"]).optional()});var ii=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function Ig(t){return se({name:"PromptCachingMiddleware",contextSchema:Pg,wrapModelCall:(e,n)=>{const r=e.runtime.context.enableCaching??t?.enableCaching??Eg,s=e.runtime.context.ttl??t?.ttl??xg,o=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??Mg,i=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??Ag;if(!r||!e.model)return n(e);if(!(e.model.getName()==="ChatAnthropic"||e.model.getName()==="ConfigurableModel"&&e.model._defaultConfig?.modelProvider==="anthropic")){const h=e.model.getName(),f=`Unsupported model '${e.model.getName()==="ConfigurableModel"?`${h} (${e.model._defaultConfig?.modelProvider})`:h}'. Prompt caching requires an Anthropic model`;if(i==="raise")throw new ii(`${f} (e.g., 'anthropic:claude-4-0-sonnet').`);return i==="warn"&&console.warn(`PromptCachingMiddleware: Skipping caching for ${h}. Consider switching to an Anthropic model for caching benefits.`),n(e)}if(e.state.messages.length+(e.systemPrompt?1:0)<o)return n(e);const c=e.messages.at(-1);if(!c)return n(e);const u=Object.getPrototypeOf(c).constructor;if(Array.isArray(c.content)){const h=new u({...c,content:[...c.content.slice(0,-1),{...c.content.at(-1),cache_control:{type:"ephemeral",ttl:s}}]});return n({...e,messages:[...e.messages.slice(0,-1),h]})}else if(typeof c.content=="string"){const h=new u({...c,content:[{type:"text",text:c.content,cache_control:{type:"ephemeral",ttl:s}}]});return n({...e,messages:[...e.messages.slice(0,-1),h]})}throw new ii("Last message content is not a string or array")}})}var Og={};Ci(Og,{AIMessage:()=>I,AIMessageChunk:()=>Gt,BaseMessage:()=>cn,BaseMessageChunk:()=>Iu,ClearToolUsesEdit:()=>Gl,Document:()=>We,DynamicStructuredTool:()=>Bn,DynamicTool:()=>vc,FakeToolCallingModel:()=>nf,HumanMessage:()=>ee,HumanMessageChunk:()=>Pu,InMemoryStore:()=>Vi,MIDDLEWARE_BRAND:()=>Ni,MultipleStructuredOutputsError:()=>fs,MultipleToolsBoundError:()=>ds,PIIDetectionError:()=>Dl,ProviderStrategy:()=>Xe,StructuredOutputParsingError:()=>xi,StructuredTool:()=>Er,SystemMessage:()=>te,SystemMessageChunk:()=>Au,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>Xl,Tool:()=>wc,ToolCallLimitExceededError:()=>Yl,ToolInvocationError:()=>Ws,ToolMessage:()=>j,ToolMessageChunk:()=>Mu,ToolStrategy:()=>Je,anthropicPromptCachingMiddleware:()=>Ig,applyStrategy:()=>Hl,context:()=>Ia,contextEditingMiddleware:()=>og,countTokensApproximately:()=>Gs,createAgent:()=>Nl,createMiddleware:()=>se,detectCreditCard:()=>Ul,detectEmail:()=>Fl,detectIP:()=>Vl,detectMacAddress:()=>Bl,detectUrl:()=>zl,dynamicSystemPromptMiddleware:()=>Rm,filterMessages:()=>xu,humanInTheLoopMiddleware:()=>_m,initChatModel:()=>it,llmToolSelectorMiddleware:()=>Fm,modelCallLimitMiddleware:()=>Ql,modelFallbackMiddleware:()=>wg,modelRetryMiddleware:()=>vg,openAIModerationMiddleware:()=>kg,piiMiddleware:()=>Zm,piiRedactionMiddleware:()=>ng,providerStrategy:()=>nh,resolveRedactionRule:()=>Wl,summarizationMiddleware:()=>km,todoListMiddleware:()=>pg,tool:()=>hi,toolCallLimitMiddleware:()=>ug,toolEmulatorMiddleware:()=>_g,toolRetryMiddleware:()=>bg,toolStrategy:()=>th,trimMessages:()=>vi});var Ls={},Rt,Or=(Rt=class extends Er{name="mcp_server_tool";description="Base tool for MCP server operations.";schema;_manager;constructor(e){super(),this._manager=e}async _call(e,n,r){throw new Error("Method not implemented.")}get manager(){return this._manager}},$(Rt,"MCPServerTool"),Rt),Ng=ve({}),jt,$g=(jt=class extends Or{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=Ng;constructor(e){super(e)}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."}},$(jt,"AcquireActiveMCPServerTool"),jt),Lt,Rg=(Lt=class extends Er{name="add_mcp_server_from_config";description="Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";schema=ve({serverName:kr().describe("The name for the new MCP server."),serverConfig:ke().describe('The configuration object for the server. This should not include the top-level "mcpServers" key.')});manager;constructor(e){super(),this.manager=e}async _call({serverName:e,serverConfig:n}){try{this.manager.client.addServer(e,n);let r=`Server '${e}' added to the client.`;y.debug(`Connecting to new server '${e}' and discovering tools.`);const o=(await this.manager.client.createSession(e)).connector,i=await this.manager.adapter.createToolsFromConnectors([o]);this.manager.serverTools[e]=i,this.manager.initializedServers[e]=!0,this.manager.activeServer=e;const a=i.length;return r+=` Session created and connected. '${e}' is now the active server with ${a} tools available.`,r+=`
338
+
339
+ ${i.map(l=>l.name).join(`
340
+ `)}`,y.info(r),r}catch(r){return y.error(`Failed to add or connect to server '${e}': ${r.message}`),`Failed to add or connect to server '${e}': ${r.message}`}}},$(Lt,"AddMCPServerFromConfigTool"),Lt),jg=ve({serverName:kr().describe("The name of the MCP server.")}),Dt,Lg=(Dt=class extends Or{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=jg;constructor(e){super(e)}async _call({serverName:e}){const n=this.manager.client.getServerNames();if(!n.includes(e)){const r=n.length>0?n.join(", "):"none";return`Server '${e}' not found. Available servers: ${r}`}if(this.manager.activeServer===e)return`Already connected to MCP server '${e}'`;try{let r=this.manager.client.getSession(e);if(y.debug(`Using existing session for server '${e}'`),r||(y.debug(`Creating new session for server '${e}'`),r=await this.manager.client.createSession(e)),this.manager.activeServer=e,!this.manager.serverTools[e]){const i=r.connector,a=await this.manager.adapter.createToolsFromConnectors([i]),l=await this.manager.adapter.createResourcesFromConnectors([i]),c=await this.manager.adapter.createPromptsFromConnectors([i]),u=[...a,...l,...c];this.manager.serverTools[e]=u,this.manager.initializedServers[e]=!0,y.debug(`Loaded ${u.length} items for server '${e}': ${a.length} tools, ${l.length} resources, ${c.length} prompts`)}const o=(this.manager.serverTools[e]||[]).length;return`Connected to MCP server '${e}'. ${o} tools, resources, and prompts are now available.`}catch(r){return y.error(`Error connecting to server '${e}': ${String(r)}`),`Failed to connect to server '${e}': ${String(r)}`}}},$(Dt,"ConnectMCPServerTool"),Dt),Dg=ve({}),Ft,Fg=(Ft=class extends Or{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=Dg;constructor(e){super(e)}async _call(){const e=this.manager.client.getServerNames();if(e.length===0)return"No MCP servers are currently defined.";const n=["Available MCP servers:"];for(const r of e){const o=r===this.manager.activeServer?" (ACTIVE)":"";n.push(`- ${r}${o}`);try{const i=this.manager.serverTools?.[r]??[],a=Array.isArray(i)?i.length:0;n.push(`${a} tools available for this server
341
+ `)}catch(i){y.error(`Unexpected error listing tools for server '${r}': ${String(i)}`)}}return n.join(`
342
+ `)}},$(Ft,"ListMCPServersTool"),Ft),Ug=ve({}),Ut,Vg=(Ut=class extends Or{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=Ug;constructor(e){super(e)}async _call(){if(!this.manager.activeServer)return"No MCP server is currently active, so there's nothing to disconnect from.";const e=this.manager.activeServer;return this.manager.activeServer=null,`Successfully disconnected from MCP server '${e}'.`}},$(Ut,"ReleaseMCPServerConnectionTool"),Ut);function Tr(t,e){if(t===e)return!0;if(t==null||e==null||typeof t!=typeof e)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)&&Array.isArray(e))return t.length!==e.length?!1:t.every((n,r)=>Tr(n,e[r]));if(typeof t=="object"&&typeof e=="object"){const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>Object.prototype.hasOwnProperty.call(e,s)&&Tr(t[s],e[s]))}return!1}$(Tr,"isEqual");var Vt,ai=(Vt=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(e,n,r){this.client=e,this.adapter=n,this.overrideManagementTools=r}setManagementTools(e){this.overrideManagementTools=e,y.info(`Overriding default management tools with a new set of ${e.length} tools.`)}logState(e){const n=this.client.getServerNames(),r=Object.keys(this.client.getAllActiveSessions());if(n.length===0){y.info("Server Manager State: No servers configured.");return}const s=n.map(o=>({"Server Name":o,Connected:r.includes(o)?"✅":"❌",Initialized:this.initializedServers[o]?"✅":"❌","Tool Count":this.serverTools[o]?.length??0,Active:this.activeServer===o?"✅":"❌"}));y.info(`Server Manager State: [${e}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&y.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const e=this.client.getServerNames();for(const n of e)try{let r=null;if(r=this.client.getSession(n),y.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(y.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),y.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let o=[],i=[],a=[];try{o=await this.adapter.createToolsFromConnectors([s]),i=await this.adapter.createResourcesFromConnectors([s]),a=await this.adapter.createPromptsFromConnectors([s])}catch(h){y.error(`Failed to create tools/resources/prompts from connector for server '${n}': ${h}`);continue}const l=[...o,...i,...a],c=this.serverTools[n];!c||!Tr(c,l)?(this.serverTools[n]=l,this.initializedServers[n]=!0,y.debug(`Prefetched ${l.length} items for server '${n}': ${o.length} tools, ${i.length} resources, ${a.length} prompts.`)):y.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){y.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){y.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new Rg(this),new Fg(this),new Lg(this),new $g(this),new Vg(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return y.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},$(Vt,"ServerManager"),Vt),Bt,li=(Bt=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(e={}){this.customCallbacks=e.customCallbacks,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.agentId=e.agentId,this.metadata=e.metadata,this.metadataProvider=e.metadataProvider,this.tagsProvider=e.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:e,langfuseInitPromise:n}=await Ht(async()=>{const{langfuseHandler:s,langfuseInitPromise:o}=await Promise.resolve().then(()=>ui);return{langfuseHandler:s,langfuseInitPromise:o}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await Ht(async()=>{const{initializeLangfuse:o}=await Promise.resolve().then(()=>ui);return{initializeLangfuse:o}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),y.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const s=n();s&&await s}const r=e();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),y.debug("ObservabilityManager: Langfuse handler available"))}catch{y.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(y.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?y.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):y.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(y.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(e=>e.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const e=await this.getCallbacks(),n=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},s=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&e.length>0,callbackCount:e.length,handlerNames:n,metadata:r,tags:s}}addCallback(e){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(e),y.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],y.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const e=await this.getCallbacks();for(const n of e)"flushAsync"in n&&typeof n.flushAsync=="function"&&await n.flushAsync();y.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const e=await this.getCallbacks();for(const n of e)"shutdownAsync"in n&&typeof n.shutdownAsync=="function"?await n.shutdownAsync():"shutdown"in n&&typeof n.shutdown=="function"&&await n.shutdown();y.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},$(Bt,"ObservabilityManager"),Bt),Bg="/api/v1/chats",zg="/api/v1/chats/{chat_id}/execute";function nc(t,e,n,r,s){if(typeof t=="object"&&t!==null){const o=t;return{query:o.prompt,maxSteps:o.maxSteps,manageConnector:o.manageConnector,externalHistory:o.externalHistory,outputSchema:o.schema}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s}}$(nc,"normalizeRemoteRunOptions");var zt,Wg=(zt=class{agentId;apiKey;baseUrl;chatId=null;constructor(e){this.agentId=e.agentId,this.baseUrl=e.baseUrl??"https://cloud.mcp-use.com";const n=e.apiKey??(typeof process<"u"&&Ls?.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(e){return Vn(e)}parseStructuredResponse(e,n){let r;if(typeof e=="object"&&e!==null)if("result"in e){const s=e.result;typeof s=="object"&&s!==null&&"result"in s?r=s.result:r=s}else r=e;else if(typeof e=="string")try{r=JSON.parse(e)}catch{r={content:e}}else r=e;try{return n.parse(r)}catch(s){y.warn(`Failed to parse structured output: ${s}`);const o=n._def?.shape();if(o&&"content"in o)return n.parse({content:String(r)});throw s}}async createChatSession(){const e={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}${Bg}`;y.info(`📝 Creating chat session for agent ${this.agentId}`);try{const s=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(e)});if(!s.ok){const a=await s.text(),l=s.status;throw l===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: ${l} - ${a}`)}const i=(await s.json()).id;return y.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(e,n,r,s,o){const{query:i,maxSteps:a,externalHistory:l,outputSchema:c}=nc(e,n,r,s,o);l!==void 0&&y.warn("External history is not yet supported for remote execution");try{y.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const u=this.chatId,h={query:i,max_steps:a??10};c&&(h.output_schema=this.pydanticToJsonSchema(c),y.info("🔧 Using structured output with schema"));const d={"Content-Type":"application/json","x-api-key":this.apiKey},f=`${this.baseUrl}${zg.replace("{chat_id}",u)}`;y.info(`🚀 Executing agent in chat ${u}`);const p=await fetch(f,{method:"POST",headers:d,body:JSON.stringify(h),signal:AbortSignal.timeout(3e5)});if(!p.ok){const S=await p.text(),C=p.status;throw C===401?(y.error(`❌ Authentication failed: ${S}`),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.")):C===403?(y.error(`❌ Access forbidden: ${S}`),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.`)):C===404?(y.error(`❌ Agent not found: ${S}`),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.`)):C===422?(y.error(`❌ Validation error: ${S}`),new Error(`Request validation failed: ${S}. Please check your query parameters and output schema format.`)):C===500?(y.error(`❌ Server error: ${S}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(y.error(`❌ Remote execution failed with status ${C}: ${S}`),new Error(`Remote agent execution failed: ${C} - ${S}`))}const m=await p.json();if(y.info(`🔧 Response: ${JSON.stringify(m)}`),y.info("✅ Remote execution completed successfully"),typeof m=="object"&&m!==null){if(m.status==="error"||m.error!==null){const S=m.error??String(m);throw y.error(`❌ Remote agent execution failed: ${S}`),new Error(`Remote agent execution failed: ${S}`)}if(String(m).includes("failed to initialize"))throw y.error(`❌ Agent initialization failed: ${m}`),new Error(`Agent initialization failed on remote server. This usually indicates:
343
+ • Invalid agent configuration (LLM model, system prompt)
344
+ • Missing or invalid MCP server configurations
345
+ • Network connectivity issues with MCP servers
346
+ • Missing environment variables or credentials
347
+ Raw error: ${m}`)}return c?this.parseStructuredResponse(m,c):typeof m=="object"&&m!==null&&"result"in m?m.result:typeof m=="string"?m:String(m)}catch(u){throw u instanceof Error?u.name==="AbortError"?(y.error(`❌ Remote execution timed out: ${u}`),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.")):(y.error(`❌ Remote execution error: ${u}`),new Error(`Remote agent execution failed: ${u.message}`)):(y.error(`❌ Remote execution error: ${u}`),new Error(`Remote agent execution failed: ${String(u)}`))}}async*stream(e,n,r,s,o){return await this.run(e,n,r,s,o)}async close(){y.info("🔌 Remote agent client closed")}},$(zt,"RemoteAgent"),zt),kn={openai:{package:"@langchain/openai",className:"ChatOpenAI",envVars:["OPENAI_API_KEY"],defaultModel:"gpt-4o"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic",envVars:["ANTHROPIC_API_KEY"],defaultModel:"claude-3-5-sonnet-20241022"},google:{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI",envVars:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY"],defaultModel:"gemini-pro"},groq:{package:"@langchain/groq",className:"ChatGroq",envVars:["GROQ_API_KEY"],defaultModel:"llama-3.1-70b-versatile"}};function yo(t){const e=t.split("/");if(e.length!==2)throw new Error(`Invalid LLM string format. Expected 'provider/model', got '${t}'. Examples: 'openai/gpt-4', 'anthropic/claude-3-5-sonnet-20241022', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`);const[n,r]=e;if(!n||!r)throw new Error(`Invalid LLM string format. Both provider and model must be non-empty. Got '${t}'`);const s=n.toLowerCase();if(!(s in kn)){const o=Object.keys(kn).join(", ");throw new Error(`Unsupported LLM provider '${n}'. Supported providers: ${o}`)}return{provider:s,model:r}}$(yo,"parseLLMString");function rc(t,e){if(e?.apiKey)return e.apiKey;const n=kn[t];if(typeof process<"u"&&Ls)for(const s of n.envVars){const o=Ls[s];if(o)return y.debug(`Using API key from environment variable ${s} for provider ${t}`),o}const r=n.envVars.join(" or ");throw new Error(`API key not found for provider '${t}'. Set ${r} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${t}/model', llmConfig: { apiKey: 'your-key' } })`)}$(rc,"getAPIKey");async function sc(t,e){y.info(`Creating LLM from string: ${t}`);const{provider:n,model:r}=yo(t),s=kn[n],o=rc(n,e);let i;try{y.debug(`Importing package ${s.package}...`),i=await import(s.package)}catch(c){throw c?.code==="MODULE_NOT_FOUND"||c?.message?.includes("Cannot find module")||c?.message?.includes("Cannot find package")?new Error(`Package '${s.package}' is not installed. Install it with: npm install ${s.package} or yarn add ${s.package}`):new Error(`Failed to import ${s.package}: ${c?.message||c}`)}const a=i[s.className];if(!a)throw new Error(`Could not find ${s.className} in package ${s.package}. This might be a version compatibility issue.`);const l={model:r,apiKey:o,...e};e?.apiKey&&(delete l.apiKey,l.apiKey=o),(n==="anthropic"||n==="google"||n==="openai"||n==="groq")&&(l.model=r);try{const c=new a(l);return y.info(`Successfully created ${n} LLM with model ${r}`),c}catch(c){throw new Error(`Failed to instantiate ${s.className} with model '${r}': ${c?.message||c}`)}}$(sc,"createLLMFromString");function Hg(t){try{return yo(t),!0}catch{return!1}}$(Hg,"isValidLLMString");function Gg(){return Object.keys(kn)}$(Gg,"getSupportedProviders");function oc(t,e){const n=new Set(e??[]),r=[];for(const s of t){if(n.has(s.name))continue;const o=s.description.replace(/\{/g,"{{").replace(/\}/g,"}}");r.push(`- ${s.name}: ${o}`)}return r}$(oc,"generateToolDescriptions");function ic(t,e,n){const r=e.join(`
348
+ `);let s;return t.includes("{tool_descriptions}")?s=t.replace("{tool_descriptions}",r):(console.warn("`{tool_descriptions}` placeholder not found; appending at end."),s=`${t}
349
+
350
+ Available tools:
351
+ ${r}`),n&&(s+=`
352
+
353
+ ${n}`),s}$(ic,"buildSystemPromptContent");function ac(t,e,n,r,s,o,i){if(o)return new te({content:o});const a=r?n:e,l=oc(t,s),c=ic(a,l,i);return new te({content:c})}$(ac,"createSystemMessage");var Kg=`You are a helpful AI assistant.
354
+ You have access to the following tools:
355
+
356
+ {tool_descriptions}
357
+
358
+ Use the following format:
359
+
360
+ Question: the input question you must answer
361
+ Thought: you should always think about what to do
362
+ Action: the action to take, should be one of the available tools
363
+ Action Input: the input to the action
364
+ Observation: the result of the action
365
+ ... (this Thought/Action/Action Input/Observation can repeat N times)
366
+ Thought: I now know the final answer
367
+ Final Answer: the final answer to the original input question`,Jg=`You are a helpful assistant designed to interact with MCP
368
+ (Model Context Protocol) servers. You can manage connections to different servers and use the tools
369
+ provided by the currently active server.
370
+
371
+ Important: The available tools change depending on which server is active.
372
+ If a request requires tools not listed below (e.g., file operations, web browsing,
373
+ image manipulation), you MUST first connect to the appropriate server using
374
+ 'connect_to_mcp_server'.
375
+ Use 'list_mcp_servers' to find the relevant server if you are unsure.
376
+ Only after successfully connecting and seeing the new tools listed in
377
+ the response should you attempt to use those server-specific tools.
378
+ Before attempting a task that requires specific tools, you should
379
+ ensure you are connected to the correct server and aware of its
380
+ available tools. If unsure, use 'list_mcp_servers' to see options
381
+ or 'get_active_mcp_server' to check the current connection.
382
+
383
+ When you connect to a server using 'connect_to_mcp_server',
384
+ you will be informed about the new tools that become available.
385
+ You can then use these server-specific tools in subsequent steps.
386
+
387
+ Here are the tools *currently* available to you (this list includes server management tools and will
388
+ change when you connect to a server):
389
+ {tool_descriptions}
390
+ `;function ar(t,e,n,r,s){if(typeof t=="object"&&t!==null){const o=t;return{query:o.prompt,maxSteps:o.maxSteps,manageConnector:o.manageConnector,externalHistory:o.externalHistory,outputSchema:o.schema}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s}}$(ar,"normalizeRunOptions");var Wt,iy=(Wt=class{static getPackageVersion(){return gc()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new Wg({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new St,this.telemetry=Rr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new li({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(typeof e.llm=="string"){if(this.isSimplifiedMode=!0,this.llmString=e.llm,this.llmConfig=e.llmConfig,this.mcpServersConfig=e.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw new Error("Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }");this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],y.info(`🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw new Error("Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.");if(this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.isSimplifiedMode)this.adapter=e.adapter??new St(this.disallowedTools),this.telemetry=Rr.getInstance(),this.modelProvider="unknown",this.modelName="unknown";else{if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new St(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new ai(this.client,this.adapter)}else this.adapter=e.adapter??new St(this.disallowedTools);if(this.telemetry=Rr.getInstance(),this.llm){const[r,s]=bo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new li({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:$(()=>this.getMetadata(),"metadataProvider"),tagsProvider:$(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:$(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:$(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:$(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(y.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(y.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){y.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await Ht(async()=>{const{MCPClient:s}=await import("./client-CsMGnuwC.js");return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),y.info("✅ MCPClient created successfully")}if(this.llmString){y.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await sc(this.llmString,this.llmConfig),y.info("✅ LLM created successfully");const[r,s]=bo(this.llm);this.modelProvider=r,this.modelName=s}catch(r){throw new Error(`Failed to create LLM from string '${this.llmString}': ${r?.message||r}`)}}if(this.useServerManager){if(!this.client)throw new Error("'client' must be available when 'useServerManager' is true.");this.serverManager=new ai(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),y.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),y.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else{const s=await this.adapter.createToolsFromConnectors(Object.values(this.sessions).map(a=>a.connector)),o=await this.adapter.createResourcesFromConnectors(Object.values(this.sessions).map(a=>a.connector)),i=await this.adapter.createPromptsFromConnectors(Object.values(this.sessions).map(a=>a.connector));this._tools=[...s,...o,...i],y.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{y.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),y.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}y.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Kg;this.systemMessage=ac(e,n,Jg,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof te))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(o=>o.name);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Ql({runLimit:this.maxSteps})],s=Nl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new te(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof te)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new St(this.disallowedTools),this._initialized&&y.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},y.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],y.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){y.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(y.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){y.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else y.warn(`Unsupported metadata value type for key '${o}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){y.warn(`Failed to get config for server '${s}': ${o}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){y.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof I)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof ee)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof j)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof I||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,o){const{query:i,maxSteps:a,manageConnector:l,externalHistory:c,outputSchema:u}=ar(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(i,a,l,c,u);const h=this.stream(i,a,l,c,u);return this._consumeAndReturn(h)}async*stream(e,n,r=!0,s,o){const{query:i,maxSteps:a,manageConnector:l,externalHistory:c,outputSchema:u}=ar(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(i,a,l,c,u);let h=!1;const d=Date.now();let f=!1,p=null,m=0;try{if(l&&!this._initialized?(await this.initialize(),h=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),h=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const k=this.serverManager.tools,_=new Set(k.map(x=>x.name)),v=new Set(this._tools.map(x=>x.name));(_.size!==v.size||[..._].some(x=>!v.has(x)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[..._].join(", ")}`),this._tools=k,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const S=c??this.conversationHistory,C=[];for(const k of S)(this._isHumanMessageLike(k)||this._isAIMessageLike(k)||this._isToolMessageLike(k))&&C.push(k);const E=i.length>50?`${i.slice(0,50).replace(/\n/g," ")}...`:i.replace(/\n/g," ");y.info(`💬 Received query: '${E}'`),y.info("🏁 Starting agent execution");const b=3;let w=0;const g=[...C,new ee(i)];for(;w<=b;){const k={messages:g};let _=!1;const v=await this._agentExecutor.stream(k,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const x of v){for(const[T,M]of Object.entries(x))if(y.debug(`📦 Node '${T}' output: ${JSON.stringify(M)}`),M&&typeof M=="object"&&"messages"in M){let P=M.messages;Array.isArray(P)||(P=[P]);for(const N of P)g.includes(N)||g.push(N);for(const N of P){if("tool_calls"in N&&Array.isArray(N.tool_calls)&&N.tool_calls.length>0)for(const oe of N.tool_calls){const ae=oe.name||"unknown",Ce=oe.args||{};this.toolsUsedNames.push(ae),m++;let Pe=JSON.stringify(Ce);Pe.length>100&&(Pe=`${Pe.slice(0,97)}...`),y.info(`🔧 Tool call: ${ae} with input: ${Pe}`),yield{action:{tool:ae,toolInput:Ce,log:`Calling tool ${ae}`},observation:""}}if(this._isToolMessageLike(N)){const oe=N.content;let ae=String(oe);if(ae.length>100&&(ae=`${ae.slice(0,97)}...`),ae=ae.replace(/\n/g," "),y.info(`📄 Tool result: ${ae}`),this.useServerManager&&this.serverManager){const Ce=this.serverManager.tools,Pe=new Set(Ce.map(nn=>nn.name)),Nn=new Set(this._tools.map(nn=>nn.name));if(Pe.size!==Nn.size||[...Pe].some(nn=>!Nn.has(nn))){y.info(`🔄 Tools changed during execution. New tools: ${[...Pe].join(", ")}`),this._tools=Ce,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),_=!0,w++,y.info(`🔃 Restarting execution with updated tools (restart ${w}/${b})`);break}}}this._isAIMessageLike(N)&&!this._messageHasToolCalls(N)&&(p=this._normalizeOutput(this._getMessageContent(N)),y.info("✅ Agent finished with output"))}if(_)break}if(_)break}if(!_)break;if(w>b){y.warn(`⚠️ Max restarts (${b}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const k=g.slice(C.length);for(const _ of k)this.addToHistory(_)}if(u&&p)try{y.info("🔧 Attempting structured output...");const k=await this._attemptStructuredOutput(p,this.llm,u);return this.memoryEnabled&&this.addToHistory(new I(`Structured result: ${JSON.stringify(k)}`)),y.info("✅ Structured output successful"),f=!0,k}catch(k){throw y.error(`❌ Structured output failed: ${k}`),new Error(`Failed to generate structured output: ${k instanceof Error?k.message:String(k)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,p||"No output generated"}catch(S){throw y.error(`❌ Error running query: ${S}`),h&&l&&(y.info("🧹 Cleaning up resources after error"),await this.close()),S}finally{const S=Date.now()-d;let C=0;this.client?C=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(C=this.connectors.length);const E=this.memoryEnabled?this.conversationHistory.length:0,b=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:i,success:f,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:C,serverIdentifiers:this.connectors.map(w=>w.publicIdentifier),totalToolsAvailable:b.length,toolsAvailableNames:b.map(w=>w.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:l??!0,externalHistoryUsed:c!==void 0,stepsTaken:m,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:p||"",executionTimeMs:S,errorType:f?null:"execution_error",conversationHistoryLength:E}),l&&!this.client&&h&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(y.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(y.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new St)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Ht(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-D8OCMEUd.js");return{prettyStreamEvents:l}},__vite__mapDeps([3,1,2])),a="";for await(const l of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o){const i=ar(e,n,r,s,o);let{query:a}=i;const{maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:h}=i;let d=!1;const f=Date.now();let p=!1,m=0,S=0,C="";h&&(a=this._enhanceQueryWithSchema(a,h));try{c&&!this._initialized?(await this.initialize(),d=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),d=!0);const E=this._agentExecutor;if(!E)throw new Error("MCP agent failed to initialize");this.maxSteps=l??this.maxSteps;const b=typeof a=="string"&&a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:typeof a=="string"?a.replace(/\n/g," "):String(a);y.info(`💬 Received query for streamEvents: '${b}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${b}`),this.addToHistory(new ee({content:a})));const w=u??this.conversationHistory,g=[];for(const v of w)this._isHumanMessageLike(v)||this._isAIMessageLike(v)||this._isToolMessageLike(v)?g.push(v):y.info(`⚠️ Skipped message of type: ${v.constructor?.name||typeof v}`);const k=[...g,new ee(a)];y.info("callbacks",this.callbacks);const _=E.streamEvents({messages:k},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const v of _)if(m++,!(!v||typeof v!="object")){if(v.event==="on_chat_model_stream"&&v.data?.chunk?.content&&(S+=v.data.chunk.content.length),v.event==="on_chat_model_stream"&&v.data?.chunk){const x=v.data.chunk;if(x.content){C||(C="");const T=this._normalizeOutput(x.content);C+=T,y.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield v,v.event==="on_chain_end"&&v.data?.output&&!C){const x=v.data.output;Array.isArray(x)&&x.length>0&&x[0]?.text?C=x[0].text:typeof x=="string"?C=x:x&&typeof x=="object"&&"output"in x&&(C=x.output)}}if(h&&C){y.info("🔧 Attempting structured output conversion...");try{let v=!1,x=null,T=null;this._attemptStructuredOutput(C,this.llm,h).then(P=>(v=!0,x=P,P)).catch(P=>{throw v=!0,T=P,P});let M=0;for(;!v;)await new Promise(P=>setTimeout(P,2e3)),v||(M++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${M*2}s)`,elapsed:M*2}});if(T)throw T;x&&(yield{event:"on_structured_output",data:{output:x}},this.memoryEnabled&&this.addToHistory(new I(`Structured result: ${JSON.stringify(x)}`)),y.info("✅ Structured output successful"))}catch(v){y.warn(`⚠️ Structured output failed: ${v}`),yield{event:"on_structured_output_error",data:{error:v instanceof Error?v.message:String(v)}}}}else this.memoryEnabled&&C&&this.addToHistory(new I(C));console.log(`
391
+
392
+ `),y.info(`🎉 StreamEvents complete - ${m} events emitted`),p=!0}catch(E){throw y.error(`❌ Error during streamEvents: ${E}`),d&&c&&(y.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),E}finally{const E=Date.now()-f;let b=0;this.client?b=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(b=this.connectors.length);const w=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:a,success:p,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:b,serverIdentifiers:this.connectors.map(g=>g.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(g=>g.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:l??null,manageConnector:c??!0,externalHistoryUsed:u!==void 0,response:`[STREAMED RESPONSE - ${S} chars]`,executionTimeMs:E,errorType:p?null:"streaming_error",conversationHistoryLength:w}),c&&!this.client&&d&&(y.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){y.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),y.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,o="";if(y.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Vn(r),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")s=n.withStructuredOutput(r);else if(n)s=n;else throw new Error("LLM is required for structured output");const i=Vn(r),{$schema:a,additionalProperties:l,...c}=i;o=JSON.stringify(c,null,2),y.info(`🔄 Schema description: ${o}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),y.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){y.info(`🔄 Structured output attempt ${f}/${h}`);let p=`
393
+ Please format the following information according to the EXACT schema specified below.
394
+ You must use the exact field names and types as shown in the schema.
395
+
396
+ Required schema format:
397
+ ${o}
398
+
399
+ Content to extract from:
400
+ ${u}
401
+
402
+ IMPORTANT:
403
+ - Use ONLY the field names specified in the schema
404
+ - Match the data types exactly (string, number, boolean, array, etc.)
405
+ - Include ALL required fields
406
+ - Return valid JSON that matches the schema structure exactly
407
+ - For missing data: use null for nullable fields, omit optional fields entirely
408
+ - Do NOT use empty strings ("") or zero (0) as placeholders for missing data
409
+ `;f>1&&(p+=`
410
+
411
+ PREVIOUS ATTEMPT FAILED with error: ${d}
412
+ Please fix the issues mentioned above and ensure the output matches the schema exactly.
413
+ `);try{y.info(`🔄 Structured output attempt ${f} - using streaming approach`);const m=u.length>300?`${u.slice(0,300)}...`:u;y.info(`🔄 Content being formatted (${u.length} chars): ${m}`),y.info(`🔄 Full format prompt (${p.length} chars):
414
+ ${p}`);const S=await s.stream(p);let C=null,E=0;for await(const w of S){if(E++,y.debug(`Chunk ${E}: ${JSON.stringify(w,null,2)}`),typeof w=="string")try{C=JSON.parse(w)}catch{y.warn(`🔄 Failed to parse string chunk as JSON: ${w}`)}else if(w&&typeof w=="object")C=w;else try{C=JSON.parse(String(w))}catch{y.warn(`🔄 Failed to parse chunk as JSON: ${w}`)}E%10===0&&y.debug(`🔄 Structured output streaming: ${E} chunks`)}if(y.info(`🔄 Structured result attempt ${f}: ${JSON.stringify(C,null,2)}`),!C)throw new Error("No structured result received from stream");const b=this._validateStructuredResult(C,r);return y.info(`✅ Structured output successful on attempt ${f}`),b}catch(m){if(d=m instanceof Error?m.message:String(m),y.warn(`⚠️ Structured output attempt ${f} failed: ${d}`),f===h)throw y.error(`❌ All ${h} structured output attempts failed`),new Error(`Failed to generate valid structured output after ${h} attempts. Last error: ${d}`);continue}}throw new Error("Unexpected error in structured output generation")}_validateStructuredResult(e,n){try{const r=n.parse(e),s=n;if(s._def&&s._def.shape)for(const[o,i]of Object.entries(s._def.shape)){const a=i,l=a.isOptional?.()??a._def?.typeName==="ZodOptional",c=a.isNullable?.()??a._def?.typeName==="ZodNullable";if(!l&&!c){const u=r[o];if(u==null||typeof u=="string"&&!u.trim()||Array.isArray(u)&&u.length===0)throw new Error(`Required field '${o}' is missing or empty`)}}return r}catch(r){throw y.debug(`Validation details: ${r}`),r}}_enhanceQueryWithSchema(e,n){try{const r=Vn(n),{$schema:s,additionalProperties:o,...i}=r,a=JSON.stringify(i,null,2);return`
415
+ ${e}
416
+
417
+ IMPORTANT: Your response must include sufficient information to populate the following structured output:
418
+
419
+ ${a}
420
+
421
+ Make sure you gather ALL the required information during your task execution.
422
+ If any required information is missing, continue working to find it.
423
+ `}catch(r){return y.warn(`Could not extract schema details: ${r}`),e}}},$(Wt,"MCPAgent"),Wt),ci={};function X(t){if(typeof process<"u"&&ci)return ci[t]}$(X,"getEnvVar");var qg=X("MCP_USE_LANGFUSE")?.toLowerCase()==="false",En={handler:null,client:null,initPromise:null};async function wo(t,e,n,r){try{const s=await Ht(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){y.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:o}=s,u=class u extends o{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(d,f,p,m,S){super(d),this.agentId=f,this.metadata=p,this.metadataProvider=m,this.tagsProvider=S,this.verbose=d?.verbose??!1}async handleChainStart(d,f,p,m,S,C,E,b){y.debug("Langfuse: Chain start intercepted");const w=this.getCustomTags(),g=this.getMetadata(),k=[...S||[],...w],_={...C||{},...g};return this.verbose&&(y.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(k)}`),y.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(_)}`)),super.handleChainStart(d,f,p,m,k,_,E,b)}getCustomTags(){const d=[],f=this.getEnvironmentTag();if(f&&d.push(`env:${f}`),this.agentId&&d.push(`agent_id:${this.agentId}`),this.tagsProvider){const p=this.tagsProvider();p&&p.length>0&&d.push(...p)}return d}getMetadata(){const d={},f=this.getEnvironmentTag();if(f&&(d.env=f),this.agentId&&(d.agent_id=this.agentId),this.metadata&&Object.assign(d,this.metadata),this.metadataProvider){const p=this.metadataProvider();p&&Object.assign(d,p)}return d}getEnvironmentTag(){const d=X("MCP_USE_AGENT_ENV");if(!d)return"unknown";const f=d.toLowerCase();return f==="local"||f==="development"?"local":f==="production"||f==="prod"?"production":f==="staging"||f==="stage"?"staging":f==="hosted"||f==="cloud"?"hosted":f.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...d){return y.debug("Langfuse: LLM start intercepted"),this.verbose&&y.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return y.debug("Langfuse: Tool start intercepted"),this.verbose&&y.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return y.debug("Langfuse: Retriever start intercepted"),this.verbose&&y.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return y.debug("Langfuse: Agent action intercepted"),this.verbose&&y.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return y.debug("Langfuse: Agent end intercepted"),this.verbose&&y.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};$(u,"LoggingCallbackHandler");let i=u;const a=e||(n?n():{}),l=r?r():[],c={publicKey:X("LANGFUSE_PUBLIC_KEY"),secretKey:X("LANGFUSE_SECRET_KEY"),baseUrl:X("LANGFUSE_HOST")||X("LANGFUSE_BASEURL")||"https://cloud.langfuse.com",flushAt:Number.parseInt(X("LANGFUSE_FLUSH_AT")||"15"),flushInterval:Number.parseInt(X("LANGFUSE_FLUSH_INTERVAL")||"10000"),release:X("LANGFUSE_RELEASE"),requestTimeout:Number.parseInt(X("LANGFUSE_REQUEST_TIMEOUT")||"10000"),enabled:X("LANGFUSE_ENABLED")!=="false",traceName:a.trace_name||X("LANGFUSE_TRACE_NAME")||"mcp-use-agent",sessionId:a.session_id||void 0,userId:a.user_id||void 0,tags:l.length>0?l:void 0,metadata:a||void 0};y.debug("Langfuse handler config:",JSON.stringify({traceName:c.traceName,sessionId:c.sessionId,userId:c.userId,tags:c.tags},null,2)),En.handler=new i(c,t,e,n,r),y.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await Ht(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;En.client=new d({publicKey:X("LANGFUSE_PUBLIC_KEY"),secretKey:X("LANGFUSE_SECRET_KEY"),baseUrl:X("LANGFUSE_HOST")||"https://cloud.langfuse.com"}),y.debug("Langfuse client initialized")}}catch(h){y.debug(`Langfuse client initialization failed: ${h}`)}}catch(s){y.debug(`Langfuse initialization error: ${s}`)}}$(wo,"initializeLangfuse");qg?y.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!X("LANGFUSE_PUBLIC_KEY")||!X("LANGFUSE_SECRET_KEY")?y.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):En.initPromise=wo();var Yg=$(()=>En.handler,"langfuseHandler"),Xg=$(()=>En.initPromise,"langfuseInitPromise");const ui=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:wo,langfuseHandler:Yg,langfuseInitPromise:Xg},Symbol.toStringTag,{value:"Module"}));export{qu as BaseAdapter,cy as BaseConnector,uy as BrowserOAuthClientProvider,hy as BrowserTelemetry,dy as HttpConnector,fy as Logger,iy as MCPAgent,py as MCPClient,my as MCPSession,li as ObservabilityManager,Wg as RemoteAgent,gy as Tel,Rr as Telemetry,yy as VERSION,sc as createLLMFromString,Ku as createReadableStreamFromGenerator,gc as getPackageVersion,Gg as getSupportedProviders,Hg as isValidLLMString,y as logger,wy as onMcpAuthorization,yo as parseLLMString,vy as setBrowserTelemetrySource,by as setTelemetrySource,Gu as streamEventsToAISDK,Ju as streamEventsToAISDKWithTools};