zen-code 4.9.2 → 4.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/dist/app.js +94 -128
  2. package/dist/chunk-075hks9v.js +1 -0
  3. package/dist/chunk-0fj768k4.js +112 -0
  4. package/dist/chunk-19mf2aa7.js +1 -0
  5. package/dist/chunk-1mq2jmfy.js +2 -0
  6. package/dist/chunk-1v863afn.js +278 -0
  7. package/dist/chunk-1vn8d8b8.js +1 -0
  8. package/dist/{chunk-hfypkhky.js → chunk-1w19w1bm.js} +1 -1
  9. package/dist/chunk-3dnayvgx.js +224 -0
  10. package/dist/chunk-4hg13vwj.js +1 -0
  11. package/dist/chunk-4scrkcqv.js +1 -0
  12. package/dist/chunk-54cdhhqm.js +1 -0
  13. package/dist/chunk-5m4yb9av.js +91 -0
  14. package/dist/chunk-5yd4ntp6.js +8 -0
  15. package/dist/{chunk-dxec2q4t.js → chunk-6scjjkn3.js} +1 -1
  16. package/dist/{chunk-hmemx3cw.js → chunk-7jatn15w.js} +2 -2
  17. package/dist/{chunk-0pss3s5r.js → chunk-7w9y11hj.js} +1 -1
  18. package/dist/chunk-7yzv6385.js +1 -0
  19. package/dist/{chunk-ce53j63y.js → chunk-875hayaj.js} +3 -3
  20. package/dist/chunk-8bs8r50r.js +1 -0
  21. package/dist/{chunk-x552nspp.js → chunk-8waww0j9.js} +2 -2
  22. package/dist/chunk-8ysg0rga.js +1 -0
  23. package/dist/chunk-9czhw5k6.js +4 -0
  24. package/dist/chunk-9tgp14v7.js +16 -0
  25. package/dist/{chunk-yndex7hs.js → chunk-a239dn0b.js} +1 -1
  26. package/dist/chunk-arv4h3h1.js +2 -0
  27. package/dist/chunk-b2551zfb.js +2 -0
  28. package/dist/chunk-b9emn03n.js +1 -0
  29. package/dist/chunk-bm7578sn.js +1 -0
  30. package/dist/{chunk-62zh99t6.js → chunk-bytq4kd1.js} +3 -125
  31. package/dist/chunk-c2wfgbj6.js +1 -0
  32. package/dist/{chunk-0zk0m93z.js → chunk-cef4vbtb.js} +1 -1
  33. package/dist/{chunk-hsev32dg.js → chunk-cnzhxgn5.js} +2 -2
  34. package/dist/chunk-d2770b2z.js +1 -0
  35. package/dist/chunk-d72063sm.js +2 -0
  36. package/dist/{chunk-6nfpdtn6.js → chunk-d988tv30.js} +1 -1
  37. package/dist/{chunk-55nx49pj.js → chunk-dx9k6sdd.js} +3 -3
  38. package/dist/chunk-e6ggkg36.js +2 -0
  39. package/dist/{chunk-x90r4sje.js → chunk-fjqtrakn.js} +1 -1
  40. package/dist/chunk-gbfpab0j.js +1 -0
  41. package/dist/chunk-gkvx829z.js +1 -0
  42. package/dist/{chunk-94jawhw7.js → chunk-gwf8b14k.js} +1 -1
  43. package/dist/chunk-gz7fz9fg.js +1 -0
  44. package/dist/{chunk-48vkm1yn.js → chunk-h0q3dvnv.js} +2 -2
  45. package/dist/chunk-h0qb9jk1.js +1 -0
  46. package/dist/chunk-h9y136h8.js +1 -0
  47. package/dist/chunk-hrcxdj3c.js +54 -0
  48. package/dist/chunk-hz9yw7cs.js +166 -0
  49. package/dist/{chunk-98wjxsna.js → chunk-j4y5rjne.js} +1 -1
  50. package/dist/chunk-k12y05c3.js +3 -0
  51. package/dist/{chunk-fkrydbn4.js → chunk-k6fxqssr.js} +3 -3
  52. package/dist/{chunk-vfwbx331.js → chunk-kmxdq21k.js} +2 -2
  53. package/dist/chunk-mcb8rewr.js +213 -0
  54. package/dist/{chunk-9k64296h.js → chunk-mm9w91rj.js} +1 -1
  55. package/dist/chunk-mv0xzmq8.js +2 -0
  56. package/dist/{chunk-rztre6k0.js → chunk-n849zsd3.js} +1 -1
  57. package/dist/chunk-nm253hhf.js +81 -0
  58. package/dist/{chunk-gyhxdxb4.js → chunk-prg6489q.js} +1 -1
  59. package/dist/{chunk-pwrscdkf.js → chunk-pxdgy0vr.js} +1 -1
  60. package/dist/{chunk-frhhpxxy.js → chunk-qhzm2qw9.js} +2 -2
  61. package/dist/{chunk-8f2zh5h6.js → chunk-qmxtys9q.js} +2 -2
  62. package/dist/chunk-r0cfe5c1.js +294 -0
  63. package/dist/chunk-rtjytfhh.js +1 -0
  64. package/dist/chunk-s7ttf0pm.js +2 -0
  65. package/dist/{chunk-k38fjqj7.js → chunk-t01t72t2.js} +2 -2
  66. package/dist/{chunk-fw3nrwpf.js → chunk-t0f66x64.js} +1 -1
  67. package/dist/chunk-tn356gwf.js +93 -0
  68. package/dist/chunk-vd8kwzra.js +41 -0
  69. package/dist/chunk-vhn13anh.js +233 -0
  70. package/dist/chunk-vnewbtjy.js +1 -0
  71. package/dist/{chunk-hfegb4pr.js → chunk-wbm7rn9w.js} +2 -2
  72. package/dist/chunk-wd3gkd45.js +3 -0
  73. package/dist/chunk-whdf0vbb.js +1 -0
  74. package/dist/{chunk-r019959h.js → chunk-ws232ksq.js} +2 -2
  75. package/dist/{chunk-rt5mpgbg.js → chunk-yerf10k7.js} +2 -2
  76. package/dist/{chunk-pndhbee8.js → chunk-yzv3n8mw.js} +2 -2
  77. package/dist/chunk-z3e4c424.js +2 -0
  78. package/dist/{chunk-jb4yt88g.js → chunk-znw7fpep.js} +2 -2
  79. package/dist/chunk-zq2g4rfd.js +1 -0
  80. package/dist/cli.js +1 -1
  81. package/dist/nonInteractive.js +314 -4
  82. package/dist/zen-keyboard.js +1 -1
  83. package/package.json +37 -37
  84. package/dist/chunk-0sxrk9sx.js +0 -1
  85. package/dist/chunk-178yjjsx.js +0 -1
  86. package/dist/chunk-1p9xzvpt.js +0 -3
  87. package/dist/chunk-2eh0sv3s.js +0 -2
  88. package/dist/chunk-43xrz4wp.js +0 -2
  89. package/dist/chunk-48ce2wt0.js +0 -1
  90. package/dist/chunk-578m1dhj.js +0 -2
  91. package/dist/chunk-5dsevrtz.js +0 -91
  92. package/dist/chunk-66890qd3.js +0 -2
  93. package/dist/chunk-738m8242.js +0 -53
  94. package/dist/chunk-8ty2zfve.js +0 -3
  95. package/dist/chunk-9b7nj74j.js +0 -1
  96. package/dist/chunk-9x562s6p.js +0 -1
  97. package/dist/chunk-a90fm6gz.js +0 -278
  98. package/dist/chunk-ac5t2ywn.js +0 -100
  99. package/dist/chunk-ad2hbq42.js +0 -1
  100. package/dist/chunk-afhxxkmv.js +0 -16
  101. package/dist/chunk-b4vvgbav.js +0 -1
  102. package/dist/chunk-b9pcntkv.js +0 -253
  103. package/dist/chunk-c7y5efa0.js +0 -1
  104. package/dist/chunk-cbjnwrt7.js +0 -2
  105. package/dist/chunk-dcs1r9as.js +0 -2
  106. package/dist/chunk-dcwnpdtk.js +0 -9
  107. package/dist/chunk-e3tyc24s.js +0 -310
  108. package/dist/chunk-e8hp8d68.js +0 -81
  109. package/dist/chunk-h1enhch1.js +0 -2
  110. package/dist/chunk-hcnx1j2z.js +0 -1
  111. package/dist/chunk-hra0748z.js +0 -2
  112. package/dist/chunk-hyf24r36.js +0 -2
  113. package/dist/chunk-jjcmm167.js +0 -1
  114. package/dist/chunk-jrepjpft.js +0 -2
  115. package/dist/chunk-kym9tb01.js +0 -1
  116. package/dist/chunk-mt1g6g89.js +0 -1
  117. package/dist/chunk-p0vzbr7s.js +0 -585
  118. package/dist/chunk-r10bn684.js +0 -1
  119. package/dist/chunk-r3pe49q4.js +0 -8
  120. package/dist/chunk-r4tq44hr.js +0 -1
  121. package/dist/chunk-rjrnaka2.js +0 -1
  122. package/dist/chunk-s77qbhtz.js +0 -3
  123. package/dist/chunk-t7rwtc17.js +0 -1
  124. package/dist/chunk-v8g52kan.js +0 -1
  125. package/dist/chunk-vd6c87cm.js +0 -2
  126. package/dist/chunk-vh9zd1v3.js +0 -5
  127. package/dist/chunk-w2hbsa9j.js +0 -86
  128. package/dist/chunk-wabmqprd.js +0 -184
  129. package/dist/chunk-wpy5r9ma.js +0 -40
  130. package/dist/chunk-yqwxbcc7.js +0 -31
  131. package/dist/chunk-z8n7y37k.js +0 -1
  132. package/dist/chunk-zr7sx9hd.js +0 -1
  133. package/dist/chunk-zxqmghzf.js +0 -1
@@ -1,4 +1,314 @@
1
- import"./chunk-hfypkhky.js";import"./chunk-66890qd3.js";import"./chunk-yqwxbcc7.js";import"./chunk-jrepjpft.js";import{Ve as E}from"./chunk-b9pcntkv.js";import"./chunk-62zh99t6.js";import"./chunk-wabmqprd.js";import"./chunk-738m8242.js";import"./chunk-e3tyc24s.js";import"./chunk-ad2hbq42.js";import"./chunk-pwrscdkf.js";import{Pf as y}from"./chunk-fkrydbn4.js";import"./chunk-p0vzbr7s.js";import"./chunk-x552nspp.js";import"./chunk-48vkm1yn.js";import"./chunk-afhxxkmv.js";import"./chunk-43xrz4wp.js";import"./chunk-ac5t2ywn.js";import"./chunk-dcwnpdtk.js";import"./chunk-cbjnwrt7.js";import"./chunk-vh9zd1v3.js";import{xj as q}from"./chunk-w2hbsa9j.js";import"./chunk-rztre6k0.js";import"./chunk-wpy5r9ma.js";import"./chunk-frhhpxxy.js";import"./chunk-h1enhch1.js";import"./chunk-hyf24r36.js";import"./chunk-578m1dhj.js";import"./chunk-1p9xzvpt.js";import"./chunk-hra0748z.js";import"./chunk-jb4yt88g.js";import"./chunk-k38fjqj7.js";import"./chunk-dcs1r9as.js";async function z(){return new Promise((b,x)=>{let T="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(d)=>{T+=d}),process.stdin.on("end",()=>{b(T)}),process.stdin.on("error",(d)=>{x(d)})})}async function h(b,x=!1){let T=await y();await T.initialize();let d=await T.getConfig(),A=b||"";if(x)try{A=(await z()).trim()}catch(w){throw console.error("❌ 读取 stdin 失败:",w),w}if(!A)console.error("❌ 错误: 未提供输入内容"),console.error(`
2
- 用法:`),console.error(' zen-code -p "你的任务描述"'),console.error(' echo "内容" | zen-code'),process.exit(1);try{let w={messages:[new q(A)],provider_id:d.provider_id,provider_type:d.provider_type||d.provider_id,model_id:d.model_id,enable_thinking:d.enable_thinking,cwd:process.cwd()},F=await E.invoke(w,{recursionLimit:500}),M=F.messages||[],N=M[M.length-1];if(N)console.log(N.text);return F}catch(w){throw console.error(`
3
- 执行失败: ${w instanceof Error?w.message:String(w)}
4
- `),w}}export{h as runNonInteractive};
1
+ import"./chunk-1w19w1bm.js";import"./chunk-r0cfe5c1.js";import{Ue as s3}from"./chunk-9czhw5k6.js";import"./chunk-vhn13anh.js";import"./chunk-mcb8rewr.js";import"./chunk-d2770b2z.js";import"./chunk-mv0xzmq8.js";import"./chunk-znw7fpep.js";import"./chunk-pxdgy0vr.js";import{kf as tK}from"./chunk-k6fxqssr.js";import"./chunk-s7ttf0pm.js";import"./chunk-0fj768k4.js";import"./chunk-1mq2jmfy.js";import"./chunk-3dnayvgx.js";import"./chunk-8waww0j9.js";import"./chunk-h0q3dvnv.js";import"./chunk-hrcxdj3c.js";import"./chunk-9tgp14v7.js";import{Eg as BJ}from"./chunk-hz9yw7cs.js";import{fh as ZU,gh as $U,hh as hY,ih as cH,jh as N9,kh as Hq,lh as CG,mh as xZ,nh as Q2,oh as Z2}from"./chunk-tn356gwf.js";import{Ik as r,Jk as O}from"./chunk-n849zsd3.js";import"./chunk-t01t72t2.js";import"./chunk-b2551zfb.js";import{Nk as M8,Ok as $4,Pk as H9,Qk as J4,Sk as Zq,Tk as $q,Uk as Y4,Vk as TK,Wk as SQ,Xk as Jq,Yk as Yq,Zk as p4,vl as p0}from"./chunk-vd8kwzra.js";import"./chunk-qhzm2qw9.js";import{Al as $1,Bl as f2,Cl as mQ,El as $8,xl as PH,yl as x6,zl as Y8}from"./chunk-arv4h3h1.js";import{Fl as i6}from"./chunk-z3e4c424.js";var $X=Object.defineProperty,_=(Q,Z)=>{let $={};for(var J in Q)$X($,J,{get:Q[J],enumerable:!0});if(!Z)$X($,Symbol.toStringTag,{value:"Module"});return $};function JX(Q){let Z=Symbol.for(Q);return{brand($,J){let Y=J?Symbol.for(`${Q}.${J}`):Z;class W extends ${[Y]=!0;constructor(...X){super(...X)}static isInstance(X){return typeof X==="object"&&X!==null&&Y in X&&X[Y]===!0}}return Object.defineProperty(W,"name",{value:$.name}),W},sub($){return JX(`${Q}.${$}`)},isInstance($){return typeof $==="object"&&$!==null&&Z in $&&$[Z]===!0}}}var YX=JX("langchain");var WX=_({ContextOverflowError:()=>QU,LangChainError:()=>XY,ModelAbortError:()=>j$,addLangChainErrorFields:()=>n8,ns:()=>E$});function n8(Q,Z){return Q.lc_error_code=Z,Q.message=`${Q.message}
2
+
3
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${Z}/
4
+ `,Q}var E$=YX.sub("error"),XY=class extends E$.brand(Error){name="LangChainError";constructor(Q){super(Q);if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}},j$=class extends E$.brand(XY,"model-abort"){name="ModelAbortError";partialOutput;constructor(Q,Z){super(Q);this.partialOutput=Z}},QU=class Q extends E$.brand(XY,"context-overflow"){name="ContextOverflowError";cause;constructor(Z){super(Z??"Input exceeded the model's context window.")}static fromError(Z){let $=new Q(Z.message);return $.cause=Z,$}};function E8(Q){return typeof Q==="object"&&Q!==null&&"type"in Q&&typeof Q.type==="string"&&"source_type"in Q&&(Q.source_type==="url"||Q.source_type==="base64"||Q.source_type==="text"||Q.source_type==="id")}function E1(Q){return E8(Q)&&Q.source_type==="url"&&"url"in Q&&typeof Q.url==="string"}function j1(Q){return E8(Q)&&Q.source_type==="base64"&&"data"in Q&&typeof Q.data==="string"}function XX(Q){return E8(Q)&&Q.source_type==="text"&&"text"in Q&&typeof Q.text==="string"}function R$(Q){return E8(Q)&&Q.source_type==="id"&&"id"in Q&&typeof Q.id==="string"}function _$(Q){if(E8(Q)){if(Q.source_type==="url")return{type:"image_url",image_url:{url:Q.url}};if(Q.source_type==="base64"){if(!Q.mime_type)throw Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${Q.mime_type};base64,${Q.data}`}}}}throw Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function qX(Q){let Z=Q.split(";")[0].split("/");if(Z.length!==2)throw Error(`Invalid mime type: "${Q}" - does not match type/subtype format.`);let $=Z[0].trim(),J=Z[1].trim();if($===""||J==="")throw Error(`Invalid mime type: "${Q}" - type or subtype is empty.`);let Y={};for(let W of Q.split(";").slice(1)){let X=W.split("=");if(X.length!==2)throw Error(`Invalid parameter syntax in mime type: "${Q}".`);let q=X[0].trim(),G=X[1].trim();if(q==="")throw Error(`Invalid parameter syntax in mime type: "${Q}".`);Y[q]=G}return{type:$,subtype:J,parameters:Y}}function DZ({dataUrl:Q,asTypedArray:Z=!1}){let $=Q.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),J;if($){J=$[1].toLowerCase();let Y=Z?Uint8Array.from(atob($[2]),(W)=>W.charCodeAt(0)):$[2];return{mime_type:J,data:Y}}}function GX(Q,Z){if(Q.type==="text"){if(!Z.fromStandardTextBlock)throw Error(`Converter for ${Z.providerName} does not implement \`fromStandardTextBlock\` method.`);return Z.fromStandardTextBlock(Q)}if(Q.type==="image"){if(!Z.fromStandardImageBlock)throw Error(`Converter for ${Z.providerName} does not implement \`fromStandardImageBlock\` method.`);return Z.fromStandardImageBlock(Q)}if(Q.type==="audio"){if(!Z.fromStandardAudioBlock)throw Error(`Converter for ${Z.providerName} does not implement \`fromStandardAudioBlock\` method.`);return Z.fromStandardAudioBlock(Q)}if(Q.type==="file"){if(!Z.fromStandardFileBlock)throw Error(`Converter for ${Z.providerName} does not implement \`fromStandardFileBlock\` method.`);return Z.fromStandardFileBlock(Q)}throw Error(`Unable to convert content block type '${Q.type}' to provider-specific format: not recognized.`)}var zX=i6(ZU(),1),KX=i6($U(),1);function UX(Q,Z){return Z?.[Q]||zX.default(Q)}function HX(Q,Z){return Z?.[Q]||KX.default(Q)}function I$(Q,Z,$){let J={};for(let Y in Q)if(Object.hasOwn(Q,Y))J[Z(Y,$)]=Q[Y];return J}function JU(Q){return"lc"in Q||Object.keys(Q).length===1&&"__lc_escaped__"in Q}function YU(Q){return{["__lc_escaped__"]:Q}}function qY(Q){return Object.keys(Q).length===1&&"__lc_escaped__"in Q}function WU(Q){return Q!==null&&typeof Q==="object"&&"lc_serializable"in Q&&typeof Q.toJSON==="function"}function XU(Q){let Z;if(Q!==null&&typeof Q==="object")if("lc_id"in Q&&Array.isArray(Q.lc_id))Z=Q.lc_id;else Z=[Q.constructor?.name??"Object"];else Z=[typeof Q];return{lc:1,type:"not_implemented",id:Z}}function T$(Q,Z=new WeakSet){if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q)){if(Z.has(Q))return XU(Q);if(WU(Q))return Q;Z.add(Q);let $=Q;if(JU($))return Z.delete(Q),YU($);let J={};for(let[Y,W]of Object.entries($))J[Y]=T$(W,Z);return Z.delete(Q),J}if(Array.isArray(Q))return Q.map(($)=>T$($,Z));return Q}function S$(Q){if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q)){let Z=Q;if(qY(Z))return Z.__lc_escaped__;let $={};for(let[J,Y]of Object.entries(Z))$[J]=S$(Y);return $}if(Array.isArray(Q))return Q.map((Z)=>S$(Z));return Q}var DX=_({Serializable:()=>g0,get_lc_unique_name:()=>R1});function BX(Q){return Array.isArray(Q)?[...Q]:{...Q}}function qU(Q,Z){let $=BX(Q);for(let[J,Y]of Object.entries(Z)){let[W,...X]=J.split(".").reverse(),q=$;for(let G of X.reverse()){if(q[G]===void 0)break;q[G]=BX(q[G]),q=q[G]}if(q[W]!==void 0)q[W]={lc:1,type:"secret",id:[Y]}}return $}function R1(Q){let Z=Object.getPrototypeOf(Q);if(typeof Q.lc_name==="function"&&(typeof Z.lc_name!=="function"||Q.lc_name()!==Z.lc_name()))return Q.lc_name();else return Q.name}var g0=class Q{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,R1(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(Z,...$){if(this.lc_serializable_keys!==void 0)this.lc_kwargs=Object.fromEntries(Object.entries(Z||{}).filter(([J])=>this.lc_serializable_keys?.includes(J)));else this.lc_kwargs=Z??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Q||typeof this.lc_kwargs!=="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let Z={},$={},J=Object.keys(this.lc_kwargs).reduce((q,G)=>{return q[G]=G in this?this[G]:this.lc_kwargs[G],q},{});for(let q=Object.getPrototypeOf(this);q;q=Object.getPrototypeOf(q))Object.assign(Z,Reflect.get(q,"lc_aliases",this)),Object.assign($,Reflect.get(q,"lc_secrets",this)),Object.assign(J,Reflect.get(q,"lc_attributes",this));Object.keys($).forEach((q)=>{let G=this,z=J,[K,...U]=q.split(".").reverse();for(let H of U.reverse()){if(!(H in G)||G[H]===void 0)return;if(!(H in z)||z[H]===void 0){if(typeof G[H]==="object"&&G[H]!=null)z[H]={};else if(Array.isArray(G[H]))z[H]=[]}G=G[H],z=z[H]}if(K in G&&G[K]!==void 0)z[K]=z[K]||G[K]});let Y={},W=new WeakSet;W.add(this);for(let[q,G]of Object.entries(J))Y[q]=T$(G,W);let X=I$(Object.keys($).length?qU(Y,$):Y,UX,Z);return{lc:1,type:"constructor",id:this.lc_id,kwargs:X}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function f(Q,Z){return p(Q)&&Q.type===Z}function p(Q){return typeof Q==="object"&&Q!==null}function e0(Q){return Array.isArray(Q)}function M(Q){return typeof Q==="string"}function fQ(Q){return typeof Q==="number"}function x$(Q){return Q instanceof Uint8Array}function GY(Q){try{return JSON.parse(Q)}catch{return}}var hQ=(Q)=>Q();function GU(Q){if(Q.type==="char_location"&&M(Q.document_title)&&fQ(Q.start_char_index)&&fQ(Q.end_char_index)&&M(Q.cited_text)){let{document_title:Z,start_char_index:$,end_char_index:J,cited_text:Y,...W}=Q;return{...W,type:"citation",source:"char",title:Z??void 0,startIndex:$,endIndex:J,citedText:Y}}if(Q.type==="page_location"&&M(Q.document_title)&&fQ(Q.start_page_number)&&fQ(Q.end_page_number)&&M(Q.cited_text)){let{document_title:Z,start_page_number:$,end_page_number:J,cited_text:Y,...W}=Q;return{...W,type:"citation",source:"page",title:Z??void 0,startIndex:$,endIndex:J,citedText:Y}}if(Q.type==="content_block_location"&&M(Q.document_title)&&fQ(Q.start_block_index)&&fQ(Q.end_block_index)&&M(Q.cited_text)){let{document_title:Z,start_block_index:$,end_block_index:J,cited_text:Y,...W}=Q;return{...W,type:"citation",source:"block",title:Z??void 0,startIndex:$,endIndex:J,citedText:Y}}if(Q.type==="web_search_result_location"&&M(Q.url)&&M(Q.title)&&M(Q.encrypted_index)&&M(Q.cited_text)){let{url:Z,title:$,encrypted_index:J,cited_text:Y,...W}=Q;return{...W,type:"citation",source:"url",url:Z,title:$,startIndex:Number(J),endIndex:Number(J),citedText:Y}}if(Q.type==="search_result_location"&&M(Q.source)&&M(Q.title)&&fQ(Q.start_block_index)&&fQ(Q.end_block_index)&&M(Q.cited_text)){let{source:Z,title:$,start_block_index:J,end_block_index:Y,cited_text:W,...X}=Q;return{...X,type:"citation",source:"search",url:Z,title:$??void 0,startIndex:J,endIndex:Y,citedText:W}}}function FX(Q){if(f(Q,"document")&&p(Q.source)&&"type"in Q.source){if(Q.source.type==="base64"&&M(Q.source.media_type)&&M(Q.source.data))return{type:"file",mimeType:Q.source.media_type,data:Q.source.data};else if(Q.source.type==="url"&&M(Q.source.url))return{type:"file",url:Q.source.url};else if(Q.source.type==="file"&&M(Q.source.file_id))return{type:"file",fileId:Q.source.file_id};else if(Q.source.type==="text"&&M(Q.source.data))return{type:"file",mimeType:String(Q.source.media_type??"text/plain"),data:Q.source.data}}else if(f(Q,"image")&&p(Q.source)&&"type"in Q.source){if(Q.source.type==="base64"&&M(Q.source.media_type)&&M(Q.source.data))return{type:"image",mimeType:Q.source.media_type,data:Q.source.data};else if(Q.source.type==="url"&&M(Q.source.url))return{type:"image",url:Q.source.url};else if(Q.source.type==="file"&&M(Q.source.file_id))return{type:"image",fileId:Q.source.file_id}}}function LX(Q){function*Z(){for(let $ of Q){let J=FX($);if(J)yield J;else yield $}}return Array.from(Z())}function VX(Q){function*Z(){let $=typeof Q.content==="string"?[{type:"text",text:Q.content}]:Q.content;for(let J of $){if(f(J,"text")&&M(J.text)){let{text:Y,citations:W,...X}=J;if(e0(W)&&W.length){let q=W.reduce((G,z)=>{let K=GU(z);if(K)return[...G,K];return G},[]);yield{...X,type:"text",text:Y,annotations:q};continue}else{yield{...X,type:"text",text:Y};continue}}else if(f(J,"thinking")&&M(J.thinking)){let{thinking:Y,signature:W,...X}=J;yield{...X,type:"reasoning",reasoning:Y,signature:W};continue}else if(f(J,"redacted_thinking")){yield{type:"non_standard",value:J};continue}else if(f(J,"tool_use")&&M(J.name)&&M(J.id)){yield{type:"tool_call",id:J.id,name:J.name,args:J.input};continue}else if(f(J,"input_json_delta")){if(zU(Q)&&Q.tool_call_chunks?.length){let Y=Q.tool_call_chunks[0];yield{type:"tool_call_chunk",id:Y.id,name:Y.name,args:Y.args,index:Y.index};continue}}else if(f(J,"server_tool_use")&&M(J.name)&&M(J.id)){let{name:Y,id:W}=J;if(Y==="web_search"){yield{id:W,type:"server_tool_call",name:"web_search",args:{query:hQ(()=>{if(typeof J.input==="string")return J.input;else if(p(J.input)&&M(J.input.query))return J.input.query;else if(M(J.partial_json)){let X=GY(J.partial_json);if(X?.query)return X.query}return""})}};continue}else if(J.name==="code_execution"){yield{id:W,type:"server_tool_call",name:"code_execution",args:{code:hQ(()=>{if(typeof J.input==="string")return J.input;else if(p(J.input)&&M(J.input.code))return J.input.code;else if(M(J.partial_json)){let X=GY(J.partial_json);if(X?.code)return X.code}return""})}};continue}}else if(f(J,"web_search_tool_result")&&M(J.tool_use_id)&&e0(J.content)){let{content:Y,tool_use_id:W}=J;yield{type:"server_tool_call_result",name:"web_search",toolCallId:W,status:"success",output:{urls:Y.reduce((X,q)=>{if(f(q,"web_search_result"))return[...X,q.url];return X},[])}};continue}else if(f(J,"code_execution_tool_result")&&M(J.tool_use_id)&&p(J.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:J.tool_use_id,status:"success",output:J.content};continue}else if(f(J,"mcp_tool_use")){yield{id:J.id,type:"server_tool_call",name:"mcp_tool_use",args:J.input};continue}else if(f(J,"mcp_tool_result")&&M(J.tool_use_id)&&p(J.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:J.tool_use_id,status:"success",output:J.content};continue}else if(f(J,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:J.input};continue}else if(f(J,"search_result")){yield{id:J.id,type:"non_standard",value:J};continue}else if(f(J,"tool_result")){yield{id:J.id,type:"non_standard",value:J};continue}else{let Y=FX(J);if(Y){yield Y;continue}}yield{type:"non_standard",value:J}}}return Array.from(Z())}var wX={translateContent:VX,translateContentChunk:VX};function zU(Q){return typeof Q?._getType==="function"&&typeof Q.concat==="function"&&Q._getType()==="ai"}function KU(Q){if(E1(Q))return{type:Q.type,mimeType:Q.mime_type,url:Q.url,metadata:Q.metadata};if(j1(Q))return{type:Q.type,mimeType:Q.mime_type??"application/octet-stream",data:Q.data,metadata:Q.metadata};if(R$(Q))return{type:Q.type,mimeType:Q.mime_type,fileId:Q.id,metadata:Q.metadata};return Q}function AX(Q){return Q.map(KU)}function PX(Q){if(f(Q,"image_url")&&p(Q.image_url))return!0;if(f(Q,"input_audio")&&p(Q.input_audio))return!0;if(f(Q,"file")&&p(Q.file))return!0;return!1}function NX(Q){if(f(Q,"image_url")&&p(Q.image_url)&&M(Q.image_url.url)){let Z=DZ({dataUrl:Q.image_url.url});if(Z)return{type:"image",mimeType:Z.mime_type,data:Z.data};else return{type:"image",url:Q.image_url.url}}else if(f(Q,"input_audio")&&p(Q.input_audio)&&M(Q.input_audio.data)&&M(Q.input_audio.format))return{type:"audio",data:Q.input_audio.data,mimeType:`audio/${Q.input_audio.format}`};else if(f(Q,"file")&&p(Q.file)&&M(Q.file.data)){let Z=DZ({dataUrl:Q.file.data});if(Z)return{type:"file",data:Z.data,mimeType:Z.mime_type};else if(M(Q.file.file_id))return{type:"file",fileId:Q.file.file_id}}return Q}function UU(Q){let Z=[];if(typeof Q.content==="string"){if(Q.content.length>0)Z.push({type:"text",text:Q.content})}else Z.push(...M$(Q.content));for(let $ of Q.tool_calls??[])Z.push({type:"tool_call",id:$.id,name:$.name,args:$.args});return Z}function HU(Q){let Z=[];if(typeof Q.content==="string"){if(Q.content.length>0)Z.push({type:"text",text:Q.content})}else Z.push(...M$(Q.content));for(let $ of Q.tool_calls??[])Z.push({type:"tool_call",id:$.id,name:$.name,args:$.args});return Z}function M$(Q){let Z=[];for(let $ of Q)if(PX($))Z.push(NX($));else Z.push($);return Z}function BU(Q){if(Q.type==="url_citation"){let{url:Z,title:$,start_index:J,end_index:Y}=Q;return{type:"citation",url:Z,title:$,startIndex:J,endIndex:Y}}if(Q.type==="file_citation"){let{file_id:Z,filename:$,index:J}=Q;return{type:"citation",title:$,startIndex:J,endIndex:J,fileId:Z}}return Q}function OX(Q){function*Z(){if(p(Q.additional_kwargs?.reasoning)&&e0(Q.additional_kwargs.reasoning.summary))yield{type:"reasoning",reasoning:Q.additional_kwargs.reasoning.summary.reduce((J,Y)=>{if(p(Y)&&M(Y.text))return`${J}${Y.text}`;return J},"")};let $=typeof Q.content==="string"?[{type:"text",text:Q.content}]:Q.content;for(let J of $)if(f(J,"text")){let{text:Y,annotations:W,...X}=J;if(Array.isArray(W))yield{...X,type:"text",text:String(Y),annotations:W.map(BU)};else yield{...X,type:"text",text:String(Y)}}for(let J of Q.tool_calls??[])yield{type:"tool_call",id:J.id,name:J.name,args:J.args};if(p(Q.additional_kwargs)&&e0(Q.additional_kwargs.tool_outputs))for(let J of Q.additional_kwargs.tool_outputs){if(f(J,"web_search_call")){let Y={};if(p(J.action)&&M(J.action.query))Y.query=J.action.query;if(yield{id:J.id,type:"server_tool_call",name:"web_search",args:Y},J.status==="completed"||J.status==="failed"){let W={};if(p(J.action))W.action=J.action;yield{type:"server_tool_call_result",toolCallId:M(J.id)?J.id:"",status:J.status==="completed"?"success":"error",output:W}}continue}else if(f(J,"file_search_call")){if(yield{id:J.id,type:"server_tool_call",name:"file_search",args:{queries:e0(J.queries)?J.queries:[]}},J.status==="completed"||J.status==="failed")yield{type:"server_tool_call_result",toolCallId:M(J.id)?J.id:"",status:J.status==="completed"?"success":"error",output:e0(J.results)?{results:J.results}:{}};continue}else if(f(J,"computer_call")){yield{type:"non_standard",value:J};continue}else if(f(J,"code_interpreter_call")){if(M(J.code))yield{id:J.id,type:"server_tool_call",name:"code_interpreter",args:{code:J.code}};if(e0(J.outputs)){let Y=hQ(()=>{if(J.status==="in_progress")return;if(J.status==="completed")return 0;if(J.status==="incomplete")return 127;if(J.status==="interpreting")return;if(J.status==="failed")return 1});for(let W of J.outputs)if(f(W,"logs")){yield{type:"server_tool_call_result",toolCallId:J.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:Y??0,stderr:[0,void 0].includes(Y)?void 0:String(W.logs),stdout:[0,void 0].includes(Y)?String(W.logs):void 0}};continue}}continue}else if(f(J,"mcp_call")){yield{id:J.id,type:"server_tool_call",name:"mcp_call",args:J.input};continue}else if(f(J,"mcp_list_tools")){yield{id:J.id,type:"server_tool_call",name:"mcp_list_tools",args:J.input};continue}else if(f(J,"mcp_approval_request")){yield{type:"non_standard",value:J};continue}else if(f(J,"image_generation_call")){if(M(J.result))yield{type:"image",mimeType:"image/png",data:J.result,id:M(J.id)?J.id:void 0,metadata:{status:M(J.status)?J.status:void 0}};yield{type:"non_standard",value:J};continue}if(p(J))yield{type:"non_standard",value:J}}}return Array.from(Z())}function DU(Q){function*Z(){yield*OX(Q);for(let $ of Q.tool_call_chunks??[])yield{type:"tool_call_chunk",id:$.id,name:$.name,args:$.args}}return Array.from(Z())}var EX={translateContent:(Q)=>{if(typeof Q.content==="string")return UU(Q);return OX(Q)},translateContentChunk:(Q)=>{if(typeof Q.content==="string")return HU(Q);return DU(Q)}};function v$(Q){return typeof Q==="object"&&Q!==null&&"type"in Q&&"content"in Q&&(typeof Q.content==="string"||Array.isArray(Q.content))}function jX(Q,Z="pretty"){if(Z==="pretty")return VU(Q);return JSON.stringify(Q)}function VU(Q){let Z=[],$=` ${Q.type.charAt(0).toUpperCase()+Q.type.slice(1)} Message `,J=Math.floor((80-$.length)/2),Y="=".repeat(J),W=$.length%2===0?Y:`${Y}=`;if(Z.push(`${Y}${$}${W}`),Q.type==="ai"){let X=Q;if(X.tool_calls&&X.tool_calls.length>0){Z.push("Tool Calls:");for(let q of X.tool_calls){Z.push(` ${q.name} (${q.id})`),Z.push(` Call ID: ${q.id}`),Z.push(" Args:");for(let[G,z]of Object.entries(q.args))Z.push(` ${G}: ${typeof z==="object"?JSON.stringify(z):z}`)}}}if(Q.type==="tool"){let X=Q;if(X.name)Z.push(`Name: ${X.name}`)}if(typeof Q.content==="string"&&Q.content.trim()){if(Z.length>1)Z.push("");Z.push(Q.content)}return Z.join(`
5
+ `)}var zY=Symbol.for("langchain.message");function GQ(Q,Z){if(typeof Q==="string"){if(Q==="")return Z;if(typeof Z==="string")return Q+Z;else if(Array.isArray(Z)&&Z.length===0)return Q;else if(Array.isArray(Z)&&Z.some(($)=>E8($)))return[{type:"text",source_type:"text",text:Q},...Z];else return[{type:"text",text:Q},...Z]}else if(Array.isArray(Z))return F6(Q,Z)??[...Q,...Z];else if(Z==="")return Q;else if(Array.isArray(Q)&&Q.some(($)=>E8($)))return[...Q,{type:"file",source_type:"text",text:Z}];else return[...Q,{type:"text",text:Z}]}function y$(Q,Z){if(Q==="error"||Z==="error")return"error";return"success"}function FU(Q,Z){function $(J,Y){if(typeof J!=="object"||J===null||J===void 0)return J;if(Y>=Z){if(Array.isArray(J))return"[Array]";return"[Object]"}if(Array.isArray(J))return J.map((X)=>$(X,Y+1));let W={};for(let X of Object.keys(J))W[X]=$(J[X],Y+1);return W}return JSON.stringify($(Q,0),null,2)}var V0=class extends g0{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[zY]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(Q){let Z=typeof Q==="string"||Array.isArray(Q)?{content:Q}:Q;if(!Z.additional_kwargs)Z.additional_kwargs={};if(!Z.response_metadata)Z.response_metadata={};super(Z);if(this.name=Z.name,Z.content===void 0&&Z.contentBlocks!==void 0)this.content=Z.contentBlocks,this.response_metadata={output_version:"v1",...Z.response_metadata};else if(Z.content!==void 0)this.content=Z.content??[],this.response_metadata=Z.response_metadata;else this.content=[],this.response_metadata=Z.response_metadata;this.additional_kwargs=Z.additional_kwargs,this.id=Z.id}get text(){if(typeof this.content==="string")return this.content;if(!Array.isArray(this.content))return"";return this.content.map((Q)=>{if(typeof Q==="string")return Q;if(Q.type==="text")return Q.text;return""}).join("")}get contentBlocks(){let Q=typeof this.content==="string"?[{type:"text",text:this.content}]:this.content;return[AX,M$,LX].reduce((Z,$)=>$(Z),Q)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(Q){return typeof Q==="object"&&Q!==null&&zY in Q&&Q[zY]===!0&&v$(Q)}_updateId(Q){this.id=Q,this.lc_kwargs.id=Q}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](Q){if(Q===null)return this;let Z=FU(this._printableFields,Math.max(4,Q));return`${this.constructor.lc_name()} ${Z}`}toFormattedString(Q="pretty"){return jX(this,Q)}};function _X(Q){return Array.isArray(Q)&&Q.every((Z)=>typeof Z.index==="number")}var KY=["index","created","timestamp"];function j0(Q,Z,$){let J=$?.ignoreKeys??KY;if(Q==null&&Z==null)return;if(Q==null||Z==null)return Q??Z;let Y={...Q};for(let[W,X]of Object.entries(Z))if(Y[W]==null)Y[W]=X;else if(X==null)continue;else if(typeof Y[W]!==typeof X||Array.isArray(Y[W])!==Array.isArray(X))throw Error(`field[${W}] already exists in the message chunk, but with a different type.`);else if(typeof Y[W]==="string")if(W==="type")continue;else if(["id","name","output_version","model_provider"].includes(W)){if(X)Y[W]=X}else if(J.includes(W))continue;else Y[W]+=X;else if(typeof Y[W]==="number"){if(J.includes(W))continue;Y[W]=Y[W]+X}else if(typeof Y[W]==="object"&&!Array.isArray(Y[W]))Y[W]=j0(Y[W],X,$);else if(Array.isArray(Y[W]))Y[W]=F6(Y[W],X,$);else if(Y[W]===X)continue;else console.warn(`field[${W}] already exists in this message chunk and value has unsupported type.`);return Y}function LU(Q){return typeof Q==="number"||typeof Q==="string"}function RX(Q){if(typeof Q!=="object"||Q===null)return!1;if(!("index"in Q))return!1;return LU(Q.index)}function F6(Q,Z,$){if(Q==null&&Z==null)return;else if(Q==null||Z==null)return Q||Z;else{let J=[...Q];for(let Y of Z)if(RX(Y)){let W=J.findIndex((X)=>{if(!RX(X))return!1;let q=X.index===Y.index,G=X.id!=null&&Y.id!=null&&X.id===Y.id,z=X.id==null||Y.id==null;return q&&(G||z)});if(W!==-1&&typeof J[W]==="object"&&J[W]!==null)J[W]=j0(J[W],Y,$);else J.push(Y)}else if(typeof Y==="object"&&Y!==null&&"text"in Y&&Y.text==="")continue;else J.push(Y);return J}}function C$(Q,Z,$){if(Q==null&&Z==null)return;if(Q==null||Z==null)return Q??Z;else if(typeof Q!==typeof Z)throw Error(`Cannot merge objects of different types.
6
+ Left ${typeof Q}
7
+ Right ${typeof Z}`);else if(typeof Q==="string"&&typeof Z==="string")return Q+Z;else if(Array.isArray(Q)&&Array.isArray(Z))return F6(Q,Z,$);else if(typeof Q==="object"&&typeof Z==="object")return j0(Q,Z,$);else if(Q===Z)return Q;else throw Error(`Can not merge objects of different types.
8
+ Left ${Q}
9
+ Right ${Z}`)}var zQ=class Q extends V0{static isInstance(Z){if(!super.isInstance(Z))return!1;let $=Object.getPrototypeOf(Z);while($!==null){if($===Q.prototype)return!0;$=Object.getPrototypeOf($)}return!1}};function b$(Q){return typeof Q.role==="string"}function R0(Q){return typeof Q?._getType==="function"}function r8(Q){return zQ.isInstance(Q)}function UY(Q){switch(Q){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function wU(Q){if(p(Q.document)&&p(Q.document.source)){let Z=UY(p(Q.document)&&M(Q.document.format)?Q.document.format:"");if(p(Q.document.source)){if(p(Q.document.source.s3Location)&&M(Q.document.source.s3Location.uri))return{type:"file",mimeType:Z,fileId:Q.document.source.s3Location.uri};if(x$(Q.document.source.bytes))return{type:"file",mimeType:Z,data:Q.document.source.bytes};if(M(Q.document.source.text))return{type:"file",mimeType:Z,data:Buffer.from(Q.document.source.text).toString("base64")};if(e0(Q.document.source.content))return{type:"file",mimeType:Z,data:Q.document.source.content.reduce(($,J)=>{if(p(J)&&M(J.text))return $+J.text;return $},"")}}}return{type:"non_standard",value:Q}}function AU(Q){if(f(Q,"image")&&p(Q.image)){let Z=UY(p(Q.image)&&M(Q.image.format)?Q.image.format:"");if(p(Q.image.source)){if(p(Q.image.source.s3Location)&&M(Q.image.source.s3Location.uri))return{type:"image",mimeType:Z,fileId:Q.image.source.s3Location.uri};if(x$(Q.image.source.bytes))return{type:"image",mimeType:Z,data:Q.image.source.bytes}}}return{type:"non_standard",value:Q}}function PU(Q){if(f(Q,"video")&&p(Q.video)){let Z=UY(p(Q.video)&&M(Q.video.format)?Q.video.format:"");if(p(Q.video.source)){if(p(Q.video.source.s3Location)&&M(Q.video.source.s3Location.uri))return{type:"video",mimeType:Z,fileId:Q.video.source.s3Location.uri};if(x$(Q.video.source.bytes))return{type:"video",mimeType:Z,data:Q.video.source.bytes}}}return{type:"non_standard",value:Q}}function IX(Q){function*Z(){let $=typeof Q.content==="string"?[{type:"text",text:Q.content}]:Q.content;for(let J of $){if(f(J,"cache_point")){yield{type:"non_standard",value:J};continue}else if(f(J,"citations_content")&&p(J.citationsContent)){yield{type:"text",text:e0(J.citationsContent.content)?J.citationsContent.content.reduce((Y,W)=>{if(p(W)&&M(W.text))return Y+W.text;return Y},""):"",annotations:e0(J.citationsContent.citations)?J.citationsContent.citations.reduce((Y,W)=>{if(p(W)){let X=e0(W.sourceContent)?W.sourceContent.reduce((G,z)=>{if(p(z)&&M(z.text))return G+z.text;return G},""):"",q=hQ(()=>{if(p(W.location)){let G=W.location.documentChar||W.location.documentPage||W.location.documentChunk;if(p(G))return{source:fQ(G.documentIndex)?G.documentIndex.toString():void 0,startIndex:fQ(G.start)?G.start:void 0,endIndex:fQ(G.end)?G.end:void 0}}return{}});Y.push({type:"citation",citedText:X,...q})}return Y},[]):[]};continue}else if(f(J,"document")&&p(J.document)){yield wU(J);continue}else if(f(J,"guard_content")){yield{type:"non_standard",value:J};continue}else if(f(J,"image")&&p(J.image)){yield AU(J);continue}else if(f(J,"reasoning_content")&&M(J.reasoningText)){yield{type:"reasoning",reasoning:J.reasoningText};continue}else if(f(J,"text")&&M(J.text)){yield{type:"text",text:J.text};continue}else if(f(J,"tool_result")){yield{type:"non_standard",value:J};continue}else if(f(J,"tool_call"))continue;else if(f(J,"video")&&p(J.video)){yield PU(J);continue}yield{type:"non_standard",value:J}}}return Array.from(Z())}var TX={translateContent:IX,translateContentChunk:IX};function SX(Q){let Z=[],$=Q.additional_kwargs?.reasoning_content;if(M($)&&$.length>0)Z.push({type:"reasoning",reasoning:$});if(typeof Q.content==="string"){if(Q.content.length>0)Z.push({type:"text",text:Q.content})}else for(let J of Q.content)if(typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&M(J.text))Z.push({type:"text",text:J.text});for(let J of Q.tool_calls??[])Z.push({type:"tool_call",id:J.id,name:J.name,args:J.args});return Z}var xX={translateContent:SX,translateContentChunk:SX};function MX(Q){function*Z(){let $=typeof Q.content==="string"?[{type:"text",text:Q.content}]:Q.content;for(let J of $){if(f(J,"text")&&M(J.text)){yield{type:"text",text:J.text};continue}else if(f(J,"thinking")&&M(J.thinking)){yield{type:"reasoning",reasoning:J.thinking,...J.signature?{signature:J.signature}:{}};continue}else if(f(J,"inlineData")&&p(J.inlineData)&&M(J.inlineData.mimeType)&&M(J.inlineData.data)){yield{type:"file",mimeType:J.inlineData.mimeType,data:J.inlineData.data};continue}else if(f(J,"functionCall")&&p(J.functionCall)&&M(J.functionCall.name)&&p(J.functionCall.args)){yield{type:"tool_call",id:Q.id,name:J.functionCall.name,args:J.functionCall.args};continue}else if(f(J,"functionResponse")){yield{type:"non_standard",value:J};continue}else if(f(J,"fileData")&&p(J.fileData)&&M(J.fileData.mimeType)&&M(J.fileData.fileUri)){yield{type:"file",mimeType:J.fileData.mimeType,fileId:J.fileData.fileUri};continue}else if(f(J,"executableCode")){yield{type:"non_standard",value:J};continue}else if(f(J,"codeExecutionResult")){yield{type:"non_standard",value:J};continue}yield{type:"non_standard",value:J}}}return Array.from(Z())}var vX={translateContent:MX,translateContentChunk:MX};function yX(Q){function*Z(){let $=typeof Q.content==="string"?[{type:"text",text:Q.content}]:Q.content;for(let J of $){if(f(J,"reasoning")&&M(J.reasoning)){let Y=hQ(()=>{let W=$.indexOf(J);if(e0(Q.additional_kwargs?.signatures)&&W>=0)return Q.additional_kwargs.signatures.at(W)});if(M(Y))yield{type:"reasoning",reasoning:J.reasoning,signature:Y};else yield{type:"reasoning",reasoning:J.reasoning};continue}else if(f(J,"thinking")&&M(J.thinking)){yield{type:"reasoning",reasoning:J.thinking,...J.signature?{signature:J.signature}:{}};continue}else if(f(J,"text")&&M(J.text)){yield{type:"text",text:J.text};continue}else if(f(J,"image_url")){if(M(J.image_url))if(J.image_url.startsWith("data:")){let Y=J.image_url.match(/^data:([^;]+);base64,(.+)$/);if(Y)yield{type:"image",data:Y[2],mimeType:Y[1]};else yield{type:"image",url:J.image_url}}else yield{type:"image",url:J.image_url};continue}else if(f(J,"media")&&M(J.mimeType)&&M(J.data)){yield{type:"file",mimeType:J.mimeType,data:J.data};continue}yield{type:"non_standard",value:J}}}return Array.from(Z())}var CX={translateContent:yX,translateContentChunk:yX};function bX(Q){let Z=[],$=Q.additional_kwargs?.reasoning;if(M($)&&$.length>0)Z.push({type:"reasoning",reasoning:$});if(typeof Q.content==="string"){let J=Q.content,Y=J.match(/<think>([\s\S]*?)<\/think>/);if(Y){let W=Y[1].trim();if(W.length>0)Z.push({type:"reasoning",reasoning:W});J=J.replace(/<think>[\s\S]*?<\/think>/,"").trim()}if(J.length>0)Z.push({type:"text",text:J})}else for(let J of Q.content)if(typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&M(J.text)){let Y=J.text,W=Y.match(/<think>([\s\S]*?)<\/think>/);if(W){let X=W[1].trim();if(X.length>0)Z.push({type:"reasoning",reasoning:X});Y=Y.replace(/<think>[\s\S]*?<\/think>/,"").trim()}if(Y.length>0)Z.push({type:"text",text:Y})}for(let J of Q.tool_calls??[])Z.push({type:"tool_call",id:J.id,name:J.name,args:J.args});return Z}var kX={translateContent:bX,translateContentChunk:bX};function fX(Q){let Z=[],$=Q.additional_kwargs?.reasoning_content;if(M($)&&$.length>0)Z.push({type:"reasoning",reasoning:$});if(typeof Q.content==="string"){if(Q.content.length>0)Z.push({type:"text",text:Q.content})}else for(let J of Q.content)if(typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&M(J.text))Z.push({type:"text",text:J.text});for(let J of Q.tool_calls??[])Z.push({type:"tool_call",id:J.id,name:J.name,args:J.args});return Z}var hX={translateContent:fX,translateContentChunk:fX};function gX(Q){let Z=[];if(p(Q.additional_kwargs?.reasoning)){let J=Q.additional_kwargs.reasoning;if(e0(J.summary)){let Y=J.summary.reduce((W,X)=>{if(p(X)&&M(X.text))return`${W}${X.text}`;return W},"");if(Y.length>0)Z.push({type:"reasoning",reasoning:Y})}}let $=Q.additional_kwargs?.reasoning_content;if(M($)&&$.length>0)Z.push({type:"reasoning",reasoning:$});if(typeof Q.content==="string"){if(Q.content.length>0)Z.push({type:"text",text:Q.content})}else for(let J of Q.content)if(typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&M(J.text))Z.push({type:"text",text:J.text});for(let J of Q.tool_calls??[])Z.push({type:"tool_call",id:J.id,name:J.name,args:J.args});return Z}var mX={translateContent:gX,translateContentChunk:gX};function dX(Q){function*Z(){let $=hQ(()=>{if(typeof Q.content==="string")if(Q.additional_kwargs.originalTextContentBlock)return[{...Q.additional_kwargs.originalTextContentBlock,type:"text"}];else return[{type:"text",text:Q.content}];else return Q.content});for(let J of $){let Y=hQ(()=>{if(f(J,"text")&&M(J.text))return{type:"text",text:J.text};else if(f(J,"inlineData")&&p(J.inlineData)&&M(J.inlineData.mimeType)&&M(J.inlineData.data))return{type:"file",mimeType:J.inlineData.mimeType,data:J.inlineData.data};else if(f(J,"functionCall")&&p(J.functionCall)&&M(J.functionCall.name)&&p(J.functionCall.args))return{type:"tool_call",id:Q.id,name:J.functionCall.name,args:J.functionCall.args};else if(f(J,"functionResponse"))return{type:"non_standard",value:J};else if(f(J,"fileData")&&p(J.fileData)&&M(J.fileData.mimeType)&&M(J.fileData.fileUri))return{type:"file",mimeType:J.fileData.mimeType,fileId:J.fileData.fileUri};else if(f(J,"executableCode"))return{type:"non_standard",value:J};else if(f(J,"codeExecutionResult"))return{type:"non_standard",value:J};return{type:"non_standard",value:J}}),W=hQ(()=>{if("thought"in J&&J.thought)return{type:"reasoning",reasoning:Y.type==="text"?Y.text:"",reasoningContentBlock:Y};else return Y}),X={thought:J.thought,thoughtSignature:J.thoughtSignature,partMetadata:J.partMetadata,...W};for(let q in X)if(X[q]===void 0)delete X[q];yield X}}return Array.from(Z())}var uX={translateContent:dX,translateContentChunk:dX};globalThis.lc_block_translators_registry??=new Map([["anthropic",wX],["bedrock-converse",TX],["deepseek",xX],["google",uX],["google-genai",vX],["google-vertexai",CX],["groq",kX],["ollama",hX],["openai",EX],["xai",mX]]);function HY(Q){return globalThis.lc_block_translators_registry.get(Q)}function k$(Q,Z){return j0(Q,Z)??{}}function pX(Q,Z){let $={};if(Q?.audio!==void 0||Z?.audio!==void 0)$.audio=(Q?.audio??0)+(Z?.audio??0);if(Q?.image!==void 0||Z?.image!==void 0)$.image=(Q?.image??0)+(Z?.image??0);if(Q?.video!==void 0||Z?.video!==void 0)$.video=(Q?.video??0)+(Z?.video??0);if(Q?.document!==void 0||Z?.document!==void 0)$.document=(Q?.document??0)+(Z?.document??0);if(Q?.text!==void 0||Z?.text!==void 0)$.text=(Q?.text??0)+(Z?.text??0);return $}function NU(Q,Z){let $={...pX(Q,Z)};if(Q?.cache_read!==void 0||Z?.cache_read!==void 0)$.cache_read=(Q?.cache_read??0)+(Z?.cache_read??0);if(Q?.cache_creation!==void 0||Z?.cache_creation!==void 0)$.cache_creation=(Q?.cache_creation??0)+(Z?.cache_creation??0);return $}function OU(Q,Z){let $={...pX(Q,Z)};if(Q?.reasoning!==void 0||Z?.reasoning!==void 0)$.reasoning=(Q?.reasoning??0)+(Z?.reasoning??0);return $}function _1(Q,Z){return{input_tokens:(Q?.input_tokens??0)+(Z?.input_tokens??0),output_tokens:(Q?.output_tokens??0)+(Z?.output_tokens??0),total_tokens:(Q?.total_tokens??0)+(Z?.total_tokens??0),input_token_details:NU(Q?.input_token_details,Z?.input_token_details),output_token_details:OU(Q?.output_token_details,Z?.output_token_details)}}var cX=_({ToolMessage:()=>i,ToolMessageChunk:()=>o6,defaultToolCallParser:()=>FZ,isDirectToolOutput:()=>VZ,isToolMessage:()=>LZ,isToolMessageChunk:()=>BY});function VZ(Q){return Q!=null&&typeof Q==="object"&&"lc_direct_tool_output"in Q&&Q.lc_direct_tool_output===!0}var i=class extends V0{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(Q,Z,$){let J=typeof Q==="string"||Array.isArray(Q)?{content:Q,name:$,tool_call_id:Z}:Q;super(J);this.tool_call_id=J.tool_call_id,this.artifact=J.artifact,this.status=J.status,this.metadata=J.metadata}static isInstance(Q){return super.isInstance(Q)&&Q.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},o6=class extends zQ{type="tool";tool_call_id;status;artifact;constructor(Q){super(Q);this.tool_call_id=Q.tool_call_id,this.artifact=Q.artifact,this.status=Q.status}static lc_name(){return"ToolMessageChunk"}concat(Q){return new this.constructor({content:GQ(this.content,Q.content),additional_kwargs:j0(this.additional_kwargs,Q.additional_kwargs),response_metadata:j0(this.response_metadata,Q.response_metadata),artifact:C$(this.artifact,Q.artifact),tool_call_id:this.tool_call_id,id:this.id??Q.id,status:y$(this.status,Q.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function FZ(Q){let Z=[],$=[];for(let J of Q)if(!J.function)continue;else{let Y=J.function.name;try{let W=JSON.parse(J.function.arguments);Z.push({name:Y||"",args:W||{},id:J.id})}catch{$.push({name:Y,args:J.function.arguments,id:J.id,error:"Malformed args."})}}return[Z,$]}function LZ(Q){return typeof Q==="object"&&Q!==null&&"getType"in Q&&typeof Q.getType==="function"&&Q.getType()==="tool"}function BY(Q){return Q._getType()==="tool"}function L6(Q){return!!(Q&&typeof Q==="object"&&("type"in Q)&&Q.type==="tool_call")}function lX(Q){return!!(Q&&typeof Q==="object"&&("toolCall"in Q)&&Q.toolCall!=null&&typeof Q.toolCall==="object"&&("id"in Q.toolCall)&&typeof Q.toolCall.id==="string")}var w6=class extends Error{output;constructor(Q,Z){super(Q);this.output=Z}};function n6(Q,Z=Q8){Q=Q.trim();let $=Q.indexOf("```");if($===-1)return Z(Q);let J=Q.substring($+3);if(J.startsWith(`json
10
+ `))J=J.substring(5);else if(J.startsWith("json"))J=J.substring(4);else if(J.startsWith(`
11
+ `))J=J.substring(1);let Y=J.indexOf("```"),W=J;if(Y!==-1)W=J.substring(0,Y);return Z(W.trim())}function EU(Q){try{return JSON.parse(Q)}catch{}let Z=Q.trim();if(Z.length===0)throw Error("Unexpected end of JSON input");let $=0;function J(){while($<Z.length&&/\s/.test(Z[$]))$+=1}function Y(){if(Z[$]!=='"')throw Error(`Expected '"' at position ${$}, got '${Z[$]}'`);$+=1;let K="",U=!1;while($<Z.length){let H=Z[$];if(U){if(H==="n")K+=`
12
+ `;else if(H==="t")K+="\t";else if(H==="r")K+="\r";else if(H==="\\")K+="\\";else if(H==='"')K+='"';else if(H==="b")K+="\b";else if(H==="f")K+="\f";else if(H==="/")K+="/";else if(H==="u"){let B=Z.substring($+1,$+5);if(/^[0-9A-Fa-f]{0,4}$/.test(B)){if(B.length===4)K+=String.fromCharCode(Number.parseInt(B,16));else K+=`u${B}`;$+=B.length}else throw Error(`Invalid unicode escape sequence '\\u${B}' at position ${$}`)}else throw Error(`Invalid escape sequence '\\${H}' at position ${$}`);U=!1}else if(H==="\\")U=!0;else if(H==='"')return $+=1,K;else K+=H;$+=1}if(U)K+="\\";return K}function W(){let K=$,U="";if(Z[$]==="-")U+="-",$+=1;if($<Z.length&&Z[$]==="0"){if(U+="0",$+=1,Z[$]>="0"&&Z[$]<="9")throw Error(`Invalid number at position ${K}`)}if($<Z.length&&Z[$]>="1"&&Z[$]<="9")while($<Z.length&&Z[$]>="0"&&Z[$]<="9")U+=Z[$],$+=1;if($<Z.length&&Z[$]==="."){U+=".",$+=1;while($<Z.length&&Z[$]>="0"&&Z[$]<="9")U+=Z[$],$+=1}if($<Z.length&&(Z[$]==="e"||Z[$]==="E")){if(U+=Z[$],$+=1,$<Z.length&&(Z[$]==="+"||Z[$]==="-"))U+=Z[$],$+=1;while($<Z.length&&Z[$]>="0"&&Z[$]<="9")U+=Z[$],$+=1}if(U==="-")return-0;let H=Number.parseFloat(U);if(Number.isNaN(H))throw $=K,Error(`Invalid number '${U}' at position ${K}`);return H}function X(){if(J(),$>=Z.length)throw Error(`Unexpected end of input at position ${$}`);let K=Z[$];if(K==="{")return G();if(K==="[")return q();if(K==='"')return Y();if("null".startsWith(Z.substring($,$+4)))return $+=Math.min(4,Z.length-$),null;if("true".startsWith(Z.substring($,$+4)))return $+=Math.min(4,Z.length-$),!0;if("false".startsWith(Z.substring($,$+5)))return $+=Math.min(5,Z.length-$),!1;if(K==="-"||K>="0"&&K<="9")return W();throw Error(`Unexpected character '${K}' at position ${$}`)}function q(){if(Z[$]!=="[")throw Error(`Expected '[' at position ${$}, got '${Z[$]}'`);let K=[];if($+=1,J(),$>=Z.length)return K;if(Z[$]==="]")return $+=1,K;while($<Z.length){if(J(),$>=Z.length)return K;if(K.push(X()),J(),$>=Z.length)return K;if(Z[$]==="]")return $+=1,K;else if(Z[$]===","){$+=1;continue}throw Error(`Expected ',' or ']' at position ${$}, got '${Z[$]}'`)}return K}function G(){if(Z[$]!=="{")throw Error(`Expected '{' at position ${$}, got '${Z[$]}'`);let K={};if($+=1,J(),$>=Z.length)return K;if(Z[$]==="}")return $+=1,K;while($<Z.length){if(J(),$>=Z.length)return K;let U=Y();if(J(),$>=Z.length)return K;if(Z[$]!==":")throw Error(`Expected ':' at position ${$}, got '${Z[$]}'`);if($+=1,J(),$>=Z.length)return K;if(K[U]=X(),J(),$>=Z.length)return K;if(Z[$]==="}")return $+=1,K;else if(Z[$]===","){$+=1;continue}throw Error(`Expected ',' or '}' at position ${$}, got '${Z[$]}'`)}return K}let z=X();if(J(),$<Z.length)throw Error(`Unexpected character '${Z[$]}' at position ${$}`);return z}function Q8(Q){try{if(typeof Q>"u")return null;return EU(Q)}catch{return null}}var Z8=class Q extends V0{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return Q}constructor(Z,$){if(typeof Z==="string"||Array.isArray(Z))Z={content:Z,role:$};super(Z);this.role=Z.role}static isInstance(Z){return super.isInstance(Z)&&Z.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},r6=class extends zQ{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(Q,Z){if(typeof Q==="string"||Array.isArray(Q))Q={content:Q,role:Z};super(Q);this.role=Q.role}concat(Q){return new this.constructor({content:GQ(this.content,Q.content),additional_kwargs:j0(this.additional_kwargs,Q.additional_kwargs),response_metadata:j0(this.response_metadata,Q.response_metadata),role:this.role,id:this.id??Q.id})}static isInstance(Q){return super.isInstance(Q)&&Q.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function iX(Q){return Q._getType()==="generic"}function oX(Q){return Q._getType()==="generic"}var s6=class extends V0{static lc_name(){return"FunctionMessage"}type="function";name;constructor(Q){super(Q);this.name=Q.name}},t6=class extends zQ{static lc_name(){return"FunctionMessageChunk"}type="function";concat(Q){return new this.constructor({content:GQ(this.content,Q.content),additional_kwargs:j0(this.additional_kwargs,Q.additional_kwargs),response_metadata:j0(this.response_metadata,Q.response_metadata),name:this.name??"",id:this.id??Q.id})}};function nX(Q){return Q._getType()==="function"}function rX(Q){return Q._getType()==="function"}var G0=class extends V0{static lc_name(){return"HumanMessage"}type="human";constructor(Q){super(Q)}static isInstance(Q){return super.isInstance(Q)&&Q.type==="human"}},A6=class extends zQ{static lc_name(){return"HumanMessageChunk"}type="human";constructor(Q){super(Q)}concat(Q){return new this.constructor({content:GQ(this.content,Q.content),additional_kwargs:j0(this.additional_kwargs,Q.additional_kwargs),response_metadata:j0(this.response_metadata,Q.response_metadata),id:this.id??Q.id})}static isInstance(Q){return super.isInstance(Q)&&Q.type==="human"}};function sX(Q){return Q.getType()==="human"}function tX(Q){return Q.getType()==="human"}var gQ=class extends V0{type="remove";id;constructor(Q){super({...Q,content:[]});this.id=Q.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(Q){return super.isInstance(Q)&&Q.type==="remove"}};var L0=class Q extends V0{static lc_name(){return"SystemMessage"}type="system";constructor(Z){super(Z)}concat(Z){if(typeof Z==="string")return new Q({...this,content:GQ(this.content,Z)});if(Q.isInstance(Z))return new Q({...this,additional_kwargs:{...this.additional_kwargs,...Z.additional_kwargs},response_metadata:{...this.response_metadata,...Z.response_metadata},content:GQ(this.content,Z.content)});throw Error("Unexpected chunk type for system message")}static isInstance(Z){return super.isInstance(Z)&&Z.type==="system"}},j8=class extends zQ{static lc_name(){return"SystemMessageChunk"}type="system";constructor(Q){super(Q)}concat(Q){return new this.constructor({content:GQ(this.content,Q.content),additional_kwargs:j0(this.additional_kwargs,Q.additional_kwargs),response_metadata:j0(this.response_metadata,Q.response_metadata),id:this.id??Q.id})}static isInstance(Q){return super.isInstance(Q)&&Q.type==="system"}};function aX(Q){return Q._getType()==="system"}function eX(Q){return Q._getType()==="system"}var Q5=(Q)=>Q();function jU(Q){if(L6(Q))return Q;else if(typeof Q.id==="string"&&Q.type==="function"&&typeof Q.function==="object"&&Q.function!==null&&"arguments"in Q.function&&typeof Q.function.arguments==="string"&&"name"in Q.function&&typeof Q.function.name==="string")return{id:Q.id,args:JSON.parse(Q.function.arguments),name:Q.function.name,type:"tool_call"};else return Q}function RU(Q){return typeof Q==="object"&&Q!=null&&Q.lc===1&&Array.isArray(Q.id)&&Q.kwargs!=null&&typeof Q.kwargs==="object"}function DY(Q){let Z,$;if(RU(Q)){let J=Q.id.at(-1);if(J==="HumanMessage"||J==="HumanMessageChunk")Z="user";else if(J==="AIMessage"||J==="AIMessageChunk")Z="assistant";else if(J==="SystemMessage"||J==="SystemMessageChunk")Z="system";else if(J==="FunctionMessage"||J==="FunctionMessageChunk")Z="function";else if(J==="ToolMessage"||J==="ToolMessageChunk")Z="tool";else Z="unknown";$=Q.kwargs}else{let{type:J,...Y}=Q;Z=J,$=Y}if(Z==="human"||Z==="user")return new G0($);else if(Z==="ai"||Z==="assistant"){let{tool_calls:J,...Y}=$;if(!Array.isArray(J))return new h($);let W=J.map(jU);return new h({...Y,tool_calls:W})}else if(Z==="system")return new L0($);else if(Z==="developer")return new L0({...$,additional_kwargs:{...$.additional_kwargs,__openai_role__:"developer"}});else if(Z==="tool"&&"tool_call_id"in $)return new i({...$,content:$.content,tool_call_id:$.tool_call_id,name:$.name});else if(Z==="remove"&&"id"in $&&typeof $.id==="string")return new gQ({...$,id:$.id});else throw n8(Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
13
+
14
+ Received: ${JSON.stringify(Q,null,2)}`),"MESSAGE_COERCION_FAILURE")}function KQ(Q){if(typeof Q==="string")return new G0(Q);else if(R0(Q))return Q;if(Array.isArray(Q)){let[Z,$]=Q;return DY({type:Z,content:$})}else if(b$(Q)){let{role:Z,...$}=Q;return DY({...$,type:Z})}else return DY(Q)}function a6(Q,Z="Human",$="AI"){let J=[];for(let Y of Q){let W;if(Y.type==="human")W=Z;else if(Y.type==="ai")W=$;else if(Y.type==="system")W="System";else if(Y.type==="tool")W="Tool";else if(Y.type==="generic")W=Y.role;else throw Error(`Got unsupported message type: ${Y.type}`);let X=Y.name?`${Y.name}, `:"",q=Y.text,G=`${W}: ${X}${q}`;if(Y.type==="ai"){let z=Y;if(z.tool_calls&&z.tool_calls.length>0)G+=JSON.stringify(z.tool_calls);else if(z.additional_kwargs&&"function_call"in z.additional_kwargs)G+=JSON.stringify(z.additional_kwargs.function_call)}J.push(G)}return J.join(`
15
+ `)}function _U(Q){if(Q.data!==void 0)return Q;else{let Z=Q;return{type:Z.type,data:{content:Z.text,role:Z.role,name:void 0,tool_call_id:void 0}}}}function wZ(Q){let Z=_U(Q);switch(Z.type){case"human":return new G0(Z.data);case"ai":return new h(Z.data);case"system":return new L0(Z.data);case"function":if(Z.data.name===void 0)throw Error("Name must be defined for function messages");return new s6(Z.data);case"tool":if(Z.data.tool_call_id===void 0)throw Error("Tool call ID must be defined for tool messages");return new i(Z.data);case"generic":if(Z.data.role===void 0)throw Error("Role must be defined for chat messages");return new Z8(Z.data);default:throw Error(`Got unexpected type: ${Z.type}`)}}function Z5(Q){return Q.map(wZ)}function $5(Q){return Q.map((Z)=>Z.toDict())}function e6(Q){let Z=Q._getType();if(Z==="human")return new A6({...Q});else if(Z==="ai"){let $={...Q};if("tool_calls"in $)$={...$,tool_call_chunks:$.tool_calls?.map((J)=>({...J,type:"tool_call_chunk",index:void 0,args:JSON.stringify(J.args)}))};return new y0({...$})}else if(Z==="system")return new j8({...Q});else if(Z==="function")return new t6({...Q});else if(Z8.isInstance(Q))return new r6({...Q});else throw Error("Unknown message type.")}function f$(Q){let Z=Q.reduce((Y,W)=>{let X=Y.findIndex(([q])=>{if("id"in W&&W.id&&"index"in W&&W.index!==void 0)return W.id===q.id&&W.index===q.index;if("id"in W&&W.id)return W.id===q.id;if("index"in W&&W.index!==void 0)return W.index===q.index;return!1});if(X!==-1)Y[X].push(W);else Y.push([W]);return Y},[]),$=[],J=[];for(let Y of Z){let W=null,X=Y[0]?.name??"",q=Y.map((K)=>K.args||"").join("").trim(),G=q.length?q:"{}",z=Y[0]?.id;try{if(W=Q8(G),!z||W===null||typeof W!=="object"||Array.isArray(W))throw Error("Malformed tool call chunk args.");$.push({name:X,args:W,id:z,type:"tool_call"})}catch{J.push({name:X,args:G,id:z,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:Q,tool_calls:$,invalid_tool_calls:J}}var h=class extends V0{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}constructor(Q){let Z;if(typeof Q==="string"||Array.isArray(Q))Z={content:Q,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{Z=Q;let $=Z.additional_kwargs?.tool_calls,J=Z.tool_calls;if($!=null&&$.length>0&&(J===void 0||J.length===0))console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
16
+
17
+ Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if($!=null&&J===void 0){let[Y,W]=FZ($);Z.tool_calls=Y??[],Z.invalid_tool_calls=W??[]}else Z.tool_calls=Z.tool_calls??[],Z.invalid_tool_calls=Z.invalid_tool_calls??[]}catch{Z.tool_calls=[],Z.invalid_tool_calls=[]}if(Z.response_metadata!==void 0&&"output_version"in Z.response_metadata&&Z.response_metadata.output_version==="v1")Z.contentBlocks=Z.content,Z.content=void 0;if(Z.contentBlocks!==void 0){if(Z.tool_calls)Z.contentBlocks.push(...Z.tool_calls.map((W)=>({type:"tool_call",id:W.id,name:W.name,args:W.args})));let Y=Z.contentBlocks.filter((W)=>W.type==="tool_call").filter((W)=>!Z.tool_calls?.some((X)=>X.id===W.id&&X.name===W.name));if(Y.length>0)Z.tool_calls=Y.map((W)=>({type:"tool_call",id:W.id,name:W.name,args:W.args}))}}super(Z);if(typeof Z!=="string")this.tool_calls=Z.tool_calls??this.tool_calls,this.invalid_tool_calls=Z.invalid_tool_calls??this.invalid_tool_calls;this.usage_metadata=Z.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider==="string"){let Z=HY(this.response_metadata.model_provider);if(Z)return Z.translateContent(this)}let Q=super.contentBlocks;if(this.tool_calls){let Z=this.tool_calls.filter(($)=>!Q.some((J)=>J.id===$.id&&J.name===$.name));Q.push(...Z.map(($)=>({type:"tool_call",id:$.id,name:$.name,args:$.args})))}return Q}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(Q){return super.isInstance(Q)&&Q.type==="ai"}};function I1(Q){return Q._getType()==="ai"}function AZ(Q){return Q._getType()==="ai"}var y0=class extends zQ{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(Q){let Z;if(typeof Q==="string"||Array.isArray(Q))Z={content:Q,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(Q.tool_call_chunks===void 0||Q.tool_call_chunks.length===0)Z={...Q,tool_calls:Q.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:Q.usage_metadata!==void 0?Q.usage_metadata:void 0};else{let $=f$(Q.tool_call_chunks??[]);Z={...Q,tool_call_chunks:$.tool_call_chunks,tool_calls:$.tool_calls,invalid_tool_calls:$.invalid_tool_calls,usage_metadata:Q.usage_metadata!==void 0?Q.usage_metadata:void 0}}super(Z);this.tool_call_chunks=Z.tool_call_chunks??this.tool_call_chunks,this.tool_calls=Z.tool_calls??this.tool_calls,this.invalid_tool_calls=Z.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=Z.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider==="string"){let Z=HY(this.response_metadata.model_provider);if(Z)return Z.translateContent(this)}let Q=super.contentBlocks;if(this.tool_calls){if(typeof this.content!=="string"){let Z=this.content.filter(($)=>$.type==="tool_call").map(($)=>$.id);for(let $ of this.tool_calls)if($.id&&!Z.includes($.id))Q.push({...$,type:"tool_call",id:$.id,name:$.name,args:$.args})}}return Q}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(Q){let Z={content:GQ(this.content,Q.content),additional_kwargs:j0(this.additional_kwargs,Q.additional_kwargs),response_metadata:k$(this.response_metadata,Q.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??Q.id};if(this.tool_call_chunks!==void 0||Q.tool_call_chunks!==void 0){let J=F6(this.tool_call_chunks,Q.tool_call_chunks);if(J!==void 0&&J.length>0)Z.tool_call_chunks=J}if(this.tool_calls!==void 0||Q.tool_calls!==void 0){let J=F6(this.tool_calls,Q.tool_calls);if(J!==void 0&&J.length>0)Z.tool_calls=J}if(this.usage_metadata!==void 0||Q.usage_metadata!==void 0)Z.usage_metadata=_1(this.usage_metadata,Q.usage_metadata);return new this.constructor(Z)}static isInstance(Q){return super.isInstance(Q)&&Q.type==="ai"}};var J5=_({getEnv:()=>G5,getEnvironmentVariable:()=>wQ,getRuntimeEnvironment:()=>FY,isBrowser:()=>Y5,isDeno:()=>h$,isJsDom:()=>X5,isNode:()=>q5,isWebWorker:()=>W5}),Y5=()=>typeof window<"u"&&typeof window.document<"u",W5=()=>typeof globalThis==="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",X5=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),h$=()=>typeof Deno<"u",q5=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!h$(),G5=()=>{let Q;if(Y5())Q="browser";else if(q5())Q="node";else if(W5())Q="webworker";else if(X5())Q="jsdom";else if(h$())Q="deno";else Q="other";return Q},VY;function FY(){if(VY===void 0)VY={library:"langchain-js",runtime:G5()};return VY}function wQ(Q){try{if(typeof process<"u")return process.env?.[Q];else if(h$())return Deno?.env.get(Q);else return}catch{return}}$8();var z5=_({BaseCallbackHandler:()=>J8,callbackHandlerPrefersStreaming:()=>PZ,isBaseCallbackHandler:()=>LY}),TU=class{};function PZ(Q){return"lc_prefer_streaming"in Q&&Q.lc_prefer_streaming}var J8=class extends TU{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,R1(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=wQ("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(Q){super();if(this.lc_kwargs=Q||{},Q)this.ignoreLLM=Q.ignoreLLM??this.ignoreLLM,this.ignoreChain=Q.ignoreChain??this.ignoreChain,this.ignoreAgent=Q.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=Q.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=Q.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=Q.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(Q._awaitHandler??this.awaitHandlers)}copy(){return new this.constructor(this)}toJSON(){return g0.prototype.toJSON.call(this)}toJSONNotImplemented(){return g0.prototype.toJSONNotImplemented.call(this)}static fromMethods(Q){class Z extends J8{name=mQ();constructor(){super();Object.assign(this,Q)}}return new Z}},LY=(Q)=>{let Z=Q;return Z!==void 0&&typeof Z.copy==="function"&&typeof Z.name==="string"&&typeof Z.awaitHandlers==="boolean"};$8();var K5="gen_ai.operation.name",U5="gen_ai.system",wY="gen_ai.request.model",H5="gen_ai.response.model",AY="gen_ai.usage.input_tokens",PY="gen_ai.usage.output_tokens",NY="gen_ai.usage.total_tokens",B5="gen_ai.request.max_tokens",D5="gen_ai.request.temperature",V5="gen_ai.request.top_p",F5="gen_ai.request.frequency_penalty",L5="gen_ai.request.presence_penalty",w5="gen_ai.response.finish_reasons",A5="gen_ai.prompt",P5="gen_ai.completion",N5="gen_ai.request.extra_query",O5="gen_ai.request.extra_body",E5="gen_ai.serialized.name",j5="gen_ai.serialized.signature",R5="gen_ai.serialized.doc",_5="gen_ai.response.id",I5="gen_ai.response.service_tier",T5="gen_ai.response.system_fingerprint",S5="gen_ai.usage.input_token_details",x5="gen_ai.usage.output_token_details",M5="langsmith.trace.session_id",v5="langsmith.trace.session_name",y5="langsmith.span.kind",C5="langsmith.trace.name",b5="langsmith.metadata",OY="langsmith.span.tags";var k5="langsmith.request.streaming",f5="langsmith.request.headers";var xU=(...Q)=>fetch(...Q),MU=void 0,h5=Symbol.for("ls:fetch_implementation");var g5=()=>{if(globalThis[h5]===void 0)return!0;return MU??!1},m5=(Q)=>{return async(...Z)=>{if(Q||m0("DEBUG")==="true"){let[J,Y]=Z;console.log(`→ ${Y?.method||"GET"} ${J}`)}let $=await(globalThis[h5]??xU)(...Z);if(Q||m0("DEBUG")==="true")console.log(`← ${$.status} ${$.statusText} ${$.url}`);return $}};var NZ=()=>{return m0("PROJECT")??dQ("LANGCHAIN_SESSION")??"default"};$8();var d5={};function Q1(Q){if(!d5[Q])console.warn(Q),d5[Q]=!0}var x=(Q)=>BigInt(Q),l5=x("0x9E3779B1"),i5=x("0x85EBCA77"),vU=x("0xC2B2AE3D"),P6=x("0x9E3779B185EBCA87"),Z1=x("0xC2B2AE3D27D4EB4F"),o5=x("0x165667B19E3779F9"),_Y=x("0x85EBCA77C2B2AE63"),yU=x("0x27D4EB2F165667C5"),CU=x("0x165667919E3779F9"),bU=x("0x9FB21C651E98DF25");function kU(Q){let Z=new Uint8Array(Q.length/2);for(let $=0;$<Q.length;$+=2)Z[$/2]=parseInt(Q.substring($,$+2),16);return Z}var R8=kU("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),S1=(x(1)<<x(128))-x(1),e=(x(1)<<x(64))-x(1),u$=(x(1)<<x(32))-x(1),s8=64,n5=s8/8,fU=8,g$=4;function A0(Q,Z=0){return new Uint8Array(Q.buffer,Q.byteOffset+Z,Q.length-Z)}function N0(Q,Z=0){return new DataView(Q.buffer,Q.byteOffset+Z).getBigUint64(0,!0)}function T1(Q,Z=0){return new DataView(Q.buffer,Q.byteOffset+Z).getUint32(0,!0)}function EY(Q,Z=0){return Q[Z]}var hU=(Q)=>{return(Q&x(255))<<x(56)|(Q&x(65280))<<x(40)|(Q&x(16711680))<<x(24)|(Q&x(4278190080))<<x(8)|(Q&x(1095216660480))>>x(8)|(Q&x(280375465082880))>>x(24)|(Q&x(71776119061217280))>>x(40)|(Q&x(18374686479671624000))>>x(56)},gU=(Q)=>{return Q=(Q&x(65535))<<x(16)|(Q&x(4294901760))>>x(16),Q=(Q&x(16711935))<<x(8)|(Q&x(4278255360))>>x(8),Q},mU=(Q,Z)=>(Q&u$)*(Z&u$)&e,x1=(Q)=>{if(!Q)throw Error("Assert failed")};function dU(Q,Z){return(Q<<Z|Q>>x(32)-Z)&u$}function r5(Q,Z,$){for(let J=0;J<n5;J++){let Y=N0(Z,J*8),W=Y^N0($,J*8);Q[J^1]+=Y,Q[J]+=mU(W,W>>x(32))}return Q}function u5(Q,Z,$,J){for(let Y=0;Y<J;Y++)r5(Q,A0(Z,Y*s8),A0($,Y*8));return Q}function uU(Q,Z){for(let $=0;$<n5;$++){let J=N0(Z,$*8),Y=Q[$];Y=jY(Y,x(47)),Y^=J,Y*=l5,Q[$]=Y&e}return Q}function m$(Q,Z){return s5(Q[0]^N0(Z,0),Q[1]^N0(Z,fU))}function p5(Q,Z,$){let J=$;return J+=m$(Q.slice(0),A0(Z,0*g$)),J+=m$(Q.slice(2),A0(Z,4*g$)),J+=m$(Q.slice(4),A0(Z,8*g$)),J+=m$(Q.slice(6),A0(Z,12*g$)),_8(J&e)}function pU(Q,Z,$,J,Y){let W=Math.floor(($.byteLength-s8)/8),X=s8*W,q=Math.floor((Z.byteLength-1)/X);for(let G=0;G<q;G++)Q=u5(Q,A0(Z,G*X),$,W),Q=Y(Q,A0($,$.byteLength-s8));{let G=Math.floor((Z.byteLength-1-X*q)/s8);Q=u5(Q,A0(Z,q*X),$,G),Q=J(Q,A0(Z,Z.byteLength-s8),A0($,$.byteLength-s8-7))}return Q}function cU(Q,Z,$){let J=new BigUint64Array([vU,P6,Z1,o5,_Y,i5,yU,l5]);x1(Q.length>128),J=pU(J,Q,Z,r5,uU),x1(J.length*8==64);{let Y=p5(J,A0(Z,11),x(Q.byteLength)*P6&e);return p5(J,A0(Z,Z.byteLength-s8-11),~(x(Q.byteLength)*Z1)&e)<<x(64)|Y}}function s5(Q,Z){let $=Q*Z&S1;return $&e^$>>x(64)}function c5(Q,Z,$){return s5((N0(Q,0)^N0(Z,0)+$)&e,(N0(Q,8)^N0(Z,8)-$)&e)}function d$(Q,Z,$,J,Y){let W=Q&e,X=Q>>x(64)&e;return W+=c5(Z,J,Y),W^=N0($,0)+N0($,8),W&=e,X+=c5($,A0(J,16),Y),X^=N0(Z,0)+N0(Z,8),X&=e,X<<x(64)|W}function _8(Q){return Q^=Q>>x(37),Q*=CU,Q&=e,Q^=Q>>x(32),Q}function p$(Q){return Q^=Q>>x(33),Q*=Z1,Q&=e,Q^=Q>>x(29),Q*=o5,Q&=e,Q^=Q>>x(32),Q}function lU(Q,Z,$){let J=Q.byteLength;x1(J>0&&J<=3);let Y=x(EY(Q,J-1))|x(J<<8)|x(EY(Q,0)<<16)|x(EY(Q,J>>1)<<24),W=(x(T1(Z,0))^x(T1(Z,4)))+$,X=(Y^W)&e,q=(x(T1(Z,8))^x(T1(Z,12)))-$,G=(dU(gU(Y),x(13))^q)&e;return(p$(G)&e)<<x(64)|p$(X)}function jY(Q,Z){return Q^Q>>Z}function iU(Q,Z,$){let J=Q.byteLength;x1(J>=4&&J<=8);{let Y=T1(Q,0),W=T1(Q,J-4),X=x(Y)|x(W)<<x(32),q=(N0(Z,16)^N0(Z,24))+$&e,z=(X^q)*(P6+(x(J)<<x(2)))&S1;return z+=(z&e)<<x(65),z&=S1,z^=z>>x(67),jY(jY(z&e,x(35))*bU&e,x(28))|_8(z>>x(64))<<x(64)}}function oU(Q,Z,$){let J=Q.byteLength;x1(J>=9&&J<=16);{let Y=(N0(Z,32)^N0(Z,40))+$&e,W=(N0(Z,48)^N0(Z,56))-$&e,X=N0(Q),q=N0(Q,J-8),G=(X^q^Y)*P6,z=(G&e)+(x(J-1)<<x(54));G=G&(S1^e)|z,q^=W,G+=q+(q&u$)*(i5-x(1))<<x(64),G&=S1,G^=hU(G>>x(64));let K=(G&e)*Z1;return K+=(G>>x(64))*Z1<<x(64),K&=S1,_8(K&e)|_8(K>>x(64))<<x(64)}}function nU(Q,Z){let $=Q.byteLength;if(x1($<=16),$>8)return oU(Q,R8,Z);if($>=4)return iU(Q,R8,Z);if($>0)return lU(Q,R8,Z);return p$(Z^N0(R8,64)^N0(R8,72))|p$(Z^N0(R8,80)^N0(R8,88))<<x(64)}function RY(Q){return~Q+x(1)&e}function rU(Q,Z,$){let J=x(Q.byteLength)*P6&e,Y=x(Q.byteLength-1)/x(32);while(Y>=0){let q=Number(Y);J=d$(J,A0(Q,16*q),A0(Q,Q.byteLength-16*(q+1)),A0(Z,32*q),$),Y--}let W=J+(J>>x(64))&e;W=_8(W);let X=(J&e)*P6+(J>>x(64))*_Y+(x(Q.byteLength)-$&e)*Z1;return X&=e,X=RY(_8(X)),W|X<<x(64)}function sU(Q,Z,$){let J=x(Q.byteLength)*P6&e;for(let X=32;X<160;X+=32)J=d$(J,A0(Q,X-32),A0(Q,X-16),A0(Z,X-32),$);J=_8(J&e)|_8(J>>x(64))<<x(64);for(let X=160;X<=Q.byteLength;X+=32)J=d$(J,A0(Q,X-32),A0(Q,X-16),A0(Z,3+X-160),$);J=d$(J,A0(Q,Q.byteLength-16),A0(Q,Q.byteLength-32),A0(Z,103),RY($));let Y=J+(J>>x(64))&e;Y=_8(Y);let W=(J&e)*P6+(J>>x(64))*_Y+(x(Q.byteLength)-$&e)*Z1;return W&=e,W=RY(_8(W)),Y|W<<x(64)}function t5(Q,Z=x(0)){let $=Q.byteLength;if($<=16)return nU(Q,Z);if($<=128)return rU(Q,R8,Z);if($<=240)return sU(Q,R8,Z);return cU(Q,R8,Z)}function a5(Q){let Z=new Uint8Array(16),$=new DataView(Z.buffer),J=Q&e,Y=Q>>x(64);return $.setBigUint64(0,Y,!1),$.setBigUint64(8,J,!1),Z}var e5=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function n(Q,Z){if(!e5.test(Q)){let $=Z!==void 0?`Invalid UUID for ${Z}: ${Q}`:`Invalid UUID: ${Q}`;throw Error($)}return Q}function c$(Q){let Z=typeof Q==="string"?Date.parse(Q):Q;return mQ({msecs:Z,seq:0})}function tU(Q){if(!e5.test(Q))return null;let Z=Q[14];return parseInt(Z,16)}function aU(Q){let Z=Q.replace(/-/g,""),$=new Uint8Array(16);for(let J=0;J<16;J++)$[J]=parseInt(Z.slice(J*2,J*2+2),16);return $}function eU(Q){let Z=Array.from(Q).map(($)=>$.toString(16).padStart(2,"0")).join("");return`${Z.slice(0,8)}-${Z.slice(8,12)}-${Z.slice(12,16)}-${Z.slice(16,20)}-${Z.slice(20)}`}var QH=new TextEncoder;function ZH(Q){let Z=QH.encode(Q),$=t5(Z);return a5($)}function OZ(Q,Z){let $=`${Q}:${Z}`,J=ZH($),Y=new Uint8Array(16);if(tU(Q)===7){let X=aU(Q);Y.set(X.slice(0,6),0)}else{let X=Date.now();Y[0]=X/1099511627776&255,Y[1]=X/4294967296&255,Y[2]=X/16777216&255,Y[3]=X/65536&255,Y[4]=X/256&255,Y[5]=X&255}return Y[6]=112|J[0]&15,Y[7]=J[1],Y[8]=128|J[2]&63,Y.set(J.slice(3,10),9),eU(Y)}import*as RQ from"node:fs";import*as Q7 from"node:path";function Z7(Q,Z){let $=Q7.dirname(Q);if(!RQ.existsSync($))RQ.mkdirSync($,{recursive:!0});let J={entries:Z},Y=`${Q}.tmp`;try{RQ.writeFileSync(Y,JSON.stringify(J,null,2)),RQ.renameSync(Y,Q)}catch(W){if(RQ.existsSync(Y))RQ.unlinkSync(Y);throw W}}function $7(Q){if(!RQ.existsSync(Q))return null;try{let Z=RQ.readFileSync(Q,"utf-8");return JSON.parse(Z).entries??null}catch{return null}}function $H(Q,Z){if(Z===null)return!1;return Date.now()-Q.createdAt>Z*1000}class IY{constructor(Q={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(Q)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let Q=this.totalRequests;return Q>0?this._metrics.hits/Q:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(Q,Z){if(this.maxSize===0)return;let $=this.cache.get(Q);if(!$){this._metrics.misses+=1;return}return this.cache.delete(Q),this.cache.set(Q,{...$,refreshFunc:Z}),this._metrics.hits+=1,$.value}set(Q,Z,$){if(this.maxSize===0)return;if(this.refreshTimer===void 0)this.startRefreshLoop();if(!this.cache.has(Q)&&this.cache.size>=this.maxSize){let Y=this.cache.keys().next().value;if(Y!==void 0)this.cache.delete(Y)}let J={value:Z,createdAt:Date.now(),refreshFunc:$};this.cache.delete(Q),this.cache.set(Q,J)}invalidate(Q){this.cache.delete(Q)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){if(this.refreshTimer)clearInterval(this.refreshTimer),this.refreshTimer=void 0}dump(Q){let Z={};for(let[$,J]of this.cache.entries())Z[$]=J.value;Z7(Q,Z)}load(Q){let Z=$7(Q);if(!Z)return 0;let $=0,J=Date.now();for(let[Y,W]of Object.entries(Z)){if(this.cache.size>=this.maxSize)break;let X={value:W,createdAt:J};this.cache.set(Y,X),$+=1}return $}startRefreshLoop(){if(this.stop(),this.ttlSeconds!==null){if(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch((Q)=>{console.warn("Unexpected error in cache refresh loop:",Q)})},this.refreshIntervalSeconds*1000),this.refreshTimer.unref)this.refreshTimer.unref()}}getStaleEntries(){let Q=[];for(let[Z,$]of this.cache.entries())if($H($,this.ttlSeconds))Q.push([Z,$]);return Q}async refreshStaleEntries(){let Q=this.getStaleEntries();if(Q.length===0)return;for(let[Z,$]of Q)if($.refreshFunc!==void 0)try{let J=await $.refreshFunc();this.set(Z,J,$.refreshFunc),this._metrics.refreshes+=1}catch(J){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${Z}:`,J)}}configure(Q){this.stop(),this.refreshIntervalSeconds=Q.refreshIntervalSeconds??60,this.maxSize=Q.maxSize??100,this.ttlSeconds=Q.ttlSeconds??300}}var l$=new IY;var i$="0.5.4";var T8,JH=()=>typeof window<"u"&&typeof window.document<"u",YH=()=>typeof globalThis==="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",WH=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),J7=()=>typeof Deno<"u",XH=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!J7(),xY=()=>{if(T8)return T8;if(typeof Bun<"u")T8="bun";else if(JH())T8="browser";else if(XH())T8="node";else if(YH())T8="webworker";else if(WH())T8="jsdom";else if(J7())T8="deno";else T8="other";return T8},TY;function o$(){if(TY===void 0){let Q=xY(),Z=GH();TY={library:"langsmith",runtime:Q,sdk:"langsmith-js",sdk_version:i$,...Z}}return TY}function MY(){let Q=qH(),Z={},$=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[J,Y]of Object.entries(Q))if(typeof Y==="string"&&!$.includes(J)&&!J.toLowerCase().includes("key")&&!J.toLowerCase().includes("secret")&&!J.toLowerCase().includes("token"))if(J==="LANGCHAIN_REVISION_ID")Z.revision_id=Y;else Z[J]=Y;return Z}function qH(){let Q={};try{if(typeof process<"u"&&process.env){for(let[Z,$]of Object.entries(process.env))if((Z.startsWith("LANGCHAIN_")||Z.startsWith("LANGSMITH_"))&&$!=null)if((Z.toLowerCase().includes("key")||Z.toLowerCase().includes("secret")||Z.toLowerCase().includes("token"))&&typeof $==="string")Q[Z]=$.slice(0,2)+"*".repeat($.length-4)+$.slice(-2);else Q[Z]=$}}catch(Z){}return Q}function dQ(Q){try{return typeof process<"u"?process.env?.[Q]:void 0}catch(Z){return}}function m0(Q){return dQ(`LANGSMITH_${Q}`)||dQ(`LANGCHAIN_${Q}`)}var SY;function GH(){if(SY!==void 0)return SY;let Q=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],Z={};for(let $ of Q){let J=dQ($);if(J!==void 0)Z[$]=J}return SY=Z,Z}function n$(){return dQ("OTEL_ENABLED")==="true"||m0("OTEL_ENABLED")==="true"}class W7{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(Q,...Z){if(!this.hasWarned&&n$())console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0;let $;if(Z.length===1&&typeof Z[0]==="function")$=Z[0];else if(Z.length===2&&typeof Z[1]==="function")$=Z[1];else if(Z.length===3&&typeof Z[2]==="function")$=Z[2];if(typeof $==="function")return $();return}}class X7{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new W7})}getTracer(Q,Z){return this.mockTracer}getActiveSpan(){return}setSpan(Q,Z){return Q}getSpan(Q){return}setSpanContext(Q,Z){return Q}getTracerProvider(){return}setGlobalTracerProvider(Q){return!1}}class q7{active(){return{}}with(Q,Z){return Z()}}var vY=Symbol.for("ls:otel_trace"),yY=Symbol.for("ls:otel_context"),Y7=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),zH=new X7,KH=new q7;class G7{getTraceInstance(){return globalThis[vY]??zH}getContextInstance(){return globalThis[yY]??KH}initializeGlobalInstances(Q){if(globalThis[vY]===void 0)globalThis[vY]=Q.trace;if(globalThis[yY]===void 0)globalThis[yY]=Q.context}setDefaultOTLPTracerComponents(Q){globalThis[Y7]=Q}getDefaultOTLPTracerComponents(){return globalThis[Y7]??void 0}}var CY=new G7;function r$(){return CY.getTraceInstance()}function z7(){return CY.getContextInstance()}function K7(){return CY.getDefaultOTLPTracerComponents()}var UH={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function HH(Q){return UH[Q]||Q}class bY{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(Q,Z){for(let $ of Q)try{if(!$.run)continue;if($.operation==="post"){let J=this.createSpanForRun($,$.run,Z.get($.id));if(J&&!$.run.end_time)this.spans.set($.id,J)}else this.updateSpanForRun($,$.run)}catch(J){console.error(`Error processing operation ${$.id}:`,J)}}createSpanForRun(Q,Z,$){let J=$&&r$().getSpan($);if(!J)return;try{return this.finishSpanSetup(J,Z,Q)}catch(Y){console.error(`Failed to create span for run ${Q.id}:`,Y);return}}finishSpanSetup(Q,Z,$){if(this.setSpanAttributes(Q,Z,$),Z.error)Q.setStatus({code:2}),Q.recordException(Error(Z.error));else Q.setStatus({code:1});if(Z.end_time)Q.end(new Date(Z.end_time));return Q}updateSpanForRun(Q,Z){try{let $=this.spans.get(Q.id);if(!$){console.debug(`No span found for run ${Q.id} during update`);return}if(this.setSpanAttributes($,Z,Q),Z.error)$.setStatus({code:2}),$.recordException(Error(Z.error));else $.setStatus({code:1});let J=Z.end_time;if(J)$.end(new Date(J)),this.spans.delete(Q.id)}catch($){console.error(`Failed to update span for run ${Q.id}:`,$)}}extractModelName(Q){if(Q.extra?.metadata){let Z=Q.extra.metadata;if(Z.ls_model_name)return Z.ls_model_name;if(Z.invocation_params){let $=Z.invocation_params;if($.model)return $.model;else if($.model_name)return $.model_name}}return}setSpanAttributes(Q,Z,$){if("run_type"in Z&&Z.run_type){Q.setAttribute(y5,Z.run_type);let X=HH(Z.run_type||"chain");Q.setAttribute(K5,X)}if("name"in Z&&Z.name)Q.setAttribute(C5,Z.name);if("session_id"in Z&&Z.session_id)Q.setAttribute(M5,Z.session_id);if("session_name"in Z&&Z.session_name)Q.setAttribute(v5,Z.session_name);this.setGenAiSystem(Q,Z);let J=this.extractModelName(Z);if(J)Q.setAttribute(wY,J);if("prompt_tokens"in Z&&typeof Z.prompt_tokens==="number")Q.setAttribute(AY,Z.prompt_tokens);if("completion_tokens"in Z&&typeof Z.completion_tokens==="number")Q.setAttribute(PY,Z.completion_tokens);if("total_tokens"in Z&&typeof Z.total_tokens==="number")Q.setAttribute(NY,Z.total_tokens);this.setInvocationParameters(Q,Z);let Y=Z.extra?.metadata||{};for(let[X,q]of Object.entries(Y))if(q!==null&&q!==void 0)Q.setAttribute(`${b5}.${X}`,String(q));let W=Z.tags;if(W&&Array.isArray(W))Q.setAttribute(OY,W.join(", "));else if(W)Q.setAttribute(OY,String(W));if("serialized"in Z&&typeof Z.serialized==="object"){let X=Z.serialized;if(X.name)Q.setAttribute(E5,String(X.name));if(X.signature)Q.setAttribute(j5,String(X.signature));if(X.doc)Q.setAttribute(R5,String(X.doc))}this.setIOAttributes(Q,$)}setGenAiSystem(Q,Z){let $="langchain",J=this.extractModelName(Z);if(J){let Y=J.toLowerCase();if(Y.includes("anthropic")||Y.startsWith("claude"))$="anthropic";else if(Y.includes("bedrock"))$="aws.bedrock";else if(Y.includes("azure")&&Y.includes("openai"))$="az.ai.openai";else if(Y.includes("azure")&&Y.includes("inference"))$="az.ai.inference";else if(Y.includes("cohere"))$="cohere";else if(Y.includes("deepseek"))$="deepseek";else if(Y.includes("gemini"))$="gemini";else if(Y.includes("groq"))$="groq";else if(Y.includes("watson")||Y.includes("ibm"))$="ibm.watsonx.ai";else if(Y.includes("mistral"))$="mistral_ai";else if(Y.includes("gpt")||Y.includes("openai"))$="openai";else if(Y.includes("perplexity")||Y.includes("sonar"))$="perplexity";else if(Y.includes("vertex"))$="vertex_ai";else if(Y.includes("xai")||Y.includes("grok"))$="xai"}Q.setAttribute(U5,$)}setInvocationParameters(Q,Z){if(!Z.extra?.metadata?.invocation_params)return;let $=Z.extra.metadata.invocation_params;if($.max_tokens!==void 0)Q.setAttribute(B5,$.max_tokens);if($.temperature!==void 0)Q.setAttribute(D5,$.temperature);if($.top_p!==void 0)Q.setAttribute(V5,$.top_p);if($.frequency_penalty!==void 0)Q.setAttribute(F5,$.frequency_penalty);if($.presence_penalty!==void 0)Q.setAttribute(L5,$.presence_penalty)}setIOAttributes(Q,Z){if(Z.run.inputs)try{let $=Z.run.inputs;if(typeof $==="object"&&$!==null){if($.model&&Array.isArray($.messages))Q.setAttribute(wY,$.model);if($.stream!==void 0)Q.setAttribute(k5,$.stream);if($.extra_headers)Q.setAttribute(f5,JSON.stringify($.extra_headers));if($.extra_query)Q.setAttribute(N5,JSON.stringify($.extra_query));if($.extra_body)Q.setAttribute(O5,JSON.stringify($.extra_body))}Q.setAttribute(A5,JSON.stringify($))}catch($){console.debug(`Failed to process inputs for run ${Z.id}`,$)}if(Z.run.outputs)try{let $=Z.run.outputs,J=this.getUnifiedRunTokens($);if(J)Q.setAttribute(AY,J[0]),Q.setAttribute(PY,J[1]),Q.setAttribute(NY,J[0]+J[1]);if($&&typeof $==="object"){if($.model)Q.setAttribute(H5,String($.model));if($.id)Q.setAttribute(_5,$.id);if($.choices&&Array.isArray($.choices)){let Y=$.choices.map((W)=>W.finish_reason).filter((W)=>W).map(String);if(Y.length>0)Q.setAttribute(w5,Y.join(", "))}if($.service_tier)Q.setAttribute(I5,$.service_tier);if($.system_fingerprint)Q.setAttribute(T5,$.system_fingerprint);if($.usage_metadata&&typeof $.usage_metadata==="object"){let Y=$.usage_metadata;if(Y.input_token_details)Q.setAttribute(S5,JSON.stringify(Y.input_token_details));if(Y.output_token_details)Q.setAttribute(x5,JSON.stringify(Y.output_token_details))}}Q.setAttribute(P5,JSON.stringify($))}catch($){console.debug(`Failed to process outputs for run ${Z.id}`,$)}}getUnifiedRunTokens(Q){if(!Q)return null;let Z=this.extractUnifiedRunTokens(Q.usage_metadata);if(Z)return Z;let $=Object.keys(Q);for(let W of $){let X=Q[W];if(!X||typeof X!=="object")continue;if(Z=this.extractUnifiedRunTokens(X.usage_metadata),Z)return Z;if(X.lc===1&&X.kwargs&&typeof X.kwargs==="object"){if(Z=this.extractUnifiedRunTokens(X.kwargs.usage_metadata),Z)return Z}}let J=Q.generations||[];if(!Array.isArray(J))return null;let Y=Array.isArray(J[0])?J.flat():J;for(let W of Y)if(typeof W==="object"&&W.message&&typeof W.message==="object"&&W.message.kwargs&&typeof W.message.kwargs==="object"){if(Z=this.extractUnifiedRunTokens(W.message.kwargs.usage_metadata),Z)return Z}return null}extractUnifiedRunTokens(Q){if(!Q||typeof Q!=="object")return null;if(typeof Q.input_tokens!=="number"||typeof Q.output_tokens!=="number")return null;return[Q.input_tokens,Q.output_tokens]}}var BH=Object.prototype.toString,DH=(Q)=>BH.call(Q)==="[object Error]",VH=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function kY(Q){if(!(Q&&DH(Q)&&Q.name==="TypeError"&&typeof Q.message==="string"))return!1;let{message:$,stack:J}=Q;if($==="Load failed")return J===void 0||"__sentry_captured__"in Q;if($.startsWith("error sending request for url"))return!0;return VH.has($)}function FH(Q){if(typeof Q==="number"){if(Q<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(Q))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(Q!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function s$(Q,Z,{min:$=0,allowInfinity:J=!1}={}){if(Z===void 0)return;if(typeof Z!=="number"||Number.isNaN(Z))throw TypeError(`Expected \`${Q}\` to be a number${J?" or Infinity":""}.`);if(!J&&!Number.isFinite(Z))throw TypeError(`Expected \`${Q}\` to be a finite number.`);if(Z<$)throw TypeError(`Expected \`${Q}\` to be ≥ ${$}.`)}class H7 extends Error{constructor(Q){super();if(Q instanceof Error)this.originalError=Q,{message:Q}=Q;else this.originalError=Error(Q),this.originalError.stack=this.stack;this.name="AbortError",this.message=Q}}function LH(Q,Z){let $=Math.max(1,Q+1),J=Z.randomize?Math.random()+1:1,Y=Math.round(J*Z.minTimeout*Z.factor**($-1));return Y=Math.min(Y,Z.maxTimeout),Y}function U7(Q,Z){if(!Number.isFinite(Z))return Z;return Z-(performance.now()-Q)}async function wH({error:Q,attemptNumber:Z,retriesConsumed:$,startTime:J,options:Y}){let W=Q instanceof Error?Q:TypeError(`Non-error was thrown: "${Q}". You should only throw errors.`);if(W instanceof H7)throw W.originalError;let X=Number.isFinite(Y.retries)?Math.max(0,Y.retries-$):Y.retries,q=Y.maxRetryTime??Number.POSITIVE_INFINITY,G=Object.freeze({error:W,attemptNumber:Z,retriesLeft:X,retriesConsumed:$});if(await Y.onFailedAttempt(G),U7(J,q)<=0)throw W;let z=await Y.shouldConsumeRetry(G),K=U7(J,q);if(K<=0||X<=0)throw W;if(W instanceof TypeError&&!kY(W)){if(z)throw W;return Y.signal?.throwIfAborted(),!1}if(!await Y.shouldRetry(G))throw W;if(!z)return Y.signal?.throwIfAborted(),!1;let U=LH($,Y),H=Math.min(U,K);if(H>0)await new Promise((B,F)=>{let w=()=>{clearTimeout(A),Y.signal?.removeEventListener("abort",w),F(Y.signal.reason)},A=setTimeout(()=>{Y.signal?.removeEventListener("abort",w),B()},H);if(Y.unref)A.unref?.();Y.signal?.addEventListener("abort",w,{once:!0})});return Y.signal?.throwIfAborted(),!0}async function fY(Q,Z={}){if(Z={...Z},FH(Z.retries),Object.hasOwn(Z,"forever"))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");if(Z.retries??=10,Z.factor??=2,Z.minTimeout??=1000,Z.maxTimeout??=Number.POSITIVE_INFINITY,Z.maxRetryTime??=Number.POSITIVE_INFINITY,Z.randomize??=!1,Z.onFailedAttempt??=()=>{},Z.shouldRetry??=()=>!0,Z.shouldConsumeRetry??=()=>!0,s$("factor",Z.factor,{min:0,allowInfinity:!1}),s$("minTimeout",Z.minTimeout,{min:0,allowInfinity:!1}),s$("maxTimeout",Z.maxTimeout,{min:0,allowInfinity:!0}),s$("maxRetryTime",Z.maxRetryTime,{min:0,allowInfinity:!0}),!(Z.factor>0))Z.factor=1;Z.signal?.throwIfAborted();let $=0,J=0,Y=performance.now();while(Number.isFinite(Z.retries)?J<=Z.retries:!0){$++;try{Z.signal?.throwIfAborted();let W=await Q($);return Z.signal?.throwIfAborted(),W}catch(W){if(await wH({error:W,attemptNumber:$,retriesConsumed:J,startTime:Y,options:Z}))J++}}throw Error("Retry attempts exhausted without throwing an error.")}var t$=i6(hY(),1),B7="default"in t$.default?t$.default.default:t$.default;var AH=[408,425,429,500,502,503,504];class a${constructor(Q){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=Q.maxConcurrency??1/0,this.maxRetries=Q.maxRetries??6,this.maxQueueSizeBytes=Q.maxQueueSizeBytes,this.queue=new B7({concurrency:this.maxConcurrency}),this.onFailedResponseHook=Q?.onFailedResponseHook}call(Q,...Z){return this.callWithOptions({},Q,...Z)}callWithOptions(Q,Z,...$){let J=Q.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&J>0&&this.queueSizeBytes+J>this.maxQueueSizeBytes)return Promise.reject(Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${J} bytes.`));if(J>0)this.queueSizeBytes+=J;let Y=this.onFailedResponseHook,W=this.queue.add(()=>fY(()=>Z(...$).catch((X)=>{if(X instanceof Error)throw X;else throw Error(X)}),{async onFailedAttempt({error:X}){if(typeof X!=="object"||X==null)throw X;let q="message"in X&&typeof X.message==="string"?X.message:void 0;if(q?.startsWith("Cancel")||q?.startsWith("TimeoutError")||q?.startsWith("AbortError"))throw X;if("name"in X&&X.name==="TimeoutError")throw X;if("code"in X&&X.code==="ECONNABORTED")throw X;let G="response"in X?X.response:void 0;if(Y){if(await Y(G))return}let z=G?.status??("status"in X?X.status:void 0);if(z!=null&&(typeof z==="number"||typeof z==="string")&&!AH.includes(+z))throw X},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});if(J>0)W=W.finally(()=>{this.queueSizeBytes-=J});if(Q.signal)return Promise.race([W,new Promise((X,q)=>{Q.signal?.addEventListener("abort",()=>{q(Error("AbortError"))})})]);return W}}function gY(Q){return typeof Q?._getType==="function"}function mY(Q){let Z={type:Q._getType(),data:{content:Q.content}};if(Q?.additional_kwargs&&Object.keys(Q.additional_kwargs).length>0)Z.data.additional_kwargs={...Q.additional_kwargs};return Z}var NH=i6(PH(),1);function t8(Q){if(!Q||Q.split("/").length>2||Q.startsWith("/")||Q.endsWith("/")||Q.split(":").length>2)throw Error(`Invalid identifier format: ${Q}`);let[Z,$]=Q.split(":"),J=$||"latest";if(Z.includes("/")){let[Y,W]=Z.split("/",2);if(!Y||!W)throw Error(`Invalid identifier format: ${Q}`);return[Y,W,J]}else{if(!Z)throw Error(`Invalid identifier format: ${Q}`);return["-",Z,J]}}class D7 extends Error{constructor(Q){super(Q);Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}class V7 extends Error{constructor(Q){super(Q);Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}}function dY(Q){return Q!=null&&typeof Q==="object"&&"name"in Q&&Q?.name==="LangSmithNotFoundError"}async function u(Q,Z,$){let J;if(Q.ok){if($)J=await Q.text();return}if(Q.status===403)try{if((await Q.json())?.error==="org_scoped_key_requires_workspace")J="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable."}catch(X){let q=Error(`${Q.status} ${Q.statusText}`);throw q.status=Q?.status,q}if(J===void 0)try{J=await Q.text()}catch(X){J=""}let Y=`Failed to ${Z}. Received status [${Q.status}]: ${Q.statusText}. Message: ${J}`;if(Q.status===404)throw new V7(Y);if(Q.status===409)throw new D7(Y);let W=Error(Y);throw W.status=Q.status,W}var F7="ERR_CONFLICTING_ENDPOINTS";class uY extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS.");Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:F7}),this.name="ConflictingEndpointsError"}}function L7(Q){return typeof Q==="object"&&Q!==null&&Q.code===F7}var w7="[...]",OH={result:"[Circular]"},Q9=[],M1=[],EH=new TextEncoder;function jH(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function e$(Q){return EH.encode(Q)}function A7(Q){if(Q&&typeof Q==="object"&&Q!==null){if(Q instanceof Map)return Object.fromEntries(Q);else if(Q instanceof Set)return Array.from(Q);else if(Q instanceof Date)return Q.toISOString();else if(Q instanceof RegExp)return Q.toString();else if(Q instanceof Error)return{name:Q.name,message:Q.message}}else if(typeof Q==="bigint")return Q.toString();return Q}function RH(Q){return function(Z,$){if(Q){let J=Q.call(this,Z,$);if(J!==void 0)return J}return A7($)}}function _Q(Q,Z,$,J,Y){try{let W=JSON.stringify(Q,RH($),J);return e$(W)}catch(W){if(!W.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${Z?`
18
+ Context: ${Z}`:""}`),e$("[Unserializable]");if(m0("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${Z?`
19
+ Context: ${Z}`:""}`),typeof Y>"u")Y=jH();cY(Q,"",0,[],void 0,0,Y);let X;try{if(M1.length===0)X=JSON.stringify(Q,$,J);else X=JSON.stringify(Q,_H($),J)}catch(q){return e$("[unable to serialize, circular reference is too complex to analyze]")}finally{while(Q9.length!==0){let q=Q9.pop();if(q.length===4)Object.defineProperty(q[0],q[1],q[3]);else q[0][q[1]]=q[2]}}return e$(X)}}function pY(Q,Z,$,J){var Y=Object.getOwnPropertyDescriptor(J,$);if(Y.get!==void 0)if(Y.configurable)Object.defineProperty(J,$,{value:Q}),Q9.push([J,$,Z,Y]);else M1.push([Z,$,Q]);else J[$]=Q,Q9.push([J,$,Z])}function cY(Q,Z,$,J,Y,W,X){W+=1;var q;if(typeof Q==="object"&&Q!==null){for(q=0;q<J.length;q++)if(J[q]===Q){pY(OH,Q,Z,Y);return}if(typeof X.depthLimit<"u"&&W>X.depthLimit){pY(w7,Q,Z,Y);return}if(typeof X.edgesLimit<"u"&&$+1>X.edgesLimit){pY(w7,Q,Z,Y);return}if(J.push(Q),Array.isArray(Q))for(q=0;q<Q.length;q++)cY(Q[q],q,q,J,Q,W,X);else{Q=A7(Q);var G=Object.keys(Q);for(q=0;q<G.length;q++){var z=G[q];cY(Q[z],z,q,J,Q,W,X)}}J.pop()}}function _H(Q){return Q=typeof Q<"u"?Q:function(Z,$){return $},function(Z,$){if(M1.length>0)for(var J=0;J<M1.length;J++){var Y=M1[J];if(Y[1]===Z&&Y[0]===$){$=Y[2],M1.splice(J,1);break}}return Q.call(this,Z,$)}}function P7(Q,Z,$){if($)return Q;let J=o$(),Y=Z??MY(),W=Q.extra??{},X=W.metadata;return Q.extra={...W,runtime:{...J,...W?.runtime},metadata:{...Y,...Y.revision_id||"revision_id"in Q&&Q.revision_id?{revision_id:("revision_id"in Q?Q.revision_id:void 0)??Y.revision_id}:{},...X}},Q}var IH=(Q)=>{let Z=Q?.toString()??m0("TRACING_SAMPLING_RATE");if(Z===void 0)return;let $=parseFloat(Z);if($<0||$>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${$}`);return $},TH=(Q)=>{let $=Q.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return $==="localhost"||$==="127.0.0.1"||$==="::1"};async function SH(Q){let Z=[];for await(let $ of Q)Z.push($);return Z}function Z9(Q){if(Q===void 0)return;return Q.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}var xH=async(Q)=>{if(Q?.status===429){let Z=parseInt(Q.headers.get("retry-after")??"10",10)*1000;if(Z>0)return await new Promise(($)=>setTimeout($,Z)),!0}return!1};function N7(Q){if(typeof Q==="number")return Number(Q.toFixed(4));return Q}var MH=25165824,j7=1073741824,vH=1e4,yH=100,O7="https://api.smith.langchain.com";class R7{constructor(Q){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=Q??j7}peek(){return this.items[0]}push(Q){let Z,$=new Promise((Y)=>{Z=Y}),J=_Q(Q.item,`Serializing run with id: ${Q.item.id}`).length;if(this.sizeBytes+J>this.maxSizeBytes&&this.items.length>0)return console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${Q.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${J} bytes.`),Z(),$;return this.items.push({action:Q.action,payload:Q.item,otelContext:Q.otelContext,apiKey:Q.apiKey,apiUrl:Q.apiUrl,itemPromiseResolve:Z,itemPromise:$,size:J}),this.sizeBytes+=J,$}pop({upToSizeBytes:Q,upToSize:Z}){if(Q<1)throw Error("Number of bytes to pop off may not be less than 1.");let $=[],J=0;while(J+(this.peek()?.size??0)<Q&&this.items.length>0&&$.length<Z){let Y=this.items.shift();if(Y)$.push(Y),J+=Y.size,this.sizeBytes-=Y.size}if($.length===0&&this.items.length>0){let Y=this.items.shift();$.push(Y),J+=Y.size,this.sizeBytes-=Y.size}return[$.map((Y)=>({action:Y.action,item:Y.payload,otelContext:Y.otelContext,apiKey:Y.apiKey,apiUrl:Y.apiUrl,size:Y.size})),()=>$.forEach((Y)=>Y.itemPromiseResolve())]}}class I8{get _fetch(){return this.fetchImplementation||m5(this.debug)}constructor(Q={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:dQ("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:m0("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:dQ("LANGSMITH_DEBUG")==="true"});let Z=I8.getDefaultClientConfig();if(this.tracingSampleRate=IH(Q.tracingSamplingRate),this.apiUrl=Z9(Q.apiUrl??Z.apiUrl)??"",this.apiUrl.endsWith("/"))this.apiUrl=this.apiUrl.slice(0,-1);if(this.apiKey=Z9(Q.apiKey??Z.apiKey),this.webUrl=Z9(Q.webUrl??Z.webUrl),this.webUrl?.endsWith("/"))this.webUrl=this.webUrl.slice(0,-1);if(this.workspaceId=Z9(Q.workspaceId??m0("WORKSPACE_ID")),this.timeout_ms=Q.timeout_ms??90000,this.caller=new a$({...Q.callerOptions??{},maxRetries:4,debug:Q.debug??this.debug}),this.traceBatchConcurrency=Q.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error("Trace batch concurrency must be positive.");this.debug=Q.debug??this.debug,this.fetchImplementation=Q.fetchImplementation;let $=Q.maxIngestMemoryBytes??j7;if(this.batchIngestCaller=new a$({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:$,...Q.callerOptions??{},onFailedResponseHook:xH,debug:Q.debug??this.debug}),this.hideInputs=Q.hideInputs??Q.anonymizer??Z.hideInputs,this.hideOutputs=Q.hideOutputs??Q.anonymizer??Z.hideOutputs,this.omitTracedRuntimeInfo=Q.omitTracedRuntimeInfo??!1,this.autoBatchTracing=Q.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new R7($),this.blockOnRootRunFinalization=Q.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=Q.batchSizeBytesLimit,this.batchSizeLimit=Q.batchSizeLimit,this.fetchOptions=Q.fetchOptions||{},this.manualFlushMode=Q.manualFlushMode??this.manualFlushMode,n$())this.langSmithToOTELTranslator=new bY;if(this.cachedLSEnvVarsForMetadata=MY(),Q.cache!==void 0&&Q.disablePromptCache)Q1("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value.");if(Q.cache!==void 0)if(Q1("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),Q.cache===!1)this._promptCache=void 0;else if(Q.cache===!0)this._promptCache=l$;else this._promptCache=Q.cache;else if(!Q.disablePromptCache)this._promptCache=l$}static getDefaultClientConfig(){let Q=m0("API_KEY"),Z=m0("ENDPOINT")??O7,$=m0("HIDE_INPUTS")==="true",J=m0("HIDE_OUTPUTS")==="true";return{apiUrl:Z,apiKey:Q,webUrl:void 0,hideInputs:$,hideOutputs:J}}getHostUrl(){if(this.webUrl)return this.webUrl;else if(TH(this.apiUrl))return this.webUrl="http://localhost:3000",this.webUrl;else if(this.apiUrl.endsWith("/api/v1"))return this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl;else if(this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api"))return this.webUrl=this.apiUrl.replace("/api",""),this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("dev"))return this.webUrl="https://dev.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("eu"))return this.webUrl="https://eu.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("beta"))return this.webUrl="https://beta.smith.langchain.com",this.webUrl;else return this.webUrl="https://smith.langchain.com",this.webUrl}get headers(){let Q={"User-Agent":`langsmith-js/${i$}`};if(this.apiKey)Q["x-api-key"]=`${this.apiKey}`;if(this.workspaceId)Q["x-tenant-id"]=this.workspaceId;return Q}_getPlatformEndpointPath(Q){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${Q}`:`/platform/${Q}`}async processInputs(Q){if(this.hideInputs===!1)return Q;if(this.hideInputs===!0)return{};if(typeof this.hideInputs==="function")return this.hideInputs(Q);return Q}async processOutputs(Q){if(this.hideOutputs===!1)return Q;if(this.hideOutputs===!0)return{};if(typeof this.hideOutputs==="function")return this.hideOutputs(Q);return Q}async prepareRunCreateOrUpdateInputs(Q){let Z={...Q};if(Z.inputs!==void 0)Z.inputs=await this.processInputs(Z.inputs);if(Z.outputs!==void 0)Z.outputs=await this.processOutputs(Z.outputs);return Z}async _getResponse(Q,Z){let $=Z?.toString()??"",J=`${this.apiUrl}${Q}?${$}`;return await this.caller.call(async()=>{let W=await this._fetch(J,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(W,`fetch ${Q}`),W})}async _get(Q,Z){return(await this._getResponse(Q,Z)).json()}async*_getPaginated(Q,Z=new URLSearchParams,$){let J=Number(Z.get("offset"))||0,Y=Number(Z.get("limit"))||100;while(!0){Z.set("offset",String(J)),Z.set("limit",String(Y));let W=`${this.apiUrl}${Q}?${Z}`,X=await this.caller.call(async()=>{let G=await this._fetch(W,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(G,`fetch ${Q}`),G}),q=$?$(await X.json()):await X.json();if(q.length===0)break;if(yield q,q.length<Y)break;J+=q.length}}async*_getCursorPaginatedList(Q,Z=null,$="POST",J="runs"){let Y=Z?{...Z}:{};while(!0){let W=JSON.stringify(Y),q=await(await this.caller.call(async()=>{let z=await this._fetch(`${this.apiUrl}${Q}`,{method:$,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:W});return await u(z,`fetch ${Q}`),z})).json();if(!q)break;if(!q[J])break;yield q[J];let G=q.cursors;if(!G)break;if(!G.next)break;Y.cursor=G.next}}_shouldSample(){if(this.tracingSampleRate===void 0)return!0;return Math.random()<this.tracingSampleRate}_filterForSampling(Q,Z=!1){if(this.tracingSampleRate===void 0)return Q;if(Z){let $=[];for(let J of Q)if(!this.filteredPostUuids.has(J.trace_id))$.push(J);else if(J.id===J.trace_id)this.filteredPostUuids.delete(J.trace_id);return $}else{let $=[];for(let J of Q){let Y=J.trace_id??J.id;if(this.filteredPostUuids.has(Y))continue;if(J.id===Y)if(this._shouldSample())$.push(J);else this.filteredPostUuids.add(Y);else $.push(J)}return $}}async _getBatchSizeLimitBytes(){let Q=await this._ensureServerInfo();return this.batchSizeBytesLimit??Q?.batch_ingest_config?.size_limit_bytes??MH}async _getBatchSizeLimit(){let Q=await this._ensureServerInfo();return this.batchSizeLimit??Q?.batch_ingest_config?.size_limit??yH}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:Q,batchSizeLimit:Z}){let $=[];while(this.autoBatchQueue.items.length>0){let[J,Y]=this.autoBatchQueue.pop({upToSizeBytes:Q,upToSize:Z});if(!J.length){Y();break}let W=J.reduce((G,z)=>{let K=z.apiUrl??this.apiUrl,U=z.apiKey??this.apiKey,B=z.apiKey===this.apiKey&&z.apiUrl===this.apiUrl?"default":`${K}|${U}`;if(!G[B])G[B]=[];return G[B].push(z),G},{}),X=[];for(let[G,z]of Object.entries(W)){let K=this._processBatch(z,{apiUrl:G==="default"?void 0:G.split("|")[0],apiKey:G==="default"?void 0:G.split("|")[1]});X.push(K)}let q=Promise.all(X).finally(Y);$.push(q)}return Promise.all($)}async _processBatch(Q,Z){if(!Q.length)return;let $=Q.reduce((J,Y)=>J+(Y.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(Q);else{let J={runCreates:Q.filter((X)=>X.action==="create").map((X)=>X.item),runUpdates:Q.filter((X)=>X.action==="update").map((X)=>X.item)},Y=await this._ensureServerInfo();if(!this._multipartDisabled&&(Y?.batch_ingest_config?.use_multipart_endpoint??!0)){let X=!this._runCompressionDisabled&&Y?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(J,{...Z,useGzip:X,sizeBytes:$})}catch(q){if(dY(q))this._multipartDisabled=!0,await this.batchIngestRuns(J,{...Z,sizeBytes:$});else throw q}}else await this.batchIngestRuns(J,{...Z,sizeBytes:$})}}catch(J){console.error("Error exporting batch:",J)}}_sendBatchToOTELTranslator(Q){if(this.langSmithToOTELTranslator!==void 0){let Z=new Map,$=[];for(let J of Q)if(J.item.id&&J.otelContext)if(Z.set(J.item.id,J.otelContext),J.action==="create")$.push({operation:"post",id:J.item.id,trace_id:J.item.trace_id??J.item.id,run:J.item});else $.push({operation:"patch",id:J.item.id,trace_id:J.item.trace_id??J.item.id,run:J.item});this.langSmithToOTELTranslator.exportBatch($,Z)}}async processRunOperation(Q){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,Q.item=P7(Q.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let Z=this.autoBatchQueue.push(Q);if(this.manualFlushMode)return Z;let $=await this._getBatchSizeLimitBytes(),J=await this._getBatchSizeLimit();if(this.autoBatchQueue.sizeBytes>$||this.autoBatchQueue.items.length>J)this.drainAutoBatchQueue({batchSizeLimitBytes:$,batchSizeLimit:J});if(this.autoBatchQueue.items.length>0)this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:$,batchSizeLimit:J})},this.autoBatchAggregationDelayMs);return Z}async _getServerInfo(){let Z=await(await this.caller.call(async()=>{let $=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(vH),...this.fetchOptions});return await u($,"get server info"),$})).json();if(this.debug)console.log(`
20
+ === LangSmith Server Configuration ===
21
+ `+JSON.stringify(Z,null,2)+`
22
+ `);return Z}async _ensureServerInfo(){if(this._getServerInfoPromise===void 0)this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(Q){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${Q.status??"Unspecified status code"} ${Q.message}`)}return this._serverInfo??{}})();return this._getServerInfoPromise.then((Q)=>{if(this._serverInfo===void 0)this._getServerInfoPromise=void 0;return Q})}async _getSettings(){if(!this.settings)this.settings=this._get("/settings");return await this.settings}async flush(){let Q=await this._getBatchSizeLimitBytes(),Z=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:Q,batchSizeLimit:Z})}_cloneCurrentOTELContext(){let Q=r$(),Z=z7();if(this.langSmithToOTELTranslator!==void 0){let $=Q.getActiveSpan();if($)return Q.setSpan(Z.active(),$)}return}async createRun(Q,Z){if(!this._filterForSampling([Q]).length)return;let $={...this.headers,"Content-Type":"application/json"},J=Q.project_name;delete Q.project_name;let Y=await this.prepareRunCreateOrUpdateInputs({session_name:J,...Q,start_time:Q.start_time??Date.now()});if(this.autoBatchTracing&&Y.trace_id!==void 0&&Y.dotted_order!==void 0){let q=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:Y,otelContext:q,apiKey:Z?.apiKey,apiUrl:Z?.apiUrl}).catch(console.error);return}let W=P7(Y,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);if(Z?.apiKey!==void 0)$["x-api-key"]=Z.apiKey;if(Z?.workspaceId!==void 0)$["x-tenant-id"]=Z.workspaceId;let X=_Q(W,`Creating run with id: ${W.id}`);await this.caller.call(async()=>{let q=await this._fetch(`${Z?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:$,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:X});return await u(q,"create run",!0),q})}async batchIngestRuns({runCreates:Q,runUpdates:Z},$){if(Q===void 0&&Z===void 0)return;let J=await Promise.all(Q?.map((q)=>this.prepareRunCreateOrUpdateInputs(q))??[]),Y=await Promise.all(Z?.map((q)=>this.prepareRunCreateOrUpdateInputs(q))??[]);if(J.length>0&&Y.length>0){let q=J.reduce((z,K)=>{if(!K.id)return z;return z[K.id]=K,z},{}),G=[];for(let z of Y)if(z.id!==void 0&&q[z.id])q[z.id]={...q[z.id],...z};else G.push(z);J=Object.values(q),Y=G}let W={post:J,patch:Y};if(!W.post.length&&!W.patch.length)return;let X={post:[],patch:[]};for(let q of["post","patch"]){let G=q,z=W[G].reverse(),K=z.pop();while(K!==void 0)X[G].push(K),K=z.pop()}if(X.post.length>0||X.patch.length>0){let q=X.post.map((G)=>G.id).concat(X.patch.map((G)=>G.id)).join(",");await this._postBatchIngestRuns(_Q(X,`Ingesting runs with ids: ${q}`),$)}}async _postBatchIngestRuns(Q,Z){let $={...this.headers,"Content-Type":"application/json",Accept:"application/json"};if(Z?.apiKey!==void 0)$["x-api-key"]=Z.apiKey;await this.batchIngestCaller.callWithOptions({sizeBytes:Z?.sizeBytes},async()=>{let J=await this._fetch(`${Z?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:$,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:Q});return await u(J,"batch create run",!0),J})}async multipartIngestRuns({runCreates:Q,runUpdates:Z},$){if(Q===void 0&&Z===void 0)return;let J={},Y=[];for(let K of Q??[]){let U=await this.prepareRunCreateOrUpdateInputs(K);if(U.id!==void 0&&U.attachments!==void 0)J[U.id]=U.attachments;delete U.attachments,Y.push(U)}let W=[];for(let K of Z??[])W.push(await this.prepareRunCreateOrUpdateInputs(K));if(Y.find((K)=>{return K.trace_id===void 0||K.dotted_order===void 0})!==void 0)throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(W.find((K)=>{return K.trace_id===void 0||K.dotted_order===void 0})!==void 0)throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(Y.length>0&&W.length>0){let K=Y.reduce((H,B)=>{if(!B.id)return H;return H[B.id]=B,H},{}),U=[];for(let H of W)if(H.id!==void 0&&K[H.id])K[H.id]={...K[H.id],...H};else U.push(H);Y=Object.values(K),W=U}if(Y.length===0&&W.length===0)return;let G=[],z=[];for(let[K,U]of[["post",Y],["patch",W]])for(let H of U){let{inputs:B,outputs:F,events:w,extra:A,error:E,serialized:P,attachments:j,...R}=H,k={inputs:B,outputs:F,events:w,extra:A,error:E,serialized:P},b=_Q(R,`Serializing for multipart ingestion of run with id: ${R.id}`);z.push({name:`${K}.${R.id}`,payload:new Blob([b],{type:`application/json; length=${b.length}`})});for(let[T,V]of Object.entries(k)){if(V===void 0)continue;let v=_Q(V,`Serializing ${T} for multipart ingestion of run with id: ${R.id}`);z.push({name:`${K}.${R.id}.${T}`,payload:new Blob([v],{type:`application/json; length=${v.length}`})})}if(R.id!==void 0){let T=J[R.id];if(T){delete J[R.id];for(let[V,v]of Object.entries(T)){let I,y;if(Array.isArray(v))[I,y]=v;else I=v.mimeType,y=v.data;if(V.includes(".")){console.warn(`Skipping attachment '${V}' for run ${R.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}z.push({name:`attachment.${R.id}.${V}`,payload:new Blob([y],{type:`${I}; length=${y.byteLength}`})})}}}G.push(`trace=${R.trace_id},id=${R.id}`)}await this._sendMultipartRequest(z,G.join("; "),$)}async _createNodeFetchBody(Q,Z){let $=[];for(let W of Q)$.push(new Blob([`--${Z}\r
23
+ `])),$.push(new Blob([`Content-Disposition: form-data; name="${W.name}"\r
24
+ `,`Content-Type: ${W.payload.type}\r
25
+ \r
26
+ `])),$.push(W.payload),$.push(new Blob([`\r
27
+ `]));return $.push(new Blob([`--${Z}--\r
28
+ `])),await new Blob($).arrayBuffer()}async _createMultipartStream(Q,Z){let $=new TextEncoder;return new ReadableStream({async start(Y){let W=async(X)=>{if(typeof X==="string")Y.enqueue($.encode(X));else Y.enqueue(X)};for(let X of Q){await W(`--${Z}\r
29
+ `),await W(`Content-Disposition: form-data; name="${X.name}"\r
30
+ `),await W(`Content-Type: ${X.payload.type}\r
31
+ \r
32
+ `);let G=X.payload.stream().getReader();try{let z;while(!(z=await G.read()).done)Y.enqueue(z.value)}finally{G.releaseLock()}await W(`\r
33
+ `)}await W(`--${Z}--\r
34
+ `),Y.close()}})}async _sendMultipartRequest(Q,Z,$){let J="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),Y=()=>this._createNodeFetchBody(Q,J),W=()=>this._createMultipartStream(Q,J),X=async(q)=>{return this.batchIngestCaller.callWithOptions({sizeBytes:$?.sizeBytes},async()=>{let G=await q(),z={...this.headers,"Content-Type":`multipart/form-data; boundary=${J}`};if($?.apiKey!==void 0)z["x-api-key"]=$.apiKey;let K=G;if($?.useGzip&&typeof G==="object"&&"pipeThrough"in G)K=G.pipeThrough(new CompressionStream("gzip")),z["Content-Encoding"]="gzip";let U=await this._fetch(`${$?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:z,body:K,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(U,"Failed to send multipart request",!0),U})};try{let q,G=!1;if(g5()&&!this.multipartStreamingDisabled&&xY()!=="bun")G=!0,q=await X(W);else q=await X(Y);if((!this.multipartStreamingDisabled||G)&&q.status===422&&($?.apiUrl??this.apiUrl)!==O7)console.warn(`Streaming multipart upload to ${$?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${Z}".`),this.multipartStreamingDisabled=!0,q=await X(Y)}catch(q){if(dY(q))throw q;console.warn(`${q.message.trim()}
35
+
36
+ Context: ${Z}`)}}async updateRun(Q,Z,$){if(n(Q),Z.inputs)Z.inputs=await this.processInputs(Z.inputs);if(Z.outputs)Z.outputs=await this.processOutputs(Z.outputs);let J={...Z,id:Q};if(!this._filterForSampling([J],!0).length)return;if(this.autoBatchTracing&&J.trace_id!==void 0&&J.dotted_order!==void 0){let X=this._cloneCurrentOTELContext();if(Z.end_time!==void 0&&J.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:J,otelContext:X,apiKey:$?.apiKey,apiUrl:$?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:J,otelContext:X,apiKey:$?.apiKey,apiUrl:$?.apiUrl}).catch(console.error);return}let Y={...this.headers,"Content-Type":"application/json"};if($?.apiKey!==void 0)Y["x-api-key"]=$.apiKey;if($?.workspaceId!==void 0)Y["x-tenant-id"]=$.workspaceId;let W=_Q(Z,`Serializing payload to update run with id: ${Q}`);await this.caller.call(async()=>{let X=await this._fetch(`${$?.apiUrl??this.apiUrl}/runs/${Q}`,{method:"PATCH",headers:Y,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:W});return await u(X,"update run",!0),X})}async readRun(Q,{loadChildRuns:Z}={loadChildRuns:!1}){n(Q);let $=await this._get(`/runs/${Q}`);if(Z)$=await this._loadChildRuns($);return $}async getRunUrl({runId:Q,run:Z,projectOpts:$}){if(Z!==void 0){let J;if(Z.session_id)J=Z.session_id;else if($?.projectName)J=(await this.readProject({projectName:$?.projectName})).id;else if($?.projectId)J=$?.projectId;else J=(await this.readProject({projectName:m0("PROJECT")||"default"})).id;let Y=await this._getTenantId();return`${this.getHostUrl()}/o/${Y}/projects/p/${J}/r/${Z.id}?poll=true`}else if(Q!==void 0){let J=await this.readRun(Q);if(!J.app_path)throw Error(`Run ${Q} has no app_path`);return`${this.getHostUrl()}${J.app_path}`}else throw Error("Must provide either runId or run")}async _loadChildRuns(Q){let Z=await SH(this.listRuns({isRoot:!1,projectId:Q.session_id,traceId:Q.trace_id})),$={},J={};Z.sort((Y,W)=>(Y?.dotted_order??"").localeCompare(W?.dotted_order??""));for(let Y of Z){if(Y.parent_run_id===null||Y.parent_run_id===void 0)throw Error(`Child run ${Y.id} has no parent`);if(Y.dotted_order?.startsWith(Q.dotted_order??"")&&Y.id!==Q.id){if(!(Y.parent_run_id in $))$[Y.parent_run_id]=[];$[Y.parent_run_id].push(Y),J[Y.id]=Y}}Q.child_runs=$[Q.id]||[];for(let Y in $)if(Y!==Q.id)J[Y].child_runs=$[Y];return Q}async*listRuns(Q){let{projectId:Z,projectName:$,parentRunId:J,traceId:Y,referenceExampleId:W,startTime:X,executionOrder:q,isRoot:G,runType:z,error:K,id:U,query:H,filter:B,traceFilter:F,treeFilter:w,limit:A,select:E,order:P}=Q,j=[];if(Z)j=Array.isArray(Z)?Z:[Z];if($){let T=Array.isArray($)?$:[$],V=await Promise.all(T.map((v)=>this.readProject({projectName:v}).then((I)=>I.id)));j.push(...V)}let R=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],k={session:j.length?j:null,run_type:z,reference_example:W,query:H,filter:B,trace_filter:F,tree_filter:w,execution_order:q,parent_run:J,start_time:X?X.toISOString():null,error:K,id:U,limit:A,trace:Y,select:E?E:R,is_root:G,order:P};if(k.select.includes("child_run_ids"))Q1("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let b=0;for await(let T of this._getCursorPaginatedList("/runs/query",k))if(A){if(b>=A)break;if(T.length+b>A){yield*T.slice(0,A-b);break}b+=T.length,yield*T}else yield*T}async*listGroupRuns(Q){let{projectId:Z,projectName:$,groupBy:J,filter:Y,startTime:W,endTime:X,limit:q,offset:G}=Q,K={session_id:Z||(await this.readProject({projectName:$})).id,group_by:J,filter:Y,start_time:W?W.toISOString():null,end_time:X?X.toISOString():null,limit:Number(q)||100},U=Number(G)||0,H="/runs/group",B=`${this.apiUrl}${H}`;while(!0){let F={...K,offset:U},w=Object.fromEntries(Object.entries(F).filter(([k,b])=>b!==void 0)),A=JSON.stringify(w),P=await(await this.caller.call(async()=>{let k=await this._fetch(B,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:A});return await u(k,`Failed to fetch ${H}`),k})).json(),{groups:j,total:R}=P;if(j.length===0)break;for(let k of j)yield k;if(U+=j.length,U>=R)break}}async getRunStats({id:Q,trace:Z,parentRun:$,runType:J,projectNames:Y,projectIds:W,referenceExampleIds:X,startTime:q,endTime:G,error:z,query:K,filter:U,traceFilter:H,treeFilter:B,isRoot:F,dataSourceType:w}){let A=W||[];if(Y)A=[...W||[],...await Promise.all(Y.map((b)=>this.readProject({projectName:b}).then((T)=>T.id)))];let P=Object.fromEntries(Object.entries({id:Q,trace:Z,parent_run:$,run_type:J,session:A,reference_example:X,start_time:q,end_time:G,error:z,query:K,filter:U,trace_filter:H,tree_filter:B,is_root:F,data_source_type:w}).filter(([b,T])=>T!==void 0)),j=JSON.stringify(P);return await(await this.caller.call(async()=>{let b=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:j});return await u(b,"get run stats"),b})).json()}async shareRun(Q,{shareId:Z}={}){let $={run_id:Q,share_token:Z||Y8()};n(Q);let J=JSON.stringify($),W=await(await this.caller.call(async()=>{let X=await this._fetch(`${this.apiUrl}/runs/${Q}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:J});return await u(X,"share run"),X})).json();if(W===null||!("share_token"in W))throw Error("Invalid response from server");return`${this.getHostUrl()}/public/${W.share_token}/r`}async unshareRun(Q){n(Q),await this.caller.call(async()=>{let Z=await this._fetch(`${this.apiUrl}/runs/${Q}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(Z,"unshare run",!0),Z})}async readRunSharedLink(Q){n(Q);let $=await(await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/runs/${Q}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(J,"read run shared link"),J})).json();if($===null||!("share_token"in $))return;return`${this.getHostUrl()}/public/${$.share_token}/r`}async listSharedRuns(Q,{runIds:Z}={}){let $=new URLSearchParams({share_token:Q});if(Z!==void 0)for(let W of Z)$.append("id",W);return n(Q),await(await this.caller.call(async()=>{let W=await this._fetch(`${this.apiUrl}/public/${Q}/runs${$}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(W,"list shared runs"),W})).json()}async readDatasetSharedSchema(Q,Z){if(!Q&&!Z)throw Error("Either datasetId or datasetName must be given");if(!Q)Q=(await this.readDataset({datasetName:Z})).id;n(Q);let J=await(await this.caller.call(async()=>{let Y=await this._fetch(`${this.apiUrl}/datasets/${Q}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(Y,"read dataset shared schema"),Y})).json();return J.url=`${this.getHostUrl()}/public/${J.share_token}/d`,J}async shareDataset(Q,Z){if(!Q&&!Z)throw Error("Either datasetId or datasetName must be given");if(!Q)Q=(await this.readDataset({datasetName:Z})).id;let $={dataset_id:Q};n(Q);let J=JSON.stringify($),W=await(await this.caller.call(async()=>{let X=await this._fetch(`${this.apiUrl}/datasets/${Q}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:J});return await u(X,"share dataset"),X})).json();return W.url=`${this.getHostUrl()}/public/${W.share_token}/d`,W}async unshareDataset(Q){n(Q),await this.caller.call(async()=>{let Z=await this._fetch(`${this.apiUrl}/datasets/${Q}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(Z,"unshare dataset",!0),Z})}async readSharedDataset(Q){return n(Q),await(await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/public/${Q}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(J,"read shared dataset"),J})).json()}async listSharedExamples(Q,Z){let $={};if(Z?.exampleIds)$.id=Z.exampleIds;let J=new URLSearchParams;Object.entries($).forEach(([X,q])=>{if(Array.isArray(q))q.forEach((G)=>J.append(X,G));else J.append(X,q)});let Y=await this.caller.call(async()=>{let X=await this._fetch(`${this.apiUrl}/public/${Q}/examples?${J.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(X,"list shared examples"),X}),W=await Y.json();if(!Y.ok){if("detail"in W)throw Error(`Failed to list shared examples.
37
+ Status: ${Y.status}
38
+ Message: ${Array.isArray(W.detail)?W.detail.join(`
39
+ `):"Unspecified error"}`);throw Error(`Failed to list shared examples: ${Y.status} ${Y.statusText}`)}return W.map((X)=>({...X,_hostUrl:this.getHostUrl()}))}async createProject({projectName:Q,description:Z=null,metadata:$=null,upsert:J=!1,projectExtra:Y=null,referenceDatasetId:W=null}){let X=J?"?upsert=true":"",q=`${this.apiUrl}/sessions${X}`,G=Y||{};if($)G.metadata=$;let z={name:Q,extra:G,description:Z};if(W!==null)z.reference_dataset_id=W;let K=JSON.stringify(z);return await(await this.caller.call(async()=>{let B=await this._fetch(q,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:K});return await u(B,"create project"),B})).json()}async updateProject(Q,{name:Z=null,description:$=null,metadata:J=null,projectExtra:Y=null,endTime:W=null}){let X=`${this.apiUrl}/sessions/${Q}`,q=Y;if(J)q={...q||{},metadata:J};let G=JSON.stringify({name:Z,extra:q,description:$,end_time:W?new Date(W).toISOString():null});return await(await this.caller.call(async()=>{let U=await this._fetch(X,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:G});return await u(U,"update project"),U})).json()}async hasProject({projectId:Q,projectName:Z}){let $="/sessions",J=new URLSearchParams;if(Q!==void 0&&Z!==void 0)throw Error("Must provide either projectName or projectId, not both");else if(Q!==void 0)n(Q),$+=`/${Q}`;else if(Z!==void 0)J.append("name",Z);else throw Error("Must provide projectName or projectId");let Y=await this.caller.call(async()=>{let W=await this._fetch(`${this.apiUrl}${$}?${J}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(W,"has project"),W});try{let W=await Y.json();if(!Y.ok)return!1;if(Array.isArray(W))return W.length>0;return!0}catch(W){return!1}}async readProject({projectId:Q,projectName:Z,includeStats:$}){let J="/sessions",Y=new URLSearchParams;if(Q!==void 0&&Z!==void 0)throw Error("Must provide either projectName or projectId, not both");else if(Q!==void 0)n(Q),J+=`/${Q}`;else if(Z!==void 0)Y.append("name",Z);else throw Error("Must provide projectName or projectId");if($!==void 0)Y.append("include_stats",$.toString());let W=await this._get(J,Y),X;if(Array.isArray(W)){if(W.length===0)throw Error(`Project[id=${Q}, name=${Z}] not found`);X=W[0]}else X=W;return X}async getProjectUrl({projectId:Q,projectName:Z}){if(Q===void 0&&Z===void 0)throw Error("Must provide either projectName or projectId");let $=await this.readProject({projectId:Q,projectName:Z}),J=await this._getTenantId();return`${this.getHostUrl()}/o/${J}/projects/p/${$.id}`}async getDatasetUrl({datasetId:Q,datasetName:Z}){if(Q===void 0&&Z===void 0)throw Error("Must provide either datasetName or datasetId");let $=await this.readDataset({datasetId:Q,datasetName:Z}),J=await this._getTenantId();return`${this.getHostUrl()}/o/${J}/datasets/${$.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let Q=new URLSearchParams({limit:"1"});for await(let Z of this._getPaginated("/sessions",Q))return this._tenantId=Z[0].tenant_id,Z[0].tenant_id;throw Error("No projects found to resolve tenant.")}async*listProjects({projectIds:Q,name:Z,nameContains:$,referenceDatasetId:J,referenceDatasetName:Y,includeStats:W,datasetVersion:X,referenceFree:q,metadata:G}={}){let z=new URLSearchParams;if(Q!==void 0)for(let K of Q)z.append("id",K);if(Z!==void 0)z.append("name",Z);if($!==void 0)z.append("name_contains",$);if(J!==void 0)z.append("reference_dataset",J);else if(Y!==void 0){let K=await this.readDataset({datasetName:Y});z.append("reference_dataset",K.id)}if(W!==void 0)z.append("include_stats",W.toString());if(X!==void 0)z.append("dataset_version",X);if(q!==void 0)z.append("reference_free",q.toString());if(G!==void 0)z.append("metadata",JSON.stringify(G));for await(let K of this._getPaginated("/sessions",z))yield*K}async deleteProject({projectId:Q,projectName:Z}){let $;if(Q===void 0&&Z===void 0)throw Error("Must provide projectName or projectId");else if(Q!==void 0&&Z!==void 0)throw Error("Must provide either projectName or projectId, not both");else if(Q===void 0)$=(await this.readProject({projectName:Z})).id;else $=Q;n($),await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/sessions/${$}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(J,`delete session ${$} (${Z})`,!0),J})}async uploadCsv({csvFile:Q,fileName:Z,inputKeys:$,outputKeys:J,description:Y,dataType:W,name:X}){let q=`${this.apiUrl}/datasets/upload`,G=new FormData,z=new Blob([Q],{type:"text/csv"});if(G.append("file",z,Z),$.forEach((H)=>{G.append("input_keys",H)}),J.forEach((H)=>{G.append("output_keys",H)}),Y)G.append("description",Y);if(W)G.append("data_type",W);if(X)G.append("name",X);return await(await this.caller.call(async()=>{let H=await this._fetch(q,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:G});return await u(H,"upload CSV"),H})).json()}async createDataset(Q,{description:Z,dataType:$,inputsSchema:J,outputsSchema:Y,metadata:W}={}){let X={name:Q,description:Z,extra:W?{metadata:W}:void 0};if($)X.data_type=$;if(J)X.inputs_schema_definition=J;if(Y)X.outputs_schema_definition=Y;let q=JSON.stringify(X);return await(await this.caller.call(async()=>{let K=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:q});return await u(K,"create dataset"),K})).json()}async readDataset({datasetId:Q,datasetName:Z}){let $="/datasets",J=new URLSearchParams({limit:"1"});if(Q&&Z)throw Error("Must provide either datasetName or datasetId, not both");else if(Q)n(Q),$+=`/${Q}`;else if(Z)J.append("name",Z);else throw Error("Must provide datasetName or datasetId");let Y=await this._get($,J),W;if(Array.isArray(Y)){if(Y.length===0)throw Error(`Dataset[id=${Q}, name=${Z}] not found`);W=Y[0]}else W=Y;return W}async hasDataset({datasetId:Q,datasetName:Z}){try{return await this.readDataset({datasetId:Q,datasetName:Z}),!0}catch($){if($ instanceof Error&&$.message.toLocaleLowerCase().includes("not found"))return!1;throw $}}async diffDatasetVersions({datasetId:Q,datasetName:Z,fromVersion:$,toVersion:J}){let Y=Q;if(Y===void 0&&Z===void 0)throw Error("Must provide either datasetName or datasetId");else if(Y!==void 0&&Z!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(Y===void 0)Y=(await this.readDataset({datasetName:Z})).id;let W=new URLSearchParams({from_version:typeof $==="string"?$:$.toISOString(),to_version:typeof J==="string"?J:J.toISOString()});return await this._get(`/datasets/${Y}/versions/diff`,W)}async readDatasetOpenaiFinetuning({datasetId:Q,datasetName:Z}){if(Q!==void 0);else if(Z!==void 0)Q=(await this.readDataset({datasetName:Z})).id;else throw Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`/datasets/${Q}/openai_ft`)).text()).trim().split(`
40
+ `).map((X)=>JSON.parse(X))}async*listDatasets({limit:Q=100,offset:Z=0,datasetIds:$,datasetName:J,datasetNameContains:Y,metadata:W}={}){let q=new URLSearchParams({limit:Q.toString(),offset:Z.toString()});if($!==void 0)for(let G of $)q.append("id",G);if(J!==void 0)q.append("name",J);if(Y!==void 0)q.append("name_contains",Y);if(W!==void 0)q.append("metadata",JSON.stringify(W));for await(let G of this._getPaginated("/datasets",q))yield*G}async updateDataset(Q){let{datasetId:Z,datasetName:$,...J}=Q;if(!Z&&!$)throw Error("Must provide either datasetName or datasetId");let Y=Z??(await this.readDataset({datasetName:$})).id;n(Y);let W=JSON.stringify(J);return await(await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/datasets/${Y}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:W});return await u(q,"update dataset"),q})).json()}async updateDatasetTag(Q){let{datasetId:Z,datasetName:$,asOf:J,tag:Y}=Q;if(!Z&&!$)throw Error("Must provide either datasetName or datasetId");let W=Z??(await this.readDataset({datasetName:$})).id;n(W);let X=JSON.stringify({as_of:typeof J==="string"?J:J.toISOString(),tag:Y});await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/datasets/${W}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:X});return await u(q,"update dataset tags",!0),q})}async deleteDataset({datasetId:Q,datasetName:Z}){let $="/datasets",J=Q;if(Q!==void 0&&Z!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(Z!==void 0)J=(await this.readDataset({datasetName:Z})).id;if(J!==void 0)n(J),$+=`/${J}`;else throw Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let Y=await this._fetch(this.apiUrl+$,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(Y,`delete ${$}`,!0),Y})}async indexDataset({datasetId:Q,datasetName:Z,tag:$}){let J=Q;if(!J&&!Z)throw Error("Must provide either datasetName or datasetId");else if(J&&Z)throw Error("Must provide either datasetName or datasetId, not both");else if(!J)J=(await this.readDataset({datasetName:Z})).id;n(J);let W=JSON.stringify({tag:$});await(await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/datasets/${J}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:W});return await u(q,"index dataset"),q})).json()}async similarExamples(Q,Z,$,{filter:J}={}){let Y={limit:$,inputs:Q};if(J!==void 0)Y.filter=J;n(Z);let W=JSON.stringify(Y);return(await(await this.caller.call(async()=>{let G=await this._fetch(`${this.apiUrl}/datasets/${Z}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:W});return await u(G,"fetch similar examples"),G})).json()).examples}async createExample(Q,Z,$){if(E7(Q)){if(Z!==void 0||$!==void 0)throw Error("Cannot provide outputs or options when using ExampleCreate object")}let J=Z?$?.datasetId:Q.dataset_id,Y=Z?$?.datasetName:Q.dataset_name;if(J===void 0&&Y===void 0)throw Error("Must provide either datasetName or datasetId");else if(J!==void 0&&Y!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(J===void 0)J=(await this.readDataset({datasetName:Y})).id;let W=(Z?$?.createdAt:Q.created_at)||new Date,X;if(!E7(Q))X={inputs:Q,outputs:Z,created_at:W?.toISOString(),id:$?.exampleId,metadata:$?.metadata,split:$?.split,source_run_id:$?.sourceRunId,use_source_run_io:$?.useSourceRunIO,use_source_run_attachments:$?.useSourceRunAttachments,attachments:$?.attachments};else X=Q;let q=await this._uploadExamplesMultipart(J,[X]);return await this.readExample(q.example_ids?.[0]??Y8())}async createExamples(Q){if(Array.isArray(Q)){if(Q.length===0)return[];let E=Q,P=E[0].dataset_id,j=E[0].dataset_name;if(P===void 0&&j===void 0)throw Error("Must provide either datasetName or datasetId");else if(P!==void 0&&j!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(P===void 0)P=(await this.readDataset({datasetName:j})).id;let R=await this._uploadExamplesMultipart(P,E);return await Promise.all(R.example_ids.map((b)=>this.readExample(b)))}let{inputs:Z,outputs:$,metadata:J,splits:Y,sourceRunIds:W,useSourceRunIOs:X,useSourceRunAttachments:q,attachments:G,exampleIds:z,datasetId:K,datasetName:U}=Q;if(Z===void 0)throw Error("Must provide inputs when using legacy parameters");let H=K,B=U;if(H===void 0&&B===void 0)throw Error("Must provide either datasetName or datasetId");else if(H!==void 0&&B!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(H===void 0)H=(await this.readDataset({datasetName:B})).id;let F=Z.map((E,P)=>{return{dataset_id:H,inputs:E,outputs:$?.[P],metadata:J?.[P],split:Y?.[P],id:z?.[P],attachments:G?.[P],source_run_id:W?.[P],use_source_run_io:X?.[P],use_source_run_attachments:q?.[P]}}),w=await this._uploadExamplesMultipart(H,F);return await Promise.all(w.example_ids.map((E)=>this.readExample(E)))}async createLLMExample(Q,Z,$){return this.createExample({input:Q},{output:Z},$)}async createChatExample(Q,Z,$){let J=Q.map((W)=>{if(gY(W))return mY(W);return W}),Y=gY(Z)?mY(Z):Z;return this.createExample({input:J},{output:Y},$)}async readExample(Q){n(Q);let Z=`/examples/${Q}`,$=await this._get(Z),{attachment_urls:J,...Y}=$,W=Y;if(J)W.attachments=Object.entries(J).reduce((X,[q,G])=>{return X[q.slice(11)]={presigned_url:G.presigned_url,mime_type:G.mime_type},X},{});return W}async*listExamples({datasetId:Q,datasetName:Z,exampleIds:$,asOf:J,splits:Y,inlineS3Urls:W,metadata:X,limit:q,offset:G,filter:z,includeAttachments:K}={}){let U;if(Q!==void 0&&Z!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(Q!==void 0)U=Q;else if(Z!==void 0)U=(await this.readDataset({datasetName:Z})).id;else throw Error("Must provide a datasetName or datasetId");let H=new URLSearchParams({dataset:U}),B=J?typeof J==="string"?J:J?.toISOString():void 0;if(B)H.append("as_of",B);let F=W??!0;if(H.append("inline_s3_urls",F.toString()),$!==void 0)for(let A of $)H.append("id",A);if(Y!==void 0)for(let A of Y)H.append("splits",A);if(X!==void 0){let A=JSON.stringify(X);H.append("metadata",A)}if(q!==void 0)H.append("limit",q.toString());if(G!==void 0)H.append("offset",G.toString());if(z!==void 0)H.append("filter",z);if(K===!0)["attachment_urls","outputs","metadata"].forEach((A)=>H.append("select",A));let w=0;for await(let A of this._getPaginated("/examples",H)){for(let E of A){let{attachment_urls:P,...j}=E,R=j;if(P)R.attachments=Object.entries(P).reduce((k,[b,T])=>{return k[b.slice(11)]={presigned_url:T.presigned_url,mime_type:T.mime_type||void 0},k},{});yield R,w++}if(q!==void 0&&w>=q)break}}async deleteExample(Q){n(Q);let Z=`/examples/${Q}`;await this.caller.call(async()=>{let $=await this._fetch(this.apiUrl+Z,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u($,`delete ${Z}`,!0),$})}async deleteExamples(Q,Z){if(Q.forEach(($)=>n($)),Z?.hardDelete){let $=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}${$}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({example_ids:Q,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(J,"hard delete examples",!0),J})}else{let $=new URLSearchParams;Q.forEach((J)=>$.append("example_ids",J)),await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/examples?${$.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(J,"delete examples",!0),J})}}async updateExample(Q,Z){let $;if(Z)$=Q;else $=Q.id;n($);let J;if(Z)J={id:$,...Z};else J=Q;let Y;if(J.dataset_id!==void 0)Y=J.dataset_id;else Y=(await this.readExample($)).dataset_id;return this._updateExamplesMultipart(Y,[J])}async updateExamples(Q){let Z;if(Q[0].dataset_id===void 0)Z=(await this.readExample(Q[0].id)).dataset_id;else Z=Q[0].dataset_id;return this._updateExamplesMultipart(Z,Q)}async readDatasetVersion({datasetId:Q,datasetName:Z,asOf:$,tag:J}){let Y;if(!Q)Y=(await this.readDataset({datasetName:Z})).id;else Y=Q;if(n(Y),$&&J||!$&&!J)throw Error("Exactly one of asOf and tag must be specified.");let W=new URLSearchParams;if($!==void 0)W.append("as_of",typeof $==="string"?$:$.toISOString());if(J!==void 0)W.append("tag",J);return await(await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/datasets/${Y}/version?${W.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(q,"read dataset version"),q})).json()}async listDatasetSplits({datasetId:Q,datasetName:Z,asOf:$}){let J;if(Q===void 0&&Z===void 0)throw Error("Must provide dataset name or ID");else if(Q!==void 0&&Z!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(Q===void 0)J=(await this.readDataset({datasetName:Z})).id;else J=Q;n(J);let Y=new URLSearchParams,W=$?typeof $==="string"?$:$?.toISOString():void 0;if(W)Y.append("as_of",W);return await this._get(`/datasets/${J}/splits`,Y)}async updateDatasetSplits({datasetId:Q,datasetName:Z,splitName:$,exampleIds:J,remove:Y=!1}){let W;if(Q===void 0&&Z===void 0)throw Error("Must provide dataset name or ID");else if(Q!==void 0&&Z!==void 0)throw Error("Must provide either datasetName or datasetId, not both");else if(Q===void 0)W=(await this.readDataset({datasetName:Z})).id;else W=Q;n(W);let X={split_name:$,examples:J.map((G)=>{return n(G),G}),remove:Y},q=JSON.stringify(X);await this.caller.call(async()=>{let G=await this._fetch(`${this.apiUrl}/datasets/${W}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:q});return await u(G,"update dataset splits",!0),G})}async createFeedback(Q,Z,{score:$,value:J,correction:Y,comment:W,sourceInfo:X,feedbackSourceType:q="api",sourceRunId:G,feedbackId:z,feedbackConfig:K,projectId:U,comparativeExperimentId:H,sessionId:B,startTime:F}){if(!Q&&!U)throw Error("One of runId or projectId must be provided");if(Q&&U)throw Error("Only one of runId or projectId can be provided");let w={type:q??"api",metadata:X??{}};if(G!==void 0&&w?.metadata!==void 0&&!w.metadata.__run)w.metadata.__run={run_id:G};if(w?.metadata!==void 0&&w.metadata.__run?.run_id!==void 0)n(w.metadata.__run.run_id);let A={id:z??Y8(),run_id:Q,key:Z,score:N7($),value:J,correction:Y,comment:W,feedback_source:w,comparative_experiment_id:H,feedbackConfig:K,session_id:B??U,start_time:F},E=JSON.stringify(A),P=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let j=await this._fetch(P,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:E});return await u(j,"create feedback",!0),j}),A}async updateFeedback(Q,{score:Z,value:$,correction:J,comment:Y}){let W={};if(Z!==void 0&&Z!==null)W.score=N7(Z);if($!==void 0&&$!==null)W.value=$;if(J!==void 0&&J!==null)W.correction=J;if(Y!==void 0&&Y!==null)W.comment=Y;n(Q);let X=JSON.stringify(W);await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/feedback/${Q}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:X});return await u(q,"update feedback",!0),q})}async readFeedback(Q){n(Q);let Z=`/feedback/${Q}`;return await this._get(Z)}async deleteFeedback(Q){n(Q);let Z=`/feedback/${Q}`;await this.caller.call(async()=>{let $=await this._fetch(this.apiUrl+Z,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u($,`delete ${Z}`,!0),$})}async*listFeedback({runIds:Q,feedbackKeys:Z,feedbackSourceTypes:$}={}){let J=new URLSearchParams;if(Q)for(let Y of Q)n(Y),J.append("run",Y);if(Z)for(let Y of Z)J.append("key",Y);if($)for(let Y of $)J.append("source",Y);for await(let Y of this._getPaginated("/feedback",J))yield*Y}async createPresignedFeedbackToken(Q,Z,{expiration:$,feedbackConfig:J}={}){let Y={run_id:Q,feedback_key:Z,feedback_config:J};if($){if(typeof $==="string")Y.expires_at=$;else if($?.hours||$?.minutes||$?.days)Y.expires_in=$}else Y.expires_in={hours:3};let W=JSON.stringify(Y);return await(await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:W});return await u(q,"create presigned feedback token"),q})).json()}async createComparativeExperiment({name:Q,experimentIds:Z,referenceDatasetId:$,createdAt:J,description:Y,metadata:W,id:X}){if(Z.length===0)throw Error("At least one experiment is required");if(!$)$=(await this.readProject({projectId:Z[0]})).reference_dataset_id;if(!$==null)throw Error("A reference dataset is required");let q={id:X,name:Q,experiment_ids:Z,reference_dataset_id:$,description:Y,created_at:(J??new Date)?.toISOString(),extra:{}};if(W)q.extra.metadata=W;let G=JSON.stringify(q);return(await this.caller.call(async()=>{let K=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:G});return await u(K,"create comparative experiment"),K})).json()}async*listPresignedFeedbackTokens(Q){n(Q);let Z=new URLSearchParams({run_id:Q});for await(let $ of this._getPaginated("/feedback/tokens",Z))yield*$}_selectEvalResults(Q){let Z;if("results"in Q)Z=Q.results;else if(Array.isArray(Q))Z=Q;else Z=[Q];return Z}async _logEvaluationFeedback(Q,Z,$){let J=this._selectEvalResults(Q),Y=[];for(let W of J){let X=$||{};if(W.evaluatorInfo)X={...W.evaluatorInfo,...X};let q=null;if(W.targetRunId)q=W.targetRunId;else if(Z)q=Z.id;Y.push(await this.createFeedback(q,W.key,{score:W.score,value:W.value,comment:W.comment,correction:W.correction,sourceInfo:X,sourceRunId:W.sourceRunId,feedbackConfig:W.feedbackConfig,feedbackSourceType:"model",sessionId:Z?.session_id,startTime:Z?.start_time}))}return[J,Y]}async logEvaluationFeedback(Q,Z,$){let[J]=await this._logEvaluationFeedback(Q,Z,$);return J}async createFeedbackConfig(Q){let{feedbackKey:Z,feedbackConfig:$,isLowerScoreBetter:J=!1}=Q,Y={feedback_key:Z,feedback_config:$,is_lower_score_better:J};return(await this.caller.call(async()=>{let X=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(Y)});return await u(X,"create feedback config"),X})).json()}async*listFeedbackConfigs(Q={}){let{feedbackKeys:Z,nameContains:$,limit:J}=Q,Y=new URLSearchParams;if(Z)Z.forEach((X)=>{Y.append("key",X)});if($)Y.append("name_contains",$);Y.append("limit",(J!==void 0?Math.min(J,100):100).toString());let W=0;for await(let X of this._getPaginated("/feedback-configs",Y))if(yield*X,W+=X.length,J!==void 0&&W>=J)break}async updateFeedbackConfig(Q,Z={}){let{feedbackConfig:$,isLowerScoreBetter:J}=Z,Y={feedback_key:Q};if($!==void 0)Y.feedback_config=$;if(J!==void 0)Y.is_lower_score_better=J;return(await this.caller.call(async()=>{let X=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(Y)});return await u(X,"update feedback config"),X})).json()}async deleteFeedbackConfig(Q){let Z=new URLSearchParams({feedback_key:Q});await this.caller.call(async()=>{let $=await this._fetch(`${this.apiUrl}/feedback-configs?${Z}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u($,"delete feedback config",!0),$})}async*listAnnotationQueues(Q={}){let{queueIds:Z,name:$,nameContains:J,limit:Y}=Q,W=new URLSearchParams;if(Z)Z.forEach((q,G)=>{n(q,`queueIds[${G}]`),W.append("ids",q)});if($)W.append("name",$);if(J)W.append("name_contains",J);W.append("limit",(Y!==void 0?Math.min(Y,100):100).toString());let X=0;for await(let q of this._getPaginated("/annotation-queues",W))if(yield*q,X++,Y!==void 0&&X>=Y)break}async createAnnotationQueue(Q){let{name:Z,description:$,queueId:J,rubricInstructions:Y,rubricItems:W}=Q,X={name:Z,description:$,id:J||Y8(),rubric_instructions:Y,rubric_items:W},q=JSON.stringify(Object.fromEntries(Object.entries(X).filter(([z,K])=>K!==void 0)));return(await this.caller.call(async()=>{let z=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:q});return await u(z,"create annotation queue"),z})).json()}async readAnnotationQueue(Q){return(await this.caller.call(async()=>{let $=await this._fetch(`${this.apiUrl}/annotation-queues/${n(Q,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u($,"read annotation queue"),$})).json()}async updateAnnotationQueue(Q,Z){let{name:$,description:J,rubricInstructions:Y,rubricItems:W}=Z,X={};if($!==void 0)X.name=$;if(J!==void 0)X.description=J;if(Y!==void 0)X.rubric_instructions=Y;if(W!==void 0)X.rubric_items=W;let q=JSON.stringify(X);await this.caller.call(async()=>{let G=await this._fetch(`${this.apiUrl}/annotation-queues/${n(Q,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:q});return await u(G,"update annotation queue",!0),G})}async deleteAnnotationQueue(Q){await this.caller.call(async()=>{let Z=await this._fetch(`${this.apiUrl}/annotation-queues/${n(Q,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(Z,"delete annotation queue",!0),Z})}async addRunsToAnnotationQueue(Q,Z){let $=JSON.stringify(Z.map((J,Y)=>n(J,`runIds[${Y}]`).toString()));await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/annotation-queues/${n(Q,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:$});return await u(J,"add runs to annotation queue",!0),J})}async getRunFromAnnotationQueue(Q,Z){let $=`/annotation-queues/${n(Q,"queueId")}/run`;return(await this.caller.call(async()=>{let Y=await this._fetch(`${this.apiUrl}${$}/${Z}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(Y,"get run from annotation queue"),Y})).json()}async deleteRunFromAnnotationQueue(Q,Z){await this.caller.call(async()=>{let $=await this._fetch(`${this.apiUrl}/annotation-queues/${n(Q,"queueId")}/runs/${n(Z,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u($,"delete run from annotation queue",!0),$})}async getSizeFromAnnotationQueue(Q){return(await this.caller.call(async()=>{let $=await this._fetch(`${this.apiUrl}/annotation-queues/${n(Q,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u($,"get size from annotation queue"),$})).json()}async _currentTenantIsOwner(Q){let Z=await this._getSettings();return Q=="-"||Z.tenant_handle===Q}async _ownerConflictError(Q,Z){let $=await this._getSettings();return Error(`Cannot ${Q} for another tenant.
41
+
42
+ Current tenant: ${$.tenant_handle}
43
+
44
+ Requested tenant: ${Z}`)}async _getLatestCommitHash(Q){let $=await(await this.caller.call(async()=>{let J=await this._fetch(`${this.apiUrl}/commits/${Q}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(J,"get latest commit hash"),J})).json();if($.commits.length===0)return;return $.commits[0].commit_hash}async _likeOrUnlikePrompt(Q,Z){let[$,J,Y]=t8(Q),W=JSON.stringify({like:Z});return(await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/likes/${$}/${J}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:W});return await u(q,`${Z?"like":"unlike"} prompt`),q})).json()}async _getPromptUrl(Q){let[Z,$,J]=t8(Q);if(!await this._currentTenantIsOwner(Z))if(J!=="latest")return`${this.getHostUrl()}/hub/${Z}/${$}/${J.substring(0,8)}`;else return`${this.getHostUrl()}/hub/${Z}/${$}`;else{let Y=await this._getSettings();if(J!=="latest")return`${this.getHostUrl()}/prompts/${$}/${J.substring(0,8)}?organizationId=${Y.id}`;else return`${this.getHostUrl()}/prompts/${$}?organizationId=${Y.id}`}}async promptExists(Q){return!!await this.getPrompt(Q)}async likePrompt(Q){return this._likeOrUnlikePrompt(Q,!0)}async unlikePrompt(Q){return this._likeOrUnlikePrompt(Q,!1)}async*listCommits(Q){for await(let Z of this._getPaginated(`/commits/${Q}/`,new URLSearchParams,($)=>$.commits))yield*Z}async*listPrompts(Q){let Z=new URLSearchParams;if(Z.append("sort_field",Q?.sortField??"updated_at"),Z.append("sort_direction","desc"),Z.append("is_archived",(!!Q?.isArchived).toString()),Q?.isPublic!==void 0)Z.append("is_public",Q.isPublic.toString());if(Q?.query)Z.append("query",Q.query);for await(let $ of this._getPaginated("/repos",Z,(J)=>J.repos))yield*$}async getPrompt(Q){let[Z,$,J]=t8(Q),W=await(await this.caller.call(async()=>{let X=await this._fetch(`${this.apiUrl}/repos/${Z}/${$}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(X?.status===404)return null;return await u(X,"get prompt"),X}))?.json();if(W?.repo)return W.repo;else return null}async createPrompt(Q,Z){let $=await this._getSettings();if(Z?.isPublic&&!$.tenant_handle)throw Error(`Cannot create a public prompt without first
45
+
46
+ creating a LangChain Hub handle.
47
+ You can add a handle by creating a public prompt at:
48
+
49
+ https://smith.langchain.com/prompts`);let[J,Y,W]=t8(Q);if(!await this._currentTenantIsOwner(J))throw await this._ownerConflictError("create a prompt",J);let X={repo_handle:Y,...Z?.description&&{description:Z.description},...Z?.readme&&{readme:Z.readme},...Z?.tags&&{tags:Z.tags},is_public:!!Z?.isPublic},q=JSON.stringify(X),G=await this.caller.call(async()=>{let K=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:q});return await u(K,"create prompt"),K}),{repo:z}=await G.json();return z}async createCommit(Q,Z,$){if(!await this.promptExists(Q))throw Error("Prompt does not exist, you must create it first.");let[J,Y,W]=t8(Q),X=$?.parentCommitHash==="latest"||!$?.parentCommitHash?await this._getLatestCommitHash(`${J}/${Y}`):$?.parentCommitHash,q={manifest:JSON.parse(JSON.stringify(Z)),parent_commit:X},G=JSON.stringify(q),K=await(await this.caller.call(async()=>{let U=await this._fetch(`${this.apiUrl}/commits/${J}/${Y}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:G});return await u(U,"create commit"),U})).json();return this._getPromptUrl(`${J}/${Y}${K.commit_hash?`:${K.commit_hash}`:""}`)}async updateExamplesMultipart(Q,Z=[]){return this._updateExamplesMultipart(Q,Z)}async _updateExamplesMultipart(Q,Z=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let $=new FormData;for(let W of Z){let X=W.id,q={...W.metadata&&{metadata:W.metadata},...W.split&&{split:W.split}},G=_Q(q,`Serializing body for example with id: ${X}`),z=new Blob([G],{type:"application/json"});if($.append(X,z),W.inputs){let K=_Q(W.inputs,`Serializing inputs for example with id: ${X}`),U=new Blob([K],{type:"application/json"});$.append(`${X}.inputs`,U)}if(W.outputs){let K=_Q(W.outputs,`Serializing outputs whle updating example with id: ${X}`),U=new Blob([K],{type:"application/json"});$.append(`${X}.outputs`,U)}if(W.attachments)for(let[K,U]of Object.entries(W.attachments)){let H,B;if(Array.isArray(U))[H,B]=U;else H=U.mimeType,B=U.data;let F=new Blob([B],{type:`${H}; length=${B.byteLength}`});$.append(`${X}.attachment.${K}`,F)}if(W.attachments_operations){let K=_Q(W.attachments_operations,`Serializing attachments while updating example with id: ${X}`),U=new Blob([K],{type:"application/json"});$.append(`${X}.attachments_operations`,U)}}let J=Q??Z[0]?.dataset_id;return(await this.caller.call(async()=>{let W=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${J}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:$});return await u(W,"update examples"),W})).json()}async uploadExamplesMultipart(Q,Z=[]){return this._uploadExamplesMultipart(Q,Z)}async _uploadExamplesMultipart(Q,Z=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let $=new FormData;for(let Y of Z){let W=(Y.id??Y8()).toString(),X={created_at:Y.created_at,...Y.metadata&&{metadata:Y.metadata},...Y.split&&{split:Y.split},...Y.source_run_id&&{source_run_id:Y.source_run_id},...Y.use_source_run_io&&{use_source_run_io:Y.use_source_run_io},...Y.use_source_run_attachments&&{use_source_run_attachments:Y.use_source_run_attachments}},q=_Q(X,`Serializing body for uploaded example with id: ${W}`),G=new Blob([q],{type:"application/json"});if($.append(W,G),Y.inputs){let z=_Q(Y.inputs,`Serializing inputs for uploaded example with id: ${W}`),K=new Blob([z],{type:"application/json"});$.append(`${W}.inputs`,K)}if(Y.outputs){let z=_Q(Y.outputs,`Serializing outputs for uploaded example with id: ${W}`),K=new Blob([z],{type:"application/json"});$.append(`${W}.outputs`,K)}if(Y.attachments)for(let[z,K]of Object.entries(Y.attachments)){let U,H;if(Array.isArray(K))[U,H]=K;else U=K.mimeType,H=K.data;let B=new Blob([H],{type:`${U}; length=${H.byteLength}`});$.append(`${W}.attachment.${z}`,B)}}return(await this.caller.call(async()=>{let Y=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${Q}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:$});return await u(Y,"upload examples"),Y})).json()}async updatePrompt(Q,Z){if(!await this.promptExists(Q))throw Error("Prompt does not exist, you must create it first.");let[$,J]=t8(Q);if(!await this._currentTenantIsOwner($))throw await this._ownerConflictError("update a prompt",$);let Y={};if(Z?.description!==void 0)Y.description=Z.description;if(Z?.readme!==void 0)Y.readme=Z.readme;if(Z?.tags!==void 0)Y.tags=Z.tags;if(Z?.isPublic!==void 0)Y.is_public=Z.isPublic;if(Z?.isArchived!==void 0)Y.is_archived=Z.isArchived;if(Object.keys(Y).length===0)throw Error("No valid update options provided");let W=JSON.stringify(Y);return(await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/repos/${$}/${J}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:W});return await u(q,"update prompt"),q})).json()}async deletePrompt(Q){if(!await this.promptExists(Q))throw Error("Prompt does not exist, you must create it first.");let[Z,$,J]=t8(Q);if(!await this._currentTenantIsOwner(Z))throw await this._ownerConflictError("delete a prompt",Z);return(await this.caller.call(async()=>{let W=await this._fetch(`${this.apiUrl}/repos/${Z}/${$}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(W,"delete prompt"),W})).json()}_getPromptCacheKey(Q,Z){return`${Q}${Z?":with_model":""}`}async _fetchPromptFromApi(Q,Z){let[$,J,Y]=t8(Q),X=await(await this.caller.call(async()=>{let q=await this._fetch(`${this.apiUrl}/commits/${$}/${J}/${Y}${Z?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await u(q,"pull prompt commit"),q})).json();return{owner:$,repo:J,commit_hash:X.commit_hash,manifest:X.manifest,examples:X.examples}}async pullPromptCommit(Q,Z){let $=this._fetchPromptFromApi.bind(this,Q,Z);if(!Z?.skipCache&&this._promptCache){let J=this._getPromptCacheKey(Q,Z?.includeModel),Y=this._promptCache.get(J,$);if(Y)return Y;let W=await $();return this._promptCache.set(J,W,$),W}return this._fetchPromptFromApi(Q,Z)}async _pullPrompt(Q,Z){let $=await this.pullPromptCommit(Q,{includeModel:Z?.includeModel,skipCache:Z?.skipCache});return JSON.stringify($.manifest)}async pushPrompt(Q,Z){if(await this.promptExists(Q)){if(Z&&Object.keys(Z).some((J)=>J!=="object"))await this.updatePrompt(Q,{description:Z?.description,readme:Z?.readme,tags:Z?.tags,isPublic:Z?.isPublic})}else await this.createPrompt(Q,{description:Z?.description,readme:Z?.readme,tags:Z?.tags,isPublic:Z?.isPublic});if(!Z?.object)return await this._getPromptUrl(Q);return await this.createCommit(Q,Z?.object,{parentCommitHash:Z?.parentCommitHash})}async clonePublicDataset(Q,Z={}){let{sourceApiUrl:$=this.apiUrl,datasetName:J}=Z,[Y,W]=this.parseTokenOrUrl(Q,$),X=new I8({apiUrl:Y,apiKey:"placeholder"}),q=await X.readSharedDataset(W),G=J||q.name;try{if(await this.hasDataset({datasetId:G})){console.log(`Dataset ${G} already exists in your tenant. Skipping.`);return}}catch(U){}let z=await X.listSharedExamples(W),K=await this.createDataset(G,{description:q.description,dataType:q.data_type||"kv",inputsSchema:q.inputs_schema_definition??void 0,outputsSchema:q.outputs_schema_definition??void 0});try{await this.createExamples({inputs:z.map((U)=>U.inputs),outputs:z.flatMap((U)=>U.outputs?[U.outputs]:[]),datasetId:K.id})}catch(U){throw console.error(`An error occurred while creating dataset ${G}. You should delete it manually.`),U}}parseTokenOrUrl(Q,Z,$=2,J="dataset"){try{return n(Q),[Z,Q]}catch(Y){}try{let W=new URL(Q).pathname.split("/").filter((X)=>X!=="");if(W.length>=$){let X=W[W.length-$];return[Z,X]}else throw Error(`Invalid public ${J} URL: ${Q}`)}catch(Y){throw Error(`Invalid public ${J} URL or token: ${Q}`)}}cleanup(){if(this._promptCache)this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();if(await new Promise((Q)=>setTimeout(Q,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:Q})=>Q),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0)await K7()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function E7(Q){return"dataset_id"in Q||"dataset_name"in Q}var _7=(Q)=>{if(Q!==void 0)return Q;return!!["TRACING_V2","TRACING"].find(($)=>m0($)==="true")};var S8=Symbol.for("lc:context_variables");var $9=Symbol.for("langsmith:replica_trace_roots");function lY(Q,Z){if(S8 in Q)return Q[S8][Z];return}function I7(Q,Z,$){let J=S8 in Q?Q[S8]:{};J[Z]=$,Q[S8]=J}$8();var EZ=36,CH="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function T7(Q){let $=Object.keys(Q).sort().map((J)=>`${J}:${Q[J]??""}`).join("|");return $1($,CH)}function bH(Q){return Q.replace(/[-:.]/g,"")}function x7(Q,Z=1){let $=Z.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(Q).toISOString().slice(0,-1)}${$}Z`}function iY(Q,Z,$=1){let J=x7(Q,$);return{dottedOrder:bH(J)+Z,microsecondPrecisionDatestring:J}}var kH=new Set(["projectName","updates","reroot"]);function fH(Q){let Z={};for(let $ of Object.keys(Q))if(kH.has($))Z[$]=Q[$];return Z}class J9{constructor(Q,Z,$,J){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=Q,this.tags=Z,this.project_name=$,this.replicas=J}static fromHeader(Q){let Z=Q.split(","),$={},J=[],Y,W;for(let X of Z){let[q,G]=X.split("="),z=decodeURIComponent(G);if(q==="langsmith-metadata")$=JSON.parse(z);else if(q==="langsmith-tags")J=z.split(",");else if(q==="langsmith-project")Y=z;else if(q==="langsmith-replicas")W=JSON.parse(z).map((U)=>{if(Array.isArray(U))return U;return fH(U)})}return new J9($,J,Y,W)}toHeader(){let Q=[];if(this.metadata&&Object.keys(this.metadata).length>0)Q.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`);if(this.tags&&this.tags.length>0)Q.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`);if(this.project_name)Q.push(`langsmith-project=${encodeURIComponent(this.project_name)}`);return Q.join(",")}}class r0{constructor(Q){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),M7(Q)){Object.assign(this,{...Q});return}let Z=r0.getDefaultConfig(),{metadata:$,...J}=Q,Y=J.client??r0.getSharedClient(),W={...$,...J?.extra?.metadata};if(J.extra={...J.extra,metadata:W},"id"in J&&J.id==null)delete J.id;if(Object.assign(this,{...Z,...J,client:Y}),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order)this._serialized_start_time=x7(this.start_time,this.execution_order);if(!this.id)this.id=c$(this._serialized_start_time??this.start_time);if(!this.trace_id)if(this.parent_run)this.trace_id=this.parent_run.trace_id??this.id;else this.trace_id=this.id;if(this.replicas=dH(this.replicas),!this.dotted_order){let{dottedOrder:X}=iY(this.start_time,this.id,this.execution_order);if(this.parent_run)this.dotted_order=this.parent_run.dotted_order+"."+X;else this.dotted_order=X}}set metadata(Q){this.extra={...this.extra,metadata:{...this.extra?.metadata,...Q}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let Q=Date.now();return{run_type:"chain",project_name:NZ(),child_runs:[],api_url:dQ("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:dQ("LANGCHAIN_API_KEY"),caller_options:{},start_time:Q,serialized:{},inputs:{},extra:{}}}static getSharedClient(){if(!r0.sharedClient)r0.sharedClient=new I8;return r0.sharedClient}createChild(Q){let Z=this.child_execution_order+1,$=this.replicas?.map((z)=>{let{reroot:K,...U}=z;return U}),J=Q.replicas??$,Y=new r0({...Q,parent_run:this,project_name:this.project_name,replicas:J,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:Z,child_execution_order:Z});if(S8 in this)Y[S8]=this[S8];let W=Symbol.for("lc:child_config"),X=Q.extra?.[W]??this.extra[W];if(gH(X)){let z={...X},K=hH(z.callbacks)?z.callbacks.copy?.():void 0;if(K)Object.assign(K,{_parentRunId:Y.id}),K.handlers?.find(v7)?.updateFromRunTree?.(Y),z.callbacks=K;Y.extra[W]=z}let q=new Set,G=this;while(G!=null&&!q.has(G.id))q.add(G.id),G.child_execution_order=Math.max(G.child_execution_order,Z),G=G.parent_run;return this.child_runs.push(Y),Y}async end(Q,Z,$=Date.now(),J){if(this.outputs=this.outputs??Q,this.error=this.error??Z,this.end_time=this.end_time??$,J&&Object.keys(J).length>0)this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...J}}:{metadata:J}}_convertToCreate(Q,Z,$=!0){let J=Q.extra??{};if(J?.runtime?.library===void 0){if(!J.runtime)J.runtime={};if(Z){for(let[X,q]of Object.entries(Z))if(!J.runtime[X])J.runtime[X]=q}}let Y,W;if(!$)Y=Q.child_runs.map((X)=>this._convertToCreate(X,Z,$)),W=void 0;else W=Q.parent_run?.id??Q.parent_run_id,Y=[];return{id:Q.id,name:Q.name,start_time:Q._serialized_start_time??Q.start_time,end_time:Q.end_time,run_type:Q.run_type,reference_example_id:Q.reference_example_id,extra:J,serialized:Q.serialized,error:Q.error,inputs:Q.inputs,outputs:Q.outputs,session_name:Q.project_name,child_runs:Y,parent_run_id:W,trace_id:Q.trace_id,dotted_order:Q.dotted_order,tags:Q.tags,attachments:Q.attachments,events:Q.events}}_sliceParentId(Q,Z){if(Z.dotted_order){let $=Z.dotted_order.split("."),J=null;for(let Y=0;Y<$.length;Y++)if($[Y].slice(-EZ)===Q){J=Y;break}if(J!==null){let Y=$.slice(J+1);if(Z.dotted_order=Y.join("."),Y.length>0)Z.trace_id=Y[0].slice(-EZ);else Z.trace_id=Z.id}}if(Z.parent_run_id===Q)Z.parent_run_id=void 0}_setReplicaTraceRoot(Q,Z){let $=lY(this,$9)??{};$[Q]=Z,I7(this,$9,$);for(let J of this.child_runs)J._setReplicaTraceRoot(Q,Z)}_remapForProject(Q){let{projectName:Z,runtimeEnv:$,excludeChildRuns:J=!0,reroot:Y=!1,distributedParentId:W,apiUrl:X,apiKey:q,workspaceId:G}=Q,z=this._convertToCreate(this,$,J);if(Z===this.project_name)return{...z,session_name:Z};if(Y){if(W)this._sliceParentId(W,z);else if(z.parent_run_id=void 0,z.dotted_order){let E=z.dotted_order.split(".");if(E.length>0)z.dotted_order=E[E.length-1],z.trace_id=z.id}let A=T7({projectName:Z,apiUrl:X,apiKey:q,workspaceId:G});this._setReplicaTraceRoot(A,z.id)}let K;if(!Y){let A=lY(this,$9)??{},E=T7({projectName:Z,apiUrl:X,apiKey:q,workspaceId:G});if(K=A[E],K){if(z.trace_id=K,z.dotted_order){let P=z.dotted_order.split("."),j=null;for(let R=0;R<P.length;R++)if(P[R].slice(-EZ)===K){j=R;break}if(j!==null){let R=P.slice(j);z.dotted_order=R.join(".")}}}}let U=z.id,H=OZ(U,Z),B;if(z.trace_id)B=OZ(z.trace_id,Z);else B=H;let F;if(z.parent_run_id)F=OZ(z.parent_run_id,Z);let w;if(z.dotted_order)w=z.dotted_order.split(".").map((P)=>{let j=P.slice(-EZ),R=OZ(j,Z);return P.slice(0,-EZ)+R}).join(".");return{...z,id:H,trace_id:B,parent_run_id:F,dotted_order:w,session_name:Z}}async postRun(Q=!0){if(this._awaitInputsOnPost)this.inputs=await this.inputs;try{let Z=o$();if(this.replicas&&this.replicas.length>0)for(let{projectName:$,apiKey:J,apiUrl:Y,workspaceId:W,reroot:X}of this.replicas){let q=this._remapForProject({projectName:$??this.project_name,runtimeEnv:Z,excludeChildRuns:!0,reroot:X,distributedParentId:this.distributedParentId,apiUrl:Y,apiKey:J,workspaceId:W});await this.client.createRun(q,{apiKey:J,apiUrl:Y,workspaceId:W})}else{let $=this._convertToCreate(this,Z,Q);await this.client.createRun($)}if(!Q){Q1("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let $ of this.child_runs)await $.postRun(!1)}this.child_runs=[]}catch(Z){console.error(`Error in postRun for run ${this.id}:`,Z)}}async patchRun(Q){if(this.replicas&&this.replicas.length>0)for(let{projectName:Z,apiKey:$,apiUrl:J,workspaceId:Y,updates:W,reroot:X}of this.replicas){let q=this._remapForProject({projectName:Z??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:X,distributedParentId:this.distributedParentId,apiUrl:J,apiKey:$,workspaceId:Y}),G={id:q.id,name:q.name,run_type:q.run_type,start_time:q.start_time,outputs:q.outputs,error:q.error,parent_run_id:q.parent_run_id,session_name:q.session_name,reference_example_id:q.reference_example_id,end_time:q.end_time,dotted_order:q.dotted_order,trace_id:q.trace_id,events:q.events,tags:q.tags,extra:q.extra,attachments:this.attachments,...W};if(!Q?.excludeInputs)G.inputs=q.inputs;await this.client.updateRun(q.id,G,{apiKey:$,apiUrl:J,workspaceId:Y})}else try{let Z={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};if(!Q?.excludeInputs)Z.inputs=this.inputs;await this.client.updateRun(this.id,Z)}catch(Z){console.error(`Error in patchRun for run ${this.id}`,Z)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(Q){if(!this.events)this.events=[];if(typeof Q==="string")this.events.push({name:"event",time:new Date().toISOString(),message:Q});else this.events.push({...Q,time:Q.time??new Date().toISOString()})}static fromRunnableConfig(Q,Z){let $=Q?.callbacks,J,Y,W,X=_7();if($){let G=$?.getParentRunId?.()??"",z=$?.handlers?.find((K)=>K?.name=="langchain_tracer");J=z?.getRun?.(G),Y=z?.projectName,W=z?.client,X=X||!!z}if(!J)return new r0({...Z,client:W,tracingEnabled:X,project_name:Y});return new r0({name:J.name,id:J.id,trace_id:J.trace_id,dotted_order:J.dotted_order,client:W,tracingEnabled:X,project_name:Y,tags:[...new Set((J?.tags??[]).concat(Q?.tags??[]))],extra:{metadata:{...J?.extra?.metadata,...Q?.metadata}}}).createChild(Z)}static fromDottedOrder(Q){return this.fromHeaders({"langsmith-trace":Q})}static fromHeaders(Q,Z){let $="get"in Q&&typeof Q.get==="function"?{"langsmith-trace":Q.get("langsmith-trace"),baggage:Q.get("baggage")}:Q,J=$["langsmith-trace"];if(!J||typeof J!=="string")return;let Y=J.trim(),W=Y.split(".").map((z)=>{let[K,U]=z.split("Z");return{strTime:K,time:Date.parse(K+"Z"),uuid:U}}),X=W[0].uuid,q={...Z,name:Z?.name??"parent",run_type:Z?.run_type??"chain",start_time:Z?.start_time??Date.now(),id:W.at(-1)?.uuid,trace_id:X,dotted_order:Y};if($.baggage&&typeof $.baggage==="string"){let z=J9.fromHeader($.baggage);q.metadata=z.metadata,q.tags=z.tags,q.project_name=z.project_name,q.replicas=z.replicas}let G=new r0(q);return G.distributedParentId=G.id,G}toHeaders(Q){let Z={"langsmith-trace":this.dotted_order,baggage:new J9(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(Q)for(let[$,J]of Object.entries(Z))Q.set($,J);return Z}}Object.defineProperty(r0,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function M7(Q){return Q!=null&&typeof Q.createChild==="function"&&typeof Q.postRun==="function"}function v7(Q){return typeof Q==="object"&&Q!=null&&typeof Q.name==="string"&&Q.name==="langchain_tracer"}function S7(Q){return Array.isArray(Q)&&Q.some((Z)=>v7(Z))}function hH(Q){return typeof Q==="object"&&Q!=null&&Array.isArray(Q.handlers)}function gH(Q){let Z=Q?.callbacks;return Q!=null&&typeof Z==="object"&&(S7(Z?.handlers)||S7(Z))}function mH(){let Q=dQ("LANGSMITH_RUNS_ENDPOINTS");if(!Q)return[];try{let Z=JSON.parse(Q);if(Array.isArray(Z)){let $=[];for(let J of Z){if(typeof J!=="object"||J===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof J}`);continue}if(typeof J.api_url!=="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof J.api_url}`);continue}if(typeof J.api_key!=="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof J.api_key}`);continue}$.push({apiUrl:J.api_url.replace(/\/$/,""),apiKey:J.api_key})}return $}else if(typeof Z==="object"&&Z!==null){uH(Z);let $=[];for(let[J,Y]of Object.entries(Z)){let W=J.replace(/\/$/,"");if(typeof Y==="string")$.push({apiUrl:W,apiKey:Y});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${J}: expected string, got ${typeof Y}`);continue}}return $}else return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of "+`objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof Z}`),[]}catch(Z){if(L7(Z))throw Z;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of "+"objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function dH(Q){if(Q)return Q.map((Z)=>{if(Array.isArray(Z))return{projectName:Z[0],updates:Z[1]};return Z});return mH()}function uH(Q){if(Object.keys(Q).length>0&&m0("ENDPOINT"))throw new uY}var y7=_({BaseTracer:()=>WQ,isBaseTracer:()=>J1}),pH=(Q)=>{if(!Q)return;return Q.events=Q.events??[],Q.child_runs=Q.child_runs??[],Q};function nY(Q,Z){if(!Q)return;return new r0({...Q,start_time:Q._serialized_start_time??Q.start_time,parent_run:nY(Z),child_runs:Q.child_runs.map(($)=>nY($)).filter(($)=>$!==void 0),extra:{...Q.extra,runtime:FY()},tracingEnabled:!1})}function oY(Q,Z){return Q&&!Array.isArray(Q)&&typeof Q==="object"?Q:{[Z]:Q}}function J1(Q){return typeof Q._addRunToRunMap==="function"}var WQ=class extends J8{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(Q){super(...arguments)}copy(){return this}getRunById(Q){if(Q===void 0)return;return this.usesRunTreeMap?pH(this.runTreeMap.get(Q)):this.runMap.get(Q)}stringifyError(Q){if(Q instanceof Error)return Q.message+(Q?.stack?`
50
+
51
+ ${Q.stack}`:"");if(typeof Q==="string")return Q;return`${Q}`}_addChildRun(Q,Z){Q.child_runs.push(Z)}_addRunToRunMap(Q){let{dottedOrder:Z,microsecondPrecisionDatestring:$}=iY(new Date(Q.start_time).getTime(),Q.id,Q.execution_order),J={...Q},Y=this.getRunById(J.parent_run_id);if(J.parent_run_id!==void 0)if(Y){if(this._addChildRun(Y,J),Y.child_execution_order=Math.max(Y.child_execution_order,J.child_execution_order),J.trace_id=Y.trace_id,Y.dotted_order!==void 0)J.dotted_order=[Y.dotted_order,Z].join("."),J._serialized_start_time=$}else J.parent_run_id=void 0;else J.trace_id=J.id,J.dotted_order=Z,J._serialized_start_time=$;if(this.usesRunTreeMap){let W=nY(J,Y);if(W!==void 0)this.runTreeMap.set(J.id,W)}else this.runMap.set(J.id,J);return J}async _endTrace(Q){let Z=Q.parent_run_id!==void 0&&this.getRunById(Q.parent_run_id);if(Z)Z.child_execution_order=Math.max(Z.child_execution_order,Q.child_execution_order);else await this.persistRun(Q);if(await this.onRunUpdate?.(Q),this.usesRunTreeMap)this.runTreeMap.delete(Q.id);else this.runMap.delete(Q.id)}_getExecutionOrder(Q){let Z=Q!==void 0&&this.getRunById(Q);if(!Z)return 1;return Z.child_execution_order+1}_createRunForLLMStart(Q,Z,$,J,Y,W,X,q){let G=this._getExecutionOrder(J),z=Date.now(),K=X?{...Y,metadata:X}:Y,U={id:$,name:q??Q.id[Q.id.length-1],parent_run_id:J,start_time:z,serialized:Q,events:[{name:"start",time:new Date(z).toISOString()}],inputs:{prompts:Z},execution_order:G,child_runs:[],child_execution_order:G,run_type:"llm",extra:K??{},tags:W||[]};return this._addRunToRunMap(U)}async handleLLMStart(Q,Z,$,J,Y,W,X,q){let G=this.getRunById($)??this._createRunForLLMStart(Q,Z,$,J,Y,W,X,q);return await this.onRunCreate?.(G),await this.onLLMStart?.(G),G}_createRunForChatModelStart(Q,Z,$,J,Y,W,X,q){let G=this._getExecutionOrder(J),z=Date.now(),K=X?{...Y,metadata:X}:Y,U={id:$,name:q??Q.id[Q.id.length-1],parent_run_id:J,start_time:z,serialized:Q,events:[{name:"start",time:new Date(z).toISOString()}],inputs:{messages:Z},execution_order:G,child_runs:[],child_execution_order:G,run_type:"llm",extra:K??{},tags:W||[]};return this._addRunToRunMap(U)}async handleChatModelStart(Q,Z,$,J,Y,W,X,q){let G=this.getRunById($)??this._createRunForChatModelStart(Q,Z,$,J,Y,W,X,q);return await this.onRunCreate?.(G),await this.onLLMStart?.(G),G}async handleLLMEnd(Q,Z,$,J,Y){let W=this.getRunById(Z);if(!W||W?.run_type!=="llm")throw Error("No LLM run to end.");return W.end_time=Date.now(),W.outputs=Q,W.events.push({name:"end",time:new Date(W.end_time).toISOString()}),W.extra={...W.extra,...Y},await this.onLLMEnd?.(W),await this._endTrace(W),W}async handleLLMError(Q,Z,$,J,Y){let W=this.getRunById(Z);if(!W||W?.run_type!=="llm")throw Error("No LLM run to end.");return W.end_time=Date.now(),W.error=this.stringifyError(Q),W.events.push({name:"error",time:new Date(W.end_time).toISOString()}),W.extra={...W.extra,...Y},await this.onLLMError?.(W),await this._endTrace(W),W}_createRunForChainStart(Q,Z,$,J,Y,W,X,q,G){let z=this._getExecutionOrder(J),K=Date.now(),U={id:$,name:q??Q.id[Q.id.length-1],parent_run_id:J,start_time:K,serialized:Q,events:[{name:"start",time:new Date(K).toISOString()}],inputs:Z,execution_order:z,child_execution_order:z,run_type:X??"chain",child_runs:[],extra:W?{...G,metadata:W}:{...G},tags:Y||[]};return this._addRunToRunMap(U)}async handleChainStart(Q,Z,$,J,Y,W,X,q){let G=this.getRunById($)??this._createRunForChainStart(Q,Z,$,J,Y,W,X,q);return await this.onRunCreate?.(G),await this.onChainStart?.(G),G}async handleChainEnd(Q,Z,$,J,Y){let W=this.getRunById(Z);if(!W)throw Error("No chain run to end.");if(W.end_time=Date.now(),W.outputs=oY(Q,"output"),W.events.push({name:"end",time:new Date(W.end_time).toISOString()}),Y?.inputs!==void 0)W.inputs=oY(Y.inputs,"input");return await this.onChainEnd?.(W),await this._endTrace(W),W}async handleChainError(Q,Z,$,J,Y){let W=this.getRunById(Z);if(!W)throw Error("No chain run to end.");if(W.end_time=Date.now(),W.error=this.stringifyError(Q),W.events.push({name:"error",time:new Date(W.end_time).toISOString()}),Y?.inputs!==void 0)W.inputs=oY(Y.inputs,"input");return await this.onChainError?.(W),await this._endTrace(W),W}_createRunForToolStart(Q,Z,$,J,Y,W,X){let q=this._getExecutionOrder(J),G=Date.now(),z={id:$,name:X??Q.id[Q.id.length-1],parent_run_id:J,start_time:G,serialized:Q,events:[{name:"start",time:new Date(G).toISOString()}],inputs:{input:Z},execution_order:q,child_execution_order:q,run_type:"tool",child_runs:[],extra:W?{metadata:W}:{},tags:Y||[]};return this._addRunToRunMap(z)}async handleToolStart(Q,Z,$,J,Y,W,X){let q=this.getRunById($)??this._createRunForToolStart(Q,Z,$,J,Y,W,X);return await this.onRunCreate?.(q),await this.onToolStart?.(q),q}async handleToolEnd(Q,Z){let $=this.getRunById(Z);if(!$||$?.run_type!=="tool")throw Error("No tool run to end");return $.end_time=Date.now(),$.outputs={output:Q},$.events.push({name:"end",time:new Date($.end_time).toISOString()}),await this.onToolEnd?.($),await this._endTrace($),$}async handleToolError(Q,Z){let $=this.getRunById(Z);if(!$||$?.run_type!=="tool")throw Error("No tool run to end");return $.end_time=Date.now(),$.error=this.stringifyError(Q),$.events.push({name:"error",time:new Date($.end_time).toISOString()}),await this.onToolError?.($),await this._endTrace($),$}async handleAgentAction(Q,Z){let $=this.getRunById(Z);if(!$||$?.run_type!=="chain")return;let J=$;J.actions=J.actions||[],J.actions.push(Q),J.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:Q}}),await this.onAgentAction?.($)}async handleAgentEnd(Q,Z){let $=this.getRunById(Z);if(!$||$?.run_type!=="chain")return;$.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:Q}}),await this.onAgentEnd?.($)}_createRunForRetrieverStart(Q,Z,$,J,Y,W,X){let q=this._getExecutionOrder(J),G=Date.now(),z={id:$,name:X??Q.id[Q.id.length-1],parent_run_id:J,start_time:G,serialized:Q,events:[{name:"start",time:new Date(G).toISOString()}],inputs:{query:Z},execution_order:q,child_execution_order:q,run_type:"retriever",child_runs:[],extra:W?{metadata:W}:{},tags:Y||[]};return this._addRunToRunMap(z)}async handleRetrieverStart(Q,Z,$,J,Y,W,X){let q=this.getRunById($)??this._createRunForRetrieverStart(Q,Z,$,J,Y,W,X);return await this.onRunCreate?.(q),await this.onRetrieverStart?.(q),q}async handleRetrieverEnd(Q,Z){let $=this.getRunById(Z);if(!$||$?.run_type!=="retriever")throw Error("No retriever run to end");return $.end_time=Date.now(),$.outputs={documents:Q},$.events.push({name:"end",time:new Date($.end_time).toISOString()}),await this.onRetrieverEnd?.($),await this._endTrace($),$}async handleRetrieverError(Q,Z){let $=this.getRunById(Z);if(!$||$?.run_type!=="retriever")throw Error("No retriever run to end");return $.end_time=Date.now(),$.error=this.stringifyError(Q),$.events.push({name:"error",time:new Date($.end_time).toISOString()}),await this.onRetrieverError?.($),await this._endTrace($),$}async handleText(Q,Z){let $=this.getRunById(Z);if(!$||$?.run_type!=="chain")return;$.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:Q}}),await this.onText?.($)}async handleLLMNewToken(Q,Z,$,J,Y,W){let X=this.getRunById($);if(!X||X?.run_type!=="llm")throw Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return X.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:Q,idx:Z,chunk:W?.chunk}}),await this.onLLMNewToken?.(X,Q,{chunk:W?.chunk}),X}};var rY=i6(cH(),1),b7=_({ConsoleCallbackHandler:()=>Y9});function AQ(Q,Z){return`${Q.open}${Z}${Q.close}`}function cQ(Q,Z){try{return JSON.stringify(Q,null,2)}catch{return Z}}function C7(Q){if(typeof Q==="string")return Q.trim();if(Q===null||Q===void 0)return Q;return cQ(Q,Q.toString())}function N6(Q){if(!Q.end_time)return"";let Z=Q.end_time-Q.start_time;if(Z<1000)return`${Z}ms`;return`${(Z/1000).toFixed(2)}s`}var{color:IQ}=rY.default,Y9=class extends WQ{name="console_callback_handler";persistRun(Q){return Promise.resolve()}getParents(Q){let Z=[],$=Q;while($.parent_run_id){let J=this.runMap.get($.parent_run_id);if(J)Z.push(J),$=J;else break}return Z}getBreadcrumbs(Q){let Z=[...this.getParents(Q).reverse(),Q].map(($,J,Y)=>{let W=`${$.execution_order}:${$.run_type}:${$.name}`;return J===Y.length-1?AQ(rY.default.bold,W):W}).join(" > ");return AQ(IQ.grey,Z)}onChainStart(Q){let Z=this.getBreadcrumbs(Q);console.log(`${AQ(IQ.green,"[chain/start]")} [${Z}] Entering Chain run with input: ${cQ(Q.inputs,"[inputs]")}`)}onChainEnd(Q){let Z=this.getBreadcrumbs(Q);console.log(`${AQ(IQ.cyan,"[chain/end]")} [${Z}] [${N6(Q)}] Exiting Chain run with output: ${cQ(Q.outputs,"[outputs]")}`)}onChainError(Q){let Z=this.getBreadcrumbs(Q);console.log(`${AQ(IQ.red,"[chain/error]")} [${Z}] [${N6(Q)}] Chain run errored with error: ${cQ(Q.error,"[error]")}`)}onLLMStart(Q){let Z=this.getBreadcrumbs(Q),$="prompts"in Q.inputs?{prompts:Q.inputs.prompts.map((J)=>J.trim())}:Q.inputs;console.log(`${AQ(IQ.green,"[llm/start]")} [${Z}] Entering LLM run with input: ${cQ($,"[inputs]")}`)}onLLMEnd(Q){let Z=this.getBreadcrumbs(Q);console.log(`${AQ(IQ.cyan,"[llm/end]")} [${Z}] [${N6(Q)}] Exiting LLM run with output: ${cQ(Q.outputs,"[response]")}`)}onLLMError(Q){let Z=this.getBreadcrumbs(Q);console.log(`${AQ(IQ.red,"[llm/error]")} [${Z}] [${N6(Q)}] LLM run errored with error: ${cQ(Q.error,"[error]")}`)}onToolStart(Q){let Z=this.getBreadcrumbs(Q);console.log(`${AQ(IQ.green,"[tool/start]")} [${Z}] Entering Tool run with input: "${C7(Q.inputs.input)}"`)}onToolEnd(Q){let Z=this.getBreadcrumbs(Q);console.log(`${AQ(IQ.cyan,"[tool/end]")} [${Z}] [${N6(Q)}] Exiting Tool run with output: "${C7(Q.outputs?.output)}"`)}onToolError(Q){let Z=this.getBreadcrumbs(Q);console.log(`${AQ(IQ.red,"[tool/error]")} [${Z}] [${N6(Q)}] Tool run errored with error: ${cQ(Q.error,"[error]")}`)}onRetrieverStart(Q){let Z=this.getBreadcrumbs(Q);console.log(`${AQ(IQ.green,"[retriever/start]")} [${Z}] Entering Retriever run with input: ${cQ(Q.inputs,"[inputs]")}`)}onRetrieverEnd(Q){let Z=this.getBreadcrumbs(Q);console.log(`${AQ(IQ.cyan,"[retriever/end]")} [${Z}] [${N6(Q)}] Exiting Retriever run with output: ${cQ(Q.outputs,"[outputs]")}`)}onRetrieverError(Q){let Z=this.getBreadcrumbs(Q);console.log(`${AQ(IQ.red,"[retriever/error]")} [${Z}] [${N6(Q)}] Retriever run errored with error: ${cQ(Q.error,"[error]")}`)}onAgentAction(Q){let Z=Q,$=this.getBreadcrumbs(Q);console.log(`${AQ(IQ.blue,"[agent/action]")} [${$}] Agent selected action: ${cQ(Z.actions[Z.actions.length-1],"[action]")}`)}};var sY,W9=()=>{if(sY===void 0)sY=new I8(wQ("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{});return sY};class k7{getStore(){return}run(Q,Z){return Z()}}var tY=Symbol.for("ls:tracing_async_local_storage"),lH=new k7;class f7{getInstance(){return globalThis[tY]??lH}initializeGlobalInstance(Q){if(globalThis[tY]===void 0)globalThis[tY]=Q}}var iH=new f7;function h7(Q=!1){let Z=iH.getInstance().getStore();if(!Q&&Z===void 0)throw Error(`Could not get the current run tree.
52
+
53
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return Z}function X9(Q){return typeof Q==="function"&&"langsmith:traceable"in Q}var g7=_({LangChainTracer:()=>q9});function oH(Q){let Z=void 0;for(let $ of Q)for(let J of $)if(h.isInstance(J.message)&&J.message.usage_metadata!==void 0)Z=_1(Z,J.message.usage_metadata);return Z}var q9=class Q extends WQ{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(Z={}){super(Z);let{exampleId:$,projectName:J,client:Y,replicas:W}=Z;this.projectName=J??NZ(),this.replicas=W,this.exampleId=$,this.client=Y??W9();let X=Q.getTraceableRunTree();if(X)this.updateFromRunTree(X)}async persistRun(Z){}async onRunCreate(Z){if(!Z.extra?.lc_defers_inputs)await this.getRunTreeWithTracingConfig(Z.id)?.postRun()}async onRunUpdate(Z){let $=this.getRunTreeWithTracingConfig(Z.id);if(Z.extra?.lc_defers_inputs)await $?.postRun();else await $?.patchRun()}onLLMEnd(Z){let $=Z.outputs;if($?.generations){let J=oH($.generations);if(J!==void 0){Z.extra=Z.extra??{};let Y=Z.extra.metadata??{};Y.usage_metadata=J,Z.extra.metadata=Y}}}getRun(Z){return this.runTreeMap.get(Z)}updateFromRunTree(Z){this.runTreeMap.set(Z.id,Z);let $=Z,J=new Set;while($.parent_run){if(J.has($.id))break;if(J.add($.id),!$.parent_run)break;$=$.parent_run}J.clear();let Y=[$];while(Y.length>0){let W=Y.shift();if(!W||J.has(W.id))continue;if(J.add(W.id),this.runTreeMap.set(W.id,W),W.child_runs)Y.push(...W.child_runs)}this.client=Z.client??this.client,this.replicas=Z.replicas??this.replicas,this.projectName=Z.project_name??this.projectName,this.exampleId=Z.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(Z){let $=this.runTreeMap.get(Z);if(!$)return;return new r0({...$,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return h7(!0)}catch{return}}};var m7=Symbol.for("ls:tracing_async_local_storage"),O6=Symbol.for("lc:context_variables"),d7=(Q)=>{globalThis[m7]=Q},E6=()=>{return globalThis[m7]};var G9=i6(hY(),1),Y1;function nH(){return new("default"in G9.default?G9.default.default:G9.default)({autoStart:!0,concurrency:1})}function rH(){if(typeof Y1>"u")Y1=nH();return Y1}async function T0(Q,Z){if(Z===!0){let $=E6();if($!==void 0)await $.run(void 0,async()=>Q());else await Q()}else Y1=rH(),Y1.add(async()=>{let $=E6();if($!==void 0)await $.run(void 0,async()=>Q());else await Q()})}async function u7(){let Q=W9();await Promise.allSettled([typeof Y1<"u"?Y1.onIdle():Promise.resolve(),Q.awaitPendingTraceBatches()])}var p7=_({awaitAllCallbacks:()=>u7,consumeCallback:()=>T0});var c7=(Q)=>{if(Q!==void 0)return Q;return!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find((Z)=>wQ(Z)==="true")};function aY(Q){let Z=E6();if(Z===void 0)return;return Z.getStore()?.[O6]?.[Q]}var sH=Symbol("lc:configure_hooks"),l7=()=>aY(sH)||[];$8();var i7=_({BaseCallbackManager:()=>o7,BaseRunManager:()=>jZ,CallbackManager:()=>d0,CallbackManagerForChainRun:()=>r7,CallbackManagerForLLMRun:()=>eY,CallbackManagerForRetrieverRun:()=>n7,CallbackManagerForToolRun:()=>s7,ensureHandler:()=>v1,parseCallbackConfigArg:()=>W1});function W1(Q){if(!Q)return{};else if(Array.isArray(Q)||"name"in Q)return{callbacks:Q};else return Q}var o7=class{setHandler(Q){return this.setHandlers([Q])}},jZ=class{constructor(Q,Z,$,J,Y,W,X,q){this.runId=Q,this.handlers=Z,this.inheritableHandlers=$,this.tags=J,this.inheritableTags=Y,this.metadata=W,this.inheritableMetadata=X,this._parentRunId=q}get parentRunId(){return this._parentRunId}async handleText(Q){await Promise.all(this.handlers.map((Z)=>T0(async()=>{try{await Z.handleText?.(Q,this.runId,this._parentRunId,this.tags)}catch($){if((Z.raiseError?console.error:console.warn)(`Error in handler ${Z.constructor.name}, handleText: ${$}`),Z.raiseError)throw $}},Z.awaitHandlers)))}async handleCustomEvent(Q,Z,$,J,Y){await Promise.all(this.handlers.map((W)=>T0(async()=>{try{await W.handleCustomEvent?.(Q,Z,this.runId,this.tags,this.metadata)}catch(X){if((W.raiseError?console.error:console.warn)(`Error in handler ${W.constructor.name}, handleCustomEvent: ${X}`),W.raiseError)throw X}},W.awaitHandlers)))}},n7=class extends jZ{getChild(Q){let Z=new d0(this.runId);if(Z.setHandlers(this.inheritableHandlers),Z.addTags(this.inheritableTags),Z.addMetadata(this.inheritableMetadata),Q)Z.addTags([Q],!1);return Z}async handleRetrieverEnd(Q){await Promise.all(this.handlers.map((Z)=>T0(async()=>{if(!Z.ignoreRetriever)try{await Z.handleRetrieverEnd?.(Q,this.runId,this._parentRunId,this.tags)}catch($){if((Z.raiseError?console.error:console.warn)(`Error in handler ${Z.constructor.name}, handleRetriever`),Z.raiseError)throw $}},Z.awaitHandlers)))}async handleRetrieverError(Q){await Promise.all(this.handlers.map((Z)=>T0(async()=>{if(!Z.ignoreRetriever)try{await Z.handleRetrieverError?.(Q,this.runId,this._parentRunId,this.tags)}catch($){if((Z.raiseError?console.error:console.warn)(`Error in handler ${Z.constructor.name}, handleRetrieverError: ${$}`),Z.raiseError)throw Q}},Z.awaitHandlers)))}},eY=class extends jZ{async handleLLMNewToken(Q,Z,$,J,Y,W){await Promise.all(this.handlers.map((X)=>T0(async()=>{if(!X.ignoreLLM)try{await X.handleLLMNewToken?.(Q,Z??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,W)}catch(q){if((X.raiseError?console.error:console.warn)(`Error in handler ${X.constructor.name}, handleLLMNewToken: ${q}`),X.raiseError)throw q}},X.awaitHandlers)))}async handleLLMError(Q,Z,$,J,Y){await Promise.all(this.handlers.map((W)=>T0(async()=>{if(!W.ignoreLLM)try{await W.handleLLMError?.(Q,this.runId,this._parentRunId,this.tags,Y)}catch(X){if((W.raiseError?console.error:console.warn)(`Error in handler ${W.constructor.name}, handleLLMError: ${X}`),W.raiseError)throw X}},W.awaitHandlers)))}async handleLLMEnd(Q,Z,$,J,Y){await Promise.all(this.handlers.map((W)=>T0(async()=>{if(!W.ignoreLLM)try{await W.handleLLMEnd?.(Q,this.runId,this._parentRunId,this.tags,Y)}catch(X){if((W.raiseError?console.error:console.warn)(`Error in handler ${W.constructor.name}, handleLLMEnd: ${X}`),W.raiseError)throw X}},W.awaitHandlers)))}},r7=class extends jZ{getChild(Q){let Z=new d0(this.runId);if(Z.setHandlers(this.inheritableHandlers),Z.addTags(this.inheritableTags),Z.addMetadata(this.inheritableMetadata),Q)Z.addTags([Q],!1);return Z}async handleChainError(Q,Z,$,J,Y){await Promise.all(this.handlers.map((W)=>T0(async()=>{if(!W.ignoreChain)try{await W.handleChainError?.(Q,this.runId,this._parentRunId,this.tags,Y)}catch(X){if((W.raiseError?console.error:console.warn)(`Error in handler ${W.constructor.name}, handleChainError: ${X}`),W.raiseError)throw X}},W.awaitHandlers)))}async handleChainEnd(Q,Z,$,J,Y){await Promise.all(this.handlers.map((W)=>T0(async()=>{if(!W.ignoreChain)try{await W.handleChainEnd?.(Q,this.runId,this._parentRunId,this.tags,Y)}catch(X){if((W.raiseError?console.error:console.warn)(`Error in handler ${W.constructor.name}, handleChainEnd: ${X}`),W.raiseError)throw X}},W.awaitHandlers)))}async handleAgentAction(Q){await Promise.all(this.handlers.map((Z)=>T0(async()=>{if(!Z.ignoreAgent)try{await Z.handleAgentAction?.(Q,this.runId,this._parentRunId,this.tags)}catch($){if((Z.raiseError?console.error:console.warn)(`Error in handler ${Z.constructor.name}, handleAgentAction: ${$}`),Z.raiseError)throw $}},Z.awaitHandlers)))}async handleAgentEnd(Q){await Promise.all(this.handlers.map((Z)=>T0(async()=>{if(!Z.ignoreAgent)try{await Z.handleAgentEnd?.(Q,this.runId,this._parentRunId,this.tags)}catch($){if((Z.raiseError?console.error:console.warn)(`Error in handler ${Z.constructor.name}, handleAgentEnd: ${$}`),Z.raiseError)throw $}},Z.awaitHandlers)))}},s7=class extends jZ{getChild(Q){let Z=new d0(this.runId);if(Z.setHandlers(this.inheritableHandlers),Z.addTags(this.inheritableTags),Z.addMetadata(this.inheritableMetadata),Q)Z.addTags([Q],!1);return Z}async handleToolError(Q){await Promise.all(this.handlers.map((Z)=>T0(async()=>{if(!Z.ignoreAgent)try{await Z.handleToolError?.(Q,this.runId,this._parentRunId,this.tags)}catch($){if((Z.raiseError?console.error:console.warn)(`Error in handler ${Z.constructor.name}, handleToolError: ${$}`),Z.raiseError)throw $}},Z.awaitHandlers)))}async handleToolEvent(Q){await Promise.all(this.handlers.map((Z)=>T0(async()=>{if(!Z.ignoreAgent)try{await Z.handleToolEvent?.(Q,this.runId,this._parentRunId,this.tags)}catch($){if(Z.raiseError)throw $}},Z.awaitHandlers)))}async handleToolEnd(Q){await Promise.all(this.handlers.map((Z)=>T0(async()=>{if(!Z.ignoreAgent)try{await Z.handleToolEnd?.(Q,this.runId,this._parentRunId,this.tags)}catch($){if((Z.raiseError?console.error:console.warn)(`Error in handler ${Z.constructor.name}, handleToolEnd: ${$}`),Z.raiseError)throw $}},Z.awaitHandlers)))}},d0=class Q extends o7{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(Z,$){super();this.handlers=$?.handlers??this.handlers,this.inheritableHandlers=$?.inheritableHandlers??this.inheritableHandlers,this.tags=$?.tags??this.tags,this.inheritableTags=$?.inheritableTags??this.inheritableTags,this.metadata=$?.metadata??this.metadata,this.inheritableMetadata=$?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=Z}getParentRunId(){return this._parentRunId}async handleLLMStart(Z,$,J=void 0,Y=void 0,W=void 0,X=void 0,q=void 0,G=void 0){return Promise.all($.map(async(z,K)=>{let U=K===0&&J?J:mQ();return await Promise.all(this.handlers.map((H)=>{if(H.ignoreLLM)return;if(J1(H))H._createRunForLLMStart(Z,[z],U,this._parentRunId,W,this.tags,this.metadata,G);return T0(async()=>{try{await H.handleLLMStart?.(Z,[z],U,this._parentRunId,W,this.tags,this.metadata,G)}catch(B){if((H.raiseError?console.error:console.warn)(`Error in handler ${H.constructor.name}, handleLLMStart: ${B}`),H.raiseError)throw B}},H.awaitHandlers)})),new eY(U,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(Z,$,J=void 0,Y=void 0,W=void 0,X=void 0,q=void 0,G=void 0){return Promise.all($.map(async(z,K)=>{let U=K===0&&J?J:mQ();return await Promise.all(this.handlers.map((H)=>{if(H.ignoreLLM)return;if(J1(H))H._createRunForChatModelStart(Z,[z],U,this._parentRunId,W,this.tags,this.metadata,G);return T0(async()=>{try{if(H.handleChatModelStart)await H.handleChatModelStart?.(Z,[z],U,this._parentRunId,W,this.tags,this.metadata,G);else if(H.handleLLMStart){let B=a6(z);await H.handleLLMStart?.(Z,[B],U,this._parentRunId,W,this.tags,this.metadata,G)}}catch(B){if((H.raiseError?console.error:console.warn)(`Error in handler ${H.constructor.name}, handleLLMStart: ${B}`),H.raiseError)throw B}},H.awaitHandlers)})),new eY(U,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(Z,$,J=mQ(),Y=void 0,W=void 0,X=void 0,q=void 0,G=void 0,z=void 0){return await Promise.all(this.handlers.map((K)=>{if(K.ignoreChain)return;if(J1(K))K._createRunForChainStart(Z,$,J,this._parentRunId,this.tags,this.metadata,Y,q,z);return T0(async()=>{try{await K.handleChainStart?.(Z,$,J,this._parentRunId,this.tags,this.metadata,Y,q,z)}catch(U){if((K.raiseError?console.error:console.warn)(`Error in handler ${K.constructor.name}, handleChainStart: ${U}`),K.raiseError)throw U}},K.awaitHandlers)})),new r7(J,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(Z,$,J=mQ(),Y=void 0,W=void 0,X=void 0,q=void 0,G=void 0){return await Promise.all(this.handlers.map((z)=>{if(z.ignoreAgent)return;if(J1(z))z._createRunForToolStart(Z,$,J,this._parentRunId,this.tags,this.metadata,q);return T0(async()=>{try{await z.handleToolStart?.(Z,$,J,this._parentRunId,this.tags,this.metadata,q,G)}catch(K){if((z.raiseError?console.error:console.warn)(`Error in handler ${z.constructor.name}, handleToolStart: ${K}`),z.raiseError)throw K}},z.awaitHandlers)})),new s7(J,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(Z,$,J=mQ(),Y=void 0,W=void 0,X=void 0,q=void 0){return await Promise.all(this.handlers.map((G)=>{if(G.ignoreRetriever)return;if(J1(G))G._createRunForRetrieverStart(Z,$,J,this._parentRunId,this.tags,this.metadata,q);return T0(async()=>{try{await G.handleRetrieverStart?.(Z,$,J,this._parentRunId,this.tags,this.metadata,q)}catch(z){if((G.raiseError?console.error:console.warn)(`Error in handler ${G.constructor.name}, handleRetrieverStart: ${z}`),G.raiseError)throw z}},G.awaitHandlers)})),new n7(J,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(Z,$,J,Y,W){await Promise.all(this.handlers.map((X)=>T0(async()=>{if(!X.ignoreCustomEvent)try{await X.handleCustomEvent?.(Z,$,J,this.tags,this.metadata)}catch(q){if((X.raiseError?console.error:console.warn)(`Error in handler ${X.constructor.name}, handleCustomEvent: ${q}`),X.raiseError)throw q}},X.awaitHandlers)))}addHandler(Z,$=!0){if(this.handlers.push(Z),$)this.inheritableHandlers.push(Z)}removeHandler(Z){this.handlers=this.handlers.filter(($)=>$!==Z),this.inheritableHandlers=this.inheritableHandlers.filter(($)=>$!==Z)}setHandlers(Z,$=!0){this.handlers=[],this.inheritableHandlers=[];for(let J of Z)this.addHandler(J,$)}addTags(Z,$=!0){if(this.removeTags(Z),this.tags.push(...Z),$)this.inheritableTags.push(...Z)}removeTags(Z){this.tags=this.tags.filter(($)=>!Z.includes($)),this.inheritableTags=this.inheritableTags.filter(($)=>!Z.includes($))}addMetadata(Z,$=!0){if(this.metadata={...this.metadata,...Z},$)this.inheritableMetadata={...this.inheritableMetadata,...Z}}removeMetadata(Z){for(let $ of Object.keys(Z))delete this.metadata[$],delete this.inheritableMetadata[$]}copy(Z=[],$=!0){let J=new Q(this._parentRunId);for(let Y of this.handlers){let W=this.inheritableHandlers.includes(Y);J.addHandler(Y,W)}for(let Y of this.tags){let W=this.inheritableTags.includes(Y);J.addTags([Y],W)}for(let Y of Object.keys(this.metadata)){let W=Object.keys(this.inheritableMetadata).includes(Y);J.addMetadata({[Y]:this.metadata[Y]},W)}for(let Y of Z){if(J.handlers.filter((W)=>W.name==="console_callback_handler").some((W)=>W.name===Y.name))continue;J.addHandler(Y,$)}return J}static fromHandlers(Z){class $ extends J8{name=mQ();constructor(){super();Object.assign(this,Z)}}let J=new this;return J.addHandler(new $),J}static configure(Z,$,J,Y,W,X,q){return this._configureSync(Z,$,J,Y,W,X,q)}static _configureSync(Z,$,J,Y,W,X,q){let G;if(Z||$){if(Array.isArray(Z)||!Z)G=new Q,G.setHandlers(Z?.map(v1)??[],!0);else G=Z;G=G.copy(Array.isArray($)?$.map(v1):$?.handlers,!1)}let z=wQ("LANGCHAIN_VERBOSE")==="true"||q?.verbose,K=q9.getTraceableRunTree(),U=K?.tracingEnabled??c7();if(K?.tracingEnabled===!1&&G){let B=G.handlers.filter((F)=>F.name==="langchain_tracer");for(let F of B)G.removeHandler(F)}let H=U||(wQ("LANGCHAIN_TRACING")??!1);if(z||H){if(!G)G=new Q;if(z&&!G.handlers.some((B)=>B.name===Y9.prototype.name)){let B=new Y9;G.addHandler(B,!0)}if(H&&!G.handlers.some((B)=>B.name==="langchain_tracer")){if(U){let B=new q9;G.addHandler(B,!0)}}if(U){if(K&&G._parentRunId===void 0)G._parentRunId=K.id,G.handlers.find((B)=>B.name==="langchain_tracer")?.updateFromRunTree(K)}}for(let{contextVar:B,inheritable:F=!0,handlerClass:w,envVar:A}of l7()){let E=A&&wQ(A)==="true"&&w,P,j=B!==void 0?aY(B):void 0;if(j&&LY(j))P=j;else if(E)P=new w({});if(P!==void 0){if(!G)G=new Q;if(!G.handlers.some((R)=>R.name===P.name))G.addHandler(P,F)}}if(J||Y){if(G)G.addTags(J??[]),G.addTags(Y??[],!1)}if(W||X){if(G)G.addMetadata(W??{}),G.addMetadata(X??{},!1)}return G}};function v1(Q){if("name"in Q)return Q;return J8.fromMethods(Q)}var Q4=class{getStore(){}run(Q,Z){return Z()}enterWith(Q){}},tH=new Q4,t7=Symbol.for("lc:child_config"),aH=class{getInstance(){return E6()??tH}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[t7]}runWithConfig(Q,Z,$){let J=d0._configureSync(Q?.callbacks,void 0,Q?.tags,void 0,Q?.metadata),Y=this.getInstance(),W=Y.getStore(),X=J?.getParentRunId(),q=J?.handlers?.find((z)=>z?.name==="langchain_tracer"),G;if(q&&X)G=q.getRunTreeWithTracingConfig(X);else if(!$)G=new r0({name:"<runnable_lambda>",tracingEnabled:!1});if(G)G.extra={...G.extra,[t7]:Q};if(W!==void 0&&W[O6]!==void 0){if(G===void 0)G={};G[O6]=W[O6]}return Y.run(G,Z)}initializeGlobalInstance(Q){if(E6()===void 0)d7(Q)}},q0=new aH;var a7=_({AsyncLocalStorageProviderSingleton:()=>q0,MockAsyncLocalStorage:()=>Q4,_CONTEXT_VARIABLES_KEY:()=>O6});var z9=25;async function QQ(Q){return d0._configureSync(Q?.callbacks,void 0,Q?.tags,void 0,Q?.metadata)}function w0(...Q){let Z={};for(let $ of Q.filter((J)=>!!J))for(let J of Object.keys($))if(J==="metadata")Z[J]={...Z[J],...$[J]};else if(J==="tags"){let Y=Z[J]??[];Z[J]=[...new Set(Y.concat($[J]??[]))]}else if(J==="configurable")Z[J]={...Z[J],...$[J]};else if(J==="timeout"){if(Z.timeout===void 0)Z.timeout=$.timeout;else if($.timeout!==void 0)Z.timeout=Math.min(Z.timeout,$.timeout)}else if(J==="signal"){if(Z.signal===void 0)Z.signal=$.signal;else if($.signal!==void 0)if("any"in AbortSignal)Z.signal=AbortSignal.any([Z.signal,$.signal]);else Z.signal=$.signal}else if(J==="callbacks"){let Y=Z.callbacks,W=$.callbacks;if(Array.isArray(W))if(!Y)Z.callbacks=W;else if(Array.isArray(Y))Z.callbacks=Y.concat(W);else{let X=Y.copy();for(let q of W)X.addHandler(v1(q),!0);Z.callbacks=X}else if(W)if(!Y)Z.callbacks=W;else if(Array.isArray(Y)){let X=W.copy();for(let q of Y)X.addHandler(v1(q),!0);Z.callbacks=X}else Z.callbacks=new d0(W._parentRunId,{handlers:Y.handlers.concat(W.handlers),inheritableHandlers:Y.inheritableHandlers.concat(W.inheritableHandlers),tags:Array.from(new Set(Y.tags.concat(W.tags))),inheritableTags:Array.from(new Set(Y.inheritableTags.concat(W.inheritableTags))),metadata:{...Y.metadata,...W.metadata}})}else{let Y=J;Z[Y]=$[Y]??Z[Y]}return Z}var eH=new Set(["string","number","boolean"]);function t(Q){let Z=q0.getRunnableConfig(),$={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(Z){let{runId:J,runName:Y,...W}=Z;$=Object.entries(W).reduce((X,[q,G])=>{if(G!==void 0)X[q]=G;return X},$)}if(Q)$=Object.entries(Q).reduce((J,[Y,W])=>{if(W!==void 0)J[Y]=W;return J},$);if($?.configurable){for(let J of Object.keys($.configurable))if(eH.has(typeof $.configurable[J])&&!$.metadata?.[J]){if(!$.metadata)$.metadata={};$.metadata[J]=$.configurable[J]}}if($.timeout!==void 0){if($.timeout<=0)throw Error("Timeout must be a positive number");let J=$.timeout,Y=AbortSignal.timeout(J);if(!$.metadata)$.metadata={};if($.metadata.timeoutMs===void 0)$.metadata.timeoutMs=J;if($.signal!==void 0){if("any"in AbortSignal)$.signal=AbortSignal.any([$.signal,Y])}else $.signal=Y;delete $.timeout}return $}function W0(Q={},{callbacks:Z,maxConcurrency:$,recursionLimit:J,runName:Y,configurable:W,runId:X}={}){let q=t(Q);if(Z!==void 0)delete q.runName,q.callbacks=Z;if(J!==void 0)q.recursionLimit=J;if($!==void 0)q.maxConcurrency=$;if(Y!==void 0)q.runName=Y;if(W!==void 0)q.configurable={...q.configurable,...W};if(X!==void 0)delete q.runId;return q}function PQ(Q){if(!Q)return;return{configurable:Q.configurable,recursionLimit:Q.recursionLimit,callbacks:Q.callbacks,tags:Q.tags,metadata:Q.metadata,maxConcurrency:Q.maxConcurrency,timeout:Q.timeout,signal:Q.signal,store:Q.store}}async function TQ(Q,Z){if(Z===void 0)return Q;let $;return Promise.race([Q.catch((J)=>{if(!Z?.aborted)throw J;else return}),new Promise((J,Y)=>{if($=()=>{Y(j6(Z))},Z.addEventListener("abort",$,{once:!0}),Z.aborted)Y(j6(Z))})]).finally(()=>Z.removeEventListener("abort",$))}function j6(Q){if(Q?.reason instanceof Error)return Q.reason;if(typeof Q?.reason==="string")return Error(Q.reason);return Error("Aborted")}var e7=_({AsyncGeneratorWithSetup:()=>x8,IterableReadableStream:()=>S0,atee:()=>K9,concat:()=>uQ,pipeGeneratorWithSetup:()=>Z4}),S0=class Q extends ReadableStream{reader;ensureReader(){if(!this.reader)this.reader=this.getReader()}async next(){this.ensureReader();try{let Z=await this.reader.read();if(Z.done)return this.reader.releaseLock(),{done:!0,value:void 0};else return{done:!1,value:Z.value}}catch(Z){throw this.reader.releaseLock(),Z}}async return(){if(this.ensureReader(),this.locked){let Z=this.reader.cancel();this.reader.releaseLock(),await Z}return{done:!0,value:void 0}}async throw(Z){if(this.ensureReader(),this.locked){let $=this.reader.cancel();this.reader.releaseLock(),await $}throw Z}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(Z){let $=Z.getReader();return new Q({start(J){return Y();function Y(){return $.read().then(({done:W,value:X})=>{if(W){J.close();return}return J.enqueue(X),Y()})}},cancel(){$.releaseLock()}})}static fromAsyncGenerator(Z){return new Q({async pull($){let{value:J,done:Y}=await Z.next();if(Y)$.close();$.enqueue(J)},async cancel($){await Z.return($)}})}};function K9(Q,Z=2){let $=Array.from({length:Z},()=>[]);return $.map(async function*(Y){while(!0)if(Y.length===0){let W=await Q.next();for(let X of $)X.push(W)}else if(Y[0].done)return;else yield Y.shift().value})}function uQ(Q,Z){if(Array.isArray(Q)&&Array.isArray(Z))return Q.concat(Z);else if(typeof Q==="string"&&typeof Z==="string")return Q+Z;else if(typeof Q==="number"&&typeof Z==="number")return Q+Z;else if("concat"in Q&&typeof Q.concat==="function")return Q.concat(Z);else if(typeof Q==="object"&&typeof Z==="object"){let $={...Q};for(let[J,Y]of Object.entries(Z))if(J in $&&!Array.isArray($[J]))$[J]=uQ($[J],Y);else $[J]=Y;return $}else throw Error(`Cannot concat ${typeof Q} and ${typeof Z}`)}var x8=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(Q){this.generator=Q.generator,this.config=Q.config,this.signal=Q.signal??this.config?.signal,this.setup=new Promise((Z,$)=>{q0.runWithConfig(PQ(Q.config),async()=>{if(this.firstResult=Q.generator.next(),Q.startSetup)this.firstResult.then(Q.startSetup).then(Z,$);else this.firstResult.then((J)=>Z(void 0),$)},!0)})}async next(...Q){if(this.signal?.throwIfAborted(),!this.firstResultUsed)return this.firstResultUsed=!0,this.firstResult;return q0.runWithConfig(PQ(this.config),this.signal?async()=>{return TQ(this.generator.next(...Q),this.signal)}:async()=>{return this.generator.next(...Q)},!0)}async return(Q){return this.generator.return(Q)}async throw(Q){return this.generator.throw(Q)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function Z4(Q,Z,$,J,...Y){let W=new x8({generator:Z,startSetup:$,signal:J}),X=await W.setup;return{output:Q(W,X,...Y),setup:X}}var Qq=_({ChatGenerationChunk:()=>R6,GenerationChunk:()=>a8,RUN_KEY:()=>X1}),X1="__run",a8=class Q{text;generationInfo;constructor(Z){this.text=Z.text,this.generationInfo=Z.generationInfo}concat(Z){return new Q({text:this.text+Z.text,generationInfo:{...this.generationInfo,...Z.generationInfo}})}},R6=class Q extends a8{message;constructor(Z){super(Z);this.message=Z.message}concat(Z){return new Q({text:this.text+Z.text,generationInfo:{...this.generationInfo,...Z.generationInfo},message:this.message.concat(Z.message)})}};function H0(Q){if(typeof Q!=="object"||Q===null)return!1;let Z=Q;if(!("_zod"in Z))return!1;let $=Z._zod;return typeof $==="object"&&$!==null&&"def"in $}function x0(Q){if(typeof Q!=="object"||Q===null)return!1;let Z=Q;if(!("_def"in Z)||"_zod"in Z)return!1;let $=Z._def;return typeof $==="object"&&$!=null&&"typeName"in $}function Wq(Q){if(H0(Q))console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior.");return x0(Q)}function ZQ(Q){if(!Q)return!1;if(typeof Q!=="object")return!1;if(Array.isArray(Q))return!1;if(H0(Q)||x0(Q))return!0;return!1}function W4(Q){if(typeof Q==="object"&&Q!==null&&"_def"in Q&&typeof Q._def==="object"&&Q._def!==null&&"typeName"in Q._def&&Q._def.typeName==="ZodLiteral")return!0;return!1}function X4(Q){if(!H0(Q))return!1;if(typeof Q==="object"&&Q!==null&&"_zod"in Q&&typeof Q._zod==="object"&&Q._zod!==null&&"def"in Q._zod&&typeof Q._zod.def==="object"&&Q._zod.def!==null&&"type"in Q._zod.def&&Q._zod.def.type==="literal")return!0;return!1}function Xq(Q){if(W4(Q))return!0;if(X4(Q))return!0;return!1}async function C1(Q,Z){if(H0(Q))try{return{success:!0,data:await J4(Q,Z)}}catch($){return{success:!1,error:$}}if(x0(Q))return await Q.safeParseAsync(Z);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function _6(Q,Z){if(H0(Q))return await J4(Q,Z);if(x0(Q))return await Q.parseAsync(Z);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function q4(Q,Z){if(H0(Q))try{return{success:!0,data:H9(Q,Z)}}catch($){return{success:!1,error:$}}if(x0(Q))return Q.safeParse(Z);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function xQ(Q,Z){if(H0(Q))return H9(Q,Z);if(x0(Q))return Q.parse(Z);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function W8(Q){if(H0(Q))return SQ.get(Q)?.description;if(x0(Q))return Q.description;if("description"in Q&&typeof Q.description==="string")return Q.description}function qq(Q){if(!ZQ(Q))return!1;if(x0(Q)){let Z=Q._def;if(Z.typeName==="ZodObject"){let $=Q;return!$.shape||Object.keys($.shape).length===0}if(Z.typeName==="ZodRecord")return!0}if(H0(Q)){let Z=Q._zod.def;if(Z.type==="object"){let $=Q;return!$.shape||Object.keys($.shape).length===0}if(Z.type==="record")return!0}if(typeof Q==="object"&&Q!==null&&!("shape"in Q))return!0;return!1}function b1(Q){if(!ZQ(Q))return!1;if(x0(Q))return Q._def.typeName==="ZodString";if(H0(Q))return Q._zod.def.type==="string";return!1}function B9(Q){if(typeof Q==="object"&&Q!==null&&"_def"in Q&&typeof Q._def==="object"&&Q._def!==null&&"typeName"in Q._def&&Q._def.typeName==="ZodObject")return!0;return!1}function lQ(Q){if(!H0(Q))return!1;if(typeof Q==="object"&&Q!==null&&"_zod"in Q&&typeof Q._zod==="object"&&Q._zod!==null&&"def"in Q._zod&&typeof Q._zod.def==="object"&&Q._zod.def!==null&&"type"in Q._zod.def&&Q._zod.def.type==="object")return!0;return!1}function RZ(Q){if(!H0(Q))return!1;if(typeof Q==="object"&&Q!==null&&"_zod"in Q&&typeof Q._zod==="object"&&Q._zod!==null&&"def"in Q._zod&&typeof Q._zod.def==="object"&&Q._zod.def!==null&&"type"in Q._zod.def&&Q._zod.def.type==="array")return!0;return!1}function G4(Q){if(!H0(Q))return!1;if(typeof Q==="object"&&Q!==null&&"_zod"in Q&&typeof Q._zod==="object"&&Q._zod!==null&&"def"in Q._zod&&typeof Q._zod.def==="object"&&Q._zod.def!==null&&"type"in Q._zod.def&&Q._zod.def.type==="optional")return!0;return!1}function z4(Q){if(!H0(Q))return!1;if(typeof Q==="object"&&Q!==null&&"_zod"in Q&&typeof Q._zod==="object"&&Q._zod!==null&&"def"in Q._zod&&typeof Q._zod.def==="object"&&Q._zod.def!==null&&"type"in Q._zod.def&&Q._zod.def.type==="nullable")return!0;return!1}function _0(Q){if(B9(Q))return!0;if(lQ(Q))return!0;return!1}function e8(Q){if(x0(Q))return Q.shape;if(H0(Q))return Q._zod.def.shape;throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function D9(Q,Z){if(x0(Q))return Q.extend(Z);if(H0(Q))return $4.extend(Q,Z);throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function I6(Q){if(x0(Q))return Q.partial();if(H0(Q))return $4.partial(Y4,Q,void 0);throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function y1(Q,Z=!1){if(x0(Q))return Q.strict();if(lQ(Q)){let $=Q._zod.def.shape;if(Z)for(let[W,X]of Object.entries(Q._zod.def.shape)){if(lQ(X))$[W]=y1(X,Z);else if(RZ(X)){let G=X._zod.def.element;if(lQ(G))G=y1(G,Z);$[W]=M8(X,{...X._zod.def,element:G})}else $[W]=X;let q=SQ.get(X);if(q)SQ.add($[W],q)}let J=M8(Q,{...Q._zod.def,shape:$,catchall:Yq($q)}),Y=SQ.get(Q);if(Y)SQ.add(J,Y);return J}throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function U9(Q,Z=!1){if(B9(Q))return Q.passthrough();if(lQ(Q)){let $=Q._zod.def.shape;if(Z)for(let[W,X]of Object.entries(Q._zod.def.shape)){if(lQ(X))$[W]=U9(X,Z);else if(RZ(X)){let G=X._zod.def.element;if(lQ(G))G=U9(G,Z);$[W]=M8(X,{...X._zod.def,element:G})}else $[W]=X;let q=SQ.get(X);if(q)SQ.add($[W],q)}let J=M8(Q,{...Q._zod.def,shape:$,catchall:Jq(Zq)}),Y=SQ.get(Q);if(Y)SQ.add(J,Y);return J}throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function T6(Q){if(x0(Q))try{let Z=Q.parse(void 0);return()=>Z}catch{return}if(H0(Q))try{let Z=H9(Q,void 0);return()=>Z}catch{return}}function QB(Q){return x0(Q)&&"typeName"in Q._def&&Q._def.typeName==="ZodEffects"}function ZB(Q){return H0(Q)&&Q._zod.def.type==="pipe"}function q1(Q,Z,$){let J=$.get(Q);if(J!==void 0)return J;if(x0(Q)){if(QB(Q))return q1(Q._def.schema,Z,$);return Q}if(H0(Q)){let Y=Q;if(ZB(Q))Y=q1(Q._zod.def.in,Z,$);if(Z){if(lQ(Y)){let X={};for(let[q,G]of Object.entries(Y._zod.def.shape))X[q]=q1(G,Z,$);Y=M8(Y,{...Y._zod.def,shape:X})}else if(RZ(Y)){let X=q1(Y._zod.def.element,Z,$);Y=M8(Y,{...Y._zod.def,element:X})}else if(G4(Y)){let X=q1(Y._zod.def.innerType,Z,$);Y=M8(Y,{...Y._zod.def,innerType:X})}else if(z4(Y)){let X=q1(Y._zod.def.innerType,Z,$);Y=M8(Y,{...Y._zod.def,innerType:X})}}let W=SQ.get(Q);if(W)SQ.add(Y,W);return $.set(Q,Y),Y}throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function V9(Q,Z=!1){return q1(Q,Z,new WeakMap)}function F9(Q,Z){if(x0(Q)){let $=e8(Q),J={};for(let[Y,W]of Object.entries($))if(Z(Y,W))J[Y]=W.optional();else J[Y]=W;return Q.extend(J)}if(H0(Q)){let $=e8(Q),J={...Q._zod.def.shape};for(let[X,q]of Object.entries($))if(Z(X,q))J[X]=new Y4({type:"optional",innerType:q});let Y=M8(Q,{...Q._zod.def,shape:J}),W=SQ.get(Q);if(W)SQ.add(Y,W);return Y}throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function L9(Q){return Q instanceof Error&&(Q.constructor.name==="ZodError"||Q.constructor.name==="$ZodError")}var Gq=_({isSerializableSchema:()=>iQ,isStandardJsonSchema:()=>w9,isStandardSchema:()=>zq});function zq(Q){return(typeof Q==="object"||typeof Q==="function")&&Q!==null&&"~standard"in Q&&typeof Q["~standard"]==="object"&&Q["~standard"]!==null&&"validate"in Q["~standard"]}function w9(Q){return(typeof Q==="object"||typeof Q==="function")&&Q!==null&&"~standard"in Q&&typeof Q["~standard"]==="object"&&Q["~standard"]!==null&&"jsonSchema"in Q["~standard"]}function iQ(Q){return zq(Q)&&w9(Q)}var U4=Symbol("Let zodToJsonSchema decide on which parser to use"),K4={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},H4=(Q)=>typeof Q==="string"?{...K4,name:Q}:{...K4,...Q};var B4=(Q)=>{let Z=H4(Q),$=Z.name!==void 0?[...Z.basePath,Z.definitionPath,Z.name]:Z.basePath;return{...Z,flags:{hasReferencedOpenAiAnyType:!1},currentPath:$,propertyPath:void 0,seen:new Map(Object.entries(Z.definitions).map(([J,Y])=>[Y._def,{def:Y._def,path:[...Z.basePath,Z.definitionPath,J],jsonSchema:void 0}]))}};var _Z=(Q,Z)=>{let $=0;for(;$<Q.length&&$<Z.length;$++)if(Q[$]!==Z[$])break;return[(Q.length-$).toString(),...Z.slice($)].join("/")};function O0(Q){if(Q.target!=="openAi")return{};let Z=[...Q.basePath,Q.definitionPath,Q.openAiAnyTypeName];return Q.flags.hasReferencedOpenAiAnyType=!0,{$ref:Q.$refStrategy==="relative"?_Z(Z,Q.currentPath):Z.join("/")}}function A9(Q,Z,$,J){if(!J?.errorMessages)return;if($)Q.errorMessage={...Q.errorMessage,[Z]:$}}function X0(Q,Z,$,J,Y){Q[Z]=$,A9(Q,Z,J,Y)}function D4(Q,Z){let $={type:"array"};if(Q.type?._def&&Q.type?._def?.typeName!==r.ZodAny)$.items=o(Q.type._def,{...Z,currentPath:[...Z.currentPath,"items"]});if(Q.minLength)X0($,"minItems",Q.minLength.value,Q.minLength.message,Z);if(Q.maxLength)X0($,"maxItems",Q.maxLength.value,Q.maxLength.message,Z);if(Q.exactLength)X0($,"minItems",Q.exactLength.value,Q.exactLength.message,Z),X0($,"maxItems",Q.exactLength.value,Q.exactLength.message,Z);return $}function V4(Q,Z){let $={type:"integer",format:"int64"};if(!Q.checks)return $;for(let J of Q.checks)switch(J.kind){case"min":if(Z.target==="jsonSchema7")if(J.inclusive)X0($,"minimum",J.value,J.message,Z);else X0($,"exclusiveMinimum",J.value,J.message,Z);else{if(!J.inclusive)$.exclusiveMinimum=!0;X0($,"minimum",J.value,J.message,Z)}break;case"max":if(Z.target==="jsonSchema7")if(J.inclusive)X0($,"maximum",J.value,J.message,Z);else X0($,"exclusiveMaximum",J.value,J.message,Z);else{if(!J.inclusive)$.exclusiveMaximum=!0;X0($,"maximum",J.value,J.message,Z)}break;case"multipleOf":X0($,"multipleOf",J.value,J.message,Z);break}return $}function F4(){return{type:"boolean"}}function IZ(Q,Z){return o(Q.type._def,Z)}var L4=(Q,Z)=>{return o(Q.innerType._def,Z)};function P9(Q,Z,$){let J=$??Z.dateStrategy;if(Array.isArray(J))return{anyOf:J.map((Y)=>P9(Q,Z,Y))};switch(J){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return $B(Q,Z)}}var $B=(Q,Z)=>{let $={type:"integer",format:"unix-time"};if(Z.target==="openApi3")return $;for(let J of Q.checks)switch(J.kind){case"min":X0($,"minimum",J.value,J.message,Z);break;case"max":X0($,"maximum",J.value,J.message,Z);break}return $};function w4(Q,Z){return{...o(Q.innerType._def,Z),default:Q.defaultValue()}}function A4(Q,Z){return Z.effectStrategy==="input"?o(Q.schema._def,Z):O0(Z)}function P4(Q){return{type:"string",enum:Array.from(Q.values)}}var JB=(Q)=>{if("type"in Q&&Q.type==="string")return!1;return"allOf"in Q};function N4(Q,Z){let $=[o(Q.left._def,{...Z,currentPath:[...Z.currentPath,"allOf","0"]}),o(Q.right._def,{...Z,currentPath:[...Z.currentPath,"allOf","1"]})].filter((W)=>!!W),J=Z.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,Y=[];return $.forEach((W)=>{if(JB(W)){if(Y.push(...W.allOf),W.unevaluatedProperties===void 0)J=void 0}else{let X=W;if("additionalProperties"in W&&W.additionalProperties===!1){let{additionalProperties:q,...G}=W;X=G}else J=void 0;Y.push(X)}}),Y.length?{allOf:Y,...J}:void 0}function O4(Q,Z){let $=typeof Q.value;if($!=="bigint"&&$!=="number"&&$!=="boolean"&&$!=="string")return{type:Array.isArray(Q.value)?"array":"object"};if(Z.target==="openApi3")return{type:$==="bigint"?"integer":$,enum:[Q.value]};return{type:$==="bigint"?"integer":$,const:Q.value}}var E4=void 0,oQ={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(E4===void 0)E4=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return E4},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function TZ(Q,Z){let $={type:"string"};if(Q.checks)for(let J of Q.checks)switch(J.kind){case"min":X0($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,J.value):J.value,J.message,Z);break;case"max":X0($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,J.value):J.value,J.message,Z);break;case"email":switch(Z.emailStrategy){case"format:email":X8($,"email",J.message,Z);break;case"format:idn-email":X8($,"idn-email",J.message,Z);break;case"pattern:zod":NQ($,oQ.email,J.message,Z);break}break;case"url":X8($,"uri",J.message,Z);break;case"uuid":X8($,"uuid",J.message,Z);break;case"regex":NQ($,J.regex,J.message,Z);break;case"cuid":NQ($,oQ.cuid,J.message,Z);break;case"cuid2":NQ($,oQ.cuid2,J.message,Z);break;case"startsWith":NQ($,RegExp(`^${j4(J.value,Z)}`),J.message,Z);break;case"endsWith":NQ($,RegExp(`${j4(J.value,Z)}$`),J.message,Z);break;case"datetime":X8($,"date-time",J.message,Z);break;case"date":X8($,"date",J.message,Z);break;case"time":X8($,"time",J.message,Z);break;case"duration":X8($,"duration",J.message,Z);break;case"length":X0($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,J.value):J.value,J.message,Z),X0($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,J.value):J.value,J.message,Z);break;case"includes":NQ($,RegExp(j4(J.value,Z)),J.message,Z);break;case"ip":if(J.version!=="v6")X8($,"ipv4",J.message,Z);if(J.version!=="v4")X8($,"ipv6",J.message,Z);break;case"base64url":NQ($,oQ.base64url,J.message,Z);break;case"jwt":NQ($,oQ.jwt,J.message,Z);break;case"cidr":if(J.version!=="v6")NQ($,oQ.ipv4Cidr,J.message,Z);if(J.version!=="v4")NQ($,oQ.ipv6Cidr,J.message,Z);break;case"emoji":NQ($,oQ.emoji(),J.message,Z);break;case"ulid":NQ($,oQ.ulid,J.message,Z);break;case"base64":switch(Z.base64Strategy){case"format:binary":X8($,"binary",J.message,Z);break;case"contentEncoding:base64":X0($,"contentEncoding","base64",J.message,Z);break;case"pattern:zod":NQ($,oQ.base64,J.message,Z);break}break;case"nanoid":NQ($,oQ.nanoid,J.message,Z);break;case"toLowerCase":case"toUpperCase":case"trim":break;default:((Y)=>{})(J)}return $}function j4(Q,Z){return Z.patternStrategy==="escape"?WB(Q):Q}var YB=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function WB(Q){let Z="";for(let $=0;$<Q.length;$++){if(!YB.has(Q[$]))Z+="\\";Z+=Q[$]}return Z}function X8(Q,Z,$,J){if(Q.format||Q.anyOf?.some((Y)=>Y.format)){if(!Q.anyOf)Q.anyOf=[];if(Q.format){if(Q.anyOf.push({format:Q.format,...Q.errorMessage&&J.errorMessages&&{errorMessage:{format:Q.errorMessage.format}}}),delete Q.format,Q.errorMessage){if(delete Q.errorMessage.format,Object.keys(Q.errorMessage).length===0)delete Q.errorMessage}}Q.anyOf.push({format:Z,...$&&J.errorMessages&&{errorMessage:{format:$}}})}else X0(Q,"format",Z,$,J)}function NQ(Q,Z,$,J){if(Q.pattern||Q.allOf?.some((Y)=>Y.pattern)){if(!Q.allOf)Q.allOf=[];if(Q.pattern){if(Q.allOf.push({pattern:Q.pattern,...Q.errorMessage&&J.errorMessages&&{errorMessage:{pattern:Q.errorMessage.pattern}}}),delete Q.pattern,Q.errorMessage){if(delete Q.errorMessage.pattern,Object.keys(Q.errorMessage).length===0)delete Q.errorMessage}}Q.allOf.push({pattern:Kq(Z,J),...$&&J.errorMessages&&{errorMessage:{pattern:$}}})}else X0(Q,"pattern",Kq(Z,J),$,J)}function Kq(Q,Z){if(!Z.applyRegexFlags||!Q.flags)return Q.source;let $={i:Q.flags.includes("i"),m:Q.flags.includes("m"),s:Q.flags.includes("s")},J=$.i?Q.source.toLowerCase():Q.source,Y="",W=!1,X=!1,q=!1;for(let G=0;G<J.length;G++){if(W){Y+=J[G],W=!1;continue}if($.i){if(X){if(J[G].match(/[a-z]/)){if(q)Y+=J[G],Y+=`${J[G-2]}-${J[G]}`.toUpperCase(),q=!1;else if(J[G+1]==="-"&&J[G+2]?.match(/[a-z]/))Y+=J[G],q=!0;else Y+=`${J[G]}${J[G].toUpperCase()}`;continue}}else if(J[G].match(/[a-z]/)){Y+=`[${J[G]}${J[G].toUpperCase()}]`;continue}}if($.m){if(J[G]==="^"){Y+=`(^|(?<=[\r
54
+ ]))`;continue}else if(J[G]==="$"){Y+=`($|(?=[\r
55
+ ]))`;continue}}if($.s&&J[G]==="."){Y+=X?`${J[G]}\r
56
+ `:`[${J[G]}\r
57
+ ]`;continue}if(Y+=J[G],J[G]==="\\")W=!0;else if(X&&J[G]==="]")X=!1;else if(!X&&J[G]==="[")X=!0}try{new RegExp(Y)}catch{return console.warn(`Could not convert regex pattern at ${Z.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Q.source}return Y}function SZ(Q,Z){if(Z.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(Z.target==="openApi3"&&Q.keyType?._def.typeName===r.ZodEnum)return{type:"object",required:Q.keyType._def.values,properties:Q.keyType._def.values.reduce((J,Y)=>({...J,[Y]:o(Q.valueType._def,{...Z,currentPath:[...Z.currentPath,"properties",Y]})??O0(Z)}),{}),additionalProperties:Z.rejectedAdditionalProperties};let $={type:"object",additionalProperties:o(Q.valueType._def,{...Z,currentPath:[...Z.currentPath,"additionalProperties"]})??Z.allowedAdditionalProperties};if(Z.target==="openApi3")return $;if(Q.keyType?._def.typeName===r.ZodString&&Q.keyType._def.checks?.length){let{type:J,...Y}=TZ(Q.keyType._def,Z);return{...$,propertyNames:Y}}else if(Q.keyType?._def.typeName===r.ZodEnum)return{...$,propertyNames:{enum:Q.keyType._def.values}};else if(Q.keyType?._def.typeName===r.ZodBranded&&Q.keyType._def.type._def.typeName===r.ZodString&&Q.keyType._def.type._def.checks?.length){let{type:J,...Y}=IZ(Q.keyType._def,Z);return{...$,propertyNames:Y}}return $}function R4(Q,Z){if(Z.mapStrategy==="record")return SZ(Q,Z);return{type:"array",maxItems:125,items:{type:"array",items:[o(Q.keyType._def,{...Z,currentPath:[...Z.currentPath,"items","items","0"]})||O0(Z),o(Q.valueType._def,{...Z,currentPath:[...Z.currentPath,"items","items","1"]})||O0(Z)],minItems:2,maxItems:2}}}function _4(Q){let Z=Q.values,$=Object.keys(Q.values).filter((Y)=>{return typeof Z[Z[Y]]!=="number"}).map((Y)=>Z[Y]),J=Array.from(new Set($.map((Y)=>typeof Y)));return{type:J.length===1?J[0]==="string"?"string":"number":["string","number"],enum:$}}function I4(Q){return Q.target==="openAi"?void 0:{not:O0({...Q,currentPath:[...Q.currentPath,"not"]})}}function T4(Q){return Q.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var k1={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function S4(Q,Z){if(Z.target==="openApi3")return Uq(Q,Z);let $=Q.options instanceof Map?Array.from(Q.options.values()):Q.options;if($.every((J)=>(J._def.typeName in k1)&&(!J._def.checks||!J._def.checks.length))){let J=$.reduce((Y,W)=>{let X=k1[W._def.typeName];return X&&!Y.includes(X)?[...Y,X]:Y},[]);return{type:J.length>1?J:J[0]}}else if($.every((J)=>J._def.typeName==="ZodLiteral"&&!J.description)){let J=$.reduce((Y,W)=>{let X=typeof W._def.value;switch(X){case"string":case"number":case"boolean":return[...Y,X];case"bigint":return[...Y,"integer"];case"object":if(W._def.value===null)return[...Y,"null"];return Y;default:return Y}},[]);if(J.length===$.length){let Y=J.filter((W,X,q)=>q.indexOf(W)===X);return{type:Y.length>1?Y:Y[0],enum:$.reduce((W,X)=>{return W.includes(X._def.value)?W:[...W,X._def.value]},[])}}}else if($.every((J)=>J._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((J,Y)=>[...J,...Y._def.values.filter((W)=>!J.includes(W))],[])};return Uq(Q,Z)}var Uq=(Q,Z)=>{let $=(Q.options instanceof Map?Array.from(Q.options.values()):Q.options).map((J,Y)=>o(J._def,{...Z,currentPath:[...Z.currentPath,"anyOf",`${Y}`]})).filter((J)=>!!J&&(!Z.strictUnions||typeof J==="object"&&Object.keys(J).length>0));return $.length?{anyOf:$}:void 0};function x4(Q,Z){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Q.innerType._def.typeName)&&(!Q.innerType._def.checks||!Q.innerType._def.checks.length)){if(Z.target==="openApi3")return{type:k1[Q.innerType._def.typeName],nullable:!0};return{type:[k1[Q.innerType._def.typeName],"null"]}}if(Z.target==="openApi3"){let J=o(Q.innerType._def,{...Z,currentPath:[...Z.currentPath]});if(J&&"$ref"in J)return{allOf:[J],nullable:!0};return J&&{...J,nullable:!0}}let $=o(Q.innerType._def,{...Z,currentPath:[...Z.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function M4(Q,Z){let $={type:"number"};if(!Q.checks)return $;for(let J of Q.checks)switch(J.kind){case"int":$.type="integer",A9($,"type",J.message,Z);break;case"min":if(Z.target==="jsonSchema7")if(J.inclusive)X0($,"minimum",J.value,J.message,Z);else X0($,"exclusiveMinimum",J.value,J.message,Z);else{if(!J.inclusive)$.exclusiveMinimum=!0;X0($,"minimum",J.value,J.message,Z)}break;case"max":if(Z.target==="jsonSchema7")if(J.inclusive)X0($,"maximum",J.value,J.message,Z);else X0($,"exclusiveMaximum",J.value,J.message,Z);else{if(!J.inclusive)$.exclusiveMaximum=!0;X0($,"maximum",J.value,J.message,Z)}break;case"multipleOf":X0($,"multipleOf",J.value,J.message,Z);break}return $}function v4(Q,Z){let $=Z.target==="openAi",J={type:"object",properties:{}},Y=[],W=Q.shape();for(let q in W){let G=W[q];if(G===void 0||G._def===void 0)continue;let z=qB(G);if(z&&$){if(G._def.typeName==="ZodOptional")G=G._def.innerType;if(!G.isNullable())G=G.nullable();z=!1}let K=o(G._def,{...Z,currentPath:[...Z.currentPath,"properties",q],propertyPath:[...Z.currentPath,"properties",q]});if(K===void 0)continue;if(J.properties[q]=K,!z)Y.push(q)}if(Y.length)J.required=Y;let X=XB(Q,Z);if(X!==void 0)J.additionalProperties=X;return J}function XB(Q,Z){if(Q.catchall._def.typeName!=="ZodNever")return o(Q.catchall._def,{...Z,currentPath:[...Z.currentPath,"additionalProperties"]});switch(Q.unknownKeys){case"passthrough":return Z.allowedAdditionalProperties;case"strict":return Z.rejectedAdditionalProperties;case"strip":return Z.removeAdditionalStrategy==="strict"?Z.allowedAdditionalProperties:Z.rejectedAdditionalProperties}}function qB(Q){try{return Q.isOptional()}catch{return!0}}var y4=(Q,Z)=>{if(Z.currentPath.toString()===Z.propertyPath?.toString())return o(Q.innerType._def,Z);let $=o(Q.innerType._def,{...Z,currentPath:[...Z.currentPath,"anyOf","1"]});return $?{anyOf:[{not:O0(Z)},$]}:O0(Z)};var C4=(Q,Z)=>{if(Z.pipeStrategy==="input")return o(Q.in._def,Z);else if(Z.pipeStrategy==="output")return o(Q.out._def,Z);let $=o(Q.in._def,{...Z,currentPath:[...Z.currentPath,"allOf","0"]});return{allOf:[$,o(Q.out._def,{...Z,currentPath:[...Z.currentPath,"allOf",$?"1":"0"]})].filter((J)=>J!==void 0)}};function b4(Q,Z){return o(Q.type._def,Z)}function k4(Q,Z){let $={type:"array",uniqueItems:!0,items:o(Q.valueType._def,{...Z,currentPath:[...Z.currentPath,"items"]})};if(Q.minSize)X0($,"minItems",Q.minSize.value,Q.minSize.message,Z);if(Q.maxSize)X0($,"maxItems",Q.maxSize.value,Q.maxSize.message,Z);return $}function f4(Q,Z){if(Q.rest)return{type:"array",minItems:Q.items.length,items:Q.items.map(($,J)=>o($._def,{...Z,currentPath:[...Z.currentPath,"items",`${J}`]})).reduce(($,J)=>J===void 0?$:[...$,J],[]),additionalItems:o(Q.rest._def,{...Z,currentPath:[...Z.currentPath,"additionalItems"]})};else return{type:"array",minItems:Q.items.length,maxItems:Q.items.length,items:Q.items.map(($,J)=>o($._def,{...Z,currentPath:[...Z.currentPath,"items",`${J}`]})).reduce(($,J)=>J===void 0?$:[...$,J],[])}}function h4(Q){return{not:O0(Q)}}function g4(Q){return O0(Q)}var m4=(Q,Z)=>{return o(Q.innerType._def,Z)};var d4=(Q,Z,$)=>{switch(Z){case r.ZodString:return TZ(Q,$);case r.ZodNumber:return M4(Q,$);case r.ZodObject:return v4(Q,$);case r.ZodBigInt:return V4(Q,$);case r.ZodBoolean:return F4();case r.ZodDate:return P9(Q,$);case r.ZodUndefined:return h4($);case r.ZodNull:return T4($);case r.ZodArray:return D4(Q,$);case r.ZodUnion:case r.ZodDiscriminatedUnion:return S4(Q,$);case r.ZodIntersection:return N4(Q,$);case r.ZodTuple:return f4(Q,$);case r.ZodRecord:return SZ(Q,$);case r.ZodLiteral:return O4(Q,$);case r.ZodEnum:return P4(Q);case r.ZodNativeEnum:return _4(Q);case r.ZodNullable:return x4(Q,$);case r.ZodOptional:return y4(Q,$);case r.ZodMap:return R4(Q,$);case r.ZodSet:return k4(Q,$);case r.ZodLazy:return()=>Q.getter()._def;case r.ZodPromise:return b4(Q,$);case r.ZodNaN:case r.ZodNever:return I4($);case r.ZodEffects:return A4(Q,$);case r.ZodAny:return O0($);case r.ZodUnknown:return g4($);case r.ZodDefault:return w4(Q,$);case r.ZodBranded:return IZ(Q,$);case r.ZodReadonly:return m4(Q,$);case r.ZodCatch:return L4(Q,$);case r.ZodPipeline:return C4(Q,$);case r.ZodFunction:case r.ZodVoid:case r.ZodSymbol:return;default:return((J)=>{return})(Z)}};function o(Q,Z,$=!1){let J=Z.seen.get(Q);if(Z.override){let q=Z.override?.(Q,Z,J,$);if(q!==U4)return q}if(J&&!$){let q=GB(J,Z);if(q!==void 0)return q}let Y={def:Q,path:Z.currentPath,jsonSchema:void 0};Z.seen.set(Q,Y);let W=d4(Q,Q.typeName,Z),X=typeof W==="function"?o(W(),Z):W;if(X)zB(Q,Z,X);if(Z.postProcess){let q=Z.postProcess(X,Q,Z);return Y.jsonSchema=X,q}return Y.jsonSchema=X,X}var GB=(Q,Z)=>{switch(Z.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:_Z(Z.currentPath,Q.path)};case"none":case"seen":if(Q.path.length<Z.currentPath.length&&Q.path.every(($,J)=>Z.currentPath[J]===$))return console.warn(`Recursive reference detected at ${Z.currentPath.join("/")}! Defaulting to any`),O0(Z);return Z.$refStrategy==="seen"?O0(Z):void 0}},zB=(Q,Z,$)=>{if(Q.description){if($.description=Q.description,Z.markdownDescription)$.markdownDescription=Q.description}return $};var u4=(Q,Z)=>{let $=B4(Z),J=typeof Z==="object"&&Z.definitions?Object.entries(Z.definitions).reduce((G,[z,K])=>({...G,[z]:o(K._def,{...$,currentPath:[...$.basePath,$.definitionPath,z]},!0)??O0($)}),{}):void 0,Y=typeof Z==="string"?Z:Z?.nameStrategy==="title"?void 0:Z?.name,W=o(Q._def,Y===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,Y]},!1)??O0($),X=typeof Z==="object"&&Z.name!==void 0&&Z.nameStrategy==="title"?Z.name:void 0;if(X!==void 0)W.title=X;if($.flags.hasReferencedOpenAiAnyType){if(!J)J={};if(!J[$.openAiAnyTypeName])J[$.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:$.$refStrategy==="relative"?"1":[...$.basePath,$.definitionPath,$.openAiAnyTypeName].join("/")}}}let q=Y===void 0?J?{...W,[$.definitionPath]:J}:W:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,Y].join("/"),[$.definitionPath]:{...J,[Y]:W}};if($.target==="jsonSchema7")q.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09"||$.target==="openAi")q.$schema="https://json-schema.org/draft/2019-09/schema#";if($.target==="openAi"&&(("anyOf"in q)||("oneOf"in q)||("allOf"in q)||("type"in q)&&Array.isArray(q.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return q};var Bq=_({Validator:()=>xZ,deepCompareStrict:()=>N9,toJsonSchema:()=>M0,validatesOnlyStrings:()=>f1});function M0(Q,Z){if(w9(Q)&&!H0(Q))return Q["~standard"].jsonSchema.input({target:"draft-07"});if(H0(Q)){let $=V9(Q,!0);if(lQ($))return p4(y1($,!0),Z);else return p4(Q,Z)}if(x0(Q))return u4(Q);return Q}function f1(Q){if(!Q||typeof Q!=="object"||Object.keys(Q).length===0||Array.isArray(Q))return!1;if("type"in Q){if(typeof Q.type==="string")return Q.type==="string";if(Array.isArray(Q.type))return Q.type.every((Z)=>Z==="string");return!1}if("enum"in Q)return Array.isArray(Q.enum)&&Q.enum.length>0&&Q.enum.every((Z)=>typeof Z==="string");if("const"in Q)return typeof Q.const==="string";if("allOf"in Q&&Array.isArray(Q.allOf))return Q.allOf.some((Z)=>f1(Z));if("anyOf"in Q&&Array.isArray(Q.anyOf)||"oneOf"in Q&&Array.isArray(Q.oneOf)){let Z="anyOf"in Q?Q.anyOf:Q.oneOf;return Z.length>0&&Z.every(($)=>f1($))}if("not"in Q)return!1;if("$ref"in Q&&typeof Q.$ref==="string"){let Z=Q.$ref,$=Hq(Q);if($[Z])return f1($[Z]);return!1}return!1}/*!
58
+ * https://github.com/Starcounter-Jack/JSON-Patch
59
+ * (c) 2017-2022 Joachim Wester
60
+ * MIT licensed
61
+ */var KB=Object.prototype.hasOwnProperty;function E9(Q,Z){return KB.call(Q,Z)}function j9(Q){if(Array.isArray(Q)){let $=Array(Q.length);for(let J=0;J<$.length;J++)$[J]=""+J;return $}if(Object.keys)return Object.keys(Q);let Z=[];for(let $ in Q)if(E9(Q,$))Z.push($);return Z}function OQ(Q){switch(typeof Q){case"object":return JSON.parse(JSON.stringify(Q));case"undefined":return null;default:return Q}}function R9(Q){let Z=0,$=Q.length,J;while(Z<$){if(J=Q.charCodeAt(Z),J>=48&&J<=57){Z++;continue}return!1}return!0}function Q6(Q){if(Q.indexOf("/")===-1&&Q.indexOf("~")===-1)return Q;return Q.replace(/~/g,"~0").replace(/\//g,"~1")}function _9(Q){return Q.replace(/~1/g,"/").replace(/~0/g,"~")}function O9(Q){if(Q===void 0)return!0;if(Q){if(Array.isArray(Q)){for(let $=0,J=Q.length;$<J;$++)if(O9(Q[$]))return!0}else if(typeof Q==="object"){let $=j9(Q),J=$.length;for(var Z=0;Z<J;Z++)if(O9(Q[$[Z]]))return!0}}return!1}function Dq(Q,Z){let $=[Q];for(let J in Z){let Y=typeof Z[J]==="object"?JSON.stringify(Z[J],null,2):Z[J];if(typeof Y<"u")$.push(`${J}: ${Y}`)}return $.join(`
62
+ `)}var I9=class extends Error{constructor(Q,Z,$,J,Y){super(Dq(Q,{name:Z,index:$,operation:J,tree:Y}));this.name=Z,this.index=$,this.operation=J,this.tree=Y,Object.setPrototypeOf(this,new.target.prototype),this.message=Dq(Q,{name:Z,index:$,operation:J,tree:Y})}};var Vq=_({JsonPatchError:()=>C0,_areEquals:()=>g1,applyOperation:()=>S6,applyPatch:()=>Z6,applyReducer:()=>Fq,deepClone:()=>UB,getValueByPointer:()=>MZ,validate:()=>c4,validator:()=>vZ}),C0=I9,UB=OQ,h1={add:function(Q,Z,$){if(Z==="__proto__"||Z==="constructor")throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return Q[Z]=this.value,{newDocument:$}},remove:function(Q,Z,$){if(Z==="__proto__"||Z==="constructor")throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var J=Q[Z];return delete Q[Z],{newDocument:$,removed:J}},replace:function(Q,Z,$){if(Z==="__proto__"||Z==="constructor")throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var J=Q[Z];return Q[Z]=this.value,{newDocument:$,removed:J}},move:function(Q,Z,$){let J=MZ($,this.path);if(J)J=OQ(J);let Y=S6($,{op:"remove",path:this.from}).removed;return S6($,{op:"add",path:this.path,value:Y}),{newDocument:$,removed:J}},copy:function(Q,Z,$){let J=MZ($,this.from);return S6($,{op:"add",path:this.path,value:OQ(J)}),{newDocument:$}},test:function(Q,Z,$){return{newDocument:$,test:g1(Q[Z],this.value)}},_get:function(Q,Z,$){return this.value=Q[Z],{newDocument:$}}},HB={add:function(Q,Z,$){if(R9(Z))Q.splice(Z,0,this.value);else Q[Z]=this.value;return{newDocument:$,index:Z}},remove:function(Q,Z,$){return{newDocument:$,removed:Q.splice(Z,1)[0]}},replace:function(Q,Z,$){var J=Q[Z];return Q[Z]=this.value,{newDocument:$,removed:J}},move:h1.move,copy:h1.copy,test:h1.test,_get:h1._get};function MZ(Q,Z){if(Z=="")return Q;var $={op:"_get",path:Z};return S6(Q,$),$.value}function S6(Q,Z,$=!1,J=!0,Y=!0,W=0){if($)if(typeof $=="function")$(Z,0,Q,Z.path);else vZ(Z,0);if(Z.path===""){let X={newDocument:Q};if(Z.op==="add")return X.newDocument=Z.value,X;else if(Z.op==="replace")return X.newDocument=Z.value,X.removed=Q,X;else if(Z.op==="move"||Z.op==="copy"){if(X.newDocument=MZ(Q,Z.from),Z.op==="move")X.removed=Q;return X}else if(Z.op==="test"){if(X.test=g1(Q,Z.value),X.test===!1)throw new C0("Test operation failed","TEST_OPERATION_FAILED",W,Z,Q);return X.newDocument=Q,X}else if(Z.op==="remove")return X.removed=Q,X.newDocument=null,X;else if(Z.op==="_get")return Z.value=Q,X;else if($)throw new C0("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",W,Z,Q);else return X}else{if(!J)Q=OQ(Q);let X=(Z.path||"").split("/"),q=Q,G=1,z=X.length,K=void 0,U,H;if(typeof $=="function")H=$;else H=vZ;while(!0){if(U=X[G],U&&U.indexOf("~")!=-1)U=_9(U);if(Y&&(U=="__proto__"||U=="prototype"&&G>0&&X[G-1]=="constructor"))throw TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if($){if(K===void 0){if(q[U]===void 0)K=X.slice(0,G).join("/");else if(G==z-1)K=Z.path;if(K!==void 0)H(Z,0,Q,K)}}if(G++,Array.isArray(q)){if(U==="-")U=q.length;else if($&&!R9(U))throw new C0("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",W,Z,Q);else if(R9(U))U=~~U;if(G>=z){if($&&Z.op==="add"&&U>q.length)throw new C0("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",W,Z,Q);let B=HB[Z.op].call(Z,q,U,Q);if(B.test===!1)throw new C0("Test operation failed","TEST_OPERATION_FAILED",W,Z,Q);return B}}else if(G>=z){let B=h1[Z.op].call(Z,q,U,Q);if(B.test===!1)throw new C0("Test operation failed","TEST_OPERATION_FAILED",W,Z,Q);return B}if(q=q[U],$&&G<z&&(!q||typeof q!=="object"))throw new C0("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",W,Z,Q)}}}function Z6(Q,Z,$,J=!0,Y=!0){if($){if(!Array.isArray(Z))throw new C0("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY")}if(!J)Q=OQ(Q);let W=Array(Z.length);for(let X=0,q=Z.length;X<q;X++)W[X]=S6(Q,Z[X],$,!0,Y,X),Q=W[X].newDocument;return W.newDocument=Q,W}function Fq(Q,Z,$){let J=S6(Q,Z);if(J.test===!1)throw new C0("Test operation failed","TEST_OPERATION_FAILED",$,Z,Q);return J.newDocument}function vZ(Q,Z,$,J){if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw new C0("Operation is not an object","OPERATION_NOT_AN_OBJECT",Z,Q,$);else if(!h1[Q.op])throw new C0("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",Z,Q,$);else if(typeof Q.path!=="string")throw new C0("Operation `path` property is not a string","OPERATION_PATH_INVALID",Z,Q,$);else if(Q.path.indexOf("/")!==0&&Q.path.length>0)throw new C0('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",Z,Q,$);else if((Q.op==="move"||Q.op==="copy")&&typeof Q.from!=="string")throw new C0("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",Z,Q,$);else if((Q.op==="add"||Q.op==="replace"||Q.op==="test")&&Q.value===void 0)throw new C0("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",Z,Q,$);else if((Q.op==="add"||Q.op==="replace"||Q.op==="test")&&O9(Q.value))throw new C0("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",Z,Q,$);else if($){if(Q.op=="add"){var Y=Q.path.split("/").length,W=J.split("/").length;if(Y!==W+1&&Y!==W)throw new C0("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",Z,Q,$)}else if(Q.op==="replace"||Q.op==="remove"||Q.op==="_get"){if(Q.path!==J)throw new C0("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",Z,Q,$)}else if(Q.op==="move"||Q.op==="copy"){var X=c4([{op:"_get",path:Q.from,value:void 0}],$);if(X&&X.name==="OPERATION_PATH_UNRESOLVABLE")throw new C0("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",Z,Q,$)}}}function c4(Q,Z,$){try{if(!Array.isArray(Q))throw new C0("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(Z)Z6(OQ(Z),OQ(Q),$||!0);else{$=$||vZ;for(var J=0;J<Q.length;J++)$(Q[J],J,Z,void 0)}}catch(Y){if(Y instanceof C0)return Y;else throw Y}}function g1(Q,Z){if(Q===Z)return!0;if(Q&&Z&&typeof Q=="object"&&typeof Z=="object"){var $=Array.isArray(Q),J=Array.isArray(Z),Y,W,X;if($&&J){if(W=Q.length,W!=Z.length)return!1;for(Y=W;Y--!==0;)if(!g1(Q[Y],Z[Y]))return!1;return!0}if($!=J)return!1;var q=Object.keys(Q);if(W=q.length,W!==Object.keys(Z).length)return!1;for(Y=W;Y--!==0;)if(!Z.hasOwnProperty(q[Y]))return!1;for(Y=W;Y--!==0;)if(X=q[Y],!g1(Q[X],Z[X]))return!1;return!0}return Q!==Q&&Z!==Z}/*!
63
+ * https://github.com/Starcounter-Jack/JSON-Patch
64
+ * (c) 2013-2021 Joachim Wester
65
+ * MIT license
66
+ */function Lq(Q,Z,$,J,Y){if(Z===Q)return;if(typeof Z.toJSON==="function")Z=Z.toJSON();var W=j9(Z),X=j9(Q),q=!1;for(var G=X.length-1;G>=0;G--){var z=X[G],K=Q[z];if(E9(Z,z)&&!(Z[z]===void 0&&K!==void 0&&Array.isArray(Z)===!1)){var U=Z[z];if(typeof K=="object"&&K!=null&&typeof U=="object"&&U!=null&&Array.isArray(K)===Array.isArray(U))Lq(K,U,$,J+"/"+Q6(z),Y);else if(K!==U){if(Y)$.push({op:"test",path:J+"/"+Q6(z),value:OQ(K)});$.push({op:"replace",path:J+"/"+Q6(z),value:OQ(U)})}}else if(Array.isArray(Q)===Array.isArray(Z)){if(Y)$.push({op:"test",path:J+"/"+Q6(z),value:OQ(K)});$.push({op:"remove",path:J+"/"+Q6(z)}),q=!0}else{if(Y)$.push({op:"test",path:J,value:Q});$.push({op:"replace",path:J,value:Z})}}if(!q&&W.length==X.length)return;for(var G=0;G<W.length;G++){var z=W[G];if(!E9(Q,z)&&Z[z]!==void 0)$.push({op:"add",path:J+"/"+Q6(z),value:OQ(Z[z])})}}function $6(Q,Z,$=!1){var J=[];return Lq(Q,Z,J,"",$),J}var OR={...Vq,JsonPatchError:I9,deepClone:OQ,escapePathComponent:Q6,unescapePathComponent:_9};var Pq=_({LogStreamCallbackHandler:()=>S9,RunLog:()=>T9,RunLogPatch:()=>v8,isLogStreamHandler:()=>l4}),v8=class{ops;constructor(Q){this.ops=Q.ops??[]}concat(Q){let Z=this.ops.concat(Q.ops),$=Z6({},Z);return new T9({ops:Z,state:$[$.length-1].newDocument})}},T9=class Q extends v8{state;constructor(Z){super(Z);this.state=Z.state}concat(Z){let $=this.ops.concat(Z.ops),J=Z6(this.state,Z.ops);return new Q({ops:$,state:J[J.length-1].newDocument})}static fromRunLogPatch(Z){let $=Z6({},Z.ops);return new Q({ops:Z.ops,state:$[$.length-1].newDocument})}},l4=(Q)=>Q.name==="log_stream_tracer";async function wq(Q,Z){if(Z==="original")throw Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");let{inputs:$}=Q;if(["retriever","llm","prompt"].includes(Q.run_type))return $;if(Object.keys($).length===1&&$?.input==="")return;return $.input}async function Aq(Q,Z){let{outputs:$}=Q;if(Z==="original")return $;if(["retriever","llm","prompt"].includes(Q.run_type))return $;if($!==void 0&&Object.keys($).length===1&&$?.output!==void 0)return $.output;return $}function BB(Q){return Q!==void 0&&Q.message!==void 0}var S9=class extends WQ{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(Q){super({_awaitHandler:!0,...Q});this.autoClose=Q?.autoClose??!0,this.includeNames=Q?.includeNames,this.includeTypes=Q?.includeTypes,this.includeTags=Q?.includeTags,this.excludeNames=Q?.excludeNames,this.excludeTypes=Q?.excludeTypes,this.excludeTags=Q?.excludeTags,this._schemaFormat=Q?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=S0.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(Q){}_includeRun(Q){if(Q.id===this.rootId)return!1;let Z=Q.tags??[],$=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;if(this.includeNames!==void 0)$=$||this.includeNames.includes(Q.name);if(this.includeTypes!==void 0)$=$||this.includeTypes.includes(Q.run_type);if(this.includeTags!==void 0)$=$||Z.find((J)=>this.includeTags?.includes(J))!==void 0;if(this.excludeNames!==void 0)$=$&&!this.excludeNames.includes(Q.name);if(this.excludeTypes!==void 0)$=$&&!this.excludeTypes.includes(Q.run_type);if(this.excludeTags!==void 0)$=$&&Z.every((J)=>!this.excludeTags?.includes(J));return $}async*tapOutputIterable(Q,Z){for await(let $ of Z){if(Q!==this.rootId){let J=this.keyMapByRunId[Q];if(J)await this.writer.write(new v8({ops:[{op:"add",path:`/logs/${J}/streamed_output/-`,value:$}]}))}yield $}}async onRunCreate(Q){if(this.rootId===void 0)this.rootId=Q.id,await this.writer.write(new v8({ops:[{op:"replace",path:"",value:{id:Q.id,name:Q.name,type:Q.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}));if(!this._includeRun(Q))return;if(this.counterMapByRunName[Q.name]===void 0)this.counterMapByRunName[Q.name]=0;this.counterMapByRunName[Q.name]+=1;let Z=this.counterMapByRunName[Q.name];this.keyMapByRunId[Q.id]=Z===1?Q.name:`${Q.name}:${Z}`;let $={id:Q.id,name:Q.name,type:Q.run_type,tags:Q.tags??[],metadata:Q.extra?.metadata??{},start_time:new Date(Q.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};if(this._schemaFormat==="streaming_events")$.inputs=await wq(Q,this._schemaFormat);await this.writer.write(new v8({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[Q.id]}`,value:$}]}))}async onRunUpdate(Q){try{let Z=this.keyMapByRunId[Q.id];if(Z===void 0)return;let $=[];if(this._schemaFormat==="streaming_events")$.push({op:"replace",path:`/logs/${Z}/inputs`,value:await wq(Q,this._schemaFormat)});if($.push({op:"add",path:`/logs/${Z}/final_output`,value:await Aq(Q,this._schemaFormat)}),Q.end_time!==void 0)$.push({op:"add",path:`/logs/${Z}/end_time`,value:new Date(Q.end_time).toISOString()});let J=new v8({ops:$});await this.writer.write(J)}finally{if(Q.id===this.rootId){let Z=new v8({ops:[{op:"replace",path:"/final_output",value:await Aq(Q,this._schemaFormat)}]});if(await this.writer.write(Z),this.autoClose)await this.writer.close()}}}async onLLMNewToken(Q,Z,$){let J=this.keyMapByRunId[Q.id];if(J===void 0)return;let Y=Q.inputs.messages!==void 0,W;if(Y)if(BB($?.chunk))W=$?.chunk;else W=new y0({id:`run-${Q.id}`,content:Z});else W=Z;let X=new v8({ops:[{op:"add",path:`/logs/${J}/streamed_output_str/-`,value:Z},{op:"add",path:`/logs/${J}/streamed_output/-`,value:W}]});await this.writer.write(X)}};function x9({name:Q,serialized:Z}){if(Q!==void 0)return Q;if(Z?.name!==void 0)return Z.name;else if(Z?.id!==void 0&&Array.isArray(Z?.id))return Z.id[Z.id.length-1];return"Unnamed"}var Nq=(Q)=>Q.name==="event_stream_tracer",Oq=class extends WQ{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(Q){super({_awaitHandler:!0,...Q});this.autoClose=Q?.autoClose??!0,this.includeNames=Q?.includeNames,this.includeTypes=Q?.includeTypes,this.includeTags=Q?.includeTags,this.excludeNames=Q?.excludeNames,this.excludeTypes=Q?.excludeTypes,this.excludeTags=Q?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=S0.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(Q){}_includeRun(Q){let Z=Q.tags??[],$=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;if(this.includeNames!==void 0)$=$||this.includeNames.includes(Q.name);if(this.includeTypes!==void 0)$=$||this.includeTypes.includes(Q.runType);if(this.includeTags!==void 0)$=$||Z.find((J)=>this.includeTags?.includes(J))!==void 0;if(this.excludeNames!==void 0)$=$&&!this.excludeNames.includes(Q.name);if(this.excludeTypes!==void 0)$=$&&!this.excludeTypes.includes(Q.runType);if(this.excludeTags!==void 0)$=$&&Z.every((J)=>!this.excludeTags?.includes(J));return $}async*tapOutputIterable(Q,Z){let $=await Z.next();if($.done)return;let J=this.runInfoMap.get(Q);if(J===void 0){yield $.value;return}function Y(X,q){if(X==="llm"&&typeof q==="string")return new a8({text:q});return q}let W=this.tappedPromises.get(Q);if(W===void 0){let X;W=new Promise((q)=>{X=q}),this.tappedPromises.set(Q,W);try{let q={event:`on_${J.runType}_stream`,run_id:Q,name:J.name,tags:J.tags,metadata:J.metadata,data:{}};await this.send({...q,data:{chunk:Y(J.runType,$.value)}},J),yield $.value;for await(let G of Z){if(J.runType!=="tool"&&J.runType!=="retriever")await this.send({...q,data:{chunk:Y(J.runType,G)}},J);yield G}}finally{X?.()}}else{yield $.value;for await(let X of Z)yield X}}async send(Q,Z){if(this.readableStreamClosed)return;if(this._includeRun(Z))await this.writer.write(Q)}async sendEndEvent(Q,Z){let $=this.tappedPromises.get(Q.run_id);if($!==void 0)$.then(()=>{this.send(Q,Z)});else await this.send(Q,Z)}async onLLMStart(Q){let Z=x9(Q),$=Q.inputs.messages!==void 0?"chat_model":"llm",J={tags:Q.tags??[],metadata:Q.extra?.metadata??{},name:Z,runType:$,inputs:Q.inputs};this.runInfoMap.set(Q.id,J);let Y=`on_${$}_start`;await this.send({event:Y,data:{input:Q.inputs},name:Z,tags:Q.tags??[],run_id:Q.id,metadata:Q.extra?.metadata??{}},J)}async onLLMNewToken(Q,Z,$){let J=this.runInfoMap.get(Q.id),Y,W;if(J===void 0)throw Error(`onLLMNewToken: Run ID ${Q.id} not found in run map.`);if(this.runInfoMap.size===1)return;if(J.runType==="chat_model")if(W="on_chat_model_stream",$?.chunk===void 0)Y=new y0({content:Z,id:`run-${Q.id}`});else Y=$.chunk.message;else if(J.runType==="llm")if(W="on_llm_stream",$?.chunk===void 0)Y=new a8({text:Z});else Y=$.chunk;else throw Error(`Unexpected run type ${J.runType}`);await this.send({event:W,data:{chunk:Y},run_id:Q.id,name:J.name,tags:J.tags,metadata:J.metadata},J)}async onLLMEnd(Q){let Z=this.runInfoMap.get(Q.id);this.runInfoMap.delete(Q.id);let $;if(Z===void 0)throw Error(`onLLMEnd: Run ID ${Q.id} not found in run map.`);let J=Q.outputs?.generations,Y;if(Z.runType==="chat_model"){for(let W of J??[]){if(Y!==void 0)break;Y=W[0]?.message}$="on_chat_model_end"}else if(Z.runType==="llm")Y={generations:J?.map((W)=>{return W.map((X)=>{return{text:X.text,generationInfo:X.generationInfo}})}),llmOutput:Q.outputs?.llmOutput??{}},$="on_llm_end";else throw Error(`onLLMEnd: Unexpected run type: ${Z.runType}`);await this.sendEndEvent({event:$,data:{output:Y,input:Z.inputs},run_id:Q.id,name:Z.name,tags:Z.tags,metadata:Z.metadata},Z)}async onChainStart(Q){let Z=x9(Q),$=Q.run_type??"chain",J={tags:Q.tags??[],metadata:Q.extra?.metadata??{},name:Z,runType:Q.run_type},Y={};if(Q.inputs.input===""&&Object.keys(Q.inputs).length===1)Y={},J.inputs={};else if(Q.inputs.input!==void 0)Y.input=Q.inputs.input,J.inputs=Q.inputs.input;else Y.input=Q.inputs,J.inputs=Q.inputs;this.runInfoMap.set(Q.id,J),await this.send({event:`on_${$}_start`,data:Y,name:Z,tags:Q.tags??[],run_id:Q.id,metadata:Q.extra?.metadata??{}},J)}async onChainEnd(Q){let Z=this.runInfoMap.get(Q.id);if(this.runInfoMap.delete(Q.id),Z===void 0)throw Error(`onChainEnd: Run ID ${Q.id} not found in run map.`);let $=`on_${Q.run_type}_end`,J=Q.inputs??Z.inputs??{},Y={output:Q.outputs?.output??Q.outputs,input:J};if(J.input&&Object.keys(J).length===1)Y.input=J.input,Z.inputs=J.input;await this.sendEndEvent({event:$,data:Y,run_id:Q.id,name:Z.name,tags:Z.tags,metadata:Z.metadata??{}},Z)}async onToolStart(Q){let Z=x9(Q),$={tags:Q.tags??[],metadata:Q.extra?.metadata??{},name:Z,runType:"tool",inputs:Q.inputs??{}};this.runInfoMap.set(Q.id,$),await this.send({event:"on_tool_start",data:{input:Q.inputs??{}},name:Z,run_id:Q.id,tags:Q.tags??[],metadata:Q.extra?.metadata??{}},$)}async onToolEnd(Q){let Z=this.runInfoMap.get(Q.id);if(this.runInfoMap.delete(Q.id),Z===void 0)throw Error(`onToolEnd: Run ID ${Q.id} not found in run map.`);if(Z.inputs===void 0)throw Error(`onToolEnd: Run ID ${Q.id} is a tool call, and is expected to have traced inputs.`);let $=Q.outputs?.output===void 0?Q.outputs:Q.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:$,input:Z.inputs},run_id:Q.id,name:Z.name,tags:Z.tags,metadata:Z.metadata},Z)}async onToolError(Q){let Z=this.runInfoMap.get(Q.id);if(this.runInfoMap.delete(Q.id),Z===void 0)throw Error(`onToolEnd: Run ID ${Q.id} not found in run map.`);if(Z.inputs===void 0)throw Error(`onToolEnd: Run ID ${Q.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:Z.inputs,error:Q.error},run_id:Q.id,name:Z.name,tags:Z.tags,metadata:Z.metadata},Z)}async onRetrieverStart(Q){let Z=x9(Q),$={tags:Q.tags??[],metadata:Q.extra?.metadata??{},name:Z,runType:"retriever",inputs:{query:Q.inputs.query}};this.runInfoMap.set(Q.id,$),await this.send({event:"on_retriever_start",data:{input:{query:Q.inputs.query}},name:Z,tags:Q.tags??[],run_id:Q.id,metadata:Q.extra?.metadata??{}},$)}async onRetrieverEnd(Q){let Z=this.runInfoMap.get(Q.id);if(this.runInfoMap.delete(Q.id),Z===void 0)throw Error(`onRetrieverEnd: Run ID ${Q.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:Q.outputs?.documents??Q.outputs,input:Z.inputs},run_id:Q.id,name:Z.name,tags:Z.tags,metadata:Z.metadata},Z)}async handleCustomEvent(Q,Z,$){let J=this.runInfoMap.get($);if(J===void 0)throw Error(`handleCustomEvent: Run ID ${$} not found in run map.`);await this.send({event:"on_custom_event",run_id:$,name:Q,tags:J.tags,metadata:J.metadata,data:Z},J)}async finish(){let Q=[...this.tappedPromises.values()];Promise.all(Q).finally(()=>{this.writer.close()})}};var DB=Object.prototype.toString,VB=(Q)=>DB.call(Q)==="[object Error]",FB=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Eq(Q){if(!(Q&&VB(Q)&&Q.name==="TypeError"&&typeof Q.message==="string"))return!1;let{message:Z,stack:$}=Q;if(Z==="Load failed")return $===void 0||"__sentry_captured__"in Q;if(Z.startsWith("error sending request for url"))return!0;return FB.has(Z)}function LB(Q){if(typeof Q==="number"){if(Q<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(Q))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(Q!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function M9(Q,Z,{min:$=0,allowInfinity:J=!1}={}){if(Z===void 0)return;if(typeof Z!=="number"||Number.isNaN(Z))throw TypeError(`Expected \`${Q}\` to be a number${J?" or Infinity":""}.`);if(!J&&!Number.isFinite(Z))throw TypeError(`Expected \`${Q}\` to be a finite number.`);if(Z<$)throw TypeError(`Expected \`${Q}\` to be ≥ ${$}.`)}var wB=class extends Error{constructor(Q){super();if(Q instanceof Error)this.originalError=Q,{message:Q}=Q;else this.originalError=Error(Q),this.originalError.stack=this.stack;this.name="AbortError",this.message=Q}};function AB(Q,Z){let $=Math.max(1,Q+1),J=Z.randomize?Math.random()+1:1,Y=Math.round(J*Z.minTimeout*Z.factor**($-1));return Y=Math.min(Y,Z.maxTimeout),Y}function jq(Q,Z){if(!Number.isFinite(Z))return Z;return Z-(performance.now()-Q)}async function PB({error:Q,attemptNumber:Z,retriesConsumed:$,startTime:J,options:Y}){let W=Q instanceof Error?Q:TypeError(`Non-error was thrown: "${Q}". You should only throw errors.`);if(W instanceof wB)throw W.originalError;let X=Number.isFinite(Y.retries)?Math.max(0,Y.retries-$):Y.retries,q=Y.maxRetryTime??Number.POSITIVE_INFINITY,G=Object.freeze({error:W,attemptNumber:Z,retriesLeft:X,retriesConsumed:$});if(await Y.onFailedAttempt(G),jq(J,q)<=0)throw W;let z=await Y.shouldConsumeRetry(G),K=jq(J,q);if(K<=0||X<=0)throw W;if(W instanceof TypeError&&!Eq(W)){if(z)throw W;return Y.signal?.throwIfAborted(),!1}if(!await Y.shouldRetry(G))throw W;if(!z)return Y.signal?.throwIfAborted(),!1;let U=AB($,Y),H=Math.min(U,K);if(H>0)await new Promise((B,F)=>{let w=()=>{clearTimeout(A),Y.signal?.removeEventListener("abort",w),F(Y.signal.reason)},A=setTimeout(()=>{Y.signal?.removeEventListener("abort",w),B()},H);if(Y.unref)A.unref?.();Y.signal?.addEventListener("abort",w,{once:!0})});return Y.signal?.throwIfAborted(),!0}async function yZ(Q,Z={}){if(Z={...Z},LB(Z.retries),Object.hasOwn(Z,"forever"))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");if(Z.retries??=10,Z.factor??=2,Z.minTimeout??=1000,Z.maxTimeout??=Number.POSITIVE_INFINITY,Z.maxRetryTime??=Number.POSITIVE_INFINITY,Z.randomize??=!1,Z.onFailedAttempt??=()=>{},Z.shouldRetry??=()=>!0,Z.shouldConsumeRetry??=()=>!0,M9("factor",Z.factor,{min:0,allowInfinity:!1}),M9("minTimeout",Z.minTimeout,{min:0,allowInfinity:!1}),M9("maxTimeout",Z.maxTimeout,{min:0,allowInfinity:!0}),M9("maxRetryTime",Z.maxRetryTime,{min:0,allowInfinity:!0}),!(Z.factor>0))Z.factor=1;Z.signal?.throwIfAborted();let $=0,J=0,Y=performance.now();while(Number.isFinite(Z.retries)?J<=Z.retries:!0){$++;try{Z.signal?.throwIfAborted();let W=await Q($);return Z.signal?.throwIfAborted(),W}catch(W){if(await PB({error:W,attemptNumber:$,retriesConsumed:J,startTime:Y,options:Z}))J++}}throw Error("Retry attempts exhausted without throwing an error.")}var v9=i6(hY(),1),Rq=_({AsyncCaller:()=>J6}),NB=[400,401,402,403,404,405,406,407,409],OB=(Q)=>{if(typeof Q!=="object"||Q===null)return;if("message"in Q&&typeof Q.message==="string"&&(Q.message.startsWith("Cancel")||Q.message.startsWith("AbortError"))||"name"in Q&&typeof Q.name==="string"&&Q.name==="AbortError")throw Q;if("code"in Q&&typeof Q.code==="string"&&Q.code==="ECONNABORTED")throw Q;let Z="response"in Q&&typeof Q.response==="object"&&Q.response!==null&&"status"in Q.response&&typeof Q.response.status==="number"?Q.response.status:void 0,$="status"in Q&&typeof Q.status==="number"?Q.status:void 0,J=Z??$;if(J&&NB.includes(+J))throw Q;if(("error"in Q&&typeof Q.error==="object"&&Q.error!==null&&"code"in Q.error&&typeof Q.error.code==="string"?Q.error.code:void 0)==="insufficient_quota"){let Y=Error("message"in Q&&typeof Q.message==="string"?Q.message:"Insufficient quota");throw Y.name="InsufficientQuotaError",Y}},J6=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(Q){this.maxConcurrency=Q.maxConcurrency??1/0,this.maxRetries=Q.maxRetries??6,this.onFailedAttempt=Q.onFailedAttempt??OB,this.queue=new("default"in v9.default?v9.default.default:v9.default)({concurrency:this.maxConcurrency})}async call(Q,...Z){return this.queue.add(()=>yZ(()=>Q(...Z).catch(($)=>{if($ instanceof Error)throw $;else throw Error($)}),{onFailedAttempt:({error:$})=>this.onFailedAttempt?.($),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(Q,Z,...$){if(Q.signal){let J;return Promise.race([this.call(Z,...$),new Promise((Y,W)=>{J=()=>{W(j6(Q.signal))},Q.signal?.addEventListener("abort",J,{once:!0})})]).finally(()=>{if(Q.signal&&J)Q.signal.removeEventListener("abort",J)})}return this.call(Z,...$)}fetch(...Q){return this.call(()=>fetch(...Q).then((Z)=>Z.ok?Z:Promise.reject(Z)))}};var i4=class extends WQ{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:Q,onStart:Z,onEnd:$,onError:J}){super({_awaitHandler:!0});this.config=Q,this.argOnStart=Z,this.argOnEnd=$,this.argOnError=J}persistRun(Q){return Promise.resolve()}async onRunCreate(Q){if(this.rootId)return;if(this.rootId=Q.id,this.argOnStart)await this.argOnStart(Q,this.config)}async onRunUpdate(Q){if(Q.id!==this.rootId)return;if(!Q.error){if(this.argOnEnd)await this.argOnEnd(Q,this.config)}else if(this.argOnError)await this.argOnError(Q,this.config)}};function CZ(Q){return Q?Q.lc_runnable:!1}var _q=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(Q){this.includeNames=Q.includeNames,this.includeTypes=Q.includeTypes,this.includeTags=Q.includeTags,this.excludeNames=Q.excludeNames,this.excludeTypes=Q.excludeTypes,this.excludeTags=Q.excludeTags}includeEvent(Q,Z){let $=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,J=Q.tags??[];if(this.includeNames!==void 0)$=$||this.includeNames.includes(Q.name);if(this.includeTypes!==void 0)$=$||this.includeTypes.includes(Z);if(this.includeTags!==void 0)$=$||J.some((Y)=>this.includeTags?.includes(Y));if(this.excludeNames!==void 0)$=$&&!this.excludeNames.includes(Q.name);if(this.excludeTypes!==void 0)$=$&&!this.excludeTypes.includes(Z);if(this.excludeTags!==void 0)$=$&&J.every((Y)=>!this.excludeTags?.includes(Y));return $}},Iq=(Q)=>{return btoa(Q).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")};function o4(Q){return Q.replace(/[^a-zA-Z-_0-9]/g,"_")}var EB=["*","_","`"];function jB(Q){let Z="";for(let[$,J]of Object.entries(Q))Z+=` classDef ${$} ${J};
67
+ `;return Z}function Tq(Q,Z,$){let{firstNode:J,lastNode:Y,nodeColors:W,withStyles:X=!0,curveStyle:q="linear",wrapLabelNWords:G=9}=$??{},z=X?`%%{init: {'flowchart': {'curve': '${q}'}}}%%
68
+ graph TD;
69
+ `:`graph TD;
70
+ `;if(X){let w={["default"]:"{0}({1})"};if(J!==void 0)w[J]="{0}([{1}]):::first";if(Y!==void 0)w[Y]="{0}([{1}]):::last";for(let[A,E]of Object.entries(Q)){let P=E.name.split(":").pop()??"",j=EB.some((k)=>P.startsWith(k)&&P.endsWith(k))?`<p>${P}</p>`:P;if(Object.keys(E.metadata??{}).length)j+=`<hr/><small><em>${Object.entries(E.metadata??{}).map(([k,b])=>`${k} = ${b}`).join(`
71
+ `)}</em></small>`;let R=(w[A]??w.default).replace("{0}",o4(A)).replace("{1}",j);z+=` ${R}
72
+ `}}let K={};for(let F of Z){let w=F.source.split(":"),A=F.target.split(":"),E=w.filter((P,j)=>P===A[j]).join(":");if(!K[E])K[E]=[];K[E].push(F)}let U=new Set;function H(F){return[...F].sort((w,A)=>{return w.split(":").length-A.split(":").length})}function B(F,w){let A=F.length===1&&F[0].source===F[0].target;if(w&&!A){let P=w.split(":").pop();if(U.has(w))throw Error(`Found duplicate subgraph '${P}' at '${w} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);U.add(w),z+=` subgraph ${P}
73
+ `}let E=H(Object.keys(K).filter((P)=>P.startsWith(`${w}:`)&&P!==w&&P.split(":").length===w.split(":").length+1));for(let P of E)B(K[P],P);for(let P of F){let{source:j,target:R,data:k,conditional:b}=P,T="";if(k!==void 0){let V=k,v=V.split(" ");if(v.length>G)V=Array.from({length:Math.ceil(v.length/G)},(I,y)=>v.slice(y*G,(y+1)*G).join(" ")).join("&nbsp;<br>&nbsp;");T=b?` -. &nbsp;${V}&nbsp; .-> `:` -- &nbsp;${V}&nbsp; --> `}else T=b?" -.-> ":" --> ";z+=` ${o4(j)}${T}${o4(R)};
74
+ `}if(w&&!A)z+=` end
75
+ `}B(K[""]??[],"");for(let F in K)if(!F.includes(":")&&F!=="")B(K[F],F);if(X)z+=jB(W??{});return z}async function Sq(Q,Z){let $=Z?.backgroundColor??"white",J=Z?.imageType??"png",Y=Iq(Q);if($!==void 0){if(!/^#(?:[0-9a-fA-F]{3}){1,2}$/.test($))$=`!${$}`}let W=`https://mermaid.ink/img/${Y}?bgColor=${$}&type=${J}`,X=await fetch(W);if(!X.ok)throw Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${X.status}`,`Status text: ${X.statusText}`].join(`
76
+ `));return await X.blob()}$8();var vq=_({Graph:()=>G1});function RB(Q,Z){if(Q!==void 0&&!x6(Q))return Q;else if(CZ(Z))try{let $=Z.getName();return $=$.startsWith("Runnable")?$.slice(8):$,$}catch{return Z.getName()}else return Z.name??"UnknownSchema"}function _B(Q){if(CZ(Q.data))return{type:"runnable",data:{id:Q.data.lc_id,name:Q.data.getName()}};else return{type:"schema",data:{...M0(Q.data.schema),title:Q.data.name}}}var G1=class Q{nodes={};edges=[];constructor(Z){this.nodes=Z?.nodes??this.nodes,this.edges=Z?.edges??this.edges}toJSON(){let Z={};return Object.values(this.nodes).forEach(($,J)=>{Z[$.id]=x6($.id)?J:$.id}),{nodes:Object.values(this.nodes).map(($)=>({id:Z[$.id],..._B($)})),edges:this.edges.map(($)=>{let J={source:Z[$.source],target:Z[$.target]};if(typeof $.data<"u")J.data=$.data;if(typeof $.conditional<"u")J.conditional=$.conditional;return J})}}addNode(Z,$,J){if($!==void 0&&this.nodes[$]!==void 0)throw Error(`Node with id ${$} already exists`);let Y=$??Y8(),W={id:Y,data:Z,name:RB($,Z),metadata:J};return this.nodes[Y]=W,W}removeNode(Z){delete this.nodes[Z.id],this.edges=this.edges.filter(($)=>$.source!==Z.id&&$.target!==Z.id)}addEdge(Z,$,J,Y){if(this.nodes[Z.id]===void 0)throw Error(`Source node ${Z.id} not in graph`);if(this.nodes[$.id]===void 0)throw Error(`Target node ${$.id} not in graph`);let W={source:Z.id,target:$.id,data:J,conditional:Y};return this.edges.push(W),W}firstNode(){return xq(this)}lastNode(){return Mq(this)}extend(Z,$=""){let J=$;if(Object.values(Z.nodes).map((G)=>G.id).every(x6))J="";let Y=(G)=>{return J?`${J}:${G}`:G};Object.entries(Z.nodes).forEach(([G,z])=>{this.nodes[Y(G)]={...z,id:Y(G)}});let W=Z.edges.map((G)=>{return{...G,source:Y(G.source),target:Y(G.target)}});this.edges=[...this.edges,...W];let X=Z.firstNode(),q=Z.lastNode();return[X?{id:Y(X.id),data:X.data}:void 0,q?{id:Y(q.id),data:q.data}:void 0]}trimFirstNode(){let Z=this.firstNode();if(Z&&xq(this,[Z.id]))this.removeNode(Z)}trimLastNode(){let Z=this.lastNode();if(Z&&Mq(this,[Z.id]))this.removeNode(Z)}reid(){let Z=Object.fromEntries(Object.values(this.nodes).map((Y)=>[Y.id,Y.name])),$=new Map;Object.values(Z).forEach((Y)=>{$.set(Y,($.get(Y)||0)+1)});let J=(Y)=>{let W=Z[Y];if(x6(Y)&&$.get(W)===1)return W;else return Y};return new Q({nodes:Object.fromEntries(Object.entries(this.nodes).map(([Y,W])=>[J(Y),{...W,id:J(Y)}])),edges:this.edges.map((Y)=>({...Y,source:J(Y.source),target:J(Y.target)}))})}drawMermaid(Z){let{withStyles:$,curveStyle:J,nodeColors:Y={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:W}=Z??{},X=this.reid(),q=X.firstNode(),G=X.lastNode();return Tq(X.nodes,X.edges,{firstNode:q?.id,lastNode:G?.id,withStyles:$,curveStyle:J,nodeColors:Y,wrapLabelNWords:W})}async drawMermaidPng(Z){return Sq(this.drawMermaid(Z),{backgroundColor:Z?.backgroundColor})}};function xq(Q,Z=[]){let $=new Set(Q.edges.filter((Y)=>!Z.includes(Y.source)).map((Y)=>Y.target)),J=[];for(let Y of Object.values(Q.nodes))if(!Z.includes(Y.id)&&!$.has(Y.id))J.push(Y);return J.length===1?J[0]:void 0}function Mq(Q,Z=[]){let $=new Set(Q.edges.filter((Y)=>!Z.includes(Y.target)).map((Y)=>Y.source)),J=[];for(let Y of Object.values(Q.nodes))if(!Z.includes(Y.id)&&!$.has(Y.id))J.push(Y);return J.length===1?J[0]:void 0}function yq(Q){let Z=new TextEncoder,$=new ReadableStream({async start(J){for await(let Y of Q)J.enqueue(Z.encode(`event: data
77
+ data: ${JSON.stringify(Y)}
78
+
79
+ `));J.enqueue(Z.encode(`event: end
80
+
81
+ `)),J.close()}});return S0.fromReadableStream($)}function n4(Q){return typeof Q==="object"&&Q!==null&&typeof Q[Symbol.iterator]==="function"&&typeof Q.next==="function"}var Cq=(Q)=>Q!=null&&typeof Q==="object"&&("next"in Q)&&typeof Q.next==="function";function y9(Q){return typeof Q==="object"&&Q!==null&&typeof Q[Symbol.asyncIterator]==="function"}function bq(Q){return Q!=null&&typeof Q==="object"&&typeof Q.next==="function"}async function kq(Q,Z){try{let $=await Q.next();while(!$.done)await Z?.($.value),$=await Q.next();return $.value}finally{await Q.return?.(void 0)}}function*r4(Q,Z){while(!0){let{value:$,done:J}=q0.runWithConfig(PQ(Q),Z.next.bind(Z),!0);if(J)break;else yield $}}async function*C9(Q,Z){let $=Z[Symbol.asyncIterator]();while(!0){let{value:J,done:Y}=await q0.runWithConfig(PQ(Q),$.next.bind(Z),!0);if(Y)break;else yield J}}$8();function l0(Q,Z){return Q&&!Array.isArray(Q)&&!(Q instanceof Date)&&typeof Q==="object"?Q:{[Z]:Q}}var c=class extends g0{lc_runnable=!0;name;getName(Q){let Z=this.name??this.constructor.lc_name()??this.constructor.name;return Q?`${Z}${Q}`:Z}withRetry(Q){return new k9({bound:this,kwargs:{},config:{},maxAttemptNumber:Q?.stopAfterAttempt,...Q})}withConfig(Q){return new b0({bound:this,config:Q,kwargs:{}})}withFallbacks(Q){let Z=Array.isArray(Q)?Q:Q.fallbacks;return new s4({runnable:this,fallbacks:Z})}_getOptionsList(Q,Z=0){if(Array.isArray(Q)&&Q.length!==Z)throw Error(`Passed "options" must be an array with the same length as the inputs, but got ${Q.length} options for ${Z} inputs`);if(Array.isArray(Q))return Q.map(t);if(Z>1&&!Array.isArray(Q)&&Q.runId){console.warn("Provided runId will be used only for the first element of the batch.");let $=Object.fromEntries(Object.entries(Q).filter(([J])=>J!=="runId"));return Array.from({length:Z},(J,Y)=>t(Y===0?Q:$))}return Array.from({length:Z},()=>t(Q))}async batch(Q,Z,$){let J=this._getOptionsList(Z??{},Q.length),Y=new J6({maxConcurrency:J[0]?.maxConcurrency??$?.maxConcurrency,onFailedAttempt:(X)=>{throw X}}),W=Q.map((X,q)=>Y.call(async()=>{try{return await this.invoke(X,J[q])}catch(G){if($?.returnExceptions)return G;throw G}}));return Promise.all(W)}async*_streamIterator(Q,Z){yield this.invoke(Q,Z)}async stream(Q,Z){let $=t(Z),J=new x8({generator:this._streamIterator(Q,$),config:$});return await J.setup,S0.fromAsyncGenerator(J)}_separateRunnableConfigFromCallOptions(Q){let Z;if(Q===void 0)Z=t(Q);else Z=t({callbacks:Q.callbacks,tags:Q.tags,metadata:Q.metadata,runName:Q.runName,configurable:Q.configurable,recursionLimit:Q.recursionLimit,maxConcurrency:Q.maxConcurrency,runId:Q.runId,timeout:Q.timeout,signal:Q.signal});let $={...Q};return delete $.callbacks,delete $.tags,delete $.metadata,delete $.runName,delete $.configurable,delete $.recursionLimit,delete $.maxConcurrency,delete $.runId,delete $.timeout,delete $.signal,[Z,$]}async _callWithConfig(Q,Z,$){let J=t($),Y=await(await QQ(J))?.handleChainStart(this.toJSON(),l0(Z,"input"),J.runId,J?.runType,void 0,void 0,J?.runName??this.getName());delete J.runId;let W;try{W=await TQ(Q.call(this,Z,J,Y),$?.signal)}catch(X){throw await Y?.handleChainError(X),X}return await Y?.handleChainEnd(l0(W,"output")),W}async _batchWithConfig(Q,Z,$,J){let Y=this._getOptionsList($??{},Z.length),W=await Promise.all(Y.map(QQ)),X=await Promise.all(W.map(async(G,z)=>{let K=await G?.handleChainStart(this.toJSON(),l0(Z[z],"input"),Y[z].runId,Y[z].runType,void 0,void 0,Y[z].runName??this.getName());return delete Y[z].runId,K})),q;try{q=await TQ(Q.call(this,Z,Y,X,J),Y?.[0]?.signal)}catch(G){throw await Promise.all(X.map((z)=>z?.handleChainError(G))),G}return await Promise.all(X.map((G)=>G?.handleChainEnd(l0(q,"output")))),q}_concatOutputChunks(Q,Z){return uQ(Q,Z)}async*_transformStreamWithConfig(Q,Z,$){let J,Y=!0,W,X=!0,q=t($),G=await QQ(q),z=this;async function*K(){for await(let H of Q){if(Y)if(J===void 0)J=H;else try{J=z._concatOutputChunks(J,H)}catch{J=void 0,Y=!1}yield H}}let U;try{let H=await Z4(Z.bind(this),K(),async()=>G?.handleChainStart(this.toJSON(),{input:""},q.runId,q.runType,void 0,void 0,q.runName??this.getName(),void 0,{lc_defers_inputs:!0}),$?.signal,q);delete q.runId,U=H.setup;let B=U?.handlers.find(Nq),F=H.output;if(B!==void 0&&U!==void 0)F=B.tapOutputIterable(U.runId,F);let w=U?.handlers.find(l4);if(w!==void 0&&U!==void 0)F=w.tapOutputIterable(U.runId,F);for await(let A of F)if(yield A,X)if(W===void 0)W=A;else try{W=this._concatOutputChunks(W,A)}catch{W=void 0,X=!1}}catch(H){throw await U?.handleChainError(H,void 0,void 0,void 0,{inputs:l0(J,"input")}),H}await U?.handleChainEnd(W??{},void 0,void 0,void 0,{inputs:l0(J,"input")})}getGraph(Q){let Z=new G1,$=Z.addNode({name:`${this.getName()}Input`,schema:O.any()}),J=Z.addNode(this),Y=Z.addNode({name:`${this.getName()}Output`,schema:O.any()});return Z.addEdge($,J),Z.addEdge(J,Y),Z}pipe(Q){return new s0({first:this,last:v0(Q)})}pick(Q){return this.pipe(new t4(Q))}assign(Q){return this.pipe(new bZ(new M6({steps:Q})))}async*transform(Q,Z){let $;for await(let J of Q)if($===void 0)$=J;else $=this._concatOutputChunks($,J);yield*this._streamIterator($,t(Z))}async*streamLog(Q,Z,$){let J=new S9({...$,autoClose:!1,_schemaFormat:"original"}),Y=t(Z);yield*this._streamLog(Q,J,Y)}async*_streamLog(Q,Z,$){let{callbacks:J}=$;if(J===void 0)$.callbacks=[Z];else if(Array.isArray(J))$.callbacks=J.concat([Z]);else{let q=J.copy();q.addHandler(Z,!0),$.callbacks=q}let Y=this.stream(Q,$);async function W(){try{let q=await Y;for await(let G of q){let z=new v8({ops:[{op:"add",path:"/streamed_output/-",value:G}]});await Z.writer.write(z)}}finally{await Z.writer.close()}}let X=W();try{for await(let q of Z)yield q}finally{await X}}streamEvents(Q,Z,$){let J;if(Z.version==="v1")J=this._streamEventsV1(Q,Z,$);else if(Z.version==="v2")J=this._streamEventsV2(Q,Z,$);else throw Error('Only versions "v1" and "v2" of the schema are currently supported.');if(Z.encoding==="text/event-stream")return yq(J);else return S0.fromAsyncGenerator(J)}async*_streamEventsV2(Q,Z,$){let J=new Oq({...$,autoClose:!1}),Y=t(Z),W=Y.runId??mQ();Y.runId=W;let X=Y.callbacks;if(X===void 0)Y.callbacks=[J];else if(Array.isArray(X))Y.callbacks=X.concat(J);else{let B=X.copy();B.addHandler(J,!0),Y.callbacks=B}let q=new AbortController,G=this;async function z(){let B,F=null;try{if(Z?.signal)if("any"in AbortSignal)B=AbortSignal.any([q.signal,Z.signal]);else B=Z.signal,F=()=>{q.abort()},Z.signal.addEventListener("abort",F,{once:!0});else B=q.signal;let w=await G.stream(Q,{...Y,signal:B}),A=J.tapOutputIterable(W,w);for await(let E of A)if(q.signal.aborted)break}finally{if(await J.finish(),B&&F)B.removeEventListener("abort",F)}}let K=z(),U=!1,H;try{for await(let B of J){if(!U){B.data.input=Q,U=!0,H=B.run_id,yield B;continue}if(B.run_id===H&&B.event.endsWith("_end")){if(B.data?.input)delete B.data.input}yield B}}finally{q.abort(),await K}}async*_streamEventsV1(Q,Z,$){let J,Y=!1,W=t(Z),X=W.tags??[],q=W.metadata??{},G=W.runName??this.getName(),z=new S9({...$,autoClose:!1,_schemaFormat:"streaming_events"}),K=new _q({...$}),U=this._streamLog(Q,z,W);for await(let B of U){if(!J)J=T9.fromRunLogPatch(B);else J=J.concat(B);if(J.state===void 0)throw Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!Y){Y=!0;let E={...J.state},P={run_id:E.id,event:`on_${E.type}_start`,name:G,tags:X,metadata:q,data:{input:Q}};if(K.includeEvent(P,E.type))yield P}let F=B.ops.filter((E)=>E.path.startsWith("/logs/")).map((E)=>E.path.split("/")[2]),w=[...new Set(F)];for(let E of w){let P,j={},R=J.state.logs[E];if(R.end_time===void 0)if(R.streamed_output.length>0)P="stream";else P="start";else P="end";if(P==="start"){if(R.inputs!==void 0)j.input=R.inputs}else if(P==="end"){if(R.inputs!==void 0)j.input=R.inputs;j.output=R.final_output}else if(P==="stream"){let k=R.streamed_output.length;if(k!==1)throw Error(`Expected exactly one chunk of streamed output, got ${k} instead. Encountered in: "${R.name}"`);j={chunk:R.streamed_output[0]},R.streamed_output=[]}yield{event:`on_${R.type}_${P}`,name:R.name,run_id:R.id,tags:R.tags,metadata:R.metadata,data:j}}let{state:A}=J;if(A.streamed_output.length>0){let E=A.streamed_output.length;if(E!==1)throw Error(`Expected exactly one chunk of streamed output, got ${E} instead. Encountered in: "${A.name}"`);let P={chunk:A.streamed_output[0]};A.streamed_output=[];let j={event:`on_${A.type}_stream`,run_id:A.id,tags:X,metadata:q,name:G,data:P};if(K.includeEvent(j,A.type))yield j}}let H=J?.state;if(H!==void 0){let B={event:`on_${H.type}_end`,name:G,run_id:H.id,tags:X,metadata:q,data:{output:H.final_output}};if(K.includeEvent(B,H.type))yield B}}static isRunnable(Q){return CZ(Q)}withListeners({onStart:Q,onEnd:Z,onError:$}){return new b0({bound:this,config:{},configFactories:[(J)=>({callbacks:[new i4({config:J,onStart:Q,onEnd:Z,onError:$})]})]})}asTool(Q){return SB(this,Q)}},b0=class Q extends c{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(Z){super(Z);this.bound=Z.bound,this.kwargs=Z.kwargs,this.config=Z.config,this.configFactories=Z.configFactories}getName(Z){return this.bound.getName(Z)}async _mergeConfig(...Z){let $=w0(this.config,...Z);return w0($,...this.configFactories?await Promise.all(this.configFactories.map(async(J)=>await J($))):[])}withConfig(Z){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...Z}})}withRetry(Z){return new k9({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:Z?.stopAfterAttempt,...Z})}async invoke(Z,$){return this.bound.invoke(Z,await this._mergeConfig($,this.kwargs))}async batch(Z,$,J){let Y=Array.isArray($)?await Promise.all($.map(async(W)=>this._mergeConfig(t(W),this.kwargs))):await this._mergeConfig(t($),this.kwargs);return this.bound.batch(Z,Y,J)}_concatOutputChunks(Z,$){return this.bound._concatOutputChunks(Z,$)}async*_streamIterator(Z,$){yield*this.bound._streamIterator(Z,await this._mergeConfig(t($),this.kwargs))}async stream(Z,$){return this.bound.stream(Z,await this._mergeConfig(t($),this.kwargs))}async*transform(Z,$){yield*this.bound.transform(Z,await this._mergeConfig(t($),this.kwargs))}streamEvents(Z,$,J){let Y=this,W=async function*(){yield*Y.bound.streamEvents(Z,{...await Y._mergeConfig(t($),Y.kwargs),version:$.version},J)};return S0.fromAsyncGenerator(W())}static isRunnableBinding(Z){return Z.bound&&c.isRunnable(Z.bound)}withListeners({onStart:Z,onEnd:$,onError:J}){return new Q({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[(Y)=>({callbacks:[new i4({config:Y,onStart:Z,onEnd:$,onError:J})]})]})}},fq=class Q extends c{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(Z){super(Z);this.bound=Z.bound}async invoke(Z,$){return this._callWithConfig(this._invoke.bind(this),Z,$)}async _invoke(Z,$,J){return this.bound.batch(Z,W0($,{callbacks:J?.getChild()}))}withListeners({onStart:Z,onEnd:$,onError:J}){return new Q({bound:this.bound.withListeners({onStart:Z,onEnd:$,onError:J})})}},k9=class extends b0{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(Q){super(Q);this.maxAttemptNumber=Q.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=Q.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(Q,Z,$){let J=Q>1?`retry:attempt:${Q}`:void 0;return W0(Z,{callbacks:$?.getChild(J)})}async _invoke(Q,Z,$){return yZ((J)=>super.invoke(Q,this._patchConfigForRetry(J,Z,$)),{onFailedAttempt:({error:J})=>this.onFailedAttempt(J,Q),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(Q,Z){return this._callWithConfig(this._invoke.bind(this),Q,Z)}async _batch(Q,Z,$,J){let Y={};try{await yZ(async(W)=>{let X=Q.map((U,H)=>H).filter((U)=>Y[U.toString()]===void 0||Y[U.toString()]instanceof Error),q=X.map((U)=>Q[U]),G=X.map((U)=>this._patchConfigForRetry(W,Z?.[U],$?.[U])),z=await super.batch(q,G,{...J,returnExceptions:!0}),K;for(let U=0;U<z.length;U+=1){let H=z[U],B=X[U];if(H instanceof Error){if(K===void 0)K=H,K.input=q[U]}Y[B.toString()]=H}if(K)throw K;return z},{onFailedAttempt:({error:W})=>this.onFailedAttempt(W,W.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(W){if(J?.returnExceptions!==!0)throw W}return Object.keys(Y).sort((W,X)=>parseInt(W,10)-parseInt(X,10)).map((W)=>Y[parseInt(W,10)])}async batch(Q,Z,$){return this._batchWithConfig(this._batch.bind(this),Q,Z,$)}},s0=class Q extends c{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(Z){super(Z);this.first=Z.first,this.middle=Z.middle??this.middle,this.last=Z.last,this.name=Z.name,this.omitSequenceTags=Z.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(Z,$){let J=t($),Y=await(await QQ(J))?.handleChainStart(this.toJSON(),l0(Z,"input"),J.runId,void 0,void 0,void 0,J?.runName);delete J.runId;let W=Z,X;try{let q=[this.first,...this.middle];for(let G=0;G<q.length;G+=1)W=await TQ(q[G].invoke(W,W0(J,{callbacks:Y?.getChild(this.omitSequenceTags?void 0:`seq:step:${G+1}`)})),$?.signal);if($?.signal?.aborted)throw j6($.signal);X=await this.last.invoke(W,W0(J,{callbacks:Y?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(q){throw await Y?.handleChainError(q),q}return await Y?.handleChainEnd(l0(X,"output")),X}async batch(Z,$,J){let Y=this._getOptionsList($??{},Z.length),W=await Promise.all(Y.map(QQ)),X=await Promise.all(W.map(async(G,z)=>{let K=await G?.handleChainStart(this.toJSON(),l0(Z[z],"input"),Y[z].runId,void 0,void 0,void 0,Y[z].runName);return delete Y[z].runId,K})),q=Z;try{for(let G=0;G<this.steps.length;G+=1)q=await TQ(this.steps[G].batch(q,X.map((z,K)=>{let U=z?.getChild(this.omitSequenceTags?void 0:`seq:step:${G+1}`);return W0(Y[K],{callbacks:U})}),J),Y[0]?.signal)}catch(G){throw await Promise.all(X.map((z)=>z?.handleChainError(G))),G}return await Promise.all(X.map((G)=>G?.handleChainEnd(l0(q,"output")))),q}_concatOutputChunks(Z,$){return this.last._concatOutputChunks(Z,$)}async*_streamIterator(Z,$){let J=await QQ($),{runId:Y,...W}=$??{},X=await J?.handleChainStart(this.toJSON(),l0(Z,"input"),Y,void 0,void 0,void 0,W?.runName),q=[this.first,...this.middle,this.last],G=!0,z;async function*K(){yield Z}try{let U=q[0].transform(K(),W0(W,{callbacks:X?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let H=1;H<q.length;H+=1)U=await q[H].transform(U,W0(W,{callbacks:X?.getChild(this.omitSequenceTags?void 0:`seq:step:${H+1}`)}));for await(let H of U)if($?.signal?.throwIfAborted(),yield H,G)if(z===void 0)z=H;else try{z=this._concatOutputChunks(z,H)}catch{z=void 0,G=!1}}catch(U){throw await X?.handleChainError(U),U}await X?.handleChainEnd(l0(z,"output"))}getGraph(Z){let $=new G1,J=null;return this.steps.forEach((Y,W)=>{let X=Y.getGraph(Z);if(W!==0)X.trimFirstNode();if(W!==this.steps.length-1)X.trimLastNode();$.extend(X);let q=X.firstNode();if(!q)throw Error(`Runnable ${Y} has no first node`);if(J)$.addEdge(J,q);J=X.lastNode()}),$}pipe(Z){if(Q.isRunnableSequence(Z))return new Q({first:this.first,middle:this.middle.concat([this.last,Z.first,...Z.middle]),last:Z.last,name:this.name??Z.name});else return new Q({first:this.first,middle:[...this.middle,this.last],last:v0(Z),name:this.name})}static isRunnableSequence(Z){return Array.isArray(Z.middle)&&c.isRunnable(Z)}static from([Z,...$],J){let Y={};if(typeof J==="string")Y.name=J;else if(J!==void 0)Y=J;return new Q({...Y,first:v0(Z),middle:$.slice(0,-1).map(v0),last:v0($[$.length-1])})}},M6=class Q extends c{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(Z){super(Z);this.steps={};for(let[$,J]of Object.entries(Z.steps))this.steps[$]=v0(J)}static from(Z){return new Q({steps:Z})}async invoke(Z,$){let J=t($),Y=await(await QQ(J))?.handleChainStart(this.toJSON(),{input:Z},J.runId,void 0,void 0,void 0,J?.runName);delete J.runId;let W={};try{let X=Object.entries(this.steps).map(async([q,G])=>{W[q]=await G.invoke(Z,W0(J,{callbacks:Y?.getChild(`map:key:${q}`)}))});await TQ(Promise.all(X),$?.signal)}catch(X){throw await Y?.handleChainError(X),X}return await Y?.handleChainEnd(W),W}async*_transform(Z,$,J){let Y={...this.steps},W=K9(Z,Object.keys(Y).length),X=new Map(Object.entries(Y).map(([q,G],z)=>{let K=G.transform(W[z],W0(J,{callbacks:$?.getChild(`map:key:${q}`)}));return[q,K.next().then((U)=>({key:q,gen:K,result:U}))]}));while(X.size){let{key:q,result:G,gen:z}=await TQ(Promise.race(X.values()),J?.signal);if(X.delete(q),!G.done)yield{[q]:G.value},X.set(q,z.next().then((K)=>({key:q,gen:z,result:K})))}}transform(Z,$){return this._transformStreamWithConfig(Z,this._transform.bind(this),$)}async stream(Z,$){async function*J(){yield Z}let Y=t($),W=new x8({generator:this.transform(J(),Y),config:Y});return await W.setup,S0.fromAsyncGenerator(W)}},IB=class Q extends c{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(Z){super(Z);if(!X9(Z.func))throw Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=Z.func}async invoke(Z,$){let[J]=this._getOptionsList($??{},1),Y=await QQ(J);return TQ(this.func(W0(J,{callbacks:Y}),Z),J?.signal)}async*_streamIterator(Z,$){let[J]=this._getOptionsList($??{},1),Y=await this.invoke(Z,$);if(y9(Y)){for await(let W of Y)J?.signal?.throwIfAborted(),yield W;return}if(Cq(Y)){while(!0){J?.signal?.throwIfAborted();let W=Y.next();if(W.done)break;yield W.value}return}yield Y}static from(Z){return new Q({func:Z})}};function TB(Q){if(X9(Q))throw Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var i0=class Q extends c{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(Z){if(X9(Z.func))return IB.from(Z.func);super(Z);TB(Z.func),this.func=Z.func}static from(Z){return new Q({func:Z})}async _invoke(Z,$,J){return new Promise((Y,W)=>{let X=W0($,{callbacks:J?.getChild(),recursionLimit:($?.recursionLimit??z9)-1});q0.runWithConfig(PQ(X),async()=>{try{let q=await this.func(Z,{...X});if(q&&c.isRunnable(q)){if($?.recursionLimit===0)throw Error("Recursion limit reached.");q=await q.invoke(Z,{...X,recursionLimit:(X.recursionLimit??z9)-1})}else if(y9(q)){let G;for await(let z of C9(X,q))if($?.signal?.throwIfAborted(),G===void 0)G=z;else try{G=this._concatOutputChunks(G,z)}catch{G=z}q=G}else if(n4(q)){let G;for(let z of r4(X,q))if($?.signal?.throwIfAborted(),G===void 0)G=z;else try{G=this._concatOutputChunks(G,z)}catch{G=z}q=G}Y(q)}catch(q){W(q)}})})}async invoke(Z,$){return this._callWithConfig(this._invoke.bind(this),Z,$)}async*_transform(Z,$,J){let Y;for await(let q of Z)if(Y===void 0)Y=q;else try{Y=this._concatOutputChunks(Y,q)}catch{Y=q}let W=W0(J,{callbacks:$?.getChild(),recursionLimit:(J?.recursionLimit??z9)-1}),X=await new Promise((q,G)=>{q0.runWithConfig(PQ(W),async()=>{try{q(await this.func(Y,{...W,config:W}))}catch(z){G(z)}})});if(X&&c.isRunnable(X)){if(J?.recursionLimit===0)throw Error("Recursion limit reached.");let q=await X.stream(Y,W);for await(let G of q)yield G}else if(y9(X))for await(let q of C9(W,X))J?.signal?.throwIfAborted(),yield q;else if(n4(X))for(let q of r4(W,X))J?.signal?.throwIfAborted(),yield q;else yield X}transform(Z,$){return this._transformStreamWithConfig(Z,this._transform.bind(this),$)}async stream(Z,$){async function*J(){yield Z}let Y=t($),W=new x8({generator:this.transform(J(),Y),config:Y});return await W.setup,S0.fromAsyncGenerator(W)}},hq=class extends M6{},s4=class extends c{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(Q){super(Q);this.runnable=Q.runnable,this.fallbacks=Q.fallbacks}*runnables(){yield this.runnable;for(let Q of this.fallbacks)yield Q}async invoke(Q,Z){let $=t(Z),J=await QQ($),{runId:Y,...W}=$,X=await J?.handleChainStart(this.toJSON(),l0(Q,"input"),Y,void 0,void 0,void 0,W?.runName),q=W0(W,{callbacks:X?.getChild()});return await q0.runWithConfig(q,async()=>{let G;for(let z of this.runnables()){$?.signal?.throwIfAborted();try{let K=await z.invoke(Q,q);return await X?.handleChainEnd(l0(K,"output")),K}catch(K){if(G===void 0)G=K}}if(G===void 0)throw Error("No error stored at end of fallback.");throw await X?.handleChainError(G),G})}async*_streamIterator(Q,Z){let $=t(Z),J=await QQ($),{runId:Y,...W}=$,X=await J?.handleChainStart(this.toJSON(),l0(Q,"input"),Y,void 0,void 0,void 0,W?.runName),q,G;for(let K of this.runnables()){$?.signal?.throwIfAborted();let U=W0(W,{callbacks:X?.getChild()});try{G=C9(U,await K.stream(Q,U));break}catch(H){if(q===void 0)q=H}}if(G===void 0){let K=q??Error("No error stored at end of fallback.");throw await X?.handleChainError(K),K}let z;try{for await(let K of G){yield K;try{z=z===void 0?z:this._concatOutputChunks(z,K)}catch{z=void 0}}}catch(K){throw await X?.handleChainError(K),K}await X?.handleChainEnd(l0(z,"output"))}async batch(Q,Z,$){if($?.returnExceptions)throw Error("Not implemented.");let J=this._getOptionsList(Z??{},Q.length),Y=await Promise.all(J.map((q)=>QQ(q))),W=await Promise.all(Y.map(async(q,G)=>{let z=await q?.handleChainStart(this.toJSON(),l0(Q[G],"input"),J[G].runId,void 0,void 0,void 0,J[G].runName);return delete J[G].runId,z})),X;for(let q of this.runnables()){J[0].signal?.throwIfAborted();try{let G=await q.batch(Q,W.map((z,K)=>W0(J[K],{callbacks:z?.getChild()})),$);return await Promise.all(W.map((z,K)=>z?.handleChainEnd(l0(G[K],"output")))),G}catch(G){if(X===void 0)X=G}}if(!X)throw Error("No error stored at end of fallbacks.");throw await Promise.all(W.map((q)=>q?.handleChainError(X))),X}};function v0(Q){if(typeof Q==="function")return new i0({func:Q});else if(c.isRunnable(Q))return Q;else if(!Array.isArray(Q)&&typeof Q==="object"){let Z={};for(let[$,J]of Object.entries(Q))Z[$]=v0(J);return new M6({steps:Z})}else throw Error(`Expected a Runnable, function or object.
82
+ Instead got an unsupported type.`)}var bZ=class extends c{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(Q){if(Q instanceof M6)Q={mapper:Q};super(Q);this.mapper=Q.mapper}async invoke(Q,Z){let $=await this.mapper.invoke(Q,Z);return{...Q,...$}}async*_transform(Q,Z,$){let J=this.mapper.getStepsKeys(),[Y,W]=K9(Q),X=this.mapper.transform(W,W0($,{callbacks:Z?.getChild()})),q=X.next();for await(let G of Y){if(typeof G!=="object"||Array.isArray(G))throw Error(`RunnableAssign can only be used with objects as input, got ${typeof G}`);let z=Object.fromEntries(Object.entries(G).filter(([K])=>!J.includes(K)));if(Object.keys(z).length>0)yield z}yield(await q).value;for await(let G of X)yield G}transform(Q,Z){return this._transformStreamWithConfig(Q,this._transform.bind(this),Z)}async stream(Q,Z){async function*$(){yield Q}let J=t(Z),Y=new x8({generator:this.transform($(),J),config:J});return await Y.setup,S0.fromAsyncGenerator(Y)}},t4=class extends c{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(Q){if(typeof Q==="string"||Array.isArray(Q))Q={keys:Q};super(Q);this.keys=Q.keys}async _pick(Q){if(typeof this.keys==="string")return Q[this.keys];else{let Z=this.keys.map(($)=>[$,Q[$]]).filter(($)=>$[1]!==void 0);return Z.length===0?void 0:Object.fromEntries(Z)}}async invoke(Q,Z){return this._callWithConfig(this._pick.bind(this),Q,Z)}async*_transform(Q){for await(let Z of Q){let $=await this._pick(Z);if($!==void 0)yield $}}transform(Q,Z){return this._transformStreamWithConfig(Q,this._transform.bind(this),Z)}async stream(Q,Z){async function*$(){yield Q}let J=t(Z),Y=new x8({generator:this.transform($(),J),config:J});return await Y.setup,S0.fromAsyncGenerator(Y)}},b9=class extends b0{name;description;schema;constructor(Q){let Z=s0.from([i0.from(async($)=>{let J;if(L6($))try{J=await _6(this.schema,$.args)}catch{throw new w6("Received tool input did not match expected schema",JSON.stringify($.args))}else J=$;return J}).withConfig({runName:`${Q.name}:parse_input`}),Q.bound]).withConfig({runName:Q.name});super({bound:Z,config:Q.config??{}});this.name=Q.name,this.description=Q.description,this.schema=Q.schema}static lc_name(){return"RunnableToolLike"}};function SB(Q,Z){let $=Z.name??Q.getName(),J=Z.description??W8(Z.schema);if(b1(Z.schema))return new b9({name:$,description:J,schema:O.object({input:O.string()}).transform((Y)=>Y.input),bound:Q});return new b9({name:$,description:J,schema:Z.schema,bound:Q})}var f9=(Q,Z)=>{let $=[...new Set(Z?.map((Y)=>{if(typeof Y==="string")return Y;let W=new Y({});if(!("getType"in W)||typeof W.getType!=="function")throw Error("Invalid type provided.");return W.getType()}))],J=Q.getType();return $.some((Y)=>Y===J)};function a4(Q,Z){if(Array.isArray(Q))return gq(Q,Z);return i0.from(($)=>{return gq($,Q)})}function gq(Q,Z={}){let{includeNames:$,excludeNames:J,includeTypes:Y,excludeTypes:W,includeIds:X,excludeIds:q}=Z,G=[];for(let z of Q){if(J&&z.name&&J.includes(z.name))continue;else if(W&&f9(z,W))continue;else if(q&&z.id&&q.includes(z.id))continue;if(!(Y||X||$))G.push(z);else if($&&z.name&&$.some((K)=>K===z.name))G.push(z);else if(Y&&f9(z,Y))G.push(z);else if(X&&z.id&&X.some((K)=>K===z.id))G.push(z)}return G}function pq(Q){if(Array.isArray(Q))return mq(Q);return i0.from(mq)}function mq(Q){if(!Q.length)return[];let Z=[];for(let $ of Q){let J=$,Y=Z.pop();if(!Y)Z.push(J);else if(J.getType()==="tool"||J.getType()!==Y.getType())Z.push(Y,J);else{let W=e6(Y),X=e6(J),q=W.concat(X);if(typeof W.content==="string"&&typeof X.content==="string")q.content=`${W.content}
83
+ ${X.content}`;Z.push(MB(q))}}return Z}function h9(Q,Z){if(Array.isArray(Q)){let $=Q;if(!Z)throw Error("Options parameter is required when providing messages.");return dq($,Z)}else{let $=Q;return i0.from((J)=>dq(J,$)).withConfig({runName:"trim_messages"})}}async function dq(Q,Z){let{maxTokens:$,tokenCounter:J,strategy:Y="last",allowPartial:W=!1,endOn:X,startOn:q,includeSystem:G=!1,textSplitter:z}=Z;if(q&&Y==="first")throw Error("`startOn` should only be specified if `strategy` is 'last'.");if(G&&Y==="first")throw Error("`includeSystem` should only be specified if `strategy` is 'last'.");let K;if("getNumTokens"in J)K=async(H)=>{return(await Promise.all(H.map((B)=>J.getNumTokens(B.content)))).reduce((B,F)=>B+F,0)};else K=async(H)=>J(H);let U=QW;if(z)if("splitText"in z)U=z.splitText;else U=async(H)=>z(H);if(Y==="first")return cq(Q,{maxTokens:$,tokenCounter:K,textSplitter:U,partialStrategy:W?"first":void 0,endOn:X});else if(Y==="last")return xB(Q,{maxTokens:$,tokenCounter:K,textSplitter:U,allowPartial:W,includeSystem:G,startOn:q,endOn:X});else throw Error(`Unrecognized strategy: '${Y}'. Must be one of 'first' or 'last'.`)}async function cq(Q,Z){let{maxTokens:$,tokenCounter:J,textSplitter:Y,partialStrategy:W,endOn:X}=Z,q=[...Q],G=0;for(let z=0;z<q.length;z+=1)if(await J(z>0?q.slice(0,-z):q)<=$){G=q.length-z;break}if(G<q.length&&W){let z=!1;if(Array.isArray(q[G].content)){let K=q[G];if(typeof K.content==="string")throw Error("Expected content to be an array.");let U=K.content.length,H=W==="last"?[...K.content].reverse():K.content;for(let B=1;B<=U;B+=1){let F=W==="first"?H.slice(0,B):H.slice(-B),w=Object.fromEntries(Object.entries(K).filter(([P])=>P!=="type"&&!P.startsWith("lc_"))),A=e4(K.getType(),{...w,content:F}),E=[...q.slice(0,G),A];if(await J(E)<=$)q=E,G+=1,z=!0;else break}if(z&&W==="last")K.content=[...H].reverse()}if(!z){let K=q[G],U;if(Array.isArray(K.content)&&K.content.some((H)=>typeof H==="string"||H.type==="text"))U=K.content.find((H)=>H.type==="text"&&H.text)?.text;else if(typeof K.content==="string")U=K.content;if(U){let H=await Y(U),B=H.length;if(W==="last")H.reverse();for(let F=0;F<B-1;F+=1)if(H.pop(),K.content=H.join(""),await J([...q.slice(0,G),K])<=$){if(W==="last")K.content=[...H].reverse().join("");q=[...q.slice(0,G),K],G+=1;break}}}}if(X){let z=Array.isArray(X)?X:[X];while(G>0&&!f9(q[G-1],z))G-=1}return q.slice(0,G)}async function xB(Q,Z){let{allowPartial:$=!1,includeSystem:J=!1,endOn:Y,startOn:W,...X}=Z,q=Q.map((K)=>{let U=Object.fromEntries(Object.entries(K).filter(([H])=>H!=="type"&&!H.startsWith("lc_")));return e4(K.getType(),U,r8(K))});if(Y){let K=Array.isArray(Y)?Y:[Y];while(q.length>0&&!f9(q[q.length-1],K))q=q.slice(0,-1)}let G=J&&q[0]?.getType()==="system",z=G?q.slice(0,1).concat(q.slice(1).reverse()):q.reverse();if(z=await cq(z,{...X,partialStrategy:$?"last":void 0,endOn:W}),G)return[z[0],...z.slice(1).reverse()];else return z.reverse()}var uq={human:{message:G0,messageChunk:A6},ai:{message:h,messageChunk:y0},system:{message:L0,messageChunk:j8},developer:{message:L0,messageChunk:j8},tool:{message:i,messageChunk:o6},function:{message:s6,messageChunk:t6},generic:{message:Z8,messageChunk:r6},remove:{message:gQ,messageChunk:gQ}};function e4(Q,Z,$){let J,Y;switch(Q){case"human":if($)J=new A6(Z);else Y=new G0(Z);break;case"ai":if($){let W={...Z};if("tool_calls"in W)W={...W,tool_call_chunks:W.tool_calls?.map((X)=>({...X,type:"tool_call_chunk",index:void 0,args:JSON.stringify(X.args)}))};J=new y0(W)}else Y=new h(Z);break;case"system":if($)J=new j8(Z);else Y=new L0(Z);break;case"developer":if($)J=new j8({...Z,additional_kwargs:{...Z.additional_kwargs,__openai_role__:"developer"}});else Y=new L0({...Z,additional_kwargs:{...Z.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in Z)if($)J=new o6(Z);else Y=new i(Z);else throw Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if($)J=new t6(Z);else{if(!Z.name)throw Error("FunctionMessage must have a 'name' field");Y=new s6(Z)}break;case"generic":if("role"in Z)if($)J=new r6(Z);else Y=new Z8(Z);else throw Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw Error(`Unrecognized message type ${Q}`)}if($&&J)return J;if(Y)return Y;throw Error(`Unrecognized message type ${Q}`)}function MB(Q){let Z=Q.getType(),$,J=Object.fromEntries(Object.entries(Q).filter(([Y])=>!["type","tool_call_chunks"].includes(Y)&&!Y.startsWith("lc_")));if(Z in uq)$=e4(Z,J);if(!$)throw Error(`Unrecognized message chunk class ${Z}. Supported classes are ${Object.keys(uq)}`);return $}function QW(Q){let Z=Q.split(`
84
+ `);return Promise.resolve([...Z.slice(0,-1).map(($)=>`${$}
85
+ `),Z[Z.length-1]])}var lq=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var iq=["image","video","audio","text-plain","file"];var oq=["text","reasoning",...lq,...iq];var nq=_({AIMessage:()=>h,AIMessageChunk:()=>y0,BaseMessage:()=>V0,BaseMessageChunk:()=>zQ,ChatMessage:()=>Z8,ChatMessageChunk:()=>r6,DEFAULT_MERGE_IGNORE_KEYS:()=>KY,FunctionMessage:()=>s6,FunctionMessageChunk:()=>t6,HumanMessage:()=>G0,HumanMessageChunk:()=>A6,KNOWN_BLOCK_TYPES:()=>oq,RemoveMessage:()=>gQ,SystemMessage:()=>L0,SystemMessageChunk:()=>j8,ToolMessage:()=>i,ToolMessageChunk:()=>o6,_isMessageFieldWithRole:()=>b$,_mergeDicts:()=>j0,_mergeLists:()=>F6,_mergeObj:()=>C$,_mergeStatus:()=>y$,coerceMessageLikeToMessage:()=>KQ,collapseToolCallChunks:()=>f$,convertToChunk:()=>e6,convertToOpenAIImageBlock:()=>_$,convertToProviderContentBlock:()=>GX,defaultTextSplitter:()=>QW,defaultToolCallParser:()=>FZ,filterMessages:()=>a4,getBufferString:()=>a6,iife:()=>Q5,isAIMessage:()=>I1,isAIMessageChunk:()=>AZ,isBase64ContentBlock:()=>j1,isBaseMessage:()=>R0,isBaseMessageChunk:()=>r8,isChatMessage:()=>iX,isChatMessageChunk:()=>oX,isDataContentBlock:()=>E8,isDirectToolOutput:()=>VZ,isFunctionMessage:()=>nX,isFunctionMessageChunk:()=>rX,isHumanMessage:()=>sX,isHumanMessageChunk:()=>tX,isIDContentBlock:()=>R$,isMessage:()=>v$,isOpenAIToolCallArray:()=>_X,isPlainTextContentBlock:()=>XX,isSystemMessage:()=>aX,isSystemMessageChunk:()=>eX,isToolMessage:()=>LZ,isToolMessageChunk:()=>BY,isURLContentBlock:()=>E1,mapChatMessagesToStoredMessages:()=>$5,mapStoredMessageToChatMessage:()=>wZ,mapStoredMessagesToChatMessages:()=>Z5,mergeContent:()=>GQ,mergeMessageRuns:()=>pq,mergeResponseMetadata:()=>k$,mergeUsageMetadata:()=>_1,parseBase64DataUrl:()=>DZ,parseMimeType:()=>qX,trimMessages:()=>h9});var d="0123456789abcdef".split(""),vB=[-2147483648,8388608,32768,128],q8=[24,16,8,0],g9=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],$Q=[];function G8(Q,Z){if(Z)$Q[0]=$Q[16]=$Q[1]=$Q[2]=$Q[3]=$Q[4]=$Q[5]=$Q[6]=$Q[7]=$Q[8]=$Q[9]=$Q[10]=$Q[11]=$Q[12]=$Q[13]=$Q[14]=$Q[15]=0,this.blocks=$Q;else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];if(Q)this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428;else this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225;this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=Q}G8.prototype.update=function(Q){if(this.finalized)return;var Z,$=typeof Q;if($!=="string"){if($==="object"){if(Q===null)throw Error(ERROR);else if(ARRAY_BUFFER&&Q.constructor===ArrayBuffer)Q=new Uint8Array(Q);else if(!Array.isArray(Q)){if(!ARRAY_BUFFER||!ArrayBuffer.isView(Q))throw Error(ERROR)}}else throw Error(ERROR);Z=!0}var J,Y=0,W,X=Q.length,q=this.blocks;while(Y<X){if(this.hashed)this.hashed=!1,q[0]=this.block,this.block=q[16]=q[1]=q[2]=q[3]=q[4]=q[5]=q[6]=q[7]=q[8]=q[9]=q[10]=q[11]=q[12]=q[13]=q[14]=q[15]=0;if(Z)for(W=this.start;Y<X&&W<64;++Y)q[W>>>2]|=Q[Y]<<q8[W++&3];else for(W=this.start;Y<X&&W<64;++Y)if(J=Q.charCodeAt(Y),J<128)q[W>>>2]|=J<<q8[W++&3];else if(J<2048)q[W>>>2]|=(192|J>>>6)<<q8[W++&3],q[W>>>2]|=(128|J&63)<<q8[W++&3];else if(J<55296||J>=57344)q[W>>>2]|=(224|J>>>12)<<q8[W++&3],q[W>>>2]|=(128|J>>>6&63)<<q8[W++&3],q[W>>>2]|=(128|J&63)<<q8[W++&3];else J=65536+((J&1023)<<10|Q.charCodeAt(++Y)&1023),q[W>>>2]|=(240|J>>>18)<<q8[W++&3],q[W>>>2]|=(128|J>>>12&63)<<q8[W++&3],q[W>>>2]|=(128|J>>>6&63)<<q8[W++&3],q[W>>>2]|=(128|J&63)<<q8[W++&3];if(this.lastByteIndex=W,this.bytes+=W-this.start,W>=64)this.block=q[16],this.start=W-64,this.hash(),this.hashed=!0;else this.start=W}if(this.bytes>4294967295)this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296;return this};G8.prototype.finalize=function(){if(this.finalized)return;this.finalized=!0;var Q=this.blocks,Z=this.lastByteIndex;if(Q[16]=this.block,Q[Z>>>2]|=vB[Z&3],this.block=Q[16],Z>=56){if(!this.hashed)this.hash();Q[0]=this.block,Q[16]=Q[1]=Q[2]=Q[3]=Q[4]=Q[5]=Q[6]=Q[7]=Q[8]=Q[9]=Q[10]=Q[11]=Q[12]=Q[13]=Q[14]=Q[15]=0}Q[14]=this.hBytes<<3|this.bytes>>>29,Q[15]=this.bytes<<3,this.hash()};G8.prototype.hash=function(){var Q=this.h0,Z=this.h1,$=this.h2,J=this.h3,Y=this.h4,W=this.h5,X=this.h6,q=this.h7,G=this.blocks,z,K,U,H,B,F,w,A,E,P,j;for(z=16;z<64;++z)B=G[z-15],K=(B>>>7|B<<25)^(B>>>18|B<<14)^B>>>3,B=G[z-2],U=(B>>>17|B<<15)^(B>>>19|B<<13)^B>>>10,G[z]=G[z-16]+K+G[z-7]+U<<0;j=Z&$;for(z=0;z<64;z+=4){if(this.first){if(this.is224)A=300032,B=G[0]-1413257819,q=B-150054599<<0,J=B+24177077<<0;else A=704751109,B=G[0]-210244248,q=B-1521486534<<0,J=B+143694565<<0;this.first=!1}else K=(Q>>>2|Q<<30)^(Q>>>13|Q<<19)^(Q>>>22|Q<<10),U=(Y>>>6|Y<<26)^(Y>>>11|Y<<21)^(Y>>>25|Y<<7),A=Q&Z,H=A^Q&$^j,w=Y&W^~Y&X,B=q+U+w+g9[z]+G[z],F=K+H,q=J+B<<0,J=B+F<<0;K=(J>>>2|J<<30)^(J>>>13|J<<19)^(J>>>22|J<<10),U=(q>>>6|q<<26)^(q>>>11|q<<21)^(q>>>25|q<<7),E=J&Q,H=E^J&Z^A,w=X&q^~X&Y,B=W+U+w+g9[z+1]+G[z+1],F=K+H,X=$+B<<0,$=B+F<<0,K=($>>>2|$<<30)^($>>>13|$<<19)^($>>>22|$<<10),U=(X>>>6|X<<26)^(X>>>11|X<<21)^(X>>>25|X<<7),P=$&J,H=P^$&Q^E,w=W&X^~W&q,B=Y+U+w+g9[z+2]+G[z+2],F=K+H,W=Z+B<<0,Z=B+F<<0,K=(Z>>>2|Z<<30)^(Z>>>13|Z<<19)^(Z>>>22|Z<<10),U=(W>>>6|W<<26)^(W>>>11|W<<21)^(W>>>25|W<<7),j=Z&$,H=j^Z&J^P,w=W&X^~W&q,B=Y+U+w+g9[z+3]+G[z+3],F=K+H,Y=Q+B<<0,Q=B+F<<0,this.chromeBugWorkAround=!0}this.h0=this.h0+Q<<0,this.h1=this.h1+Z<<0,this.h2=this.h2+$<<0,this.h3=this.h3+J<<0,this.h4=this.h4+Y<<0,this.h5=this.h5+W<<0,this.h6=this.h6+X<<0,this.h7=this.h7+q<<0};G8.prototype.hex=function(){this.finalize();var Q=this.h0,Z=this.h1,$=this.h2,J=this.h3,Y=this.h4,W=this.h5,X=this.h6,q=this.h7,G=d[Q>>>28&15]+d[Q>>>24&15]+d[Q>>>20&15]+d[Q>>>16&15]+d[Q>>>12&15]+d[Q>>>8&15]+d[Q>>>4&15]+d[Q&15]+d[Z>>>28&15]+d[Z>>>24&15]+d[Z>>>20&15]+d[Z>>>16&15]+d[Z>>>12&15]+d[Z>>>8&15]+d[Z>>>4&15]+d[Z&15]+d[$>>>28&15]+d[$>>>24&15]+d[$>>>20&15]+d[$>>>16&15]+d[$>>>12&15]+d[$>>>8&15]+d[$>>>4&15]+d[$&15]+d[J>>>28&15]+d[J>>>24&15]+d[J>>>20&15]+d[J>>>16&15]+d[J>>>12&15]+d[J>>>8&15]+d[J>>>4&15]+d[J&15]+d[Y>>>28&15]+d[Y>>>24&15]+d[Y>>>20&15]+d[Y>>>16&15]+d[Y>>>12&15]+d[Y>>>8&15]+d[Y>>>4&15]+d[Y&15]+d[W>>>28&15]+d[W>>>24&15]+d[W>>>20&15]+d[W>>>16&15]+d[W>>>12&15]+d[W>>>8&15]+d[W>>>4&15]+d[W&15]+d[X>>>28&15]+d[X>>>24&15]+d[X>>>20&15]+d[X>>>16&15]+d[X>>>12&15]+d[X>>>8&15]+d[X>>>4&15]+d[X&15];if(!this.is224)G+=d[q>>>28&15]+d[q>>>24&15]+d[q>>>20&15]+d[q>>>16&15]+d[q>>>12&15]+d[q>>>8&15]+d[q>>>4&15]+d[q&15];return G};G8.prototype.toString=G8.prototype.hex;G8.prototype.digest=function(){this.finalize();var Q=this.h0,Z=this.h1,$=this.h2,J=this.h3,Y=this.h4,W=this.h5,X=this.h6,q=this.h7,G=[Q>>>24&255,Q>>>16&255,Q>>>8&255,Q&255,Z>>>24&255,Z>>>16&255,Z>>>8&255,Z&255,$>>>24&255,$>>>16&255,$>>>8&255,$&255,J>>>24&255,J>>>16&255,J>>>8&255,J&255,Y>>>24&255,Y>>>16&255,Y>>>8&255,Y&255,W>>>24&255,W>>>16&255,W>>>8&255,W&255,X>>>24&255,X>>>16&255,X>>>8&255,X&255];if(!this.is224)G.push(q>>>24&255,q>>>16&255,q>>>8&255,q&255);return G};G8.prototype.array=G8.prototype.digest;G8.prototype.arrayBuffer=function(){this.finalize();var Q=new ArrayBuffer(this.is224?28:32),Z=new DataView(Q);if(Z.setUint32(0,this.h0),Z.setUint32(4,this.h1),Z.setUint32(8,this.h2),Z.setUint32(12,this.h3),Z.setUint32(16,this.h4),Z.setUint32(20,this.h5),Z.setUint32(24,this.h6),!this.is224)Z.setUint32(28,this.h7);return Q};var z1=(...Q)=>{return new G8(!1,!0).update(Q.join("")).hex()};var rq=_({sha256:()=>z1});var sq=_({BaseCache:()=>aq,InMemoryCache:()=>ZW,defaultHashKeyEncoder:()=>tq,deserializeStoredGeneration:()=>yB,serializeGeneration:()=>CB}),tq=(...Q)=>z1(Q.join("_"));function yB(Q){if(Q.message!==void 0)return{text:Q.text,message:wZ(Q.message)};else return{text:Q.text}}function CB(Q){let Z={text:Q.text};if(Q.message!==void 0)Z.message=Q.message.toDict();return Z}var aq=class{keyEncoder=tq;makeDefaultKeyEncoder(Q){this.keyEncoder=Q}},bB=new Map,ZW=class Q extends aq{cache;constructor(Z){super();this.cache=Z??new Map}lookup(Z,$){return Promise.resolve(this.cache.get(this.keyEncoder(Z,$))??null)}async update(Z,$,J){this.cache.set(this.keyEncoder(Z,$),J)}static global(){return new Q(bB)}};var eq=_({BasePromptValue:()=>m9,ChatPromptValue:()=>fZ,ImagePromptValue:()=>$W,StringPromptValue:()=>kZ}),m9=class extends g0{},kZ=class extends m9{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(Q){super({value:Q});this.value=Q}toString(){return this.value}toChatMessages(){return[new G0(this.value)]}},fZ=class extends m9{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(Q){if(Array.isArray(Q))Q={messages:Q};super(Q);this.messages=Q.messages}toString(){return a6(this.messages)}toChatMessages(){return this.messages}},$W=class extends m9{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(Q){if(!("imageUrl"in Q))Q={imageUrl:Q};super(Q);this.imageUrl=Q.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new G0({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}};var $2=_({encodingForModel:()=>u9,getEncoding:()=>J2}),d9={},kB=new J6({});async function J2(Q){if(!(Q in d9))d9[Q]=kB.fetch(`https://tiktoken.pages.dev/js/${Q}.json`).then((Z)=>Z.json()).then((Z)=>new Q2(Z)).catch((Z)=>{throw delete d9[Q],Z});return await d9[Q]}async function u9(Q){return J2(Z2(Q))}var Y2=_({BaseLangChain:()=>c9,BaseLanguageModel:()=>K1,calculateMaxTokens:()=>gB,getEmbeddingContextSize:()=>fB,getModelContextSize:()=>hZ,getModelNameForTiktoken:()=>p9,isOpenAITool:()=>hB}),p9=(Q)=>{if(Q.startsWith("gpt-5"))return"gpt-5";if(Q.startsWith("gpt-3.5-turbo-16k"))return"gpt-3.5-turbo-16k";if(Q.startsWith("gpt-3.5-turbo-"))return"gpt-3.5-turbo";if(Q.startsWith("gpt-4-32k"))return"gpt-4-32k";if(Q.startsWith("gpt-4-"))return"gpt-4";if(Q.startsWith("gpt-4o"))return"gpt-4o";return Q},fB=(Q)=>{switch(Q){case"text-embedding-ada-002":return 8191;default:return 2046}},hZ=(Q)=>{switch(p9(Q)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 400000;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128000;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128000;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8000;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 200000;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function hB(Q){if(typeof Q!=="object"||!Q)return!1;if("type"in Q&&Q.type==="function"&&"function"in Q&&typeof Q.function==="object"&&Q.function&&"name"in Q.function&&"parameters"in Q.function)return!0;return!1}var gB=async({prompt:Q,modelName:Z})=>{let $;try{$=(await u9(p9(Z))).encode(Q).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),$=Math.ceil(Q.length/4)}return hZ(Z)-$},mB=()=>!1,c9=class extends c{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(Q){super(Q);this.verbose=Q.verbose??mB(),this.callbacks=Q.callbacks,this.tags=Q.tags??[],this.metadata=Q.metadata??{},this._addVersion("@langchain/core","1.1.31")}_addVersion(Q,Z){let $=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof $==="object"&&$!==null?$:{},[Q]:Z}}}},K1=class extends c9{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:Q,callbackManager:Z,...$}){let{cache:J,...Y}=$;super({callbacks:Q??Z,...Y});if(typeof J==="object")this.cache=J;else if(J)this.cache=ZW.global();else this.cache=void 0;this.caller=new J6($??{})}_encoding;async getNumTokens(Q){let Z;if(typeof Q==="string")Z=Q;else Z=Q.map((J)=>{if(typeof J==="string")return J;if(J.type==="text"&&"text"in J)return J.text;return""}).join("");let $=Math.ceil(Z.length/4);if(!this._encoding)try{this._encoding=await u9("modelName"in this?p9(this.modelName):"gpt2")}catch(J){console.warn("Failed to calculate number of tokens, falling back to approximate count",J)}if(this._encoding)try{$=this._encoding.encode(Z).length}catch(J){console.warn("Failed to calculate number of tokens, falling back to approximate count",J)}return $}static _convertInputToPromptValue(Q){if(typeof Q==="string")return new kZ(Q);else if(Array.isArray(Q))return new fZ(Q.map(KQ));else return Q}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:Q,...Z}){let $={...this._identifyingParams(),...Z,_type:this._llmType(),_model:this._modelType()};return Object.entries($).filter(([J,Y])=>Y!==void 0).map(([J,Y])=>`${J}:${JSON.stringify(Y)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(Q){throw Error("Use .toJSON() instead")}get profile(){return{}}};var W2=(Q)=>Q();function l9(Q){return new Q.constructor({...Q,content:Q.contentBlocks,response_metadata:{...Q.response_metadata,output_version:"v1"}})}var Y6=class extends c{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(Q){super(Q);if(Q)this.func=Q.func}async invoke(Q,Z){let $=t(Z);if(this.func)await this.func(Q,$);return this._callWithConfig((J)=>Promise.resolve(J),Q,$)}async*transform(Q,Z){let $=t(Z),J,Y=!0;for await(let W of this._transformStreamWithConfig(Q,(X)=>X,$))if(yield W,Y)if(J===void 0)J=W;else try{J=uQ(J,W)}catch{J=void 0,Y=!1}if(this.func&&J!==void 0)await this.func(J,$)}static assign(Q){return new bZ(new M6({steps:Q}))}};var X2=class extends c{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(Q){super(Q);this.runnables=Q.runnables}async invoke(Q,Z){let{key:$,input:J}=Q,Y=this.runnables[$];if(Y===void 0)throw Error(`No runnable associated with key "${$}".`);return Y.invoke(J,t(Z))}async batch(Q,Z,$){let J=Q.map((K)=>K.key),Y=Q.map((K)=>K.input);if(J.find((K)=>this.runnables[K]===void 0)!==void 0)throw Error("One or more keys do not have a corresponding runnable.");let W=J.map((K)=>this.runnables[K]),X=this._getOptionsList(Z??{},Q.length),q=X[0]?.maxConcurrency??$?.maxConcurrency,G=q&&q>0?q:Q.length,z=[];for(let K=0;K<Y.length;K+=G){let U=Y.slice(K,K+G).map((B,F)=>W[F].invoke(B,X[F])),H=await Promise.all(U);z.push(H)}return z.flat()}async stream(Q,Z){let{key:$,input:J}=Q,Y=this.runnables[$];if(Y===void 0)throw Error(`No runnable associated with key "${$}".`);return Y.stream(J,Z)}};var q2=class extends c{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(Q){super(Q);this.branches=Q.branches,this.default=Q.default}static from(Q){if(Q.length<1)throw Error("RunnableBranch requires at least one branch");let Z=Q.slice(0,-1).map(([J,Y])=>[v0(J),v0(Y)]),$=v0(Q[Q.length-1]);return new this({branches:Z,default:$})}async _invoke(Q,Z,$){let J;for(let Y=0;Y<this.branches.length;Y+=1){let[W,X]=this.branches[Y];if(await W.invoke(Q,W0(Z,{callbacks:$?.getChild(`condition:${Y+1}`)}))){J=await X.invoke(Q,W0(Z,{callbacks:$?.getChild(`branch:${Y+1}`)}));break}}if(!J)J=await this.default.invoke(Q,W0(Z,{callbacks:$?.getChild("branch:default")}));return J}async invoke(Q,Z={}){return this._callWithConfig(this._invoke,Q,Z)}async*_streamIterator(Q,Z){let $=await(await QQ(Z))?.handleChainStart(this.toJSON(),l0(Q,"input"),Z?.runId,void 0,void 0,void 0,Z?.runName),J,Y=!0,W;try{for(let X=0;X<this.branches.length;X+=1){let[q,G]=this.branches[X];if(await q.invoke(Q,W0(Z,{callbacks:$?.getChild(`condition:${X+1}`)}))){W=await G.stream(Q,W0(Z,{callbacks:$?.getChild(`branch:${X+1}`)}));for await(let z of W)if(yield z,Y)if(J===void 0)J=z;else try{J=uQ(J,z)}catch{J=void 0,Y=!1}break}}if(W===void 0){W=await this.default.stream(Q,W0(Z,{callbacks:$?.getChild("branch:default")}));for await(let X of W)if(yield X,Y)if(J===void 0)J=X;else try{J=uQ(J,X)}catch{J=void 0,Y=!1}}}catch(X){throw await $?.handleChainError(X),X}await $?.handleChainEnd(J??{})}};var G2=class extends b0{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(Q){let Z=i0.from((W,X)=>this._enterHistory(W,X??{})).withConfig({runName:"loadHistory"}),$=Q.historyMessagesKey??Q.inputMessagesKey;if($)Z=Y6.assign({[$]:Z}).withConfig({runName:"insertHistory"});let J=Z.pipe(Q.runnable.withListeners({onEnd:(W,X)=>this._exitHistory(W,X??{})})).withConfig({runName:"RunnableWithMessageHistory"}),Y=Q.config??{};super({...Q,config:Y,bound:J});this.runnable=Q.runnable,this.getMessageHistory=Q.getMessageHistory,this.inputMessagesKey=Q.inputMessagesKey,this.outputMessagesKey=Q.outputMessagesKey,this.historyMessagesKey=Q.historyMessagesKey}_getInputMessages(Q){let Z;if(typeof Q==="object"&&!Array.isArray(Q)&&!R0(Q)){let $;if(this.inputMessagesKey)$=this.inputMessagesKey;else if(Object.keys(Q).length===1)$=Object.keys(Q)[0];else $="input";if(Array.isArray(Q[$])&&Array.isArray(Q[$][0]))Z=Q[$][0];else Z=Q[$]}else Z=Q;if(typeof Z==="string")return[new G0(Z)];else if(Array.isArray(Z))return Z;else if(R0(Z))return[Z];else throw Error(`Expected a string, BaseMessage, or array of BaseMessages.
86
+ Got ${JSON.stringify(Z,null,2)}`)}_getOutputMessages(Q){let Z;if(!Array.isArray(Q)&&!R0(Q)&&typeof Q!=="string"){let $;if(this.outputMessagesKey!==void 0)$=this.outputMessagesKey;else if(Object.keys(Q).length===1)$=Object.keys(Q)[0];else $="output";if(Q.generations!==void 0)Z=Q.generations[0][0].message;else Z=Q[$]}else Z=Q;if(typeof Z==="string")return[new h(Z)];else if(Array.isArray(Z))return Z;else if(R0(Z))return[Z];else throw Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(Z,null,2)}`)}async _enterHistory(Q,Z){let $=await(Z?.configurable?.messageHistory).getMessages();if(this.historyMessagesKey===void 0)return $.concat(this._getInputMessages(Q));return $}async _exitHistory(Q,Z){let $=Z.configurable?.messageHistory,J;if(Array.isArray(Q.inputs)&&Array.isArray(Q.inputs[0]))J=Q.inputs[0];else J=Q.inputs;let Y=this._getInputMessages(J);if(this.historyMessagesKey===void 0){let q=await $.getMessages();Y=Y.slice(q.length)}let W=Q.outputs;if(!W)throw Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(Q,null,2)}`);let X=this._getOutputMessages(W);await $.addMessages([...Y,...X])}async _mergeConfig(...Q){let Z=await super._mergeConfig(...Q);if(!Z.configurable||!Z.configurable.sessionId){let J={[this.inputMessagesKey??"input"]:"foo"};throw Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
87
+ eg. chain.invoke(${JSON.stringify(J)}, ${JSON.stringify({configurable:{sessionId:"123"}})})`)}let{sessionId:$}=Z.configurable;return Z.configurable.messageHistory=await this.getMessageHistory($),Z}};var z2=_({RouterRunnable:()=>X2,Runnable:()=>c,RunnableAssign:()=>bZ,RunnableBinding:()=>b0,RunnableBranch:()=>q2,RunnableEach:()=>fq,RunnableLambda:()=>i0,RunnableMap:()=>M6,RunnableParallel:()=>hq,RunnablePassthrough:()=>Y6,RunnablePick:()=>t4,RunnableRetry:()=>k9,RunnableSequence:()=>s0,RunnableToolLike:()=>b9,RunnableWithFallbacks:()=>s4,RunnableWithMessageHistory:()=>G2,_coerceToRunnable:()=>v0,ensureConfig:()=>t,getCallbackManagerForConfig:()=>QQ,mergeConfigs:()=>w0,patchConfig:()=>W0,pickRunnableConfigKeys:()=>PQ,raceWithSignal:()=>TQ});var m1=class extends c{parseResultWithPrompt(Q,Z,$){return this.parseResult(Q,$)}_baseMessageToString(Q){return typeof Q.content==="string"?Q.content:this._baseMessageContentToString(Q.content)}_baseMessageContentToString(Q){return JSON.stringify(Q)}async invoke(Q,Z){if(typeof Q==="string")return this._callWithConfig(async($,J)=>this.parseResult([{text:$}],J?.callbacks),Q,{...Z,runType:"parser"});else return this._callWithConfig(async($,J)=>this.parseResult([{message:$,text:this._baseMessageToString($)}],J?.callbacks),Q,{...Z,runType:"parser"})}},z8=class extends m1{parseResult(Q,Z){return this.parse(Q[0].text,Z)}async parseWithPrompt(Q,Z,$){return this.parse(Q,$)}_type(){throw Error("_type not implemented")}},UQ=class extends Error{llmOutput;observation;sendToLLM;constructor(Q,Z,$,J=!1){super(Q);if(this.llmOutput=Z,this.observation=$,this.sendToLLM=J,J){if($===void 0||Z===void 0)throw Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true")}n8(this,"OUTPUT_PARSING_FAILURE")}};var W6=class extends z8{async*_transform(Q){for await(let Z of Q)if(typeof Z==="string")yield this.parseResult([{text:Z}]);else yield this.parseResult([{message:Z,text:this._baseMessageToString(Z)}])}async*transform(Q,Z){yield*this._transformStreamWithConfig(Q,this._transform.bind(this),{...Z,runType:"parser"})}},y8=class extends W6{diff=!1;constructor(Q){super(Q);this.diff=Q?.diff??this.diff}async*_transform(Q){let Z,$;for await(let J of Q){if(typeof J!=="string"&&typeof J.content!=="string")throw Error("Cannot handle non-string output.");let Y;if(r8(J)){if(typeof J.content!=="string")throw Error("Cannot handle non-string message output.");Y=new R6({message:J,text:J.content})}else if(R0(J)){if(typeof J.content!=="string")throw Error("Cannot handle non-string message output.");Y=new R6({message:e6(J),text:J.content})}else Y=new a8({text:J});if($===void 0)$=Y;else $=$.concat(Y);let W=await this.parsePartialResult([$]);if(W!==void 0&&W!==null&&!N9(W,Z)){if(this.diff)yield this._diff(Z,W);else yield W;Z=W}}}getFormatInstructions(){return""}};var K2=_({applyPatch:()=>Z6,compare:()=>$6});var i9=class extends y8{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(Q,Z){if(this.diff)return super._concatOutputChunks(Q,Z);return Z}_diff(Q,Z){if(!Z)return;if(!Q)return[{op:"replace",path:"",value:Z}];return $6(Q,Z)}async parsePartialResult(Q){return n6(Q[0].text)}async parse(Q){return n6(Q,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(Q){return Q.text}};var o9=class extends z8{static lc_name(){return"StandardSchemaOutputParser"}lc_namespace=["langchain","output_parsers","standard_schema"];schema;constructor(Q){super();this.schema=Q}static fromSerializableSchema(Q){return new this(Q)}async parse(Q){try{let Z=n6(Q,JSON.parse),$=await this.schema["~standard"].validate(Z);if($.issues)throw Error(`Validation failed: ${JSON.stringify($.issues)}`);return $.value}catch(Z){throw new UQ(`Failed to parse. Text: "${Q}". Error: ${Z}`,Q)}}getFormatInstructions(){return""}};var gZ=class extends z8{static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(Q){super(Q);this.schema=Q}static fromZodSchema(Q){return new this(Q)}static fromNamesAndDescriptions(Q){let Z=O.object(Object.fromEntries(Object.entries(Q).map(([$,J])=>[$,O.string().describe(J)])));return new this(Z)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
88
+
89
+ "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
90
+
91
+ For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
92
+ would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
93
+ Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
94
+
95
+ Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
96
+
97
+ Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
98
+ \`\`\`json
99
+ ${JSON.stringify(M0(this.schema))}
100
+ \`\`\`
101
+ `}async parse(Q){try{let Z=Q.trim(),$=(Z.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||Z.match(/```json\s*([\s\S]*?)```/)?.[1]||Z).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(J,Y)=>{return`"${Y.replace(/\n/g,"\\n")}"`}).replace(/\n/g,"");return await _6(this.schema,JSON.parse($))}catch(Z){throw new UQ(`Failed to parse. Text: "${Q}". Error: ${Z}`,Q)}}},JW=class extends gZ{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(Q){let Z=Q?.interpolationDepth??1;if(Z<1)throw Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
102
+ \`\`\`json
103
+ ${this._schemaToInstruction(M0(this.schema)).replaceAll("{","{".repeat(Z)).replaceAll("}","}".repeat(Z))}
104
+ \`\`\``}_schemaToInstruction(Q,Z=2){let $=Q;if("type"in $){let J=!1,Y;if(Array.isArray($.type)){let q=$.type.findIndex((G)=>G==="null");if(q!==-1)J=!0,$.type.splice(q,1);Y=$.type.join(" | ")}else Y=$.type;if($.type==="object"&&$.properties){let q=$.description?` // ${$.description}`:"";return`{
105
+ ${Object.entries($.properties).map(([G,z])=>{let K=$.required?.includes(G)?"":" (optional)";return`${" ".repeat(Z)}"${G}": ${this._schemaToInstruction(z,Z+2)}${K}`}).join(`
106
+ `)}
107
+ ${" ".repeat(Z-2)}}${q}`}if($.type==="array"&&$.items){let q=$.description?` // ${$.description}`:"";return`array[
108
+ ${" ".repeat(Z)}${this._schemaToInstruction($.items,Z+2)}
109
+ ${" ".repeat(Z-2)}] ${q}`}let W=J?" (nullable)":"",X=$.description?` // ${$.description}`:"";return`${Y}${X}${W}`}if("anyOf"in $)return $.anyOf.map((J)=>this._schemaToInstruction(J,Z)).join(`
110
+ ${" ".repeat(Z-2)}`);throw Error("unsupported schema type")}static fromZodSchema(Q){return new this(Q)}static fromNamesAndDescriptions(Q){let Z=O.object(Object.fromEntries(Object.entries(Q).map(([$,J])=>[$,O.string().describe(J)])));return new this(Z)}},U2=class extends z8{structuredInputParser;constructor({inputSchema:Q}){super(...arguments);this.structuredInputParser=new JW(Q)}async parse(Q){let Z;try{Z=await this.structuredInputParser.parse(Q)}catch($){throw new UQ(`Failed to parse. Text: "${Q}". Error: ${$}`,Q)}return this.outputProcessor(Z)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}};var H2=class extends W6{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(Q){return Promise.resolve(this.textEncoder.encode(Q))}getFormatInstructions(){return""}};var d1=class extends W6{re;async*_transform(Q){let Z="";for await(let $ of Q){if(typeof $==="string")Z+=$;else Z+=$.content;if(!this.re){let J=await this.parse(Z);if(J.length>1){for(let Y of J.slice(0,-1))yield[Y];Z=J[J.length-1]}}else{let J=[...Z.matchAll(this.re)];if(J.length>1){let Y=0;for(let W of J.slice(0,-1))yield[W[1]],Y+=(W.index??0)+W[0].length;Z=Z.slice(Y)}}}for(let $ of await this.parse(Z))yield[$]}},B2=class extends d1{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(Q){try{return Q.trim().split(",").map((Z)=>Z.trim())}catch{throw new UQ(`Could not parse output: ${Q}`,Q)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},D2=class extends d1{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:Q,separator:Z}){super(...arguments);this.length=Q,this.separator=Z||","}async parse(Q){try{let Z=Q.trim().split(this.separator).map(($)=>$.trim());if(this.length!==void 0&&Z.length!==this.length)throw new UQ(`Incorrect number of items. Expected ${this.length}, got ${Z.length}.`);return Z}catch(Z){if(Object.getPrototypeOf(Z)===UQ.prototype)throw Z;throw new UQ(`Could not parse output: ${Q}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},V2=class extends d1{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
111
+
112
+ 1. foo
113
+
114
+ 2. bar
115
+
116
+ 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(Q){return[...Q.matchAll(this.re)??[]].map((Z)=>Z[1])}},F2=class extends d1{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
117
+
118
+ 1. foo
119
+
120
+ 2. bar
121
+
122
+ 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(Q){return[...Q.matchAll(this.re)??[]].map((Z)=>Z[1])}};var L2=class extends W6{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(Q){return Promise.resolve(Q)}getFormatInstructions(){return""}_textContentToString(Q){return Q.text}_imageUrlContentToString(Q){throw Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(Q){switch(Q.type){case"text":case"text_delta":if("text"in Q)return this._textContentToString(Q);break;case"image_url":if("image_url"in Q)return this._imageUrlContentToString(Q);break;case"reasoning":case"thinking":case"redacted_thinking":return"";default:throw Error(`Cannot coerce "${Q.type}" message part into a string.`)}throw Error(`Invalid content type: ${Q.type}`)}_baseMessageContentToString(Q){return Q.reduce((Z,$)=>Z+this._messageContentToString($),"")}};var dB=function(){let Q={};Q.parser=function(L,D){return new $(L,D)},Q.SAXParser=$,Q.SAXStream=z,Q.createStream=G,Q.MAX_BUFFER_LENGTH=65536;let Z=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];Q.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function $(L,D){if(!(this instanceof $))return new $(L,D);var S=this;if(Y(S),S.q=S.c="",S.bufferCheckPosition=Q.MAX_BUFFER_LENGTH,S.opt=D||{},S.opt.lowercase=S.opt.lowercase||S.opt.lowercasetags,S.looseCase=S.opt.lowercase?"toLowerCase":"toUpperCase",S.tags=[],S.closed=S.closedRoot=S.sawRoot=!1,S.tag=S.error=null,S.strict=!!L,S.noscript=!!(L||S.opt.noscript),S.state=V.BEGIN,S.strictEntities=S.opt.strictEntities,S.ENTITIES=S.strictEntities?Object.create(Q.XML_ENTITIES):Object.create(Q.ENTITIES),S.attribList=[],S.opt.xmlns)S.ns=Object.create(F);if(S.trackPosition=S.opt.position!==!1,S.trackPosition)S.position=S.line=S.column=0;I(S,"onready")}if(!Object.create)Object.create=function(L){function D(){}return D.prototype=L,new D};if(!Object.keys)Object.keys=function(L){var D=[];for(var S in L)if(L.hasOwnProperty(S))D.push(S);return D};function J(L){var D=Math.max(Q.MAX_BUFFER_LENGTH,10),S=0;for(var N=0,D0=Z.length;N<D0;N++){var c0=L[Z[N]].length;if(c0>D)switch(Z[N]){case"textNode":l(L);break;case"cdata":y(L,"oncdata",L.cdata),L.cdata="";break;case"script":y(L,"onscript",L.script),L.script="";break;default:a(L,"Max buffer length exceeded: "+Z[N])}S=Math.max(S,c0)}L.bufferCheckPosition=Q.MAX_BUFFER_LENGTH-S+L.position}function Y(L){for(var D=0,S=Z.length;D<S;D++)L[Z[D]]=""}function W(L){if(l(L),L.cdata!=="")y(L,"oncdata",L.cdata),L.cdata="";if(L.script!=="")y(L,"onscript",L.script),L.script=""}$.prototype={end:function(){aQ(this)},write:aK,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){W(this)}};var X=ReadableStream;if(!X)X=function(){};var q=Q.EVENTS.filter(function(L){return L!=="error"&&L!=="end"});function G(L,D){return new z(L,D)}function z(L,D){if(!(this instanceof z))return new z(L,D);X.apply(this),this._parser=new $(L,D),this.writable=!0,this.readable=!0;var S=this;this._parser.onend=function(){S.emit("end")},this._parser.onerror=function(N){S.emit("error",N),S._parser.error=null},this._decoder=null,q.forEach(function(N){Object.defineProperty(S,"on"+N,{get:function(){return S._parser["on"+N]},set:function(D0){if(!D0)return S.removeAllListeners(N),S._parser["on"+N]=D0,D0;S.on(N,D0)},enumerable:!0,configurable:!1})})}z.prototype=Object.create(X.prototype,{constructor:{value:z}}),z.prototype.write=function(L){return this._parser.write(L.toString()),this.emit("data",L),!0},z.prototype.end=function(L){if(L&&L.length)this.write(L);return this._parser.end(),!0},z.prototype.on=function(L,D){var S=this;if(!S._parser["on"+L]&&q.indexOf(L)!==-1)S._parser["on"+L]=function(){var N=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);N.splice(0,0,L),S.emit.apply(S,N)};return X.prototype.on.call(S,L,D)};var K="[CDATA[",U="DOCTYPE",H="http://www.w3.org/XML/1998/namespace",B="http://www.w3.org/2000/xmlns/",F={xml:H,xmlns:B},w=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,A=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,E=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,P=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function j(L){return L===" "||L===`
123
+ `||L==="\r"||L==="\t"}function R(L){return L==='"'||L==="'"}function k(L){return L===">"||j(L)}function b(L,D){return L.test(D)}function T(L,D){return!b(L,D)}var V=0;Q.STATE={BEGIN:V++,BEGIN_WHITESPACE:V++,TEXT:V++,TEXT_ENTITY:V++,OPEN_WAKA:V++,SGML_DECL:V++,SGML_DECL_QUOTED:V++,DOCTYPE:V++,DOCTYPE_QUOTED:V++,DOCTYPE_DTD:V++,DOCTYPE_DTD_QUOTED:V++,COMMENT_STARTING:V++,COMMENT:V++,COMMENT_ENDING:V++,COMMENT_ENDED:V++,CDATA:V++,CDATA_ENDING:V++,CDATA_ENDING_2:V++,PROC_INST:V++,PROC_INST_BODY:V++,PROC_INST_ENDING:V++,OPEN_TAG:V++,OPEN_TAG_SLASH:V++,ATTRIB:V++,ATTRIB_NAME:V++,ATTRIB_NAME_SAW_WHITE:V++,ATTRIB_VALUE:V++,ATTRIB_VALUE_QUOTED:V++,ATTRIB_VALUE_CLOSED:V++,ATTRIB_VALUE_UNQUOTED:V++,ATTRIB_VALUE_ENTITY_Q:V++,ATTRIB_VALUE_ENTITY_U:V++,CLOSE_TAG:V++,CLOSE_TAG_SAW_WHITE:V++,SCRIPT:V++,SCRIPT_ENDING:V++},Q.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},Q.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(Q.ENTITIES).forEach(function(L){var D=Q.ENTITIES[L],S=typeof D==="number"?String.fromCharCode(D):D;Q.ENTITIES[L]=S});for(var v in Q.STATE)Q.STATE[Q.STATE[v]]=v;V=Q.STATE;function I(L,D,S){L[D]&&L[D](S)}function y(L,D,S){if(L.textNode)l(L);I(L,D,S)}function l(L){if(L.textNode=g(L.opt,L.textNode),L.textNode)I(L,"ontext",L.textNode);L.textNode=""}function g(L,D){if(L.trim)D=D.trim();if(L.normalize)D=D.replace(/\s+/g," ");return D}function a(L,D){if(l(L),L.trackPosition)D+=`
124
+ Line: `+L.line+`
125
+ Column: `+L.column+`
126
+ Char: `+L.c;return D=Error(D),L.error=D,I(L,"onerror",D),L}function aQ(L){if(L.sawRoot&&!L.closedRoot)s(L,"Unclosed root tag");if(L.state!==V.BEGIN&&L.state!==V.BEGIN_WHITESPACE&&L.state!==V.TEXT)a(L,"Unexpected end");return l(L),L.c="",L.closed=!0,I(L,"onend"),$.call(L,L.strict,L.opt),L}function s(L,D){if(typeof L!=="object"||!(L instanceof $))throw Error("bad call to strictFail");if(L.strict)a(L,D)}function u6(L){if(!L.strict)L.tagName=L.tagName[L.looseCase]();var D=L.tags[L.tags.length-1]||L,S=L.tag={name:L.tagName,attributes:{}};if(L.opt.xmlns)S.ns=D.ns;L.attribList.length=0,y(L,"onopentagstart",S)}function BZ(L,D){var S=L.indexOf(":")<0?["",L]:L.split(":"),N=S[0],D0=S[1];if(D&&L==="xmlns")N="xmlns",D0="";return{prefix:N,local:D0}}function JY(L){if(!L.strict)L.attribName=L.attribName[L.looseCase]();if(L.attribList.indexOf(L.attribName)!==-1||L.tag.attributes.hasOwnProperty(L.attribName)){L.attribName=L.attribValue="";return}if(L.opt.xmlns){var D=BZ(L.attribName,!0),S=D.prefix,N=D.local;if(S==="xmlns")if(N==="xml"&&L.attribValue!==H)s(L,"xml: prefix must be bound to "+H+`
127
+ Actual: `+L.attribValue);else if(N==="xmlns"&&L.attribValue!==B)s(L,"xmlns: prefix must be bound to "+B+`
128
+ Actual: `+L.attribValue);else{var D0=L.tag,c0=L.tags[L.tags.length-1]||L;if(D0.ns===c0.ns)D0.ns=Object.create(c0.ns);D0.ns[N]=L.attribValue}L.attribList.push([L.attribName,L.attribValue])}else L.tag.attributes[L.attribName]=L.attribValue,y(L,"onattribute",{name:L.attribName,value:L.attribValue});L.attribName=L.attribValue=""}function p6(L,D){if(L.opt.xmlns){var S=L.tag,N=BZ(L.tagName);if(S.prefix=N.prefix,S.local=N.local,S.uri=S.ns[N.prefix]||"",S.prefix&&!S.uri)s(L,"Unbound namespace prefix: "+JSON.stringify(L.tagName)),S.uri=N.prefix;var D0=L.tags[L.tags.length-1]||L;if(S.ns&&D0.ns!==S.ns)Object.keys(S.ns).forEach(function(ZX){y(L,"onopennamespace",{prefix:ZX,uri:S.ns[ZX]})});for(var c0=0,kQ=L.attribList.length;c0<kQ;c0++){var LQ=L.attribList[c0],eQ=LQ[0],c6=LQ[1],qQ=BZ(eQ,!0),l6=qQ.prefix,eK=qQ.local,QX=l6===""?"":S.ns[l6]||"",WY={name:eQ,value:c6,prefix:l6,local:eK,uri:QX};if(l6&&l6!=="xmlns"&&!QX)s(L,"Unbound namespace prefix: "+JSON.stringify(l6)),WY.uri=l6;L.tag.attributes[eQ]=WY,y(L,"onattribute",WY)}L.attribList.length=0}if(L.tag.isSelfClosing=!!D,L.sawRoot=!0,L.tags.push(L.tag),y(L,"onopentag",L.tag),!D){if(!L.noscript&&L.tagName.toLowerCase()==="script")L.state=V.SCRIPT;else L.state=V.TEXT;L.tag=null,L.tagName=""}L.attribName=L.attribValue="",L.attribList.length=0}function YY(L){if(!L.tagName){s(L,"Weird empty close tag."),L.textNode+="</>",L.state=V.TEXT;return}if(L.script){if(L.tagName!=="script"){L.script+="</"+L.tagName+">",L.tagName="",L.state=V.SCRIPT;return}y(L,"onscript",L.script),L.script=""}var D=L.tags.length,S=L.tagName;if(!L.strict)S=S[L.looseCase]();var N=S;while(D--)if(L.tags[D].name!==N)s(L,"Unexpected close tag");else break;if(D<0){s(L,"Unmatched closing tag: "+L.tagName),L.textNode+="</"+L.tagName+">",L.state=V.TEXT;return}L.tagName=S;var D0=L.tags.length;while(D0-- >D){var c0=L.tag=L.tags.pop();L.tagName=L.tag.name,y(L,"onclosetag",L.tagName);var kQ={};for(var LQ in c0.ns)kQ[LQ]=c0.ns[LQ];var eQ=L.tags[L.tags.length-1]||L;if(L.opt.xmlns&&c0.ns!==eQ.ns)Object.keys(c0.ns).forEach(function(c6){var qQ=c0.ns[c6];y(L,"onclosenamespace",{prefix:c6,uri:qQ})})}if(D===0)L.closedRoot=!0;L.tagName=L.attribValue=L.attribName="",L.attribList.length=0,L.state=V.TEXT}function t3(L){var D=L.entity,S=D.toLowerCase(),N,D0="";if(L.ENTITIES[D])return L.ENTITIES[D];if(L.ENTITIES[S])return L.ENTITIES[S];if(D=S,D.charAt(0)==="#")if(D.charAt(1)==="x")D=D.slice(2),N=parseInt(D,16),D0=N.toString(16);else D=D.slice(1),N=parseInt(D,10),D0=N.toString(10);if(D=D.replace(/^0+/,""),isNaN(N)||D0.toLowerCase()!==D)return s(L,"Invalid character entity"),"&"+L.entity+";";return String.fromCodePoint(N)}function a3(L,D){if(D==="<")L.state=V.OPEN_WAKA,L.startTagPosition=L.position;else if(!j(D))s(L,"Non-whitespace before first tag."),L.textNode=D,L.state=V.TEXT}function e3(L,D){var S="";if(D<L.length)S=L.charAt(D);return S}function aK(L){var D=this;if(this.error)throw this.error;if(D.closed)return a(D,"Cannot write after close. Assign an onready handler.");if(L===null)return aQ(D);if(typeof L==="object")L=L.toString();var S=0,N="";while(!0){if(N=e3(L,S++),D.c=N,!N)break;if(D.trackPosition)if(D.position++,N===`
129
+ `)D.line++,D.column=0;else D.column++;switch(D.state){case V.BEGIN:if(D.state=V.BEGIN_WHITESPACE,N==="\uFEFF")continue;a3(D,N);continue;case V.BEGIN_WHITESPACE:a3(D,N);continue;case V.TEXT:if(D.sawRoot&&!D.closedRoot){var D0=S-1;while(N&&N!=="<"&&N!=="&")if(N=e3(L,S++),N&&D.trackPosition)if(D.position++,N===`
130
+ `)D.line++,D.column=0;else D.column++;D.textNode+=L.substring(D0,S-1)}if(N==="<"&&!(D.sawRoot&&D.closedRoot&&!D.strict))D.state=V.OPEN_WAKA,D.startTagPosition=D.position;else{if(!j(N)&&(!D.sawRoot||D.closedRoot))s(D,"Text data outside of root node.");if(N==="&")D.state=V.TEXT_ENTITY;else D.textNode+=N}continue;case V.SCRIPT:if(N==="<")D.state=V.SCRIPT_ENDING;else D.script+=N;continue;case V.SCRIPT_ENDING:if(N==="/")D.state=V.CLOSE_TAG;else D.script+="<"+N,D.state=V.SCRIPT;continue;case V.OPEN_WAKA:if(N==="!")D.state=V.SGML_DECL,D.sgmlDecl="";else if(j(N));else if(b(w,N))D.state=V.OPEN_TAG,D.tagName=N;else if(N==="/")D.state=V.CLOSE_TAG,D.tagName="";else if(N==="?")D.state=V.PROC_INST,D.procInstName=D.procInstBody="";else{if(s(D,"Unencoded <"),D.startTagPosition+1<D.position){var c0=D.position-D.startTagPosition;N=Array(c0).join(" ")+N}D.textNode+="<"+N,D.state=V.TEXT}continue;case V.SGML_DECL:if((D.sgmlDecl+N).toUpperCase()===K)y(D,"onopencdata"),D.state=V.CDATA,D.sgmlDecl="",D.cdata="";else if(D.sgmlDecl+N==="--")D.state=V.COMMENT,D.comment="",D.sgmlDecl="";else if((D.sgmlDecl+N).toUpperCase()===U){if(D.state=V.DOCTYPE,D.doctype||D.sawRoot)s(D,"Inappropriately located doctype declaration");D.doctype="",D.sgmlDecl=""}else if(N===">")y(D,"onsgmldeclaration",D.sgmlDecl),D.sgmlDecl="",D.state=V.TEXT;else if(R(N))D.state=V.SGML_DECL_QUOTED,D.sgmlDecl+=N;else D.sgmlDecl+=N;continue;case V.SGML_DECL_QUOTED:if(N===D.q)D.state=V.SGML_DECL,D.q="";D.sgmlDecl+=N;continue;case V.DOCTYPE:if(N===">")D.state=V.TEXT,y(D,"ondoctype",D.doctype),D.doctype=!0;else if(D.doctype+=N,N==="[")D.state=V.DOCTYPE_DTD;else if(R(N))D.state=V.DOCTYPE_QUOTED,D.q=N;continue;case V.DOCTYPE_QUOTED:if(D.doctype+=N,N===D.q)D.q="",D.state=V.DOCTYPE;continue;case V.DOCTYPE_DTD:if(D.doctype+=N,N==="]")D.state=V.DOCTYPE;else if(R(N))D.state=V.DOCTYPE_DTD_QUOTED,D.q=N;continue;case V.DOCTYPE_DTD_QUOTED:if(D.doctype+=N,N===D.q)D.state=V.DOCTYPE_DTD,D.q="";continue;case V.COMMENT:if(N==="-")D.state=V.COMMENT_ENDING;else D.comment+=N;continue;case V.COMMENT_ENDING:if(N==="-"){if(D.state=V.COMMENT_ENDED,D.comment=g(D.opt,D.comment),D.comment)y(D,"oncomment",D.comment);D.comment=""}else D.comment+="-"+N,D.state=V.COMMENT;continue;case V.COMMENT_ENDED:if(N!==">")s(D,"Malformed comment"),D.comment+="--"+N,D.state=V.COMMENT;else D.state=V.TEXT;continue;case V.CDATA:if(N==="]")D.state=V.CDATA_ENDING;else D.cdata+=N;continue;case V.CDATA_ENDING:if(N==="]")D.state=V.CDATA_ENDING_2;else D.cdata+="]"+N,D.state=V.CDATA;continue;case V.CDATA_ENDING_2:if(N===">"){if(D.cdata)y(D,"oncdata",D.cdata);y(D,"onclosecdata"),D.cdata="",D.state=V.TEXT}else if(N==="]")D.cdata+="]";else D.cdata+="]]"+N,D.state=V.CDATA;continue;case V.PROC_INST:if(N==="?")D.state=V.PROC_INST_ENDING;else if(j(N))D.state=V.PROC_INST_BODY;else D.procInstName+=N;continue;case V.PROC_INST_BODY:if(!D.procInstBody&&j(N))continue;else if(N==="?")D.state=V.PROC_INST_ENDING;else D.procInstBody+=N;continue;case V.PROC_INST_ENDING:if(N===">")y(D,"onprocessinginstruction",{name:D.procInstName,body:D.procInstBody}),D.procInstName=D.procInstBody="",D.state=V.TEXT;else D.procInstBody+="?"+N,D.state=V.PROC_INST_BODY;continue;case V.OPEN_TAG:if(b(A,N))D.tagName+=N;else if(u6(D),N===">")p6(D);else if(N==="/")D.state=V.OPEN_TAG_SLASH;else{if(!j(N))s(D,"Invalid character in tag name");D.state=V.ATTRIB}continue;case V.OPEN_TAG_SLASH:if(N===">")p6(D,!0),YY(D);else s(D,"Forward-slash in opening tag not followed by >"),D.state=V.ATTRIB;continue;case V.ATTRIB:if(j(N))continue;else if(N===">")p6(D);else if(N==="/")D.state=V.OPEN_TAG_SLASH;else if(b(w,N))D.attribName=N,D.attribValue="",D.state=V.ATTRIB_NAME;else s(D,"Invalid attribute name");continue;case V.ATTRIB_NAME:if(N==="=")D.state=V.ATTRIB_VALUE;else if(N===">")s(D,"Attribute without value"),D.attribValue=D.attribName,JY(D),p6(D);else if(j(N))D.state=V.ATTRIB_NAME_SAW_WHITE;else if(b(A,N))D.attribName+=N;else s(D,"Invalid attribute name");continue;case V.ATTRIB_NAME_SAW_WHITE:if(N==="=")D.state=V.ATTRIB_VALUE;else if(j(N))continue;else if(s(D,"Attribute without value"),D.tag.attributes[D.attribName]="",D.attribValue="",y(D,"onattribute",{name:D.attribName,value:""}),D.attribName="",N===">")p6(D);else if(b(w,N))D.attribName=N,D.state=V.ATTRIB_NAME;else s(D,"Invalid attribute name"),D.state=V.ATTRIB;continue;case V.ATTRIB_VALUE:if(j(N))continue;else if(R(N))D.q=N,D.state=V.ATTRIB_VALUE_QUOTED;else s(D,"Unquoted attribute value"),D.state=V.ATTRIB_VALUE_UNQUOTED,D.attribValue=N;continue;case V.ATTRIB_VALUE_QUOTED:if(N!==D.q){if(N==="&")D.state=V.ATTRIB_VALUE_ENTITY_Q;else D.attribValue+=N;continue}JY(D),D.q="",D.state=V.ATTRIB_VALUE_CLOSED;continue;case V.ATTRIB_VALUE_CLOSED:if(j(N))D.state=V.ATTRIB;else if(N===">")p6(D);else if(N==="/")D.state=V.OPEN_TAG_SLASH;else if(b(w,N))s(D,"No whitespace between attributes"),D.attribName=N,D.attribValue="",D.state=V.ATTRIB_NAME;else s(D,"Invalid attribute name");continue;case V.ATTRIB_VALUE_UNQUOTED:if(!k(N)){if(N==="&")D.state=V.ATTRIB_VALUE_ENTITY_U;else D.attribValue+=N;continue}if(JY(D),N===">")p6(D);else D.state=V.ATTRIB;continue;case V.CLOSE_TAG:if(!D.tagName)if(j(N))continue;else if(T(w,N))if(D.script)D.script+="</"+N,D.state=V.SCRIPT;else s(D,"Invalid tagname in closing tag.");else D.tagName=N;else if(N===">")YY(D);else if(b(A,N))D.tagName+=N;else if(D.script)D.script+="</"+D.tagName,D.tagName="",D.state=V.SCRIPT;else{if(!j(N))s(D,"Invalid tagname in closing tag");D.state=V.CLOSE_TAG_SAW_WHITE}continue;case V.CLOSE_TAG_SAW_WHITE:if(j(N))continue;if(N===">")YY(D);else s(D,"Invalid characters in closing tag");continue;case V.TEXT_ENTITY:case V.ATTRIB_VALUE_ENTITY_Q:case V.ATTRIB_VALUE_ENTITY_U:var kQ,LQ;switch(D.state){case V.TEXT_ENTITY:kQ=V.TEXT,LQ="textNode";break;case V.ATTRIB_VALUE_ENTITY_Q:kQ=V.ATTRIB_VALUE_QUOTED,LQ="attribValue";break;case V.ATTRIB_VALUE_ENTITY_U:kQ=V.ATTRIB_VALUE_UNQUOTED,LQ="attribValue";break}if(N===";")if(D.opt.unparsedEntities){var eQ=t3(D);D.entity="",D.state=kQ,D.write(eQ)}else D[LQ]+=t3(D),D.entity="",D.state=kQ;else if(b(D.entity.length?P:E,N))D.entity+=N;else s(D,"Invalid character in entity name"),D[LQ]+="&"+D.entity+N,D.entity="",D.state=kQ;continue;default:throw Error(D,"Unknown state: "+D.state)}}if(D.position>=D.bufferCheckPosition)J(D);return D}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */if(!String.fromCodePoint)(function(){var L=String.fromCharCode,D=Math.floor,S=function(){var N=16384,D0=[],c0,kQ,LQ=-1,eQ=arguments.length;if(!eQ)return"";var c6="";while(++LQ<eQ){var qQ=Number(arguments[LQ]);if(!isFinite(qQ)||qQ<0||qQ>1114111||D(qQ)!==qQ)throw RangeError("Invalid code point: "+qQ);if(qQ<=65535)D0.push(qQ);else qQ-=65536,c0=(qQ>>10)+55296,kQ=qQ%1024+56320,D0.push(c0,kQ);if(LQ+1===eQ||D0.length>N)c6+=L.apply(null,D0),D0.length=0}return c6};if(Object.defineProperty)Object.defineProperty(String,"fromCodePoint",{value:S,configurable:!0,writable:!0});else String.fromCodePoint=S})();return Q},w2=dB();var n9=`The output should be formatted as a XML file.
131
+ 1. Output should conform to the tags below.
132
+ 2. If tags are not given, make them on your own.
133
+ 3. Remember to always open and close all the tags.
134
+
135
+ As an example, for the tags ["foo", "bar", "baz"]:
136
+ 1. String "<foo>
137
+ <bar>
138
+ <baz></baz>
139
+ </bar>
140
+ </foo>" is a well-formatted instance of the schema.
141
+ 2. String "<foo>
142
+ <bar>
143
+ </foo>" is a badly-formatted instance.
144
+ 3. String "<foo>
145
+ <tag>
146
+ </tag>
147
+ </foo>" is a badly-formatted instance.
148
+
149
+ Here are the output tags:
150
+ \`\`\`
151
+ {tags}
152
+ \`\`\``,A2=class extends y8{tags;constructor(Q){super(Q);this.tags=Q?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(Q,Z){if(!Z)return;if(!Q)return[{op:"replace",path:"",value:Z}];return $6(Q,Z)}async parsePartialResult(Q){return r9(Q[0].text)}async parse(Q){return r9(Q)}getFormatInstructions(){return this.tags&&this.tags.length>0?n9.replace("{tags}",this.tags?.join(", ")??""):n9}},uB=(Q)=>Q.split(`
153
+ `).map((Z)=>Z.replace(/^\s+/,"")).join(`
154
+ `).trim(),P2=(Q)=>{if(Object.keys(Q).length===0)return{};let Z={};if(Q.children.length>0)return Z[Q.name]=Q.children.map(P2),Z;else return Z[Q.name]=Q.text??void 0,Z};function r9(Q){let Z=uB(Q),$=w2.parser(!0),J={},Y=[];$.onopentag=(q)=>{let G={name:q.name,attributes:q.attributes,children:[],text:"",isSelfClosing:q.isSelfClosing};if(Y.length>0)Y[Y.length-1].children.push(G);else J=G;if(!q.isSelfClosing)Y.push(G)},$.onclosetag=()=>{if(Y.length>0){let q=Y.pop();if(Y.length===0&&q)J=q}},$.ontext=(q)=>{if(Y.length>0){let G=Y[Y.length-1];G.text+=q}},$.onattribute=(q)=>{if(Y.length>0){let G=Y[Y.length-1];G.attributes[q.name]=q.value}};let W=/```(xml)?(.*)```/s.exec(Z),X=W?W[2]:Z;if($.write(X).close(),J&&J.name==="?xml")J=J.children[0];return P2(J)}var N2=_({AsymmetricStructuredOutputParser:()=>U2,BaseCumulativeTransformOutputParser:()=>y8,BaseLLMOutputParser:()=>m1,BaseOutputParser:()=>z8,BaseTransformOutputParser:()=>W6,BytesOutputParser:()=>H2,CommaSeparatedListOutputParser:()=>B2,CustomListOutputParser:()=>D2,JsonMarkdownStructuredOutputParser:()=>JW,JsonOutputParser:()=>i9,ListOutputParser:()=>d1,MarkdownListOutputParser:()=>F2,NumberedListOutputParser:()=>V2,OutputParserException:()=>UQ,StandardSchemaOutputParser:()=>o9,StringOutputParser:()=>L2,StructuredOutputParser:()=>gZ,XMLOutputParser:()=>A2,XML_FORMAT_INSTRUCTIONS:()=>n9,parseJsonMarkdown:()=>n6,parsePartialJson:()=>Q8,parseXMLMarkdown:()=>r9});function YW(Q,Z){if(Q.function===void 0)return;let $;if(Z?.partial)try{$=Q8(Q.function.arguments??"{}")}catch{return}else try{$=JSON.parse(Q.function.arguments)}catch(Y){throw new UQ([`Function "${Q.function.name}" arguments:`,"",Q.function.arguments,"","are not valid JSON.",`Error: ${Y.message}`].join(`
155
+ `))}let J={name:Q.function.name,args:$,type:"tool_call"};if(Z?.returnId)J.id=Q.id;return J}function O2(Q){if(Q.id===void 0)throw Error('All OpenAI tool calls must have an "id" field.');return{id:Q.id,type:"function",function:{name:Q.name,arguments:JSON.stringify(Q.args)}}}function E2(Q,Z){return{name:Q.function?.name,args:Q.function?.arguments,id:Q.id,error:Z,type:"invalid_tool_call"}}var WW=class extends y8{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(Q){super(Q);this.returnId=Q?.returnId??this.returnId}_diff(){throw Error("Not supported.")}async parse(){throw Error("Not implemented.")}async parseResult(Q){return await this.parsePartialResult(Q,!1)}async parsePartialResult(Q,Z=!0){let $=Q[0].message,J;if(I1($)&&$.tool_calls?.length)J=$.tool_calls.map((W)=>{let{id:X,...q}=W;if(!this.returnId)return q;return{id:X,...q}});else if($.additional_kwargs.tool_calls!==void 0)J=JSON.parse(JSON.stringify($.additional_kwargs.tool_calls)).map((W)=>{return YW(W,{returnId:this.returnId,partial:Z})});if(!J)return[];let Y=[];for(let W of J)if(W!==void 0){let X={type:W.name,args:W.args,id:W.id};Y.push(X)}return Y}},s9=class extends WW{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(Q){super(Q);if(this.keyName=Q.keyName,this.returnSingle=Q.returnSingle??this.returnSingle,"zodSchema"in Q)this.zodSchema=Q.zodSchema;if("serializableSchema"in Q)this.serializableSchema=Q.serializableSchema}async _validateResult(Q){if(this.serializableSchema!==void 0){let $=await this.serializableSchema["~standard"].validate(Q);if($.issues)throw new UQ(`Failed to parse. Text: "${JSON.stringify(Q,null,2)}". Error: ${JSON.stringify($.issues)}`,JSON.stringify(Q,null,2));return $.value}if(this.zodSchema===void 0)return Q;let Z=await C1(this.zodSchema,Q);if(Z.success)return Z.data;else throw new UQ(`Failed to parse. Text: "${JSON.stringify(Q,null,2)}". Error: ${JSON.stringify(Z.error?.issues)}`,JSON.stringify(Q,null,2))}async parsePartialResult(Q){let Z=(await super.parsePartialResult(Q)).filter((J)=>J.type===this.keyName),$=Z;if(!Z.length)return;if(!this.returnId)$=Z.map((J)=>J.args);if(this.returnSingle)return $[0];return $}async parseResult(Q){let Z=(await super.parsePartialResult(Q,!1)).filter((J)=>J.type===this.keyName),$=Z;if(!Z.length)return;if(!this.returnId)$=Z.map((J)=>J.args);if(this.returnSingle)return this._validateResult($[0]);return await Promise.all($.map((J)=>this._validateResult(J)))}};var j2=_({extendInteropZodObject:()=>D9,getInteropZodDefaultGetter:()=>T6,getInteropZodObjectShape:()=>e8,getSchemaDescription:()=>W8,interopParse:()=>xQ,interopParseAsync:()=>_6,interopSafeParse:()=>q4,interopSafeParseAsync:()=>C1,interopZodObjectMakeFieldsOptional:()=>F9,interopZodObjectPartial:()=>I6,interopZodObjectPassthrough:()=>U9,interopZodObjectStrict:()=>y1,interopZodTransformInputSchema:()=>V9,isInteropZodError:()=>L9,isInteropZodLiteral:()=>Xq,isInteropZodObject:()=>_0,isInteropZodSchema:()=>ZQ,isShapelessZodSchema:()=>qq,isSimpleStringZodSchema:()=>b1,isZodArrayV4:()=>RZ,isZodLiteralV3:()=>W4,isZodLiteralV4:()=>X4,isZodNullableV4:()=>z4,isZodObjectV3:()=>B9,isZodObjectV4:()=>lQ,isZodOptionalV4:()=>G4,isZodSchema:()=>Wq,isZodSchemaV3:()=>x0,isZodSchemaV4:()=>H0});var R2=_({assembleStructuredOutputPipeline:()=>XW,createContentParser:()=>pB,createFunctionCallingParser:()=>cB});function pB(Q){if(ZQ(Q))return gZ.fromZodSchema(Q);if(iQ(Q))return o9.fromSerializableSchema(Q);return new i9}function cB(Q,Z,$){let J=$??s9;if(ZQ(Q))return new J({returnSingle:!0,keyName:Z,zodSchema:Q});if(iQ(Q))return new J({returnSingle:!0,keyName:Z,serializableSchema:Q});return new J({returnSingle:!0,keyName:Z})}function XW(Q,Z,$,J){if(!$){let G=Q.pipe(Z);return J?G.withConfig({runName:J}):G}let Y=Y6.assign({parsed:(G,z)=>Z.invoke(G.raw,z)}),W=Y6.assign({parsed:()=>null}),X=Y.withFallbacks({fallbacks:[W]}),q=s0.from([{raw:Q},X]);return J?q.withConfig({runName:J}):q}var _2=_({BaseChatModel:()=>K8,SimpleChatModel:()=>lB});function qW(Q){let Z=[];for(let $ of Q){let J=$;if(Array.isArray($.content))for(let Y=0;Y<$.content.length;Y++){let W=$.content[Y];if(E1(W)||j1(W)){if(J===$)J=new $.constructor({...J,content:[...$.content.slice(0,Y),_$(W),...$.content.slice(Y+1)]})}}Z.push(J)}return Z}var K8=class Q extends K1{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(Z){super(Z);this.outputVersion=W2(()=>{let $=Z.outputVersion??wQ("LC_OUTPUT_VERSION");if($&&["v0","v1"].includes($))return $;return"v0"})}_separateRunnableConfigFromCallOptionsCompat(Z){let[$,J]=super._separateRunnableConfigFromCallOptions(Z);return J.signal=$.signal,[$,J]}async invoke(Z,$){let J=Q._convertInputToPromptValue(Z);return(await this.generatePrompt([J],$,$?.callbacks)).generations[0][0].message}async*_streamResponseChunks(Z,$,J){throw Error("Not implemented.")}async*_streamIterator(Z,$){if(this._streamResponseChunks===Q.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(Z,$);else{let J=Q._convertInputToPromptValue(Z).toChatMessages(),[Y,W]=this._separateRunnableConfigFromCallOptionsCompat($),X={...Y.metadata,...this.getLsParams(W)},q=await d0.configure(Y.callbacks,this.callbacks,Y.tags,this.tags,X,this.metadata,{verbose:this.verbose}),G={options:W,invocation_params:this?.invocationParams(W),batch_size:1},z=W.outputVersion??this.outputVersion,K=await q?.handleChatModelStart(this.toJSON(),[qW(J)],Y.runId,void 0,G,void 0,void 0,Y.runName),U,H;try{for await(let B of this._streamResponseChunks(J,W,K?.[0])){if(W.signal?.throwIfAborted(),B.message.id==null){let F=K?.at(0)?.runId;if(F!=null)B.message._updateId(`run-${F}`)}if(B.message.response_metadata={...B.generationInfo,...B.message.response_metadata},z==="v1")yield l9(B.message);else yield B.message;if(!U)U=B;else U=U.concat(B);if(AZ(B.message)&&B.message.usage_metadata!==void 0)H={tokenUsage:{promptTokens:B.message.usage_metadata.input_tokens,completionTokens:B.message.usage_metadata.output_tokens,totalTokens:B.message.usage_metadata.total_tokens}}}W.signal?.throwIfAborted()}catch(B){throw await Promise.all((K??[]).map((F)=>F?.handleLLMError(B))),B}await Promise.all((K??[]).map((B)=>B?.handleLLMEnd({generations:[[U]],llmOutput:H})))}}getLsParams(Z){let $=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:Z.stop,ls_provider:$}}async _generateUncached(Z,$,J,Y){let W=Z.map((U)=>U.map(KQ)),X;if(Y!==void 0&&Y.length===W.length)X=Y;else{let U={...J.metadata,...this.getLsParams($)},H=await d0.configure(J.callbacks,this.callbacks,J.tags,this.tags,U,this.metadata,{verbose:this.verbose}),B={options:$,invocation_params:this?.invocationParams($),batch_size:1};X=await H?.handleChatModelStart(this.toJSON(),W.map(qW),J.runId,void 0,B,void 0,void 0,J.runName)}let q=$.outputVersion??this.outputVersion,G=[],z=[];if(!!X?.[0].handlers.find(PZ)&&!this.disableStreaming&&W.length===1&&this._streamResponseChunks!==Q.prototype._streamResponseChunks)try{let U=await this._streamResponseChunks(W[0],$,X?.[0]),H,B;for await(let F of U){if($.signal?.aborted){let w=H?.message;throw new j$("Model invocation was aborted.",w)}if(F.message.id==null){let w=X?.at(0)?.runId;if(w!=null)F.message._updateId(`run-${w}`)}if(H===void 0)H=F;else H=uQ(H,F);if(AZ(F.message)&&F.message.usage_metadata!==void 0)B={tokenUsage:{promptTokens:F.message.usage_metadata.input_tokens,completionTokens:F.message.usage_metadata.output_tokens,totalTokens:F.message.usage_metadata.total_tokens}}}if($.signal?.aborted){let F=H?.message;throw new j$("Model invocation was aborted.",F)}if(H===void 0)throw Error("Received empty response from chat model call.");G.push([H]),await X?.[0].handleLLMEnd({generations:G,llmOutput:B})}catch(U){throw await X?.[0].handleLLMError(U),U}else{let U=await Promise.allSettled(W.map(async(H,B)=>{let F=await this._generate(H,{...$,promptIndex:B},X?.[B]);if(q==="v1")for(let w of F.generations)w.message=l9(w.message);return F}));await Promise.all(U.map(async(H,B)=>{if(H.status==="fulfilled"){let F=H.value;for(let w of F.generations){if(w.message.id==null){let A=X?.at(0)?.runId;if(A!=null)w.message._updateId(`run-${A}`)}w.message.response_metadata={...w.generationInfo,...w.message.response_metadata}}if(F.generations.length===1)F.generations[0].message.response_metadata={...F.llmOutput,...F.generations[0].message.response_metadata};return G[B]=F.generations,z[B]=F.llmOutput,X?.[B]?.handleLLMEnd({generations:[F.generations],llmOutput:F.llmOutput})}else return await X?.[B]?.handleLLMError(H.reason),Promise.reject(H.reason)}))}let K={generations:G,llmOutput:z.length?this._combineLLMOutput?.(...z):void 0};return Object.defineProperty(K,X1,{value:X?{runIds:X?.map((U)=>U.runId)}:void 0,configurable:!0}),K}async _generateCached({messages:Z,cache:$,llmStringKey:J,parsedOptions:Y,handledOptions:W}){let X=Z.map((A)=>A.map(KQ)),q={...W.metadata,...this.getLsParams(Y)},G=await d0.configure(W.callbacks,this.callbacks,W.tags,this.tags,q,this.metadata,{verbose:this.verbose}),z={options:Y,invocation_params:this?.invocationParams(Y),batch_size:1},K=await G?.handleChatModelStart(this.toJSON(),X.map(qW),W.runId,void 0,z,void 0,void 0,W.runName),U=[],H=(await Promise.allSettled(X.map(async(A,E)=>{let P=Q._convertInputToPromptValue(A).toString(),j=await $.lookup(P,J);if(j==null)U.push(E);return j}))).map((A,E)=>({result:A,runManager:K?.[E]})).filter(({result:A})=>A.status==="fulfilled"&&A.value!=null||A.status==="rejected"),B=Y.outputVersion??this.outputVersion,F=[];await Promise.all(H.map(async({result:A,runManager:E},P)=>{if(A.status==="fulfilled"){let j=A.value;if(F[P]=j.map((R)=>{if("message"in R&&R0(R.message)&&I1(R.message)){if(R.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},B==="v1")R.message=l9(R.message)}return R.generationInfo={...R.generationInfo,tokenUsage:{}},R}),j.length)await E?.handleLLMNewToken(j[0].text);return E?.handleLLMEnd({generations:[j]},void 0,void 0,void 0,{cached:!0})}else return await E?.handleLLMError(A.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(A.reason)}));let w={generations:F,missingPromptIndices:U,startedRunManagers:K};return Object.defineProperty(w,X1,{value:K?{runIds:K?.map((A)=>A.runId)}:void 0,configurable:!0}),w}async generate(Z,$,J){let Y;if(Array.isArray($))Y={stop:$};else Y=$;let W=Z.map((F)=>F.map(KQ)),[X,q]=this._separateRunnableConfigFromCallOptionsCompat(Y);if(X.callbacks=X.callbacks??J,!this.cache)return this._generateUncached(W,q,X);let{cache:G}=this,z=this._getSerializedCacheKeyParametersForCall(q),{generations:K,missingPromptIndices:U,startedRunManagers:H}=await this._generateCached({messages:W,cache:G,llmStringKey:z,parsedOptions:q,handledOptions:X}),B={};if(U.length>0){let F=await this._generateUncached(U.map((w)=>W[w]),q,X,H!==void 0?U.map((w)=>H?.[w]):void 0);await Promise.all(F.generations.map(async(w,A)=>{let E=U[A];K[E]=w;let P=Q._convertInputToPromptValue(W[E]).toString();return G.update(P,z,w)})),B=F.llmOutput??{}}return{generations:K,llmOutput:B}}invocationParams(Z){return{}}_modelType(){return"base_chat_model"}async generatePrompt(Z,$,J){let Y=Z.map((W)=>W.toChatMessages());return this.generate(Y,$,J)}withStructuredOutput(Z,$){if(typeof this.bindTools!=="function")throw Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if($?.strict)throw Error('"strict" mode is not supported for this model by default.');let J=Z,Y=$?.name,W=W8(J)??"A function available to call.",X=$?.method,q=$?.includeRaw;if(X==="jsonMode")throw Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let G=Y??"extract";if(!ZQ(J)&&!iQ(J)&&"name"in J)G=J.name;let z=ZQ(J)||iQ(J)?M0(J):J,K=[{type:"function",function:{name:G,description:W,parameters:z}}];return XW(this.bindTools(K),i0.from((U)=>{if(!y0.isInstance(U))throw Error("Input is not an AIMessageChunk.");if(!U.tool_calls||U.tool_calls.length===0)throw Error("No tool calls found in the response.");let H=U.tool_calls.find((B)=>B.name===G);if(!H)throw Error(`No tool call found with name ${G}.`);return H.args}),q,q?"StructuredOutputRunnable":"StructuredOutput")}},lB=class extends K8{async _generate(Q,Z,$){let J=new h(await this._call(Q,Z,$));if(typeof J.content!=="string")throw Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:J.content,message:J}]}}};var t9={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}},T2=Object.keys(t9);async function oB(Q,Z){let $;if(Z)$=t9[Z];else{let J=Object.entries(t9).find(([,Y])=>Y.className===Q);$=J?J[1]:void 0}if(!$)return;try{return(await import($.package))[$.className]}catch(J){let Y=J;if("code"in Y&&Y.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in Y&&typeof Y.message==="string"){let W=(Y.message.startsWith("Error: ")?Y.message.slice(7):Y.message).split("Cannot find package '")[1].split("'")[0];throw Error(`Unable to import ${W}. Please install with \`npm install ${W}\` or \`pnpm install ${W}\``)}throw J}}async function nB(Q,Z,$={}){let J=Z||rB(Q);if(!J)throw Error(`Unable to infer model provider for { model: ${Q} }, please specify modelProvider directly.`);let Y=t9[J];if(!Y){let q=T2.join(", ");throw Error(`Unsupported { modelProvider: ${J} }.
156
+
157
+ Supported model providers are: ${q}`)}let{modelProvider:W,...X}=$;return new(await oB(Y.className,J))({model:Q,...X})}function rB(Q){if(Q.startsWith("gpt-3")||Q.startsWith("gpt-4")||Q.startsWith("gpt-5")||Q.startsWith("o1")||Q.startsWith("o3")||Q.startsWith("o4"))return"openai";else if(Q.startsWith("claude"))return"anthropic";else if(Q.startsWith("command"))return"cohere";else if(Q.startsWith("accounts/fireworks"))return"fireworks";else if(Q.startsWith("gemini"))return"google-vertexai";else if(Q.startsWith("amazon."))return"bedrock";else if(Q.startsWith("mistral"))return"mistralai";else if(Q.startsWith("sonar")||Q.startsWith("pplx"))return"perplexity";else return}var I2=class Q extends K8{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(Z){super(Z);if(this._defaultConfig=Z.defaultConfig??{},Z.configurableFields==="any")this._configurableFields="any";else this._configurableFields=Z.configurableFields??["model","modelProvider"];if(Z.configPrefix)this._configPrefix=Z.configPrefix.endsWith("_")?Z.configPrefix:`${Z.configPrefix}_`;else this._configPrefix="";this._queuedMethodOperations=Z.queuedMethodOperations??this._queuedMethodOperations,this._profile=Z.profile??void 0}async _getModelInstance(Z){let $=this._getCacheKey(Z),J=this._modelInstanceCache.get($);if(J)return J;let Y={...this._defaultConfig,...this._modelParams(Z)},W=await nB(Y.model,Y.modelProvider,Y);for(let[X,q]of Object.entries(this._queuedMethodOperations))if(X in W&&typeof W[X]==="function")W=await W[X](...q);return this._modelInstanceCache.set($,W),W}async _generate(Z,$,J){return(await this._getModelInstance($))._generate(Z,$??{},J)}bindTools(Z,$){let J={...this._queuedMethodOperations};return J.bindTools=[Z,$],new Q({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:J})}withStructuredOutput=(Z,...$)=>{let J={...this._queuedMethodOperations};return J.withStructuredOutput=[Z,...$],new Q({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:J})};_modelParams(Z){let $=Z?.configurable??{},J={};for(let[Y,W]of Object.entries($))if(Y.startsWith(this._configPrefix)){let X=this._removePrefix(Y,this._configPrefix);J[X]=W}if(this._configurableFields!=="any")J=Object.fromEntries(Object.entries(J).filter(([Y])=>this._configurableFields.includes(Y)));return J}_removePrefix(Z,$){return Z.startsWith($)?Z.slice($.length):Z}withConfig(Z){let $={...Z||{}},J=this._modelParams($),Y=Object.fromEntries(Object.entries($).filter(([W])=>W!=="configurable"));return Y.configurable=Object.fromEntries(Object.entries($.configurable||{}).filter(([W])=>this._configPrefix&&!Object.keys(J).includes(this._removePrefix(W,this._configPrefix)))),new b0({config:$,bound:new Q({defaultConfig:{...this._defaultConfig,...J},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(Z,$){let J=await this._getModelInstance($),Y=t($);return J.invoke(Z,Y)}async stream(Z,$){let J=new x8({generator:await(await this._getModelInstance($)).stream(Z,$),config:$});return await J.setup,S0.fromAsyncGenerator(J)}async batch(Z,$,J){return super.batch(Z,$,J)}async*transform(Z,$){let J=await this._getModelInstance($),Y=t($);yield*J.transform(Z,Y)}async*streamLog(Z,$,J){let Y=await this._getModelInstance($),W=t($);yield*Y.streamLog(Z,W,{...J,_schemaFormat:"original",includeNames:J?.includeNames,includeTypes:J?.includeTypes,includeTags:J?.includeTags,excludeNames:J?.excludeNames,excludeTypes:J?.excludeTypes,excludeTags:J?.excludeTags})}streamEvents(Z,$,J){let Y=this;async function*W(){let X=await Y._getModelInstance($),q=t($),G=X.streamEvents(Z,q,J);for await(let z of G)yield z}return S0.fromAsyncGenerator(W())}get profile(){if(this._profile)return this._profile;let Z=this._getCacheKey({});return this._modelInstanceCache.get(Z)?.profile??{}}_getCacheKey(Z){let $=Z??{};if($.configurable){let{configurable:J}=$,Y={};for(let[W,X]of Object.entries(J))if(!W.startsWith("__pregel_"))Y[W]=X;$={...$,configurable:Y}}return JSON.stringify($)}};async function v6(Q,Z){let{configurableFields:$,configPrefix:J,modelProvider:Y,profile:W,...X}={configPrefix:"",...Z??{}};if(Y===void 0&&Q?.includes(":")){let[K,...U]=Q.split(":"),H=U.length===0?[K]:[K,U.join(":")];if(T2.includes(H[0]))[Y,Q]=H}let q=Array.isArray($)?[...$]:$;if(!Q&&q===void 0)q=["model","modelProvider"];if(J&&q===void 0)console.warn(`{ configPrefix: ${J} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let G={...X},z;if(q===void 0)z=new I2({defaultConfig:{...G,model:Q,modelProvider:Y},configPrefix:J,profile:W});else{if(Q)G.model=Q;if(Y)G.modelProvider=Y;z=new I2({defaultConfig:G,configPrefix:J,configurableFields:q,profile:W})}return await z._getModelInstance(),z}import{AsyncLocalStorage as sB}from"node:async_hooks";function S2(){q0.initializeGlobalInstance(new sB)}var Q0="__start__",m="__end__",C8="__input__",M2="__copy__",t0="__error__",e9="__pregel_ns_writes",U8="__pregel_send",QJ="__pregel_call",b8="__pregel_read",k0="__pregel_checkpointer",X6="__pregel_resuming",u1="__pregel_task_id",dZ="__pregel_stream";var p1="__pregel_resume_map",nQ="__pregel_scratchpad",uZ="__pregel_previous",v2="__pregel_durability",GW="checkpoint_id",rQ="checkpoint_ns",y2="__pregel_node_finished",MQ="checkpoint_map",zW="__pregel_abort_signals",J0="__interrupt__",JQ="__resume__",ZJ="__no_writes__",H8="__return__",U1="__previous__",K0="langsmith:hidden",C2="langsmith:nostream",KW="__self__",YQ="__pregel_tasks",HQ="__pregel_push",pZ="__pregel_pull",BQ="00000000-0000-0000-0000-000000000000",b2=["langsmith:hidden","__input__","__interrupt__","__resume__","__error__","__no_writes__","__pregel_send","__pregel_read","__pregel_checkpointer","__pregel_durability","__pregel_stream","__pregel_resuming","__pregel_task_id","__pregel_call","__pregel_resume_value","__pregel_scratchpad","__pregel_previous","checkpoint_map","checkpoint_ns","checkpoint_id"],P0="|",EQ=":",a9=Symbol.for("langgraph.command"),$J=class{[a9];constructor(Q){this[a9]=Q}};function JJ(Q){let Z=Q;return Z!==null&&Z!==void 0&&typeof Z.node==="string"&&Z.args!==void 0}var u0=class{lg_name="Send";node;args;constructor(Q,Z){this.node=Q,this.args=mZ(Z)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function o0(Q){return Q instanceof u0}var x2="__overwrite__";function YJ(Q){if(typeof Q==="object"&&Q!==null&&x2 in Q)return[!0,Q[x2]];return[!1,void 0]}function k2(Q){return YJ(Q)[0]}function c1(Q){if(!Q||typeof Q!=="object")return!1;if(!("__interrupt__"in Q))return!1;return Array.isArray(Q.__interrupt__)}var B0=class extends $J{lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(Q){super(Q);if(this.resume=Q.resume,this.graph=Q.graph,this.update=Q.update,Q.goto)this.goto=Array.isArray(Q.goto)?mZ(Q.goto):[mZ(Q.goto)]}_updateAsTuples(){if(this.update&&typeof this.update==="object"&&!Array.isArray(this.update))return Object.entries(this.update);else if(Array.isArray(this.update)&&this.update.every((Q)=>Array.isArray(Q)&&Q.length===2&&typeof Q[0]==="string"))return this.update;else return[["__root__",this.update]]}toJSON(){let Q;if(typeof this.goto==="string")Q=this.goto;else if(o0(this.goto))Q=this.goto.toJSON();else Q=this.goto?.map((Z)=>{if(typeof Z==="string")return Z;else return Z.toJSON()});return{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:Q}}};function z0(Q){if(typeof Q!=="object")return!1;if(Q===null||Q===void 0)return!1;if("lg_name"in Q&&Q.lg_name==="Command")return!0;return!1}function mZ(Q,Z=new Map){if(Q!==void 0&&Q!==null&&typeof Q==="object"){if(Z.has(Q))return Z.get(Q);let $;if(Array.isArray(Q))$=[],Z.set(Q,$),Q.forEach((J,Y)=>{$[Y]=mZ(J,Z)});else if(z0(Q)&&!(Q instanceof B0))$=new B0(Q),Z.set(Q,$);else if(JJ(Q)&&!(Q instanceof u0))$=new u0(Q.node,Q.args),Z.set(Q,$);else if(z0(Q)||o0(Q))$=Q,Z.set(Q,$);else if("lc_serializable"in Q&&Q.lc_serializable)$=Q,Z.set(Q,$);else{$={},Z.set(Q,$);for(let[J,Y]of Object.entries(Q))$[J]=mZ(Y,Z)}return $}return Q}var k8=class extends Error{lc_error_code;constructor(Q,Z){let $=Q??"";if(Z?.lc_error_code)$=`${$}
158
+
159
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${Z.lc_error_code}/
160
+ `;super($);this.lc_error_code=Z?.lc_error_code}},WJ=class extends k8{get is_bubble_up(){return!0}},XJ=class extends k8{constructor(Q,Z){super(Q,Z);this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},y6=class extends k8{constructor(Q,Z){super(Q,Z);this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},f8=class extends WJ{interrupts;constructor(Q,Z){super(JSON.stringify(Q,null,2),Z);this.name="GraphInterrupt",this.interrupts=Q??[]}static get unminifiable_name(){return"GraphInterrupt"}},cZ=class extends f8{constructor(Q,Z){super([{value:Q}],Z);this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},lZ=class extends WJ{command;constructor(Q){super();this.name="ParentCommand",this.command=Q}static get unminifiable_name(){return"ParentCommand"}};function qJ(Q){return Q!==void 0&&Q.name===lZ.unminifiable_name}function h8(Q){return Q!==void 0&&Q.is_bubble_up===!0}function sQ(Q){return Q!==void 0&&[f8.unminifiable_name,cZ.unminifiable_name].includes(Q.name)}var iZ=class extends k8{constructor(Q,Z){super(Q,Z);this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},U0=class extends k8{constructor(Q,Z){super(Q,Z);this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},Z0=class extends k8{constructor(Q,Z){super(Q,Z);this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}};var GJ=class extends k8{constructor(Q,Z){super(Q,Z);this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};var l1=class extends k8{constructor(Q,Z){super(Q,Z);this.name="StateGraphInputError",this.message="Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema."}static get unminifiable_name(){return"StateGraphInputError"}};$8();function oZ(Q){return f2({clockseq:Q})}function q6(Q,Z){let $=Z.replace(/-/g,"").match(/.{2}/g).map((J)=>parseInt(J,16));return $1(Q,new Uint8Array($))}var UW="__error__",H1="__scheduled__",HW="__interrupt__",BW="__resume__";var h2="[...]",tB="[Circular]",zJ=[],i1=[];function aB(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function g2(Q,Z,$,J){if(typeof J>"u")J=aB();VW(Q,"",0,[],void 0,0,J);var Y;try{if(i1.length===0)Y=JSON.stringify(Q,Z,$);else Y=JSON.stringify(Q,eB(Z),$)}catch(X){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{while(zJ.length!==0){var W=zJ.pop();if(W.length===4)Object.defineProperty(W[0],W[1],W[3]);else W[0][W[1]]=W[2]}}return Y}function DW(Q,Z,$,J){var Y=Object.getOwnPropertyDescriptor(J,$);if(Y.get!==void 0)if(Y.configurable)Object.defineProperty(J,$,{value:Q}),zJ.push([J,$,Z,Y]);else i1.push([Z,$,Q]);else J[$]=Q,zJ.push([J,$,Z])}function VW(Q,Z,$,J,Y,W,X){W+=1;var q;if(typeof Q==="object"&&Q!==null){for(q=0;q<J.length;q++)if(J[q]===Q){DW(tB,Q,Z,Y);return}if(typeof X.depthLimit<"u"&&W>X.depthLimit){DW(h2,Q,Z,Y);return}if(typeof X.edgesLimit<"u"&&$+1>X.edgesLimit){DW(h2,Q,Z,Y);return}if(J.push(Q),Array.isArray(Q))for(q=0;q<Q.length;q++)VW(Q[q],q,q,J,Q,W,X);else{var G=Object.keys(Q);for(q=0;q<G.length;q++){var z=G[q];VW(Q[z],z,q,J,Q,W,X)}}J.pop()}}function eB(Q){return Q=typeof Q<"u"?Q:function(Z,$){return $},function(Z,$){if(i1.length>0)for(var J=0;J<i1.length;J++){var Y=i1[J];if(Y[1]===Z&&Y[0]===$){$=Y[2],i1.splice(J,1);break}}return Q.call(this,Z,$)}}var m2=[];var d2=_({});var u2=_({});var p2=_({BaseChatMessageHistory:()=>FW,BaseListChatMessageHistory:()=>KJ,InMemoryChatMessageHistory:()=>QD}),FW=class extends g0{async addMessages(Q){for(let Z of Q)await this.addMessage(Z)}},KJ=class extends g0{addUserMessage(Q){return this.addMessage(new G0(Q))}addAIMessage(Q){return this.addMessage(new h(Q))}async addMessages(Q){for(let Z of Q)await this.addMessage(Z)}clear(){throw Error("Not implemented.")}},QD=class extends KJ{lc_namespace=["langchain","stores","message","in_memory"];messages=[];constructor(Q){super(...arguments);this.messages=Q??[]}async getMessages(){return this.messages}async addMessage(Q){this.messages.push(Q)}async clear(){this.messages=[]}};var vQ=class{pageContent;metadata;id;constructor(Q){this.pageContent=Q.pageContent!==void 0?Q.pageContent.toString():"",this.metadata=Q.metadata??{},this.id=Q.id}};var LW=class extends c{lc_namespace=["langchain_core","documents","transformers"];invoke(Q,Z){return this.transformDocuments(Q)}},c2=class extends LW{async transformDocuments(Q){let Z=[];for(let $ of Q){let J=await this._transformDocument($);Z.push(J)}return Z}};var l2=_({BaseDocumentTransformer:()=>LW,Document:()=>vQ,MappingDocumentTransformer:()=>c2});var i2=_({BaseDocumentLoader:()=>wW}),wW=class{};var o2=_({LangSmithLoader:()=>ZD}),ZD=class extends wW{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(Q){super();if(Q.client&&Q.clientConfig)throw Error("client and clientConfig cannot both be provided.");this.client=Q.client??new I8(Q?.clientConfig),this.contentKey=Q.contentKey?Q.contentKey.split("."):[],this.formatContent=Q.formatContent??$D,this.datasetId=Q.datasetId,this.datasetName=Q.datasetName,this.exampleIds=Q.exampleIds,this.asOf=Q.asOf,this.splits=Q.splits,this.inlineS3Urls=Q.inlineS3Urls,this.offset=Q.offset,this.limit=Q.limit,this.metadata=Q.metadata,this.filter=Q.filter}async load(){let Q=[];for await(let Z 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 $=Z.inputs;for(let W of this.contentKey)$=$[W];let J=this.formatContent($),Y=Z;["created_at","modified_at"].forEach((W)=>{if(W in Y){if(typeof Y[W]==="object")Y[W]=Y[W].toString()}}),Q.push({pageContent:J,metadata:Y})}return Q}};function $D(Q){if(typeof Q==="string")return Q;else try{return JSON.stringify(Q,null,2)}catch{return String(Q)}}var n2=_({Embeddings:()=>UJ}),UJ=class{caller;constructor(Q){this.caller=new J6(Q??{})}};var o1=class extends g0{lc_namespace=["langchain_core","example_selectors","base"]};var AW=class{async getPromptAsync(Q,Z){return this.getPrompt(Q).partial(Z?.partialVariables??{})}},r2=class extends AW{defaultPrompt;conditionals;constructor(Q,Z=[]){super();this.defaultPrompt=Q,this.conditionals=Z}getPrompt(Q){for(let[Z,$]of this.conditionals)if(Z(Q))return $;return this.defaultPrompt}};function s2(Q){return Q._modelType()==="base_llm"}function t2(Q){return Q._modelType()==="base_chat_model"}function a2(Q){return Q.split(/\n| /).length}var e2=class Q extends o1{examples=[];examplePrompt;getTextLength=a2;maxLength=2048;exampleTextLengths=[];constructor(Z){super(Z);this.examplePrompt=Z.examplePrompt,this.maxLength=Z.maxLength??2048,this.getTextLength=Z.getTextLength??a2}async addExample(Z){this.examples.push(Z);let $=await this.examplePrompt.format(Z);this.exampleTextLengths.push(this.getTextLength($))}async calculateExampleTextLengths(Z,$){if(Z.length>0)return Z;let{examples:J,examplePrompt:Y}=$;return(await Promise.all(J.map((W)=>Y.format(W)))).map((W)=>this.getTextLength(W))}async selectExamples(Z){let $=Object.values(Z).join(" "),J=this.maxLength-this.getTextLength($),Y=0,W=[];while(J>0&&Y<this.examples.length){let X=J-this.exampleTextLengths[Y];if(X<0)break;else W.push(this.examples[Y]),J=X;Y+=1}return W}static async fromExamples(Z,$){let J=new Q($);return await Promise.all(Z.map((Y)=>J.addExample(Y))),J}};function PW(Q){return Object.keys(Q).sort().map((Z)=>Q[Z])}var QG=class Q extends o1{vectorStoreRetriever;exampleKeys;inputKeys;constructor(Z){super(Z);if(this.exampleKeys=Z.exampleKeys,this.inputKeys=Z.inputKeys,Z.vectorStore!==void 0)this.vectorStoreRetriever=Z.vectorStore.asRetriever({k:Z.k??4,filter:Z.filter});else if(Z.vectorStoreRetriever)this.vectorStoreRetriever=Z.vectorStoreRetriever;else throw Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(Z){let $=PW((this.inputKeys??Object.keys(Z)).reduce((J,Y)=>({...J,[Y]:Z[Y]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new vQ({pageContent:$,metadata:Z})])}async selectExamples(Z){let $=PW((this.inputKeys??Object.keys(Z)).reduce((Y,W)=>({...Y,[W]:Z[W]}),{})).join(" "),J=(await this.vectorStoreRetriever.invoke($)).map((Y)=>Y.metadata);if(this.exampleKeys)return J.map((Y)=>this.exampleKeys.reduce((W,X)=>({...W,[X]:Y[X]}),{}));return J}static async fromExamples(Z,$,J,Y={}){let W=Y.inputKeys??null,X=Z.map((q)=>PW(W?W.reduce((G,z)=>({...G,[z]:q[z]}),{}):q).join(" "));return new Q({vectorStore:await J.fromTexts(X,Z,$,Y),k:Y.k??4,exampleKeys:Y.exampleKeys,inputKeys:Y.inputKeys})}};var ZG=_({BaseExampleSelector:()=>o1,BasePromptSelector:()=>AW,ConditionalPromptSelector:()=>r2,LengthBasedExampleSelector:()=>e2,SemanticSimilarityExampleSelector:()=>QG,isChatModel:()=>t2,isLLM:()=>s2});var nZ="10f90ea3-90a4-4962-bf75-83a0f3c1c62a",$G=class extends g0{lc_namespace=["langchain","recordmanagers"]};$8();var NW=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=z1;constructor(Q){this.uid=Q.uid,this.pageContent=Q.pageContent,this.metadata=Q.metadata}makeDefaultKeyEncoder(Q){this.keyEncoder=Q}calculateHashes(){let Q=["hash_","content_hash","metadata_hash"];for(let $ of Q)if($ in this.metadata)throw Error(`Metadata cannot contain key ${$} as it is reserved for internal use. Restricted keys: [${Q.join(", ")}]`);let Z=this._hashStringToUUID(this.pageContent);try{let $=this._hashNestedDictToUUID(this.metadata);this.contentHash=Z,this.metadataHash=$}catch($){throw Error(`Failed to hash metadata: ${$}. Please use a dict that can be serialized using json.`)}if(this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),!this.uid)this.uid=this.hash_}toDocument(){return new vQ({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(Q,Z){let $=new this({pageContent:Q.pageContent,metadata:Q.metadata,uid:Z||Q.uid});return $.calculateHashes(),$}_hashStringToUUID(Q){return $1(this.keyEncoder(Q),nZ)}_hashNestedDictToUUID(Q){let Z=JSON.stringify(Q,Object.keys(Q).sort());return $1(this.keyEncoder(Z),nZ)}};function OW(Q,Z){let $=[],J=[];if(Z.forEach((Y)=>{if(J.push(Y),J.length>=Q)$.push(J),J=[]}),J.length>0)$.push(J);return $}function EW(Q){let Z=new Set,$=[];for(let J of Q){if(!J.hash_)throw Error("Hashed document does not have a hash");if(!Z.has(J.hash_))Z.add(J.hash_),$.push(J)}return $}function jW(Q){if(Q===null)return(Z)=>null;else if(typeof Q==="string")return(Z)=>Z.metadata[Q];else if(typeof Q==="function")return Q;else throw Error(`sourceIdKey should be null, a string or a function, got ${typeof Q}`)}var RW=(Q)=>{if("load"in Q&&typeof Q.load==="function"&&"loadAndSplit"in Q&&typeof Q.loadAndSplit==="function")return!0;return!1};async function JG(Q){let{docsSource:Z,recordManager:$,vectorStore:J,options:Y}=Q,{batchSize:W=100,cleanup:X,sourceIdKey:q,cleanupBatchSize:G=1000,forceUpdate:z=!1}=Y??{};if(X==="incremental"&&!q)throw Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");let K=RW(Z)?await Z.load():Z,U=jW(q??null),H=await $.getTime(),B=0,F=0,w=0,A=0,E=OW(W??100,K);for(let P of E){let j=EW(P.map((I)=>NW.fromDocument(I))),R=j.map((I)=>U(I));if(X==="incremental")j.forEach((I,y)=>{if(R[y]===null)throw Error("sourceIdKey must be provided when cleanup is incremental")});let k=await $.exists(j.map((I)=>I.uid)),b=[],T=[],V=[],v=new Set;if(j.forEach((I,y)=>{if(k[y])if(z)v.add(I.uid);else{V.push(I.uid);return}b.push(I.uid),T.push(I.toDocument())}),V.length>0)await $.update(V,{timeAtLeast:H}),A+=V.length;if(T.length>0)await J.addDocuments(T,{ids:b}),B+=T.length-v.size,w+=v.size;if(await $.update(j.map((I)=>I.uid),{timeAtLeast:H,groupIds:R}),X==="incremental"){R.forEach((y)=>{if(!y)throw Error("Source id cannot be null")});let I=await $.listKeys({before:H,groupIds:R});if(I.length>0)await J.delete({ids:I}),await $.deleteKeys(I),F+=I.length}}if(X==="full"){let P=await $.listKeys({before:H,limit:G});while(P.length>0)await J.delete({ids:P}),await $.deleteKeys(P),F+=P.length,P=await $.listKeys({before:H,limit:G})}return{numAdded:B,numDeleted:F,numUpdated:w,numSkipped:A}}var YG=_({RecordManager:()=>$G,UUIDV5_NAMESPACE:()=>nZ,_HashedDocument:()=>NW,_batch:()=>OW,_deduplicateInOrder:()=>EW,_getSourceIdAssigner:()=>jW,_isBaseDocumentLoader:()=>RW,index:()=>JG});var WG=_({BaseLLM:()=>XG,LLM:()=>HJ}),XG=class Q extends K1{lc_namespace=["langchain","llms",this._llmType()];async invoke(Z,$){let J=Q._convertInputToPromptValue(Z);return(await this.generatePrompt([J],$,$?.callbacks)).generations[0][0].text}async*_streamResponseChunks(Z,$,J){throw Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(Z){let[$,J]=super._separateRunnableConfigFromCallOptions(Z);return J.signal=$.signal,[$,J]}async*_streamIterator(Z,$){if(this._streamResponseChunks===Q.prototype._streamResponseChunks)yield this.invoke(Z,$);else{let J=Q._convertInputToPromptValue(Z),[Y,W]=this._separateRunnableConfigFromCallOptionsCompat($),X=await d0.configure(Y.callbacks,this.callbacks,Y.tags,this.tags,Y.metadata,this.metadata,{verbose:this.verbose}),q={options:W,invocation_params:this?.invocationParams(W),batch_size:1},G=await X?.handleLLMStart(this.toJSON(),[J.toString()],Y.runId,void 0,q,void 0,void 0,Y.runName),z=new a8({text:""});try{for await(let K of this._streamResponseChunks(J.toString(),W,G?.[0])){if(!z)z=K;else z=z.concat(K);if(typeof K.text==="string")yield K.text}}catch(K){throw await Promise.all((G??[]).map((U)=>U?.handleLLMError(K))),K}await Promise.all((G??[]).map((K)=>K?.handleLLMEnd({generations:[[z]]})))}}async generatePrompt(Z,$,J){let Y=Z.map((W)=>W.toString());return this.generate(Y,$,J)}invocationParams(Z){return{}}_flattenLLMResult(Z){let $=[];for(let J=0;J<Z.generations.length;J+=1){let Y=Z.generations[J];if(J===0)$.push({generations:[Y],llmOutput:Z.llmOutput});else{let W=Z.llmOutput?{...Z.llmOutput,tokenUsage:{}}:void 0;$.push({generations:[Y],llmOutput:W})}}return $}async _generateUncached(Z,$,J,Y){let W;if(Y!==void 0&&Y.length===Z.length)W=Y;else{let z=await d0.configure(J.callbacks,this.callbacks,J.tags,this.tags,J.metadata,this.metadata,{verbose:this.verbose}),K={options:$,invocation_params:this?.invocationParams($),batch_size:Z.length};W=await z?.handleLLMStart(this.toJSON(),Z,J.runId,void 0,K,void 0,void 0,J?.runName)}let X=!!W?.[0].handlers.find(PZ),q;if(X&&Z.length===1&&this._streamResponseChunks!==Q.prototype._streamResponseChunks)try{let z=await this._streamResponseChunks(Z[0],$,W?.[0]),K;for await(let U of z)if(K===void 0)K=U;else K=uQ(K,U);if(K===void 0)throw Error("Received empty response from chat model call.");q={generations:[[K]],llmOutput:{}},await W?.[0].handleLLMEnd(q)}catch(z){throw await W?.[0].handleLLMError(z),z}else{try{q=await this._generate(Z,$,W?.[0])}catch(K){throw await Promise.all((W??[]).map((U)=>U?.handleLLMError(K))),K}let z=this._flattenLLMResult(q);await Promise.all((W??[]).map((K,U)=>K?.handleLLMEnd(z[U])))}let G=W?.map((z)=>z.runId)||void 0;return Object.defineProperty(q,X1,{value:G?{runIds:G}:void 0,configurable:!0}),q}async _generateCached({prompts:Z,cache:$,llmStringKey:J,parsedOptions:Y,handledOptions:W,runId:X}){let q=await d0.configure(W.callbacks,this.callbacks,W.tags,this.tags,W.metadata,this.metadata,{verbose:this.verbose}),G={options:Y,invocation_params:this?.invocationParams(Y),batch_size:Z.length},z=await q?.handleLLMStart(this.toJSON(),Z,X,void 0,G,void 0,void 0,W?.runName),K=[],U=(await Promise.allSettled(Z.map(async(F,w)=>{let A=await $.lookup(F,J);if(A==null)K.push(w);return A}))).map((F,w)=>({result:F,runManager:z?.[w]})).filter(({result:F})=>F.status==="fulfilled"&&F.value!=null||F.status==="rejected"),H=[];await Promise.all(U.map(async({result:F,runManager:w},A)=>{if(F.status==="fulfilled"){let E=F.value;if(H[A]=E.map((P)=>{return P.generationInfo={...P.generationInfo,tokenUsage:{}},P}),E.length)await w?.handleLLMNewToken(E[0].text);return w?.handleLLMEnd({generations:[E]},void 0,void 0,void 0,{cached:!0})}else return await w?.handleLLMError(F.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(F.reason)}));let B={generations:H,missingPromptIndices:K,startedRunManagers:z};return Object.defineProperty(B,X1,{value:z?{runIds:z?.map((F)=>F.runId)}:void 0,configurable:!0}),B}async generate(Z,$,J){if(!Array.isArray(Z))throw Error("Argument 'prompts' is expected to be a string[]");let Y;if(Array.isArray($))Y={stop:$};else Y=$;let[W,X]=this._separateRunnableConfigFromCallOptionsCompat(Y);if(W.callbacks=W.callbacks??J,!this.cache)return this._generateUncached(Z,X,W);let{cache:q}=this,G=this._getSerializedCacheKeyParametersForCall(X),{generations:z,missingPromptIndices:K,startedRunManagers:U}=await this._generateCached({prompts:Z,cache:q,llmStringKey:G,parsedOptions:X,handledOptions:W,runId:W.runId}),H={};if(K.length>0){let B=await this._generateUncached(K.map((F)=>Z[F]),X,W,U!==void 0?K.map((F)=>U?.[F]):void 0);await Promise.all(B.generations.map(async(F,w)=>{let A=K[w];return z[A]=F,q.update(Z[A],G,F)})),H=B.llmOutput??{}}return{generations:z,llmOutput:H}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},HJ=class extends XG{async _generate(Q,Z,$){return{generations:await Promise.all(Q.map((J,Y)=>this._call(J,{...Z,promptIndex:Y},$).then((W)=>[{text:W}])))}}};var qG=_({});var GG=_({BaseMemory:()=>JD,getInputValue:()=>YD,getOutputValue:()=>WD,getPromptInputKey:()=>XD}),JD=class{},zG=(Q,Z)=>{if(Z!==void 0)return Q[Z];let $=Object.keys(Q);if($.length===1)return Q[$[0]]},YD=(Q,Z)=>{let $=zG(Q,Z);if(!$){let J=Object.keys(Q);throw Error(`input values have ${J.length} keys, you must specify an input key or pass only 1 key as input`)}return $},WD=(Q,Z)=>{let $=zG(Q,Z);if(!$&&$!==""){let J=Object.keys(Q);throw Error(`output values have ${J.length} keys, you must specify an output key or pass only 1 key as output`)}return $};function XD(Q,Z){let $=Object.keys(Q).filter((J)=>!Z.includes(J)&&J!=="stop");if($.length!==1)throw Error(`One input key expected, but got ${$.length}`);return $[0]}var _W=class extends m1{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(Q){super();this.argsOnly=Q?.argsOnly??this.argsOnly}async parseResult(Q){if("message"in Q[0]){let Z=Q[0].message.additional_kwargs.function_call;if(!Z)throw Error(`No function_call in message ${JSON.stringify(Q)}`);if(!Z.arguments)throw Error(`No arguments in function_call ${JSON.stringify(Q)}`);if(this.argsOnly)return Z.arguments;return JSON.stringify(Z)}else throw Error(`No message in generations ${JSON.stringify(Q)}`)}},IW=class extends y8{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(Q){super(Q);this.argsOnly=Q?.argsOnly??this.argsOnly,this.outputParser=new _W(Q)}_diff(Q,Z){if(!Z)return;return $6(Q??{},Z)}async parsePartialResult(Q){let Z=Q[0];if(!Z.message)return;let{message:$}=Z,J=$.additional_kwargs.function_call;if(!J)return;if(this.argsOnly)return Q8(J.arguments);return{...J,arguments:Q8(J.arguments)}}async parseResult(Q){let Z=await this.outputParser.parseResult(Q);if(!Z)throw Error(`No result from "OutputFunctionsParser" ${JSON.stringify(Q)}`);return this.parse(Z)}async parse(Q){let Z=JSON.parse(Q);if(this.argsOnly)return Z;return Z.arguments=JSON.parse(Z.arguments),Z}getFormatInstructions(){return""}},KG=class extends m1{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new IW;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(Q){super(Q);this.attrName=Q.attrName}async parseResult(Q){return(await this.outputParser.parseResult(Q))[this.attrName]}};var UG=_({JsonKeyOutputFunctionsParser:()=>KG,JsonOutputFunctionsParser:()=>IW,OutputFunctionsParser:()=>_W});var HG=_({JsonOutputKeyToolsParser:()=>s9,JsonOutputToolsParser:()=>WW,convertLangChainToolCallToOpenAI:()=>O2,makeInvalidToolCall:()=>E2,parseToolCall:()=>YW});var g8=class extends c{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(Q){super(Q);let{inputVariables:Z}=Q;if(Z.includes("stop"))throw Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,Q)}async mergePartialAndUserVariables(Q){let Z=this.partialVariables??{},$={};for(let[J,Y]of Object.entries(Z))if(typeof Y==="string")$[J]=Y;else $[J]=await Y();return{...$,...Q}}async invoke(Q,Z){let $={...this.metadata,...Z?.metadata},J=[...this.tags??[],...Z?.tags??[]];return this._callWithConfig((Y)=>this.formatPromptValue(Y),Q,{...Z,tags:J,metadata:$,runType:"prompt"})}};var G6=class extends g8{async formatPromptValue(Q){return new kZ(await this.format(Q))}};function BG(){BJ.escape=(Q)=>Q}var B1=(Q)=>{let Z=Q.split(""),$=[],J=(W,X)=>{for(let q=X;q<Z.length;q+=1)if(W.includes(Z[q]))return q;return-1},Y=0;while(Y<Z.length)if(Z[Y]==="{"&&Y+1<Z.length&&Z[Y+1]==="{")$.push({type:"literal",text:"{"}),Y+=2;else if(Z[Y]==="}"&&Y+1<Z.length&&Z[Y+1]==="}")$.push({type:"literal",text:"}"}),Y+=2;else if(Z[Y]==="{"){let W=J("}",Y);if(W<0)throw Error("Unclosed '{' in template.");$.push({type:"variable",name:Z.slice(Y+1,W).join("")}),Y=W+1}else if(Z[Y]==="}")throw Error("Single '}' in template.");else{let W=J("{}",Y),X=(W<0?Z.slice(Y):Z.slice(Y,W)).join("");$.push({type:"literal",text:X}),Y=W<0?Z.length:W}return $},DG=(Q,Z=[])=>{let $=[];for(let J of Q)if(J[0]==="name"){let Y=J[1].includes(".")?J[1].split(".")[0]:J[1];$.push({type:"variable",name:Y})}else if(["#","&","^",">"].includes(J[0])){if($.push({type:"variable",name:J[1]}),J[0]==="#"&&J.length>4&&Array.isArray(J[4])){let Y=[...Z,J[1]],W=DG(J[4],Y);$.push(...W)}}else $.push({type:"literal",text:J[1]});return $},n1=(Q)=>{return BG(),DG(BJ.parse(Q))},TW=(Q,Z)=>{return B1(Q).reduce(($,J)=>{if(J.type==="variable"){if(J.name in Z)return $+(typeof Z[J.name]==="string"?Z[J.name]:JSON.stringify(Z[J.name]));throw Error(`(f-string) Missing value for input ${J.name}`)}return $+J.text},"")},SW=(Q,Z)=>{return BG(),BJ.render(Q,Z)},rZ={"f-string":TW,mustache:SW},xW={"f-string":B1,mustache:n1},DQ=(Q,Z,$)=>{try{return rZ[Z](Q,$)}catch(J){throw n8(J,"INVALID_PROMPT_INPUT")}},D1=(Q,Z)=>xW[Z](Q),z6=(Q,Z,$)=>{if(!(Z in rZ)){let J=Object.keys(rZ);throw Error(`Invalid template format. Got \`${Z}\`;
161
+ should be one of ${J}`)}try{let J=Object.fromEntries($.map((Y)=>[Y,"foo"]));if(Array.isArray(Q))Q.forEach((Y)=>{if(Y.type==="text"&&"text"in Y&&typeof Y.text==="string")DQ(Y.text,Z,J);else if(Y.type==="image_url"){if(typeof Y.image_url==="string")DQ(Y.image_url,Z,J);else if(typeof Y.image_url==="object"&&Y.image_url!==null&&"url"in Y.image_url&&typeof Y.image_url.url==="string"){let W=Y.image_url.url;DQ(W,Z,J)}}else throw Error(`Invalid message template received. ${JSON.stringify(Y,null,2)}`)});else DQ(Q,Z,J)}catch(J){throw Error(`Invalid prompt schema: ${J.message}`)}};var B8=class Q extends G6{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(Z){super(Z);if(Z.templateFormat==="mustache"&&Z.validateTemplate===void 0)this.validateTemplate=!1;if(Object.assign(this,Z),this.validateTemplate){if(this.templateFormat==="mustache")throw Error("Mustache templates cannot be validated.");let $=this.inputVariables;if(this.partialVariables)$=$.concat(Object.keys(this.partialVariables));z6(this.template,this.templateFormat,$)}}_getPromptType(){return"prompt"}async format(Z){let $=await this.mergePartialAndUserVariables(Z);return DQ(this.template,this.templateFormat,$)}static fromExamples(Z,$,J,Y=`
162
+
163
+ `,W=""){return new Q({inputVariables:J,template:[W,...Z,$].join(Y)})}static fromTemplate(Z,$){let{templateFormat:J="f-string",...Y}=$??{},W=new Set;return D1(Z,J).forEach((X)=>{if(X.type==="variable")W.add(X.name)}),new Q({inputVariables:[...W],templateFormat:J,template:Z,...Y})}async partial(Z){let $=this.inputVariables.filter((Y)=>!(Y in Z)),J={...this.partialVariables??{},...Z};return new Q({...this,inputVariables:$,partialVariables:J})}serialize(){if(this.outputParser!==void 0)throw 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(Z){if(!Z.template)throw Error("Prompt template must have a template");return new Q({inputVariables:Z.input_variables,template:Z.template,templateFormat:Z.template_format})}};var r1=class Q extends g8{static lc_name(){return"ImagePromptTemplate"}lc_namespace=["langchain_core","prompts","image"];template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(Z){super(Z);if(this.template=Z.template,this.templateFormat=Z.templateFormat??this.templateFormat,this.validateTemplate=Z.validateTemplate??this.validateTemplate,this.additionalContentFields=Z.additionalContentFields,this.validateTemplate){let $=this.inputVariables;if(this.partialVariables)$=$.concat(Object.keys(this.partialVariables));z6([{type:"image_url",image_url:this.template}],this.templateFormat,$)}}_getPromptType(){return"prompt"}async partial(Z){let $=this.inputVariables.filter((Y)=>!(Y in Z)),J={...this.partialVariables??{},...Z};return new Q({...this,inputVariables:$,partialVariables:J})}async format(Z){let $={};for(let[X,q]of Object.entries(this.template))if(typeof q==="string")$[X]=DQ(q,this.templateFormat,Z);else $[X]=q;let J=Z.url||$.url,Y=Z.detail||$.detail;if(!J)throw Error("Must provide either an image URL.");if(typeof J!=="string")throw Error("url must be a string.");let W={url:J};if(Y)W.detail=Y;return W}async formatPromptValue(Z){return new $W(await this.format(Z))}};var sZ=class extends c{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(Q){let Z=Q.templateFormat??"f-string",$=MW(Q.template,Z);super({inputVariables:$,...Q});this.template=Q.template,this.templateFormat=Z,this.inputVariables=$}async format(Q){return vW(this.template,Q,this.templateFormat)}async invoke(Q){return await this._callWithConfig(this.format.bind(this),Q,{runType:"prompt"})}};function MW(Q,Z){let $=[];for(let J of Object.values(Q))if(typeof J==="string")D1(J,Z).forEach((Y)=>{if(Y.type==="variable")$.push(Y.name)});else if(Array.isArray(J)){for(let Y of J)if(typeof Y==="string")D1(Y,Z).forEach((W)=>{if(W.type==="variable")$.push(W.name)});else if(typeof Y==="object")$.push(...MW(Y,Z))}else if(typeof J==="object"&&J!==null)$.push(...MW(J,Z));return Array.from(new Set($))}function vW(Q,Z,$){let J={};for(let[Y,W]of Object.entries(Q))if(typeof W==="string")J[Y]=DQ(W,$,Z);else if(Array.isArray(W)){let X=[];for(let q of W)if(typeof q==="string")X.push(DQ(q,$,Z));else if(typeof q==="object")X.push(vW(q,Z,$));J[Y]=X}else if(typeof W==="object"&&W!==null)J[Y]=vW(W,Z,$);else J[Y]=W;return J}var tZ=class extends c{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(Q,Z){return this._callWithConfig(($)=>this.formatMessages($),Q,{...Z,runType:"prompt"})}},DJ=class extends tZ{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(Q){if(typeof Q==="string")Q={variableName:Q};super(Q);this.variableName=Q.variableName,this.optional=Q.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(Q){let Z=Q[this.variableName];if(this.optional&&!Z)return[];else if(!Z){let J=Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw J.name="InputFormatError",J}let $;try{if(Array.isArray(Z))$=Z.map(KQ);else $=[KQ(Z)]}catch(J){let Y=typeof Z==="string"?Z:JSON.stringify(Z,null,2),W=Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${Y}`,`Additional message: ${J.message}`].join(`
164
+
165
+ `));throw W.name="InputFormatError",W.lc_error_code=J.lc_error_code,W}return $}},yW=class extends tZ{prompt;constructor(Q){if(!("prompt"in Q))Q={prompt:Q};super(Q);this.prompt=Q.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(Q){return[await this.format(Q)]}},aZ=class extends g8{constructor(Q){super(Q)}async format(Q){return(await this.formatPromptValue(Q)).toString()}async formatPromptValue(Q){return new fZ(await this.formatMessages(Q))}},CW=class extends yW{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(Q,Z){if(!("prompt"in Q))Q={prompt:Q,role:Z};super(Q);this.role=Q.role}async format(Q){return new Z8(await this.prompt.format(Q),this.role)}static fromTemplate(Q,Z,$){return new this(B8.fromTemplate(Q,{templateFormat:$?.templateFormat}),Z)}};function qD(Q){if(Q===null||typeof Q!=="object"||Array.isArray(Q))return!1;return Object.keys(Q).length===1&&"text"in Q&&typeof Q.text==="string"}function GD(Q){if(Q===null||typeof Q!=="object"||Array.isArray(Q))return!1;return"image_url"in Q&&(typeof Q.image_url==="string"||typeof Q.image_url==="object"&&Q.image_url!==null&&("url"in Q.image_url)&&typeof Q.image_url.url==="string")}var bW=class extends tZ{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}chatMessageClass;constructor(Q,Z){if(!("prompt"in Q))Q={prompt:Q};super(Q);if(this.prompt=Q.prompt,Array.isArray(this.prompt)){let $=[];this.prompt.forEach((J)=>{if("inputVariables"in J)$=$.concat(J.inputVariables)}),this.inputVariables=$}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=Z??this.additionalOptions}createMessage(Q){let Z=this.constructor;if(Z._messageClass())return new(Z._messageClass())({content:Q});else if(Z.chatMessageClass){let $=Z.chatMessageClass();return new $({content:Q,role:this.getRoleFromMessageClass($.lc_name())})}else throw Error("No message class defined")}getRoleFromMessageClass(Q){switch(Q){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw Error("Invalid message class name")}}static fromTemplate(Q,Z){if(typeof Q==="string")return new this(B8.fromTemplate(Q,Z));let $=[];for(let J of Q)if(typeof J==="string")$.push(B8.fromTemplate(J,Z));else if(J===null);else if(qD(J)){let Y="";if(typeof J.text==="string")Y=J.text??"";let W={...Z,additionalContentFields:J};$.push(B8.fromTemplate(Y,W))}else if(GD(J)){let Y=J.image_url??"",W,X=[];if(typeof Y==="string"){let q;if(Z?.templateFormat==="mustache")q=n1(Y);else q=B1(Y);let G=q.flatMap((z)=>z.type==="variable"?[z.name]:[]);if((G?.length??0)>0){if(G.length>1)throw Error(`Only one format variable allowed per image template.
166
+ Got: ${G}
167
+ From: ${Y}`);X=[G[0]]}else X=[];Y={url:Y},W=new r1({template:Y,inputVariables:X,templateFormat:Z?.templateFormat,additionalContentFields:J})}else if(typeof Y==="object"){if("url"in Y){let q;if(Z?.templateFormat==="mustache")q=n1(Y.url);else q=B1(Y.url);X=q.flatMap((G)=>G.type==="variable"?[G.name]:[])}else X=[];W=new r1({template:Y,inputVariables:X,templateFormat:Z?.templateFormat,additionalContentFields:J})}else throw Error("Invalid image template");$.push(W)}else if(typeof J==="object")$.push(new sZ({template:J,templateFormat:Z?.templateFormat}));return new this({prompt:$,additionalOptions:Z})}async format(Q){if(this.prompt instanceof G6){let Z=await this.prompt.format(Q);return this.createMessage(Z)}else{let Z=[];for(let $ of this.prompt){let J={};if(!("inputVariables"in $))throw Error(`Prompt ${$} does not have inputVariables defined.`);for(let Y of $.inputVariables){if(!J)J={[Y]:Q[Y]};J={...J,[Y]:Q[Y]}}if($ instanceof G6){let Y=await $.format(J),W;if("additionalContentFields"in $)W=$.additionalContentFields;if(Y!=="")Z.push({...W,type:"text",text:Y})}else if($ instanceof r1){let Y=await $.format(J),W;if("additionalContentFields"in $)W=$.additionalContentFields;Z.push({...W,type:"image_url",image_url:Y})}else if($ instanceof sZ){let Y=await $.format(J),W;if("additionalContentFields"in $)W=$.additionalContentFields;Z.push({...W,...Y})}}return this.createMessage(Z)}}async formatMessages(Q){return[await this.format(Q)]}},VJ=class extends bW{static _messageClass(){return G0}static lc_name(){return"HumanMessagePromptTemplate"}},kW=class extends bW{static _messageClass(){return h}static lc_name(){return"AIMessagePromptTemplate"}},fW=class extends bW{static _messageClass(){return L0}static lc_name(){return"SystemMessagePromptTemplate"}};function zD(Q){return typeof Q.formatMessages==="function"}function KD(Q,Z){if(zD(Q)||R0(Q))return Q;if(Array.isArray(Q)&&Q[0]==="placeholder"){let Y=Q[1];if(Z?.templateFormat==="mustache"&&typeof Y==="string"&&Y.slice(0,2)==="{{"&&Y.slice(-2)==="}}")return new DJ({variableName:Y.slice(2,-2),optional:!0});else if(typeof Y==="string"&&Y[0]==="{"&&Y[Y.length-1]==="}")return new DJ({variableName:Y.slice(1,-1),optional:!0});throw Error(`Invalid placeholder template for format ${Z?.templateFormat??'"f-string"'}: "${Q[1]}". Expected a variable name surrounded by ${Z?.templateFormat==="mustache"?"double":"single"} curly braces.`)}let $=KQ(Q),J;if(typeof $.content==="string")J=$.content;else J=$.content.map((Y)=>{if("text"in Y)return{...Y,text:Y.text};else if("image_url"in Y)return{...Y,image_url:Y.image_url};else return Y});if($._getType()==="human")return VJ.fromTemplate(J,Z);else if($._getType()==="ai")return kW.fromTemplate(J,Z);else if($._getType()==="system")return fW.fromTemplate(J,Z);else if(Z8.isInstance($))return CW.fromTemplate($.content,$.role,Z);else throw Error(`Could not coerce message prompt template from input. Received message type: "${$._getType()}".`)}function UD(Q){return Q.constructor.lc_name()==="MessagesPlaceholder"}var s1=class Q extends aZ{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(Z){super(Z);if(Z.templateFormat==="mustache"&&Z.validateTemplate===void 0)this.validateTemplate=!1;if(Object.assign(this,Z),this.validateTemplate){let $=new Set;for(let q of this.promptMessages){if(q instanceof V0)continue;for(let G of q.inputVariables)$.add(G)}let J=this.inputVariables,Y=new Set(this.partialVariables?J.concat(Object.keys(this.partialVariables)):J),W=new Set([...Y].filter((q)=>!$.has(q)));if(W.size>0)throw Error(`Input variables \`${[...W]}\` are not used in any of the prompt messages.`);let X=new Set([...$].filter((q)=>!Y.has(q)));if(X.size>0)throw Error(`Input variables \`${[...X]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(Z,$){if(typeof Z.content==="string")return Z;return Z.content=await Promise.all(Z.content.map(async(J)=>{if(J.type!=="image_url")return J;let Y="";if(typeof J.image_url==="string")Y=J.image_url;else if(typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string")Y=J.image_url.url;let W=await B8.fromTemplate(Y,{templateFormat:this.templateFormat}).format($);if(typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url)J.image_url.url=W;else J.image_url=W;return J})),Z}async formatMessages(Z){let $=await this.mergePartialAndUserVariables(Z),J=[];for(let Y of this.promptMessages)if(Y instanceof V0)J.push(await this._parseImagePrompts(Y,$));else{let W;if(this.templateFormat==="mustache")W={...$};else W=Y.inputVariables.reduce((q,G)=>{if(!(G in $)&&!(UD(Y)&&Y.optional))throw n8(Error(`Missing value for input variable \`${G.toString()}\``),"INVALID_PROMPT_INPUT");return q[G]=$[G],q},{});let X=await Y.formatMessages(W);J=J.concat(X)}return J}async partial(Z){let $=this.inputVariables.filter((Y)=>!(Y in Z)),J={...this.partialVariables??{},...Z};return new Q({...this,inputVariables:$,partialVariables:J})}static fromTemplate(Z,$){let J=new VJ({prompt:B8.fromTemplate(Z,$)});return this.fromMessages([J])}static fromMessages(Z,$){let J=Z.reduce((X,q)=>X.concat(q instanceof Q?q.promptMessages:[KD(q,$)]),[]),Y=Z.reduce((X,q)=>q instanceof Q?Object.assign(X,q.partialVariables):X,Object.create(null)),W=new Set;for(let X of J){if(X instanceof V0)continue;for(let q of X.inputVariables){if(q in Y)continue;W.add(q)}}return new this({...$,inputVariables:[...W],promptMessages:J,partialVariables:Y,templateFormat:$?.templateFormat})}};var VG=class Q extends G6{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
168
+
169
+ `;prefix="";templateFormat="f-string";validateTemplate=!0;constructor(Z){super(Z);if(Object.assign(this,Z),this.examples!==void 0&&this.exampleSelector!==void 0)throw Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let $=this.inputVariables;if(this.partialVariables)$=$.concat(Object.keys(this.partialVariables));z6(this.prefix+this.suffix,this.templateFormat,$)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(Z){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(Z);throw Error("One of 'examples' and 'example_selector' should be provided")}async partial(Z){let $=this.inputVariables.filter((Y)=>!(Y in Z)),J={...this.partialVariables??{},...Z};return new Q({...this,inputVariables:$,partialVariables:J})}async format(Z){let $=await this.mergePartialAndUserVariables(Z),J=await this.getExamples($),Y=await Promise.all(J.map((W)=>this.examplePrompt.format(W)));return DQ([this.prefix,...Y,this.suffix].join(this.exampleSeparator),this.templateFormat,$)}serialize(){if(this.exampleSelector||!this.examples)throw Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw 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(Z){let{example_prompt:$}=Z;if(!$)throw Error("Missing example prompt");let J=await B8.deserialize($),Y;if(Array.isArray(Z.examples))Y=Z.examples;else throw Error("Invalid examples format. Only list or string are supported.");return new Q({inputVariables:Z.input_variables,examplePrompt:J,examples:Y,exampleSeparator:Z.example_separator,prefix:Z.prefix,suffix:Z.suffix,templateFormat:Z.template_format})}},FG=class Q extends aZ{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
170
+
171
+ `;prefix="";templateFormat="f-string";validateTemplate=!0;_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(Z){super(Z);if(this.examples=Z.examples,this.examplePrompt=Z.examplePrompt,this.exampleSeparator=Z.exampleSeparator??`
172
+
173
+ `,this.exampleSelector=Z.exampleSelector,this.prefix=Z.prefix??"",this.suffix=Z.suffix??"",this.templateFormat=Z.templateFormat??"f-string",this.validateTemplate=Z.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let $=this.inputVariables;if(this.partialVariables)$=$.concat(Object.keys(this.partialVariables));z6(this.prefix+this.suffix,this.templateFormat,$)}}async getExamples(Z){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(Z);throw Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(Z){let $=await this.mergePartialAndUserVariables(Z),J=await this.getExamples($);J=J.map((W)=>{let X={};return this.examplePrompt.inputVariables.forEach((q)=>{X[q]=W[q]}),X});let Y=[];for(let W of J){let X=await this.examplePrompt.formatMessages(W);Y.push(...X)}return Y}async format(Z){let $=await this.mergePartialAndUserVariables(Z),J=await this.getExamples($),Y=(await Promise.all(J.map((W)=>this.examplePrompt.formatMessages(W)))).flat().map((W)=>W.content);return DQ([this.prefix,...Y,this.suffix].join(this.exampleSeparator),this.templateFormat,$)}async partial(Z){let $=this.inputVariables.filter((Y)=>!(Y in Z)),J={...this.partialVariables??{},...Z};return new Q({...this,inputVariables:$,partialVariables:J})}};var LG=class Q extends g8{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(Z){super({...Z,inputVariables:[]});this.pipelinePrompts=Z.pipelinePrompts,this.finalPrompt=Z.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let Z=this.pipelinePrompts.map((J)=>J.name),$=this.pipelinePrompts.map((J)=>J.prompt.inputVariables.filter((Y)=>!Z.includes(Y))).flat();return[...new Set($)]}static extractRequiredInputValues(Z,$){return $.reduce((J,Y)=>{return J[Y]=Z[Y],J},{})}async formatPipelinePrompts(Z){let $=await this.mergePartialAndUserVariables(Z);for(let{name:J,prompt:Y}of this.pipelinePrompts){let W=Q.extractRequiredInputValues($,Y.inputVariables);if(Y instanceof s1)$[J]=await Y.formatMessages(W);else $[J]=await Y.format(W)}return Q.extractRequiredInputValues($,this.finalPrompt.inputVariables)}async formatPromptValue(Z){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(Z))}async format(Z){return this.finalPrompt.format(await this.formatPipelinePrompts(Z))}async partial(Z){let $={...this};return $.inputVariables=this.inputVariables.filter((J)=>!(J in Z)),$.partialVariables={...this.partialVariables??{},...Z},new Q($)}serialize(){throw Error("Not implemented.")}_getPromptType(){return"pipeline"}};function wG(Q){return typeof Q==="object"&&Q!=null&&"withStructuredOutput"in Q&&typeof Q.withStructuredOutput==="function"}function HD(Q){return typeof Q==="object"&&Q!=null&&"lc_id"in Q&&Array.isArray(Q.lc_id)&&Q.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var AG=class Q extends s1{schema;method;lc_namespace=["langchain_core","prompts","structured"];get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(Z){super(Z);this.schema=Z.schema,this.method=Z.method}pipe(Z){if(wG(Z))return super.pipe(Z.withStructuredOutput(this.schema));if(HD(Z)&&wG(Z.bound))return super.pipe(new b0({bound:Z.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:Z.kwargs??{},config:Z.config,configFactories:Z.configFactories}));throw Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(Z,$,J){return Q.fromMessages(Z,{schema:$,method:J})}};var PG=_({AIMessagePromptTemplate:()=>kW,BaseChatPromptTemplate:()=>aZ,BaseMessagePromptTemplate:()=>tZ,BaseMessageStringPromptTemplate:()=>yW,BasePromptTemplate:()=>g8,BaseStringPromptTemplate:()=>G6,ChatMessagePromptTemplate:()=>CW,ChatPromptTemplate:()=>s1,DEFAULT_FORMATTER_MAPPING:()=>rZ,DEFAULT_PARSER_MAPPING:()=>xW,DictPromptTemplate:()=>sZ,FewShotChatMessagePromptTemplate:()=>FG,FewShotPromptTemplate:()=>VG,HumanMessagePromptTemplate:()=>VJ,ImagePromptTemplate:()=>r1,MessagesPlaceholder:()=>DJ,PipelinePromptTemplate:()=>LG,PromptTemplate:()=>B8,StructuredPrompt:()=>AG,SystemMessagePromptTemplate:()=>fW,checkValidTemplate:()=>z6,interpolateFString:()=>TW,interpolateMustache:()=>SW,parseFString:()=>B1,parseMustache:()=>n1,parseTemplate:()=>D1,renderTemplate:()=>DQ});var NG=_({BaseDocumentCompressor:()=>BD}),BD=class{static isBaseDocumentCompressor(Q){return Q?.compressDocuments!==void 0}};var OG=_({BaseRetriever:()=>eZ}),eZ=class extends c{callbacks;tags;metadata;verbose;constructor(Q){super(Q);this.callbacks=Q?.callbacks,this.tags=Q?.tags??[],this.metadata=Q?.metadata??{},this.verbose=Q?.verbose??!1}_getRelevantDocuments(Q,Z){throw Error("Not implemented!")}async invoke(Q,Z){let $=t(W1(Z)),J=await(await d0.configure($.callbacks,this.callbacks,$.tags,this.tags,$.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),Q,$.runId,void 0,void 0,void 0,$.runName);try{let Y=await this._getRelevantDocuments(Q,J);return await J?.handleRetrieverEnd(Y),Y}catch(Y){throw await J?.handleRetrieverError(Y),Y}}};var EG=_({BaseStore:()=>jG,InMemoryStore:()=>RG}),jG=class extends g0{},RG=class extends jG{lc_namespace=["langchain","storage"];store={};async mget(Q){return Q.map((Z)=>this.store[Z])}async mset(Q){for(let[Z,$]of Q)this.store[Z]=$}async mdelete(Q){for(let Z of Q)delete this.store[Z]}async*yieldKeys(Q){let Z=Object.keys(this.store);for(let $ of Z)if(Q===void 0||$.startsWith(Q))yield $}};var D8={and:"and",or:"or",not:"not"},Y0={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"},FJ=class{},LJ=class{accept(Q){if(this.exprName==="Operation")return Q.visitOperation(this);else if(this.exprName==="Comparison")return Q.visitComparison(this);else if(this.exprName==="StructuredQuery")return Q.visitStructuredQuery(this);else throw Error("Unknown Expression type")}},wJ=class extends LJ{},_G=class extends wJ{exprName="Comparison";constructor(Q,Z,$){super();this.comparator=Q,this.attribute=Z,this.value=$}},IG=class extends wJ{exprName="Operation";constructor(Q,Z){super();this.operator=Q,this.args=Z}},TG=class extends LJ{exprName="StructuredQuery";constructor(Q,Z){super();this.query=Q,this.filter=Z}};function hW(Q){return Q&&typeof Q==="object"&&!Array.isArray(Q)}function yQ(Q){if(!Q)return!0;if(typeof Q==="string"&&Q.length>0)return!1;if(typeof Q==="function")return!1;return hW(Q)&&Object.keys(Q).length===0}function gW(Q){if(typeof Q==="number")return Q%1===0;else if(typeof Q==="string"){let Z=parseInt(Q,10);return!Number.isNaN(Z)&&Z%1===0&&Z.toString()===Q}return!1}function mW(Q){if(typeof Q==="number")return Q%1!==0;else if(typeof Q==="string"){let Z=parseFloat(Q);return!Number.isNaN(Z)&&Z%1!==0&&Z.toString()===Q}return!1}function dW(Q){return typeof Q==="string"&&(Number.isNaN(parseFloat(Q))||parseFloat(Q).toString()!==Q)}function uW(Q){return typeof Q==="boolean"}function t1(Q){let Z;if(dW(Q))Z=Q;else if(gW(Q))Z=parseInt(Q,10);else if(mW(Q))Z=parseFloat(Q);else if(uW(Q))Z=Boolean(Q);else throw Error("Unsupported value type");return Z}var Q$=class extends FJ{},SG=class extends Q${allowedOperators;allowedComparators;constructor(Q){super();this.allowedOperators=Q?.allowedOperators??[D8.and,D8.or],this.allowedComparators=Q?.allowedComparators??[Y0.eq,Y0.ne,Y0.gt,Y0.gte,Y0.lt,Y0.lte]}formatFunction(Q){if(Q in Y0){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(Q)===-1)throw Error(`Comparator ${Q} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(Q in D8){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(Q)===-1)throw Error(`Operator ${Q} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw Error("Unknown comparator or operator");return`$${Q}`}visitOperation(Q){let Z=Q.args?.map(($)=>$.accept(this));return{[this.formatFunction(Q.operator)]:Z}}visitComparison(Q){return{[Q.attribute]:{[this.formatFunction(Q.comparator)]:t1(Q.value)}}}visitStructuredQuery(Q){let Z={};if(Q.filter)Z={filter:Q.filter.accept(this)};return Z}mergeFilters(Q,Z,$="and",J=!1){if(yQ(Q)&&yQ(Z))return;if(yQ(Q)||$==="replace"){if(yQ(Z))return;return Z}if(yQ(Z)){if(J)return Q;if($==="and")return;return Q}if($==="and")return{$and:[Q,Z]};else if($==="or")return{$or:[Q,Z]};else throw Error("Unknown merge type")}};var xG=class extends Q${allowedOperators=[D8.and,D8.or];allowedComparators=[Y0.eq,Y0.ne,Y0.gt,Y0.gte,Y0.lt,Y0.lte];formatFunction(){throw Error("Not implemented")}getAllowedComparatorsForType(Q){switch(Q){case"string":return[Y0.eq,Y0.ne,Y0.gt,Y0.gte,Y0.lt,Y0.lte];case"number":return[Y0.eq,Y0.ne,Y0.gt,Y0.gte,Y0.lt,Y0.lte];case"boolean":return[Y0.eq,Y0.ne];default:throw Error(`Unsupported data type: ${Q}`)}}getComparatorFunction(Q){switch(Q){case Y0.eq:return(Z,$)=>Z===$;case Y0.ne:return(Z,$)=>Z!==$;case Y0.gt:return(Z,$)=>Z>$;case Y0.gte:return(Z,$)=>Z>=$;case Y0.lt:return(Z,$)=>Z<$;case Y0.lte:return(Z,$)=>Z<=$;default:throw Error("Unknown comparator")}}getOperatorFunction(Q){switch(Q){case D8.and:return(Z,$)=>Z&&$;case D8.or:return(Z,$)=>Z||$;default:throw Error("Unknown operator")}}visitOperation(Q){let{operator:Z,args:$}=Q;if(this.allowedOperators.includes(Z)){let J=this.getOperatorFunction(Z);return(Y)=>{if(!$)return!0;return $.reduce((W,X)=>{let q=X.accept(this);if(typeof q==="function")return J(W,q(Y));else throw Error("Filter is not a function")},!0)}}else throw Error("Operator not allowed")}visitComparison(Q){let{comparator:Z,attribute:$,value:J}=Q,Y=[Y0.ne];if(this.allowedComparators.includes(Z)){if(!this.getAllowedComparatorsForType(typeof J).includes(Z))throw Error(`'${Z}' comparator not allowed to be used with ${typeof J}`);let W=this.getComparatorFunction(Z);return(X)=>{let q=X.metadata[$];if(q===void 0){if(Y.includes(Z))return!0;return!1}return W(q,t1(J))}}else throw Error("Comparator not allowed")}visitStructuredQuery(Q){if(!Q.filter)return{};let Z=Q.filter?.accept(this);if(typeof Z!=="function")throw Error("Structured query filter is not a function");return{filter:Z}}mergeFilters(Q,Z,$="and"){if(yQ(Q)&&yQ(Z))return;if(yQ(Q)||$==="replace"){if(yQ(Z))return;return Z}if(yQ(Z)){if($==="and")return;return Q}if($==="and")return(J)=>Q(J)&&Z(J);else if($==="or")return(J)=>Q(J)||Z(J);else throw Error("Unknown merge type")}};var MG=_({BaseTranslator:()=>Q$,BasicTranslator:()=>SG,Comparators:()=>Y0,Comparison:()=>_G,Expression:()=>LJ,FilterDirective:()=>wJ,FunctionalTranslator:()=>xG,Operation:()=>IG,Operators:()=>D8,StructuredQuery:()=>TG,Visitor:()=>FJ,castValue:()=>t1,isBoolean:()=>uW,isFilterEmpty:()=>yQ,isFloat:()=>mW,isInt:()=>gW,isObject:()=>hW,isString:()=>dW});function Z$(Q){if(!V0.isInstance(Q))return typeof Q;return Q.constructor.name||Q.type}function AJ(Q,Z){return function($,J){let{isNot:Y,utils:W}=this;if(!Z($))return{pass:!1,message:()=>`${W.matcherHint(`toBe${Q}`,void 0,void 0)}
174
+
175
+ Expected: ${Y?"not ":""}${Q}
176
+ Received: ${Z$($)}`,actual:Z$($),expected:Q};if(J===void 0)return{pass:!0,message:()=>`${W.matcherHint(`toBe${Q}`,void 0,void 0)}
177
+
178
+ Expected: not ${Q}
179
+ Received: ${Q}`};let X=$;if(typeof J==="string")return{pass:X.content===J,message:()=>`${W.matcherHint(`toBe${Q}`,void 0,void 0)}
180
+
181
+ Expected: ${Q} with content ${W.printExpected(J)}
182
+ Received: ${Q} with content ${W.printReceived(X.content)}`,actual:X.content,expected:J};return{pass:Object.entries(J).every(([q,G])=>this.equals(X[q],G)),message:()=>{let q={};for(let G of Object.keys(J))q[G]=X[G];return`${W.matcherHint(`toBe${Q}`,void 0,void 0)}
183
+
184
+ Expected: ${Q} matching ${W.printExpected(J)}
185
+ Received: ${Q} with ${W.printReceived(q)}`},actual:(()=>{let q={};for(let G of Object.keys(J))q[G]=X[G];return q})(),expected:J}}}var pW=AJ("HumanMessage",G0.isInstance),cW=AJ("AIMessage",h.isInstance),lW=AJ("SystemMessage",L0.isInstance),iW=AJ("ToolMessage",i.isInstance);function oW(Q,Z){let{isNot:$,utils:J}=this;if(!h.isInstance(Q))return{pass:!1,message:()=>`${J.matcherHint("toHaveToolCalls")}
186
+
187
+ Expected: AIMessage
188
+ Received: ${Z$(Q)}`};let Y=Q.tool_calls??[];if(Y.length!==Z.length)return{pass:!1,message:()=>`${J.matcherHint("toHaveToolCalls")}
189
+
190
+ Expected ${$?"not ":""}${Z.length} tool call(s), received ${Y.length}`,actual:Y.length,expected:Z.length};let W=Z.filter((X)=>!Y.some((q)=>Object.entries(X).every(([G,z])=>this.equals(q[G],z))));if(W.length>0)return{pass:!1,message:()=>`${J.matcherHint("toHaveToolCalls")}
191
+
192
+ Could not find matching tool call(s) for:
193
+ ${J.printExpected(W)}
194
+ Received tool calls: ${J.printReceived(Y.map((X)=>({name:X.name,id:X.id,args:X.args})))}`,actual:Y.map((X)=>({name:X.name,id:X.id,args:X.args})),expected:Z};return{pass:!0,message:()=>`${J.matcherHint("toHaveToolCalls")}
195
+
196
+ Expected AIMessage not to have matching tool calls`}}function nW(Q,Z){let{isNot:$,utils:J}=this;if(!h.isInstance(Q))return{pass:!1,message:()=>`${J.matcherHint("toHaveToolCallCount")}
197
+
198
+ Expected: AIMessage
199
+ Received: ${Z$(Q)}`};let Y=Q.tool_calls?.length??0;return{pass:Y===Z,message:()=>`${J.matcherHint("toHaveToolCallCount")}
200
+
201
+ Expected ${$?"not ":""}${Z} tool call(s)
202
+ Received: ${Y}`,actual:Y,expected:Z}}function rW(Q,Z){let{isNot:$,utils:J}=this;if(!h.isInstance(Q))return{pass:!1,message:()=>`${J.matcherHint("toContainToolCall")}
203
+
204
+ Expected: AIMessage
205
+ Received: ${Z$(Q)}`};let Y=Q.tool_calls??[];return{pass:Y.some((W)=>Object.entries(Z).every(([X,q])=>this.equals(W[X],q))),message:()=>`${J.matcherHint("toContainToolCall")}
206
+
207
+ Expected AIMessage ${$?"not ":""}to contain a tool call matching ${J.printExpected(Z)}
208
+ Received tool calls: ${J.printReceived(Y.map((W)=>({name:W.name,id:W.id})))}`,actual:Y.map((W)=>({name:W.name,id:W.id})),expected:Z}}function sW(Q,Z){let{isNot:$,utils:J}=this;if(!Array.isArray(Q))return{pass:!1,message:()=>`${J.matcherHint("toHaveToolMessages")}
209
+
210
+ Expected an array of messages
211
+ Received: ${typeof Q}`};let Y=Q.filter(i.isInstance);if(Y.length!==Z.length)return{pass:!1,message:()=>`${J.matcherHint("toHaveToolMessages")}
212
+
213
+ Expected ${$?"not ":""}${Z.length} tool message(s), found ${Y.length}`,actual:Y.length,expected:Z.length};for(let W=0;W<Z.length;W++)if(!Object.entries(Z[W]).every(([X,q])=>this.equals(Y[W][X],q)))return{pass:!1,message:()=>{let X={};for(let q of Object.keys(Z[W]))X[q]=Y[W][q];return`${J.matcherHint("toHaveToolMessages")}
214
+
215
+ Tool message at index ${W} did not match:
216
+ Expected: ${J.printExpected(Z[W])}
217
+ Received: ${J.printReceived(X)}`},actual:Y[W],expected:Z[W]};return{pass:!0,message:()=>`${J.matcherHint("toHaveToolMessages")}
218
+
219
+ Expected messages not to contain matching tool messages`}}function tW(Q,Z){let{isNot:$,utils:J}=this,Y=Q?.__interrupt__;if(!(Array.isArray(Y)&&Y.length>0))return{pass:!1,message:()=>`${J.matcherHint("toHaveBeenInterrupted")}
220
+
221
+ Expected result ${$?"not ":""}to have been interrupted
222
+ Received __interrupt__: ${J.printReceived(Y)}`};if(Z===void 0)return{pass:!0,message:()=>`${J.matcherHint("toHaveBeenInterrupted")}
223
+
224
+ Expected result not to have been interrupted
225
+ Received ${Y.length} interrupt(s)`};let W=Y[0]?.value;return{pass:this.equals(W,Z),message:()=>`${J.matcherHint("toHaveBeenInterrupted")}
226
+
227
+ Expected interrupt value: ${J.printExpected(Z)}
228
+ Received interrupt value: ${J.printReceived(W)}`,actual:W,expected:Z}}function aW(Q,Z){let{isNot:$,utils:J}=this,Y=Q?.structuredResponse;if(Y===void 0)return{pass:!1,message:()=>`${J.matcherHint("toHaveStructuredResponse")}
229
+
230
+ Expected result ${$?"not ":""}to have a structured response
231
+ Received structuredResponse: undefined`};if(Z===void 0)return{pass:!0,message:()=>`${J.matcherHint("toHaveStructuredResponse")}
232
+
233
+ Expected result not to have a structured response`};return{pass:Object.entries(Z).every(([W,X])=>this.equals(Y[W],X)),message:()=>`${J.matcherHint("toHaveStructuredResponse")}
234
+
235
+ Expected structured response: ${J.printExpected(Z)}
236
+ Received structured response: ${J.printReceived(Y)}`,actual:Y,expected:Z}}var eW={toBeHumanMessage:pW,toBeAIMessage:cW,toBeSystemMessage:lW,toBeToolMessage:iW,toHaveToolCalls:oW,toHaveToolCallCount:nW,toContainToolCall:rW,toHaveToolMessages:sW,toHaveBeenInterrupted:tW,toHaveStructuredResponse:aW};function DD(Q){return Q.map((Z)=>Z.text).filter(Boolean).join("-")}var vG=0;function VD(){return vG+=1,`fake_tc_${vG}`}var FD=class Q extends K8{queue=[];_alwaysThrowError;_structuredResponseValue;_tools=[];_callIndex=0;_calls=[];get calls(){return this._calls}get callCount(){return this._calls.length}constructor(){super({})}_llmType(){return"fake-model-builder"}_combineLLMOutput(){return[]}respond(Z){if(typeof Z==="function")this.queue.push({kind:"factory",factory:Z});else if(V0.isInstance(Z))this.queue.push({kind:"message",message:Z});else this.queue.push({kind:"error",error:Z});return this}respondWithTools(Z){return this.queue.push({kind:"toolCalls",toolCalls:Z.map(($)=>({name:$.name,args:$.args,id:$.id??VD(),type:"tool_call"}))}),this}alwaysThrow(Z){return this._alwaysThrowError=Z,this}structuredResponse(Z){return this._structuredResponseValue=Z,this}bindTools(Z){let $=[...this._tools,...Z],J=new Q;return J.queue=this.queue,J._alwaysThrowError=this._alwaysThrowError,J._structuredResponseValue=this._structuredResponseValue,J._tools=$,J._calls=this._calls,J._callIndex=this._callIndex,J.withConfig({})}withStructuredOutput(Z,$){let{_structuredResponseValue:J}=this;return i0.from(async()=>{return J})}async _generate(Z,$,J){this._calls.push({messages:[...Z],options:$});let Y=this._callIndex;if(this._callIndex+=1,this._alwaysThrowError)throw this._alwaysThrowError;let W=this.queue[Y];if(!W)throw Error(`FakeModel: no response queued for invocation ${Y} (${this.queue.length} total queued).`);if(W.kind==="error")throw W.error;if(W.kind==="factory"){let q=W.factory(Z);if(!V0.isInstance(q))throw q;return{generations:[{text:"",message:q}]}}if(W.kind==="message")return{generations:[{text:"",message:W.message}]};let X=DD(Z);return{generations:[{text:X,message:new h({content:X,id:Y.toString(),tool_calls:W.toolCalls.length>0?W.toolCalls.map((q)=>({...q,type:"tool_call"})):void 0})}],llmOutput:{}}}};function Q3(){return new FD}var yG=_({fakeModel:()=>Q3,langchainMatchers:()=>eW,toBeAIMessage:()=>cW,toBeHumanMessage:()=>pW,toBeSystemMessage:()=>lW,toBeToolMessage:()=>iW,toContainToolCall:()=>rW,toHaveBeenInterrupted:()=>tW,toHaveStructuredResponse:()=>aW,toHaveToolCallCount:()=>nW,toHaveToolCalls:()=>oW,toHaveToolMessages:()=>sW});function $$(Q){return Q!==void 0&&Array.isArray(Q.lc_namespace)}function J$(Q){return Q!==void 0&&c.isRunnable(Q)&&"lc_name"in Q.constructor&&typeof Q.constructor.lc_name==="function"&&Q.constructor.lc_name()==="RunnableToolLike"}function Y$(Q){return!!Q&&typeof Q==="object"&&"name"in Q&&"schema"in Q&&(ZQ(Q.schema)||Q.schema!=null&&typeof Q.schema==="object"&&("type"in Q.schema)&&typeof Q.schema.type==="string"&&["null","boolean","object","array","number","string"].includes(Q.schema.type))}function a1(Q){return Y$(Q)||J$(Q)||$$(Q)}var bG=_({BaseToolkit:()=>LD,DynamicStructuredTool:()=>J3,DynamicTool:()=>$3,StructuredTool:()=>V1,Tool:()=>Z3,ToolInputParsingException:()=>w6,isLangChainTool:()=>a1,isRunnableToolLike:()=>J$,isStructuredTool:()=>$$,isStructuredToolParams:()=>Y$,tool:()=>Y3}),V1=class extends c9{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(Q){super(Q??{});this.verboseParsingErrors=Q?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=Q?.responseFormat??this.responseFormat,this.defaultConfig=Q?.defaultConfig??this.defaultConfig,this.metadata=Q?.metadata??this.metadata,this.extras=Q?.extras??this.extras}async invoke(Q,Z){let $,J=t(w0(this.defaultConfig,Z));if(L6(Q))$=Q.args,J={...J,toolCall:Q};else $=Q;return this.call($,J)}async call(Q,Z,$){let J=L6(Q)?Q.args:Q,Y;if(ZQ(this.schema))try{Y=await _6(this.schema,J)}catch(B){let F="Received tool input did not match expected schema";if(this.verboseParsingErrors)F=`${F}
237
+ Details: ${B.message}`;if(L9(B))F=`${F}
238
+
239
+ ${p0.prettifyError(B)}`;throw new w6(F,JSON.stringify(Q))}else{let B=CG(J,this.schema);if(!B.valid){let F="Received tool input did not match expected schema";if(this.verboseParsingErrors)F=`${F}
240
+ Details: ${B.errors.map((w)=>`${w.keywordLocation}: ${w.error}`).join(`
241
+ `)}`;throw new w6(F,JSON.stringify(Q))}Y=J}let W=W1(Z),X=d0.configure(W.callbacks,this.callbacks,W.tags||$,this.tags,W.metadata,this.metadata,{verbose:this.verbose}),q;if(L6(Q))q=Q.id;if(!q&&lX(W))q=W.toolCall.id;let G=await X?.handleToolStart(this.toJSON(),typeof Q==="string"?Q:JSON.stringify(Q),W.runId,void 0,void 0,void 0,W.runName,q);delete W.runId;let z;try{let B=await this._call(Y,G,W);z=bq(B)?await kq(B,async(F)=>{try{await G?.handleToolEvent(F)}catch(w){await G?.handleToolError(w)}}):B}catch(B){throw await G?.handleToolError(B),B}let K,U;if(this.responseFormat==="content_and_artifact")if(Array.isArray(z)&&z.length===2)[K,U]=z;else throw Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
242
+ Result: ${JSON.stringify(z)}`);else K=z;let H=wD({content:K,artifact:U,toolCallId:q,name:this.name,metadata:this.metadata});return await G?.handleToolEnd(H),H}},Z3=class extends V1{schema=O.object({input:O.string().optional()}).transform((Q)=>Q.input);constructor(Q){super(Q)}call(Q,Z){let $=typeof Q==="string"||Q==null?{input:Q}:Q;return super.call($,Z)}},$3=class extends Z3{static lc_name(){return"DynamicTool"}name;description;func;constructor(Q){super(Q);this.name=Q.name,this.description=Q.description,this.func=Q.func,this.returnDirect=Q.returnDirect??this.returnDirect}async call(Q,Z){let $=W1(Z);if($.runName===void 0)$.runName=this.name;return super.call(Q,$)}_call(Q,Z,$){return this.func(Q,Z,$)}},J3=class extends V1{static lc_name(){return"DynamicStructuredTool"}description;func;schema;constructor(Q){super(Q);this.name=Q.name,this.description=Q.description,this.func=Q.func,this.returnDirect=Q.returnDirect??this.returnDirect,this.schema=Q.schema}async call(Q,Z,$){let J=W1(Z);if(J.runName===void 0)J.runName=this.name;return super.call(Q,J,$)}_call(Q,Z,$){return this.func(Q,Z,$)}},LD=class{getTools(){return this.tools}};function Y3(Q,Z){let $=b1(Z.schema),J=f1(Z.schema);if(!Z.schema||$||J)return new $3({...Z,description:Z.description??Z.schema?.description??`${Z.name} tool`,func:async(X,q,G)=>{return new Promise((z,K)=>{let U=W0(G,{callbacks:q?.getChild()});q0.runWithConfig(PQ(U),async()=>{try{z(Q(X,U))}catch(H){K(H)}})})}});let Y=Z.schema,W=Z.description??Z.schema.description??`${Z.name} tool`;return new J3({...Z,description:W,schema:Y,func:async(X,q,G)=>{return new Promise((z,K)=>{let U,H=()=>{if(G?.signal&&U)G.signal.removeEventListener("abort",U)};if(G?.signal)U=()=>{H(),K(j6(G.signal))},G.signal.addEventListener("abort",U,{once:!0});let B=W0(G,{callbacks:q?.getChild()});q0.runWithConfig(PQ(B),async()=>{try{let F=await Q(X,B);if(G?.signal?.aborted){H();return}H(),z(F)}catch(F){H(),K(F)}})})}})}function wD(Q){let{content:Z,artifact:$,toolCallId:J,metadata:Y}=Q;if(J&&!VZ(Z))if(typeof Z==="string"||Array.isArray(Z)&&Z.every((W)=>typeof W==="object"))return new i({status:"success",content:Z,artifact:$,tool_call_id:J,name:Q.name,metadata:Y});else return new i({status:"success",content:AD(Z),artifact:$,tool_call_id:J,name:Q.name,metadata:Y});else return Z}function AD(Q){try{return JSON.stringify(Q)??""}catch(Z){return`${Q}`}}var kG=_({RunCollectorCallbackHandler:()=>PD}),PD=class extends WQ{name="run_collector";exampleId;tracedRuns;constructor({exampleId:Q}={}){super({_awaitHandler:!0});this.exampleId=Q,this.tracedRuns=[]}async persistRun(Q){let Z={...Q};Z.reference_example_id=this.exampleId,this.tracedRuns.push(Z)}};var fG=_({});var hG=_({chunkArray:()=>ND}),ND=(Q,Z)=>Q.reduce(($,J,Y)=>{let W=Math.floor(Y/Z);return $[W]=($[W]||[]).concat([J]),$},[]);var gG=_({context:()=>mG});function mG(Q,...Z){let $=Q.raw,J="";for(let Y=0;Y<$.length;Y++){let W=$[Y].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(J+=W,Y<Z.length){let X=OD(Z[Y],J);J+=typeof X==="string"?X:JSON.stringify(X)}}return J=ED(J),J=J.trim(),J=J.replace(/\\n/g,`
243
+ `),J}function OD(Q,Z){if(typeof Q!=="string"||!Q.includes(`
244
+ `))return Q;let $=Z.slice(Z.lastIndexOf(`
245
+ `)+1).match(/^(\s+)/);if($){let J=$[1];return Q.replace(/\n/g,`
246
+ ${J}`)}return Q}function ED(Q){let Z=Q.split(`
247
+ `),$=null;for(let J of Z){let Y=J.match(/^(\s+)\S+/);if(Y){let W=Y[1].length;if($===null)$=W;else $=Math.min($,W)}}if($===null)return Q;return Z.map((J)=>J[0]===" "||J[0]==="\t"?J.slice($):J).join(`
248
+ `)}var dG=_({EventStreamContentType:()=>jD,convertEventStreamToIterableReadableDataStream:()=>_D,getBytes:()=>uG,getLines:()=>pG,getMessages:()=>cG}),jD="text/event-stream";async function uG(Q,Z){if(Q instanceof ReadableStream){let $=Q.getReader();while(!0){let J=await $.read();if(J.done){Z(new Uint8Array,!0);break}Z(J.value)}}else try{for await(let $ of Q)Z(new Uint8Array($));Z(new Uint8Array,!0)}catch($){throw Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${$.message}`].join(`
249
+ `))}}var e1=function(Q){return Q[Q.NewLine=10]="NewLine",Q[Q.CarriageReturn=13]="CarriageReturn",Q[Q.Space=32]="Space",Q[Q.Colon=58]="Colon",Q}(e1||{});function pG(Q){let Z,$,J,Y=!1;return function(X,q){if(q){Q(X,0,!0);return}if(Z===void 0)Z=X,$=0,J=-1;else Z=RD(Z,X);let G=Z.length,z=0;while($<G){if(Y){if(Z[$]===e1.NewLine)z=++$;Y=!1}let K=-1;for(;$<G&&K===-1;++$)switch(Z[$]){case e1.Colon:if(J===-1)J=$-z;break;case e1.CarriageReturn:Y=!0;case e1.NewLine:K=$;break}if(K===-1)break;Q(Z.subarray(z,K),J),z=$,J=-1}if(z===G)Z=void 0;else if(z!==0)Z=Z.subarray(z),$-=z}}function cG(Q,Z,$){let J=W3(),Y=new TextDecoder;return function(X,q,G){if(G){if(!ID(J))Q?.(J),J=W3();return}if(X.length===0)Q?.(J),J=W3();else if(q>0){let z=Y.decode(X.subarray(0,q)),K=q+(X[q+1]===e1.Space?2:1),U=Y.decode(X.subarray(K));switch(z){case"data":J.data=J.data?J.data+`
250
+ `+U:U;break;case"event":J.event=U;break;case"id":Z?.(J.id=U);break;case"retry":{let H=parseInt(U,10);if(!Number.isNaN(H))$?.(J.retry=H);break}}}}}function RD(Q,Z){let $=new Uint8Array(Q.length+Z.length);return $.set(Q),$.set(Z,Q.length),$}function W3(){return{data:"",event:"",id:"",retry:void 0}}function _D(Q,Z){let $=new ReadableStream({async start(J){let Y=cG((X)=>{if(X.event==="error")throw Error(X.data??"Unspecified event streaming error.");else if(X.event==="metadata")Z?.(X);else if(X.data)J.enqueue(X.data)});await uG(Q,pG((X,q,G)=>{if(Y(X,q,G),G)J.close()}))}});return S0.fromReadableStream($)}function ID(Q){return Q.data===""&&Q.event===""&&Q.id===""&&Q.retry===void 0}var lG=_({});var iG=_({convertToOpenAIFunction:()=>oG,convertToOpenAITool:()=>nG,isLangChainTool:()=>a1,isRunnableToolLike:()=>J$,isStructuredTool:()=>$$,isStructuredToolParams:()=>Y$});function oG(Q,Z){let $=typeof Z==="number"?void 0:Z;return{name:Q.name,description:Q.description,parameters:M0(Q.schema),...$?.strict!==void 0?{strict:$.strict}:{}}}function nG(Q,Z){let $=typeof Z==="number"?void 0:Z,J;if(a1(Q))J={type:"function",function:oG(Q)};else J=Q;if($?.strict!==void 0)J.function.strict=$.strict;return J}function PJ(Q,Z){let $=0,J=0,Y=0;for(let W=0;W<Q.length;W++)$+=Q[W]*Z[W],J+=Q[W]*Q[W],Y+=Z[W]*Z[W];return $/(Math.sqrt(J)*Math.sqrt(Y))}function rG(Q,Z){let $=0;for(let J=0;J<Q.length;J++)$+=Q[J]*Z[J];return $}function TD(Q,Z){let $=0;for(let J=0;J<Q.length;J++)$+=(Q[J]-Z[J])*(Q[J]-Z[J]);return $}function sG(Q,Z){return Math.sqrt(TD(Q,Z))}var tG=_({cosineSimilarity:()=>X3,euclideanDistance:()=>MD,innerProduct:()=>xD,matrixFunc:()=>NJ,maximalMarginalRelevance:()=>vD,normalize:()=>SD});function NJ(Q,Z,$){if(Q.length===0||Q[0].length===0||Z.length===0||Z[0].length===0)return[[]];if(Q[0].length!==Z[0].length)throw Error(`Number of columns in X and Y must be the same. X has shape ${[Q.length,Q[0].length]} and Y has shape ${[Z.length,Z[0].length]}.`);return Q.map((J)=>Z.map((Y)=>$(J,Y)).map((Y)=>Number.isNaN(Y)?0:Y))}function SD(Q,Z=!1){let $=yD(Q);return Q.map((J)=>J.map((Y)=>Z?1-Y/$:Y/$))}function X3(Q,Z){return NJ(Q,Z,PJ)}function xD(Q,Z){return NJ(Q,Z,rG)}function MD(Q,Z){return NJ(Q,Z,sG)}function vD(Q,Z,$=0.5,J=4){if(Math.min(J,Z.length)<=0)return[];let Y=X3(Array.isArray(Q[0])?Q:[Q],Z)[0],W=aG(Y).maxIndex,X=[Z[W]],q=[W];while(q.length<Math.min(J,Z.length)){let G=-1/0,z=-1,K=X3(Z,X);Y.forEach((U,H)=>{if(q.includes(H))return;let B=Math.max(...K[H]),F=$*U-(1-$)*B;if(F>G)G=F,z=H}),X.push(Z[z]),q.push(z)}return q}function aG(Q){if(Q.length===0)return{maxIndex:-1,maxValue:NaN};let Z=Q[0],$=0;for(let J=1;J<Q.length;J+=1)if(Q[J]>Z)$=J,Z=Q[J];return{maxIndex:$,maxValue:Z}}function yD(Q){return Q.reduce((Z,$)=>Math.max(Z,aG($).maxValue),0)}var eG=_({isCloudMetadata:()=>q3,isLocalhost:()=>G3,isPrivateIp:()=>Yz,isSafeUrl:()=>dD,isSameOrigin:()=>uD,validateSafeUrl:()=>Wz}),CD=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8","169.254.0.0/16","0.0.0.0/8","::1/128","fc00::/7","fe80::/10","ff00::/8"],bD=["169.254.169.254","169.254.170.2","100.100.100.200"],kD=["metadata.google.internal","metadata","instance-data"],fD=["localhost","localhost.localdomain"],hD=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function Qz(Q){return hD.test(Q)}function OJ(Q){return Jz(Q)!==null}function Zz(Q){return Qz(Q)||OJ(Q)}function $z(Q){if(Qz(Q))return Q.split(".").map((Z)=>parseInt(Z,10));else if(OJ(Q)){let Z=Jz(Q);if(!Z)return null;let $=Z.split(":"),J=[];for(let Y of $)J.push(parseInt(Y,16));return J}return null}function Jz(Q){if(!Q||typeof Q!=="string")return null;if(!Q.includes(":"))return null;if(!/^[0-9a-fA-F:]+$/.test(Q))return null;let Z=Q;if(Z.includes("::")){let J=Z.split("::");if(J.length>2)return null;let[Y,W]=J,X=Y?Y.split(":"):[],q=W?W.split(":"):[],G=8-(X.length+q.length);if(G<0)return null;let z=Array(G).fill("0");Z=[...X,...z,...q].filter((K)=>K!=="").join(":")}let $=Z.split(":");if($.length!==8)return null;for(let J of $){if(J.length===0||J.length>4)return null;if(!/^[0-9a-fA-F]+$/.test(J))return null}return $.map((J)=>J.padStart(4,"0").toLowerCase()).join(":")}function gD(Q){let[Z,$]=Q.split("/");if(!Z||!$)return null;let J=$z(Z);if(!J)return null;let Y=parseInt($,10);if(isNaN(Y))return null;let W=OJ(Z);if(W&&Y>128)return null;if(!W&&Y>32)return null;return{addr:J,prefixLen:Y,isIpv6:W}}function mD(Q,Z){let $=$z(Q);if(!$)return!1;let J=gD(Z);if(!J)return!1;let Y=OJ(Q);if(Y!==J.isIpv6)return!1;let{addr:W,prefixLen:X}=J;if(Y)for(let q=0;q<Math.ceil(X/16);q++){let G=65535<<16-Math.min(16,X-q*16)&65535;if(($[q]&G)!==(W[q]&G))return!1}else for(let q=0;q<Math.ceil(X/8);q++){let G=255<<8-Math.min(8,X-q*8)&255;if(($[q]&G)!==(W[q]&G))return!1}return!0}function Yz(Q){if(!Zz(Q))return!1;for(let Z of CD)if(mD(Q,Z))return!0;return!1}function q3(Q,Z){if(bD.includes(Z||""))return!0;let $=Q.toLowerCase();if(kD.includes($))return!0;return!1}function G3(Q,Z){if(Z){if(Z==="127.0.0.1"||Z==="::1"||Z==="0.0.0.0")return!0;if(Z.startsWith("127."))return!0}let $=Q.toLowerCase();if(fD.includes($))return!0;return!1}function Wz(Q,Z){let $=Z?.allowPrivate??!1,J=Z?.allowHttp??!1;try{let Y;try{Y=new URL(Q)}catch{throw Error(`Invalid URL: ${Q}`)}let W=Y.hostname;if(!W)throw Error("URL missing hostname.");if(q3(W))throw Error(`URL points to cloud metadata endpoint: ${W}`);if(G3(W)){if(!$)throw Error(`URL points to localhost: ${W}`);return Q}let X=Y.protocol;if(X!=="http:"&&X!=="https:")throw Error(`Invalid URL scheme: ${X}. Only http and https are allowed.`);if(X==="http:"&&!J)throw Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true.");if(Zz(W)){let q=W;if(G3(W,q)){if(!$)throw Error(`URL points to localhost: ${W}`);return Q}if(q3(W,q))throw Error(`URL resolves to cloud metadata IP: ${q} (${W})`);if(Yz(q)){if(!$)throw Error(`URL resolves to private IP: ${q} (${W}). Set allowPrivate: true to allow.`)}return Q}return Q}catch(Y){if(Y&&typeof Y==="object"&&"message"in Y)throw Y;throw Error(`URL validation failed: ${Y}`)}}function dD(Q,Z){try{return Wz(Q,Z),!0}catch{return!1}}function uD(Q,Z){try{return new URL(Q).origin===new URL(Z).origin}catch{return!1}}var Xz=_({SaveableVectorStore:()=>pD,VectorStore:()=>jJ,VectorStoreRetriever:()=>EJ}),EJ=class extends eZ{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(Q){super(Q);if(this.vectorStore=Q.vectorStore,this.k=Q.k??this.k,this.searchType=Q.searchType??this.searchType,this.filter=Q.filter,Q.searchType==="mmr")this.searchKwargs=Q.searchKwargs}async _getRelevantDocuments(Q,Z){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!=="function")throw Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(Q,{k:this.k,filter:this.filter,...this.searchKwargs},Z?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(Q,this.k,this.filter,Z?.getChild("vectorstore"))}async addDocuments(Q,Z){return this.vectorStore.addDocuments(Q,Z)}},jJ=class extends g0{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(Q,Z){super(Z);this.embeddings=Q}async delete(Q){throw Error("Not implemented.")}async similaritySearch(Q,Z=4,$=void 0,J=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(Q),Z,$)).map((Y)=>Y[0])}async similaritySearchWithScore(Q,Z=4,$=void 0,J=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(Q),Z,$)}static fromTexts(Q,Z,$,J){throw Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(Q,Z,$){throw Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(Q,Z,$,J,Y,W){if(typeof Q==="number")return new EJ({vectorStore:this,k:Q,filter:Z,tags:[...J??[],this._vectorstoreType()],metadata:Y,verbose:W,callbacks:$});else{let X={vectorStore:this,k:Q?.k,filter:Q?.filter,tags:[...Q?.tags??[],this._vectorstoreType()],metadata:Q?.metadata,verbose:Q?.verbose,callbacks:Q?.callbacks,searchType:Q?.searchType};if(Q?.searchType==="mmr")return new EJ({...X,searchKwargs:Q.searchKwargs});return new EJ({...X})}}},pD=class extends jJ{static load(Q,Z){throw Error("Not implemented")}};var qz=class extends K8{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(Q,Z,$){if(Z?.stop?.length)return{generations:[{message:new h(Z.stop[0]),text:Z.stop[0]}]};let J=Q.map((Y)=>{if(typeof Y.content==="string")return Y.content;return JSON.stringify(Y.content,null,2)}).join(`
251
+ `);return await $?.handleLLMNewToken(J),{generations:[{message:new h(J),text:J}],llmOutput:{}}}},Gz=class Q extends K8{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:Z=50,responses:$=[],chunks:J=[],toolStyle:Y="openai",thrownErrorString:W,...X}){super(X);this.sleep=Z,this.responses=$,this.chunks=J,this.toolStyle=Y,this.thrownErrorString=W}_llmType(){return"fake"}bindTools(Z){let $=[...this.tools,...Z],J=$.map((X)=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:X.name,description:X.description,parameters:M0(X.schema)}};case"anthropic":return{name:X.name,description:X.description,input_schema:M0(X.schema)};case"bedrock":return{toolSpec:{name:X.name,description:X.description,inputSchema:M0(X.schema)}};case"google":return{name:X.name,description:X.description,parameters:M0(X.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),Y=this.toolStyle==="google"?[{functionDeclarations:J}]:J,W=new Q({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return W.tools=$,W.withConfig({tools:Y})}async _generate(Z,$,J){if(this.thrownErrorString)throw Error(this.thrownErrorString);return{generations:[{text:"",message:new h({content:this.responses?.[0]?.content??Z[0].content??"",tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(Z,$,J){if(this.thrownErrorString)throw Error(this.thrownErrorString);if(this.chunks?.length){for(let X of this.chunks){let q=new R6({message:new y0({content:X.content,tool_calls:X.tool_calls,additional_kwargs:X.additional_kwargs??{}}),text:X.content?.toString()??""});if($.signal?.aborted)break;yield q,await J?.handleLLMNewToken(X.content,void 0,void 0,void 0,void 0,{chunk:q})}return}let Y=this.responses?.[0]??new h(typeof Z[0].content==="string"?Z[0].content:""),W=typeof Y.content==="string"?Y.content:"";for(let X of W){await new Promise((G)=>setTimeout(G,this.sleep));let q=new R6({message:new y0({content:X}),text:X});if($.signal?.aborted)break;yield q,await J?.handleLLMNewToken(X,void 0,void 0,void 0,void 0,{chunk:q})}}},zz=class Q extends K8{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(Z){super(Z);let{responses:$,sleep:J,emitCustomEvent:Y,generationInfo:W}=Z;this.responses=$,this.sleep=J,this.emitCustomEvent=Y??this.emitCustomEvent,this.generationInfo=W}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(Z,$,J){if(await this._sleepIfRequested(),$?.thrownErrorString)throw Error($.thrownErrorString);if(this.emitCustomEvent)await J?.handleCustomEvent("some_test_event",{someval:!0});if($?.stop?.length)return{generations:[this._formatGeneration($.stop[0])]};else{let Y=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(Y)],llmOutput:{}}}}_formatGeneration(Z){return{message:new h(Z),text:Z}}async*_streamResponseChunks(Z,$,J){let Y=this._currentResponse();if(this._incrementResponse(),this.emitCustomEvent)await J?.handleCustomEvent("some_test_event",{someval:!0});let W=[...Y];for(let X=0;X<W.length;X++){let q=W[X],G=X===W.length-1;if(await this._sleepIfRequested(),$?.thrownErrorString)throw Error($.thrownErrorString);let z=this._createResponseChunk(q,G?this.generationInfo:void 0);if($.signal?.aborted)break;yield z,J?.handleLLMNewToken(q)}}async _sleepIfRequested(){if(this.sleep!==void 0)await this._sleep()}async _sleep(){return new Promise((Z)=>{setTimeout(()=>Z(),this.sleep)})}_createResponseChunk(Z,$){return new R6({message:new y0({content:Z}),text:Z,generationInfo:$})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){if(this.i<this.responses.length-1)this.i+=1;else this.i=0}bindTools(Z){let $=[...this.tools,...Z],J=$.map((X)=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:X.name,description:X.description,parameters:M0(X.schema)}};case"anthropic":return{name:X.name,description:X.description,input_schema:M0(X.schema)};case"bedrock":return{toolSpec:{name:X.name,description:X.description,inputSchema:M0(X.schema)}};case"google":return{name:X.name,description:X.description,parameters:M0(X.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),Y=this.toolStyle==="google"?[{functionDeclarations:J}]:J,W=new Q({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return W.tools=$,W.toolStyle=this.toolStyle,W.i=this.i,W.withConfig({tools:Y})}withStructuredOutput(Z,$){return i0.from(async(J)=>{let Y=await this.invoke(J);if(Y.tool_calls?.[0]?.args)return Y.tool_calls[0].args;if(typeof Y.content==="string")return JSON.parse(Y.content);throw Error("No structured output found")})}};var Kz=class extends UJ{vectorSize;constructor(Q){super(Q??{});this.vectorSize=Q?.vectorSize??4}async embedDocuments(Q){return Promise.all(Q.map((Z)=>this.embedQuery(Z)))}async embedQuery(Q){let Z=Q;Z=Z.toLowerCase().replaceAll(/[^a-z ]/g,"");let $=Z.length%this.vectorSize,J=$===0?0:this.vectorSize-$,Y=Z.length+J;Z=Z.padEnd(Y," ");let W=Z.length/this.vectorSize,X=[];for(let q=0;q<Z.length;q+=W)X.push(Z.slice(q,q+W));return X.map((q)=>{let G=0;for(let z=0;z<q.length;z+=1)G+=q===" "?0:q.charCodeAt(z);return G%26/26})}},Uz=class extends UJ{constructor(Q){super(Q??{})}embedDocuments(Q){return Promise.resolve(Q.map(()=>[0.1,0.2,0.3,0.4]))}embedQuery(Q){return Promise.resolve([0.1,0.2,0.3,0.4])}};var Hz=class extends HJ{response;thrownErrorString;constructor(Q){super(Q);this.response=Q.response,this.thrownErrorString=Q.thrownErrorString}_llmType(){return"fake"}async _call(Q,Z,$){if(this.thrownErrorString)throw Error(this.thrownErrorString);let J=this.response??Q;return await $?.handleLLMNewToken(J),J}},Bz=class extends HJ{sleep=50;responses;thrownErrorString;constructor(Q){super(Q);this.sleep=Q.sleep??this.sleep,this.responses=Q.responses,this.thrownErrorString=Q.thrownErrorString}_llmType(){return"fake"}async _call(Q){if(this.thrownErrorString)throw Error(this.thrownErrorString);let Z=this.responses?.[0];return this.responses=this.responses?.slice(1),Z??Q}async*_streamResponseChunks(Q,Z,$){if(this.thrownErrorString)throw Error(this.thrownErrorString);let J=this.responses?.[0];this.responses=this.responses?.slice(1);for(let Y of J??Q)await new Promise((W)=>setTimeout(W,this.sleep)),yield{text:Y,generationInfo:{}},await $?.handleLLMNewToken(Y)}};var Dz=class extends FW{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(Q){this.messages.push(Q)}async addUserMessage(Q){this.messages.push(new G0(Q))}async addAIMessage(Q){this.messages.push(new h(Q))}async clear(){this.messages=[]}},Vz=class extends KJ{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(Q){this.messages.push(Q)}async getMessages(){return this.messages}},Fz=class extends WQ{name="fake_tracer";runs=[];constructor(){super()}persistRun(Q){return this.runs.push(Q),Promise.resolve()}};var Lz=class extends z8{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(Q){return Q.split(",").map((Z)=>Z.trim())}};var wz=class extends eZ{lc_namespace=["test","fake"];output=[new vQ({pageContent:"foo"}),new vQ({pageContent:"bar"})];constructor(Q){super();this.output=Q?.output??this.output}async _getRelevantDocuments(Q){return this.output}};var Az=class extends c{lc_namespace=["tests","fake"];returnOptions;constructor(Q){super(Q);this.returnOptions=Q.returnOptions}async invoke(Q,Z){if(this.returnOptions)return Z??{};return{input:Q}}};var Pz=class extends V1{name;description;schema;constructor(Q){super(Q);this.name=Q.name,this.description=Q.description,this.schema=Q.schema}async _call(Q,Z){return JSON.stringify(Q)}};var Nz=class extends WQ{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super();this.runPromise=new Promise((Q)=>{this.runPromiseResolver=Q})}async persistRun(Q){this.runPromiseResolver(Q)}async extract(){return this.runPromise}};var Oz=class Q extends jJ{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(Z,{similarity:$,...J}={}){super(Z,J);this.similarity=$??PJ}async addDocuments(Z){let $=Z.map(({pageContent:J})=>J);return this.addVectors(await this.embeddings.embedDocuments($),Z)}async addVectors(Z,$){let J=Z.map((Y,W)=>({content:$[W].pageContent,embedding:Y,metadata:$[W].metadata}));this.memoryVectors=this.memoryVectors.concat(J)}async similaritySearchVectorWithScore(Z,$,J){let Y=(X)=>{if(!J)return!0;return J(new vQ({metadata:X.metadata,pageContent:X.content}))},W=this.memoryVectors.filter(Y);return W.map((X,q)=>({similarity:this.similarity(Z,X.embedding),index:q})).sort((X,q)=>X.similarity>q.similarity?-1:0).slice(0,$).map((X)=>[new vQ({metadata:W[X.index].metadata,pageContent:W[X.index].content}),X.similarity])}static async fromTexts(Z,$,J,Y){let W=[];for(let X=0;X<Z.length;X+=1){let q=Array.isArray($)?$[X]:$,G=new vQ({pageContent:Z[X],metadata:q});W.push(G)}return Q.fromDocuments(W,J,Y)}static async fromDocuments(Z,$,J){let Y=new this($,J);return await Y.addDocuments(Z),Y}static async fromExistingIndex(Z,$){return new this(Z,$)}};var Ez=_({FakeChatMessageHistory:()=>Dz,FakeChatModel:()=>qz,FakeEmbeddings:()=>Uz,FakeLLM:()=>Hz,FakeListChatMessageHistory:()=>Vz,FakeListChatModel:()=>zz,FakeRetriever:()=>wz,FakeRunnable:()=>Az,FakeSplitIntoListParser:()=>Lz,FakeStreamingChatModel:()=>Gz,FakeStreamingLLM:()=>Bz,FakeTool:()=>Pz,FakeTracer:()=>Fz,FakeVectorStore:()=>Oz,SingleRunExtractor:()=>Nz,SyntheticEmbeddings:()=>Kz});var jz=_({agents:()=>u2,caches:()=>sq,callbacks__base:()=>z5,callbacks__manager:()=>i7,callbacks__promises:()=>p7,chat_history:()=>p2,document_loaders__base:()=>i2,document_loaders__langsmith:()=>o2,documents:()=>l2,embeddings:()=>n2,errors:()=>WX,example_selectors:()=>ZG,index:()=>d2,indexing:()=>YG,language_models__base:()=>Y2,language_models__chat_models:()=>_2,language_models__llms:()=>WG,language_models__profile:()=>qG,language_models__structured_output:()=>R2,load__serializable:()=>DX,memory:()=>GG,messages:()=>nq,messages__tool:()=>cX,output_parsers:()=>N2,output_parsers__openai_functions:()=>UG,output_parsers__openai_tools:()=>HG,outputs:()=>Qq,prompt_values:()=>eq,prompts:()=>PG,retrievers:()=>OG,retrievers__document_compressors:()=>NG,runnables:()=>z2,runnables__graph:()=>vq,singletons:()=>a7,stores:()=>EG,structured_query:()=>MG,testing:()=>yG,tools:()=>bG,tracers__base:()=>y7,tracers__console:()=>b7,tracers__log_stream:()=>Pq,tracers__run_collector:()=>kG,tracers__tracer_langchain:()=>g7,types__stream:()=>fG,utils__async_caller:()=>Rq,utils__chunk_array:()=>hG,utils__context:()=>gG,utils__env:()=>J5,utils__event_source_parse:()=>dG,utils__format:()=>lG,utils__function_calling:()=>iG,utils__hash:()=>rq,utils__json_patch:()=>K2,utils__json_schema:()=>Bq,utils__math:()=>tG,utils__ssrf:()=>eG,utils__standard_schema:()=>Gq,utils__stream:()=>e7,utils__testing:()=>Ez,utils__tiktoken:()=>$2,utils__types:()=>j2,vectorstores:()=>Xz});var cD=50;function lD(Q){let Z={};for(let $=Q;$&&$.prototype;$=Object.getPrototypeOf($))Object.assign(Z,Reflect.get($.prototype,"lc_aliases"));return Object.entries(Z).reduce(($,[J,Y])=>{return $[Y]=J,$},{})}async function RJ(Q){let{optionalImportsMap:Z,optionalImportEntrypoints:$,importMap:J,secretsMap:Y,secretsFromEnv:W,path:X,depth:q,maxDepth:G}=this,z=X.join(".");if(q>G)throw Error(`Maximum recursion depth (${G}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof Q!=="object"||Q==null)return Q;if(Array.isArray(Q))return Promise.all(Q.map((H,B)=>RJ.call({...this,path:[...X,`${B}`],depth:q+1},H)));let K=Q;if(qY(K))return S$(K);if("lc"in K&&"type"in K&&"id"in K&&K.lc===1&&K.type==="secret"){let[H]=K.id;if(H in Y)return Y[H];else if(W){let B=wQ(H);if(B)return B}throw Error(`Missing secret "${H}" at ${z}`)}if("lc"in K&&"type"in K&&"id"in K&&K.lc===1&&K.type==="not_implemented"){let B=JSON.stringify(K);throw Error(`Trying to load an object that doesn't implement serialization: ${z} -> ${B}`)}if("lc"in K&&"type"in K&&"id"in K&&"kwargs"in K&&K.lc===1&&K.type==="constructor"){let H=K,B=JSON.stringify(H),[F,...w]=H.id.slice().reverse(),A=w.reverse(),E={langchain_core:jz,langchain:J},P=null,j=[A.join("/")];if(A[0]==="langchain_community")j.push(["langchain",...A.slice(1)].join("/"));let R=j.find((T)=>(T in Z));if(m2.concat($).includes(A.join("/"))||R)if(R!==void 0)P=await Z[R];else throw Error(`Missing key "${A.join("/")}" for ${z} in load(optionalImportsMap={})`);else{let T;if(A[0]==="langchain"||A[0]==="langchain_core")T=E[A[0]],A.shift();else throw Error(`Invalid namespace: ${z} -> ${B}`);if(A.length===0)throw Error(`Invalid namespace: ${z} -> ${B}`);let V;do if(V=A.join("__"),V in T)break;else A.pop();while(A.length>0);if(V in T)P=T[V]}if(typeof P!=="object"||P===null)throw Error(`Invalid namespace: ${z} -> ${B}`);let k=P[F]??Object.values(P).find((T)=>typeof T==="function"&&R1(T)===F);if(typeof k!=="function")throw Error(`Invalid identifer: ${z} -> ${B}`);let b=new k(I$(await RJ.call({...this,path:[...X,"kwargs"],depth:q+1},H.kwargs),HX,lD(k)));return Object.defineProperty(b.constructor,"name",{value:F}),b}let U={};for(let[H,B]of Object.entries(K))U[H]=await RJ.call({...this,path:[...X,H],depth:q+1},B);return U}async function Rz(Q,Z){let $=JSON.parse(Q),J={optionalImportsMap:Z?.optionalImportsMap??{},optionalImportEntrypoints:Z?.optionalImportEntrypoints??[],secretsMap:Z?.secretsMap??{},secretsFromEnv:Z?.secretsFromEnv??!1,importMap:Z?.importMap??{},path:["$"],depth:0,maxDepth:Z?.maxDepth??cD};return RJ.call(J,$)}function iD(Q){return Q!==null&&Q.lc===1&&Q.type==="constructor"&&Array.isArray(Q.id)}async function K3(Q){if(Q&&typeof Q==="object")if(Array.isArray(Q))return await Promise.all(Q.map(($)=>K3($)));else{let Z={};for(let[$,J]of Object.entries(Q))Z[$]=await K3(J);if(Z.lc===2&&Z.type==="undefined")return;else if(Z.lc===2&&Z.type==="constructor"&&Array.isArray(Z.id))try{let $=Z.id[Z.id.length-1],J;switch($){case"Set":J=Set;break;case"Map":J=Map;break;case"RegExp":J=RegExp;break;case"Error":J=Error;break;default:return Z}if(Z.method)return J[Z.method](...Z.args||[]);else return new J(...Z.args||[])}catch($){return Z}else if(iD(Z))return Rz(JSON.stringify(Z));return Z}return Q}function z3(Q,Z,$,J){return{lc:2,type:"constructor",id:[Q.name],method:Z??null,args:$??[],kwargs:J??{}}}function oD(Q){if(Q===void 0)return{lc:2,type:"undefined"};else if(Q instanceof Set||Q instanceof Map)return z3(Q.constructor,void 0,[Array.from(Q)]);else if(Q instanceof RegExp)return z3(RegExp,void 0,[Q.source,Q.flags]);else if(Q instanceof Error)return z3(Q.constructor,void 0,[Q.message]);else if(Q?.lg_name==="Send")return{node:Q.node,args:Q.args};else return Q}var _J=class{_dumps(Q){return new TextEncoder().encode(g2(Q,($,J)=>{return oD(J)}))}async dumpsTyped(Q){if(Q instanceof Uint8Array)return["bytes",Q];else return["json",this._dumps(Q)]}async _loads(Q){let Z=JSON.parse(Q);return K3(Z)}async loadsTyped(Q,Z){if(Q==="bytes")return typeof Z==="string"?new TextEncoder().encode(Z):Z;else if(Q==="json")return this._loads(typeof Z==="string"?Z:new TextDecoder().decode(Z));else throw Error(`Unknown serialization type: ${Q}`)}};function U3(Q){if(typeof Q!=="object"||Q===null)return Q;let Z=Array.isArray(Q)?[]:{};for(let $ in Q)if(Object.prototype.hasOwnProperty.call(Q,$))Z[$]=U3(Q[$]);return Z}function F1(){return{v:4,id:oZ(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function V8(Q){return{v:Q.v,id:Q.id,ts:Q.ts,channel_values:{...Q.channel_values},channel_versions:{...Q.channel_versions},versions_seen:U3(Q.versions_seen)}}var IJ=class{serde=new _J;constructor(Q){this.serde=Q||this.serde}async get(Q){let Z=await this.getTuple(Q);return Z?Z.checkpoint:void 0}getNextVersion(Q){if(typeof Q==="string")throw Error("Please override this method to use string versions.");return Q!==void 0&&typeof Q==="number"?Q+1:1}};function TJ(Q,Z){if(typeof Q==="number"&&typeof Z==="number")return Math.sign(Q-Z);return String(Q).localeCompare(String(Z))}function SJ(...Q){return Q.reduce((Z,$,J)=>{if(J===0)return $;return TJ(Z,$)>=0?Z:$})}var xJ={[UW]:-1,[H1]:-2,[HW]:-3,[BW]:-4};var QZ=class extends Error{constructor(Q){super(Q);this.name="InvalidNamespaceError"}};function sD(Q){if(Q.length===0)throw new QZ("Namespace cannot be empty.");for(let Z of Q){if(typeof Z!=="string")throw new QZ(`Invalid namespace label '${Z}' found in ${Q}. Namespace labels must be strings, but got ${typeof Z}.`);if(Z.includes("."))throw new QZ(`Invalid namespace label '${Z}' found in ${Q}. Namespace labels cannot contain periods ('.').`);if(Z==="")throw new QZ(`Namespace labels cannot be empty strings. Got ${Z} in ${Q}`)}if(Q[0]==="langgraph")throw new QZ(`Root label for namespace cannot be "langgraph". Got: ${Q}`)}var ZZ=class{async get(Q,Z){return(await this.batch([{namespace:Q,key:Z}]))[0]}async search(Q,Z={}){let{filter:$,limit:J=10,offset:Y=0,query:W}=Z;return(await this.batch([{namespacePrefix:Q,filter:$,limit:J,offset:Y,query:W}]))[0]}async put(Q,Z,$,J){sD(Q),await this.batch([{namespace:Q,key:Z,value:$,index:J}])}async delete(Q,Z){await this.batch([{namespace:Q,key:Z,value:null}])}async listNamespaces(Q={}){let{prefix:Z,suffix:$,maxDepth:J,limit:Y=100,offset:W=0}=Q,X=[];if(Z)X.push({matchType:"prefix",path:Z});if($)X.push({matchType:"suffix",path:$});return(await this.batch([{matchConditions:X.length?X:void 0,maxDepth:J,limit:Y,offset:W}]))[0]}start(){}stop(){}};var tD=(Q)=>{if("lg_name"in Q&&Q.lg_name==="AsyncBatchedStore")return Q.store;return Q},W$=class extends ZZ{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(Q){super();this.store=tD(Q)}get isRunning(){return this.running}async batch(Q){throw 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(Q,Z){return this.enqueueOperation({namespace:Q,key:Z})}async search(Q,Z){let{filter:$,limit:J=10,offset:Y=0,query:W}=Z||{};return this.enqueueOperation({namespacePrefix:Q,filter:$,limit:J,offset:Y,query:W})}async put(Q,Z,$){return this.enqueueOperation({namespace:Q,key:Z,value:$})}async delete(Q,Z){return this.enqueueOperation({namespace:Q,key:Z,value:null})}start(){if(!this.running)this.running=!0,this.processingTask=this.processBatchQueue()}async stop(){if(this.running=!1,this.processingTask)await this.processingTask}enqueueOperation(Q){return new Promise((Z,$)=>{let J=this.nextKey;this.nextKey+=1,this.queue.set(J,{operation:Q,resolve:Z,reject:$})})}async processBatchQueue(){while(this.running){if(await new Promise((Z)=>{setTimeout(Z,0)}),this.queue.size===0)continue;let Q=new Map(this.queue);this.queue.clear();try{let Z=Array.from(Q.values()).map(({operation:J})=>J),$=await this.store.batch(Z);Q.forEach(({resolve:J},Y)=>{let W=Array.from(Q.keys()).indexOf(Y);J($[W])})}catch(Z){Q.forEach(({reject:$})=>{$(Z)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}};var X$=class{serde=new _J;constructor(Q){this.serde=Q||this.serde}};function B3(Q){return Q!=null&&Q.lg_is_channel===!0}var a0=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(Q){if(Q.name===U0.unminifiable_name)return!1;throw Q}}equals(Q){return this===Q}},H3=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function q$(Q){if(Q[H3]===!0)return Q;let Z={};for(let $ in Q){if(!Object.prototype.hasOwnProperty.call(Q,$))continue;let J=Q[$];if(B3(J))Z[$]=J}return Object.assign(Z,{[H3]:!0}),Z}function C6(Q,Z){let $=q$(Q),J={};for(let Y in $){if(!Object.prototype.hasOwnProperty.call($,Y))continue;let W=Z.channel_values[Y];J[Y]=$[Y].fromCheckpoint(W)}return Object.assign(J,{[H3]:!0}),J}function F8(Q,Z,$,J){let Y;if(Z===void 0)Y=Q.channel_values;else{Y={};for(let W in Z){if(!Object.prototype.hasOwnProperty.call(Z,W))continue;try{Y[W]=Z[W].checkpoint()}catch(X){if(X.name===U0.unminifiable_name);else throw X}}}return{v:4,id:J?.id??oZ($),ts:new Date().toISOString(),channel_values:Y,channel_versions:Q.channel_versions,versions_seen:Q.versions_seen}}var eD=(Q)=>{return Q!=null&&Q.lc_graph_name==="BinaryOperatorAggregate"},m8=class Q extends a0{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(Z,$){super();this.operator=Z,this.initialValueFactory=$,this.value=$?.()}fromCheckpoint(Z){let $=new Q(this.operator,this.initialValueFactory);if(typeof Z<"u")$.value=Z;return $}update(Z){let $=Z;if(!$.length)return!1;if(this.value===void 0){let Y=$[0],[W,X]=YJ(Y);if(W)this.value=X;else this.value=Y;$=$.slice(1)}let J=!1;for(let Y of $)if(k2(Y)){if(J)throw new Z0("Can receive only one Overwrite value per step.");let[,W]=YJ(Y);this.value=W,J=!0;continue}else if(!J&&this.value!==void 0)this.value=this.operator(this.value,Y);return!0}get(){if(this.value===void 0)throw new U0;return this.value}checkpoint(){if(this.value===void 0)throw new U0;return this.value}isAvailable(){return this.value!==void 0}equals(Z){if(this===Z)return!0;if(!eD(Z))return!1;return this.operator===Z.operator}};var L8=class Q extends a0{lc_graph_name="LastValue";value=[];constructor(Z){super();if(this.initialValueFactory=Z,Z)this.value=[Z()]}fromCheckpoint(Z){let $=new Q(this.initialValueFactory);if(typeof Z<"u")$.value=[Z];return $}update(Z){if(Z.length===0)return!1;if(Z.length!==1)throw new Z0("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[Z[Z.length-1]],!0}get(){if(this.value.length===0)throw new U0;return this.value[0]}checkpoint(){if(this.value.length===0)throw new U0;return this.value[0]}isAvailable(){return this.value.length!==0}},D3=class Q extends a0{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(Z){let $=new Q;if(typeof Z<"u"){let[J,Y]=Z;$.value=[J],$.finished=Y}return $}update(Z){if(Z.length===0)return!1;return this.finished=!1,this.value=[Z[Z.length-1]],!0}get(){if(this.value.length===0||!this.finished)throw new U0;return this.value[0]}checkpoint(){if(this.value.length===0)return;return[this.value[0],this.finished]}consume(){if(this.finished)return this.finished=!1,this.value=[],!0;return!1}finish(){if(!this.finished&&this.value.length>0)return this.finished=!0,!0;return!1}isAvailable(){return this.value.length!==0&&this.finished}};var G$=class{lc_graph_name="AnnotationRoot";spec;constructor(Q){this.spec=Q}static isInstance(Q){return typeof Q==="object"&&Q!==null&&"lc_graph_name"in Q&&Q.lc_graph_name==="AnnotationRoot"}},L1=function(Q){if(Q)return MJ(Q);else return new L8};L1.Root=(Q)=>new G$(Q);function MJ(Q){if(typeof Q==="object"&&Q&&"reducer"in Q&&Q.reducer)return new m8(Q.reducer,Q.default);if(typeof Q==="object"&&Q&&"value"in Q&&Q.value)return new m8(Q.value,Q.default);return new L8}var QV=["tags","metadata","callbacks","configurable"],ZV=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],$V=25;function z$(...Q){let Z={tags:[],metadata:{},callbacks:void 0,recursionLimit:$V,configurable:{}},$=q0.getRunnableConfig();if($!==void 0){for(let[J,Y]of Object.entries($))if(Y!==void 0)if(QV.includes(J)){let W;if(Array.isArray(Y))W=[...Y];else if(typeof Y==="object")if(J==="callbacks"&&"copy"in Y&&typeof Y.copy==="function")W=Y.copy();else W={...Y};else W=Y;Z[J]=W}else Z[J]=Y}for(let J of Q){if(J===void 0)continue;for(let[Y,W]of Object.entries(J))if(W!==void 0&&ZV.includes(Y))Z[Y]=W}for(let[J,Y]of Object.entries(Z.configurable))if(Z.metadata=Z.metadata??{},!J.startsWith("__")&&(typeof Y==="string"||typeof Y==="number"||typeof Y==="boolean")&&!(J in Z.metadata))Z.metadata[J]=Y;return Z}function V3(){return q0.getRunnableConfig()}function vJ(Q){return Q.split(P0).filter((Z)=>!Z.match(/^\d+$/)).map((Z)=>Z.split(EQ)[0]).join(P0)}function Tz(Q){let Z=Q.split(P0);while(Z.length>1&&Z[Z.length-1].match(/^\d+$/))Z.pop();return Z.slice(0,-1).join(P0)}var C=(Q)=>BigInt(Q),F0=(Q,Z=0)=>new DataView(Q.buffer,Q.byteOffset+Z,Q.byteLength-Z),vz=C("0x9E3779B1"),yz=C("0x85EBCA77"),JV=C("0xC2B2AE3D"),b6=C("0x9E3779B185EBCA87"),w1=C("0xC2B2AE3D27D4EB4F"),Cz=C("0x165667B19E3779F9"),w3=C("0x85EBCA77C2B2AE63"),YV=C("0x27D4EB2F165667C5"),WV=C("0x165667919E3779F9"),XV=C("0x9FB21C651E98DF25"),qV=(Q)=>{let Z=Q.length;if(Z%2!==0)throw Error("String should have an even number of characters");let $=Z/2,J=new Uint8Array($),Y=0,W=0;while(W<$){let X=Q.slice(Y,Y+=2);J[W]=Number.parseInt(X,16),W+=1}return F0(J)},d8=qV("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),$Z=(C(1)<<C(128))-C(1),$0=(C(1)<<C(64))-C(1),bJ=(C(1)<<C(32))-C(1);function JZ(Q){if(!Q)throw Error("Assert failed")}function GV(Q){let Z=new DataView(new ArrayBuffer(8));return Z.setBigUint64(0,Q,!0),Z.getBigUint64(0,!1)}function zV(Q){let Z=Q;return Z=(Z&C(65535))<<C(16)|(Z&C(4294901760))>>C(16),Z=(Z&C(16711935))<<C(8)|(Z&C(4278255360))>>C(8),Z}function KV(Q,Z){return(Q&bJ)*(Z&bJ)&$0}function UV(Q,Z){return(Q<<Z|Q>>C(32)-Z)&bJ}function bz(Q,Z,$){for(let J=0;J<8;J+=1){let Y=Z.getBigUint64(J*8,!0),W=Y^$.getBigUint64(J*8,!0);Q[J^1]+=Y,Q[J]+=KV(W,W>>C(32))}return Q}function Sz(Q,Z,$,J){for(let Y=0;Y<J;Y+=1)bz(Q,F0(Z,Y*64),F0($,Y*8));return Q}function HV(Q,Z){for(let $=0;$<8;$+=1){let J=Z.getBigUint64($*8,!0),Y=Q[$];Y=F3(Y,C(47)),Y^=J,Y*=vz,Q[$]=Y&$0}return Q}function yJ(Q,Z){return kz(Q[0]^Z.getBigUint64(0,!0),Q[1]^Z.getBigUint64(8,!0))}function xz(Q,Z,$){let J=$;return J+=yJ(Q.slice(0),F0(Z,0)),J+=yJ(Q.slice(2),F0(Z,16)),J+=yJ(Q.slice(4),F0(Z,32)),J+=yJ(Q.slice(6),F0(Z,48)),u8(J&$0)}function BV(Q,Z,$,J,Y){let W=Q,X=Math.floor(($.byteLength-64)/8),q=64*X,G=Math.floor((Z.byteLength-1)/q);for(let z=0;z<G;z+=1)W=Sz(W,F0(Z,z*q),$,X),W=Y(W,F0($,$.byteLength-64));{let z=Math.floor((Z.byteLength-1-q*G)/64);W=Sz(W,F0(Z,G*q),$,z),W=J(W,F0(Z,Z.byteLength-64),F0($,$.byteLength-64-7))}return W}function DV(Q,Z){let $=new BigUint64Array([JV,b6,w1,Cz,w3,yz,YV,vz]);JZ(Q.byteLength>128),$=BV($,Q,Z,bz,HV),JZ($.length*8===64);{let J=xz($,F0(Z,11),C(Q.byteLength)*b6&$0);return xz($,F0(Z,Z.byteLength-64-11),~(C(Q.byteLength)*w1)&$0)<<C(64)|J}}function kz(Q,Z){let $=Q*Z&$Z;return $&$0^$>>C(64)}function Mz(Q,Z,$){return kz((Q.getBigUint64(0,!0)^Z.getBigUint64(0,!0)+$)&$0,(Q.getBigUint64(8,!0)^Z.getBigUint64(8,!0)-$)&$0)}function CJ(Q,Z,$,J,Y){let W=Q&$0,X=Q>>C(64)&$0;return W+=Mz(Z,J,Y),W^=$.getBigUint64(0,!0)+$.getBigUint64(8,!0),W&=$0,X+=Mz($,F0(J,16),Y),X^=Z.getBigUint64(0,!0)+Z.getBigUint64(8,!0),X&=$0,X<<C(64)|W}function u8(Q){let Z=Q;return Z^=Z>>C(37),Z*=WV,Z&=$0,Z^=Z>>C(32),Z}function kJ(Q){let Z=Q;return Z^=Z>>C(33),Z*=w1,Z&=$0,Z^=Z>>C(29),Z*=Cz,Z&=$0,Z^=Z>>C(32),Z}function VV(Q,Z,$){let J=Q.byteLength;JZ(J>0&&J<=3);let Y=C(Q.getUint8(J-1))|C(J<<8)|C(Q.getUint8(0)<<16)|C(Q.getUint8(J>>1)<<24),W=(Y^(C(Z.getUint32(0,!0))^C(Z.getUint32(4,!0)))+$)&$0,X=(C(Z.getUint32(8,!0))^C(Z.getUint32(12,!0)))-$;return(kJ((UV(zV(Y),C(13))^X)&$0)&$0)<<C(64)|kJ(W)}function F3(Q,Z){return Q^Q>>Z}function FV(Q,Z,$){let J=Q.byteLength;JZ(J>=4&&J<=8);{let Y=Q.getUint32(0,!0),W=Q.getUint32(J-4,!0),X=((C(Y)|C(W)<<C(32))^(Z.getBigUint64(16,!0)^Z.getBigUint64(24,!0))+$&$0)*(b6+(C(J)<<C(2)))&$Z;return X+=(X&$0)<<C(65),X&=$Z,X^=X>>C(67),F3(F3(X&$0,C(35))*XV&$0,C(28))|u8(X>>C(64))<<C(64)}}function LV(Q,Z,$){let J=Q.byteLength;JZ(J>=9&&J<=16);{let Y=(Z.getBigUint64(32,!0)^Z.getBigUint64(40,!0))+$&$0,W=(Z.getBigUint64(48,!0)^Z.getBigUint64(56,!0))-$&$0,X=Q.getBigUint64(0,!0),q=Q.getBigUint64(J-8,!0),G=(X^q^Y)*b6,z=(G&$0)+(C(J-1)<<C(54));G=G&($Z^$0)|z,q^=W,G+=q+(q&bJ)*(yz-C(1))<<C(64),G&=$Z,G^=GV(G>>C(64));let K=(G&$0)*w1;return K+=(G>>C(64))*w1<<C(64),K&=$Z,u8(K&$0)|u8(K>>C(64))<<C(64)}}function wV(Q,Z){let $=Q.byteLength;if(JZ($<=16),$>8)return LV(Q,d8,Z);if($>=4)return FV(Q,d8,Z);if($>0)return VV(Q,d8,Z);return kJ(Z^d8.getBigUint64(64,!0)^d8.getBigUint64(72,!0))|kJ(Z^d8.getBigUint64(80,!0)^d8.getBigUint64(88,!0))<<C(64)}function L3(Q){return~Q+C(1)&$0}function AV(Q,Z,$){let J=C(Q.byteLength)*b6&$0,Y=C(Q.byteLength-1)/C(32);while(Y>=0){let q=Number(Y);J=CJ(J,F0(Q,16*q),F0(Q,Q.byteLength-16*(q+1)),F0(Z,32*q),$),Y-=C(1)}let W=J+(J>>C(64))&$0;W=u8(W);let X=(J&$0)*b6+(J>>C(64))*w3+(C(Q.byteLength)-$&$0)*w1;return X&=$0,X=L3(u8(X)),W|X<<C(64)}function PV(Q,Z,$){let J=C(Q.byteLength)*b6&$0;for(let X=32;X<160;X+=32)J=CJ(J,F0(Q,X-32),F0(Q,X-16),F0(Z,X-32),$);J=u8(J&$0)|u8(J>>C(64))<<C(64);for(let X=160;X<=Q.byteLength;X+=32)J=CJ(J,F0(Q,X-32),F0(Q,X-16),F0(Z,3+X-160),$);J=CJ(J,F0(Q,Q.byteLength-16),F0(Q,Q.byteLength-32),F0(Z,103),L3($));let Y=J+(J>>C(64))&$0;Y=u8(Y);let W=(J&$0)*b6+(J>>C(64))*w3+(C(Q.byteLength)-$&$0)*w1;return W&=$0,W=L3(u8(W)),Y|W<<C(64)}function K6(Q,Z=C(0)){let J=F0(typeof Q==="string"?new TextEncoder().encode(Q):Q),Y=J.byteLength,W=(X)=>X.toString(16).padStart(32,"0");if(Y<=16)return W(wV(J,Z));if(Y<=128)return W(AV(J,d8,Z));if(Y<=240)return W(PV(J,d8,Z));return W(DV(J,d8))}function fJ(Q){return/^[0-9a-f]{32}$/.test(Q)}function hJ(Q){let Z=q0.getRunnableConfig();if(!Z)throw Error("Called interrupt() outside the context of a graph.");let $=Z.configurable;if(!$)throw Error("No configurable found in config");if(!$[k0])throw new y6("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let J=$[nQ];J.interruptCounter+=1;let Y=J.interruptCounter;if(J.resume.length>0&&Y<J.resume.length)return $[U8]?.([[JQ,J.resume]]),J.resume[Y];if(J.nullResume!==void 0){if(J.resume.length!==Y)throw Error(`Resume length mismatch: ${J.resume.length} !== ${Y}`);let X=J.consumeNullResume();return J.resume.push(X),$[U8]?.([[JQ,J.resume]]),X}let W=$[rQ]?.split(P0);throw new f8([{id:W?K6(W.join(P0)):void 0,value:Q}])}var VQ=class extends c{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(Q){super();this.name=Q.name??Q.func.name,this.func=Q.func,this.config=Q.tags?{tags:Q.tags}:void 0,this.trace=Q.trace??this.trace,this.recurse=Q.recurse??this.recurse}async _tracedInvoke(Q,Z,$){return new Promise((J,Y)=>{let W=W0(Z,{callbacks:$?.getChild()});q0.runWithConfig(W,async()=>{try{J(await this.func(Q,W))}catch(X){Y(X)}})})}async invoke(Q,Z){let $,J=z$(Z),Y=w0(this.config,J);if(this.trace)$=await this._callWithConfig(this._tracedInvoke,Q,Y);else $=await q0.runWithConfig(Y,async()=>this.func(Q,Y));if(c.isRunnable($)&&this.recurse)return await q0.runWithConfig(Y,async()=>$.invoke(Q,Y));return $}};function*U6(Q,Z){if(Z===void 0)yield*Q;else for(let $ of Q)yield[Z,$]}async function w8(Q){let Z=[];for await(let $ of await Q)Z.push($);return Z}function A1(Q){let Z=[];for(let $ of Q)Z.push($);return Z}function P1(Q,Z){if(!Q)return{configurable:Z};else if(!("configurable"in Q))return{...Q,configurable:Z};else return{...Q,configurable:{...Q.configurable,...Z}}}function fz(Q){return Q!=null&&typeof Q==="function"&&Q instanceof Object.getPrototypeOf(async function*(){}).constructor}function hz(Q){return Q!=null&&typeof Q==="function"&&Q instanceof Object.getPrototypeOf(function*(){}).constructor}var wm={[Symbol.for("LG_SKIP_WRITE")]:!0};function NV(Q){return typeof Q==="object"&&Q?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}var CQ={[Symbol.for("LG_PASSTHROUGH")]:!0};function gJ(Q){return typeof Q==="object"&&Q?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}var A3=Symbol("IS_WRITER"),f0=class Q extends VQ{writes;constructor(Z,$){let J=`ChannelWrite<${Z.map((Y)=>{if(o0(Y))return Y.node;else if("channel"in Y)return Y.channel;return"..."}).join(",")}>`;super({writes:Z,name:J,tags:$,trace:!1,func:async(Y,W)=>{return this._write(Y,W??{})}});this.writes=Z}async _write(Z,$){let J=this.writes.map((Y)=>{if(P3(Y)&&gJ(Y.value))return{mapper:Y.mapper,value:Z};else if(mJ(Y)&&gJ(Y.value))return{channel:Y.channel,value:Z,skipNone:Y.skipNone,mapper:Y.mapper};else return Y});return await Q.doWrite($,J),Z}static async doWrite(Z,$){for(let W of $){if(mJ(W)){if(W.channel===YQ)throw new Z0("Cannot write to the reserved channel TASKS");if(gJ(W.value))throw new Z0("PASSTHROUGH value must be replaced")}if(P3(W)){if(gJ(W.value))throw new Z0("PASSTHROUGH value must be replaced")}}let J=[];for(let W of $)if(o0(W))J.push([YQ,W]);else if(P3(W)){let X=await W.mapper.invoke(W.value,Z);if(X!=null&&X.length>0)J.push(...X)}else if(mJ(W)){let X=W.mapper!==void 0?await W.mapper.invoke(W.value,Z):W.value;if(NV(X))continue;if(W.skipNone&&X===void 0)continue;J.push([W.channel,X])}else throw Error(`Invalid write entry: ${JSON.stringify(W)}`);let Y=Z.configurable?.[U8];Y(J)}static isWriter(Z){return Z instanceof Q||A3 in Z&&!!Z[A3]}static registerWriter(Z){return Object.defineProperty(Z,A3,{value:!0})}};function mJ(Q){return Q!==void 0&&typeof Q.channel==="string"}function P3(Q){return Q!==void 0&&!mJ(Q)&&c.isRunnable(Q.mapper)}var gz=class Q extends VQ{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(Z,$,J=!1){super({trace:!1,func:(Y,W)=>Q.doRead(W,this.channel,this.fresh,this.mapper)});this.fresh=J,this.mapper=$,this.channel=Z,this.name=Array.isArray(Z)?`ChannelRead<${Z.join(",")}>`:`ChannelRead<${Z}>`}static doRead(Z,$,J,Y){let W=Z.configurable?.[b8];if(!W)throw Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");if(Y)return Y(W($,J));else return W($,J)}},YZ=new Y6,A8=class Q extends b0{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=YZ;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(Z){let{channels:$,triggers:J,mapper:Y,writers:W,bound:X,kwargs:q,metadata:G,retryPolicy:z,cachePolicy:K,tags:U,subgraphs:H,ends:B}=Z,F=[...Z.config?.tags?Z.config.tags:[],...U??[]];super({...Z,bound:Z.bound??YZ,config:{...Z.config?Z.config:{},tags:F}});this.channels=$,this.triggers=J,this.mapper=Y,this.writers=W??this.writers,this.bound=X??this.bound,this.kwargs=q??this.kwargs,this.metadata=G??this.metadata,this.tags=F,this.retryPolicy=z,this.cachePolicy=K,this.subgraphs=H,this.ends=B}getWriters(){let Z=[...this.writers];while(Z.length>1&&Z[Z.length-1]instanceof f0&&Z[Z.length-2]instanceof f0){let $=Z.slice(-2),J=$[0].writes.concat($[1].writes);Z[Z.length-2]=new f0(J,$[0].config?.tags),Z.pop()}return Z}getNode(){let Z=this.getWriters();if(this.bound===YZ&&Z.length===0)return;else if(this.bound===YZ&&Z.length===1)return Z[0];else if(this.bound===YZ)return new s0({first:Z[0],middle:Z.slice(1,Z.length-1),last:Z[Z.length-1],omitSequenceTags:!0});else if(Z.length>0)return new s0({first:this.bound,middle:Z.slice(0,Z.length-1),last:Z[Z.length-1],omitSequenceTags:!0});else return this.bound}join(Z){if(!Array.isArray(Z))throw Error("channels must be a list");if(typeof this.channels!=="object")throw Error("all channels must be named when using .join()");return new Q({channels:{...this.channels,...Object.fromEntries(Z.map(($)=>[$,$]))},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(Z){if(f0.isWriter(Z))return new Q({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,Z],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy});else if(this.bound===YZ)return new Q({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:v0(Z),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy});else return new Q({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(Z),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function OV(Q){return"steps"in Q&&Array.isArray(Q.steps)}function K$(Q){return"lg_is_pregel"in Q&&Q.lg_is_pregel===!0}function dJ(Q){let Z=[Q];for(let $ of Z)if(K$($))return $;else if(OV($))Z.push(...$.steps)}function N1(Q,Z,$=!0,J=!1){try{return Q[Z].get()}catch(Y){if(Y.name===U0.unminifiable_name){if(J)return Y;else if($)return null}throw Y}}function P8(Q,Z,$=!0){if(Array.isArray(Z)){let J={};for(let Y of Z)try{J[Y]=N1(Q,Y,!$)}catch(W){if(W.name===U0.unminifiable_name)continue}return J}else return N1(Q,Z)}function*mz(Q,Z){if(Q.graph===B0.PARENT)throw new Z0("There is no parent graph.");if(Q.goto){let $;if(Array.isArray(Q.goto))$=Q.goto;else $=[Q.goto];for(let J of $)if(o0(J))yield[BQ,YQ,J];else if(typeof J==="string")yield[BQ,`branch:to:${J}`,"__start__"];else throw Error(`In Command.send, expected Send or string, got ${typeof J}`)}if(Q.resume)if(typeof Q.resume==="object"&&Object.keys(Q.resume).length&&Object.keys(Q.resume).every(fJ))for(let[$,J]of Object.entries(Q.resume)){let Y=Z.filter((W)=>W[0]===$&&W[1]===JQ).map((W)=>W[2]).slice(0,1)??[];Y.push(J),yield[$,JQ,Y]}else yield[BQ,JQ,Q.resume];if(Q.update){if(typeof Q.update!=="object"||!Q.update)throw Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(Q.update))for(let[$,J]of Q.update)yield[BQ,$,J];else for(let[$,J]of Object.entries(Q.update))yield[BQ,$,J]}}function*uJ(Q,Z){if(Z!==void 0&&Z!==null)if(Array.isArray(Q)&&typeof Z==="object"&&!Array.isArray(Z)){for(let $ in Z)if(Q.includes($))yield[$,Z[$]]}else if(Array.isArray(Q))throw Error('Input chunk must be an object when "inputChannels" is an array');else yield[Q,Z]}function*pJ(Q,Z,$){if(Array.isArray(Q)){if(Z===!0||Z.find(([J,Y])=>Q.includes(J)))yield P8($,Q)}else if(Z===!0||Z.some(([J,Y])=>J===Q))yield N1($,Q)}function*dz(Q,Z,$){let J=Z.filter(([q,G])=>{return(q.config===void 0||!q.config.tags?.includes(K0))&&G[0][0]!==t0&&G[0][0]!==J0});if(!J.length)return;let Y;if(J.some(([q])=>q.writes.some(([G,z])=>G===H8)))Y=J.flatMap(([q])=>q.writes.filter(([G,z])=>G===H8).map(([G,z])=>[q.name,z]));else if(!Array.isArray(Q))Y=J.flatMap(([q])=>q.writes.filter(([G,z])=>G===Q).map(([G,z])=>[q.name,z]));else Y=J.flatMap(([q])=>{let{writes:G}=q,z={};for(let[K]of G)if(Q.includes(K))z[K]=(z[K]||0)+1;if(Object.values(z).some((K)=>K>1))return G.filter(([K])=>Q.includes(K)).map(([K,U])=>[q.name,{[K]:U}]);else return[[q.name,Object.fromEntries(G.filter(([K])=>Q.includes(K)))]]});let W={};for(let[q,G]of Y){if(!(q in W))W[q]=[];W[q].push(G)}let X={};for(let q in W)if(W[q].length===1){let[G]=W[q];X[q]=G}else X[q]=W[q];if($)X.__metadata__={cached:$};yield X}function cJ(Q){let Z=typeof Q[Q0];if(Z==="number")return 0;if(Z==="string")return"";for(let $ in Q){if(!Object.prototype.hasOwnProperty.call(Q,$))continue;let J=typeof Q[$];if(J==="number")return 0;if(J==="string")return"";break}}function WZ(Q,Z){if(Object.keys(Q).length>0){let $=cJ(Z);return Object.fromEntries(Object.entries(Z).filter(([J,Y])=>Y>(Q[J]??$)))}else return Z}function uz(Q,Z){return Q&&!Array.isArray(Q)&&!(Q instanceof Date)&&typeof Q==="object"?Q:{[Z]:Q}}function bQ(Q,Z){if(Q===null)return{configurable:Z};else if(Q?.configurable===void 0)return{...Q,configurable:Z};else return{...Q,configurable:{...Q.configurable,...Z}}}function k6(Q,Z){let $=Z?.parents??{};if(Object.keys($).length>0)return bQ(Q,{[MQ]:{...$,[Q.configurable?.checkpoint_ns??""]:Q.configurable?.checkpoint_id}});else return Q}function XZ(...Q){let Z=[...new Set(Q.filter(Boolean))];if(Z.length===0)return{signal:void 0,dispose:void 0};if(Z.length===1)return{signal:Z[0],dispose:void 0};let $=new AbortController,J=()=>{let W=Z.find((X)=>X.aborted)?.reason;$.abort(W),Z.forEach((X)=>X.removeEventListener("abort",J))};Z.forEach((W)=>W.addEventListener("abort",J,{once:!0}));let Y=Z.find((W)=>W.aborted);if(Y)$.abort(Y.reason);return{signal:$.signal,dispose:()=>{Z.forEach((W)=>W.removeEventListener("abort",J))}}}var pz=(Q,Z)=>{if(!Q&&!Z)return;if(!Q)return Z;if(!Z)return Q;if(Array.isArray(Q)&&Array.isArray(Z))return[...Q,...Z];if(Array.isArray(Q))return[...Q,Z];if(Array.isArray(Z))return[Q,...Z];return[Q,Z]};var cz=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:Q,name:Z,input:$,retry:J,cache:Y,callbacks:W}){this.func=Q,this.name=Z,this.input=$,this.retry=J,this.cache=Y,this.callbacks=W}};function lz(Q){return typeof Q==="object"&&Q!==null&&"__lg_type"in Q&&Q.__lg_type==="call"}function iz(Q,Z){return new s0({name:Q,first:new VQ({func:($)=>Z(...$),name:Q,trace:!1,recurse:!1}),last:new f0([{channel:H8,value:CQ}],[K0])})}function oz(Q,Z){return new VQ({func:($,J)=>{return Z($,J)},name:Q,trace:!1,recurse:!1})}var nz=(Q)=>{return Q!==void 0?Q+1:1};function EV(Q,Z){if(Z==null)return!1;for(let $ of Q)if(Z[$])return!0;return!1}function jV(Q){let Z;for(let $ in Q){if(!Object.prototype.hasOwnProperty.call(Q,$))continue;if(Z==null)Z=Q[$];else Z=SJ(Z,Q[$])}return Z}function H$(Q,Z,$){let J=cJ(Q.channel_versions),Y=Q.versions_seen[J0]??{},W=!1;if((Q.channel_versions[Q0]??J)>(Y[Q0]??J))W=!0;else for(let q in Q.channel_versions){if(!Object.prototype.hasOwnProperty.call(Q.channel_versions,q))continue;if(Q.channel_versions[q]>(Y[q]??J)){W=!0;break}}let X=$.some((q)=>Z==="*"?!q.config?.tags?.includes(K0):Z.includes(q.name));return W&&X}function U$(Q,Z,$,J,Y=!1){let W=new Set;if(!Array.isArray(J)){for(let[q]of $.writes)if(q===J){W=new Set([q]);break}W=W||new Set}else W=new Set(J.filter((q)=>$.writes.some(([G,z])=>G===q)));let X;if(Y&&W.size>0){let q=Object.fromEntries(Object.entries(Z).filter(([K,U])=>W.has(K))),G=F8(Q,q,-1),z=C6(q,G);jQ(V8(G),z,[$],void 0,void 0),X=P8({...Z,...z},J)}else X=P8(Z,J);return X}function N3(Q,Z,$){for(let[J,Y]of $)if([HQ,YQ].includes(J)&&Y!=null){if(!o0(Y))throw new Z0(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(Y)}`);if(!(Y.node in Z))throw new Z0(`Invalid node name "${Y.node}" in Send packet`)}Q($)}var RV=new Set([ZJ,HQ,JQ,J0,H8,t0]);function jQ(Q,Z,$,J,Y){$.sort((H,B)=>{let F=H.path?.slice(0,3)||[],w=B.path?.slice(0,3)||[];for(let A=0;A<Math.min(F.length,w.length);A+=1){if(F[A]<w[A])return-1;if(F[A]>w[A])return 1}return F.length-w.length});let W=$.some((H)=>H.triggers.length>0),X=q$(Z);for(let H of $){Q.versions_seen[H.name]??={};for(let B of H.triggers)if(B in Q.channel_versions)Q.versions_seen[H.name][B]=Q.channel_versions[B]}let q=jV(Q.channel_versions),G=new Set($.flatMap((H)=>H.triggers).filter((H)=>!b2.includes(H))),z=!1;for(let H of G)if(H in X&&X[H].consume()){if(J!==void 0)Q.channel_versions[H]=J(q),z=!0}let K={};for(let H of $)for(let[B,F]of H.writes)if(RV.has(B));else if(B in X)K[B]??=[],K[B].push(F);if(q!=null&&J!=null)q=z?J(q):q;let U=new Set;for(let[H,B]of Object.entries(K))if(H in X){let F=X[H],w;try{w=F.update(B)}catch(A){if(A.name===Z0.unminifiable_name){let E=new Z0(`Invalid update for channel "${H}" with values ${JSON.stringify(B)}: ${A.message}`);throw E.lc_error_code=A.lc_error_code,E}else throw A}if(w&&J!==void 0){if(Q.channel_versions[H]=J(q),F.isAvailable())U.add(H)}}if(W)for(let H in X){if(!Object.prototype.hasOwnProperty.call(X,H))continue;let B=X[H];if(B.isAvailable()&&!U.has(H)){if(B.update([])&&J!==void 0){if(Q.channel_versions[H]=J(q),B.isAvailable())U.add(H)}}}if(W&&!EV(U,Y))for(let H in X){if(!Object.prototype.hasOwnProperty.call(X,H))continue;let B=X[H];if(B.finish()&&J!==void 0){if(Q.channel_versions[H]=J(q),B.isAvailable())U.add(H)}}return U}function*_V(Q,Z,$){if($.updatedChannels!=null&&$.triggerToNodes!=null){let J=new Set;for(let Y of $.updatedChannels){let W=$.triggerToNodes[Y];for(let X of W??[])J.add(X)}yield*[...J].sort();return}if((()=>{for(let J in Q.channel_versions)if(Q.channel_versions[J]!==null)return!1;return!0})())return;for(let J in Z){if(!Object.prototype.hasOwnProperty.call(Z,J))continue;yield J}}function f6(Q,Z,$,J,Y,W,X){let q={},G=J[YQ];if(G?.isAvailable()){let z=G.get().length;for(let K=0;K<z;K+=1){let U=lJ([HQ,K],Q,Z,$,J,Y,W,X);if(U!==void 0)q[U.id]=U}}for(let z of _V(Q,$,X)){let K=lJ([pZ,z],Q,Z,$,J,Y,W,X);if(K!==void 0)q[K.id]=K}return q}function lJ(Q,Z,$,J,Y,W,X,q){let{step:G,checkpointer:z,manager:K}=q,U=W.configurable??{},H=U.checkpoint_ns??"";if(Q[0]===HQ&&lz(Q[Q.length-1])){let B=Q[Q.length-1],F=iz(B.name,B.func),w=[HQ],A=H===""?B.name:`${H}${P0}${B.name}`,E=q6(JSON.stringify([A,G.toString(),B.name,HQ,Q[1],Q[2]]),Z.id),P=`${A}${EQ}${E}`,j=[...Q.slice(0,3),!0],R={langgraph_step:G,langgraph_node:B.name,langgraph_triggers:w,langgraph_path:j,langgraph_checkpoint_ns:P};if(X){let k=[];return{name:B.name,input:B.input,proc:F,writes:k,config:W0(w0(W,{metadata:R,store:q.store??W.store}),{runName:B.name,callbacks:K?.getChild(`graph:step:${G}`),configurable:{[u1]:E,[U8]:(b)=>N3((T)=>k.push(...T),J,b),[b8]:(b,T=!1)=>U$(Z,Y,{name:B.name,writes:k,triggers:w,path:j},b,T),[k0]:z??U[k0],[MQ]:{...U[MQ],[H]:Z.id},[nQ]:O3({pendingWrites:$??[],taskId:E,currentTaskInput:B.input,resumeMap:W.configurable?.[p1],namespaceHash:K6(P)}),[uZ]:Z.channel_values[U1],checkpoint_id:void 0,checkpoint_ns:P}}),triggers:w,retry_policy:B.retry,cache_key:B.cache?{key:K6((B.cache.keyFunc??JSON.stringify)([B.input])),ns:[e9,B.name??"__dynamic__"],ttl:B.cache.ttl}:void 0,id:E,path:j,writers:[]}}else return{id:E,name:B.name,interrupts:[],path:j}}else if(Q[0]===HQ){let B=typeof Q[1]==="number"?Q[1]:parseInt(Q[1],10);if(!Y[YQ]?.isAvailable())return;let F=Y[YQ].get();if(B<0||B>=F.length)return;let w=JJ(F[B])&&!o0(F[B])?new u0(F[B].node,F[B].args):F[B];if(!JJ(w)){console.warn(`Ignoring invalid packet ${JSON.stringify(w)} in pending sends.`);return}if(!(w.node in J)){console.warn(`Ignoring unknown node name ${w.node} in pending sends.`);return}let A=[HQ],E=H===""?w.node:`${H}${P0}${w.node}`,P=q6(JSON.stringify([E,G.toString(),w.node,HQ,B.toString()]),Z.id),j=`${E}${EQ}${P}`,R={langgraph_step:G,langgraph_node:w.node,langgraph_triggers:A,langgraph_path:Q.slice(0,3),langgraph_checkpoint_ns:j};if(X){let k=J[w.node],b=k.getNode();if(b!==void 0){if(k.metadata!==void 0)R={...R,...k.metadata};let T=[];return{name:w.node,input:w.args,proc:b,subgraphs:k.subgraphs,writes:T,config:W0(w0(W,{metadata:R,tags:k.tags,store:q.store??W.store}),{runName:w.node,callbacks:K?.getChild(`graph:step:${G}`),configurable:{[u1]:P,[U8]:(V)=>N3((v)=>T.push(...v),J,V),[b8]:(V,v=!1)=>U$(Z,Y,{name:w.node,writes:T,triggers:A,path:Q},V,v),[k0]:z??U[k0],[MQ]:{...U[MQ],[H]:Z.id},[nQ]:O3({pendingWrites:$??[],taskId:P,currentTaskInput:w.args,resumeMap:W.configurable?.[p1],namespaceHash:K6(j)}),[uZ]:Z.channel_values[U1],checkpoint_id:void 0,checkpoint_ns:j}}),triggers:A,retry_policy:k.retryPolicy,cache_key:k.cachePolicy?{key:K6((k.cachePolicy.keyFunc??JSON.stringify)([w.args])),ns:[e9,k.name??"__dynamic__",w.node],ttl:k.cachePolicy.ttl}:void 0,id:P,path:Q,writers:k.getWriters()}}}else return{id:P,name:w.node,interrupts:[],path:Q}}else if(Q[0]===pZ){let B=Q[1].toString(),F=J[B];if(F===void 0)return;if($?.length){let P=H===""?B:`${H}${P0}${B}`,j=q6(JSON.stringify([P,G.toString(),B,pZ,B]),Z.id);if($.some((R)=>R[0]===j&&R[1]!==t0))return}let w=cJ(Z.channel_versions);if(w===void 0)return;let A=Z.versions_seen[B]??{},E=F.triggers.find((P)=>{if(!Y[P].isAvailable())return!1;return(Z.channel_versions[P]??w)>(A[P]??w)});if(E!==void 0){let P=IV(F,Y,X);if(P===void 0)return;let j=H===""?B:`${H}${P0}${B}`,R=q6(JSON.stringify([j,G.toString(),B,pZ,[E]]),Z.id),k=`${j}${EQ}${R}`,b={langgraph_step:G,langgraph_node:B,langgraph_triggers:[E],langgraph_path:Q,langgraph_checkpoint_ns:k};if(X){let T=F.getNode();if(T!==void 0){if(F.metadata!==void 0)b={...b,...F.metadata};let V=[];return{name:B,input:P,proc:T,subgraphs:F.subgraphs,writes:V,config:W0(w0(W,{metadata:b,tags:F.tags,store:q.store??W.store}),{runName:B,callbacks:K?.getChild(`graph:step:${G}`),configurable:{[u1]:R,[U8]:(v)=>N3((I)=>{V.push(...I)},J,v),[b8]:(v,I=!1)=>U$(Z,Y,{name:B,writes:V,triggers:[E],path:Q},v,I),[k0]:z??U[k0],[MQ]:{...U[MQ],[H]:Z.id},[nQ]:O3({pendingWrites:$??[],taskId:R,currentTaskInput:P,resumeMap:W.configurable?.[p1],namespaceHash:K6(k)}),[uZ]:Z.channel_values[U1],checkpoint_id:void 0,checkpoint_ns:k}}),triggers:[E],retry_policy:F.retryPolicy,cache_key:F.cachePolicy?{key:K6((F.cachePolicy.keyFunc??JSON.stringify)([P])),ns:[e9,F.name??"__dynamic__",B],ttl:F.cachePolicy.ttl}:void 0,id:R,path:Q,writers:F.getWriters()}}}else return{id:R,name:B,interrupts:[],path:Q}}}}function IV(Q,Z,$){let J;if(typeof Q.channels==="object"&&!Array.isArray(Q.channels)){J={};for(let[Y,W]of Object.entries(Q.channels))if(Q.triggers.includes(W))try{J[Y]=N1(Z,W,!1)}catch(X){if(X.name===U0.unminifiable_name)return;else throw X}else if(W in Z)try{J[Y]=N1(Z,W,!1)}catch(X){if(X.name===U0.unminifiable_name)continue;else throw X}}else if(Array.isArray(Q.channels)){let Y=!1;for(let W of Q.channels)try{J=N1(Z,W,!1),Y=!0;break}catch(X){if(X.name===U0.unminifiable_name)continue;else throw X}if(!Y)return}else throw Error(`Invalid channels type, expected list or dict, got ${Q.channels}`);if($&&Q.mapper!==void 0)J=Q.mapper(J);return J}function rz(Q,Z){if(typeof Q.args!=="object"||Q.args===null)return Q;let $={};for(let[J,Y]of Object.entries(Q.args)){let W=Z[J];if(!W||W.lc_graph_name!=="UntrackedValue")$[J]=Y}return new u0(Q.node,$)}function O3({pendingWrites:Q,taskId:Z,currentTaskInput:$,resumeMap:J,namespaceHash:Y}){let W=Q.find(([q,G])=>q===BQ&&G===JQ)?.[2],X={callCounter:0,interruptCounter:-1,resume:(()=>{let q=Q.filter(([G,z])=>G===Z&&z===JQ).flatMap(([G,z,K])=>K);if(J!=null&&Y in J){let G=J[Y];q.push(G)}return q})(),nullResume:W,subgraphCounter:0,currentTaskInput:$,consumeNullResume:()=>{if(X.nullResume)return delete X.nullResume,Q.splice(Q.findIndex(([q,G])=>q===BQ&&G===JQ),1),W}};return X}var B$={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},D$=(Q,Z)=>`${Q.start}${Z}${Q.end}`;function*E3(Q){for(let{id:Z,name:$,input:J,config:Y,triggers:W,writes:X}of Q){if(Y?.tags?.includes(K0))continue;yield{id:Z,name:$,input:J,triggers:W,interrupts:X.filter(([q,G])=>{return q===Z&&G===J0}).map(([,q])=>{return q})}}}function TV(Q){if(typeof Q!=="object"||Q===null)return!1;return"$writes"in Q&&Array.isArray(Q.$writes)}function sz(Q){let Z={};for(let[$,J]of Q){let Y=String($);if(Y in Z){let W=TV(Z[Y])?Z[Y].$writes:[Z[Y]];W.push(J),Z[Y]={$writes:W}}else Z[Y]=J}return Z}function*tz(Q,Z){for(let[{id:$,name:J,config:Y},W]of Q){if(Y?.tags?.includes(K0))continue;yield{id:$,name:J,result:sz(W.filter(([X])=>{return Array.isArray(Z)?Z.includes(X):X===Z})),interrupts:W.filter((X)=>X[0]===J0).map((X)=>X[1])}}}function*az(Q,Z,$,J,Y,W,X,q){function G(U){let H={};if(U.callbacks!=null)H.callbacks=U.callbacks;if(U.configurable!=null)H.configurable=U.configurable;if(U.maxConcurrency!=null)H.max_concurrency=U.maxConcurrency;if(U.metadata!=null)H.metadata=U.metadata;if(U.recursionLimit!=null)H.recursion_limit=U.recursionLimit;if(U.runId!=null)H.run_id=U.runId;if(U.runName!=null)H.run_name=U.runName;if(U.tags!=null)H.tags=U.tags;return H}let z=Q.configurable?.checkpoint_ns,K={};for(let U of Y){if(!((U.subgraphs?.length)?U.subgraphs:[U.proc]).find(dJ))continue;let H=`${U.name}:${U.id}`;if(z)H=`${z}|${H}`;K[U.id]={configurable:{thread_id:Q.configurable?.thread_id,checkpoint_ns:H}}}yield{config:G(Q),values:P8(Z,$),metadata:J,next:Y.map((U)=>U.name),tasks:j3(Y,W,K,q),parentConfig:X?G(X):void 0}}function j3(Q,Z,$,J){return Q.map((Y)=>{let W=Z.find(([z,K])=>z===Y.id&&K===t0)?.[2],X=Z.filter(([z,K])=>z===Y.id&&K===J0).map(([,,z])=>z),q=(()=>{if(W||X.length||!Z.length)return;let z=Z.findIndex(([K,U])=>K===Y.id&&U===H8);if(z>=0)return Z[z][2];if(typeof J==="string")return Z.find(([K,U])=>K===Y.id&&U===J)?.[2];if(Array.isArray(J)){let K=Z.filter(([U,H])=>U===Y.id&&J.includes(H)).map(([,U,H])=>[U,H]);if(!K.length)return;return sz(K)}})();if(W)return{id:Y.id,name:Y.name,path:Y.path,error:W,interrupts:X,result:q};let G=$?.[Y.id];return{id:Y.id,name:Y.name,path:Y.path,interrupts:X,...G!==void 0?{state:G}:{},result:q}})}function ez(Q,Z,$){console.log([`${D$(B$.blue,`[${Q}:checkpoint]`)}`,`\x1B[1m State at the end of step ${Q}:\x1B[0m
252
+ `,JSON.stringify(P8(Z,$),null,2)].join(""))}function iJ(Q,Z){let $=Z.length;console.log([`${D$(B$.blue,`[${Q}:tasks]`)}`,`\x1B[1m Starting step ${Q} with ${$} task${$===1?"":"s"}:\x1B[0m
253
+ `,Z.map((J)=>`- ${D$(B$.green,String(J.name))} -> ${JSON.stringify(J.input,null,2)}`).join(`
254
+ `)].join(""))}function QK(Q,Z,$){let J={};for(let[Y,W]of Z)if($.includes(Y)){if(!J[Y])J[Y]=[];J[Y].push(W)}console.log([`${D$(B$.blue,`[${Q}:writes]`)}`,`\x1B[1m Finished step ${Q} with writes to ${Object.keys(J).length} channel${Object.keys(J).length!==1?"s":""}:\x1B[0m
255
+ `,Object.entries(J).map(([Y,W])=>`- ${D$(B$.yellow,Y)} -> ${W.map((X)=>JSON.stringify(X)).join(", ")}`).join(`
256
+ `)].join(""))}var _3=class extends S0{_abortController;_innerReader;constructor(Q,Z){let $=Q.getReader(),J=Z??new AbortController;super({start(Y){return W();function W(){return $.read().then(({done:X,value:q})=>{if(X){Y.close();return}return Y.enqueue(q),W()})}}});this._abortController=J,this._innerReader=$}async cancel(Q){this._abortController.abort(Q),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},oJ=class extends S0{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(Q){let Z,$=new Promise((J)=>{Z=J});super({start:(J)=>{Z(J)}});$.then((J)=>{this.controller=J}),this.passthroughFn=Q.passthroughFn,this.modes=Q.modes}push(Q){this.passthroughFn?.(Q),this.controller.enqueue(Q)}close(){try{this.controller.close()}catch(Q){}finally{this._closed=!0}}error(Q){this.controller.error(Q)}},JK=class extends J8{name="StreamToolsHandler";streamFn;runs={};constructor(Q){super();this.streamFn=Q}handleToolStart(Q,Z,$,J,Y,W,X,q){if(!W||Y&&Y.includes(K0))return;let G=W.langgraph_checkpoint_ns?.split("|")??[],z={ns:G,toolCallId:q,toolName:X??"unknown",input:Z};this.runs[$]=z,this.streamFn([G,"tools",{event:"on_tool_start",toolCallId:z.toolCallId,name:z.toolName,input:Z}])}handleToolEvent(Q,Z){let $=this.runs[Z];if(!$)return;this.streamFn([$.ns,"tools",{event:"on_tool_event",toolCallId:$.toolCallId,name:$.toolName,data:Q}])}handleToolEnd(Q,Z){let $=this.runs[Z];if(delete this.runs[Z],!$)return;this.streamFn([$.ns,"tools",{event:"on_tool_end",toolCallId:$.toolCallId,name:$.toolName,output:Q}])}handleToolError(Q,Z){let $=this.runs[Z];if(delete this.runs[Z],!$)return;this.streamFn([$.ns,"tools",{event:"on_tool_error",toolCallId:$.toolCallId,name:$.toolName,error:Q}])}};function SV(Q){return JSON.stringify(Q,function(Z,$){let J=this[Z];if(J!=null&&typeof J==="object"&&"toDict"in J&&typeof J.toDict==="function"){let{type:Y,data:W}=J.toDict();return{...W,type:Y}}return $})}function xV(Q){if(Q instanceof Error)return{error:Q.name,message:Q.message};return{error:"Error",message:JSON.stringify(Q)}}function I3(Q){if(typeof Q!=="object"||Q==null)return!1;return"configurable"in Q&&typeof Q.configurable==="object"&&Q.configurable!=null}function R3(Q){if(!I3(Q)||!Q.configurable.thread_id)return null;return{thread_id:Q.configurable.thread_id,checkpoint_ns:Q.configurable.checkpoint_ns||"",checkpoint_id:Q.configurable.checkpoint_id||null,checkpoint_map:Q.configurable.checkpoint_map||null}}function ZK(Q){if(I3(Q)){let Z=Object.fromEntries(Object.entries(Q.configurable).filter(([J])=>!J.startsWith("__"))),$={...Q,configurable:Z};return delete $.callbacks,$}return Q}function $K(Q){let Z={...Q,checkpoint:R3(Q.config),parent_checkpoint:R3(Q.parentConfig),config:ZK(Q.config),parent_config:ZK(Q.parentConfig),tasks:Q.tasks.map(($)=>{if(I3($.state)){let J=R3($.state);if(J!=null){let Y={...$,checkpoint:J};return delete Y.state,Y}}return $})};return delete Z.parentConfig,Z}function YK(Q){let Z=new TextEncoder;return new ReadableStream({async start($){let J=(Y)=>{$.enqueue(Z.encode(`event: ${Y.event}
257
+ data: ${SV(Y.data)}
258
+
259
+ `))};try{for await(let Y of Q){let[W,X,q]=Y,G=q;if(X==="debug"){let z=q;if(z.type==="checkpoint")G={...z,payload:$K(z.payload)}}if(X==="checkpoints")G=$K(q);J({event:W?.length?`${X}|${W.join("|")}`:X,data:G})}}catch(Y){J({event:"error",data:xV(Y)})}$.close()}})}var nJ=Symbol.for("INPUT_DONE"),T3=Symbol.for("INPUT_RESUMING"),MV=25;function vV(...Q){return new oJ({passthroughFn:(Z)=>{for(let $ of Q)if($.modes.has(Z[1]))$.push(Z)},modes:new Set(Q.flatMap((Z)=>Array.from(Z.modes)))})}var yV=class extends X${cache;queue=Promise.resolve();constructor(Q){super();this.cache=Q}async get(Q){return this.enqueueOperation("get",Q)}async set(Q){return this.enqueueOperation("set",Q)}async clear(Q){return this.enqueueOperation("clear",Q)}async stop(){await this.queue}enqueueOperation(Q,...Z){let $=this.queue.then(()=>{return this.cache[Q](...Z)});return this.queue=$.then(()=>{return},()=>{return}),$}},WK=class Q{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 Z=!1;if(Q0 in this.checkpoint.channel_versions)Z=!0;else for(let q in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,q)){Z=!0;break}let $=this.config.configurable?.[X6]!==void 0&&this.config.configurable?.[X6],J=this.input===null||this.input===void 0,Y=z0(this.input)&&this.input.resume!=null,W=this.input===T3,X=!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 Z&&($||J||Y||W||X)}constructor(Z){if(this.input=Z.input,this.checkpointer=Z.checkpointer,this.checkpointer!==void 0)this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer);else this.checkpointerGetNextVersion=nz;this.checkpoint=Z.checkpoint,this.checkpointMetadata=Z.checkpointMetadata,this.checkpointPreviousVersions=Z.checkpointPreviousVersions,this.channels=Z.channels,this.checkpointPendingWrites=Z.checkpointPendingWrites,this.step=Z.step,this.stop=Z.stop,this.config=Z.config,this.checkpointConfig=Z.checkpointConfig,this.isNested=Z.isNested,this.manager=Z.manager,this.outputKeys=Z.outputKeys,this.streamKeys=Z.streamKeys,this.nodes=Z.nodes,this.skipDoneTasks=Z.skipDoneTasks,this.store=Z.store,this.cache=Z.cache?new yV(Z.cache):void 0,this.stream=Z.stream,this.checkpointNamespace=Z.checkpointNamespace,this.prevCheckpointConfig=Z.prevCheckpointConfig,this.interruptAfter=Z.interruptAfter,this.interruptBefore=Z.interruptBefore,this.durability=Z.durability,this.debug=Z.debug,this.triggerToNodes=Z.triggerToNodes}static async initialize(Z){let{config:$,stream:J}=Z;if(J!==void 0&&$.configurable?.[dZ]!==void 0)J=vV(J,$.configurable[dZ]);let Y=$.configurable?!("checkpoint_id"in $.configurable):!0,W=$.configurable?.[nQ];if($.configurable&&W){if(W.subgraphCounter>0)$=bQ($,{[rQ]:[$.configurable[rQ],W.subgraphCounter.toString()].join(P0)});W.subgraphCounter+=1}let X=b8 in($.configurable??{});if(!X&&$.configurable?.checkpoint_ns!==void 0&&$.configurable?.checkpoint_ns!=="")$=bQ($,{checkpoint_ns:"",checkpoint_id:void 0});let q=$;if($.configurable?.[MQ]!==void 0&&$.configurable?.[MQ]?.[$.configurable?.checkpoint_ns])q=bQ($,{checkpoint_id:$.configurable[MQ][$.configurable?.checkpoint_ns]});let G=$.configurable?.checkpoint_ns?.split(P0)??[],z=await Z.checkpointer?.getTuple(q)??{config:$,checkpoint:F1(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};q={...$,...z.config,configurable:{checkpoint_ns:"",...$.configurable,...z.config.configurable}};let K=z.parentConfig,U=V8(z.checkpoint),H={...z.metadata},B=z.pendingWrites??[],F=C6(Z.channelSpecs,U),w=(H.step??0)+1,A=w+($.recursionLimit??MV)+1,E={...U.channel_versions},P=Z.store?new W$(Z.store):void 0;if(P)await P.start();return new Q({input:Z.input,config:$,checkpointer:Z.checkpointer,checkpoint:U,checkpointMetadata:H,checkpointConfig:q,prevCheckpointConfig:K,checkpointNamespace:G,channels:F,isNested:X,manager:Z.manager,skipDoneTasks:Y,step:w,stop:A,checkpointPreviousVersions:E,checkpointPendingWrites:B,outputKeys:Z.outputKeys??[],streamKeys:Z.streamKeys??[],nodes:Z.nodes,stream:J,store:P,cache:Z.cache,interruptAfter:Z.interruptAfter,interruptBefore:Z.interruptBefore,durability:Z.durability,debug:Z.debug,triggerToNodes:Z.triggerToNodes})}_checkpointerPutAfterPrevious(Z){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>{return this.checkpointer?.put(Z.config,Z.checkpoint,Z.metadata,Z.newVersions)}),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(Z,$){let J=$;if(J.length===0)return;if(J.every(([G])=>(G in xJ)))J=Array.from(new Map(J.map((G)=>[G[0],G])).values());let Y=!1;for(let G in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,G)){if(this.channels[G].lc_graph_name==="UntrackedValue"){Y=!0;break}}let W=J;if(Y)W=J.filter(([G])=>{let z=this.channels[G];return!z||z.lc_graph_name!=="UntrackedValue"}).map(([G,z])=>{if(G===YQ&&o0(z))return[G,rz(z,this.channels)];return[G,z]});this.checkpointPendingWrites=this.checkpointPendingWrites.filter((G)=>G[0]!==Z);for(let[G,z]of W)this.checkpointPendingWrites.push([Z,G,z]);let X=bQ(this.checkpointConfig,{[rQ]:this.config.configurable?.checkpoint_ns??"",[GW]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null)this.checkpointerPromises.push(this.checkpointer.putWrites(X,W,Z));if(this.tasks)this._outputWrites(Z,J);if(!$.length||!this.cache||!this.tasks)return;let q=this.tasks[Z];if(q==null||q.cache_key==null)return;if($[0][0]===t0||$[0][0]===J0)return;this.cache.set([{key:[q.cache_key.ns,q.cache_key.key],value:q.writes,ttl:q.cache_key.ttl}])}_outputWrites(Z,$,J=!1){let Y=this.tasks[Z];if(Y!==void 0){if(Y.config!==void 0&&(Y.config.tags??[]).includes(K0))return;if($.length>0){if($[0][0]===J0){if(Y.path?.[0]===HQ&&Y.path?.[Y.path.length-1]===!0)return;let W=$.filter((X)=>X[0]===J0).flatMap((X)=>X[1]);this._emit([["updates",{[J0]:W}],["values",{[J0]:W}]])}else if($[0][0]!==t0)this._emit(A1(U6(dz(this.outputKeys,[[Y,$]],J),"updates")))}if(!J)this._emit(A1(U6(tz([[Y,$]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];let Z=[],$=([X,q])=>{return`ns:${X.join(",")}|key:${q}`},J=[],Y={};for(let X of Object.values(this.tasks))if(X.cache_key!=null&&!X.writes.length)J.push([X.cache_key.ns,X.cache_key.key]),Y[$([X.cache_key.ns,X.cache_key.key])]=X;if(J.length===0)return[];let W=await this.cache.get(J);for(let{key:X,value:q}of W){let G=Y[$(X)];if(G!=null)G.writes.push(...q),Z.push({task:G,result:q})}return Z}async tick(Z){if(this.store&&!this.store.isRunning)await this.store?.start();let{inputKeys:$=[]}=Z;if(this.status!=="pending")throw Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![nJ,T3].includes(this.input))await this._first($);else if(this.toInterrupt.length>0)throw this.status="interrupt_before",new f8;else if(Object.values(this.tasks).every((Y)=>Y.writes.length>0)){let Y=Object.values(this.tasks).flatMap((X)=>X.writes);this.updatedChannels=jQ(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);let W=await w8(U6(pJ(this.outputKeys,Y,this.channels),"values"));if(this._emit(W),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),H$(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new f8;if(this.config.configurable?.[X6]!==void 0)delete this.config.configurable?.[X6]}else return!1;if(this.step>this.stop)return this.status="out_of_steps",!1;if(this.tasks=f6(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}),this.checkpointer)this._emit(await w8(U6(az(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints")));if(Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(let[Y,W,X]of this.checkpointPendingWrites){if(W===t0||W===J0||W===JQ)continue;let q=Object.values(this.tasks).find((G)=>G.id===Y);if(q)q.writes.push([W,X])}for(let Y of Object.values(this.tasks))if(Y.writes.length>0)this._outputWrites(Y.id,Y.writes,!0)}if(Object.values(this.tasks).every((Y)=>Y.writes.length>0))return this.tick({inputKeys:$});if(H$(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new f8;let J=await w8(U6(E3(Object.values(this.tasks)),"tasks"));return this._emit(J),!0}async finishAndHandleError(Z){if(this.durability==="exit"&&(!this.isNested||typeof Z<"u"||this.checkpointNamespace.every((J)=>!J.includes(EQ))))this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites();let $=this._suppressInterrupt(Z);if($||Z===void 0)this.output=P8(this.channels,this.outputKeys);if($){if(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some((J)=>J.writes.length>0))this.updatedChannels=jQ(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(A1(U6(pJ(this.outputKeys,Object.values(this.tasks).flatMap((J)=>J.writes),this.channels),"values")));if(sQ(Z)&&!Z.interrupts.length)this._emit([["updates",{[J0]:[]}],["values",{[J0]:[]}]])}return $}async acceptPush(Z,$,J){if(this.interruptAfter?.length>0&&H$(this.checkpoint,this.interruptAfter,[Z])){this.toInterrupt.push(Z);return}let Y=lJ([HQ,Z.path??[],$,Z.id,J],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,Z.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!Y)return;if(this.interruptBefore?.length>0&&H$(this.checkpoint,this.interruptBefore,[Y])){this.toInterrupt.push(Y);return}if(this._emit(A1(U6(E3([Y]),"tasks"))),this.debug)iJ(this.step,[Y]);if(this.tasks[Y.id]=Y,this.skipDoneTasks)this._matchWrites({[Y.id]:Y});let W=await this._matchCachedWrites();for(let{task:X}of W)this._outputWrites(X.id,X.writes,!0);return Y}_suppressInterrupt(Z){return sQ(Z)&&!this.isNested}async _first(Z){let{configurable:$}=this.config,J=$?.[nQ];if(J&&J.nullResume!==void 0)this.putWrites(BQ,[[JQ,J.nullResume]]);if(z0(this.input)){let X=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume==="object"&&Object.keys(this.input.resume).every(fJ))this.config.configurable??={},this.config.configurable[p1]=this.input.resume;if(X&&this.checkpointer==null)throw Error("Cannot use Command(resume=...) without checkpointer");let q={};for(let[G,z,K]of mz(this.input,this.checkpointPendingWrites))q[G]??=[],q[G].push([z,K]);if(Object.keys(q).length===0)throw new iZ("Received empty Command input");for(let[G,z]of Object.entries(q))this.putWrites(G,z)}let Y=(this.checkpointPendingWrites??[]).filter((X)=>X[0]===BQ).map((X)=>X.slice(1));if(Y.length>0)jQ(this.checkpoint,this.channels,[{name:C8,writes:Y,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let W=z0(this.input)&&Y.length>0;if(this.isResuming||W){for(let q in this.channels){if(!Object.prototype.hasOwnProperty.call(this.channels,q))continue;if(this.checkpoint.channel_versions[q]!==void 0){let G=this.checkpoint.channel_versions[q];this.checkpoint.versions_seen[J0]={...this.checkpoint.versions_seen[J0],[q]:G}}}let X=await w8(U6(pJ(this.outputKeys,!0,this.channels),"values"));this._emit(X)}if(this.isResuming)this.input=T3;else if(W)await this._putCheckpoint({source:"input"}),this.input=nJ;else{let X=await w8(uJ(Z,this.input));if(X.length>0){let q=f6(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=jQ(this.checkpoint,this.channels,Object.values(q).concat([{name:C8,writes:X,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=nJ}else if(!(X6 in(this.config.configurable??{})))throw new iZ(`Received no input writes for ${JSON.stringify(Z,null,2)}`);else this.input=nJ}if(!this.isNested)this.config=bQ(this.config,{[X6]:this.isResuming})}_emit(Z){for(let[$,J]of Z){if(this.stream.modes.has($))this.stream.push([this.checkpointNamespace,$,J]);if(($==="checkpoints"||$==="tasks")&&this.stream.modes.has("debug")){let Y=$==="checkpoints"?this.step-1:this.step,W=new Date().toISOString(),X=(()=>{if($==="checkpoints")return"checkpoint";else if(typeof J==="object"&&J!=null&&"result"in J)return"task_result";else return"task"})();this.stream.push([this.checkpointNamespace,"debug",{step:Y,type:X,timestamp:W,payload:J}])}}}_putCheckpoint(Z){let $=this.checkpointMetadata===Z,J=this.checkpointer!=null&&(this.durability!=="exit"||$),Y=(W)=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=bQ(this.checkpointConfig,{[rQ]:this.config.configurable?.checkpoint_ns??""});let X={...this.checkpoint.channel_versions},q=WZ(this.checkpointPreviousVersions,X);this.checkpointPreviousVersions=X,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:V8(W),metadata:{...this.checkpointMetadata},newVersions:q}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};if(!$)this.checkpointMetadata={...Z,step:this.step,parents:this.config.configurable?.[MQ]??{}};if(this.checkpoint=F8(this.checkpoint,J?this.channels:void 0,this.step,$?{id:this.checkpoint.id}:void 0),J)Y(this.checkpoint);if(!$)this.step+=1}_flushPendingWrites(){if(this.checkpointer==null)return;if(this.checkpointPendingWrites.length===0)return;let Z=bQ(this.checkpointConfig,{[rQ]:this.config.configurable?.checkpoint_ns??"",[GW]:this.checkpoint.id}),$={};for(let[J,Y,W]of this.checkpointPendingWrites)$[J]??=[],$[J].push([Y,W]);for(let[J,Y]of Object.entries($))this.checkpointerPromises.push(this.checkpointer.putWrites(Z,Y,J))}_matchWrites(Z){for(let[$,J,Y]of this.checkpointPendingWrites){if(J===t0||J===J0||J===JQ)continue;let W=Object.values(Z).find((X)=>X.id===$);if(W)W.writes.push([J,Y])}for(let $ of Object.values(Z))if($.writes.length>0)this._outputWrites($.id,$.writes,!0)}};function CV(Q){return R0(Q?.message)}var XK=class extends J8{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(Q){super();this.streamFn=Q}_emit(Q,Z,$,J=!1){if(J&&Z.id!==void 0&&this.seen[Z.id]!==void 0)return;let Y=Z.id;if($!=null)if(LZ(Z))Y??=`run-${$}-tool-${Z.tool_call_id}`;else{if(Y==null||Y===`run-${$}`)Y=this.stableMessageIdMap[$]??Y??`run-${$}`;this.stableMessageIdMap[$]??=Y}if(Y!==Z.id)Z.id=Y,Z.lc_kwargs.id=Y;if(Z.id!=null)this.seen[Z.id]=Z;this.streamFn([Q[0],"messages",[Z,Q[1]]])}handleChatModelStart(Q,Z,$,J,Y,W,X,q){if(X&&(!W||!W.includes(C2)&&!W.includes("nostream")))this.metadatas[$]=[X.langgraph_checkpoint_ns.split("|"),{tags:W,name:q,...X}]}handleLLMNewToken(Q,Z,$,J,Y,W){let X=W?.chunk;if(this.emittedChatModelRunIds[$]=!0,this.metadatas[$]!==void 0)if(CV(X))this._emit(this.metadatas[$],X.message,$);else this._emit(this.metadatas[$],new y0({content:Q}),$)}handleLLMEnd(Q,Z){if(this.metadatas[Z]===void 0)return;if(!this.emittedChatModelRunIds[Z]){let $=Q.generations?.[0]?.[0];if(R0($?.message))this._emit(this.metadatas[Z],$?.message,Z,!0);delete this.emittedChatModelRunIds[Z]}delete this.metadatas[Z],delete this.stableMessageIdMap[Z]}handleLLMError(Q,Z){delete this.metadatas[Z]}handleChainStart(Q,Z,$,J,Y,W,X,q){if(W!==void 0&&q===W.langgraph_node&&(Y===void 0||!Y.includes(K0))){if(this.metadatas[$]=[W.langgraph_checkpoint_ns.split("|"),{tags:Y,name:q,...W}],typeof Z==="object"){for(let G of Object.values(Z))if((R0(G)||r8(G))&&G.id!==void 0)this.seen[G.id]=G;else if(Array.isArray(G)){for(let z of G)if((R0(z)||r8(z))&&z.id!==void 0)this.seen[z.id]=z}}}}handleChainEnd(Q,Z){let $=this.metadatas[Z];if(delete this.metadatas[Z],$!==void 0){if(R0(Q))this._emit($,Q,Z,!0);else if(Array.isArray(Q)){for(let J of Q)if(R0(J))this._emit($,J,Z,!0)}else if(Q!=null&&typeof Q==="object"){for(let J of Object.values(Q))if(R0(J))this._emit($,J,Z,!0);else if(Array.isArray(J)){for(let Y of J)if(R0(Y))this._emit($,Y,Z,!0)}}}}handleChainError(Q,Z){delete this.metadatas[Z]}};var bV=500,kV=2,fV=128000,hV=3,gV=[400,401,402,403,404,405,406,407,409],mV=(Q)=>{if(Q.message.startsWith("Cancel")||Q.message.startsWith("AbortError")||Q.name==="AbortError")return!1;if(Q.name==="GraphValueError")return!1;if(Q?.code==="ECONNABORTED")return!1;let Z=Q?.response?.status??Q?.status;if(Z&&gV.includes(+Z))return!1;if(Q?.error?.code==="insufficient_quota")return!1;return!0};async function S3(Q,Z,$,J){let Y=Q.retry_policy??Z,W=Y!==void 0?Y.initialInterval??bV:0,X=0,q,G,{config:z}=Q;if($)z=bQ(z,$);z={...z,signal:J};while(!0){if(J?.aborted)break;Q.writes.splice(0,Q.writes.length),q=void 0;try{G=await Q.proc.invoke(Q.input,z);break}catch(K){if(q=K,q.pregelTaskId=Q.id,qJ(q)){let B=z?.configurable?.checkpoint_ns,F=q.command;if(F.graph===B){for(let w of Q.writers)await w.invoke(F,z);q=void 0;break}else if(F.graph===B0.PARENT){let w=Tz(B);q.command=new B0({...q.command,graph:w})}}if(h8(q))break;if(Y===void 0)break;if(X+=1,X>=(Y.maxAttempts??hV))break;if(!(Y.retryOn??mV)(q))break;W=Math.min(Y.maxInterval??fV,W*(Y.backoffFactor??kV));let U=Y.jitter?Math.floor(W+Math.random()*1000):W;await new Promise((B)=>setTimeout(B,U));let H=q.name??q.constructor.unminifiable_name??q.constructor.name;if(Y?.logWarning??!0)console.log(`Retrying task "${String(Q.name)}" after ${W.toFixed(2)}ms (attempt ${X}) after ${H}: ${q}`);z=bQ(z,{[X6]:!0})}}return{task:Q,result:G,error:q,signalAborted:J?.aborted}}var x3=Symbol.for("promiseAdded");function dV(){let Q={next:()=>{return},wait:Promise.resolve(x3)};function Z($){Q.next=()=>{Q.wait=new Promise(Z),$(x3)}}return Q.wait=new Promise(Z),Q}var qK=class{nodeFinished;loop;constructor({loop:Q,nodeFinished:Z}){this.loop=Q,this.nodeFinished=Z}async tick(Q={}){let{timeout:Z,retryPolicy:$,onStepWrite:J,maxConcurrency:Y}=Q,W=new Set,X,q=new AbortController,G=q.signal,z=Z?AbortSignal.timeout(Z):void 0,K=Object.values(this.loop.tasks).filter((F)=>F.writes.length===0),{signals:U,disposeCombinedSignal:H}=this._initializeAbortSignals({exceptionSignal:G,stepTimeoutSignal:z,signal:Q.signal}),B=this._executeTasksWithRetry(K,{signals:U,retryPolicy:$,maxConcurrency:Y});for await(let{task:F,error:w,signalAborted:A}of B)if(this._commit(F,w),sQ(w))X=w;else if(h8(w)&&!sQ(X))X=w;else if(w&&(W.size===0||!A))q.abort(),W.add(w);if(H?.(),J?.(this.loop.step,Object.values(this.loop.tasks).map((F)=>F.writes).flat()),W.size===1)throw Array.from(W)[0];else if(W.size>1)throw AggregateError(Array.from(W),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(sQ(X))throw X;if(h8(X)&&this.loop.isNested)throw X}_initializeAbortSignals({exceptionSignal:Q,stepTimeoutSignal:Z,signal:$}){let J=this.loop.config.configurable?.[zW]??{},Y=J.externalAbortSignal??$,W=Z??J.timeoutAbortSignal,{signal:X,dispose:q}=XZ(Y,W,Q),G={externalAbortSignal:Y,timeoutAbortSignal:W,composedAbortSignal:X};return this.loop.config=bQ(this.loop.config,{[zW]:G}),{signals:G,disposeCombinedSignal:q}}async*_executeTasksWithRetry(Q,Z){let{retryPolicy:$,maxConcurrency:J,signals:Y}=Z??{},W=dV(),X={},q={executingTasksMap:X,barrier:W,retryPolicy:$,scheduleTask:async(H,B,F)=>this.loop.acceptPush(H,B,F)};if(Y?.composedAbortSignal?.aborted)throw Error("Abort");let G=0,z,K=XZ(Y?.externalAbortSignal,Y?.timeoutAbortSignal),U=K.signal?new Promise((H,B)=>{z=()=>B(Error("Abort")),K.signal?.addEventListener("abort",z,{once:!0})}):void 0;while((G===0||Object.keys(X).length>0)&&Q.length){for(;Object.values(X).length<(J??Q.length)&&G<Q.length;G+=1){let B=Q[G];X[B.id]=S3(B,$,{[QJ]:GK?.bind(q,this,B)},Y?.composedAbortSignal).catch((F)=>{return{task:B,error:F,signalAborted:Y?.composedAbortSignal?.aborted}})}let H=await Promise.race([...Object.values(X),...U?[U]:[],W.wait]);if(H===x3)continue;if(yield H,z!=null)K.signal?.removeEventListener("abort",z),K.dispose?.();delete X[H.task.id]}}_commit(Q,Z){if(Z!==void 0)if(sQ(Z)){if(Z.interrupts.length){let $=Z.interrupts.map((Y)=>[J0,Y]),J=Q.writes.filter((Y)=>Y[0]===JQ);if(J.length)$.push(...J);this.loop.putWrites(Q.id,$)}}else if(h8(Z)&&Q.writes.length)this.loop.putWrites(Q.id,Q.writes);else this.loop.putWrites(Q.id,[[t0,{message:Z.message,name:Z.name}]]);else{if(this.nodeFinished&&(Q.config?.tags==null||!Q.config.tags.includes(K0)))this.nodeFinished(String(Q.name));if(Q.writes.length===0)Q.writes.push([ZJ,null]);this.loop.putWrites(Q.id,Q.writes)}}};async function GK(Q,Z,$,J,Y,W={}){let X=Z.config?.configurable?.[nQ];if(!X)throw Error(`BUG: No scratchpad found on task ${Z.name}__${Z.id}`);let q=X.callCounter;X.callCounter+=1;let G=new cz({func:$,name:J,input:Y,cache:W.cache,retry:W.retry,callbacks:W.callbacks}),z=await this.scheduleTask(Z,q,G);if(!z)return;let K=this.executingTasksMap[z.id];if(K!==void 0)return K;if(z.writes.length>0){let U=z.writes.filter(([B])=>B===H8),H=z.writes.filter(([B])=>B===t0);if(U.length>0){if(U.length===1)return Promise.resolve(U[0][1]);throw Error(`BUG: multiple returns found for task ${z.name}__${z.id}`)}if(H.length>0){if(H.length===1){let B=H[0][1],F=B instanceof Error?B:Error(String(B));return Promise.reject(F)}throw Error(`BUG: multiple errors found for task ${z.name}__${z.id}`)}return}else{let U=S3(z,W.retry,{[QJ]:GK.bind(this,Q,z)});return this.executingTasksMap[z.id]=U,this.barrier.next(),U.then(({result:H,error:B})=>{if(B)return Promise.reject(B);return H})}}var H6=class extends Error{constructor(Q){super(Q);this.name="GraphValidationError"}};function zK({nodes:Q,channels:Z,inputChannels:$,outputChannels:J,streamChannels:Y,interruptAfterNodes:W,interruptBeforeNodes:X}){if(!Z)throw new H6("Channels not provided");let q=new Set,G=new Set;for(let[z,K]of Object.entries(Q)){if(z===J0)throw new H6(`"Node name ${J0} is reserved"`);if(K.constructor===A8)K.triggers.forEach((U)=>q.add(U));else throw new H6(`Invalid node type ${typeof K}, expected PregelNode`)}for(let z of q)if(!(z in Z))throw new H6(`Subscribed channel '${String(z)}' not in channels`);if(!Array.isArray($)){if(!q.has($))throw new H6(`Input channel ${String($)} is not subscribed to by any node`)}else if($.every((z)=>!q.has(z)))throw new H6(`None of the input channels ${$} are subscribed to by any node`);if(!Array.isArray(J))G.add(J);else J.forEach((z)=>G.add(z));if(Y&&!Array.isArray(Y))G.add(Y);else if(Array.isArray(Y))Y.forEach((z)=>G.add(z));for(let z of G)if(!(z in Z))throw new H6(`Output channel '${String(z)}' not in channels`);if(W&&W!=="*"){for(let z of W)if(!(z in Q))throw new H6(`Node ${String(z)} not in nodes`)}if(X&&X!=="*"){for(let z of X)if(!(z in Q))throw new H6(`Node ${String(z)} not in nodes`)}}function M3(Q,Z){if(Array.isArray(Q)){for(let $ of Q)if(!($ in Z))throw Error(`Key ${String($)} not found in channels`)}else if(!(Q in Z))throw Error(`Key ${String(Q)} not found in channels`)}var v3=class Q extends a0{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(Z){super();this.unique=Z?.unique??this.unique,this.accumulate=Z?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(Z){let $=new Q({unique:this.unique,accumulate:this.accumulate});if(typeof Z<"u")$.seen=new Set(Z[0]),$.values=Z[1];return $}update(Z){let $=!1;if(!this.accumulate)$=this.values.length>0,this.values=[];let J=Z.flat();if(J.length>0)if(this.unique){for(let Y of J)if(!this.seen.has(Y))$=!0,this.seen.add(Y),this.values.push(Y)}else $=!0,this.values.push(...J);return $}get(){if(this.values.length===0)throw new U0;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};var KK=class{static subscribeTo(Q,Z){let{key:$,tags:J}={key:void 0,tags:void 0,...Z??{}};if(Array.isArray(Q)&&$!==void 0)throw Error("Can't specify a key when subscribing to multiple channels");let Y;if(typeof Q==="string")if($)Y={[$]:Q};else Y=[Q];else Y=Object.fromEntries(Q.map((W)=>[W,W]));return new A8({channels:Y,triggers:Array.isArray(Q)?Q:[Q],tags:J})}static writeTo(Q,Z){let $=[];for(let J of Q)$.push({channel:J,value:CQ,skipNone:!1});for(let[J,Y]of Object.entries(Z??{}))if(c.isRunnable(Y)||typeof Y==="function")$.push({channel:J,value:CQ,skipNone:!0,mapper:v0(Y)});else $.push({channel:J,value:Y,skipNone:!1});return new f0($)}},uV=class extends c{lc_namespace=["langgraph","pregel"];invoke(Q,Z){throw Error("Not implemented")}withConfig(Q){return super.withConfig(Q)}stream(Q,Z){return super.stream(Q,Z)}},rJ=class extends uV{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(Q){super(Q);let{streamMode:Z}=Q;if(Z!=null&&!Array.isArray(Z))Z=[Z];if(this.nodes=Q.nodes,this.channels=Q.channels,YQ in this.channels&&"lc_graph_name"in this.channels[YQ]&&this.channels[YQ].lc_graph_name!=="Topic")throw Error(`Channel '${YQ}' is reserved and cannot be used in the graph.`);else this.channels[YQ]=new v3({accumulate:!1});if(this.autoValidate=Q.autoValidate??this.autoValidate,this.streamMode=Z??this.streamMode,this.inputChannels=Q.inputChannels,this.outputChannels=Q.outputChannels,this.streamChannels=Q.streamChannels??this.streamChannels,this.interruptAfter=Q.interruptAfter,this.interruptBefore=Q.interruptBefore,this.stepTimeout=Q.stepTimeout??this.stepTimeout,this.debug=Q.debug??this.debug,this.checkpointer=Q.checkpointer,this.retryPolicy=Q.retryPolicy,this.config=Q.config,this.store=Q.store,this.cache=Q.cache,this.name=Q.name,this.triggerToNodes=Q.triggerToNodes??this.triggerToNodes,this.userInterrupt=Q.userInterrupt,this.autoValidate)this.validate()}withConfig(Q){let Z=w0(this.config,Q);return new this.constructor({...this,config:Z})}validate(){zK({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(let[Q,Z]of Object.entries(this.nodes))for(let $ of Z.triggers)this.triggerToNodes[$]??=[],this.triggerToNodes[$].push(Q);return this}get streamChannelsList(){if(Array.isArray(this.streamChannels))return this.streamChannels;else if(this.streamChannels)return[this.streamChannels];else return Object.keys(this.channels)}get streamChannelsAsIs(){if(this.streamChannels)return this.streamChannels;else return Object.keys(this.channels)}async getGraphAsync(Q){return this.getGraph(Q)}*getSubgraphs(Q,Z){for(let[$,J]of Object.entries(this.nodes)){if(Q!==void 0){if(!Q.startsWith($))continue}let Y=J.subgraphs?.length?J.subgraphs:[J.bound];for(let W of Y){let X=dJ(W);if(X!==void 0){if($===Q){yield[$,X];return}if(Q===void 0)yield[$,X];if(Z){let q=Q;if(Q!==void 0)q=Q.slice($.length+1);for(let[G,z]of X.getSubgraphs(q,Z))yield[`${$}${P0}${G}`,z]}}}}}async*getSubgraphsAsync(Q,Z){yield*this.getSubgraphs(Q,Z)}async _prepareStateSnapshot({config:Q,saved:Z,subgraphCheckpointer:$,applyPendingWrites:J=!1}){if(Z===void 0)return{values:{},next:[],config:Q,tasks:[]};let Y=C6(this.channels,Z.checkpoint);if(Z.pendingWrites?.length){let U=Z.pendingWrites.filter(([H,B])=>H===BQ).map(([H,B,F])=>[String(B),F]);if(U.length>0)jQ(Z.checkpoint,Y,[{name:C8,writes:U,triggers:[]}],void 0,this.triggerToNodes)}let W=Object.values(f6(Z.checkpoint,Z.pendingWrites,this.nodes,Y,Z.config,!0,{step:(Z.metadata?.step??-1)+1,store:this.store})),X=await w8(this.getSubgraphsAsync()),q=Z.config.configurable?.checkpoint_ns??"",G={};for(let U of W){let H=X.find(([F])=>F===U.name);if(!H)continue;let B=`${String(U.name)}${EQ}${U.id}`;if(q)B=`${q}${P0}${B}`;if($===void 0){let F={configurable:{thread_id:Z.config.configurable?.thread_id,checkpoint_ns:B}};G[U.id]=F}else{let F={configurable:{[k0]:$,thread_id:Z.config.configurable?.thread_id,checkpoint_ns:B}},w=H[1];G[U.id]=await w.getState(F,{subgraphs:!0})}}if(J&&Z.pendingWrites?.length){let U=Object.fromEntries(W.map((B)=>[B.id,B]));for(let[B,F,w]of Z.pendingWrites){if([t0,J0,H1].includes(F))continue;if(!(B in U))continue;U[B].writes.push([String(F),w])}let H=W.filter((B)=>B.writes.length>0);if(H.length>0)jQ(Z.checkpoint,Y,H,void 0,this.triggerToNodes)}let z=Z?.metadata;if(z&&Z?.config?.configurable?.thread_id)z={...z,thread_id:Z.config.configurable.thread_id};let K=W.filter((U)=>U.writes.length===0).map((U)=>U.name);return{values:P8(Y,this.streamChannelsAsIs),next:K,tasks:j3(W,Z?.pendingWrites??[],G,this.streamChannelsAsIs),metadata:z,config:k6(Z.config,Z.metadata),createdAt:Z.checkpoint.ts,parentConfig:Z.parentConfig}}async getState(Q,Z){let $=Q.configurable?.[k0]??this.checkpointer;if(!$)throw new y6("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let J=Q.configurable?.checkpoint_ns??"";if(J!==""&&Q.configurable?.[k0]===void 0){let X=vJ(J);for await(let[q,G]of this.getSubgraphsAsync(X,!0))if(q===X)return await G.getState(P1(Q,{[k0]:$}),{subgraphs:Z?.subgraphs});throw Error(`Subgraph with namespace "${X}" not found.`)}let Y=w0(this.config,Q),W=await $.getTuple(Q);return await this._prepareStateSnapshot({config:Y,saved:W,subgraphCheckpointer:Z?.subgraphs?$:void 0,applyPendingWrites:!Q.configurable?.checkpoint_id})}async*getStateHistory(Q,Z){let $=Q.configurable?.[k0]??this.checkpointer;if(!$)throw new y6("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let J=Q.configurable?.checkpoint_ns??"";if(J!==""&&Q.configurable?.[k0]===void 0){let W=vJ(J);for await(let[X,q]of this.getSubgraphsAsync(W,!0))if(X===W){yield*q.getStateHistory(P1(Q,{[k0]:$}),Z);return}throw Error(`Subgraph with namespace "${W}" not found.`)}let Y=w0(this.config,Q,{configurable:{checkpoint_ns:J}});for await(let W of $.list(Y,Z))yield this._prepareStateSnapshot({config:W.config,saved:W})}async bulkUpdateState(Q,Z){let $=Q.configurable?.[k0]??this.checkpointer;if(!$)throw new y6("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(Z.length===0)throw Error("No supersteps provided");if(Z.some((X)=>X.updates.length===0))throw Error("No updates provided");let J=Q.configurable?.checkpoint_ns??"";if(J!==""&&Q.configurable?.[k0]===void 0){let X=vJ(J);for await(let[,q]of this.getSubgraphsAsync(X,!0))return await q.bulkUpdateState(P1(Q,{[k0]:$}),Z);throw Error(`Subgraph "${X}" not found`)}let Y=async(X,q)=>{let G=this.config?w0(this.config,X):X,z=await $.getTuple(G),K=z!==void 0?V8(z.checkpoint):F1(),U={...z?.checkpoint.channel_versions},H=z?.metadata?.step??-1,B=P1(G,{checkpoint_ns:G.configurable?.checkpoint_ns??""}),F=G.metadata??{};if(z?.config.configurable)B=P1(G,z.config.configurable),F={...z.metadata,...F};let{values:w,asNode:A}=q[0];if(w==null&&A===void 0){if(q.length>1)throw new Z0("Cannot create empty checkpoint with multiple updates");return k6(await $.put(B,F8(K,void 0,H),{source:"update",step:H+1,parents:z?.metadata?.parents??{}},{}),z?z.metadata:void 0)}let E=C6(this.channels,K);if(w===null&&A===m){if(q.length>1)throw new Z0("Cannot apply multiple updates when clearing state");if(z){let T=f6(K,z.pendingWrites||[],this.nodes,E,z.config,!0,{step:(z.metadata?.step??-1)+1,checkpointer:$,store:this.store}),V=(z.pendingWrites||[]).filter((v)=>v[0]===BQ).map((v)=>v.slice(1));if(V.length>0)jQ(K,E,[{name:C8,writes:V,triggers:[]}],$.getNextVersion.bind($),this.triggerToNodes);for(let[v,I,y]of z.pendingWrites||[]){if([t0,J0,H1].includes(I))continue;if(!(v in T))continue;T[v].writes.push([I,y])}jQ(K,E,Object.values(T),$.getNextVersion.bind($),this.triggerToNodes)}return k6(await $.put(B,F8(K,E,H),{...F,source:"update",step:H+1,parents:z?.metadata?.parents??{}},WZ(U,K.channel_versions)),z?z.metadata:void 0)}if(A===M2){if(q.length>1)throw new Z0("Cannot copy checkpoint with multiple updates");if(z==null)throw new Z0("Cannot copy a non-existent checkpoint");let T=(I)=>{if(!Array.isArray(I))return!1;if(I.length===0)return!1;return I.every((y)=>Array.isArray(y)&&y.length===2)},V=F8(K,void 0,H),v=await $.put(z.parentConfig??P1(z.config,{checkpoint_id:void 0}),V,{source:"fork",step:H+1,parents:z.metadata?.parents??{}},{});if(T(w)){let I=f6(V,z.pendingWrites,this.nodes,E,v,!1,{step:H+2}),y=Object.values(I).reduce((g,{name:a,id:aQ})=>{return g[a]??=[],g[a].push({id:aQ}),g},{}),l=w.reduce((g,a)=>{let[aQ,s]=a;g[s]??=[];let u6=g[s].length,BZ=y[s]?.[u6]?.id;return g[s].push({values:aQ,asNode:s,taskId:BZ}),g},{});return Y(k6(v,z.metadata),Object.values(l).flat())}return k6(v,z.metadata)}if(A===C8){if(q.length>1)throw new Z0("Cannot apply multiple updates when updating as input");let T=await w8(uJ(this.inputChannels,w));if(T.length===0)throw new Z0(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);jQ(K,E,[{name:C8,writes:T,triggers:[]}],$.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let V=z?.metadata?.step!=null?z.metadata.step+1:-1,v=await $.put(B,F8(K,E,V),{source:"input",step:V,parents:z?.metadata?.parents??{}},WZ(U,K.channel_versions));return await $.putWrites(v,T,q6(C8,K.id)),k6(v,z?z.metadata:void 0)}if(G.configurable?.checkpoint_id===void 0&&z?.pendingWrites!==void 0&&z.pendingWrites.length>0){let T=f6(K,z.pendingWrites,this.nodes,E,z.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(z.metadata?.step??-1)+1}),V=(z.pendingWrites??[]).filter((I)=>I[0]===BQ).map((I)=>I.slice(1));if(V.length>0)jQ(z.checkpoint,E,[{name:C8,writes:V,triggers:[]}],void 0,this.triggerToNodes);for(let[I,y,l]of z.pendingWrites){if([t0,J0,H1].includes(y)||T[I]===void 0)continue;T[I].writes.push([y,l])}let v=Object.values(T).filter((I)=>{return I.writes.length>0});if(v.length>0)jQ(K,E,v,void 0,this.triggerToNodes)}let P=Object.values(K.versions_seen).map((T)=>{return Object.values(T)}).flat().find((T)=>!!T),j=[];if(q.length===1){let{values:T,asNode:V,taskId:v}=q[0];if(V===void 0&&Object.keys(this.nodes).length===1)[V]=Object.keys(this.nodes);else if(V===void 0&&P===void 0){if(typeof this.inputChannels==="string"&&this.nodes[this.inputChannels]!==void 0)V=this.inputChannels}else if(V===void 0){let I=Object.entries(K.versions_seen).map(([y,l])=>{return Object.values(l).map((g)=>{return[g,y]})}).flat().filter(([y,l])=>l!==J0).sort(([y],[l])=>TJ(y,l));if(I){if(I.length===1)V=I[0][1];else if(I[I.length-1][0]!==I[I.length-2][0])V=I[I.length-1][1]}}if(V===void 0)throw new Z0('Ambiguous update, specify "asNode"');j.push({values:T,asNode:V,taskId:v})}else for(let{asNode:T,values:V,taskId:v}of q){if(T==null)throw new Z0('"asNode" is required when applying multiple updates');j.push({values:V,asNode:T,taskId:v})}let R=[];for(let{asNode:T,values:V,taskId:v}of j){if(this.nodes[T]===void 0)throw new Z0(`Node "${T.toString()}" does not exist`);let I=this.nodes[T].getWriters();if(!I.length)throw new Z0(`No writers found for node "${T.toString()}"`);R.push({name:T,input:V,proc:I.length>1?s0.from(I,{omitSequenceTags:!0}):I[0],writes:[],triggers:[J0],id:v??q6(J0,K.id),writers:[]})}for(let T of R)await T.proc.invoke(T.input,W0({...G,store:G?.store??this.store},{runName:G.runName??`${this.getName()}UpdateState`,configurable:{[U8]:(V)=>T.writes.push(...V),[b8]:(V,v=!1)=>U$(K,E,T,V,v)}}));for(let T of R){let V=T.writes.filter((v)=>v[0]!==HQ);if(z!==void 0&&V.length>0)await $.putWrites(B,V,T.id)}jQ(K,E,R,$.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let k=WZ(U,K.channel_versions),b=await $.put(B,F8(K,E,H+1),{source:"update",step:H+1,parents:z?.metadata?.parents??{}},k);for(let T of R){let V=T.writes.filter((v)=>v[0]===HQ);if(V.length>0)await $.putWrites(b,V,T.id)}return k6(b,z?z.metadata:void 0)},W=Q;for(let{updates:X}of Z)W=await Y(W,X);return W}async updateState(Q,Z,$){return this.bulkUpdateState(Q,[{updates:[{values:Z,asNode:$}]}])}_defaults(Q){let{debug:Z,streamMode:$,inputKeys:J,outputKeys:Y,interruptAfter:W,interruptBefore:X,...q}=Q,G=!0,z=Z!==void 0?Z:this.debug,K=Y;if(K===void 0)K=this.streamChannelsAsIs;else M3(K,this.channels);let U=J;if(U===void 0)U=this.inputChannels;else M3(U,this.channels);let H=X??this.interruptBefore??[],B=W??this.interruptAfter??[],F;if($!==void 0)F=Array.isArray($)?$:[$],G=typeof $==="string";else{if(Q.configurable?.[u1]!==void 0)F=["values"];else F=this.streamMode;G=!0}let w;if(this.checkpointer===!1)w=void 0;else if(Q!==void 0&&Q.configurable?.[k0]!==void 0)w=Q.configurable[k0];else if(this.checkpointer===!0)throw Error("checkpointer: true cannot be used for root graphs.");else w=this.checkpointer;let A=Q.store??this.store,E=Q.cache??this.cache;if(Q.durability!=null&&Q.checkpointDuring!=null)throw Error("Cannot use both `durability` and `checkpointDuring` at the same time.");let P=(()=>{if(Q.checkpointDuring==null)return;if(Q.checkpointDuring===!1)return"exit";return"async"})(),j=Q.durability??P??Q?.configurable?.[v2]??"async";return[z,F,U,K,q,H,B,w,A,G,E,j]}async stream(Q,Z){let $=new AbortController,J={recursionLimit:this.config?.recursionLimit,...Z,signal:XZ(Z?.signal,$.signal).signal},Y=await super.stream(Q,J);return new _3(Z?.encoding==="text/event-stream"?YK(Y):Y,$)}streamEvents(Q,Z,$){let J=new AbortController,Y={recursionLimit:this.config?.recursionLimit,...Z,callbacks:pz(this.config?.callbacks,Z?.callbacks),signal:XZ(Z?.signal,J.signal).signal};return new _3(super.streamEvents(Q,Y,$),J)}async _validateInput(Q){return Q}async _validateContext(Q){return Q}async*_streamIterator(Q,Z){let $="version"in(Z??{})?void 0:Z?.encoding??void 0,J=Z?.subgraphs,Y=z$(this.config,Z);if(Y.recursionLimit===void 0||Y.recursionLimit<1)throw Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&Y.configurable===void 0)throw Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');let W=await this._validateInput(Q),{runId:X,...q}=Y,[G,z,,K,U,H,B,F,w,A,E,P]=this._defaults(q);if(typeof U.context<"u")U.context=await this._validateContext(U.context);else U.configurable=await this._validateContext(U.configurable);let j=new oJ({modes:new Set(z)});if(this.checkpointer===!0){U.configurable??={};let I=U.configurable[rQ]??"";U.configurable[rQ]=I.split(P0).map((y)=>y.split(EQ)[0]).join(P0)}if(z.includes("messages")){let I=new XK((l)=>j.push(l)),{callbacks:y}=U;if(y===void 0)U.callbacks=[I];else if(Array.isArray(y))U.callbacks=y.concat(I);else{let l=y.copy();l.addHandler(I,!0),U.callbacks=l}}if(z.includes("tools")){let I=new JK((l)=>j.push(l)),{callbacks:y}=U;if(y===void 0)U.callbacks=[I];else if(Array.isArray(y))U.callbacks=y.concat(I);else{let l=y.copy();l.addHandler(I,!0),U.callbacks=l}}U.writer??=(I)=>{if(!z.includes("custom"))return;let y=V3()?.configurable?.[rQ]?.split(P0).slice(0,-1);j.push([y??[],"custom",I])},U.interrupt??=this.userInterrupt??hJ;let R=await(await QQ(U))?.handleChainStart(this.toJSON(),uz(Q,"input"),X,void 0,void 0,void 0,U?.runName??this.getName()),k=q$(this.channels),b,T,v=(async()=>{try{b=await WK.initialize({input:W,config:U,checkpointer:F,nodes:this.nodes,channelSpecs:k,outputKeys:K,streamKeys:this.streamChannelsAsIs,store:w,cache:E,stream:j,interruptAfter:B,interruptBefore:H,manager:R,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:P});let I=new qK({loop:b,nodeFinished:U.configurable?.[y2]});if(Z?.subgraphs)b.config.configurable={...b.config.configurable,[dZ]:b.stream};if(await this._runLoop({loop:b,runner:I,debug:G,config:U}),P==="sync")await Promise.all(b?.checkpointerPromises??[])}catch(I){T=I}finally{try{if(b)await b.store?.stop(),await b.cache?.stop();await Promise.all(b?.checkpointerPromises??[])}catch(I){T=T??I}if(T)j.error(T);else j.close()}})();try{for await(let I of j){if(I===void 0)throw Error("Data structure error.");let[y,l,g]=I;if(z.includes(l)){if($==="text/event-stream"){if(J)yield[y,l,g];else yield[null,l,g];continue}if(J&&!A)yield[y,l,g];else if(!A)yield[l,g];else if(J)yield[y,g];else yield g}}}catch(I){throw await R?.handleChainError(T),I}finally{await v}await R?.handleChainEnd(b?.output??{},X,void 0,void 0,void 0)}async invoke(Q,Z){let $=Z?.streamMode??"values",J={...Z,outputKeys:Z?.outputKeys??this.outputChannels,streamMode:$,encoding:void 0},Y=[],W=await this.stream(Q,J),X=[],q;for await(let G of W)if($==="values")if(c1(G))X.push(G[J0]);else q=G;else Y.push(G);if($==="values"){if(X.length>0){let G=X.flat(1);if(q==null)return{[J0]:G};if(typeof q==="object")return{...q,[J0]:G}}return q}return Y}async _runLoop(Q){let{loop:Z,runner:$,debug:J,config:Y}=Q,W;try{while(await Z.tick({inputKeys:this.inputChannels})){for(let{task:X}of await Z._matchCachedWrites())Z._outputWrites(X.id,X.writes,!0);if(J)ez(Z.checkpointMetadata.step,Z.channels,this.streamChannelsList);if(J)iJ(Z.step,Object.values(Z.tasks));await $.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(X,q)=>{if(J)QK(X,q,this.streamChannelsList)},maxConcurrency:Y.maxConcurrency,signal:Y.signal})}if(Z.status==="out_of_steps")throw new XJ([`Recursion limit of ${Y.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(X){if(W=X,!await Z.finishAndHandleError(W))throw X}finally{if(W===void 0)await Z.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}};var N8=class Q extends a0{lc_graph_name="EphemeralValue";guard;value=[];constructor(Z=!0){super();this.guard=Z}fromCheckpoint(Z){let $=new Q(this.guard);if(typeof Z<"u")$.value=[Z];return $}update(Z){if(Z.length===0){let $=this.value.length>0;return this.value=[],$}if(Z.length!==1&&this.guard)throw new Z0("EphemeralValue can only receive one value per step.");return this.value=[Z[Z.length-1]],!0}get(){if(this.value.length===0)throw new U0;return this.value[0]}checkpoint(){if(this.value.length===0)throw new U0;return this.value[0]}isAvailable(){return this.value.length!==0}};$8();var y3=class{path;ends;constructor(Q){if(c.isRunnable(Q.path))this.path=Q.path;else this.path=v0(Q.path);this.ends=Array.isArray(Q.pathMap)?Q.pathMap.reduce((Z,$)=>{return Z[$]=$,Z},{}):Q.pathMap}run(Q,Z){return f0.registerWriter(new VQ({name:"<branch_run>",trace:!1,func:async($,J)=>{try{return await this._route($,J,Q,Z)}catch(Y){if(Y.name===cZ.unminifiable_name)console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
260
+ NodeInterrupt should only be thrown inside a node, not in edge conditions.`);throw Y}}}))}async _route(Q,Z,$,J){let Y=await this.path.invoke(J?J(Z):Q,Z);if(!Array.isArray(Y))Y=[Y];let W;if(this.ends)W=Y.map((X)=>o0(X)?X:this.ends[X]);else W=Y;if(W.some((X)=>!X))throw Error("Branch condition returned unknown or null destination");if(W.filter(o0).some((X)=>X.node===m))throw new Z0("Cannot send a packet to the END node");return await $(W,Z)??Q}},V$=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(Q){if(this.compiled)console.warn(Q)}get allEdges(){return this.edges}addNode(...Q){function Z(J){return J.length>=1&&typeof J[0]!=="string"}let $=Z(Q)?Array.isArray(Q[0])?Q[0]:Object.entries(Q[0]):[[Q[0],Q[1],Q[2]]];if($.length===0)throw Error("No nodes provided in `addNode`");for(let[J,Y,W]of $){for(let q of[P0,EQ])if(J.includes(q))throw Error(`"${q}" 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."),J in this.nodes)throw Error(`Node \`${J}\` already present.`);if(J===m)throw Error(`Node \`${J}\` is reserved.`);let X=v0(Y);this.nodes[J]={runnable:X,metadata:W?.metadata,subgraphs:K$(X)?[X]:W?.subgraphs,ends:W?.ends}}return this}addEdge(Q,Z){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),Q===m)throw Error("END cannot be a start node");if(Z===Q0)throw Error("START cannot be an end node");if(Array.from(this.edges).some(([$])=>$===Q)&&!("channels"in this))throw Error(`Already found path for ${Q}. For multiple edges, use StateGraph.`);return this.edges.add([Q,Z]),this}addConditionalEdges(Q,Z,$){let J=typeof Q==="object"?Q:{source:Q,path:Z,pathMap:$};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!c.isRunnable(J.path))J.path=v0(J.path);let Y=J.path.getName()==="RunnableLambda"?"condition":J.path.getName();if(this.branches[J.source]&&this.branches[J.source][Y])throw Error(`Condition \`${Y}\` already present for node \`${Q}\``);return this.branches[J.source]??={},this.branches[J.source][Y]=new y3(J),this}setEntryPoint(Q){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(Q0,Q)}setFinishPoint(Q){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(Q,m)}compile({checkpointer:Q,interruptBefore:Z,interruptAfter:$,name:J}={}){this.validate([...Array.isArray(Z)?Z:[],...Array.isArray($)?$:[]]);let Y=new C3({builder:this,checkpointer:Q,interruptAfter:$,interruptBefore:Z,autoValidate:!1,nodes:{},channels:{[Q0]:new N8,[m]:new N8},inputChannels:Q0,outputChannels:m,streamChannels:[],streamMode:"values",name:J});for(let[W,X]of Object.entries(this.nodes))Y.attachNode(W,X);for(let[W,X]of this.edges)Y.attachEdge(W,X);for(let[W,X]of Object.entries(this.branches))for(let[q,G]of Object.entries(X))Y.attachBranch(W,q,G);return Y.validate()}validate(Q){let Z=new Set([...this.allEdges].map(([J,Y])=>J));for(let[J]of Object.entries(this.branches))Z.add(J);for(let J of Z)if(J!==Q0&&!(J in this.nodes))throw Error(`Found edge starting at unknown node \`${J}\``);let $=new Set([...this.allEdges].map(([J,Y])=>Y));for(let[J,Y]of Object.entries(this.branches))for(let W of Object.values(Y))if(W.ends!=null)for(let X of Object.values(W.ends))$.add(X);else{$.add(m);for(let X of Object.keys(this.nodes))if(X!==J)$.add(X)}for(let J of Object.values(this.nodes))for(let Y of J.ends??[])$.add(Y);for(let J of Object.keys(this.nodes))if(!$.has(J))throw new GJ([`Node \`${J}\` 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(`
261
+ `),{lc_error_code:"UNREACHABLE_NODE"});for(let J of $)if(J!==m&&!(J in this.nodes))throw Error(`Found edge ending at unknown node \`${J}\``);if(Q){for(let J of Q)if(!(J in this.nodes))throw Error(`Interrupt node \`${J}\` is not present`)}this.compiled=!0}},C3=class extends rJ{builder;constructor({builder:Q,...Z}){super(Z);this.builder=Q}attachNode(Q,Z){this.channels[Q]=new N8,this.nodes[Q]=new A8({channels:[],triggers:[],metadata:Z.metadata,subgraphs:Z.subgraphs,ends:Z.ends}).pipe(Z.runnable).pipe(new f0([{channel:Q,value:CQ}],[K0])),this.streamChannels.push(Q)}attachEdge(Q,Z){if(Z===m){if(Q===Q0)throw Error("Cannot have an edge from START to END");this.nodes[Q].writers.push(new f0([{channel:m,value:CQ}],[K0]))}else this.nodes[Z].triggers.push(Q),this.nodes[Z].channels.push(Q)}attachBranch(Q,Z,$){if(Q===Q0&&!this.nodes[Q0])this.nodes[Q0]=KK.subscribeTo(Q0,{tags:[K0]});this.nodes[Q].pipe($.run((Y)=>{return new f0(Y.map((W)=>{if(o0(W))return W;return{channel:W===m?m:`branch:${Q}:${Z}:${W}`,value:CQ}}),[K0])}));let J=$.ends?Object.values($.ends):Object.keys(this.nodes);for(let Y of J)if(Y!==m){let W=`branch:${Q}:${Z}:${Y}`;this.channels[W]=new N8,this.nodes[Y].triggers.push(W),this.nodes[Y].channels.push(W)}}async getGraphAsync(Q){let Z=Q?.xray,$=new G1,J={[Q0]:$.addNode({schema:p0.any()},Q0)},Y={},W={};if(Z)W=Object.fromEntries((await w8(this.getSubgraphsAsync())).filter((G)=>UK(G[1])));function X(G,z,K,U=!1){if(z===m&&Y[m]===void 0)Y[m]=$.addNode({schema:p0.any()},m);if(J[G]===void 0)return;if(Y[z]===void 0)throw Error(`End node ${z} not found!`);return $.addEdge(J[G],Y[z],K!==z?K:void 0,U)}for(let[G,z]of Object.entries(this.builder.nodes)){let K=FQ(G),U=z.runnable,H=z.metadata??{};if(this.interruptBefore?.includes(G)&&this.interruptAfter?.includes(G))H.__interrupt="before,after";else if(this.interruptBefore?.includes(G))H.__interrupt="before";else if(this.interruptAfter?.includes(G))H.__interrupt="after";if(Z){let B=typeof Z==="number"?Z-1:Z,F=W[G]!==void 0?await W[G].getGraphAsync({...Q,xray:B}):U.getGraph(Q);if(F.trimFirstNode(),F.trimLastNode(),Object.keys(F.nodes).length>1){let E=function(j){return j?j.lc_runnable:!1},P=function(j,R){if(j!==void 0&&!x6(j))return j;else if(E(R))try{let k=R.getName();return k=k.startsWith("Runnable")?k.slice(8):k,k}catch(k){return R.getName()}else return R.name??"UnknownSchema"},[w,A]=$.extend(F,K);if(w===void 0)throw Error(`Could not extend subgraph "${G}" due to missing entrypoint.`);if(A!==void 0)J[K]={name:P(A.id,A.data),...A};Y[K]={name:P(w.id,w.data),...w}}else{let w=$.addNode(U,K,H);J[K]=w,Y[K]=w}}else{let B=$.addNode(U,K,H);J[K]=B,Y[K]=B}}let q=[...this.builder.allEdges].sort(([G],[z])=>{if(G<z)return-1;else if(z>G)return 1;else return 0});for(let[G,z]of q)X(FQ(G),FQ(z));for(let[G,z]of Object.entries(this.builder.branches)){let K={...Object.fromEntries(Object.keys(this.builder.nodes).filter((U)=>U!==G).map((U)=>[FQ(U),FQ(U)])),[m]:m};for(let U of Object.values(z)){let H;if(U.ends!==void 0)H=U.ends;else H=K;for(let[B,F]of Object.entries(H))X(FQ(G),FQ(F),B,!0)}}for(let[G,z]of Object.entries(this.builder.nodes))if(z.ends!==void 0)for(let K of z.ends)X(FQ(G),FQ(K),void 0,!0);return $}getGraph(Q){let Z=Q?.xray,$=new G1,J={[Q0]:$.addNode({schema:p0.any()},Q0)},Y={},W={};if(Z)W=Object.fromEntries(A1(this.getSubgraphs()).filter((G)=>UK(G[1])));function X(G,z,K,U=!1){if(z===m&&Y[m]===void 0)Y[m]=$.addNode({schema:p0.any()},m);return $.addEdge(J[G],Y[z],K!==z?K:void 0,U)}for(let[G,z]of Object.entries(this.builder.nodes)){let K=FQ(G),U=z.runnable,H=z.metadata??{};if(this.interruptBefore?.includes(G)&&this.interruptAfter?.includes(G))H.__interrupt="before,after";else if(this.interruptBefore?.includes(G))H.__interrupt="before";else if(this.interruptAfter?.includes(G))H.__interrupt="after";if(Z){let B=typeof Z==="number"?Z-1:Z,F=W[G]!==void 0?W[G].getGraph({...Q,xray:B}):U.getGraph(Q);if(F.trimFirstNode(),F.trimLastNode(),Object.keys(F.nodes).length>1){let E=function(j){return j?j.lc_runnable:!1},P=function(j,R){if(j!==void 0&&!x6(j))return j;else if(E(R))try{let k=R.getName();return k=k.startsWith("Runnable")?k.slice(8):k,k}catch(k){return R.getName()}else return R.name??"UnknownSchema"},[w,A]=$.extend(F,K);if(w===void 0)throw Error(`Could not extend subgraph "${G}" due to missing entrypoint.`);if(A!==void 0)J[K]={name:P(A.id,A.data),...A};Y[K]={name:P(w.id,w.data),...w}}else{let w=$.addNode(U,K,H);J[K]=w,Y[K]=w}}else{let B=$.addNode(U,K,H);J[K]=B,Y[K]=B}}let q=[...this.builder.allEdges].sort(([G],[z])=>{if(G<z)return-1;else if(z>G)return 1;else return 0});for(let[G,z]of q)X(FQ(G),FQ(z));for(let[G,z]of Object.entries(this.builder.branches)){let K={...Object.fromEntries(Object.keys(this.builder.nodes).filter((U)=>U!==G).map((U)=>[FQ(U),FQ(U)])),[m]:m};for(let U of Object.values(z)){let H;if(U.ends!==void 0)H=U.ends;else H=K;for(let[B,F]of Object.entries(H))X(FQ(G),FQ(F),B,!0)}}return $}};function UK(Q){return typeof Q.attachNode==="function"&&typeof Q.attachEdge==="function"}function FQ(Q){if(Q==="subgraph")return`"${Q}"`;return Q}function p8(Q){return typeof Q==="object"&&Q!==null&&"~standard"in Q&&typeof Q["~standard"]==="object"&&Q["~standard"]!==null&&"validate"in Q["~standard"]}function HK(Q){return typeof Q==="object"&&Q!==null&&"~standard"in Q&&typeof Q["~standard"]==="object"&&Q["~standard"]!==null&&"jsonSchema"in Q["~standard"]}function c8(Q){if(HK(Q))try{return Q["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function l8(Q){if(Q==null)return;if(!p8(Q))return;try{let Z=Q["~standard"].validate(void 0);if(Z&&typeof Z==="object"&&!(("then"in Z)&&typeof Z.then==="function")){let $=Z;if(!$.issues){let J=$.value;return()=>J}}}catch{}}var b3=Symbol.for("langgraph.channel.missing"),F$=class Q extends a0{lc_graph_name="UntrackedValue";guard;_value=b3;initialValueFactory;constructor(Z){super();if(this.guard=Z?.guard??!0,this.initialValueFactory=Z?.initialValueFactory,this.initialValueFactory)this._value=this.initialValueFactory()}fromCheckpoint(Z){return new Q({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(Z){if(Z.length===0)return!1;if(Z.length!==1&&this.guard)throw new Z0("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this._value=Z[Z.length-1],!0}get(){if(this._value===b3)throw new U0;return this._value}checkpoint(){}isAvailable(){return this._value!==b3}};var k3=Symbol.for("langgraph.state.reduced_value"),n0=class{[k3]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(Q,Z){this.reducer=Z.reducer,this.jsonSchemaExtra=Z.jsonSchemaExtra,this.valueSchema=Q,this.inputSchema="inputSchema"in Z?Z.inputSchema:Q,this.jsonSchemaExtra=Z.jsonSchemaExtra}static isInstance(Q){return typeof Q==="object"&&Q!==null&&k3 in Q&&Q[k3]===!0}};var BK=Symbol.for("langgraph.state.untracked_value"),pQ=class{[BK]=!0;schema;guard;constructor(Q,Z){this.schema=Q,this.guard=Z?.guard??!0}static isInstance(Q){return typeof Q==="object"&&Q!==null&&BK in Q}};var h6=(Q,Z)=>Q.size===Z.size&&[...Q].every(($)=>Z.has($)),f3=class Q extends a0{lc_graph_name="NamedBarrierValue";names;seen;constructor(Z){super();this.names=Z,this.seen=new Set}fromCheckpoint(Z){let $=new Q(this.names);if(typeof Z<"u")$.seen=new Set(Z);return $}update(Z){let $=!1;for(let J of Z)if(this.names.has(J)){if(!this.seen.has(J))this.seen.add(J),$=!0}else throw new Z0(`Value ${JSON.stringify(J)} not in names ${JSON.stringify(this.names)}`);return $}get(){if(!h6(this.names,this.seen))throw new U0}checkpoint(){return[...this.seen]}consume(){if(this.seen&&this.names&&h6(this.seen,this.names))return this.seen=new Set,!0;return!1}isAvailable(){return!!this.names&&h6(this.names,this.seen)}},h3=class Q extends a0{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(Z){super();this.names=Z,this.seen=new Set,this.finished=!1}fromCheckpoint(Z){let $=new Q(this.names);if(typeof Z<"u"){let[J,Y]=Z;$.seen=new Set(J),$.finished=Y}return $}update(Z){let $=!1;for(let J of Z)if(this.names.has(J)&&!this.seen.has(J))this.seen.add(J),$=!0;else if(!this.names.has(J))throw new Z0(`Value ${JSON.stringify(J)} not in names ${JSON.stringify(this.names)}`);return $}get(){if(!this.finished||!h6(this.names,this.seen))throw new U0}checkpoint(){return[[...this.seen],this.finished]}consume(){if(this.finished&&this.seen&&this.names&&h6(this.seen,this.names))return this.seen=new Set,this.finished=!1,!0;return!1}finish(){if(!this.finished&&!!this.names&&h6(this.names,this.seen))return this.finished=!0,!0;return!1}isAvailable(){return this.finished&&!!this.names&&h6(this.names,this.seen)}};var g3=Symbol.for("langgraph.state.state_schema"),E0=class{[g3]=!0;constructor(Q){this.fields=Q}getChannels(){let Q={};for(let[Z,$]of Object.entries(this.fields))if(n0.isInstance($)){let J=l8($.valueSchema);Q[Z]=new m8($.reducer,J)}else if(pQ.isInstance($)){let J=$.schema?l8($.schema):void 0;Q[Z]=new F$({guard:$.guard,initialValueFactory:J})}else if(p8($))Q[Z]=new L8(l8($));else throw Error(`Invalid state field "${Z}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return Q}getJsonSchema(){let Q={},Z=[];for(let[$,J]of Object.entries(this.fields)){let Y;if(n0.isInstance(J)){if(Y=c8(J.valueSchema),J.jsonSchemaExtra)Y={...Y??{},...J.jsonSchemaExtra}}else if(pQ.isInstance(J))Y=J.schema?c8(J.schema):void 0;else if(p8(J))Y=c8(J);if(Y){Q[$]=Y;let W=!1;if(n0.isInstance(J))W=l8(J.valueSchema)!==void 0;else if(pQ.isInstance(J))W=J.schema?l8(J.schema)!==void 0:!1;else W=l8(J)!==void 0;if(!W)Z.push($)}}return{type:"object",properties:Q,required:Z.length>0?Z:void 0}}getInputJsonSchema(){let Q={};for(let[Z,$]of Object.entries(this.fields)){let J;if(n0.isInstance($))J=c8($.inputSchema);else if(pQ.isInstance($))J=$.schema?c8($.schema):void 0;else if(p8($))J=c8($);if(J)Q[Z]=J}return{type:"object",properties:Q}}getChannelKeys(){return Object.entries(this.fields).map(([Q])=>Q)}getAllKeys(){return Object.keys(this.fields)}async validateInput(Q){if(Q==null||typeof Q!=="object")return Q;let Z={};for(let[$,J]of Object.entries(Q)){let Y=this.fields[$];if(Y===void 0){Z[$]=J;continue}let W;if(n0.isInstance(Y))W=Y.inputSchema;else if(pQ.isInstance(Y))W=Y.schema;else if(p8(Y))W=Y;if(W){let X=await W["~standard"].validate(J);if(X.issues)throw Error(`Validation failed for field "${$}": ${JSON.stringify(X.issues)}`);Z[$]=X.value}else Z[$]=J}return Z}static isInstance(Q){return typeof Q==="object"&&Q!==null&&g3 in Q&&Q[g3]===!0}};$8();var L$="__remove_all__";function B6(Q,Z){let $=Array.isArray(Q)?Q:[Q],J=Array.isArray(Z)?Z:[Z],Y=$.map(KQ),W=J.map(KQ);for(let K of Y)if(K.id===null||K.id===void 0)K.id=Y8(),K.lc_kwargs.id=K.id;let X;for(let K=0;K<W.length;K+=1){let U=W[K];if(U.id===null||U.id===void 0)U.id=Y8(),U.lc_kwargs.id=U.id;if(gQ.isInstance(U)&&U.id===L$)X=K}if(X!=null)return W.slice(X+1);let q=[...Y],G=new Map(q.map((K,U)=>[K.id,U])),z=new Set;for(let K of W){let U=G.get(K.id);if(U!==void 0)if(gQ.isInstance(K))z.add(K.id);else z.delete(K.id),q[U]=K;else{if(gQ.isInstance(K))throw Error(`Attempting to delete a message with an ID that doesn't exist ('${K.id}')`);G.set(K.id,q.length),q.push(K)}}return q.filter((K)=>!z.has(K.id))}var pV=p0.custom().default(()=>[]),cV=p0.custom(),g6=new n0(pV,{inputSchema:cV,reducer:B6,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var VK="lg:",FK=class{_map=new Map;_extensionCache=new Map;get(Q){return this._map.get(Q)}extend(Q,Z){let $=this.get(Q);this._map.set(Q,Z($))}remove(Q){return this._map.delete(Q),this}has(Q){return this._map.has(Q)}getChannelsForSchema(Q){let Z={},$=e8(Q);for(let[J,Y]of Object.entries($)){let W=this.get(Y);if(W?.reducer)Z[J]=new m8(W.reducer.fn,W.default);else Z[J]=new L8(W?.default)}return Z}getExtendedChannelSchemas(Q,Z){if(Object.keys(Z).length===0)return Q;let $=Object.entries(Z).filter(([,W])=>W===!0).sort(([W],[X])=>W.localeCompare(X)).map(([W,X])=>`${W}:${X}`).join("|"),J=this._extensionCache.get($)??new Map;if(J.has(Q))return J.get(Q);let Y=Q;if(Z.withReducerSchema||Z.withJsonSchemaExtrasAsDescription){let W=Object.entries(e8(Q)).map(([X,q])=>{let G=this.get(q),z=Z.withReducerSchema?G?.reducer?.schema??q:q;if(Z.withJsonSchemaExtrasAsDescription&&G?.jsonSchemaExtra){let K=W8(z)??W8(q),U=JSON.stringify({...G.jsonSchemaExtra,description:K});z=z.describe(`${VK}${U}`)}return[X,z]});if(Y=D9(Q,Object.fromEntries(W)),x0(Y))Y._def.unknownKeys="strip"}if(Z.asPartial)Y=I6(Y);return J.set(Q,Y),this._extensionCache.set($,J),Y}},i8=new FK;function qZ(Q,Z){if(Z.reducer&&!Z.default){let $=T6(Q);if($!=null)Z.default=$}if(Z.reducer){let $=Object.assign(Q,{lg_reducer_schema:Z.reducer?.schema??Q});return i8.extend($,()=>Z),$}else return i8.extend(Q,()=>Z),Q}function O1(Q){if(Q==null)return!1;if(E0.isInstance(Q))return!0;if(_0(Q))return!0;if(typeof Q==="object"&&"lc_graph_name"in Q&&Q.lc_graph_name==="AnnotationRoot")return!0;if(typeof Q==="object"&&!Array.isArray(Q)&&Object.keys(Q).length>0&&Object.values(Q).every((Z)=>typeof Z==="function"||B3(Z)))return!0;return!1}function LK(Q){if(typeof Q!=="object"||Q==null)return!1;let Z=Q,$="state"in Z&&O1(Z.state),J="stateSchema"in Z&&O1(Z.stateSchema),Y="input"in Z&&O1(Z.input);if(!$&&!J&&!Y)return!1;if("input"in Z&&Z.input!=null&&!O1(Z.input))return!1;if("output"in Z&&Z.output!=null&&!O1(Z.output))return!1;return!0}var D6="__root__",sJ=Symbol.for("langgraph.state.partial"),GZ=class extends V${channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=i8;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(Q,Z){super();let $=this._normalizeToStateGraphInit(Q,Z),J=$.state??$.stateSchema??$.input;if(!J)throw new l1;let Y=this._getChannelsFromSchema(J);if(this._schemaDefinition=Y,E0.isInstance(J))this._schemaRuntimeDefinition=J;else if(_0(J))this._schemaRuntimeDefinition=J;if($.input)if(E0.isInstance($.input))this._inputRuntimeDefinition=$.input;else if(_0($.input))this._inputRuntimeDefinition=$.input;else this._inputRuntimeDefinition=sJ;else this._inputRuntimeDefinition=sJ;if($.output)if(E0.isInstance($.output))this._outputRuntimeDefinition=$.output;else if(_0($.output))this._outputRuntimeDefinition=$.output;else this._outputRuntimeDefinition=this._schemaRuntimeDefinition;else this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let W=$.input?this._getChannelsFromSchema($.input):Y,X=$.output?this._getChannelsFromSchema($.output):Y;if(this._inputDefinition=W,this._outputDefinition=X,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),$.context){if(_0($.context))this._configRuntimeSchema=$.context}this._interrupt=$.interrupt,this._writer=$.writer}_normalizeToStateGraphInit(Q,Z){if(LK(Q)){if(_0(Z)||G$.isInstance(Z))return{...Q,context:Z};let $=Z;return{...Q,input:Q.input??$?.input,output:Q.output??$?.output,context:Q.context??$?.context,interrupt:Q.interrupt??$?.interrupt,writer:Q.writer??$?.writer,nodes:Q.nodes??$?.nodes}}if(O1(Q)){if(_0(Z)||G$.isInstance(Z))return{state:Q,context:Z};let $=Z;return{state:Q,input:$?.input,output:$?.output,context:$?.context,interrupt:$?.interrupt,writer:$?.writer,nodes:$?.nodes}}if(iV(Q))return{state:lV(Q.channels)};throw new l1}_getChannelsFromSchema(Q){if(E0.isInstance(Q))return Q.getChannels();if(_0(Q))return this._metaRegistry.getChannelsForSchema(Q);if(typeof Q==="object"&&"lc_graph_name"in Q&&Q.lc_graph_name==="AnnotationRoot")return Q.spec;if(typeof Q==="object"&&!Array.isArray(Q)&&Object.keys(Q).length>0)return Q;throw new l1("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([Q,Z])=>Q.map(($)=>[$,Z]))])}_addSchema(Q){if(this._schemaDefinitions.has(Q))return;this._schemaDefinitions.set(Q,Q);for(let[Z,$]of Object.entries(Q)){let J;if(typeof $==="function")J=$();else J=$;if(this.channels[Z]!==void 0){if(!this.channels[Z].equals(J)){if(J.lc_graph_name!=="LastValue")throw Error(`Channel "${Z}" already exists with a different type.`)}}else this.channels[Z]=J}}addNode(...Q){function Z(J){return J.length>=1&&typeof J[0]!=="string"}let $=Z(Q)?Array.isArray(Q[0])?Q[0]:Object.entries(Q[0]).map(([J,Y])=>[J,Y]):[[Q[0],Q[1],Q[2]]];if($.length===0)throw Error("No nodes provided in `addNode`");for(let[J,Y,W]of $){if(J in this.channels)throw Error(`${J} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let K of[P0,EQ])if(J.includes(K))throw Error(`"${K}" 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."),J in this.nodes)throw Error(`Node \`${J}\` already present.`);if(J===m||J===Q0)throw Error(`Node \`${J}\` is reserved.`);let X=this._schemaDefinition;if(W?.input!==void 0)X=this._getChannelsFromSchema(W.input);this._addSchema(X);let q;if(c.isRunnable(Y))q=Y;else if(typeof Y==="function")q=new VQ({func:Y,name:J,trace:!1});else q=v0(Y);let G=W?.cachePolicy;if(typeof G==="boolean")G=G?{}:void 0;let z={runnable:q,retryPolicy:W?.retryPolicy,cachePolicy:G,metadata:W?.metadata,input:X??this._schemaDefinition,subgraphs:K$(q)?[q]:W?.subgraphs,ends:W?.ends,defer:W?.defer};this.nodes[J]=z}return this}addEdge(Q,Z){if(typeof Q==="string")return super.addEdge(Q,Z);if(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(let $ of Q){if($===m)throw Error("END cannot be a start node");if(!Object.keys(this.nodes).some((J)=>J===$))throw Error(`Need to add a node named "${$}" first`)}if(Z===m)throw Error("END cannot be an end node");if(!Object.keys(this.nodes).some(($)=>$===Z))throw Error(`Need to add a node named "${Z}" first`);return this.waitingEdges.add([Q,Z]),this}addSequence(Q){let Z=Array.isArray(Q)?Q:Object.entries(Q);if(Z.length===0)throw Error("Sequence requires at least one node.");let $;for(let[J,Y,W]of Z){if(J in this.nodes)throw Error(`Node names must be unique: node with the name "${J}" already exists.`);let X=J;if(this.addNode(X,Y,W),$!=null)this.addEdge($,X);$=X}return this}compile({checkpointer:Q,store:Z,cache:$,interruptBefore:J,interruptAfter:Y,name:W,description:X}={}){this.validate([...Array.isArray(J)?J:[],...Array.isArray(Y)?Y:[]]);let q=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),G=q.length===1&&q[0]===D6?D6:q,z=Object.keys(this.channels),K=z.length===1&&z[0]===D6?D6:z,U=this._interrupt,H=new tJ({builder:this,checkpointer:Q,interruptAfter:Y,interruptBefore:J,autoValidate:!1,nodes:{},channels:{...this.channels,[Q0]:new N8},inputChannels:Q0,outputChannels:G,streamChannels:K,streamMode:"updates",store:Z,cache:$,name:W,description:X,userInterrupt:U});H.attachNode(Q0);for(let[B,F]of Object.entries(this.nodes))H.attachNode(B,F);H.attachBranch(Q0,KW,wK(),{withReader:!1});for(let[B]of Object.entries(this.nodes))H.attachBranch(B,KW,wK(),{withReader:!1});for(let[B,F]of this.edges)H.attachEdge(B,F);for(let[B,F]of this.waitingEdges)H.attachEdge(B,F);for(let[B,F]of Object.entries(this.branches))for(let[w,A]of Object.entries(F))H.attachBranch(B,w,A);return H.validate()}};function lV(Q){let Z={};for(let[$,J]of Object.entries(Q))if($===D6)Z[$]=MJ(J);else Z[$]=MJ(J);return Z}var tJ=class extends C3{description;_metaRegistry=i8;constructor({description:Q,...Z}){super(Z);this.description=Q}attachNode(Q,Z){let $;if(Q===Q0)$=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([q])=>q);else $=Object.keys(this.builder.channels);function J(q){if(z0(q)){if(q.graph===B0.PARENT)return null;return q._updateAsTuples()}else if(Array.isArray(q)&&q.length>0&&q.some((G)=>z0(G))){let G=[];for(let z of q)if(z0(z)){if(z.graph===B0.PARENT)continue;G.push(...z._updateAsTuples())}else G.push([D6,z]);return G}else if(q!=null)return[[D6,q]];return null}let Y=Q;function W(q){if(!q)return null;else if(z0(q)){if(q.graph===B0.PARENT)return null;return q._updateAsTuples().filter(([G])=>$.includes(G))}else if(Array.isArray(q)&&q.length>0&&q.some(z0)){let G=[];for(let z of q)if(z0(z)){if(z.graph===B0.PARENT)continue;G.push(...z._updateAsTuples().filter(([K])=>$.includes(K)))}else{let K=W(z);if(K)G.push(...K??[])}return G}else if(typeof q==="object"&&!Array.isArray(q))return Object.entries(q).filter(([G])=>$.includes(G));else{let G=Array.isArray(q)?"array":typeof q;throw new Z0(`Expected node "${Y.toString()}" to return an object or an array containing at least one Command object, received ${G}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}let X=[{value:CQ,mapper:new VQ({func:$.length&&$[0]===D6?J:W,trace:!1,recurse:!1})}];if(Q===Q0)this.nodes[Q]=new A8({tags:[K0],triggers:[Q0],channels:[Q0],writers:[new f0(X,[K0])]});else{let q=Z?.input??this.builder._schemaDefinition,G=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(q)).map((U)=>[U,U])),z=Object.keys(G).length===1&&D6 in G,K=`branch:to:${Q}`;this.channels[K]=Z?.defer?new D3:new N8(!1),this.nodes[Q]=new A8({triggers:[K],channels:z?Object.keys(G):G,writers:[new f0(X,[K0])],mapper:z?void 0:(U)=>{return Object.fromEntries(Object.entries(U).filter(([H])=>(H in G)))},bound:Z?.runnable,metadata:Z?.metadata,retryPolicy:Z?.retryPolicy,cachePolicy:Z?.cachePolicy,subgraphs:Z?.subgraphs,ends:Z?.ends})}}attachEdge(Q,Z){if(Z===m)return;if(typeof Q==="string")this.nodes[Q].writers.push(new f0([{channel:`branch:to:${Z}`,value:null}],[K0]));else if(Array.isArray(Q)){let $=`join:${Q.join("+")}:${Z}`;this.channels[$]=this.builder.nodes[Z].defer?new h3(new Set(Q)):new f3(new Set(Q)),this.nodes[Z].triggers.push($);for(let J of Q)this.nodes[J].writers.push(new f0([{channel:$,value:J}],[K0]))}}attachBranch(Q,Z,$,J={withReader:!0}){let Y=async(W,X)=>{let q=W.filter((z)=>z!==m);if(!q.length)return;let G=q.map((z)=>{if(o0(z))return z;return{channel:z===m?z:`branch:to:${z}`,value:Q}});await f0.doWrite({...X,tags:(X.tags??[]).concat([K0])},G)};this.nodes[Q].writers.push($.run(Y,J.withReader?(W)=>gz.doRead(W,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(Q){if(Q==null)return Q;let Z=this.builder._inputRuntimeDefinition,$=this.builder._schemaRuntimeDefinition;if(E0.isInstance(Z)){if(z0(Q)){let Y=Q;if(Q.update)Y.update=await Z.validateInput(Array.isArray(Q.update)?Object.fromEntries(Q.update):Q.update);return Y}return await Z.validateInput(Q)}if(Z===sJ&&E0.isInstance($)){if(z0(Q)){let Y=Q;if(Q.update)Y.update=await $.validateInput(Array.isArray(Q.update)?Object.fromEntries(Q.update):Q.update);return Y}return await $.validateInput(Q)}let J=(()=>{let Y=(W)=>{if(W==null)return;return this._metaRegistry.getExtendedChannelSchemas(W,{withReducerSchema:!0})};if(_0(Z))return Y(Z);if(Z===sJ){if(_0($))return I6(Y($));return}})();if(z0(Q)){let Y=Q;if(Q.update&&J!=null)Y.update=xQ(J,Q.update);return Y}if(J!=null)return xQ(J,Q);return Q}isInterrupted(Q){return c1(Q)}async _validateContext(Q){let Z=this.builder._configRuntimeSchema;if(_0(Z))xQ(Z,Q);return Q}};function iV(Q){return typeof Q==="object"&&Q!==null&&Q.channels!==void 0}function oV(Q){if(o0(Q))return[Q];let Z=[];if(z0(Q))Z.push(Q);else if(Array.isArray(Q))Z.push(...Q.filter(z0));let $=[];for(let J of Z){if(J.graph===B0.PARENT)throw new lZ(J);if(o0(J.goto))$.push(J.goto);else if(typeof J.goto==="string")$.push(J.goto);else if(Array.isArray(J.goto))$.push(...J.goto)}return $}function wK(){return new y3({path:new VQ({func:oV,tags:[K0],trace:!1,recurse:!1,name:"<control_branch>"})})}var m3=function(Z,$){let{name:J,checkpointer:Y,store:W,cache:X}=typeof Z==="string"?{name:Z,checkpointer:void 0,store:void 0}:Z;if(fz($)||hz($))throw Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");let q="updates",G=oz(J,$);function z(B){return typeof B==="object"&&B!==null&&"__lg_type"in B&&B.__lg_type==="__pregel_final"}let K=new VQ({name:"pluckReturnValue",func:(B)=>{return z(B)?B.value:B}}),U=new VQ({name:"pluckSaveValue",func:(B)=>{return z(B)?B.save:B}}),H=new A8({bound:G,triggers:[Q0],channels:[Q0],writers:[new f0([{channel:m,value:CQ,mapper:K},{channel:U1,value:CQ,mapper:U}],[K0])]});return new rJ({name:J,checkpointer:Y,nodes:{[J]:H},channels:{[Q0]:new N8,[m]:new L8,[U1]:new L8},inputChannels:Q0,outputChannels:m,streamChannels:m,streamMode:q,store:W,cache:X})};m3.final=function({value:Z,save:$}){return{value:Z,save:$,__lg_type:"__pregel_final"}};var AK=L1.Root({messages:L1({reducer:B6,default:()=>[]})}),d3={reducer:{fn:B6},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},PK=O.object({messages:qZ(O.custom(),d3)});S2();var w$=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.")}},A$=class extends Error{toolNames;constructor(Q){super(`The model has called multiple tools: ${Q.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`);this.toolNames=Q}},aJ=class extends Error{toolName;errors;constructor(Q,Z){super(`Failed to parse structured output for tool '${Q}':${Z.map(($)=>`
262
+ - ${$}`).join("")}.`);this.toolName=Q,this.errors=Z}},P$=class extends Error{toolCall;toolError;constructor(Q,Z){let $=Q instanceof Error?Q:Error(String(Q)),J=JSON.stringify(Z.args);super(`Error invoking tool '${Z.name}' with kwargs ${J} with error: ${$.stack}
263
+ Please fix the error and try again.`);this.toolCall=Z,this.toolError=$}},zZ=class Q extends Error{static "~brand"="MiddlewareError";constructor(Z,$){let J=Z instanceof Error?Z.message:String(Z);super(J);if(this.name=Z instanceof Error?Z.name:`${$[0].toUpperCase()+$.slice(1)}Error`,Z instanceof Error)this.cause=Z}static wrap(Z,$){if(h8(Z))return Z;return new Q(Z,$)}static isInstance(Z){return Z instanceof Error&&"~brand"in Z&&Z["~brand"]==="MiddlewareError"}};function N$(Q){return"invoke"in Q&&typeof Q.invoke==="function"&&"_streamResponseChunks"in Q}function KZ(Q){return typeof Q==="object"&&Q!=null&&"_queuedMethodOperations"in Q&&"_getModelInstance"in Q&&typeof Q._getModelInstance==="function"}var OK=!0,QF=0,tQ=class Q{constructor(Z,$,J){this.schema=Z,this.tool=$,this.options=J}get name(){return this.tool.function.name}static fromSchema(Z,$){function J(W){return W??`extract-${++QF}`}if(iQ(Z)||ZQ(Z)){let W=M0(Z);return new Q(W,{type:"function",function:{name:J(W.title),strict:!1,description:W.description??"Tool for extracting structured output from the model's response.",parameters:W}},$)}let Y;if(typeof Z.name==="string"&&typeof Z.parameters==="object"&&Z.parameters!=null)Y=Z;else Y={name:J(Z.title),description:Z.description??"",parameters:Z.schema||Z};return new Q(M0(Z),{type:"function",function:Y},$)}parse(Z){let $=new xZ(this.schema).validate(Z);if(!$.valid)throw new aJ(this.name,$.errors.map((J)=>J.error));return Z}},V6=class Q{_schemaType;schema;strict;constructor(Z,$){if("schema"in Z&&typeof Z.schema==="object"&&Z.schema!==null&&!("type"in Z)){let J=Z;this.schema=J.schema,this.strict=J.strict??OK}else this.schema=Z,this.strict=$??OK}static fromSchema(Z,$){return new Q(M0(Z),$)}parse(Z){let $;if(typeof Z.content==="string")$=Z.content;else if(Array.isArray(Z.content)){for(let J of Z.content)if(typeof J==="object"&&J!==null&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string"){$=J.text;break}}if(!$||$==="")return;try{let J=JSON.parse($);if(!new xZ(this.schema).validate(J).valid)return;return J}catch{}}};function jK(Q,Z,$){if(!Q)return[];if(typeof Q==="object"&&Q!==null&&"__responseFormatUndefined"in Q)return[];if(Array.isArray(Q)){if(Q.every((Y)=>Y instanceof tQ||Y instanceof V6))return Q;if(Q.every((Y)=>iQ(Y)))return Q.map((Y)=>tQ.fromSchema(Y,Z));if(Q.every((Y)=>_0(Y)))return Q.map((Y)=>tQ.fromSchema(Y,Z));if(Q.every((Y)=>typeof Y==="object"&&Y!==null&&!_0(Y)&&!iQ(Y)))return Q.map((Y)=>tQ.fromSchema(Y,Z));throw Error(`Invalid response format: list contains mixed types.
264
+ All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`)}if(Q instanceof tQ||Q instanceof V6)return[Q];let J=RK($);if(iQ(Q))return J?[V6.fromSchema(Q)]:[tQ.fromSchema(Q,Z)];if(_0(Q))return J?[V6.fromSchema(Q)]:[tQ.fromSchema(Q,Z)];if(typeof Q==="object"&&Q!==null&&"properties"in Q)return J?[V6.fromSchema(Q)]:[tQ.fromSchema(Q,Z)];throw Error(`Invalid response format: ${String(Q)}`)}var ZF=["ChatOpenAI","ChatXAI"],EK=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function RK(Q){if(!Q)return!1;if(typeof Q==="string"){let $=Q.split(":").pop();return EK.some((J)=>$.includes(J))}if(KZ(Q))return RK(Q._defaultConfig.model);if(!N$(Q))return!1;let Z=Q.getName();if(Z==="FakeToolCallingChatModel")return!0;if(ZF.includes(Z)&&(("model"in Q)&&EK.some(($)=>typeof Q.model==="string"&&Q.model.includes($))||Z==="FakeToolCallingModel"&&("structuredResponse"in Q)))return!0;return!1}function o8(Q){if(!Q||typeof Q==="function")return;return Q.canJumpTo}function m6(Q){if(typeof Q==="function")return Q;return Q.hook}var u3=Symbol.for("langgraph-zod");if(!(u3 in globalThis))globalThis[u3]=new WeakSet;function IK(Q){let Z=globalThis[u3];if(Z.has(Q))return;Object.defineProperty(Q,"langgraph",{get(){let $=this;return{metadata(J){return qZ($,{jsonSchemaExtra:J})},reducer(J,Y){return qZ($,{default:T6($),reducer:{schema:Y,fn:J}})}}}}),Z.add(Q)}try{IK(O.ZodType.prototype),IK(p0.ZodType.prototype)}catch(Q){throw 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:Q})}var SK=class extends TK{constructor(Q){super();this.parent=Q,this._map=this.parent._map}add(Q,...Z){let $=Z[0];if($&&!$?.default){let J=T6(Q);if(J!=null)$.default=J}return super.add(Q,...Z)}},$F=new SK(i8);function xK(Q=!0,Z,$=[]){let J={jumpTo:new pQ},Y={},W={},X=(q)=>{if(E0.isInstance(q)){for(let[z,K]of Object.entries(q.fields))if(!(z in J)){if(J[z]=K,z.startsWith("_"))continue;if(n0.isInstance(K))Y[z]=K.inputSchema||K.valueSchema,W[z]=K.valueSchema;else Y[z]=K,W[z]=K}return}let G=e8(q);for(let[z,K]of Object.entries(G)){let U=z.startsWith("_");if(!(z in J)){if(H0(K)){let H=i8.get(K);if(H?.reducer){if(H.reducer.schema){if(J[z]=new n0(K,{inputSchema:H.reducer.schema,reducer:H.reducer.fn}),!U)Y[z]=H.reducer.schema,W[z]=K}else if(J[z]=new n0(K,{reducer:H.reducer.fn}),!U)Y[z]=K,W[z]=K;continue}}if(J[z]=K,!U)Y[z]=K,W[z]=K}}};if(Z&&(E0.isInstance(Z)||_0(Z)))X(Z);for(let q of $)if(q.stateSchema&&(E0.isInstance(q.stateSchema)||_0(q.stateSchema)))X(q.stateSchema);if(Q)W.structuredResponse=new pQ;return{state:new E0({messages:g6,...J}),input:new E0({messages:g6,...Y}),output:new E0({messages:g6,...W})}}var p3=/<name>(.*?)<\/name>/s,c3=/<content>(.*?)<\/content>/s;function JF(Q,Z){if(E0.isInstance(Q)){let $={};for(let J of Object.keys(Q.fields))if(J in Z)$[J]=Z[J];return $}if(ZQ(Q))return xQ(Q,Z);throw Error(`Invalid state schema type: ${typeof Q}`)}function vK(Q){if(!h.isInstance(Q)||y0.isInstance(Q))return Q;if(!Q.name)return Q;let{name:Z}=Q;if(typeof Q.content==="string")return new h({...Q.lc_kwargs,content:`<name>${Z}</name><content>${Q.content}</content>`,name:void 0});let $=[],J=0;for(let Y of Q.content)if(typeof Y==="string")J+=1,$.push(`<name>${Z}</name><content>${Y}</content>`);else if(typeof Y==="object"&&"type"in Y&&Y.type==="text")J+=1,$.push({...Y,text:`<name>${Z}</name><content>${Y.text}</content>`});else $.push(Y);if(!J)$.unshift({type:"text",text:`<name>${Z}</name><content></content>`});return new h({...Q.lc_kwargs,content:$,name:void 0})}function yK(Q){if(!h.isInstance(Q)||!Q.content)return Q;let Z=[],$;if(Array.isArray(Q.content))Z=Q.content.filter((J)=>{if(J.type==="text"&&typeof J.text==="string"){let Y=J.text.match(p3),W=J.text.match(c3);if(Y&&(!W||W[1]===""))return $=Y[1],!1;return!0}return!0}).map((J)=>{if(J.type==="text"&&typeof J.text==="string"){let Y=J.text.match(p3),W=J.text.match(c3);if(!Y||!W)return J;return $=Y[1],{...J,text:W[1]}}return J});else{let J=Q.content,Y=J.match(p3),W=J.match(c3);if(!Y||!W)return Q;$=Y[1],Z=W[1]}return new h({...Object.keys(Q.lc_kwargs??{}).length>0?Q.lc_kwargs:Q,content:Z,name:$})}function UZ(Q){return c.isRunnable(Q)}function MK(Q){if(!N$(Q))return!1;return"bindTools"in Q&&typeof Q.bindTools==="function"}var l3=(Q,Z,$={})=>{if(MK(Q))return Q.bindTools(Z,$);if(b0.isRunnableBinding(Q)&&MK(Q.bound)){let J=Q.bound.bindTools(Z,$);if(b0.isRunnableBinding(J))return new b0({bound:J.bound,config:{...Q.config,...J.config},kwargs:{...Q.kwargs,...J.kwargs},configFactories:J.configFactories??Q.configFactories});return new b0({bound:J,config:Q.config,kwargs:Q.kwargs,configFactories:Q.configFactories})}return null};function eJ(Q){if(typeof Q==="function")return;let Z=Q;if(s0.isRunnableSequence(Z))Z=Z.steps.find(($)=>b0.isRunnableBinding($))||Z;if(KZ(Z))return;if(b0.isRunnableBinding(Z)){let $=Z.kwargs!=null&&typeof Z.kwargs==="object"&&"tools"in Z.kwargs&&Array.isArray(Z.kwargs.tools)&&Z.kwargs.tools.length>0,J=Z.config!=null&&typeof Z.config==="object"&&"tools"in Z.config&&Array.isArray(Z.config.tools)&&Z.config.tools.length>0;if($||J)throw new w$}if("tools"in Z&&Z.tools!==void 0&&Array.isArray(Z.tools)&&Z.tools.length>0)throw new w$}function i3(Q){return Boolean(h.isInstance(Q)&&Q.tool_calls&&Q.tool_calls.length>0)}function CK(Q){if(Q==null)return new L0("");if(L0.isInstance(Q))return Q;if(typeof Q==="string")return new L0({content:[{type:"text",text:Q}]});throw Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof Q}`)}async function bK(Q,Z,$={}){let J=l3(Q,Z,$);if(J)return J;if(KZ(Q)){let Y=l3(await Q._getModelInstance(),Z,$);if(Y)return Y}if(s0.isRunnableSequence(Q)){let Y=Q.steps.findIndex((W)=>b0.isRunnableBinding(W)||N$(W)||KZ(W));if(Y>=0){let W=l3(Q.steps[Y],Z,$);if(W){let X=Q.steps.slice();return X.splice(Y,1,W),s0.from(X)}}}throw Error(`llm ${Q} must define bindTools method.`)}function YF(Q){if(Q.length===0)return;if(Q.length===1)return Q[0];function Z(J,Y){return async(W,X)=>{return J(W,async(G)=>{return Y(G,X)})}}let $=Q[Q.length-1];for(let J=Q.length-2;J>=0;J--)$=Z(Q[J],$);return $}function kK(Q){let Z=Q.filter(($)=>$.wrapToolCall);if(Z.length===0)return;return YF(Z.map(($)=>{let J=$.wrapToolCall;return async(W,X)=>{let q=W.state,G=async(z)=>{let K={...q,...z.state};return X({...z,state:K})};try{let z=await J({...W,state:{messages:q.messages,...$.stateSchema?JF($.stateSchema,{...q}):{}}},G);if(!i.isInstance(z)&&!z0(z))throw Error(`Invalid response from "wrapToolCall" in middleware "${$.name}": expected ToolMessage or Command, got ${typeof z}`);return z}catch(z){throw zZ.wrap(z,$.name)}}}))}async function fK(Q,Z){let $={};for(let J of Q){if(!J.stateSchema)continue;let Y=J.stateSchema;if(E0.isInstance(J.stateSchema)){let q={};for(let[G,z]of Object.entries(J.stateSchema.fields))if(n0.isInstance(z))q[G]=z.inputSchema||z.valueSchema;else q[G]=z;Y=p0.object(q)}let W=await C1(F9(Y,(q)=>q.startsWith("_")),Z);if(W.success){Object.assign($,W.data);continue}let X=W.error.issues.filter((q)=>q.code==="invalid_type").map((q)=>` - ${q.path.join(".")}: Required`).join(`
265
+ `);throw Error(`Middleware "${J.name}" has required state fields that must be initialized:
266
+ ${X}
267
+
268
+ To fix this, either:
269
+ 1. Provide default values in your middleware's state schema using .default():
270
+ stateSchema: z.object({
271
+ myField: z.string().default("default value")
272
+ })
273
+
274
+ 2. Or make the fields optional using .optional():
275
+ stateSchema: z.object({
276
+ myField: z.string().optional()
277
+ })
278
+
279
+ 3. Or ensure you pass these values when invoking the agent:
280
+ agent.invoke({
281
+ messages: [...],
282
+ ${W.error.issues[0]?.path.join(".")}: "value"
283
+ })`)}return $}function hK(Q){let Z={messages:p0.custom(()=>[]),structuredResponse:p0.any().optional()};if(!Q)return p0.object(Z);let $;if(E0.isInstance(Q)){$={};for(let[Y,W]of Object.entries(Q.fields))if(n0.isInstance(W))$[Y]=W.inputSchema||W.valueSchema;else $[Y]=W}else $=Q.shape;let J={...Z};for(let[Y,W]of Object.entries($))if(Y.startsWith("_"))J[Y]=W.optional();else J[Y]=W;return p0.object(J)}function gK(Q){if(_0(Q))return I6(Q);if(E0.isInstance(Q)){let Z={};for(let[$,J]of Object.entries(Q.fields)){let Y;if(n0.isInstance(J))Y=J.inputSchema||J.valueSchema;else Y=J;Z[$]=H0(Y)?Y.optional():p0.any().optional()}return p0.object(Z)}return p0.object({})}function O8(Q){if(!Q)return;if(["model_request","tools",m].includes(Q))return Q;if(Q==="model")return"model_request";if(Q==="tools")return"tools";if(Q==="end")return m;throw Error(`Invalid jump target: ${Q}, must be "model", "tools" or "end".`)}function QY(...Q){return AbortSignal.any(Q.filter((Z)=>Z!==null&&Z!==void 0&&typeof Z==="object"&&("aborted"in Z)&&typeof Z.aborted==="boolean"))}var HZ=class extends c{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#Q;constructor(Q){super();this.name=Q.name??Q.func.name,this.func=Q.func,this.config=Q.tags?{tags:Q.tags}:void 0,this.recurse=Q.recurse??this.recurse}getState(){return this.#Q}setState(Q){this.#Q={...this.#Q,...Q}}async invoke(Q,Z){let $=w0(this.config,Z),J=await q0.runWithConfig($,async()=>this.func(Q,$));if(c.isRunnable(J)&&this.recurse)return await q0.runWithConfig($,async()=>J.invoke(Q,$));return this.#Q=J,J}};function mK(Q,Z){let $,J;if(Z==="inline")$=vK,J=yK;else throw Error(`Invalid agent name mode: ${Z}. Needs to be one of: "inline"`);function Y(W){return W.map($)}return s0.from([i0.from(Y),Q,i0.from(J)])}function WF(Q){return h.isInstance(Q)||z0(Q)||typeof Q==="object"&&Q!==null&&"structuredResponse"in Q&&"messages"in Q}var h0="model_request",dK=class extends HZ{#Q;#J;constructor(Q){super({name:Q.name??"model",func:(Z,$)=>this.#Z(Z,$)});this.#Q=Q,this.#J=Q.systemMessage}#Y(Q){if(!this.#Q.responseFormat)return;let Z=jK(this.#Q.responseFormat,void 0,Q);if(!Z.every(($)=>$ instanceof V6))return{type:"tool",tools:Z.filter(($)=>$ instanceof tQ).reduce(($,J)=>{return $[J.name]=J,$},{})};return{type:"native",strategy:Z[0]}}async#Z(Q,Z){let $=Q.messages.at(-1);if($&&i.isInstance($)&&$.name&&this.#Q.shouldReturnDirect.has($.name))return[new B0({update:{messages:[]}})];let{response:J,lastAiMessage:Y,collectedCommands:W}=await this.#X(Q,Z);if(typeof J==="object"&&J!==null&&"structuredResponse"in J&&"messages"in J){let{structuredResponse:G,messages:z}=J;return{messages:[...Q.messages,...z],structuredResponse:G}}let X=[],q=h.isInstance(J)?J:Y;if(q)if(q.name=this.name,q.lc_kwargs.name=this.name,this.#W(Q,q))X.push(new B0({update:{messages:[new h({content:"Sorry, need more steps to process this request.",name:this.name,id:q.id})]}}));else X.push(new B0({update:{messages:[q]}}));if(z0(J)&&!W.includes(J))X.push(J);return X.push(...W),X}#$(){if(typeof this.#Q.model==="string")return v6(this.#Q.model);if(this.#Q.model)return this.#Q.model;throw Error("No model option was provided, either via `model` option.")}async#X(Q,Z,$={}){let J=await this.#$(),Y=Z,W=this.#J,X=null,q=[],G=async(H)=>{eJ(H.model);let B=this.#Y(H.model),F=await this.#K(H.model,H,B),w=[...W.text===""?[]:[W],...H.messages],A=QY(this.#Q.signal,Z.signal),E=await TQ(F.invoke(w,{...Z,signal:A}),A);if(X=E,B?.type==="native"){let R=B.strategy.parse(E);if(R)return{structuredResponse:R,messages:[E]};return E}if(!B||!E.tool_calls)return E;let P=E.tool_calls.filter((R)=>(R.name in B.tools));if(P.length===0)return E;if(P.length>1)return this.#G(E,P,B);let j=B.tools[P[0].name]?.options?.toolMessageContent;return this.#z(E,P[0],B,j??$.lastMessage)},z=this.#Q.wrapModelCallHookMiddleware??[],K=G;for(let H=z.length-1;H>=0;H--){let[B,F]=z[H];if(B.wrapModelCall){let w=K,A=B,E=F;K=async(P)=>{let j=W,R=A.contextSchema?xQ(A.contextSchema,Y?.context||{}):Y?.context,k=Object.freeze({context:R,store:Y.store,configurable:Y.configurable,writer:Y.writer,interrupt:Y.interrupt,signal:Y.signal}),b={...P,state:{...B.stateSchema?xQ(gK(B.stateSchema),Q):{},...E(),messages:Q.messages},runtime:k},T=async(V)=>{W=j;let v=V.tools??[],I=v.filter((s)=>UZ(s)&&!this.#Q.toolClasses.some((u6)=>u6.name===s.name));if(I.length>0)throw Error(`You have added a new tool in "wrapModelCall" hook of middleware "${A.name}": ${I.map((s)=>s.name).join(", ")}. This is not supported.`);let y=v.filter((s)=>UZ(s)&&this.#Q.toolClasses.every((u6)=>u6!==s));if(y.length>0)throw Error(`You have modified a tool in "wrapModelCall" hook of middleware "${A.name}": ${y.map((s)=>s.name).join(", ")}. This is not supported.`);let l=V,g=V.systemPrompt!==W.text,a=V.systemMessage!==W;if(g&&a)throw Error("Cannot change both systemPrompt and systemMessage in the same request.");if(g)W=new L0({content:[{type:"text",text:V.systemPrompt}]}),l={...V,systemPrompt:W.text,systemMessage:W};if(a)W=new L0({...V.systemMessage}),l={...V,systemPrompt:W.text,systemMessage:W};let aQ=await w(l);if(z0(aQ)&&X){if(!q.includes(aQ))q.push(aQ);return X}return aQ};if(!A.wrapModelCall)return T(b);try{let V=await A.wrapModelCall(b,T);if(!WF(V))throw Error(`Invalid response from "wrapModelCall" in middleware "${A.name}": expected AIMessage or Command, got ${typeof V}`);if(h.isInstance(V))X=V;else if(z0(V))q.push(V);return V}catch(V){throw zZ.wrap(V,A.name)}}}}W=this.#J;let U={model:J,systemPrompt:W?.text,systemMessage:W,messages:Q.messages,tools:this.#Q.toolClasses,state:Q,runtime:Object.freeze({context:Y?.context,store:Y.store,configurable:Y.configurable,writer:Y.writer,interrupt:Y.interrupt,signal:Y.signal})};return{response:await K(U),lastAiMessage:X,collectedCommands:q}}#G(Q,Z,$){let J=new A$(Z.map((Y)=>Y.name));return this.#q(J,Q,Z[0],$)}#z(Q,Z,$,J){let Y=$.tools[Z.name];try{let W=Y.parse(Z.args);return{structuredResponse:W,messages:[Q,new i({tool_call_id:Z.id??"",content:JSON.stringify(W),name:Z.name}),new h(J??`Returning structured response: ${JSON.stringify(W)}`)]}}catch(W){return this.#q(W,Q,Z,$)}}async#q(Q,Z,$,J){let Y=Object.values(J.tools).at(0)?.options?.handleError,W=$.id;if(!W)throw Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(Y===!1)throw Q;if(Y===void 0||typeof Y==="boolean"&&Y||Array.isArray(Y)&&Y.some((X)=>X instanceof A$))return new B0({update:{messages:[Z,new i({content:Q.message,tool_call_id:W})]},goto:h0});if(typeof Y==="string")return new B0({update:{messages:[Z,new i({content:Y,tool_call_id:W})]},goto:h0});if(typeof Y==="function"){let X=await Y(Q);if(typeof X!=="string")throw Error("Error handler must return a string.");return new B0({update:{messages:[Z,new i({content:X,tool_call_id:W})]},goto:h0})}return new B0({update:{messages:[Z,new i({content:Q.message,tool_call_id:W})]},goto:h0})}#W(Q,Z){let $=h.isInstance(Z)&&Z.tool_calls?.every((Y)=>this.#Q.shouldReturnDirect.has(Y.name)),J="remainingSteps"in Q?Q.remainingSteps:void 0;return Boolean(J&&(J<1&&$||J<2&&i3(Q.messages.at(-1))))}async#K(Q,Z,$){let J={},Y=Object.values($&&"tools"in $?$.tools:{}),W=[...Z?.tools??this.#Q.toolClasses,...Y.map((G)=>G.tool)],X=Z?.toolChoice||(Y.length>0?"any":void 0);if($?.type==="native"){let G=Z?.modelSettings?.strict??$?.strategy?.strict??!0,z={name:$.strategy.schema?.name??"extract",description:W8($.strategy.schema),schema:$.strategy.schema,strict:G};Object.assign(J,{response_format:{type:"json_schema",json_schema:z},outputConfig:{format:{type:"json_schema",schema:$.strategy.schema}},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:$.strategy.schema},strict:G})}let q=await bK(Q,W,{...J,...Z?.modelSettings,tool_choice:X});return this.#Q.includeAgentName==="inline"?mK(q,this.#Q.includeAgentName):q}getState(){let Q=super.getState();return{messages:[],...Q&&!z0(Q)?Q:{}}}};var uK=(Q,Z)=>`Error: ${Q} is not a valid tool, try one of [${Z.join(", ")}].`,I0="tools",pK=(Q)=>Array.isArray(Q)&&Q.every(V0.isInstance),XF=(Q)=>typeof Q==="object"&&Q!=null&&("messages"in Q)&&pK(Q.messages),qF=(Q)=>typeof Q==="object"&&Q!=null&&("lg_tool_call"in Q);function GF(Q,Z){if(Q instanceof P$)return new i({content:Q.message,tool_call_id:Z.id,name:Z.name});return new i({content:`${Q}
284
+ Please fix your mistakes.`,tool_call_id:Z.id,name:Z.name})}var cK=class extends HZ{tools;trace=!1;signal;handleToolErrors=GF;wrapToolCall;constructor(Q,Z){let{name:$,tags:J,handleToolErrors:Y,signal:W,wrapToolCall:X}=Z??{};super({name:$,tags:J,func:(q,G)=>this.run(q,G)});this.options=Z,this.tools=Q,this.handleToolErrors=Y??this.handleToolErrors,this.signal=W,this.wrapToolCall=X}#Q(Q,Z,$){if(sQ(Q))throw Q;if(this.signal?.aborted)throw Q;if($&&this.handleToolErrors!==!0)throw Q;if(!this.handleToolErrors)throw Q;if(typeof this.handleToolErrors==="function"){let J=this.handleToolErrors(Q,Z);if(J&&i.isInstance(J))return J;throw Q}else if(this.handleToolErrors)return new i({name:Z.name,content:`${Q}
285
+ Please fix your mistakes.`,tool_call_id:Z.id});throw Q}async runTool(Q,Z,$){let J=Z,Y={context:J?.context,writer:J?.writer,interrupt:J?.interrupt,signal:J?.signal},W=this.tools.find((G)=>G.name===Q.name),X=async(G)=>{let{toolCall:z,tool:K}=G,U=K??this.tools.find((B)=>B.name===z.name);if(U===void 0){let B=this.tools.map((F)=>F.name);return new i({content:uK(z.name,B),tool_call_id:z.id,name:z.name,status:"error"})}let H=U;try{let B=await H.invoke({...z,type:"tool_call"},{...Z,config:Z,toolCallId:z.id,state:Z.configurable?.__pregel_scratchpad?.currentTaskInput,signal:QY(this.signal,Z.signal)});if(i.isInstance(B)||z0(B))return B;return new i({name:H.name,content:typeof B==="string"?B:JSON.stringify(B),tool_call_id:z.id})}catch(B){if(B instanceof w6)throw new P$(B,z);throw B}},q={toolCall:Q,tool:W,state:$,runtime:Y};if(this.wrapToolCall)try{return await this.wrapToolCall(q,X)}catch(G){return this.#Q(G,Q,!0)}if(!W){let G=this.tools.map((z)=>z.name);return new i({content:uK(Q.name,G),tool_call_id:Q.id,name:Q.name,status:"error"})}try{return await X(q)}catch(G){return this.#Q(G,Q,!1)}}async run(Q,Z){let $;if(qF(Q)){let{lg_tool_call:W,jumpTo:X,...q}=Q;$=[await this.runTool(Q.lg_tool_call,Z,q)]}else{let W;if(pK(Q))W=Q;else if(XF(Q))W=Q.messages;else throw Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let X=new Set(W.filter((G)=>G.getType()==="tool").map((G)=>G.tool_call_id)),q;for(let G=W.length-1;G>=0;G-=1){let z=W[G];if(h.isInstance(z)){q=z;break}}if(!h.isInstance(q))throw Error("ToolNode only accepts AIMessages as input.");$=await Promise.all(q.tool_calls?.filter((G)=>G.id==null||!X.has(G.id)).map((G)=>this.runTool(G,Z,Q))??[])}if(!$.some(z0))return Array.isArray(Q)?$:{messages:$};let J=[],Y=null;for(let W of $)if(z0(W))if(W.graph===B0.PARENT&&Array.isArray(W.goto)&&W.goto.every((X)=>zF(X)))if(Y)Y.goto.push(...W.goto);else Y=new B0({graph:B0.PARENT,goto:W.goto});else J.push(W);else J.push(Array.isArray(Q)?[W]:{messages:[W]});if(Y)J.push(Y);return J}};function zF(Q){return Q instanceof u0}var KF=class{},UF=class{},d6=class extends HZ{#Q;constructor(Q,Z){super(Q);this.#Q=Z}async invokeMiddleware(Q,Z){let $={};if(this.middleware.contextSchema){let G=this.middleware.contextSchema?.shape;if(G){let z={},K=Z?.context||{};for(let U of Object.keys(G))if(U in K)z[U]=K[U];$=xQ(this.middleware.contextSchema,z)}}let J={...this.#Q.getState(),...Q,messages:Q.messages},Y={context:$,store:Z?.store,configurable:Z?.configurable,writer:Z?.writer,interrupt:Z?.interrupt,signal:Z?.signal},W=await this.runHook(J,Object.freeze(Object.assign(new UF,{...Y,context:Object.freeze(Object.assign(new KF,$))})));if(!W)return{jumpTo:void 0};let X,q;if(this.name?.startsWith("BeforeAgentNode_"))X=o8(this.middleware.beforeAgent),q="beforeAgent.canJumpTo";else if(this.name?.startsWith("BeforeModelNode_"))X=o8(this.middleware.beforeModel),q="beforeModel.canJumpTo";else if(this.name?.startsWith("AfterAgentNode_"))X=o8(this.middleware.afterAgent),q="afterAgent.canJumpTo";else if(this.name?.startsWith("AfterModelNode_"))X=o8(this.middleware.afterModel),q="afterModel.canJumpTo";if(typeof W.jumpTo==="string"&&!X?.includes(W.jumpTo)){let G=X&&X.length>0?`must be one of: ${X?.join(", ")}.`:q?`no ${q} defined in middleware ${this.middleware.name}`:"";throw Error(`Invalid jump target: ${W.jumpTo}, ${G}.`)}if(typeof W==="object"&&"type"in W){if(W.type==="terminate"){if(W.error)throw W.error;return{...J,...W.result||{},jumpTo:W.jumpTo}}throw Error(`Invalid control action: ${JSON.stringify(W)}`)}return{...J,...W,jumpTo:W.jumpTo}}get nodeOptions(){return{input:hK(this.middleware.stateSchema)}}};var lK=class extends d6{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(Q,Z){super({name:`BeforeAgentNode_${Q.name}`,func:async($,J)=>this.invokeMiddleware($,J)},Z);this.middleware=Q}runHook(Q,Z){return m6(this.middleware.beforeAgent)(Q,Z)}};var iK=class extends d6{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(Q,Z){super({name:`BeforeModelNode_${Q.name}`,func:async($,J)=>this.invokeMiddleware($,J)},Z);this.middleware=Q}runHook(Q,Z){return m6(this.middleware.beforeModel)(Q,Z)}};var oK=class extends d6{lc_namespace=["langchain","agents","afterModelNodes"];constructor(Q,Z){super({name:`AfterModelNode_${Q.name}`,func:async($,J)=>this.invokeMiddleware($,J)},Z);this.middleware=Q}runHook(Q,Z){return m6(this.middleware.afterModel)(Q,Z)}};var nK=class extends d6{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(Q,Z){super({name:`AfterAgentNode_${Q.name}`,func:async($,J)=>this.invokeMiddleware($,J)},Z);this.middleware=Q}runHook(Q,Z){return m6(this.middleware.afterAgent)(Q,Z)}};var rK=class{#Q=new Map;addNode(Q,Z){this.#Q.set(Q.name,[...this.#Q.get(Q.name)??[],Z])}getState(Q){let Z=(this.#Q.get(Q)??[]).reduce(($,J)=>{return{...$,...J.getState()??{}}},{});return delete Z.jumpTo,Z}};var HF=class Q{#Q;#J="v2";#Y;#Z=new rK;#$;constructor(Z,$){if(this.options=Z,this.#$=$??{},Z.name)this.#$=w0(this.#$,{metadata:{lc_agent_name:Z.name}});if(this.#J=Z.version??this.#J,!Z.model)throw Error("`model` option is required to create an agent.");if(typeof Z.model!=="string")eJ(Z.model);let J=this.options.middleware?.filter((V)=>V.tools).flatMap((V)=>V.tools)??[],Y=[...Z.tools??[],...J],W=new Set(Y.filter(UZ).filter((V)=>("returnDirect"in V)&&V.returnDirect).map((V)=>V.name)),{state:X,input:q,output:G}=xK(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),z=new GZ(X,{input:q,output:G,context:this.options.contextSchema}),K=[],U=[],H=[],B=[],F=[];this.#Y=new dK({model:this.options.model,systemMessage:CK(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:Y,shouldReturnDirect:W,signal:this.options.signal,wrapModelCallHookMiddleware:F});let w=new Set,A=this.options.middleware??[];for(let V=0;V<A.length;V++){let v,I,y,l,g=A[V];if(w.has(g.name))throw Error(`Middleware ${g.name} is defined multiple times`);if(w.add(g.name),g.beforeAgent){v=new lK(g,{getState:()=>this.#Z.getState(g.name)}),this.#Z.addNode(g,v);let a=`${g.name}.before_agent`;K.push({index:V,name:a,allowed:o8(g.beforeAgent)}),z.addNode(a,v,v.nodeOptions)}if(g.beforeModel){I=new iK(g,{getState:()=>this.#Z.getState(g.name)}),this.#Z.addNode(g,I);let a=`${g.name}.before_model`;U.push({index:V,name:a,allowed:o8(g.beforeModel)}),z.addNode(a,I,I.nodeOptions)}if(g.afterModel){y=new oK(g,{getState:()=>this.#Z.getState(g.name)}),this.#Z.addNode(g,y);let a=`${g.name}.after_model`;H.push({index:V,name:a,allowed:o8(g.afterModel)}),z.addNode(a,y,y.nodeOptions)}if(g.afterAgent){l=new nK(g,{getState:()=>this.#Z.getState(g.name)}),this.#Z.addNode(g,l);let a=`${g.name}.after_agent`;B.push({index:V,name:a,allowed:o8(g.afterAgent)}),z.addNode(a,l,l.nodeOptions)}if(g.wrapModelCall)F.push([g,()=>this.#Z.getState(g.name)])}z.addNode(h0,this.#Y);let E=A.some((V)=>V.wrapToolCall),P=Y.filter(UZ);if(P.length>0||E){let V=new cK(P,{signal:this.options.signal,wrapToolCall:kK(A)});z.addNode(I0,V)}let j;if(K.length>0)j=K[0].name;else if(U.length>0)j=U[0].name;else j=h0;let R=U.length>0?U[0].name:h0,k=B.length>0?B[B.length-1].name:m;z.addEdge(Q0,j);let b=P.length>0||E;for(let V=0;V<K.length;V++){let v=K[V],I=v.name,y=V===K.length-1?R:K[V+1].name;if(v.allowed&&v.allowed.length>0){let l=v.allowed.map((a)=>O8(a)).filter((a)=>a!==I0||b),g=Array.from(new Set([y,...l.map((a)=>a===m?k:a)]));z.addConditionalEdges(I,this.#K(P,y,k,b),g)}else z.addEdge(I,y)}for(let V=0;V<U.length;V++){let v=U[V],I=v.name,y=V===U.length-1?h0:U[V+1].name;if(v.allowed&&v.allowed.length>0){let l=v.allowed.map((a)=>O8(a)).filter((a)=>a!==I0||b),g=Array.from(new Set([y,...l]));z.addConditionalEdges(I,this.#H(P,y,b),g)}else z.addEdge(I,y)}let T=H.at(-1);if(H.length>0&&T)z.addEdge(h0,T.name);else{let V=this.#X(P,!1,b).map((v)=>v===m?k:v);if(V.length===1)z.addEdge(h0,V[0]);else z.addConditionalEdges(h0,this.#z(k),V)}for(let V=H.length-1;V>0;V--){let v=H[V],I=v.name,y=H[V-1].name;if(v.allowed&&v.allowed.length>0){let l=v.allowed.map((a)=>O8(a)).filter((a)=>a!==I0||b),g=Array.from(new Set([y,...l]));z.addConditionalEdges(I,this.#W(P,v.allowed,y,b),g)}else z.addEdge(I,y)}if(H.length>0){let V=H[0],v=V.name,I=this.#X(P,!0,b).filter((g)=>g!==I0||b),y=Boolean(V.allowed&&V.allowed.length>0),l=I.map((g)=>g===m?k:g);z.addConditionalEdges(v,this.#q(P,y,k,b),l)}for(let V=B.length-1;V>0;V--){let v=B[V],I=v.name,y=B[V-1].name;if(v.allowed&&v.allowed.length>0){let l=v.allowed.map((a)=>O8(a)).filter((a)=>a!==I0||b),g=Array.from(new Set([y,...l]));z.addConditionalEdges(I,this.#W(P,v.allowed,y,b),g)}else z.addEdge(I,y)}if(B.length>0){let V=B[0],v=V.name;if(V.allowed&&V.allowed.length>0){let I=V.allowed.map((l)=>O8(l)).filter((l)=>l!==I0||b),y=Array.from(new Set([m,...I]));z.addConditionalEdges(v,this.#W(P,V.allowed,m,b),y)}else z.addEdge(v,m)}if(b){let V=R;if(W.size>0)z.addConditionalEdges(I0,this.#G(W,k),[V,k]);else z.addEdge(I0,V)}this.#Q=z.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#Q}get checkpointer(){return this.#Q.checkpointer}set checkpointer(Z){this.#Q.checkpointer=Z}get store(){return this.#Q.store}set store(Z){this.#Q.store=Z}withConfig(Z){return new Q(this.options,w0(this.#$,Z))}#X(Z,$=!1,J=Z.length>0){let Y=[];if(J)Y.push(I0);if($)Y.push(h0);return Y.push(m),Y}#G(Z,$){return(J)=>{let Y=J.messages,W=Y[Y.length-1];if(i.isInstance(W)&&W.name&&Z.has(W.name))return this.options.responseFormat?h0:$;return h0}}#z(Z=m){return($)=>{let J=$.messages.at(-1);if(!h.isInstance(J)||!J.tool_calls||J.tool_calls.length===0)return Z;if(J.tool_calls.every((W)=>W.name.startsWith("extract-")))return Z;if(this.#J==="v1")return I0;let Y=J.tool_calls.filter((W)=>!W.name.startsWith("extract-"));if(Y.length===0)return Z;return Y.map((W)=>new u0(I0,{...$,lg_tool_call:W}))}}#q(Z,$,J,Y=Z.length>0){let W=Boolean(this.options.responseFormat);return(X)=>{let q=X,G=q.messages,z=G.at(-1);if(h.isInstance(z)&&(!z.tool_calls||z.tool_calls.length===0))return J;if($&&q.jumpTo){let A=O8(q.jumpTo);if(A===m)return J;if(A===I0){if(!Y)return J;return new u0(I0,{...X,jumpTo:void 0})}return new u0(h0,{...X,jumpTo:void 0})}let K=G.filter(i.isInstance),U=G.filter(h.isInstance).at(-1),H=U?.tool_calls?.filter((A)=>!K.some((E)=>E.tool_call_id===A.id));if(H&&H.length>0)return H.map((A)=>new u0(I0,{...X,lg_tool_call:A}));let B=U?.tool_calls?.some((A)=>A.name.startsWith("extract-"));if(H&&H.length===0&&!B&&W)return h0;if(!h.isInstance(z)||!z.tool_calls||z.tool_calls.length===0)return J;let F=z.tool_calls.every((A)=>A.name.startsWith("extract-")),w=z.tool_calls.some((A)=>!A.name.startsWith("extract-"));if(F||!w)return J;return I0}}#W(Z,$,J,Y=Z.length>0){let W=new Set($.map((X)=>O8(X)));return(X)=>{let q=X;if(q.jumpTo){let G=O8(q.jumpTo);if(G===m&&W.has(m))return m;if(G===I0&&W.has(I0)){if(!Y)return m;return new u0(I0,{...X,jumpTo:void 0})}if(G===h0&&W.has(h0))return new u0(h0,{...X,jumpTo:void 0})}return J}}#K(Z,$,J,Y=Z.length>0){return(W)=>{let X=W;if(!X.jumpTo)return $;let q=O8(X.jumpTo);if(q===m)return J;if(q===I0){if(!Y)return J;return new u0(I0,{...W,jumpTo:void 0})}return new u0(h0,{...W,jumpTo:void 0})}}#H(Z,$,J=Z.length>0){return(Y)=>{let W=Y;if(!W.jumpTo)return $;let X=O8(W.jumpTo);if(X===m)return m;if(X===I0){if(!J)return m;return new u0(I0,{...Y,jumpTo:void 0})}return new u0(h0,{...Y,jumpTo:void 0})}}async#U(Z,$){if(!this.options.middleware||this.options.middleware.length===0||Z instanceof B0||!Z)return Z;let J=await fK(this.options.middleware,Z),Y={...(await this.#Q.getState($).catch(()=>({values:{}}))).values,...Z};if(!Y)return Y;for(let[W,X]of Object.entries(J))if(!(W in Y))Y[W]=X;return Y}async invoke(Z,$){let J=w0(this.#$,$),Y=await this.#U(Z,J);return this.#Q.invoke(Y,J)}async stream(Z,$){let J=w0(this.#$,$),Y=await this.#U(Z,J);return this.#Q.stream(Y,J)}async drawMermaidPng(Z){let $=await(await(await this.#Q.getGraphAsync()).drawMermaidPng(Z)).arrayBuffer();return new Uint8Array($)}async drawMermaid(Z){return(await this.#Q.getGraphAsync()).drawMermaid(Z)}streamEvents(Z,$,J){let Y=w0(this.#$,$);return this.#Q.streamEvents(Z,{...Y,version:$?.version??"v2"},J)}getGraphAsync(Z){return this.#Q.getGraphAsync(Z)}getState(Z,$){return this.#Q.getState(Z,$)}getStateHistory(Z,$){return this.#Q.getStateHistory(Z,$)}getSubgraphs(Z,$){return this.#Q.getSubgraphs(Z,$)}getSubgraphAsync(Z,$){return this.#Q.getSubgraphsAsync(Z,$)}updateState(Z,$,J){return this.#Q.updateState(Z,$,J)}get builder(){return this.#Q.builder}};var FF=O.function().args(O.custom(),O.custom(),O.custom()).returns(O.union([O.string(),O.promise(O.string())])),LF=["approve","edit","reject"],wF=O.enum(LF),AF=O.object({allowedDecisions:O.array(wF),description:O.union([O.string(),FF]).optional(),argsSchema:O.record(O.any()).optional()}),wn=O.object({interruptOn:O.record(O.union([O.boolean(),AF])).optional(),descriptionPrefix:O.string().default("Tool execution requires approval")});var PF=`<role>
286
+ Context Extraction Assistant
287
+ </role>
288
+
289
+ <primary_objective>
290
+ Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
291
+ </primary_objective>
292
+
293
+ <objective_information>
294
+ 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.
295
+ 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.
296
+ </objective_information>
297
+
298
+ <instructions>
299
+ 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.
300
+ 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.
301
+ </instructions>
302
+
303
+ 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:
304
+
305
+ 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.
306
+ Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
307
+
308
+ <messages>
309
+ Messages to summarize:
310
+ {messages}
311
+ </messages>`;var NF=O.function().args(O.array(O.custom())).returns(O.union([O.number(),O.promise(O.number())])),O$=O.object({fraction:O.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:O.number().positive("Tokens must be greater than 0").optional(),messages:O.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine((Q)=>{return[Q.fraction,Q.tokens,Q.messages].filter((Z)=>Z!==void 0).length>=1},{message:"At least one of fraction, tokens, or messages must be provided"}),n3=O.object({fraction:O.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:O.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:O.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine((Q)=>{return[Q.fraction,Q.tokens,Q.messages].filter((Z)=>Z!==void 0).length===1},{message:"Exactly one of fraction, tokens, or messages must be provided"}),xn=O.object({model:O.custom(),trigger:O.union([O$,O.array(O$)]).optional(),keep:n3.optional(),tokenCounter:NF.optional(),summaryPrompt:O.string().default(PF),trimTokensToSummarize:O.number().optional(),summaryPrefix:O.string().optional(),maxTokensBeforeSummary:O.number().optional(),messagesToKeep:O.number().optional()});function r3(Q){if("profile"in Q&&typeof Q.profile==="object"&&Q.profile&&"maxInputTokens"in Q.profile&&(typeof Q.profile.maxInputTokens==="number"||Q.profile.maxInputTokens==null))return Q.profile.maxInputTokens??void 0;if("model"in Q&&typeof Q.model==="string")return hZ(Q.model);if("modelName"in Q&&typeof Q.modelName==="string")return hZ(Q.modelName)}var mn=O.object({model:O.string().or(O.instanceof(K1)).optional(),systemPrompt:O.string().optional(),maxTools:O.number().optional(),alwaysInclude:O.array(O.string()).optional()});var on=O.object({applyToInput:O.boolean().optional(),applyToOutput:O.boolean().optional(),applyToToolResults:O.boolean().optional()});var an=O.object({rules:O.record(O.string(),O.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var OF="[cleared]",EF=1e5,ZY=3,sK=class{#Q;trigger;keep;clearToolInputs;excludeTools;placeholder;model;clearAtLeast;constructor(Q={}){let Z=Q.trigger;if(Q.triggerTokens!==void 0){if(console.warn("triggerTokens is deprecated. Use `trigger: { tokens: value }` instead."),Z===void 0)Z={tokens:Q.triggerTokens}}let $=Q.keep;if(Q.keepMessages!==void 0){if(console.warn("keepMessages is deprecated. Use `keep: { messages: value }` instead."),$===void 0)$={messages:Q.keepMessages}}if(Z===void 0)Z={tokens:EF};if($===void 0)$={messages:ZY};if(Array.isArray(Z))this.#Q=Z.map((J)=>O$.parse(J)),this.trigger=this.#Q;else{let J=O$.parse(Z);this.#Q=[J],this.trigger=J}if(this.keep=n3.parse($),Q.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=Q.clearAtLeast??0,this.clearToolInputs=Q.clearToolInputs??!1,this.excludeTools=new Set(Q.excludeTools??[]),this.placeholder=Q.placeholder??OF}async apply(Q){let{messages:Z,model:$,countTokens:J}=Q,Y=await J(Z),W=[];for(let H=0;H<Z.length;H++){let B=Z[H];if(i.isInstance(B)){let F=this.#Z(Z.slice(0,H),B.tool_call_id);if(!F)W.push(H);else if(!F.tool_calls?.find((w)=>w.id===B.tool_call_id))W.push(H)}}for(let H=W.length-1;H>=0;H--)Z.splice(W[H],1);let X=Y;if(W.length>0)X=await J(Z);if(!this.#J(Z,X,$))return;let q=[];for(let H=0;H<Z.length;H++){let B=Z[H];if(i.isInstance(B))q.push({idx:H,msg:B})}if(q.length===0)return;let G=await this.#Y(q,J,$),z=G>=q.length?[]:G>0?q.slice(0,-G):q,K=0,U=[...z];for(let{idx:H,msg:B}of U){if(B.response_metadata?.context_editing?.cleared)continue;let F=this.#Z(Z.slice(0,H),B.tool_call_id);if(!F)continue;let w=F.tool_calls?.find((P)=>P.id===B.tool_call_id);if(!w)continue;let A=B.name||w.name;if(this.excludeTools.has(A))continue;if(Z[H]=new i({tool_call_id:B.tool_call_id,content:this.placeholder,name:B.name,artifact:void 0,response_metadata:{...B.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){let P=Z.indexOf(F);if(P>=0)Z[P]=this.#$(F,B.tool_call_id)}let E=await J(Z);K=Math.max(0,X-E)}if(this.clearAtLeast>0&&K<this.clearAtLeast){let H=G>0&&G<q.length?q.slice(-G):[];for(let B=H.length-1;B>=0;B--){if(K>=this.clearAtLeast)break;let{idx:F,msg:w}=H[B];if(w.response_metadata?.context_editing?.cleared)continue;let A=this.#Z(Z.slice(0,F),w.tool_call_id);if(!A)continue;let E=A.tool_calls?.find((R)=>R.id===w.tool_call_id);if(!E)continue;let P=w.name||E.name;if(this.excludeTools.has(P))continue;if(Z[F]=new i({tool_call_id:w.tool_call_id,content:this.placeholder,name:w.name,artifact:void 0,response_metadata:{...w.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){let R=Z.indexOf(A);if(R>=0)Z[R]=this.#$(A,w.tool_call_id)}let j=await J(Z);K=Math.max(0,X-j)}}}#J(Q,Z,$){for(let J of this.#Q){let Y=!0,W=!1;if(J.messages!==void 0){if(W=!0,Q.length<J.messages)Y=!1}if(J.tokens!==void 0){if(W=!0,Z<J.tokens)Y=!1}if(J.fraction!==void 0){if(W=!0,!$)continue;let X=r3($);if(typeof X==="number"){let q=Math.floor(X*J.fraction);if(q<=0)continue;if(Z<q)Y=!1}else continue}if(W&&Y)return!0}return!1}async#Y(Q,Z,$){if("messages"in this.keep&&this.keep.messages!==void 0)return this.keep.messages;if("tokens"in this.keep&&this.keep.tokens!==void 0){let J=this.keep.tokens,Y=0,W=0;for(let X=Q.length-1;X>=0;X--){let q=Q[X],G=await Z([q.msg]);if(Y+G<=J)Y+=G,W++;else break}return W}if("fraction"in this.keep&&this.keep.fraction!==void 0){if(!$)return ZY;let J=r3($);if(typeof J==="number"){let Y=Math.floor(J*this.keep.fraction);if(Y<=0)return ZY;let W=0,X=0;for(let q=Q.length-1;q>=0;q--){let G=Q[q],z=await Z([G.msg]);if(W+z<=Y)W+=z,X++;else break}return X}}return ZY}#Z(Q,Z){for(let $=Q.length-1;$>=0;$--){let J=Q[$];if(h.isInstance(J)){if(J.tool_calls?.some((Y)=>Y.id===Z))return J}}return null}#$(Q,Z){let $=Q.tool_calls?.map((X)=>{if(X.id===Z)return{...X,args:{}};return X}),J={...Q.response_metadata},Y={...J.context_editing},W=new Set(Y.cleared_tool_inputs);return W.add(Z),Y.cleared_tool_inputs=Array.from(W).sort(),J.context_editing=Y,new h({content:Q.content,tool_calls:$,response_metadata:J,id:Q.id,name:Q.name,additional_kwargs:Q.additional_kwargs})}};var jF=["continue","error","end"],RF="continue";var _F=O.enum(jF).default(RF);var zr=O.object({toolName:O.string().optional(),threadLimit:O.number().optional(),runLimit:O.number().optional(),exitBehavior:_F}),Kr=O.object({threadToolCallCount:O.record(O.string(),O.number()).default({}),runToolCallCount:O.record(O.string(),O.number()).default({})});var IF=O.enum(["pending","in_progress","completed"]).describe("Status of the todo"),TF=O.object({content:O.string().describe("Content of the todo item"),status:IF}),wr=O.object({todos:O.array(TF).default([])});var Er=O.object({threadLimit:O.number().optional(),runLimit:O.number().optional(),exitBehavior:O.enum(["error","end"]).optional()}),jr=O.object({threadModelCallCount:O.number().default(0),runModelCallCount:O.number().default(0)});var $Y=O.object({maxRetries:O.number().min(0).default(2),retryOn:O.union([O.function().args(O.instanceof(Error)).returns(O.boolean()),O.array(O.custom())]).default(()=>()=>!0),backoffFactor:O.number().min(0).default(2),initialDelayMs:O.number().min(0).default(1000),maxDelayMs:O.number().min(0).default(60000),jitter:O.boolean().default(!0)});var hr=O.object({onFailure:O.union([O.literal("error"),O.literal("continue"),O.function().args(O.instanceof(Error)).returns(O.string())]).default("continue")}).merge($Y);var ir=O.object({tools:O.array(O.union([O.custom(),O.custom(),O.string()])).optional(),onFailure:O.union([O.literal("error"),O.literal("continue"),O.literal("raise"),O.literal("return_message"),O.function().args(O.instanceof(Error)).returns(O.string())]).default("continue")}).merge($Y);var Ys=O.object({enableCaching:O.boolean().optional(),ttl:O.enum(["5m","1h"]).optional(),minMessagesToCache:O.number().optional(),unsupportedModelBehavior:O.enum(["ignore","warn","raise"]).optional()});async function YL(){return new Promise((Q,Z)=>{let $="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(J)=>{$+=J}),process.stdin.on("end",()=>{Q($)}),process.stdin.on("error",(J)=>{Z(J)})})}async function vt(Q,Z=!1){let $=await tK();await $.initialize();let J=await $.getConfig(),Y=Q||"";if(Z)try{Y=(await YL()).trim()}catch(W){throw console.error("❌ 读取 stdin 失败:",W),W}if(!Y)console.error("❌ 错误: 未提供输入内容"),console.error(`
312
+ 用法:`),console.error(' zen-code -p "你的任务描述"'),console.error(' echo "内容" | zen-code'),process.exit(1);try{let W={messages:[new G0(Y)],provider_id:J.provider_id,provider_type:J.provider_type||J.provider_id,model_id:J.model_id,enable_thinking:J.enable_thinking,streaming:J.streaming??!1,cwd:process.cwd()},X=await s3.invoke(W,{recursionLimit:500}),q=X.messages||[],G=q[q.length-1];if(G)console.log(G.text);return X}catch(W){throw console.error(`
313
+ ❌ 执行失败: ${W instanceof Error?W.message:String(W)}
314
+ `),W}}export{vt as runNonInteractive};